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 }; 135 return Rank[(int)Kind]; 136 } 137 138 /// GetImplicitConversionName - Return the name of this kind of 139 /// implicit conversion. 140 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 141 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 142 "No conversion", 143 "Lvalue-to-rvalue", 144 "Array-to-pointer", 145 "Function-to-pointer", 146 "Noreturn adjustment", 147 "Qualification", 148 "Integral promotion", 149 "Floating point promotion", 150 "Complex promotion", 151 "Integral conversion", 152 "Floating conversion", 153 "Complex conversion", 154 "Floating-integral conversion", 155 "Pointer conversion", 156 "Pointer-to-member conversion", 157 "Boolean conversion", 158 "Compatible-types conversion", 159 "Derived-to-base conversion", 160 "Vector conversion", 161 "Vector splat", 162 "Complex-real conversion", 163 "Block Pointer conversion", 164 "Transparent Union Conversion", 165 "Writeback conversion" 166 }; 167 return Name[Kind]; 168 } 169 170 /// StandardConversionSequence - Set the standard conversion 171 /// sequence to the identity conversion. 172 void StandardConversionSequence::setAsIdentityConversion() { 173 First = ICK_Identity; 174 Second = ICK_Identity; 175 Third = ICK_Identity; 176 DeprecatedStringLiteralToCharPtr = false; 177 QualificationIncludesObjCLifetime = false; 178 ReferenceBinding = false; 179 DirectBinding = false; 180 IsLvalueReference = true; 181 BindsToFunctionLvalue = false; 182 BindsToRvalue = false; 183 BindsImplicitObjectArgumentWithoutRefQualifier = false; 184 ObjCLifetimeConversionBinding = false; 185 CopyConstructor = nullptr; 186 } 187 188 /// getRank - Retrieve the rank of this standard conversion sequence 189 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 190 /// implicit conversions. 191 ImplicitConversionRank StandardConversionSequence::getRank() const { 192 ImplicitConversionRank Rank = ICR_Exact_Match; 193 if (GetConversionRank(First) > Rank) 194 Rank = GetConversionRank(First); 195 if (GetConversionRank(Second) > Rank) 196 Rank = GetConversionRank(Second); 197 if (GetConversionRank(Third) > Rank) 198 Rank = GetConversionRank(Third); 199 return Rank; 200 } 201 202 /// isPointerConversionToBool - Determines whether this conversion is 203 /// a conversion of a pointer or pointer-to-member to bool. This is 204 /// used as part of the ranking of standard conversion sequences 205 /// (C++ 13.3.3.2p4). 206 bool StandardConversionSequence::isPointerConversionToBool() const { 207 // Note that FromType has not necessarily been transformed by the 208 // array-to-pointer or function-to-pointer implicit conversions, so 209 // check for their presence as well as checking whether FromType is 210 // a pointer. 211 if (getToType(1)->isBooleanType() && 212 (getFromType()->isPointerType() || 213 getFromType()->isObjCObjectPointerType() || 214 getFromType()->isBlockPointerType() || 215 getFromType()->isNullPtrType() || 216 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 217 return true; 218 219 return false; 220 } 221 222 /// isPointerConversionToVoidPointer - Determines whether this 223 /// conversion is a conversion of a pointer to a void pointer. This is 224 /// used as part of the ranking of standard conversion sequences (C++ 225 /// 13.3.3.2p4). 226 bool 227 StandardConversionSequence:: 228 isPointerConversionToVoidPointer(ASTContext& Context) const { 229 QualType FromType = getFromType(); 230 QualType ToType = getToType(1); 231 232 // Note that FromType has not necessarily been transformed by the 233 // array-to-pointer implicit conversion, so check for its presence 234 // and redo the conversion to get a pointer. 235 if (First == ICK_Array_To_Pointer) 236 FromType = Context.getArrayDecayedType(FromType); 237 238 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 239 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 240 return ToPtrType->getPointeeType()->isVoidType(); 241 242 return false; 243 } 244 245 /// Skip any implicit casts which could be either part of a narrowing conversion 246 /// or after one in an implicit conversion. 247 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 248 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 249 switch (ICE->getCastKind()) { 250 case CK_NoOp: 251 case CK_IntegralCast: 252 case CK_IntegralToBoolean: 253 case CK_IntegralToFloating: 254 case CK_FloatingToIntegral: 255 case CK_FloatingToBoolean: 256 case CK_FloatingCast: 257 Converted = ICE->getSubExpr(); 258 continue; 259 260 default: 261 return Converted; 262 } 263 } 264 265 return Converted; 266 } 267 268 /// Check if this standard conversion sequence represents a narrowing 269 /// conversion, according to C++11 [dcl.init.list]p7. 270 /// 271 /// \param Ctx The AST context. 272 /// \param Converted The result of applying this standard conversion sequence. 273 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 274 /// value of the expression prior to the narrowing conversion. 275 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 276 /// type of the expression prior to the narrowing conversion. 277 NarrowingKind 278 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 279 const Expr *Converted, 280 APValue &ConstantValue, 281 QualType &ConstantType) const { 282 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 283 284 // C++11 [dcl.init.list]p7: 285 // A narrowing conversion is an implicit conversion ... 286 QualType FromType = getToType(0); 287 QualType ToType = getToType(1); 288 switch (Second) { 289 // -- from a floating-point type to an integer type, or 290 // 291 // -- from an integer type or unscoped enumeration type to a floating-point 292 // type, except where the source is a constant expression and the actual 293 // value after conversion will fit into the target type and will produce 294 // the original value when converted back to the original type, or 295 case ICK_Floating_Integral: 296 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 297 return NK_Type_Narrowing; 298 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 299 llvm::APSInt IntConstantValue; 300 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 301 if (Initializer && 302 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 303 // Convert the integer to the floating type. 304 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 305 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 306 llvm::APFloat::rmNearestTiesToEven); 307 // And back. 308 llvm::APSInt ConvertedValue = IntConstantValue; 309 bool ignored; 310 Result.convertToInteger(ConvertedValue, 311 llvm::APFloat::rmTowardZero, &ignored); 312 // If the resulting value is different, this was a narrowing conversion. 313 if (IntConstantValue != ConvertedValue) { 314 ConstantValue = APValue(IntConstantValue); 315 ConstantType = Initializer->getType(); 316 return NK_Constant_Narrowing; 317 } 318 } else { 319 // Variables are always narrowings. 320 return NK_Variable_Narrowing; 321 } 322 } 323 return NK_Not_Narrowing; 324 325 // -- from long double to double or float, or from double to float, except 326 // where the source is a constant expression and the actual value after 327 // conversion is within the range of values that can be represented (even 328 // if it cannot be represented exactly), or 329 case ICK_Floating_Conversion: 330 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 331 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 332 // FromType is larger than ToType. 333 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 334 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 335 // Constant! 336 assert(ConstantValue.isFloat()); 337 llvm::APFloat FloatVal = ConstantValue.getFloat(); 338 // Convert the source value into the target type. 339 bool ignored; 340 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 341 Ctx.getFloatTypeSemantics(ToType), 342 llvm::APFloat::rmNearestTiesToEven, &ignored); 343 // If there was no overflow, the source value is within the range of 344 // values that can be represented. 345 if (ConvertStatus & llvm::APFloat::opOverflow) { 346 ConstantType = Initializer->getType(); 347 return NK_Constant_Narrowing; 348 } 349 } else { 350 return NK_Variable_Narrowing; 351 } 352 } 353 return NK_Not_Narrowing; 354 355 // -- from an integer type or unscoped enumeration type to an integer type 356 // that cannot represent all the values of the original type, except where 357 // the source is a constant expression and the actual value after 358 // conversion will fit into the target type and will produce the original 359 // value when converted back to the original type. 360 case ICK_Boolean_Conversion: // Bools are integers too. 361 if (!FromType->isIntegralOrUnscopedEnumerationType()) { 362 // Boolean conversions can be from pointers and pointers to members 363 // [conv.bool], and those aren't considered narrowing conversions. 364 return NK_Not_Narrowing; 365 } // Otherwise, fall through to the integral case. 366 case ICK_Integral_Conversion: { 367 assert(FromType->isIntegralOrUnscopedEnumerationType()); 368 assert(ToType->isIntegralOrUnscopedEnumerationType()); 369 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 370 const unsigned FromWidth = Ctx.getIntWidth(FromType); 371 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 372 const unsigned ToWidth = Ctx.getIntWidth(ToType); 373 374 if (FromWidth > ToWidth || 375 (FromWidth == ToWidth && FromSigned != ToSigned) || 376 (FromSigned && !ToSigned)) { 377 // Not all values of FromType can be represented in ToType. 378 llvm::APSInt InitializerValue; 379 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 380 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 381 // Such conversions on variables are always narrowing. 382 return NK_Variable_Narrowing; 383 } 384 bool Narrowing = false; 385 if (FromWidth < ToWidth) { 386 // Negative -> unsigned is narrowing. Otherwise, more bits is never 387 // narrowing. 388 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 389 Narrowing = true; 390 } else { 391 // Add a bit to the InitializerValue so we don't have to worry about 392 // signed vs. unsigned comparisons. 393 InitializerValue = InitializerValue.extend( 394 InitializerValue.getBitWidth() + 1); 395 // Convert the initializer to and from the target width and signed-ness. 396 llvm::APSInt ConvertedValue = InitializerValue; 397 ConvertedValue = ConvertedValue.trunc(ToWidth); 398 ConvertedValue.setIsSigned(ToSigned); 399 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 400 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 401 // If the result is different, this was a narrowing conversion. 402 if (ConvertedValue != InitializerValue) 403 Narrowing = true; 404 } 405 if (Narrowing) { 406 ConstantType = Initializer->getType(); 407 ConstantValue = APValue(InitializerValue); 408 return NK_Constant_Narrowing; 409 } 410 } 411 return NK_Not_Narrowing; 412 } 413 414 default: 415 // Other kinds of conversions are not narrowings. 416 return NK_Not_Narrowing; 417 } 418 } 419 420 /// dump - Print this standard conversion sequence to standard 421 /// error. Useful for debugging overloading issues. 422 void StandardConversionSequence::dump() const { 423 raw_ostream &OS = llvm::errs(); 424 bool PrintedSomething = false; 425 if (First != ICK_Identity) { 426 OS << GetImplicitConversionName(First); 427 PrintedSomething = true; 428 } 429 430 if (Second != ICK_Identity) { 431 if (PrintedSomething) { 432 OS << " -> "; 433 } 434 OS << GetImplicitConversionName(Second); 435 436 if (CopyConstructor) { 437 OS << " (by copy constructor)"; 438 } else if (DirectBinding) { 439 OS << " (direct reference binding)"; 440 } else if (ReferenceBinding) { 441 OS << " (reference binding)"; 442 } 443 PrintedSomething = true; 444 } 445 446 if (Third != ICK_Identity) { 447 if (PrintedSomething) { 448 OS << " -> "; 449 } 450 OS << GetImplicitConversionName(Third); 451 PrintedSomething = true; 452 } 453 454 if (!PrintedSomething) { 455 OS << "No conversions required"; 456 } 457 } 458 459 /// dump - Print this user-defined conversion sequence to standard 460 /// error. Useful for debugging overloading issues. 461 void UserDefinedConversionSequence::dump() const { 462 raw_ostream &OS = llvm::errs(); 463 if (Before.First || Before.Second || Before.Third) { 464 Before.dump(); 465 OS << " -> "; 466 } 467 if (ConversionFunction) 468 OS << '\'' << *ConversionFunction << '\''; 469 else 470 OS << "aggregate initialization"; 471 if (After.First || After.Second || After.Third) { 472 OS << " -> "; 473 After.dump(); 474 } 475 } 476 477 /// dump - Print this implicit conversion sequence to standard 478 /// error. Useful for debugging overloading issues. 479 void ImplicitConversionSequence::dump() const { 480 raw_ostream &OS = llvm::errs(); 481 if (isStdInitializerListElement()) 482 OS << "Worst std::initializer_list element conversion: "; 483 switch (ConversionKind) { 484 case StandardConversion: 485 OS << "Standard conversion: "; 486 Standard.dump(); 487 break; 488 case UserDefinedConversion: 489 OS << "User-defined conversion: "; 490 UserDefined.dump(); 491 break; 492 case EllipsisConversion: 493 OS << "Ellipsis conversion"; 494 break; 495 case AmbiguousConversion: 496 OS << "Ambiguous conversion"; 497 break; 498 case BadConversion: 499 OS << "Bad conversion"; 500 break; 501 } 502 503 OS << "\n"; 504 } 505 506 void AmbiguousConversionSequence::construct() { 507 new (&conversions()) ConversionSet(); 508 } 509 510 void AmbiguousConversionSequence::destruct() { 511 conversions().~ConversionSet(); 512 } 513 514 void 515 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 516 FromTypePtr = O.FromTypePtr; 517 ToTypePtr = O.ToTypePtr; 518 new (&conversions()) ConversionSet(O.conversions()); 519 } 520 521 namespace { 522 // Structure used by DeductionFailureInfo to store 523 // template argument information. 524 struct DFIArguments { 525 TemplateArgument FirstArg; 526 TemplateArgument SecondArg; 527 }; 528 // Structure used by DeductionFailureInfo to store 529 // template parameter and template argument information. 530 struct DFIParamWithArguments : DFIArguments { 531 TemplateParameter Param; 532 }; 533 } 534 535 /// \brief Convert from Sema's representation of template deduction information 536 /// to the form used in overload-candidate information. 537 DeductionFailureInfo 538 clang::MakeDeductionFailureInfo(ASTContext &Context, 539 Sema::TemplateDeductionResult TDK, 540 TemplateDeductionInfo &Info) { 541 DeductionFailureInfo Result; 542 Result.Result = static_cast<unsigned>(TDK); 543 Result.HasDiagnostic = false; 544 Result.Data = nullptr; 545 switch (TDK) { 546 case Sema::TDK_Success: 547 case Sema::TDK_Invalid: 548 case Sema::TDK_InstantiationDepth: 549 case Sema::TDK_TooManyArguments: 550 case Sema::TDK_TooFewArguments: 551 break; 552 553 case Sema::TDK_Incomplete: 554 case Sema::TDK_InvalidExplicitArguments: 555 Result.Data = Info.Param.getOpaqueValue(); 556 break; 557 558 case Sema::TDK_NonDeducedMismatch: { 559 // FIXME: Should allocate from normal heap so that we can free this later. 560 DFIArguments *Saved = new (Context) DFIArguments; 561 Saved->FirstArg = Info.FirstArg; 562 Saved->SecondArg = Info.SecondArg; 563 Result.Data = Saved; 564 break; 565 } 566 567 case Sema::TDK_Inconsistent: 568 case Sema::TDK_Underqualified: { 569 // FIXME: Should allocate from normal heap so that we can free this later. 570 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 571 Saved->Param = Info.Param; 572 Saved->FirstArg = Info.FirstArg; 573 Saved->SecondArg = Info.SecondArg; 574 Result.Data = Saved; 575 break; 576 } 577 578 case Sema::TDK_SubstitutionFailure: 579 Result.Data = Info.take(); 580 if (Info.hasSFINAEDiagnostic()) { 581 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 582 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 583 Info.takeSFINAEDiagnostic(*Diag); 584 Result.HasDiagnostic = true; 585 } 586 break; 587 588 case Sema::TDK_FailedOverloadResolution: 589 Result.Data = Info.Expression; 590 break; 591 592 case Sema::TDK_MiscellaneousDeductionFailure: 593 break; 594 } 595 596 return Result; 597 } 598 599 void DeductionFailureInfo::Destroy() { 600 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 601 case Sema::TDK_Success: 602 case Sema::TDK_Invalid: 603 case Sema::TDK_InstantiationDepth: 604 case Sema::TDK_Incomplete: 605 case Sema::TDK_TooManyArguments: 606 case Sema::TDK_TooFewArguments: 607 case Sema::TDK_InvalidExplicitArguments: 608 case Sema::TDK_FailedOverloadResolution: 609 break; 610 611 case Sema::TDK_Inconsistent: 612 case Sema::TDK_Underqualified: 613 case Sema::TDK_NonDeducedMismatch: 614 // FIXME: Destroy the data? 615 Data = nullptr; 616 break; 617 618 case Sema::TDK_SubstitutionFailure: 619 // FIXME: Destroy the template argument list? 620 Data = nullptr; 621 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 622 Diag->~PartialDiagnosticAt(); 623 HasDiagnostic = false; 624 } 625 break; 626 627 // Unhandled 628 case Sema::TDK_MiscellaneousDeductionFailure: 629 break; 630 } 631 } 632 633 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 634 if (HasDiagnostic) 635 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 636 return nullptr; 637 } 638 639 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 640 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 641 case Sema::TDK_Success: 642 case Sema::TDK_Invalid: 643 case Sema::TDK_InstantiationDepth: 644 case Sema::TDK_TooManyArguments: 645 case Sema::TDK_TooFewArguments: 646 case Sema::TDK_SubstitutionFailure: 647 case Sema::TDK_NonDeducedMismatch: 648 case Sema::TDK_FailedOverloadResolution: 649 return TemplateParameter(); 650 651 case Sema::TDK_Incomplete: 652 case Sema::TDK_InvalidExplicitArguments: 653 return TemplateParameter::getFromOpaqueValue(Data); 654 655 case Sema::TDK_Inconsistent: 656 case Sema::TDK_Underqualified: 657 return static_cast<DFIParamWithArguments*>(Data)->Param; 658 659 // Unhandled 660 case Sema::TDK_MiscellaneousDeductionFailure: 661 break; 662 } 663 664 return TemplateParameter(); 665 } 666 667 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 668 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 669 case Sema::TDK_Success: 670 case Sema::TDK_Invalid: 671 case Sema::TDK_InstantiationDepth: 672 case Sema::TDK_TooManyArguments: 673 case Sema::TDK_TooFewArguments: 674 case Sema::TDK_Incomplete: 675 case Sema::TDK_InvalidExplicitArguments: 676 case Sema::TDK_Inconsistent: 677 case Sema::TDK_Underqualified: 678 case Sema::TDK_NonDeducedMismatch: 679 case Sema::TDK_FailedOverloadResolution: 680 return nullptr; 681 682 case Sema::TDK_SubstitutionFailure: 683 return static_cast<TemplateArgumentList*>(Data); 684 685 // Unhandled 686 case Sema::TDK_MiscellaneousDeductionFailure: 687 break; 688 } 689 690 return nullptr; 691 } 692 693 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 694 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 695 case Sema::TDK_Success: 696 case Sema::TDK_Invalid: 697 case Sema::TDK_InstantiationDepth: 698 case Sema::TDK_Incomplete: 699 case Sema::TDK_TooManyArguments: 700 case Sema::TDK_TooFewArguments: 701 case Sema::TDK_InvalidExplicitArguments: 702 case Sema::TDK_SubstitutionFailure: 703 case Sema::TDK_FailedOverloadResolution: 704 return nullptr; 705 706 case Sema::TDK_Inconsistent: 707 case Sema::TDK_Underqualified: 708 case Sema::TDK_NonDeducedMismatch: 709 return &static_cast<DFIArguments*>(Data)->FirstArg; 710 711 // Unhandled 712 case Sema::TDK_MiscellaneousDeductionFailure: 713 break; 714 } 715 716 return nullptr; 717 } 718 719 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 720 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 721 case Sema::TDK_Success: 722 case Sema::TDK_Invalid: 723 case Sema::TDK_InstantiationDepth: 724 case Sema::TDK_Incomplete: 725 case Sema::TDK_TooManyArguments: 726 case Sema::TDK_TooFewArguments: 727 case Sema::TDK_InvalidExplicitArguments: 728 case Sema::TDK_SubstitutionFailure: 729 case Sema::TDK_FailedOverloadResolution: 730 return nullptr; 731 732 case Sema::TDK_Inconsistent: 733 case Sema::TDK_Underqualified: 734 case Sema::TDK_NonDeducedMismatch: 735 return &static_cast<DFIArguments*>(Data)->SecondArg; 736 737 // Unhandled 738 case Sema::TDK_MiscellaneousDeductionFailure: 739 break; 740 } 741 742 return nullptr; 743 } 744 745 Expr *DeductionFailureInfo::getExpr() { 746 if (static_cast<Sema::TemplateDeductionResult>(Result) == 747 Sema::TDK_FailedOverloadResolution) 748 return static_cast<Expr*>(Data); 749 750 return nullptr; 751 } 752 753 void OverloadCandidateSet::destroyCandidates() { 754 for (iterator i = begin(), e = end(); i != e; ++i) { 755 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 756 i->Conversions[ii].~ImplicitConversionSequence(); 757 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 758 i->DeductionFailure.Destroy(); 759 } 760 } 761 762 void OverloadCandidateSet::clear() { 763 destroyCandidates(); 764 NumInlineSequences = 0; 765 Candidates.clear(); 766 Functions.clear(); 767 } 768 769 namespace { 770 class UnbridgedCastsSet { 771 struct Entry { 772 Expr **Addr; 773 Expr *Saved; 774 }; 775 SmallVector<Entry, 2> Entries; 776 777 public: 778 void save(Sema &S, Expr *&E) { 779 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 780 Entry entry = { &E, E }; 781 Entries.push_back(entry); 782 E = S.stripARCUnbridgedCast(E); 783 } 784 785 void restore() { 786 for (SmallVectorImpl<Entry>::iterator 787 i = Entries.begin(), e = Entries.end(); i != e; ++i) 788 *i->Addr = i->Saved; 789 } 790 }; 791 } 792 793 /// checkPlaceholderForOverload - Do any interesting placeholder-like 794 /// preprocessing on the given expression. 795 /// 796 /// \param unbridgedCasts a collection to which to add unbridged casts; 797 /// without this, they will be immediately diagnosed as errors 798 /// 799 /// Return true on unrecoverable error. 800 static bool 801 checkPlaceholderForOverload(Sema &S, Expr *&E, 802 UnbridgedCastsSet *unbridgedCasts = nullptr) { 803 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 804 // We can't handle overloaded expressions here because overload 805 // resolution might reasonably tweak them. 806 if (placeholder->getKind() == BuiltinType::Overload) return false; 807 808 // If the context potentially accepts unbridged ARC casts, strip 809 // the unbridged cast and add it to the collection for later restoration. 810 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 811 unbridgedCasts) { 812 unbridgedCasts->save(S, E); 813 return false; 814 } 815 816 // Go ahead and check everything else. 817 ExprResult result = S.CheckPlaceholderExpr(E); 818 if (result.isInvalid()) 819 return true; 820 821 E = result.get(); 822 return false; 823 } 824 825 // Nothing to do. 826 return false; 827 } 828 829 /// checkArgPlaceholdersForOverload - Check a set of call operands for 830 /// placeholders. 831 static bool checkArgPlaceholdersForOverload(Sema &S, 832 MultiExprArg Args, 833 UnbridgedCastsSet &unbridged) { 834 for (unsigned i = 0, e = Args.size(); i != e; ++i) 835 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 836 return true; 837 838 return false; 839 } 840 841 // IsOverload - Determine whether the given New declaration is an 842 // overload of the declarations in Old. This routine returns false if 843 // New and Old cannot be overloaded, e.g., if New has the same 844 // signature as some function in Old (C++ 1.3.10) or if the Old 845 // declarations aren't functions (or function templates) at all. When 846 // it does return false, MatchedDecl will point to the decl that New 847 // cannot be overloaded with. This decl may be a UsingShadowDecl on 848 // top of the underlying declaration. 849 // 850 // Example: Given the following input: 851 // 852 // void f(int, float); // #1 853 // void f(int, int); // #2 854 // int f(int, int); // #3 855 // 856 // When we process #1, there is no previous declaration of "f", 857 // so IsOverload will not be used. 858 // 859 // When we process #2, Old contains only the FunctionDecl for #1. By 860 // comparing the parameter types, we see that #1 and #2 are overloaded 861 // (since they have different signatures), so this routine returns 862 // false; MatchedDecl is unchanged. 863 // 864 // When we process #3, Old is an overload set containing #1 and #2. We 865 // compare the signatures of #3 to #1 (they're overloaded, so we do 866 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 867 // identical (return types of functions are not part of the 868 // signature), IsOverload returns false and MatchedDecl will be set to 869 // point to the FunctionDecl for #2. 870 // 871 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 872 // into a class by a using declaration. The rules for whether to hide 873 // shadow declarations ignore some properties which otherwise figure 874 // into a function template's signature. 875 Sema::OverloadKind 876 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 877 NamedDecl *&Match, bool NewIsUsingDecl) { 878 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 879 I != E; ++I) { 880 NamedDecl *OldD = *I; 881 882 bool OldIsUsingDecl = false; 883 if (isa<UsingShadowDecl>(OldD)) { 884 OldIsUsingDecl = true; 885 886 // We can always introduce two using declarations into the same 887 // context, even if they have identical signatures. 888 if (NewIsUsingDecl) continue; 889 890 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 891 } 892 893 // If either declaration was introduced by a using declaration, 894 // we'll need to use slightly different rules for matching. 895 // Essentially, these rules are the normal rules, except that 896 // function templates hide function templates with different 897 // return types or template parameter lists. 898 bool UseMemberUsingDeclRules = 899 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 900 !New->getFriendObjectKind(); 901 902 if (FunctionDecl *OldF = OldD->getAsFunction()) { 903 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 904 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 905 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 906 continue; 907 } 908 909 if (!isa<FunctionTemplateDecl>(OldD) && 910 !shouldLinkPossiblyHiddenDecl(*I, New)) 911 continue; 912 913 Match = *I; 914 return Ovl_Match; 915 } 916 } else if (isa<UsingDecl>(OldD)) { 917 // We can overload with these, which can show up when doing 918 // redeclaration checks for UsingDecls. 919 assert(Old.getLookupKind() == LookupUsingDeclName); 920 } else if (isa<TagDecl>(OldD)) { 921 // We can always overload with tags by hiding them. 922 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 923 // Optimistically assume that an unresolved using decl will 924 // overload; if it doesn't, we'll have to diagnose during 925 // template instantiation. 926 } else { 927 // (C++ 13p1): 928 // Only function declarations can be overloaded; object and type 929 // declarations cannot be overloaded. 930 Match = *I; 931 return Ovl_NonFunction; 932 } 933 } 934 935 return Ovl_Overload; 936 } 937 938 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 939 bool UseUsingDeclRules) { 940 // C++ [basic.start.main]p2: This function shall not be overloaded. 941 if (New->isMain()) 942 return false; 943 944 // MSVCRT user defined entry points cannot be overloaded. 945 if (New->isMSVCRTEntryPoint()) 946 return false; 947 948 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 949 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 950 951 // C++ [temp.fct]p2: 952 // A function template can be overloaded with other function templates 953 // and with normal (non-template) functions. 954 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 955 return true; 956 957 // Is the function New an overload of the function Old? 958 QualType OldQType = Context.getCanonicalType(Old->getType()); 959 QualType NewQType = Context.getCanonicalType(New->getType()); 960 961 // Compare the signatures (C++ 1.3.10) of the two functions to 962 // determine whether they are overloads. If we find any mismatch 963 // in the signature, they are overloads. 964 965 // If either of these functions is a K&R-style function (no 966 // prototype), then we consider them to have matching signatures. 967 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 968 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 969 return false; 970 971 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 972 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 973 974 // The signature of a function includes the types of its 975 // parameters (C++ 1.3.10), which includes the presence or absence 976 // of the ellipsis; see C++ DR 357). 977 if (OldQType != NewQType && 978 (OldType->getNumParams() != NewType->getNumParams() || 979 OldType->isVariadic() != NewType->isVariadic() || 980 !FunctionParamTypesAreEqual(OldType, NewType))) 981 return true; 982 983 // C++ [temp.over.link]p4: 984 // The signature of a function template consists of its function 985 // signature, its return type and its template parameter list. The names 986 // of the template parameters are significant only for establishing the 987 // relationship between the template parameters and the rest of the 988 // signature. 989 // 990 // We check the return type and template parameter lists for function 991 // templates first; the remaining checks follow. 992 // 993 // However, we don't consider either of these when deciding whether 994 // a member introduced by a shadow declaration is hidden. 995 if (!UseUsingDeclRules && NewTemplate && 996 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 997 OldTemplate->getTemplateParameters(), 998 false, TPL_TemplateMatch) || 999 OldType->getReturnType() != NewType->getReturnType())) 1000 return true; 1001 1002 // If the function is a class member, its signature includes the 1003 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1004 // 1005 // As part of this, also check whether one of the member functions 1006 // is static, in which case they are not overloads (C++ 1007 // 13.1p2). While not part of the definition of the signature, 1008 // this check is important to determine whether these functions 1009 // can be overloaded. 1010 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1011 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1012 if (OldMethod && NewMethod && 1013 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1014 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1015 if (!UseUsingDeclRules && 1016 (OldMethod->getRefQualifier() == RQ_None || 1017 NewMethod->getRefQualifier() == RQ_None)) { 1018 // C++0x [over.load]p2: 1019 // - Member function declarations with the same name and the same 1020 // parameter-type-list as well as member function template 1021 // declarations with the same name, the same parameter-type-list, and 1022 // the same template parameter lists cannot be overloaded if any of 1023 // them, but not all, have a ref-qualifier (8.3.5). 1024 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1025 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1026 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1027 } 1028 return true; 1029 } 1030 1031 // We may not have applied the implicit const for a constexpr member 1032 // function yet (because we haven't yet resolved whether this is a static 1033 // or non-static member function). Add it now, on the assumption that this 1034 // is a redeclaration of OldMethod. 1035 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1036 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1037 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1038 !isa<CXXConstructorDecl>(NewMethod)) 1039 NewQuals |= Qualifiers::Const; 1040 1041 // We do not allow overloading based off of '__restrict'. 1042 OldQuals &= ~Qualifiers::Restrict; 1043 NewQuals &= ~Qualifiers::Restrict; 1044 if (OldQuals != NewQuals) 1045 return true; 1046 } 1047 1048 // enable_if attributes are an order-sensitive part of the signature. 1049 for (specific_attr_iterator<EnableIfAttr> 1050 NewI = New->specific_attr_begin<EnableIfAttr>(), 1051 NewE = New->specific_attr_end<EnableIfAttr>(), 1052 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1053 OldE = Old->specific_attr_end<EnableIfAttr>(); 1054 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1055 if (NewI == NewE || OldI == OldE) 1056 return true; 1057 llvm::FoldingSetNodeID NewID, OldID; 1058 NewI->getCond()->Profile(NewID, Context, true); 1059 OldI->getCond()->Profile(OldID, Context, true); 1060 if (NewID != OldID) 1061 return true; 1062 } 1063 1064 // The signatures match; this is not an overload. 1065 return false; 1066 } 1067 1068 /// \brief Checks availability of the function depending on the current 1069 /// function context. Inside an unavailable function, unavailability is ignored. 1070 /// 1071 /// \returns true if \arg FD is unavailable and current context is inside 1072 /// an available function, false otherwise. 1073 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1074 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1075 } 1076 1077 /// \brief Tries a user-defined conversion from From to ToType. 1078 /// 1079 /// Produces an implicit conversion sequence for when a standard conversion 1080 /// is not an option. See TryImplicitConversion for more information. 1081 static ImplicitConversionSequence 1082 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1083 bool SuppressUserConversions, 1084 bool AllowExplicit, 1085 bool InOverloadResolution, 1086 bool CStyle, 1087 bool AllowObjCWritebackConversion, 1088 bool AllowObjCConversionOnExplicit) { 1089 ImplicitConversionSequence ICS; 1090 1091 if (SuppressUserConversions) { 1092 // We're not in the case above, so there is no conversion that 1093 // we can perform. 1094 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1095 return ICS; 1096 } 1097 1098 // Attempt user-defined conversion. 1099 OverloadCandidateSet Conversions(From->getExprLoc(), 1100 OverloadCandidateSet::CSK_Normal); 1101 OverloadingResult UserDefResult 1102 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 1103 AllowExplicit, AllowObjCConversionOnExplicit); 1104 1105 if (UserDefResult == OR_Success) { 1106 ICS.setUserDefined(); 1107 ICS.UserDefined.Before.setAsIdentityConversion(); 1108 // C++ [over.ics.user]p4: 1109 // A conversion of an expression of class type to the same class 1110 // type is given Exact Match rank, and a conversion of an 1111 // expression of class type to a base class of that type is 1112 // given Conversion rank, in spite of the fact that a copy 1113 // constructor (i.e., a user-defined conversion function) is 1114 // called for those cases. 1115 if (CXXConstructorDecl *Constructor 1116 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1117 QualType FromCanon 1118 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1119 QualType ToCanon 1120 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1121 if (Constructor->isCopyConstructor() && 1122 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1123 // Turn this into a "standard" conversion sequence, so that it 1124 // gets ranked with standard conversion sequences. 1125 ICS.setStandard(); 1126 ICS.Standard.setAsIdentityConversion(); 1127 ICS.Standard.setFromType(From->getType()); 1128 ICS.Standard.setAllToTypes(ToType); 1129 ICS.Standard.CopyConstructor = Constructor; 1130 if (ToCanon != FromCanon) 1131 ICS.Standard.Second = ICK_Derived_To_Base; 1132 } 1133 } 1134 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 1135 ICS.setAmbiguous(); 1136 ICS.Ambiguous.setFromType(From->getType()); 1137 ICS.Ambiguous.setToType(ToType); 1138 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1139 Cand != Conversions.end(); ++Cand) 1140 if (Cand->Viable) 1141 ICS.Ambiguous.addConversion(Cand->Function); 1142 } else { 1143 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1144 } 1145 1146 return ICS; 1147 } 1148 1149 /// TryImplicitConversion - Attempt to perform an implicit conversion 1150 /// from the given expression (Expr) to the given type (ToType). This 1151 /// function returns an implicit conversion sequence that can be used 1152 /// to perform the initialization. Given 1153 /// 1154 /// void f(float f); 1155 /// void g(int i) { f(i); } 1156 /// 1157 /// this routine would produce an implicit conversion sequence to 1158 /// describe the initialization of f from i, which will be a standard 1159 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1160 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1161 // 1162 /// Note that this routine only determines how the conversion can be 1163 /// performed; it does not actually perform the conversion. As such, 1164 /// it will not produce any diagnostics if no conversion is available, 1165 /// but will instead return an implicit conversion sequence of kind 1166 /// "BadConversion". 1167 /// 1168 /// If @p SuppressUserConversions, then user-defined conversions are 1169 /// not permitted. 1170 /// If @p AllowExplicit, then explicit user-defined conversions are 1171 /// permitted. 1172 /// 1173 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1174 /// writeback conversion, which allows __autoreleasing id* parameters to 1175 /// be initialized with __strong id* or __weak id* arguments. 1176 static ImplicitConversionSequence 1177 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1178 bool SuppressUserConversions, 1179 bool AllowExplicit, 1180 bool InOverloadResolution, 1181 bool CStyle, 1182 bool AllowObjCWritebackConversion, 1183 bool AllowObjCConversionOnExplicit) { 1184 ImplicitConversionSequence ICS; 1185 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1186 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1187 ICS.setStandard(); 1188 return ICS; 1189 } 1190 1191 if (!S.getLangOpts().CPlusPlus) { 1192 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1193 return ICS; 1194 } 1195 1196 // C++ [over.ics.user]p4: 1197 // A conversion of an expression of class type to the same class 1198 // type is given Exact Match rank, and a conversion of an 1199 // expression of class type to a base class of that type is 1200 // given Conversion rank, in spite of the fact that a copy/move 1201 // constructor (i.e., a user-defined conversion function) is 1202 // called for those cases. 1203 QualType FromType = From->getType(); 1204 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1205 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1206 S.IsDerivedFrom(FromType, ToType))) { 1207 ICS.setStandard(); 1208 ICS.Standard.setAsIdentityConversion(); 1209 ICS.Standard.setFromType(FromType); 1210 ICS.Standard.setAllToTypes(ToType); 1211 1212 // We don't actually check at this point whether there is a valid 1213 // copy/move constructor, since overloading just assumes that it 1214 // exists. When we actually perform initialization, we'll find the 1215 // appropriate constructor to copy the returned object, if needed. 1216 ICS.Standard.CopyConstructor = nullptr; 1217 1218 // Determine whether this is considered a derived-to-base conversion. 1219 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1220 ICS.Standard.Second = ICK_Derived_To_Base; 1221 1222 return ICS; 1223 } 1224 1225 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1226 AllowExplicit, InOverloadResolution, CStyle, 1227 AllowObjCWritebackConversion, 1228 AllowObjCConversionOnExplicit); 1229 } 1230 1231 ImplicitConversionSequence 1232 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1233 bool SuppressUserConversions, 1234 bool AllowExplicit, 1235 bool InOverloadResolution, 1236 bool CStyle, 1237 bool AllowObjCWritebackConversion) { 1238 return ::TryImplicitConversion(*this, From, ToType, 1239 SuppressUserConversions, AllowExplicit, 1240 InOverloadResolution, CStyle, 1241 AllowObjCWritebackConversion, 1242 /*AllowObjCConversionOnExplicit=*/false); 1243 } 1244 1245 /// PerformImplicitConversion - Perform an implicit conversion of the 1246 /// expression From to the type ToType. Returns the 1247 /// converted expression. Flavor is the kind of conversion we're 1248 /// performing, used in the error message. If @p AllowExplicit, 1249 /// explicit user-defined conversions are permitted. 1250 ExprResult 1251 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1252 AssignmentAction Action, bool AllowExplicit) { 1253 ImplicitConversionSequence ICS; 1254 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1255 } 1256 1257 ExprResult 1258 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1259 AssignmentAction Action, bool AllowExplicit, 1260 ImplicitConversionSequence& ICS) { 1261 if (checkPlaceholderForOverload(*this, From)) 1262 return ExprError(); 1263 1264 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1265 bool AllowObjCWritebackConversion 1266 = getLangOpts().ObjCAutoRefCount && 1267 (Action == AA_Passing || Action == AA_Sending); 1268 if (getLangOpts().ObjC1) 1269 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1270 ToType, From->getType(), From); 1271 ICS = ::TryImplicitConversion(*this, From, ToType, 1272 /*SuppressUserConversions=*/false, 1273 AllowExplicit, 1274 /*InOverloadResolution=*/false, 1275 /*CStyle=*/false, 1276 AllowObjCWritebackConversion, 1277 /*AllowObjCConversionOnExplicit=*/false); 1278 return PerformImplicitConversion(From, ToType, ICS, Action); 1279 } 1280 1281 /// \brief Determine whether the conversion from FromType to ToType is a valid 1282 /// conversion that strips "noreturn" off the nested function type. 1283 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1284 QualType &ResultTy) { 1285 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1286 return false; 1287 1288 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1289 // where F adds one of the following at most once: 1290 // - a pointer 1291 // - a member pointer 1292 // - a block pointer 1293 CanQualType CanTo = Context.getCanonicalType(ToType); 1294 CanQualType CanFrom = Context.getCanonicalType(FromType); 1295 Type::TypeClass TyClass = CanTo->getTypeClass(); 1296 if (TyClass != CanFrom->getTypeClass()) return false; 1297 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1298 if (TyClass == Type::Pointer) { 1299 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1300 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1301 } else if (TyClass == Type::BlockPointer) { 1302 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1303 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1304 } else if (TyClass == Type::MemberPointer) { 1305 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1306 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1307 } else { 1308 return false; 1309 } 1310 1311 TyClass = CanTo->getTypeClass(); 1312 if (TyClass != CanFrom->getTypeClass()) return false; 1313 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1314 return false; 1315 } 1316 1317 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1318 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1319 if (!EInfo.getNoReturn()) return false; 1320 1321 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1322 assert(QualType(FromFn, 0).isCanonical()); 1323 if (QualType(FromFn, 0) != CanTo) return false; 1324 1325 ResultTy = ToType; 1326 return true; 1327 } 1328 1329 /// \brief Determine whether the conversion from FromType to ToType is a valid 1330 /// vector conversion. 1331 /// 1332 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1333 /// conversion. 1334 static bool IsVectorConversion(Sema &S, QualType FromType, 1335 QualType ToType, ImplicitConversionKind &ICK) { 1336 // We need at least one of these types to be a vector type to have a vector 1337 // conversion. 1338 if (!ToType->isVectorType() && !FromType->isVectorType()) 1339 return false; 1340 1341 // Identical types require no conversions. 1342 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1343 return false; 1344 1345 // There are no conversions between extended vector types, only identity. 1346 if (ToType->isExtVectorType()) { 1347 // There are no conversions between extended vector types other than the 1348 // identity conversion. 1349 if (FromType->isExtVectorType()) 1350 return false; 1351 1352 // Vector splat from any arithmetic type to a vector. 1353 if (FromType->isArithmeticType()) { 1354 ICK = ICK_Vector_Splat; 1355 return true; 1356 } 1357 } 1358 1359 // We can perform the conversion between vector types in the following cases: 1360 // 1)vector types are equivalent AltiVec and GCC vector types 1361 // 2)lax vector conversions are permitted and the vector types are of the 1362 // same size 1363 if (ToType->isVectorType() && FromType->isVectorType()) { 1364 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1365 S.isLaxVectorConversion(FromType, ToType)) { 1366 ICK = ICK_Vector_Conversion; 1367 return true; 1368 } 1369 } 1370 1371 return false; 1372 } 1373 1374 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1375 bool InOverloadResolution, 1376 StandardConversionSequence &SCS, 1377 bool CStyle); 1378 1379 /// IsStandardConversion - Determines whether there is a standard 1380 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1381 /// expression From to the type ToType. Standard conversion sequences 1382 /// only consider non-class types; for conversions that involve class 1383 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1384 /// contain the standard conversion sequence required to perform this 1385 /// conversion and this routine will return true. Otherwise, this 1386 /// routine will return false and the value of SCS is unspecified. 1387 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1388 bool InOverloadResolution, 1389 StandardConversionSequence &SCS, 1390 bool CStyle, 1391 bool AllowObjCWritebackConversion) { 1392 QualType FromType = From->getType(); 1393 1394 // Standard conversions (C++ [conv]) 1395 SCS.setAsIdentityConversion(); 1396 SCS.IncompatibleObjC = false; 1397 SCS.setFromType(FromType); 1398 SCS.CopyConstructor = nullptr; 1399 1400 // There are no standard conversions for class types in C++, so 1401 // abort early. When overloading in C, however, we do permit 1402 if (FromType->isRecordType() || ToType->isRecordType()) { 1403 if (S.getLangOpts().CPlusPlus) 1404 return false; 1405 1406 // When we're overloading in C, we allow, as standard conversions, 1407 } 1408 1409 // The first conversion can be an lvalue-to-rvalue conversion, 1410 // array-to-pointer conversion, or function-to-pointer conversion 1411 // (C++ 4p1). 1412 1413 if (FromType == S.Context.OverloadTy) { 1414 DeclAccessPair AccessPair; 1415 if (FunctionDecl *Fn 1416 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1417 AccessPair)) { 1418 // We were able to resolve the address of the overloaded function, 1419 // so we can convert to the type of that function. 1420 FromType = Fn->getType(); 1421 SCS.setFromType(FromType); 1422 1423 // we can sometimes resolve &foo<int> regardless of ToType, so check 1424 // if the type matches (identity) or we are converting to bool 1425 if (!S.Context.hasSameUnqualifiedType( 1426 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1427 QualType resultTy; 1428 // if the function type matches except for [[noreturn]], it's ok 1429 if (!S.IsNoReturnConversion(FromType, 1430 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1431 // otherwise, only a boolean conversion is standard 1432 if (!ToType->isBooleanType()) 1433 return false; 1434 } 1435 1436 // Check if the "from" expression is taking the address of an overloaded 1437 // function and recompute the FromType accordingly. Take advantage of the 1438 // fact that non-static member functions *must* have such an address-of 1439 // expression. 1440 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1441 if (Method && !Method->isStatic()) { 1442 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1443 "Non-unary operator on non-static member address"); 1444 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1445 == UO_AddrOf && 1446 "Non-address-of operator on non-static member address"); 1447 const Type *ClassType 1448 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1449 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1450 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1451 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1452 UO_AddrOf && 1453 "Non-address-of operator for overloaded function expression"); 1454 FromType = S.Context.getPointerType(FromType); 1455 } 1456 1457 // Check that we've computed the proper type after overload resolution. 1458 assert(S.Context.hasSameType( 1459 FromType, 1460 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1461 } else { 1462 return false; 1463 } 1464 } 1465 // Lvalue-to-rvalue conversion (C++11 4.1): 1466 // A glvalue (3.10) of a non-function, non-array type T can 1467 // be converted to a prvalue. 1468 bool argIsLValue = From->isGLValue(); 1469 if (argIsLValue && 1470 !FromType->isFunctionType() && !FromType->isArrayType() && 1471 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1472 SCS.First = ICK_Lvalue_To_Rvalue; 1473 1474 // C11 6.3.2.1p2: 1475 // ... if the lvalue has atomic type, the value has the non-atomic version 1476 // of the type of the lvalue ... 1477 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1478 FromType = Atomic->getValueType(); 1479 1480 // If T is a non-class type, the type of the rvalue is the 1481 // cv-unqualified version of T. Otherwise, the type of the rvalue 1482 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1483 // just strip the qualifiers because they don't matter. 1484 FromType = FromType.getUnqualifiedType(); 1485 } else if (FromType->isArrayType()) { 1486 // Array-to-pointer conversion (C++ 4.2) 1487 SCS.First = ICK_Array_To_Pointer; 1488 1489 // An lvalue or rvalue of type "array of N T" or "array of unknown 1490 // bound of T" can be converted to an rvalue of type "pointer to 1491 // T" (C++ 4.2p1). 1492 FromType = S.Context.getArrayDecayedType(FromType); 1493 1494 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1495 // This conversion is deprecated in C++03 (D.4) 1496 SCS.DeprecatedStringLiteralToCharPtr = true; 1497 1498 // For the purpose of ranking in overload resolution 1499 // (13.3.3.1.1), this conversion is considered an 1500 // array-to-pointer conversion followed by a qualification 1501 // conversion (4.4). (C++ 4.2p2) 1502 SCS.Second = ICK_Identity; 1503 SCS.Third = ICK_Qualification; 1504 SCS.QualificationIncludesObjCLifetime = false; 1505 SCS.setAllToTypes(FromType); 1506 return true; 1507 } 1508 } else if (FromType->isFunctionType() && argIsLValue) { 1509 // Function-to-pointer conversion (C++ 4.3). 1510 SCS.First = ICK_Function_To_Pointer; 1511 1512 // An lvalue of function type T can be converted to an rvalue of 1513 // type "pointer to T." The result is a pointer to the 1514 // function. (C++ 4.3p1). 1515 FromType = S.Context.getPointerType(FromType); 1516 } else { 1517 // We don't require any conversions for the first step. 1518 SCS.First = ICK_Identity; 1519 } 1520 SCS.setToType(0, FromType); 1521 1522 // The second conversion can be an integral promotion, floating 1523 // point promotion, integral conversion, floating point conversion, 1524 // floating-integral conversion, pointer conversion, 1525 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1526 // For overloading in C, this can also be a "compatible-type" 1527 // conversion. 1528 bool IncompatibleObjC = false; 1529 ImplicitConversionKind SecondICK = ICK_Identity; 1530 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1531 // The unqualified versions of the types are the same: there's no 1532 // conversion to do. 1533 SCS.Second = ICK_Identity; 1534 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1535 // Integral promotion (C++ 4.5). 1536 SCS.Second = ICK_Integral_Promotion; 1537 FromType = ToType.getUnqualifiedType(); 1538 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1539 // Floating point promotion (C++ 4.6). 1540 SCS.Second = ICK_Floating_Promotion; 1541 FromType = ToType.getUnqualifiedType(); 1542 } else if (S.IsComplexPromotion(FromType, ToType)) { 1543 // Complex promotion (Clang extension) 1544 SCS.Second = ICK_Complex_Promotion; 1545 FromType = ToType.getUnqualifiedType(); 1546 } else if (ToType->isBooleanType() && 1547 (FromType->isArithmeticType() || 1548 FromType->isAnyPointerType() || 1549 FromType->isBlockPointerType() || 1550 FromType->isMemberPointerType() || 1551 FromType->isNullPtrType())) { 1552 // Boolean conversions (C++ 4.12). 1553 SCS.Second = ICK_Boolean_Conversion; 1554 FromType = S.Context.BoolTy; 1555 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1556 ToType->isIntegralType(S.Context)) { 1557 // Integral conversions (C++ 4.7). 1558 SCS.Second = ICK_Integral_Conversion; 1559 FromType = ToType.getUnqualifiedType(); 1560 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1561 // Complex conversions (C99 6.3.1.6) 1562 SCS.Second = ICK_Complex_Conversion; 1563 FromType = ToType.getUnqualifiedType(); 1564 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1565 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1566 // Complex-real conversions (C99 6.3.1.7) 1567 SCS.Second = ICK_Complex_Real; 1568 FromType = ToType.getUnqualifiedType(); 1569 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1570 // Floating point conversions (C++ 4.8). 1571 SCS.Second = ICK_Floating_Conversion; 1572 FromType = ToType.getUnqualifiedType(); 1573 } else if ((FromType->isRealFloatingType() && 1574 ToType->isIntegralType(S.Context)) || 1575 (FromType->isIntegralOrUnscopedEnumerationType() && 1576 ToType->isRealFloatingType())) { 1577 // Floating-integral conversions (C++ 4.9). 1578 SCS.Second = ICK_Floating_Integral; 1579 FromType = ToType.getUnqualifiedType(); 1580 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1581 SCS.Second = ICK_Block_Pointer_Conversion; 1582 } else if (AllowObjCWritebackConversion && 1583 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1584 SCS.Second = ICK_Writeback_Conversion; 1585 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1586 FromType, IncompatibleObjC)) { 1587 // Pointer conversions (C++ 4.10). 1588 SCS.Second = ICK_Pointer_Conversion; 1589 SCS.IncompatibleObjC = IncompatibleObjC; 1590 FromType = FromType.getUnqualifiedType(); 1591 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1592 InOverloadResolution, FromType)) { 1593 // Pointer to member conversions (4.11). 1594 SCS.Second = ICK_Pointer_Member; 1595 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1596 SCS.Second = SecondICK; 1597 FromType = ToType.getUnqualifiedType(); 1598 } else if (!S.getLangOpts().CPlusPlus && 1599 S.Context.typesAreCompatible(ToType, FromType)) { 1600 // Compatible conversions (Clang extension for C function overloading) 1601 SCS.Second = ICK_Compatible_Conversion; 1602 FromType = ToType.getUnqualifiedType(); 1603 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1604 // Treat a conversion that strips "noreturn" as an identity conversion. 1605 SCS.Second = ICK_NoReturn_Adjustment; 1606 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1607 InOverloadResolution, 1608 SCS, CStyle)) { 1609 SCS.Second = ICK_TransparentUnionConversion; 1610 FromType = ToType; 1611 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1612 CStyle)) { 1613 // tryAtomicConversion has updated the standard conversion sequence 1614 // appropriately. 1615 return true; 1616 } else if (ToType->isEventT() && 1617 From->isIntegerConstantExpr(S.getASTContext()) && 1618 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1619 SCS.Second = ICK_Zero_Event_Conversion; 1620 FromType = ToType; 1621 } else { 1622 // No second conversion required. 1623 SCS.Second = ICK_Identity; 1624 } 1625 SCS.setToType(1, FromType); 1626 1627 QualType CanonFrom; 1628 QualType CanonTo; 1629 // The third conversion can be a qualification conversion (C++ 4p1). 1630 bool ObjCLifetimeConversion; 1631 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1632 ObjCLifetimeConversion)) { 1633 SCS.Third = ICK_Qualification; 1634 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1635 FromType = ToType; 1636 CanonFrom = S.Context.getCanonicalType(FromType); 1637 CanonTo = S.Context.getCanonicalType(ToType); 1638 } else { 1639 // No conversion required 1640 SCS.Third = ICK_Identity; 1641 1642 // C++ [over.best.ics]p6: 1643 // [...] Any difference in top-level cv-qualification is 1644 // subsumed by the initialization itself and does not constitute 1645 // a conversion. [...] 1646 CanonFrom = S.Context.getCanonicalType(FromType); 1647 CanonTo = S.Context.getCanonicalType(ToType); 1648 if (CanonFrom.getLocalUnqualifiedType() 1649 == CanonTo.getLocalUnqualifiedType() && 1650 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1651 FromType = ToType; 1652 CanonFrom = CanonTo; 1653 } 1654 } 1655 SCS.setToType(2, FromType); 1656 1657 // If we have not converted the argument type to the parameter type, 1658 // this is a bad conversion sequence. 1659 if (CanonFrom != CanonTo) 1660 return false; 1661 1662 return true; 1663 } 1664 1665 static bool 1666 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1667 QualType &ToType, 1668 bool InOverloadResolution, 1669 StandardConversionSequence &SCS, 1670 bool CStyle) { 1671 1672 const RecordType *UT = ToType->getAsUnionType(); 1673 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1674 return false; 1675 // The field to initialize within the transparent union. 1676 RecordDecl *UD = UT->getDecl(); 1677 // It's compatible if the expression matches any of the fields. 1678 for (const auto *it : UD->fields()) { 1679 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1680 CStyle, /*ObjCWritebackConversion=*/false)) { 1681 ToType = it->getType(); 1682 return true; 1683 } 1684 } 1685 return false; 1686 } 1687 1688 /// IsIntegralPromotion - Determines whether the conversion from the 1689 /// expression From (whose potentially-adjusted type is FromType) to 1690 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1691 /// sets PromotedType to the promoted type. 1692 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1693 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1694 // All integers are built-in. 1695 if (!To) { 1696 return false; 1697 } 1698 1699 // An rvalue of type char, signed char, unsigned char, short int, or 1700 // unsigned short int can be converted to an rvalue of type int if 1701 // int can represent all the values of the source type; otherwise, 1702 // the source rvalue can be converted to an rvalue of type unsigned 1703 // int (C++ 4.5p1). 1704 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1705 !FromType->isEnumeralType()) { 1706 if (// We can promote any signed, promotable integer type to an int 1707 (FromType->isSignedIntegerType() || 1708 // We can promote any unsigned integer type whose size is 1709 // less than int to an int. 1710 (!FromType->isSignedIntegerType() && 1711 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1712 return To->getKind() == BuiltinType::Int; 1713 } 1714 1715 return To->getKind() == BuiltinType::UInt; 1716 } 1717 1718 // C++11 [conv.prom]p3: 1719 // A prvalue of an unscoped enumeration type whose underlying type is not 1720 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1721 // following types that can represent all the values of the enumeration 1722 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1723 // unsigned int, long int, unsigned long int, long long int, or unsigned 1724 // long long int. If none of the types in that list can represent all the 1725 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1726 // type can be converted to an rvalue a prvalue of the extended integer type 1727 // with lowest integer conversion rank (4.13) greater than the rank of long 1728 // long in which all the values of the enumeration can be represented. If 1729 // there are two such extended types, the signed one is chosen. 1730 // C++11 [conv.prom]p4: 1731 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1732 // can be converted to a prvalue of its underlying type. Moreover, if 1733 // integral promotion can be applied to its underlying type, a prvalue of an 1734 // unscoped enumeration type whose underlying type is fixed can also be 1735 // converted to a prvalue of the promoted underlying type. 1736 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1737 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1738 // provided for a scoped enumeration. 1739 if (FromEnumType->getDecl()->isScoped()) 1740 return false; 1741 1742 // We can perform an integral promotion to the underlying type of the enum, 1743 // even if that's not the promoted type. 1744 if (FromEnumType->getDecl()->isFixed()) { 1745 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1746 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1747 IsIntegralPromotion(From, Underlying, ToType); 1748 } 1749 1750 // We have already pre-calculated the promotion type, so this is trivial. 1751 if (ToType->isIntegerType() && 1752 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1753 return Context.hasSameUnqualifiedType(ToType, 1754 FromEnumType->getDecl()->getPromotionType()); 1755 } 1756 1757 // C++0x [conv.prom]p2: 1758 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1759 // to an rvalue a prvalue of the first of the following types that can 1760 // represent all the values of its underlying type: int, unsigned int, 1761 // long int, unsigned long int, long long int, or unsigned long long int. 1762 // If none of the types in that list can represent all the values of its 1763 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1764 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1765 // type. 1766 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1767 ToType->isIntegerType()) { 1768 // Determine whether the type we're converting from is signed or 1769 // unsigned. 1770 bool FromIsSigned = FromType->isSignedIntegerType(); 1771 uint64_t FromSize = Context.getTypeSize(FromType); 1772 1773 // The types we'll try to promote to, in the appropriate 1774 // order. Try each of these types. 1775 QualType PromoteTypes[6] = { 1776 Context.IntTy, Context.UnsignedIntTy, 1777 Context.LongTy, Context.UnsignedLongTy , 1778 Context.LongLongTy, Context.UnsignedLongLongTy 1779 }; 1780 for (int Idx = 0; Idx < 6; ++Idx) { 1781 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1782 if (FromSize < ToSize || 1783 (FromSize == ToSize && 1784 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1785 // We found the type that we can promote to. If this is the 1786 // type we wanted, we have a promotion. Otherwise, no 1787 // promotion. 1788 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1789 } 1790 } 1791 } 1792 1793 // An rvalue for an integral bit-field (9.6) can be converted to an 1794 // rvalue of type int if int can represent all the values of the 1795 // bit-field; otherwise, it can be converted to unsigned int if 1796 // unsigned int can represent all the values of the bit-field. If 1797 // the bit-field is larger yet, no integral promotion applies to 1798 // it. If the bit-field has an enumerated type, it is treated as any 1799 // other value of that type for promotion purposes (C++ 4.5p3). 1800 // FIXME: We should delay checking of bit-fields until we actually perform the 1801 // conversion. 1802 using llvm::APSInt; 1803 if (From) 1804 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1805 APSInt BitWidth; 1806 if (FromType->isIntegralType(Context) && 1807 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1808 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1809 ToSize = Context.getTypeSize(ToType); 1810 1811 // Are we promoting to an int from a bitfield that fits in an int? 1812 if (BitWidth < ToSize || 1813 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1814 return To->getKind() == BuiltinType::Int; 1815 } 1816 1817 // Are we promoting to an unsigned int from an unsigned bitfield 1818 // that fits into an unsigned int? 1819 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1820 return To->getKind() == BuiltinType::UInt; 1821 } 1822 1823 return false; 1824 } 1825 } 1826 1827 // An rvalue of type bool can be converted to an rvalue of type int, 1828 // with false becoming zero and true becoming one (C++ 4.5p4). 1829 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1830 return true; 1831 } 1832 1833 return false; 1834 } 1835 1836 /// IsFloatingPointPromotion - Determines whether the conversion from 1837 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1838 /// returns true and sets PromotedType to the promoted type. 1839 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1840 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1841 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1842 /// An rvalue of type float can be converted to an rvalue of type 1843 /// double. (C++ 4.6p1). 1844 if (FromBuiltin->getKind() == BuiltinType::Float && 1845 ToBuiltin->getKind() == BuiltinType::Double) 1846 return true; 1847 1848 // C99 6.3.1.5p1: 1849 // When a float is promoted to double or long double, or a 1850 // double is promoted to long double [...]. 1851 if (!getLangOpts().CPlusPlus && 1852 (FromBuiltin->getKind() == BuiltinType::Float || 1853 FromBuiltin->getKind() == BuiltinType::Double) && 1854 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1855 return true; 1856 1857 // Half can be promoted to float. 1858 if (!getLangOpts().NativeHalfType && 1859 FromBuiltin->getKind() == BuiltinType::Half && 1860 ToBuiltin->getKind() == BuiltinType::Float) 1861 return true; 1862 } 1863 1864 return false; 1865 } 1866 1867 /// \brief Determine if a conversion is a complex promotion. 1868 /// 1869 /// A complex promotion is defined as a complex -> complex conversion 1870 /// where the conversion between the underlying real types is a 1871 /// floating-point or integral promotion. 1872 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1873 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1874 if (!FromComplex) 1875 return false; 1876 1877 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1878 if (!ToComplex) 1879 return false; 1880 1881 return IsFloatingPointPromotion(FromComplex->getElementType(), 1882 ToComplex->getElementType()) || 1883 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 1884 ToComplex->getElementType()); 1885 } 1886 1887 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1888 /// the pointer type FromPtr to a pointer to type ToPointee, with the 1889 /// same type qualifiers as FromPtr has on its pointee type. ToType, 1890 /// if non-empty, will be a pointer to ToType that may or may not have 1891 /// the right set of qualifiers on its pointee. 1892 /// 1893 static QualType 1894 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1895 QualType ToPointee, QualType ToType, 1896 ASTContext &Context, 1897 bool StripObjCLifetime = false) { 1898 assert((FromPtr->getTypeClass() == Type::Pointer || 1899 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1900 "Invalid similarly-qualified pointer type"); 1901 1902 /// Conversions to 'id' subsume cv-qualifier conversions. 1903 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1904 return ToType.getUnqualifiedType(); 1905 1906 QualType CanonFromPointee 1907 = Context.getCanonicalType(FromPtr->getPointeeType()); 1908 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1909 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1910 1911 if (StripObjCLifetime) 1912 Quals.removeObjCLifetime(); 1913 1914 // Exact qualifier match -> return the pointer type we're converting to. 1915 if (CanonToPointee.getLocalQualifiers() == Quals) { 1916 // ToType is exactly what we need. Return it. 1917 if (!ToType.isNull()) 1918 return ToType.getUnqualifiedType(); 1919 1920 // Build a pointer to ToPointee. It has the right qualifiers 1921 // already. 1922 if (isa<ObjCObjectPointerType>(ToType)) 1923 return Context.getObjCObjectPointerType(ToPointee); 1924 return Context.getPointerType(ToPointee); 1925 } 1926 1927 // Just build a canonical type that has the right qualifiers. 1928 QualType QualifiedCanonToPointee 1929 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1930 1931 if (isa<ObjCObjectPointerType>(ToType)) 1932 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1933 return Context.getPointerType(QualifiedCanonToPointee); 1934 } 1935 1936 static bool isNullPointerConstantForConversion(Expr *Expr, 1937 bool InOverloadResolution, 1938 ASTContext &Context) { 1939 // Handle value-dependent integral null pointer constants correctly. 1940 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1941 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1942 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1943 return !InOverloadResolution; 1944 1945 return Expr->isNullPointerConstant(Context, 1946 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1947 : Expr::NPC_ValueDependentIsNull); 1948 } 1949 1950 /// IsPointerConversion - Determines whether the conversion of the 1951 /// expression From, which has the (possibly adjusted) type FromType, 1952 /// can be converted to the type ToType via a pointer conversion (C++ 1953 /// 4.10). If so, returns true and places the converted type (that 1954 /// might differ from ToType in its cv-qualifiers at some level) into 1955 /// ConvertedType. 1956 /// 1957 /// This routine also supports conversions to and from block pointers 1958 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 1959 /// pointers to interfaces. FIXME: Once we've determined the 1960 /// appropriate overloading rules for Objective-C, we may want to 1961 /// split the Objective-C checks into a different routine; however, 1962 /// GCC seems to consider all of these conversions to be pointer 1963 /// conversions, so for now they live here. IncompatibleObjC will be 1964 /// set if the conversion is an allowed Objective-C conversion that 1965 /// should result in a warning. 1966 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1967 bool InOverloadResolution, 1968 QualType& ConvertedType, 1969 bool &IncompatibleObjC) { 1970 IncompatibleObjC = false; 1971 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 1972 IncompatibleObjC)) 1973 return true; 1974 1975 // Conversion from a null pointer constant to any Objective-C pointer type. 1976 if (ToType->isObjCObjectPointerType() && 1977 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1978 ConvertedType = ToType; 1979 return true; 1980 } 1981 1982 // Blocks: Block pointers can be converted to void*. 1983 if (FromType->isBlockPointerType() && ToType->isPointerType() && 1984 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 1985 ConvertedType = ToType; 1986 return true; 1987 } 1988 // Blocks: A null pointer constant can be converted to a block 1989 // pointer type. 1990 if (ToType->isBlockPointerType() && 1991 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1992 ConvertedType = ToType; 1993 return true; 1994 } 1995 1996 // If the left-hand-side is nullptr_t, the right side can be a null 1997 // pointer constant. 1998 if (ToType->isNullPtrType() && 1999 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2000 ConvertedType = ToType; 2001 return true; 2002 } 2003 2004 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2005 if (!ToTypePtr) 2006 return false; 2007 2008 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2009 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2010 ConvertedType = ToType; 2011 return true; 2012 } 2013 2014 // Beyond this point, both types need to be pointers 2015 // , including objective-c pointers. 2016 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2017 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2018 !getLangOpts().ObjCAutoRefCount) { 2019 ConvertedType = BuildSimilarlyQualifiedPointerType( 2020 FromType->getAs<ObjCObjectPointerType>(), 2021 ToPointeeType, 2022 ToType, Context); 2023 return true; 2024 } 2025 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2026 if (!FromTypePtr) 2027 return false; 2028 2029 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2030 2031 // If the unqualified pointee types are the same, this can't be a 2032 // pointer conversion, so don't do all of the work below. 2033 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2034 return false; 2035 2036 // An rvalue of type "pointer to cv T," where T is an object type, 2037 // can be converted to an rvalue of type "pointer to cv void" (C++ 2038 // 4.10p2). 2039 if (FromPointeeType->isIncompleteOrObjectType() && 2040 ToPointeeType->isVoidType()) { 2041 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2042 ToPointeeType, 2043 ToType, Context, 2044 /*StripObjCLifetime=*/true); 2045 return true; 2046 } 2047 2048 // MSVC allows implicit function to void* type conversion. 2049 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 2050 ToPointeeType->isVoidType()) { 2051 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2052 ToPointeeType, 2053 ToType, Context); 2054 return true; 2055 } 2056 2057 // When we're overloading in C, we allow a special kind of pointer 2058 // conversion for compatible-but-not-identical pointee types. 2059 if (!getLangOpts().CPlusPlus && 2060 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2061 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2062 ToPointeeType, 2063 ToType, Context); 2064 return true; 2065 } 2066 2067 // C++ [conv.ptr]p3: 2068 // 2069 // An rvalue of type "pointer to cv D," where D is a class type, 2070 // can be converted to an rvalue of type "pointer to cv B," where 2071 // B is a base class (clause 10) of D. If B is an inaccessible 2072 // (clause 11) or ambiguous (10.2) base class of D, a program that 2073 // necessitates this conversion is ill-formed. The result of the 2074 // conversion is a pointer to the base class sub-object of the 2075 // derived class object. The null pointer value is converted to 2076 // the null pointer value of the destination type. 2077 // 2078 // Note that we do not check for ambiguity or inaccessibility 2079 // here. That is handled by CheckPointerConversion. 2080 if (getLangOpts().CPlusPlus && 2081 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2082 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2083 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2084 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2085 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2086 ToPointeeType, 2087 ToType, Context); 2088 return true; 2089 } 2090 2091 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2092 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2093 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2094 ToPointeeType, 2095 ToType, Context); 2096 return true; 2097 } 2098 2099 return false; 2100 } 2101 2102 /// \brief Adopt the given qualifiers for the given type. 2103 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2104 Qualifiers TQs = T.getQualifiers(); 2105 2106 // Check whether qualifiers already match. 2107 if (TQs == Qs) 2108 return T; 2109 2110 if (Qs.compatiblyIncludes(TQs)) 2111 return Context.getQualifiedType(T, Qs); 2112 2113 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2114 } 2115 2116 /// isObjCPointerConversion - Determines whether this is an 2117 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2118 /// with the same arguments and return values. 2119 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2120 QualType& ConvertedType, 2121 bool &IncompatibleObjC) { 2122 if (!getLangOpts().ObjC1) 2123 return false; 2124 2125 // The set of qualifiers on the type we're converting from. 2126 Qualifiers FromQualifiers = FromType.getQualifiers(); 2127 2128 // First, we handle all conversions on ObjC object pointer types. 2129 const ObjCObjectPointerType* ToObjCPtr = 2130 ToType->getAs<ObjCObjectPointerType>(); 2131 const ObjCObjectPointerType *FromObjCPtr = 2132 FromType->getAs<ObjCObjectPointerType>(); 2133 2134 if (ToObjCPtr && FromObjCPtr) { 2135 // If the pointee types are the same (ignoring qualifications), 2136 // then this is not a pointer conversion. 2137 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2138 FromObjCPtr->getPointeeType())) 2139 return false; 2140 2141 // Check for compatible 2142 // Objective C++: We're able to convert between "id" or "Class" and a 2143 // pointer to any interface (in both directions). 2144 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2145 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2146 return true; 2147 } 2148 // Conversions with Objective-C's id<...>. 2149 if ((FromObjCPtr->isObjCQualifiedIdType() || 2150 ToObjCPtr->isObjCQualifiedIdType()) && 2151 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2152 /*compare=*/false)) { 2153 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2154 return true; 2155 } 2156 // Objective C++: We're able to convert from a pointer to an 2157 // interface to a pointer to a different interface. 2158 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2159 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2160 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2161 if (getLangOpts().CPlusPlus && LHS && RHS && 2162 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2163 FromObjCPtr->getPointeeType())) 2164 return false; 2165 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2166 ToObjCPtr->getPointeeType(), 2167 ToType, Context); 2168 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2169 return true; 2170 } 2171 2172 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2173 // Okay: this is some kind of implicit downcast of Objective-C 2174 // interfaces, which is permitted. However, we're going to 2175 // complain about it. 2176 IncompatibleObjC = true; 2177 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2178 ToObjCPtr->getPointeeType(), 2179 ToType, Context); 2180 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2181 return true; 2182 } 2183 } 2184 // Beyond this point, both types need to be C pointers or block pointers. 2185 QualType ToPointeeType; 2186 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2187 ToPointeeType = ToCPtr->getPointeeType(); 2188 else if (const BlockPointerType *ToBlockPtr = 2189 ToType->getAs<BlockPointerType>()) { 2190 // Objective C++: We're able to convert from a pointer to any object 2191 // to a block pointer type. 2192 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2193 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2194 return true; 2195 } 2196 ToPointeeType = ToBlockPtr->getPointeeType(); 2197 } 2198 else if (FromType->getAs<BlockPointerType>() && 2199 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2200 // Objective C++: We're able to convert from a block pointer type to a 2201 // pointer to any object. 2202 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2203 return true; 2204 } 2205 else 2206 return false; 2207 2208 QualType FromPointeeType; 2209 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2210 FromPointeeType = FromCPtr->getPointeeType(); 2211 else if (const BlockPointerType *FromBlockPtr = 2212 FromType->getAs<BlockPointerType>()) 2213 FromPointeeType = FromBlockPtr->getPointeeType(); 2214 else 2215 return false; 2216 2217 // If we have pointers to pointers, recursively check whether this 2218 // is an Objective-C conversion. 2219 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2220 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2221 IncompatibleObjC)) { 2222 // We always complain about this conversion. 2223 IncompatibleObjC = true; 2224 ConvertedType = Context.getPointerType(ConvertedType); 2225 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2226 return true; 2227 } 2228 // Allow conversion of pointee being objective-c pointer to another one; 2229 // as in I* to id. 2230 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2231 ToPointeeType->getAs<ObjCObjectPointerType>() && 2232 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2233 IncompatibleObjC)) { 2234 2235 ConvertedType = Context.getPointerType(ConvertedType); 2236 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2237 return true; 2238 } 2239 2240 // If we have pointers to functions or blocks, check whether the only 2241 // differences in the argument and result types are in Objective-C 2242 // pointer conversions. If so, we permit the conversion (but 2243 // complain about it). 2244 const FunctionProtoType *FromFunctionType 2245 = FromPointeeType->getAs<FunctionProtoType>(); 2246 const FunctionProtoType *ToFunctionType 2247 = ToPointeeType->getAs<FunctionProtoType>(); 2248 if (FromFunctionType && ToFunctionType) { 2249 // If the function types are exactly the same, this isn't an 2250 // Objective-C pointer conversion. 2251 if (Context.getCanonicalType(FromPointeeType) 2252 == Context.getCanonicalType(ToPointeeType)) 2253 return false; 2254 2255 // Perform the quick checks that will tell us whether these 2256 // function types are obviously different. 2257 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2258 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2259 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2260 return false; 2261 2262 bool HasObjCConversion = false; 2263 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2264 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2265 // Okay, the types match exactly. Nothing to do. 2266 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2267 ToFunctionType->getReturnType(), 2268 ConvertedType, IncompatibleObjC)) { 2269 // Okay, we have an Objective-C pointer conversion. 2270 HasObjCConversion = true; 2271 } else { 2272 // Function types are too different. Abort. 2273 return false; 2274 } 2275 2276 // Check argument types. 2277 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2278 ArgIdx != NumArgs; ++ArgIdx) { 2279 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2280 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2281 if (Context.getCanonicalType(FromArgType) 2282 == Context.getCanonicalType(ToArgType)) { 2283 // Okay, the types match exactly. Nothing to do. 2284 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2285 ConvertedType, IncompatibleObjC)) { 2286 // Okay, we have an Objective-C pointer conversion. 2287 HasObjCConversion = true; 2288 } else { 2289 // Argument types are too different. Abort. 2290 return false; 2291 } 2292 } 2293 2294 if (HasObjCConversion) { 2295 // We had an Objective-C conversion. Allow this pointer 2296 // conversion, but complain about it. 2297 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2298 IncompatibleObjC = true; 2299 return true; 2300 } 2301 } 2302 2303 return false; 2304 } 2305 2306 /// \brief Determine whether this is an Objective-C writeback conversion, 2307 /// used for parameter passing when performing automatic reference counting. 2308 /// 2309 /// \param FromType The type we're converting form. 2310 /// 2311 /// \param ToType The type we're converting to. 2312 /// 2313 /// \param ConvertedType The type that will be produced after applying 2314 /// this conversion. 2315 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2316 QualType &ConvertedType) { 2317 if (!getLangOpts().ObjCAutoRefCount || 2318 Context.hasSameUnqualifiedType(FromType, ToType)) 2319 return false; 2320 2321 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2322 QualType ToPointee; 2323 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2324 ToPointee = ToPointer->getPointeeType(); 2325 else 2326 return false; 2327 2328 Qualifiers ToQuals = ToPointee.getQualifiers(); 2329 if (!ToPointee->isObjCLifetimeType() || 2330 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2331 !ToQuals.withoutObjCLifetime().empty()) 2332 return false; 2333 2334 // Argument must be a pointer to __strong to __weak. 2335 QualType FromPointee; 2336 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2337 FromPointee = FromPointer->getPointeeType(); 2338 else 2339 return false; 2340 2341 Qualifiers FromQuals = FromPointee.getQualifiers(); 2342 if (!FromPointee->isObjCLifetimeType() || 2343 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2344 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2345 return false; 2346 2347 // Make sure that we have compatible qualifiers. 2348 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2349 if (!ToQuals.compatiblyIncludes(FromQuals)) 2350 return false; 2351 2352 // Remove qualifiers from the pointee type we're converting from; they 2353 // aren't used in the compatibility check belong, and we'll be adding back 2354 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2355 FromPointee = FromPointee.getUnqualifiedType(); 2356 2357 // The unqualified form of the pointee types must be compatible. 2358 ToPointee = ToPointee.getUnqualifiedType(); 2359 bool IncompatibleObjC; 2360 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2361 FromPointee = ToPointee; 2362 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2363 IncompatibleObjC)) 2364 return false; 2365 2366 /// \brief Construct the type we're converting to, which is a pointer to 2367 /// __autoreleasing pointee. 2368 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2369 ConvertedType = Context.getPointerType(FromPointee); 2370 return true; 2371 } 2372 2373 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2374 QualType& ConvertedType) { 2375 QualType ToPointeeType; 2376 if (const BlockPointerType *ToBlockPtr = 2377 ToType->getAs<BlockPointerType>()) 2378 ToPointeeType = ToBlockPtr->getPointeeType(); 2379 else 2380 return false; 2381 2382 QualType FromPointeeType; 2383 if (const BlockPointerType *FromBlockPtr = 2384 FromType->getAs<BlockPointerType>()) 2385 FromPointeeType = FromBlockPtr->getPointeeType(); 2386 else 2387 return false; 2388 // We have pointer to blocks, check whether the only 2389 // differences in the argument and result types are in Objective-C 2390 // pointer conversions. If so, we permit the conversion. 2391 2392 const FunctionProtoType *FromFunctionType 2393 = FromPointeeType->getAs<FunctionProtoType>(); 2394 const FunctionProtoType *ToFunctionType 2395 = ToPointeeType->getAs<FunctionProtoType>(); 2396 2397 if (!FromFunctionType || !ToFunctionType) 2398 return false; 2399 2400 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2401 return true; 2402 2403 // Perform the quick checks that will tell us whether these 2404 // function types are obviously different. 2405 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2406 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2407 return false; 2408 2409 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2410 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2411 if (FromEInfo != ToEInfo) 2412 return false; 2413 2414 bool IncompatibleObjC = false; 2415 if (Context.hasSameType(FromFunctionType->getReturnType(), 2416 ToFunctionType->getReturnType())) { 2417 // Okay, the types match exactly. Nothing to do. 2418 } else { 2419 QualType RHS = FromFunctionType->getReturnType(); 2420 QualType LHS = ToFunctionType->getReturnType(); 2421 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2422 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2423 LHS = LHS.getUnqualifiedType(); 2424 2425 if (Context.hasSameType(RHS,LHS)) { 2426 // OK exact match. 2427 } else if (isObjCPointerConversion(RHS, LHS, 2428 ConvertedType, IncompatibleObjC)) { 2429 if (IncompatibleObjC) 2430 return false; 2431 // Okay, we have an Objective-C pointer conversion. 2432 } 2433 else 2434 return false; 2435 } 2436 2437 // Check argument types. 2438 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2439 ArgIdx != NumArgs; ++ArgIdx) { 2440 IncompatibleObjC = false; 2441 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2442 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2443 if (Context.hasSameType(FromArgType, ToArgType)) { 2444 // Okay, the types match exactly. Nothing to do. 2445 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2446 ConvertedType, IncompatibleObjC)) { 2447 if (IncompatibleObjC) 2448 return false; 2449 // Okay, we have an Objective-C pointer conversion. 2450 } else 2451 // Argument types are too different. Abort. 2452 return false; 2453 } 2454 if (LangOpts.ObjCAutoRefCount && 2455 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2456 ToFunctionType)) 2457 return false; 2458 2459 ConvertedType = ToType; 2460 return true; 2461 } 2462 2463 enum { 2464 ft_default, 2465 ft_different_class, 2466 ft_parameter_arity, 2467 ft_parameter_mismatch, 2468 ft_return_type, 2469 ft_qualifer_mismatch 2470 }; 2471 2472 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2473 /// function types. Catches different number of parameter, mismatch in 2474 /// parameter types, and different return types. 2475 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2476 QualType FromType, QualType ToType) { 2477 // If either type is not valid, include no extra info. 2478 if (FromType.isNull() || ToType.isNull()) { 2479 PDiag << ft_default; 2480 return; 2481 } 2482 2483 // Get the function type from the pointers. 2484 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2485 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2486 *ToMember = ToType->getAs<MemberPointerType>(); 2487 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2488 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2489 << QualType(FromMember->getClass(), 0); 2490 return; 2491 } 2492 FromType = FromMember->getPointeeType(); 2493 ToType = ToMember->getPointeeType(); 2494 } 2495 2496 if (FromType->isPointerType()) 2497 FromType = FromType->getPointeeType(); 2498 if (ToType->isPointerType()) 2499 ToType = ToType->getPointeeType(); 2500 2501 // Remove references. 2502 FromType = FromType.getNonReferenceType(); 2503 ToType = ToType.getNonReferenceType(); 2504 2505 // Don't print extra info for non-specialized template functions. 2506 if (FromType->isInstantiationDependentType() && 2507 !FromType->getAs<TemplateSpecializationType>()) { 2508 PDiag << ft_default; 2509 return; 2510 } 2511 2512 // No extra info for same types. 2513 if (Context.hasSameType(FromType, ToType)) { 2514 PDiag << ft_default; 2515 return; 2516 } 2517 2518 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2519 *ToFunction = ToType->getAs<FunctionProtoType>(); 2520 2521 // Both types need to be function types. 2522 if (!FromFunction || !ToFunction) { 2523 PDiag << ft_default; 2524 return; 2525 } 2526 2527 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2528 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2529 << FromFunction->getNumParams(); 2530 return; 2531 } 2532 2533 // Handle different parameter types. 2534 unsigned ArgPos; 2535 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2536 PDiag << ft_parameter_mismatch << ArgPos + 1 2537 << ToFunction->getParamType(ArgPos) 2538 << FromFunction->getParamType(ArgPos); 2539 return; 2540 } 2541 2542 // Handle different return type. 2543 if (!Context.hasSameType(FromFunction->getReturnType(), 2544 ToFunction->getReturnType())) { 2545 PDiag << ft_return_type << ToFunction->getReturnType() 2546 << FromFunction->getReturnType(); 2547 return; 2548 } 2549 2550 unsigned FromQuals = FromFunction->getTypeQuals(), 2551 ToQuals = ToFunction->getTypeQuals(); 2552 if (FromQuals != ToQuals) { 2553 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2554 return; 2555 } 2556 2557 // Unable to find a difference, so add no extra info. 2558 PDiag << ft_default; 2559 } 2560 2561 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2562 /// for equality of their argument types. Caller has already checked that 2563 /// they have same number of arguments. If the parameters are different, 2564 /// ArgPos will have the parameter index of the first different parameter. 2565 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2566 const FunctionProtoType *NewType, 2567 unsigned *ArgPos) { 2568 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2569 N = NewType->param_type_begin(), 2570 E = OldType->param_type_end(); 2571 O && (O != E); ++O, ++N) { 2572 if (!Context.hasSameType(O->getUnqualifiedType(), 2573 N->getUnqualifiedType())) { 2574 if (ArgPos) 2575 *ArgPos = O - OldType->param_type_begin(); 2576 return false; 2577 } 2578 } 2579 return true; 2580 } 2581 2582 /// CheckPointerConversion - Check the pointer conversion from the 2583 /// expression From to the type ToType. This routine checks for 2584 /// ambiguous or inaccessible derived-to-base pointer 2585 /// conversions for which IsPointerConversion has already returned 2586 /// true. It returns true and produces a diagnostic if there was an 2587 /// error, or returns false otherwise. 2588 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2589 CastKind &Kind, 2590 CXXCastPath& BasePath, 2591 bool IgnoreBaseAccess) { 2592 QualType FromType = From->getType(); 2593 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2594 2595 Kind = CK_BitCast; 2596 2597 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2598 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2599 Expr::NPCK_ZeroExpression) { 2600 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2601 DiagRuntimeBehavior(From->getExprLoc(), From, 2602 PDiag(diag::warn_impcast_bool_to_null_pointer) 2603 << ToType << From->getSourceRange()); 2604 else if (!isUnevaluatedContext()) 2605 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2606 << ToType << From->getSourceRange(); 2607 } 2608 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2609 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2610 QualType FromPointeeType = FromPtrType->getPointeeType(), 2611 ToPointeeType = ToPtrType->getPointeeType(); 2612 2613 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2614 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2615 // We must have a derived-to-base conversion. Check an 2616 // ambiguous or inaccessible conversion. 2617 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2618 From->getExprLoc(), 2619 From->getSourceRange(), &BasePath, 2620 IgnoreBaseAccess)) 2621 return true; 2622 2623 // The conversion was successful. 2624 Kind = CK_DerivedToBase; 2625 } 2626 } 2627 } else if (const ObjCObjectPointerType *ToPtrType = 2628 ToType->getAs<ObjCObjectPointerType>()) { 2629 if (const ObjCObjectPointerType *FromPtrType = 2630 FromType->getAs<ObjCObjectPointerType>()) { 2631 // Objective-C++ conversions are always okay. 2632 // FIXME: We should have a different class of conversions for the 2633 // Objective-C++ implicit conversions. 2634 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2635 return false; 2636 } else if (FromType->isBlockPointerType()) { 2637 Kind = CK_BlockPointerToObjCPointerCast; 2638 } else { 2639 Kind = CK_CPointerToObjCPointerCast; 2640 } 2641 } else if (ToType->isBlockPointerType()) { 2642 if (!FromType->isBlockPointerType()) 2643 Kind = CK_AnyPointerToBlockPointerCast; 2644 } 2645 2646 // We shouldn't fall into this case unless it's valid for other 2647 // reasons. 2648 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2649 Kind = CK_NullToPointer; 2650 2651 return false; 2652 } 2653 2654 /// IsMemberPointerConversion - Determines whether the conversion of the 2655 /// expression From, which has the (possibly adjusted) type FromType, can be 2656 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2657 /// If so, returns true and places the converted type (that might differ from 2658 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2659 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2660 QualType ToType, 2661 bool InOverloadResolution, 2662 QualType &ConvertedType) { 2663 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2664 if (!ToTypePtr) 2665 return false; 2666 2667 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2668 if (From->isNullPointerConstant(Context, 2669 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2670 : Expr::NPC_ValueDependentIsNull)) { 2671 ConvertedType = ToType; 2672 return true; 2673 } 2674 2675 // Otherwise, both types have to be member pointers. 2676 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2677 if (!FromTypePtr) 2678 return false; 2679 2680 // A pointer to member of B can be converted to a pointer to member of D, 2681 // where D is derived from B (C++ 4.11p2). 2682 QualType FromClass(FromTypePtr->getClass(), 0); 2683 QualType ToClass(ToTypePtr->getClass(), 0); 2684 2685 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2686 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2687 IsDerivedFrom(ToClass, FromClass)) { 2688 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2689 ToClass.getTypePtr()); 2690 return true; 2691 } 2692 2693 return false; 2694 } 2695 2696 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2697 /// expression From to the type ToType. This routine checks for ambiguous or 2698 /// virtual or inaccessible base-to-derived member pointer conversions 2699 /// for which IsMemberPointerConversion has already returned true. It returns 2700 /// true and produces a diagnostic if there was an error, or returns false 2701 /// otherwise. 2702 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2703 CastKind &Kind, 2704 CXXCastPath &BasePath, 2705 bool IgnoreBaseAccess) { 2706 QualType FromType = From->getType(); 2707 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2708 if (!FromPtrType) { 2709 // This must be a null pointer to member pointer conversion 2710 assert(From->isNullPointerConstant(Context, 2711 Expr::NPC_ValueDependentIsNull) && 2712 "Expr must be null pointer constant!"); 2713 Kind = CK_NullToMemberPointer; 2714 return false; 2715 } 2716 2717 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2718 assert(ToPtrType && "No member pointer cast has a target type " 2719 "that is not a member pointer."); 2720 2721 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2722 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2723 2724 // FIXME: What about dependent types? 2725 assert(FromClass->isRecordType() && "Pointer into non-class."); 2726 assert(ToClass->isRecordType() && "Pointer into non-class."); 2727 2728 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2729 /*DetectVirtual=*/true); 2730 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2731 assert(DerivationOkay && 2732 "Should not have been called if derivation isn't OK."); 2733 (void)DerivationOkay; 2734 2735 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2736 getUnqualifiedType())) { 2737 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2738 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2739 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2740 return true; 2741 } 2742 2743 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2744 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2745 << FromClass << ToClass << QualType(VBase, 0) 2746 << From->getSourceRange(); 2747 return true; 2748 } 2749 2750 if (!IgnoreBaseAccess) 2751 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2752 Paths.front(), 2753 diag::err_downcast_from_inaccessible_base); 2754 2755 // Must be a base to derived member conversion. 2756 BuildBasePathArray(Paths, BasePath); 2757 Kind = CK_BaseToDerivedMemberPointer; 2758 return false; 2759 } 2760 2761 /// Determine whether the lifetime conversion between the two given 2762 /// qualifiers sets is nontrivial. 2763 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 2764 Qualifiers ToQuals) { 2765 // Converting anything to const __unsafe_unretained is trivial. 2766 if (ToQuals.hasConst() && 2767 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 2768 return false; 2769 2770 return true; 2771 } 2772 2773 /// IsQualificationConversion - Determines whether the conversion from 2774 /// an rvalue of type FromType to ToType is a qualification conversion 2775 /// (C++ 4.4). 2776 /// 2777 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2778 /// when the qualification conversion involves a change in the Objective-C 2779 /// object lifetime. 2780 bool 2781 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2782 bool CStyle, bool &ObjCLifetimeConversion) { 2783 FromType = Context.getCanonicalType(FromType); 2784 ToType = Context.getCanonicalType(ToType); 2785 ObjCLifetimeConversion = false; 2786 2787 // If FromType and ToType are the same type, this is not a 2788 // qualification conversion. 2789 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2790 return false; 2791 2792 // (C++ 4.4p4): 2793 // A conversion can add cv-qualifiers at levels other than the first 2794 // in multi-level pointers, subject to the following rules: [...] 2795 bool PreviousToQualsIncludeConst = true; 2796 bool UnwrappedAnyPointer = false; 2797 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2798 // Within each iteration of the loop, we check the qualifiers to 2799 // determine if this still looks like a qualification 2800 // conversion. Then, if all is well, we unwrap one more level of 2801 // pointers or pointers-to-members and do it all again 2802 // until there are no more pointers or pointers-to-members left to 2803 // unwrap. 2804 UnwrappedAnyPointer = true; 2805 2806 Qualifiers FromQuals = FromType.getQualifiers(); 2807 Qualifiers ToQuals = ToType.getQualifiers(); 2808 2809 // Objective-C ARC: 2810 // Check Objective-C lifetime conversions. 2811 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2812 UnwrappedAnyPointer) { 2813 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2814 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 2815 ObjCLifetimeConversion = true; 2816 FromQuals.removeObjCLifetime(); 2817 ToQuals.removeObjCLifetime(); 2818 } else { 2819 // Qualification conversions cannot cast between different 2820 // Objective-C lifetime qualifiers. 2821 return false; 2822 } 2823 } 2824 2825 // Allow addition/removal of GC attributes but not changing GC attributes. 2826 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2827 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2828 FromQuals.removeObjCGCAttr(); 2829 ToQuals.removeObjCGCAttr(); 2830 } 2831 2832 // -- for every j > 0, if const is in cv 1,j then const is in cv 2833 // 2,j, and similarly for volatile. 2834 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2835 return false; 2836 2837 // -- if the cv 1,j and cv 2,j are different, then const is in 2838 // every cv for 0 < k < j. 2839 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2840 && !PreviousToQualsIncludeConst) 2841 return false; 2842 2843 // Keep track of whether all prior cv-qualifiers in the "to" type 2844 // include const. 2845 PreviousToQualsIncludeConst 2846 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2847 } 2848 2849 // We are left with FromType and ToType being the pointee types 2850 // after unwrapping the original FromType and ToType the same number 2851 // of types. If we unwrapped any pointers, and if FromType and 2852 // ToType have the same unqualified type (since we checked 2853 // qualifiers above), then this is a qualification conversion. 2854 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2855 } 2856 2857 /// \brief - Determine whether this is a conversion from a scalar type to an 2858 /// atomic type. 2859 /// 2860 /// If successful, updates \c SCS's second and third steps in the conversion 2861 /// sequence to finish the conversion. 2862 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2863 bool InOverloadResolution, 2864 StandardConversionSequence &SCS, 2865 bool CStyle) { 2866 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2867 if (!ToAtomic) 2868 return false; 2869 2870 StandardConversionSequence InnerSCS; 2871 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2872 InOverloadResolution, InnerSCS, 2873 CStyle, /*AllowObjCWritebackConversion=*/false)) 2874 return false; 2875 2876 SCS.Second = InnerSCS.Second; 2877 SCS.setToType(1, InnerSCS.getToType(1)); 2878 SCS.Third = InnerSCS.Third; 2879 SCS.QualificationIncludesObjCLifetime 2880 = InnerSCS.QualificationIncludesObjCLifetime; 2881 SCS.setToType(2, InnerSCS.getToType(2)); 2882 return true; 2883 } 2884 2885 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2886 CXXConstructorDecl *Constructor, 2887 QualType Type) { 2888 const FunctionProtoType *CtorType = 2889 Constructor->getType()->getAs<FunctionProtoType>(); 2890 if (CtorType->getNumParams() > 0) { 2891 QualType FirstArg = CtorType->getParamType(0); 2892 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2893 return true; 2894 } 2895 return false; 2896 } 2897 2898 static OverloadingResult 2899 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2900 CXXRecordDecl *To, 2901 UserDefinedConversionSequence &User, 2902 OverloadCandidateSet &CandidateSet, 2903 bool AllowExplicit) { 2904 DeclContext::lookup_result R = S.LookupConstructors(To); 2905 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 2906 Con != ConEnd; ++Con) { 2907 NamedDecl *D = *Con; 2908 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2909 2910 // Find the constructor (which may be a template). 2911 CXXConstructorDecl *Constructor = nullptr; 2912 FunctionTemplateDecl *ConstructorTmpl 2913 = dyn_cast<FunctionTemplateDecl>(D); 2914 if (ConstructorTmpl) 2915 Constructor 2916 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2917 else 2918 Constructor = cast<CXXConstructorDecl>(D); 2919 2920 bool Usable = !Constructor->isInvalidDecl() && 2921 S.isInitListConstructor(Constructor) && 2922 (AllowExplicit || !Constructor->isExplicit()); 2923 if (Usable) { 2924 // If the first argument is (a reference to) the target type, 2925 // suppress conversions. 2926 bool SuppressUserConversions = 2927 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2928 if (ConstructorTmpl) 2929 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2930 /*ExplicitArgs*/ nullptr, 2931 From, CandidateSet, 2932 SuppressUserConversions); 2933 else 2934 S.AddOverloadCandidate(Constructor, FoundDecl, 2935 From, CandidateSet, 2936 SuppressUserConversions); 2937 } 2938 } 2939 2940 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2941 2942 OverloadCandidateSet::iterator Best; 2943 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2944 case OR_Success: { 2945 // Record the standard conversion we used and the conversion function. 2946 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2947 QualType ThisType = Constructor->getThisType(S.Context); 2948 // Initializer lists don't have conversions as such. 2949 User.Before.setAsIdentityConversion(); 2950 User.HadMultipleCandidates = HadMultipleCandidates; 2951 User.ConversionFunction = Constructor; 2952 User.FoundConversionFunction = Best->FoundDecl; 2953 User.After.setAsIdentityConversion(); 2954 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2955 User.After.setAllToTypes(ToType); 2956 return OR_Success; 2957 } 2958 2959 case OR_No_Viable_Function: 2960 return OR_No_Viable_Function; 2961 case OR_Deleted: 2962 return OR_Deleted; 2963 case OR_Ambiguous: 2964 return OR_Ambiguous; 2965 } 2966 2967 llvm_unreachable("Invalid OverloadResult!"); 2968 } 2969 2970 /// Determines whether there is a user-defined conversion sequence 2971 /// (C++ [over.ics.user]) that converts expression From to the type 2972 /// ToType. If such a conversion exists, User will contain the 2973 /// user-defined conversion sequence that performs such a conversion 2974 /// and this routine will return true. Otherwise, this routine returns 2975 /// false and User is unspecified. 2976 /// 2977 /// \param AllowExplicit true if the conversion should consider C++0x 2978 /// "explicit" conversion functions as well as non-explicit conversion 2979 /// functions (C++0x [class.conv.fct]p2). 2980 /// 2981 /// \param AllowObjCConversionOnExplicit true if the conversion should 2982 /// allow an extra Objective-C pointer conversion on uses of explicit 2983 /// constructors. Requires \c AllowExplicit to also be set. 2984 static OverloadingResult 2985 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 2986 UserDefinedConversionSequence &User, 2987 OverloadCandidateSet &CandidateSet, 2988 bool AllowExplicit, 2989 bool AllowObjCConversionOnExplicit) { 2990 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 2991 2992 // Whether we will only visit constructors. 2993 bool ConstructorsOnly = false; 2994 2995 // If the type we are conversion to is a class type, enumerate its 2996 // constructors. 2997 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 2998 // C++ [over.match.ctor]p1: 2999 // When objects of class type are direct-initialized (8.5), or 3000 // copy-initialized from an expression of the same or a 3001 // derived class type (8.5), overload resolution selects the 3002 // constructor. [...] For copy-initialization, the candidate 3003 // functions are all the converting constructors (12.3.1) of 3004 // that class. The argument list is the expression-list within 3005 // the parentheses of the initializer. 3006 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3007 (From->getType()->getAs<RecordType>() && 3008 S.IsDerivedFrom(From->getType(), ToType))) 3009 ConstructorsOnly = true; 3010 3011 S.RequireCompleteType(From->getExprLoc(), ToType, 0); 3012 // RequireCompleteType may have returned true due to some invalid decl 3013 // during template instantiation, but ToType may be complete enough now 3014 // to try to recover. 3015 if (ToType->isIncompleteType()) { 3016 // We're not going to find any constructors. 3017 } else if (CXXRecordDecl *ToRecordDecl 3018 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3019 3020 Expr **Args = &From; 3021 unsigned NumArgs = 1; 3022 bool ListInitializing = false; 3023 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3024 // But first, see if there is an init-list-constructor that will work. 3025 OverloadingResult Result = IsInitializerListConstructorConversion( 3026 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3027 if (Result != OR_No_Viable_Function) 3028 return Result; 3029 // Never mind. 3030 CandidateSet.clear(); 3031 3032 // If we're list-initializing, we pass the individual elements as 3033 // arguments, not the entire list. 3034 Args = InitList->getInits(); 3035 NumArgs = InitList->getNumInits(); 3036 ListInitializing = true; 3037 } 3038 3039 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3040 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3041 Con != ConEnd; ++Con) { 3042 NamedDecl *D = *Con; 3043 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3044 3045 // Find the constructor (which may be a template). 3046 CXXConstructorDecl *Constructor = nullptr; 3047 FunctionTemplateDecl *ConstructorTmpl 3048 = dyn_cast<FunctionTemplateDecl>(D); 3049 if (ConstructorTmpl) 3050 Constructor 3051 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3052 else 3053 Constructor = cast<CXXConstructorDecl>(D); 3054 3055 bool Usable = !Constructor->isInvalidDecl(); 3056 if (ListInitializing) 3057 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3058 else 3059 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3060 if (Usable) { 3061 bool SuppressUserConversions = !ConstructorsOnly; 3062 if (SuppressUserConversions && ListInitializing) { 3063 SuppressUserConversions = false; 3064 if (NumArgs == 1) { 3065 // If the first argument is (a reference to) the target type, 3066 // suppress conversions. 3067 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3068 S.Context, Constructor, ToType); 3069 } 3070 } 3071 if (ConstructorTmpl) 3072 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3073 /*ExplicitArgs*/ nullptr, 3074 llvm::makeArrayRef(Args, NumArgs), 3075 CandidateSet, SuppressUserConversions); 3076 else 3077 // Allow one user-defined conversion when user specifies a 3078 // From->ToType conversion via an static cast (c-style, etc). 3079 S.AddOverloadCandidate(Constructor, FoundDecl, 3080 llvm::makeArrayRef(Args, NumArgs), 3081 CandidateSet, SuppressUserConversions); 3082 } 3083 } 3084 } 3085 } 3086 3087 // Enumerate conversion functions, if we're allowed to. 3088 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3089 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3090 // No conversion functions from incomplete types. 3091 } else if (const RecordType *FromRecordType 3092 = From->getType()->getAs<RecordType>()) { 3093 if (CXXRecordDecl *FromRecordDecl 3094 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3095 // Add all of the conversion functions as candidates. 3096 std::pair<CXXRecordDecl::conversion_iterator, 3097 CXXRecordDecl::conversion_iterator> 3098 Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3099 for (CXXRecordDecl::conversion_iterator 3100 I = Conversions.first, E = Conversions.second; I != E; ++I) { 3101 DeclAccessPair FoundDecl = I.getPair(); 3102 NamedDecl *D = FoundDecl.getDecl(); 3103 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3104 if (isa<UsingShadowDecl>(D)) 3105 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3106 3107 CXXConversionDecl *Conv; 3108 FunctionTemplateDecl *ConvTemplate; 3109 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3110 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3111 else 3112 Conv = cast<CXXConversionDecl>(D); 3113 3114 if (AllowExplicit || !Conv->isExplicit()) { 3115 if (ConvTemplate) 3116 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3117 ActingContext, From, ToType, 3118 CandidateSet, 3119 AllowObjCConversionOnExplicit); 3120 else 3121 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3122 From, ToType, CandidateSet, 3123 AllowObjCConversionOnExplicit); 3124 } 3125 } 3126 } 3127 } 3128 3129 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3130 3131 OverloadCandidateSet::iterator Best; 3132 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3133 case OR_Success: 3134 // Record the standard conversion we used and the conversion function. 3135 if (CXXConstructorDecl *Constructor 3136 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3137 // C++ [over.ics.user]p1: 3138 // If the user-defined conversion is specified by a 3139 // constructor (12.3.1), the initial standard conversion 3140 // sequence converts the source type to the type required by 3141 // the argument of the constructor. 3142 // 3143 QualType ThisType = Constructor->getThisType(S.Context); 3144 if (isa<InitListExpr>(From)) { 3145 // Initializer lists don't have conversions as such. 3146 User.Before.setAsIdentityConversion(); 3147 } else { 3148 if (Best->Conversions[0].isEllipsis()) 3149 User.EllipsisConversion = true; 3150 else { 3151 User.Before = Best->Conversions[0].Standard; 3152 User.EllipsisConversion = false; 3153 } 3154 } 3155 User.HadMultipleCandidates = HadMultipleCandidates; 3156 User.ConversionFunction = Constructor; 3157 User.FoundConversionFunction = Best->FoundDecl; 3158 User.After.setAsIdentityConversion(); 3159 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3160 User.After.setAllToTypes(ToType); 3161 return OR_Success; 3162 } 3163 if (CXXConversionDecl *Conversion 3164 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3165 // C++ [over.ics.user]p1: 3166 // 3167 // [...] If the user-defined conversion is specified by a 3168 // conversion function (12.3.2), the initial standard 3169 // conversion sequence converts the source type to the 3170 // implicit object parameter of the conversion function. 3171 User.Before = Best->Conversions[0].Standard; 3172 User.HadMultipleCandidates = HadMultipleCandidates; 3173 User.ConversionFunction = Conversion; 3174 User.FoundConversionFunction = Best->FoundDecl; 3175 User.EllipsisConversion = false; 3176 3177 // C++ [over.ics.user]p2: 3178 // The second standard conversion sequence converts the 3179 // result of the user-defined conversion to the target type 3180 // for the sequence. Since an implicit conversion sequence 3181 // is an initialization, the special rules for 3182 // initialization by user-defined conversion apply when 3183 // selecting the best user-defined conversion for a 3184 // user-defined conversion sequence (see 13.3.3 and 3185 // 13.3.3.1). 3186 User.After = Best->FinalConversion; 3187 return OR_Success; 3188 } 3189 llvm_unreachable("Not a constructor or conversion function?"); 3190 3191 case OR_No_Viable_Function: 3192 return OR_No_Viable_Function; 3193 case OR_Deleted: 3194 // No conversion here! We're done. 3195 return OR_Deleted; 3196 3197 case OR_Ambiguous: 3198 return OR_Ambiguous; 3199 } 3200 3201 llvm_unreachable("Invalid OverloadResult!"); 3202 } 3203 3204 bool 3205 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3206 ImplicitConversionSequence ICS; 3207 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3208 OverloadCandidateSet::CSK_Normal); 3209 OverloadingResult OvResult = 3210 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3211 CandidateSet, false, false); 3212 if (OvResult == OR_Ambiguous) 3213 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3214 << From->getType() << ToType << From->getSourceRange(); 3215 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3216 if (!RequireCompleteType(From->getLocStart(), ToType, 3217 diag::err_typecheck_nonviable_condition_incomplete, 3218 From->getType(), From->getSourceRange())) 3219 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3220 << From->getType() << From->getSourceRange() << ToType; 3221 } else 3222 return false; 3223 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3224 return true; 3225 } 3226 3227 /// \brief Compare the user-defined conversion functions or constructors 3228 /// of two user-defined conversion sequences to determine whether any ordering 3229 /// is possible. 3230 static ImplicitConversionSequence::CompareKind 3231 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3232 FunctionDecl *Function2) { 3233 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3234 return ImplicitConversionSequence::Indistinguishable; 3235 3236 // Objective-C++: 3237 // If both conversion functions are implicitly-declared conversions from 3238 // a lambda closure type to a function pointer and a block pointer, 3239 // respectively, always prefer the conversion to a function pointer, 3240 // because the function pointer is more lightweight and is more likely 3241 // to keep code working. 3242 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3243 if (!Conv1) 3244 return ImplicitConversionSequence::Indistinguishable; 3245 3246 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3247 if (!Conv2) 3248 return ImplicitConversionSequence::Indistinguishable; 3249 3250 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3251 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3252 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3253 if (Block1 != Block2) 3254 return Block1 ? ImplicitConversionSequence::Worse 3255 : ImplicitConversionSequence::Better; 3256 } 3257 3258 return ImplicitConversionSequence::Indistinguishable; 3259 } 3260 3261 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3262 const ImplicitConversionSequence &ICS) { 3263 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3264 (ICS.isUserDefined() && 3265 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3266 } 3267 3268 /// CompareImplicitConversionSequences - Compare two implicit 3269 /// conversion sequences to determine whether one is better than the 3270 /// other or if they are indistinguishable (C++ 13.3.3.2). 3271 static ImplicitConversionSequence::CompareKind 3272 CompareImplicitConversionSequences(Sema &S, 3273 const ImplicitConversionSequence& ICS1, 3274 const ImplicitConversionSequence& ICS2) 3275 { 3276 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3277 // conversion sequences (as defined in 13.3.3.1) 3278 // -- a standard conversion sequence (13.3.3.1.1) is a better 3279 // conversion sequence than a user-defined conversion sequence or 3280 // an ellipsis conversion sequence, and 3281 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3282 // conversion sequence than an ellipsis conversion sequence 3283 // (13.3.3.1.3). 3284 // 3285 // C++0x [over.best.ics]p10: 3286 // For the purpose of ranking implicit conversion sequences as 3287 // described in 13.3.3.2, the ambiguous conversion sequence is 3288 // treated as a user-defined sequence that is indistinguishable 3289 // from any other user-defined conversion sequence. 3290 3291 // String literal to 'char *' conversion has been deprecated in C++03. It has 3292 // been removed from C++11. We still accept this conversion, if it happens at 3293 // the best viable function. Otherwise, this conversion is considered worse 3294 // than ellipsis conversion. Consider this as an extension; this is not in the 3295 // standard. For example: 3296 // 3297 // int &f(...); // #1 3298 // void f(char*); // #2 3299 // void g() { int &r = f("foo"); } 3300 // 3301 // In C++03, we pick #2 as the best viable function. 3302 // In C++11, we pick #1 as the best viable function, because ellipsis 3303 // conversion is better than string-literal to char* conversion (since there 3304 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3305 // convert arguments, #2 would be the best viable function in C++11. 3306 // If the best viable function has this conversion, a warning will be issued 3307 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3308 3309 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3310 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3311 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3312 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3313 ? ImplicitConversionSequence::Worse 3314 : ImplicitConversionSequence::Better; 3315 3316 if (ICS1.getKindRank() < ICS2.getKindRank()) 3317 return ImplicitConversionSequence::Better; 3318 if (ICS2.getKindRank() < ICS1.getKindRank()) 3319 return ImplicitConversionSequence::Worse; 3320 3321 // The following checks require both conversion sequences to be of 3322 // the same kind. 3323 if (ICS1.getKind() != ICS2.getKind()) 3324 return ImplicitConversionSequence::Indistinguishable; 3325 3326 ImplicitConversionSequence::CompareKind Result = 3327 ImplicitConversionSequence::Indistinguishable; 3328 3329 // Two implicit conversion sequences of the same form are 3330 // indistinguishable conversion sequences unless one of the 3331 // following rules apply: (C++ 13.3.3.2p3): 3332 if (ICS1.isStandard()) 3333 Result = CompareStandardConversionSequences(S, 3334 ICS1.Standard, ICS2.Standard); 3335 else if (ICS1.isUserDefined()) { 3336 // User-defined conversion sequence U1 is a better conversion 3337 // sequence than another user-defined conversion sequence U2 if 3338 // they contain the same user-defined conversion function or 3339 // constructor and if the second standard conversion sequence of 3340 // U1 is better than the second standard conversion sequence of 3341 // U2 (C++ 13.3.3.2p3). 3342 if (ICS1.UserDefined.ConversionFunction == 3343 ICS2.UserDefined.ConversionFunction) 3344 Result = CompareStandardConversionSequences(S, 3345 ICS1.UserDefined.After, 3346 ICS2.UserDefined.After); 3347 else 3348 Result = compareConversionFunctions(S, 3349 ICS1.UserDefined.ConversionFunction, 3350 ICS2.UserDefined.ConversionFunction); 3351 } 3352 3353 // List-initialization sequence L1 is a better conversion sequence than 3354 // list-initialization sequence L2 if L1 converts to std::initializer_list<X> 3355 // for some X and L2 does not. 3356 if (Result == ImplicitConversionSequence::Indistinguishable && 3357 !ICS1.isBad()) { 3358 if (ICS1.isStdInitializerListElement() && 3359 !ICS2.isStdInitializerListElement()) 3360 return ImplicitConversionSequence::Better; 3361 if (!ICS1.isStdInitializerListElement() && 3362 ICS2.isStdInitializerListElement()) 3363 return ImplicitConversionSequence::Worse; 3364 } 3365 3366 return Result; 3367 } 3368 3369 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3370 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3371 Qualifiers Quals; 3372 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3373 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3374 } 3375 3376 return Context.hasSameUnqualifiedType(T1, T2); 3377 } 3378 3379 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3380 // determine if one is a proper subset of the other. 3381 static ImplicitConversionSequence::CompareKind 3382 compareStandardConversionSubsets(ASTContext &Context, 3383 const StandardConversionSequence& SCS1, 3384 const StandardConversionSequence& SCS2) { 3385 ImplicitConversionSequence::CompareKind Result 3386 = ImplicitConversionSequence::Indistinguishable; 3387 3388 // the identity conversion sequence is considered to be a subsequence of 3389 // any non-identity conversion sequence 3390 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3391 return ImplicitConversionSequence::Better; 3392 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3393 return ImplicitConversionSequence::Worse; 3394 3395 if (SCS1.Second != SCS2.Second) { 3396 if (SCS1.Second == ICK_Identity) 3397 Result = ImplicitConversionSequence::Better; 3398 else if (SCS2.Second == ICK_Identity) 3399 Result = ImplicitConversionSequence::Worse; 3400 else 3401 return ImplicitConversionSequence::Indistinguishable; 3402 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3403 return ImplicitConversionSequence::Indistinguishable; 3404 3405 if (SCS1.Third == SCS2.Third) { 3406 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3407 : ImplicitConversionSequence::Indistinguishable; 3408 } 3409 3410 if (SCS1.Third == ICK_Identity) 3411 return Result == ImplicitConversionSequence::Worse 3412 ? ImplicitConversionSequence::Indistinguishable 3413 : ImplicitConversionSequence::Better; 3414 3415 if (SCS2.Third == ICK_Identity) 3416 return Result == ImplicitConversionSequence::Better 3417 ? ImplicitConversionSequence::Indistinguishable 3418 : ImplicitConversionSequence::Worse; 3419 3420 return ImplicitConversionSequence::Indistinguishable; 3421 } 3422 3423 /// \brief Determine whether one of the given reference bindings is better 3424 /// than the other based on what kind of bindings they are. 3425 static bool 3426 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3427 const StandardConversionSequence &SCS2) { 3428 // C++0x [over.ics.rank]p3b4: 3429 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3430 // implicit object parameter of a non-static member function declared 3431 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3432 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3433 // lvalue reference to a function lvalue and S2 binds an rvalue 3434 // reference*. 3435 // 3436 // FIXME: Rvalue references. We're going rogue with the above edits, 3437 // because the semantics in the current C++0x working paper (N3225 at the 3438 // time of this writing) break the standard definition of std::forward 3439 // and std::reference_wrapper when dealing with references to functions. 3440 // Proposed wording changes submitted to CWG for consideration. 3441 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3442 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3443 return false; 3444 3445 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3446 SCS2.IsLvalueReference) || 3447 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3448 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3449 } 3450 3451 /// CompareStandardConversionSequences - Compare two standard 3452 /// conversion sequences to determine whether one is better than the 3453 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3454 static ImplicitConversionSequence::CompareKind 3455 CompareStandardConversionSequences(Sema &S, 3456 const StandardConversionSequence& SCS1, 3457 const StandardConversionSequence& SCS2) 3458 { 3459 // Standard conversion sequence S1 is a better conversion sequence 3460 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3461 3462 // -- S1 is a proper subsequence of S2 (comparing the conversion 3463 // sequences in the canonical form defined by 13.3.3.1.1, 3464 // excluding any Lvalue Transformation; the identity conversion 3465 // sequence is considered to be a subsequence of any 3466 // non-identity conversion sequence) or, if not that, 3467 if (ImplicitConversionSequence::CompareKind CK 3468 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3469 return CK; 3470 3471 // -- the rank of S1 is better than the rank of S2 (by the rules 3472 // defined below), or, if not that, 3473 ImplicitConversionRank Rank1 = SCS1.getRank(); 3474 ImplicitConversionRank Rank2 = SCS2.getRank(); 3475 if (Rank1 < Rank2) 3476 return ImplicitConversionSequence::Better; 3477 else if (Rank2 < Rank1) 3478 return ImplicitConversionSequence::Worse; 3479 3480 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3481 // are indistinguishable unless one of the following rules 3482 // applies: 3483 3484 // A conversion that is not a conversion of a pointer, or 3485 // pointer to member, to bool is better than another conversion 3486 // that is such a conversion. 3487 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3488 return SCS2.isPointerConversionToBool() 3489 ? ImplicitConversionSequence::Better 3490 : ImplicitConversionSequence::Worse; 3491 3492 // C++ [over.ics.rank]p4b2: 3493 // 3494 // If class B is derived directly or indirectly from class A, 3495 // conversion of B* to A* is better than conversion of B* to 3496 // void*, and conversion of A* to void* is better than conversion 3497 // of B* to void*. 3498 bool SCS1ConvertsToVoid 3499 = SCS1.isPointerConversionToVoidPointer(S.Context); 3500 bool SCS2ConvertsToVoid 3501 = SCS2.isPointerConversionToVoidPointer(S.Context); 3502 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3503 // Exactly one of the conversion sequences is a conversion to 3504 // a void pointer; it's the worse conversion. 3505 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3506 : ImplicitConversionSequence::Worse; 3507 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3508 // Neither conversion sequence converts to a void pointer; compare 3509 // their derived-to-base conversions. 3510 if (ImplicitConversionSequence::CompareKind DerivedCK 3511 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3512 return DerivedCK; 3513 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3514 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3515 // Both conversion sequences are conversions to void 3516 // pointers. Compare the source types to determine if there's an 3517 // inheritance relationship in their sources. 3518 QualType FromType1 = SCS1.getFromType(); 3519 QualType FromType2 = SCS2.getFromType(); 3520 3521 // Adjust the types we're converting from via the array-to-pointer 3522 // conversion, if we need to. 3523 if (SCS1.First == ICK_Array_To_Pointer) 3524 FromType1 = S.Context.getArrayDecayedType(FromType1); 3525 if (SCS2.First == ICK_Array_To_Pointer) 3526 FromType2 = S.Context.getArrayDecayedType(FromType2); 3527 3528 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3529 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3530 3531 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3532 return ImplicitConversionSequence::Better; 3533 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3534 return ImplicitConversionSequence::Worse; 3535 3536 // Objective-C++: If one interface is more specific than the 3537 // other, it is the better one. 3538 const ObjCObjectPointerType* FromObjCPtr1 3539 = FromType1->getAs<ObjCObjectPointerType>(); 3540 const ObjCObjectPointerType* FromObjCPtr2 3541 = FromType2->getAs<ObjCObjectPointerType>(); 3542 if (FromObjCPtr1 && FromObjCPtr2) { 3543 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3544 FromObjCPtr2); 3545 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3546 FromObjCPtr1); 3547 if (AssignLeft != AssignRight) { 3548 return AssignLeft? ImplicitConversionSequence::Better 3549 : ImplicitConversionSequence::Worse; 3550 } 3551 } 3552 } 3553 3554 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3555 // bullet 3). 3556 if (ImplicitConversionSequence::CompareKind QualCK 3557 = CompareQualificationConversions(S, SCS1, SCS2)) 3558 return QualCK; 3559 3560 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3561 // Check for a better reference binding based on the kind of bindings. 3562 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3563 return ImplicitConversionSequence::Better; 3564 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3565 return ImplicitConversionSequence::Worse; 3566 3567 // C++ [over.ics.rank]p3b4: 3568 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3569 // which the references refer are the same type except for 3570 // top-level cv-qualifiers, and the type to which the reference 3571 // initialized by S2 refers is more cv-qualified than the type 3572 // to which the reference initialized by S1 refers. 3573 QualType T1 = SCS1.getToType(2); 3574 QualType T2 = SCS2.getToType(2); 3575 T1 = S.Context.getCanonicalType(T1); 3576 T2 = S.Context.getCanonicalType(T2); 3577 Qualifiers T1Quals, T2Quals; 3578 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3579 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3580 if (UnqualT1 == UnqualT2) { 3581 // Objective-C++ ARC: If the references refer to objects with different 3582 // lifetimes, prefer bindings that don't change lifetime. 3583 if (SCS1.ObjCLifetimeConversionBinding != 3584 SCS2.ObjCLifetimeConversionBinding) { 3585 return SCS1.ObjCLifetimeConversionBinding 3586 ? ImplicitConversionSequence::Worse 3587 : ImplicitConversionSequence::Better; 3588 } 3589 3590 // If the type is an array type, promote the element qualifiers to the 3591 // type for comparison. 3592 if (isa<ArrayType>(T1) && T1Quals) 3593 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3594 if (isa<ArrayType>(T2) && T2Quals) 3595 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3596 if (T2.isMoreQualifiedThan(T1)) 3597 return ImplicitConversionSequence::Better; 3598 else if (T1.isMoreQualifiedThan(T2)) 3599 return ImplicitConversionSequence::Worse; 3600 } 3601 } 3602 3603 // In Microsoft mode, prefer an integral conversion to a 3604 // floating-to-integral conversion if the integral conversion 3605 // is between types of the same size. 3606 // For example: 3607 // void f(float); 3608 // void f(int); 3609 // int main { 3610 // long a; 3611 // f(a); 3612 // } 3613 // Here, MSVC will call f(int) instead of generating a compile error 3614 // as clang will do in standard mode. 3615 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3616 SCS2.Second == ICK_Floating_Integral && 3617 S.Context.getTypeSize(SCS1.getFromType()) == 3618 S.Context.getTypeSize(SCS1.getToType(2))) 3619 return ImplicitConversionSequence::Better; 3620 3621 return ImplicitConversionSequence::Indistinguishable; 3622 } 3623 3624 /// CompareQualificationConversions - Compares two standard conversion 3625 /// sequences to determine whether they can be ranked based on their 3626 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3627 static ImplicitConversionSequence::CompareKind 3628 CompareQualificationConversions(Sema &S, 3629 const StandardConversionSequence& SCS1, 3630 const StandardConversionSequence& SCS2) { 3631 // C++ 13.3.3.2p3: 3632 // -- S1 and S2 differ only in their qualification conversion and 3633 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3634 // cv-qualification signature of type T1 is a proper subset of 3635 // the cv-qualification signature of type T2, and S1 is not the 3636 // deprecated string literal array-to-pointer conversion (4.2). 3637 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3638 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3639 return ImplicitConversionSequence::Indistinguishable; 3640 3641 // FIXME: the example in the standard doesn't use a qualification 3642 // conversion (!) 3643 QualType T1 = SCS1.getToType(2); 3644 QualType T2 = SCS2.getToType(2); 3645 T1 = S.Context.getCanonicalType(T1); 3646 T2 = S.Context.getCanonicalType(T2); 3647 Qualifiers T1Quals, T2Quals; 3648 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3649 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3650 3651 // If the types are the same, we won't learn anything by unwrapped 3652 // them. 3653 if (UnqualT1 == UnqualT2) 3654 return ImplicitConversionSequence::Indistinguishable; 3655 3656 // If the type is an array type, promote the element qualifiers to the type 3657 // for comparison. 3658 if (isa<ArrayType>(T1) && T1Quals) 3659 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3660 if (isa<ArrayType>(T2) && T2Quals) 3661 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3662 3663 ImplicitConversionSequence::CompareKind Result 3664 = ImplicitConversionSequence::Indistinguishable; 3665 3666 // Objective-C++ ARC: 3667 // Prefer qualification conversions not involving a change in lifetime 3668 // to qualification conversions that do not change lifetime. 3669 if (SCS1.QualificationIncludesObjCLifetime != 3670 SCS2.QualificationIncludesObjCLifetime) { 3671 Result = SCS1.QualificationIncludesObjCLifetime 3672 ? ImplicitConversionSequence::Worse 3673 : ImplicitConversionSequence::Better; 3674 } 3675 3676 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3677 // Within each iteration of the loop, we check the qualifiers to 3678 // determine if this still looks like a qualification 3679 // conversion. Then, if all is well, we unwrap one more level of 3680 // pointers or pointers-to-members and do it all again 3681 // until there are no more pointers or pointers-to-members left 3682 // to unwrap. This essentially mimics what 3683 // IsQualificationConversion does, but here we're checking for a 3684 // strict subset of qualifiers. 3685 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3686 // The qualifiers are the same, so this doesn't tell us anything 3687 // about how the sequences rank. 3688 ; 3689 else if (T2.isMoreQualifiedThan(T1)) { 3690 // T1 has fewer qualifiers, so it could be the better sequence. 3691 if (Result == ImplicitConversionSequence::Worse) 3692 // Neither has qualifiers that are a subset of the other's 3693 // qualifiers. 3694 return ImplicitConversionSequence::Indistinguishable; 3695 3696 Result = ImplicitConversionSequence::Better; 3697 } else if (T1.isMoreQualifiedThan(T2)) { 3698 // T2 has fewer qualifiers, so it could be the better sequence. 3699 if (Result == ImplicitConversionSequence::Better) 3700 // Neither has qualifiers that are a subset of the other's 3701 // qualifiers. 3702 return ImplicitConversionSequence::Indistinguishable; 3703 3704 Result = ImplicitConversionSequence::Worse; 3705 } else { 3706 // Qualifiers are disjoint. 3707 return ImplicitConversionSequence::Indistinguishable; 3708 } 3709 3710 // If the types after this point are equivalent, we're done. 3711 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3712 break; 3713 } 3714 3715 // Check that the winning standard conversion sequence isn't using 3716 // the deprecated string literal array to pointer conversion. 3717 switch (Result) { 3718 case ImplicitConversionSequence::Better: 3719 if (SCS1.DeprecatedStringLiteralToCharPtr) 3720 Result = ImplicitConversionSequence::Indistinguishable; 3721 break; 3722 3723 case ImplicitConversionSequence::Indistinguishable: 3724 break; 3725 3726 case ImplicitConversionSequence::Worse: 3727 if (SCS2.DeprecatedStringLiteralToCharPtr) 3728 Result = ImplicitConversionSequence::Indistinguishable; 3729 break; 3730 } 3731 3732 return Result; 3733 } 3734 3735 /// CompareDerivedToBaseConversions - Compares two standard conversion 3736 /// sequences to determine whether they can be ranked based on their 3737 /// various kinds of derived-to-base conversions (C++ 3738 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3739 /// conversions between Objective-C interface types. 3740 static ImplicitConversionSequence::CompareKind 3741 CompareDerivedToBaseConversions(Sema &S, 3742 const StandardConversionSequence& SCS1, 3743 const StandardConversionSequence& SCS2) { 3744 QualType FromType1 = SCS1.getFromType(); 3745 QualType ToType1 = SCS1.getToType(1); 3746 QualType FromType2 = SCS2.getFromType(); 3747 QualType ToType2 = SCS2.getToType(1); 3748 3749 // Adjust the types we're converting from via the array-to-pointer 3750 // conversion, if we need to. 3751 if (SCS1.First == ICK_Array_To_Pointer) 3752 FromType1 = S.Context.getArrayDecayedType(FromType1); 3753 if (SCS2.First == ICK_Array_To_Pointer) 3754 FromType2 = S.Context.getArrayDecayedType(FromType2); 3755 3756 // Canonicalize all of the types. 3757 FromType1 = S.Context.getCanonicalType(FromType1); 3758 ToType1 = S.Context.getCanonicalType(ToType1); 3759 FromType2 = S.Context.getCanonicalType(FromType2); 3760 ToType2 = S.Context.getCanonicalType(ToType2); 3761 3762 // C++ [over.ics.rank]p4b3: 3763 // 3764 // If class B is derived directly or indirectly from class A and 3765 // class C is derived directly or indirectly from B, 3766 // 3767 // Compare based on pointer conversions. 3768 if (SCS1.Second == ICK_Pointer_Conversion && 3769 SCS2.Second == ICK_Pointer_Conversion && 3770 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3771 FromType1->isPointerType() && FromType2->isPointerType() && 3772 ToType1->isPointerType() && ToType2->isPointerType()) { 3773 QualType FromPointee1 3774 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3775 QualType ToPointee1 3776 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3777 QualType FromPointee2 3778 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3779 QualType ToPointee2 3780 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3781 3782 // -- conversion of C* to B* is better than conversion of C* to A*, 3783 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3784 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3785 return ImplicitConversionSequence::Better; 3786 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3787 return ImplicitConversionSequence::Worse; 3788 } 3789 3790 // -- conversion of B* to A* is better than conversion of C* to A*, 3791 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3792 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3793 return ImplicitConversionSequence::Better; 3794 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3795 return ImplicitConversionSequence::Worse; 3796 } 3797 } else if (SCS1.Second == ICK_Pointer_Conversion && 3798 SCS2.Second == ICK_Pointer_Conversion) { 3799 const ObjCObjectPointerType *FromPtr1 3800 = FromType1->getAs<ObjCObjectPointerType>(); 3801 const ObjCObjectPointerType *FromPtr2 3802 = FromType2->getAs<ObjCObjectPointerType>(); 3803 const ObjCObjectPointerType *ToPtr1 3804 = ToType1->getAs<ObjCObjectPointerType>(); 3805 const ObjCObjectPointerType *ToPtr2 3806 = ToType2->getAs<ObjCObjectPointerType>(); 3807 3808 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3809 // Apply the same conversion ranking rules for Objective-C pointer types 3810 // that we do for C++ pointers to class types. However, we employ the 3811 // Objective-C pseudo-subtyping relationship used for assignment of 3812 // Objective-C pointer types. 3813 bool FromAssignLeft 3814 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3815 bool FromAssignRight 3816 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3817 bool ToAssignLeft 3818 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3819 bool ToAssignRight 3820 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3821 3822 // A conversion to an a non-id object pointer type or qualified 'id' 3823 // type is better than a conversion to 'id'. 3824 if (ToPtr1->isObjCIdType() && 3825 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3826 return ImplicitConversionSequence::Worse; 3827 if (ToPtr2->isObjCIdType() && 3828 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3829 return ImplicitConversionSequence::Better; 3830 3831 // A conversion to a non-id object pointer type is better than a 3832 // conversion to a qualified 'id' type 3833 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3834 return ImplicitConversionSequence::Worse; 3835 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3836 return ImplicitConversionSequence::Better; 3837 3838 // A conversion to an a non-Class object pointer type or qualified 'Class' 3839 // type is better than a conversion to 'Class'. 3840 if (ToPtr1->isObjCClassType() && 3841 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3842 return ImplicitConversionSequence::Worse; 3843 if (ToPtr2->isObjCClassType() && 3844 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3845 return ImplicitConversionSequence::Better; 3846 3847 // A conversion to a non-Class object pointer type is better than a 3848 // conversion to a qualified 'Class' type. 3849 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3850 return ImplicitConversionSequence::Worse; 3851 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3852 return ImplicitConversionSequence::Better; 3853 3854 // -- "conversion of C* to B* is better than conversion of C* to A*," 3855 if (S.Context.hasSameType(FromType1, FromType2) && 3856 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3857 (ToAssignLeft != ToAssignRight)) 3858 return ToAssignLeft? ImplicitConversionSequence::Worse 3859 : ImplicitConversionSequence::Better; 3860 3861 // -- "conversion of B* to A* is better than conversion of C* to A*," 3862 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3863 (FromAssignLeft != FromAssignRight)) 3864 return FromAssignLeft? ImplicitConversionSequence::Better 3865 : ImplicitConversionSequence::Worse; 3866 } 3867 } 3868 3869 // Ranking of member-pointer types. 3870 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3871 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3872 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3873 const MemberPointerType * FromMemPointer1 = 3874 FromType1->getAs<MemberPointerType>(); 3875 const MemberPointerType * ToMemPointer1 = 3876 ToType1->getAs<MemberPointerType>(); 3877 const MemberPointerType * FromMemPointer2 = 3878 FromType2->getAs<MemberPointerType>(); 3879 const MemberPointerType * ToMemPointer2 = 3880 ToType2->getAs<MemberPointerType>(); 3881 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3882 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3883 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3884 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3885 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3886 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3887 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3888 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3889 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3890 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3891 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3892 return ImplicitConversionSequence::Worse; 3893 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3894 return ImplicitConversionSequence::Better; 3895 } 3896 // conversion of B::* to C::* is better than conversion of A::* to C::* 3897 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3898 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3899 return ImplicitConversionSequence::Better; 3900 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3901 return ImplicitConversionSequence::Worse; 3902 } 3903 } 3904 3905 if (SCS1.Second == ICK_Derived_To_Base) { 3906 // -- conversion of C to B is better than conversion of C to A, 3907 // -- binding of an expression of type C to a reference of type 3908 // B& is better than binding an expression of type C to a 3909 // reference of type A&, 3910 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3911 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3912 if (S.IsDerivedFrom(ToType1, ToType2)) 3913 return ImplicitConversionSequence::Better; 3914 else if (S.IsDerivedFrom(ToType2, ToType1)) 3915 return ImplicitConversionSequence::Worse; 3916 } 3917 3918 // -- conversion of B to A is better than conversion of C to A. 3919 // -- binding of an expression of type B to a reference of type 3920 // A& is better than binding an expression of type C to a 3921 // reference of type A&, 3922 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3923 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3924 if (S.IsDerivedFrom(FromType2, FromType1)) 3925 return ImplicitConversionSequence::Better; 3926 else if (S.IsDerivedFrom(FromType1, FromType2)) 3927 return ImplicitConversionSequence::Worse; 3928 } 3929 } 3930 3931 return ImplicitConversionSequence::Indistinguishable; 3932 } 3933 3934 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 3935 /// C++ class. 3936 static bool isTypeValid(QualType T) { 3937 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 3938 return !Record->isInvalidDecl(); 3939 3940 return true; 3941 } 3942 3943 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 3944 /// determine whether they are reference-related, 3945 /// reference-compatible, reference-compatible with added 3946 /// qualification, or incompatible, for use in C++ initialization by 3947 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3948 /// type, and the first type (T1) is the pointee type of the reference 3949 /// type being initialized. 3950 Sema::ReferenceCompareResult 3951 Sema::CompareReferenceRelationship(SourceLocation Loc, 3952 QualType OrigT1, QualType OrigT2, 3953 bool &DerivedToBase, 3954 bool &ObjCConversion, 3955 bool &ObjCLifetimeConversion) { 3956 assert(!OrigT1->isReferenceType() && 3957 "T1 must be the pointee type of the reference type"); 3958 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3959 3960 QualType T1 = Context.getCanonicalType(OrigT1); 3961 QualType T2 = Context.getCanonicalType(OrigT2); 3962 Qualifiers T1Quals, T2Quals; 3963 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3964 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3965 3966 // C++ [dcl.init.ref]p4: 3967 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3968 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3969 // T1 is a base class of T2. 3970 DerivedToBase = false; 3971 ObjCConversion = false; 3972 ObjCLifetimeConversion = false; 3973 if (UnqualT1 == UnqualT2) { 3974 // Nothing to do. 3975 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 3976 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 3977 IsDerivedFrom(UnqualT2, UnqualT1)) 3978 DerivedToBase = true; 3979 else if (UnqualT1->isObjCObjectOrInterfaceType() && 3980 UnqualT2->isObjCObjectOrInterfaceType() && 3981 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 3982 ObjCConversion = true; 3983 else 3984 return Ref_Incompatible; 3985 3986 // At this point, we know that T1 and T2 are reference-related (at 3987 // least). 3988 3989 // If the type is an array type, promote the element qualifiers to the type 3990 // for comparison. 3991 if (isa<ArrayType>(T1) && T1Quals) 3992 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 3993 if (isa<ArrayType>(T2) && T2Quals) 3994 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 3995 3996 // C++ [dcl.init.ref]p4: 3997 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 3998 // reference-related to T2 and cv1 is the same cv-qualification 3999 // as, or greater cv-qualification than, cv2. For purposes of 4000 // overload resolution, cases for which cv1 is greater 4001 // cv-qualification than cv2 are identified as 4002 // reference-compatible with added qualification (see 13.3.3.2). 4003 // 4004 // Note that we also require equivalence of Objective-C GC and address-space 4005 // qualifiers when performing these computations, so that e.g., an int in 4006 // address space 1 is not reference-compatible with an int in address 4007 // space 2. 4008 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4009 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4010 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4011 ObjCLifetimeConversion = true; 4012 4013 T1Quals.removeObjCLifetime(); 4014 T2Quals.removeObjCLifetime(); 4015 } 4016 4017 if (T1Quals == T2Quals) 4018 return Ref_Compatible; 4019 else if (T1Quals.compatiblyIncludes(T2Quals)) 4020 return Ref_Compatible_With_Added_Qualification; 4021 else 4022 return Ref_Related; 4023 } 4024 4025 /// \brief Look for a user-defined conversion to an value reference-compatible 4026 /// with DeclType. Return true if something definite is found. 4027 static bool 4028 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4029 QualType DeclType, SourceLocation DeclLoc, 4030 Expr *Init, QualType T2, bool AllowRvalues, 4031 bool AllowExplicit) { 4032 assert(T2->isRecordType() && "Can only find conversions of record types."); 4033 CXXRecordDecl *T2RecordDecl 4034 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4035 4036 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4037 std::pair<CXXRecordDecl::conversion_iterator, 4038 CXXRecordDecl::conversion_iterator> 4039 Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4040 for (CXXRecordDecl::conversion_iterator 4041 I = Conversions.first, E = Conversions.second; I != E; ++I) { 4042 NamedDecl *D = *I; 4043 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4044 if (isa<UsingShadowDecl>(D)) 4045 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4046 4047 FunctionTemplateDecl *ConvTemplate 4048 = dyn_cast<FunctionTemplateDecl>(D); 4049 CXXConversionDecl *Conv; 4050 if (ConvTemplate) 4051 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4052 else 4053 Conv = cast<CXXConversionDecl>(D); 4054 4055 // If this is an explicit conversion, and we're not allowed to consider 4056 // explicit conversions, skip it. 4057 if (!AllowExplicit && Conv->isExplicit()) 4058 continue; 4059 4060 if (AllowRvalues) { 4061 bool DerivedToBase = false; 4062 bool ObjCConversion = false; 4063 bool ObjCLifetimeConversion = false; 4064 4065 // If we are initializing an rvalue reference, don't permit conversion 4066 // functions that return lvalues. 4067 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4068 const ReferenceType *RefType 4069 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4070 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4071 continue; 4072 } 4073 4074 if (!ConvTemplate && 4075 S.CompareReferenceRelationship( 4076 DeclLoc, 4077 Conv->getConversionType().getNonReferenceType() 4078 .getUnqualifiedType(), 4079 DeclType.getNonReferenceType().getUnqualifiedType(), 4080 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4081 Sema::Ref_Incompatible) 4082 continue; 4083 } else { 4084 // If the conversion function doesn't return a reference type, 4085 // it can't be considered for this conversion. An rvalue reference 4086 // is only acceptable if its referencee is a function type. 4087 4088 const ReferenceType *RefType = 4089 Conv->getConversionType()->getAs<ReferenceType>(); 4090 if (!RefType || 4091 (!RefType->isLValueReferenceType() && 4092 !RefType->getPointeeType()->isFunctionType())) 4093 continue; 4094 } 4095 4096 if (ConvTemplate) 4097 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4098 Init, DeclType, CandidateSet, 4099 /*AllowObjCConversionOnExplicit=*/false); 4100 else 4101 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4102 DeclType, CandidateSet, 4103 /*AllowObjCConversionOnExplicit=*/false); 4104 } 4105 4106 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4107 4108 OverloadCandidateSet::iterator Best; 4109 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4110 case OR_Success: 4111 // C++ [over.ics.ref]p1: 4112 // 4113 // [...] If the parameter binds directly to the result of 4114 // applying a conversion function to the argument 4115 // expression, the implicit conversion sequence is a 4116 // user-defined conversion sequence (13.3.3.1.2), with the 4117 // second standard conversion sequence either an identity 4118 // conversion or, if the conversion function returns an 4119 // entity of a type that is a derived class of the parameter 4120 // type, a derived-to-base Conversion. 4121 if (!Best->FinalConversion.DirectBinding) 4122 return false; 4123 4124 ICS.setUserDefined(); 4125 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4126 ICS.UserDefined.After = Best->FinalConversion; 4127 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4128 ICS.UserDefined.ConversionFunction = Best->Function; 4129 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4130 ICS.UserDefined.EllipsisConversion = false; 4131 assert(ICS.UserDefined.After.ReferenceBinding && 4132 ICS.UserDefined.After.DirectBinding && 4133 "Expected a direct reference binding!"); 4134 return true; 4135 4136 case OR_Ambiguous: 4137 ICS.setAmbiguous(); 4138 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4139 Cand != CandidateSet.end(); ++Cand) 4140 if (Cand->Viable) 4141 ICS.Ambiguous.addConversion(Cand->Function); 4142 return true; 4143 4144 case OR_No_Viable_Function: 4145 case OR_Deleted: 4146 // There was no suitable conversion, or we found a deleted 4147 // conversion; continue with other checks. 4148 return false; 4149 } 4150 4151 llvm_unreachable("Invalid OverloadResult!"); 4152 } 4153 4154 /// \brief Compute an implicit conversion sequence for reference 4155 /// initialization. 4156 static ImplicitConversionSequence 4157 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4158 SourceLocation DeclLoc, 4159 bool SuppressUserConversions, 4160 bool AllowExplicit) { 4161 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4162 4163 // Most paths end in a failed conversion. 4164 ImplicitConversionSequence ICS; 4165 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4166 4167 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4168 QualType T2 = Init->getType(); 4169 4170 // If the initializer is the address of an overloaded function, try 4171 // to resolve the overloaded function. If all goes well, T2 is the 4172 // type of the resulting function. 4173 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4174 DeclAccessPair Found; 4175 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4176 false, Found)) 4177 T2 = Fn->getType(); 4178 } 4179 4180 // Compute some basic properties of the types and the initializer. 4181 bool isRValRef = DeclType->isRValueReferenceType(); 4182 bool DerivedToBase = false; 4183 bool ObjCConversion = false; 4184 bool ObjCLifetimeConversion = false; 4185 Expr::Classification InitCategory = Init->Classify(S.Context); 4186 Sema::ReferenceCompareResult RefRelationship 4187 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4188 ObjCConversion, ObjCLifetimeConversion); 4189 4190 4191 // C++0x [dcl.init.ref]p5: 4192 // A reference to type "cv1 T1" is initialized by an expression 4193 // of type "cv2 T2" as follows: 4194 4195 // -- If reference is an lvalue reference and the initializer expression 4196 if (!isRValRef) { 4197 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4198 // reference-compatible with "cv2 T2," or 4199 // 4200 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4201 if (InitCategory.isLValue() && 4202 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4203 // C++ [over.ics.ref]p1: 4204 // When a parameter of reference type binds directly (8.5.3) 4205 // to an argument expression, the implicit conversion sequence 4206 // is the identity conversion, unless the argument expression 4207 // has a type that is a derived class of the parameter type, 4208 // in which case the implicit conversion sequence is a 4209 // derived-to-base Conversion (13.3.3.1). 4210 ICS.setStandard(); 4211 ICS.Standard.First = ICK_Identity; 4212 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4213 : ObjCConversion? ICK_Compatible_Conversion 4214 : ICK_Identity; 4215 ICS.Standard.Third = ICK_Identity; 4216 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4217 ICS.Standard.setToType(0, T2); 4218 ICS.Standard.setToType(1, T1); 4219 ICS.Standard.setToType(2, T1); 4220 ICS.Standard.ReferenceBinding = true; 4221 ICS.Standard.DirectBinding = true; 4222 ICS.Standard.IsLvalueReference = !isRValRef; 4223 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4224 ICS.Standard.BindsToRvalue = false; 4225 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4226 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4227 ICS.Standard.CopyConstructor = nullptr; 4228 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4229 4230 // Nothing more to do: the inaccessibility/ambiguity check for 4231 // derived-to-base conversions is suppressed when we're 4232 // computing the implicit conversion sequence (C++ 4233 // [over.best.ics]p2). 4234 return ICS; 4235 } 4236 4237 // -- has a class type (i.e., T2 is a class type), where T1 is 4238 // not reference-related to T2, and can be implicitly 4239 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4240 // is reference-compatible with "cv3 T3" 92) (this 4241 // conversion is selected by enumerating the applicable 4242 // conversion functions (13.3.1.6) and choosing the best 4243 // one through overload resolution (13.3)), 4244 if (!SuppressUserConversions && T2->isRecordType() && 4245 !S.RequireCompleteType(DeclLoc, T2, 0) && 4246 RefRelationship == Sema::Ref_Incompatible) { 4247 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4248 Init, T2, /*AllowRvalues=*/false, 4249 AllowExplicit)) 4250 return ICS; 4251 } 4252 } 4253 4254 // -- Otherwise, the reference shall be an lvalue reference to a 4255 // non-volatile const type (i.e., cv1 shall be const), or the reference 4256 // shall be an rvalue reference. 4257 // 4258 // We actually handle one oddity of C++ [over.ics.ref] at this 4259 // point, which is that, due to p2 (which short-circuits reference 4260 // binding by only attempting a simple conversion for non-direct 4261 // bindings) and p3's strange wording, we allow a const volatile 4262 // reference to bind to an rvalue. Hence the check for the presence 4263 // of "const" rather than checking for "const" being the only 4264 // qualifier. 4265 // This is also the point where rvalue references and lvalue inits no longer 4266 // go together. 4267 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4268 return ICS; 4269 4270 // -- If the initializer expression 4271 // 4272 // -- is an xvalue, class prvalue, array prvalue or function 4273 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4274 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4275 (InitCategory.isXValue() || 4276 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4277 (InitCategory.isLValue() && T2->isFunctionType()))) { 4278 ICS.setStandard(); 4279 ICS.Standard.First = ICK_Identity; 4280 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4281 : ObjCConversion? ICK_Compatible_Conversion 4282 : ICK_Identity; 4283 ICS.Standard.Third = ICK_Identity; 4284 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4285 ICS.Standard.setToType(0, T2); 4286 ICS.Standard.setToType(1, T1); 4287 ICS.Standard.setToType(2, T1); 4288 ICS.Standard.ReferenceBinding = true; 4289 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4290 // binding unless we're binding to a class prvalue. 4291 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4292 // allow the use of rvalue references in C++98/03 for the benefit of 4293 // standard library implementors; therefore, we need the xvalue check here. 4294 ICS.Standard.DirectBinding = 4295 S.getLangOpts().CPlusPlus11 || 4296 !(InitCategory.isPRValue() || T2->isRecordType()); 4297 ICS.Standard.IsLvalueReference = !isRValRef; 4298 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4299 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4300 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4301 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4302 ICS.Standard.CopyConstructor = nullptr; 4303 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4304 return ICS; 4305 } 4306 4307 // -- has a class type (i.e., T2 is a class type), where T1 is not 4308 // reference-related to T2, and can be implicitly converted to 4309 // an xvalue, class prvalue, or function lvalue of type 4310 // "cv3 T3", where "cv1 T1" is reference-compatible with 4311 // "cv3 T3", 4312 // 4313 // then the reference is bound to the value of the initializer 4314 // expression in the first case and to the result of the conversion 4315 // in the second case (or, in either case, to an appropriate base 4316 // class subobject). 4317 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4318 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4319 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4320 Init, T2, /*AllowRvalues=*/true, 4321 AllowExplicit)) { 4322 // In the second case, if the reference is an rvalue reference 4323 // and the second standard conversion sequence of the 4324 // user-defined conversion sequence includes an lvalue-to-rvalue 4325 // conversion, the program is ill-formed. 4326 if (ICS.isUserDefined() && isRValRef && 4327 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4328 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4329 4330 return ICS; 4331 } 4332 4333 // A temporary of function type cannot be created; don't even try. 4334 if (T1->isFunctionType()) 4335 return ICS; 4336 4337 // -- Otherwise, a temporary of type "cv1 T1" is created and 4338 // initialized from the initializer expression using the 4339 // rules for a non-reference copy initialization (8.5). The 4340 // reference is then bound to the temporary. If T1 is 4341 // reference-related to T2, cv1 must be the same 4342 // cv-qualification as, or greater cv-qualification than, 4343 // cv2; otherwise, the program is ill-formed. 4344 if (RefRelationship == Sema::Ref_Related) { 4345 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4346 // we would be reference-compatible or reference-compatible with 4347 // added qualification. But that wasn't the case, so the reference 4348 // initialization fails. 4349 // 4350 // Note that we only want to check address spaces and cvr-qualifiers here. 4351 // ObjC GC and lifetime qualifiers aren't important. 4352 Qualifiers T1Quals = T1.getQualifiers(); 4353 Qualifiers T2Quals = T2.getQualifiers(); 4354 T1Quals.removeObjCGCAttr(); 4355 T1Quals.removeObjCLifetime(); 4356 T2Quals.removeObjCGCAttr(); 4357 T2Quals.removeObjCLifetime(); 4358 if (!T1Quals.compatiblyIncludes(T2Quals)) 4359 return ICS; 4360 } 4361 4362 // If at least one of the types is a class type, the types are not 4363 // related, and we aren't allowed any user conversions, the 4364 // reference binding fails. This case is important for breaking 4365 // recursion, since TryImplicitConversion below will attempt to 4366 // create a temporary through the use of a copy constructor. 4367 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4368 (T1->isRecordType() || T2->isRecordType())) 4369 return ICS; 4370 4371 // If T1 is reference-related to T2 and the reference is an rvalue 4372 // reference, the initializer expression shall not be an lvalue. 4373 if (RefRelationship >= Sema::Ref_Related && 4374 isRValRef && Init->Classify(S.Context).isLValue()) 4375 return ICS; 4376 4377 // C++ [over.ics.ref]p2: 4378 // When a parameter of reference type is not bound directly to 4379 // an argument expression, the conversion sequence is the one 4380 // required to convert the argument expression to the 4381 // underlying type of the reference according to 4382 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4383 // to copy-initializing a temporary of the underlying type with 4384 // the argument expression. Any difference in top-level 4385 // cv-qualification is subsumed by the initialization itself 4386 // and does not constitute a conversion. 4387 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4388 /*AllowExplicit=*/false, 4389 /*InOverloadResolution=*/false, 4390 /*CStyle=*/false, 4391 /*AllowObjCWritebackConversion=*/false, 4392 /*AllowObjCConversionOnExplicit=*/false); 4393 4394 // Of course, that's still a reference binding. 4395 if (ICS.isStandard()) { 4396 ICS.Standard.ReferenceBinding = true; 4397 ICS.Standard.IsLvalueReference = !isRValRef; 4398 ICS.Standard.BindsToFunctionLvalue = false; 4399 ICS.Standard.BindsToRvalue = true; 4400 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4401 ICS.Standard.ObjCLifetimeConversionBinding = false; 4402 } else if (ICS.isUserDefined()) { 4403 const ReferenceType *LValRefType = 4404 ICS.UserDefined.ConversionFunction->getReturnType() 4405 ->getAs<LValueReferenceType>(); 4406 4407 // C++ [over.ics.ref]p3: 4408 // Except for an implicit object parameter, for which see 13.3.1, a 4409 // standard conversion sequence cannot be formed if it requires [...] 4410 // binding an rvalue reference to an lvalue other than a function 4411 // lvalue. 4412 // Note that the function case is not possible here. 4413 if (DeclType->isRValueReferenceType() && LValRefType) { 4414 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4415 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4416 // reference to an rvalue! 4417 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4418 return ICS; 4419 } 4420 4421 ICS.UserDefined.Before.setAsIdentityConversion(); 4422 ICS.UserDefined.After.ReferenceBinding = true; 4423 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4424 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4425 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4426 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4427 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4428 } 4429 4430 return ICS; 4431 } 4432 4433 static ImplicitConversionSequence 4434 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4435 bool SuppressUserConversions, 4436 bool InOverloadResolution, 4437 bool AllowObjCWritebackConversion, 4438 bool AllowExplicit = false); 4439 4440 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4441 /// initializer list From. 4442 static ImplicitConversionSequence 4443 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4444 bool SuppressUserConversions, 4445 bool InOverloadResolution, 4446 bool AllowObjCWritebackConversion) { 4447 // C++11 [over.ics.list]p1: 4448 // When an argument is an initializer list, it is not an expression and 4449 // special rules apply for converting it to a parameter type. 4450 4451 ImplicitConversionSequence Result; 4452 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4453 4454 // We need a complete type for what follows. Incomplete types can never be 4455 // initialized from init lists. 4456 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4457 return Result; 4458 4459 // C++11 [over.ics.list]p2: 4460 // If the parameter type is std::initializer_list<X> or "array of X" and 4461 // all the elements can be implicitly converted to X, the implicit 4462 // conversion sequence is the worst conversion necessary to convert an 4463 // element of the list to X. 4464 bool toStdInitializerList = false; 4465 QualType X; 4466 if (ToType->isArrayType()) 4467 X = S.Context.getAsArrayType(ToType)->getElementType(); 4468 else 4469 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4470 if (!X.isNull()) { 4471 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4472 Expr *Init = From->getInit(i); 4473 ImplicitConversionSequence ICS = 4474 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4475 InOverloadResolution, 4476 AllowObjCWritebackConversion); 4477 // If a single element isn't convertible, fail. 4478 if (ICS.isBad()) { 4479 Result = ICS; 4480 break; 4481 } 4482 // Otherwise, look for the worst conversion. 4483 if (Result.isBad() || 4484 CompareImplicitConversionSequences(S, ICS, Result) == 4485 ImplicitConversionSequence::Worse) 4486 Result = ICS; 4487 } 4488 4489 // For an empty list, we won't have computed any conversion sequence. 4490 // Introduce the identity conversion sequence. 4491 if (From->getNumInits() == 0) { 4492 Result.setStandard(); 4493 Result.Standard.setAsIdentityConversion(); 4494 Result.Standard.setFromType(ToType); 4495 Result.Standard.setAllToTypes(ToType); 4496 } 4497 4498 Result.setStdInitializerListElement(toStdInitializerList); 4499 return Result; 4500 } 4501 4502 // C++11 [over.ics.list]p3: 4503 // Otherwise, if the parameter is a non-aggregate class X and overload 4504 // resolution chooses a single best constructor [...] the implicit 4505 // conversion sequence is a user-defined conversion sequence. If multiple 4506 // constructors are viable but none is better than the others, the 4507 // implicit conversion sequence is a user-defined conversion sequence. 4508 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4509 // This function can deal with initializer lists. 4510 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4511 /*AllowExplicit=*/false, 4512 InOverloadResolution, /*CStyle=*/false, 4513 AllowObjCWritebackConversion, 4514 /*AllowObjCConversionOnExplicit=*/false); 4515 } 4516 4517 // C++11 [over.ics.list]p4: 4518 // Otherwise, if the parameter has an aggregate type which can be 4519 // initialized from the initializer list [...] the implicit conversion 4520 // sequence is a user-defined conversion sequence. 4521 if (ToType->isAggregateType()) { 4522 // Type is an aggregate, argument is an init list. At this point it comes 4523 // down to checking whether the initialization works. 4524 // FIXME: Find out whether this parameter is consumed or not. 4525 InitializedEntity Entity = 4526 InitializedEntity::InitializeParameter(S.Context, ToType, 4527 /*Consumed=*/false); 4528 if (S.CanPerformCopyInitialization(Entity, From)) { 4529 Result.setUserDefined(); 4530 Result.UserDefined.Before.setAsIdentityConversion(); 4531 // Initializer lists don't have a type. 4532 Result.UserDefined.Before.setFromType(QualType()); 4533 Result.UserDefined.Before.setAllToTypes(QualType()); 4534 4535 Result.UserDefined.After.setAsIdentityConversion(); 4536 Result.UserDefined.After.setFromType(ToType); 4537 Result.UserDefined.After.setAllToTypes(ToType); 4538 Result.UserDefined.ConversionFunction = nullptr; 4539 } 4540 return Result; 4541 } 4542 4543 // C++11 [over.ics.list]p5: 4544 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4545 if (ToType->isReferenceType()) { 4546 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4547 // mention initializer lists in any way. So we go by what list- 4548 // initialization would do and try to extrapolate from that. 4549 4550 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4551 4552 // If the initializer list has a single element that is reference-related 4553 // to the parameter type, we initialize the reference from that. 4554 if (From->getNumInits() == 1) { 4555 Expr *Init = From->getInit(0); 4556 4557 QualType T2 = Init->getType(); 4558 4559 // If the initializer is the address of an overloaded function, try 4560 // to resolve the overloaded function. If all goes well, T2 is the 4561 // type of the resulting function. 4562 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4563 DeclAccessPair Found; 4564 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4565 Init, ToType, false, Found)) 4566 T2 = Fn->getType(); 4567 } 4568 4569 // Compute some basic properties of the types and the initializer. 4570 bool dummy1 = false; 4571 bool dummy2 = false; 4572 bool dummy3 = false; 4573 Sema::ReferenceCompareResult RefRelationship 4574 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4575 dummy2, dummy3); 4576 4577 if (RefRelationship >= Sema::Ref_Related) { 4578 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4579 SuppressUserConversions, 4580 /*AllowExplicit=*/false); 4581 } 4582 } 4583 4584 // Otherwise, we bind the reference to a temporary created from the 4585 // initializer list. 4586 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4587 InOverloadResolution, 4588 AllowObjCWritebackConversion); 4589 if (Result.isFailure()) 4590 return Result; 4591 assert(!Result.isEllipsis() && 4592 "Sub-initialization cannot result in ellipsis conversion."); 4593 4594 // Can we even bind to a temporary? 4595 if (ToType->isRValueReferenceType() || 4596 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4597 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4598 Result.UserDefined.After; 4599 SCS.ReferenceBinding = true; 4600 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4601 SCS.BindsToRvalue = true; 4602 SCS.BindsToFunctionLvalue = false; 4603 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4604 SCS.ObjCLifetimeConversionBinding = false; 4605 } else 4606 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4607 From, ToType); 4608 return Result; 4609 } 4610 4611 // C++11 [over.ics.list]p6: 4612 // Otherwise, if the parameter type is not a class: 4613 if (!ToType->isRecordType()) { 4614 // - if the initializer list has one element, the implicit conversion 4615 // sequence is the one required to convert the element to the 4616 // parameter type. 4617 unsigned NumInits = From->getNumInits(); 4618 if (NumInits == 1) 4619 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4620 SuppressUserConversions, 4621 InOverloadResolution, 4622 AllowObjCWritebackConversion); 4623 // - if the initializer list has no elements, the implicit conversion 4624 // sequence is the identity conversion. 4625 else if (NumInits == 0) { 4626 Result.setStandard(); 4627 Result.Standard.setAsIdentityConversion(); 4628 Result.Standard.setFromType(ToType); 4629 Result.Standard.setAllToTypes(ToType); 4630 } 4631 return Result; 4632 } 4633 4634 // C++11 [over.ics.list]p7: 4635 // In all cases other than those enumerated above, no conversion is possible 4636 return Result; 4637 } 4638 4639 /// TryCopyInitialization - Try to copy-initialize a value of type 4640 /// ToType from the expression From. Return the implicit conversion 4641 /// sequence required to pass this argument, which may be a bad 4642 /// conversion sequence (meaning that the argument cannot be passed to 4643 /// a parameter of this type). If @p SuppressUserConversions, then we 4644 /// do not permit any user-defined conversion sequences. 4645 static ImplicitConversionSequence 4646 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4647 bool SuppressUserConversions, 4648 bool InOverloadResolution, 4649 bool AllowObjCWritebackConversion, 4650 bool AllowExplicit) { 4651 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4652 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4653 InOverloadResolution,AllowObjCWritebackConversion); 4654 4655 if (ToType->isReferenceType()) 4656 return TryReferenceInit(S, From, ToType, 4657 /*FIXME:*/From->getLocStart(), 4658 SuppressUserConversions, 4659 AllowExplicit); 4660 4661 return TryImplicitConversion(S, From, ToType, 4662 SuppressUserConversions, 4663 /*AllowExplicit=*/false, 4664 InOverloadResolution, 4665 /*CStyle=*/false, 4666 AllowObjCWritebackConversion, 4667 /*AllowObjCConversionOnExplicit=*/false); 4668 } 4669 4670 static bool TryCopyInitialization(const CanQualType FromQTy, 4671 const CanQualType ToQTy, 4672 Sema &S, 4673 SourceLocation Loc, 4674 ExprValueKind FromVK) { 4675 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4676 ImplicitConversionSequence ICS = 4677 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4678 4679 return !ICS.isBad(); 4680 } 4681 4682 /// TryObjectArgumentInitialization - Try to initialize the object 4683 /// parameter of the given member function (@c Method) from the 4684 /// expression @p From. 4685 static ImplicitConversionSequence 4686 TryObjectArgumentInitialization(Sema &S, QualType FromType, 4687 Expr::Classification FromClassification, 4688 CXXMethodDecl *Method, 4689 CXXRecordDecl *ActingContext) { 4690 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4691 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4692 // const volatile object. 4693 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4694 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4695 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4696 4697 // Set up the conversion sequence as a "bad" conversion, to allow us 4698 // to exit early. 4699 ImplicitConversionSequence ICS; 4700 4701 // We need to have an object of class type. 4702 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4703 FromType = PT->getPointeeType(); 4704 4705 // When we had a pointer, it's implicitly dereferenced, so we 4706 // better have an lvalue. 4707 assert(FromClassification.isLValue()); 4708 } 4709 4710 assert(FromType->isRecordType()); 4711 4712 // C++0x [over.match.funcs]p4: 4713 // For non-static member functions, the type of the implicit object 4714 // parameter is 4715 // 4716 // - "lvalue reference to cv X" for functions declared without a 4717 // ref-qualifier or with the & ref-qualifier 4718 // - "rvalue reference to cv X" for functions declared with the && 4719 // ref-qualifier 4720 // 4721 // where X is the class of which the function is a member and cv is the 4722 // cv-qualification on the member function declaration. 4723 // 4724 // However, when finding an implicit conversion sequence for the argument, we 4725 // are not allowed to create temporaries or perform user-defined conversions 4726 // (C++ [over.match.funcs]p5). We perform a simplified version of 4727 // reference binding here, that allows class rvalues to bind to 4728 // non-constant references. 4729 4730 // First check the qualifiers. 4731 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4732 if (ImplicitParamType.getCVRQualifiers() 4733 != FromTypeCanon.getLocalCVRQualifiers() && 4734 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4735 ICS.setBad(BadConversionSequence::bad_qualifiers, 4736 FromType, ImplicitParamType); 4737 return ICS; 4738 } 4739 4740 // Check that we have either the same type or a derived type. It 4741 // affects the conversion rank. 4742 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4743 ImplicitConversionKind SecondKind; 4744 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4745 SecondKind = ICK_Identity; 4746 } else if (S.IsDerivedFrom(FromType, ClassType)) 4747 SecondKind = ICK_Derived_To_Base; 4748 else { 4749 ICS.setBad(BadConversionSequence::unrelated_class, 4750 FromType, ImplicitParamType); 4751 return ICS; 4752 } 4753 4754 // Check the ref-qualifier. 4755 switch (Method->getRefQualifier()) { 4756 case RQ_None: 4757 // Do nothing; we don't care about lvalueness or rvalueness. 4758 break; 4759 4760 case RQ_LValue: 4761 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4762 // non-const lvalue reference cannot bind to an rvalue 4763 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4764 ImplicitParamType); 4765 return ICS; 4766 } 4767 break; 4768 4769 case RQ_RValue: 4770 if (!FromClassification.isRValue()) { 4771 // rvalue reference cannot bind to an lvalue 4772 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4773 ImplicitParamType); 4774 return ICS; 4775 } 4776 break; 4777 } 4778 4779 // Success. Mark this as a reference binding. 4780 ICS.setStandard(); 4781 ICS.Standard.setAsIdentityConversion(); 4782 ICS.Standard.Second = SecondKind; 4783 ICS.Standard.setFromType(FromType); 4784 ICS.Standard.setAllToTypes(ImplicitParamType); 4785 ICS.Standard.ReferenceBinding = true; 4786 ICS.Standard.DirectBinding = true; 4787 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4788 ICS.Standard.BindsToFunctionLvalue = false; 4789 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4790 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4791 = (Method->getRefQualifier() == RQ_None); 4792 return ICS; 4793 } 4794 4795 /// PerformObjectArgumentInitialization - Perform initialization of 4796 /// the implicit object parameter for the given Method with the given 4797 /// expression. 4798 ExprResult 4799 Sema::PerformObjectArgumentInitialization(Expr *From, 4800 NestedNameSpecifier *Qualifier, 4801 NamedDecl *FoundDecl, 4802 CXXMethodDecl *Method) { 4803 QualType FromRecordType, DestType; 4804 QualType ImplicitParamRecordType = 4805 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4806 4807 Expr::Classification FromClassification; 4808 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4809 FromRecordType = PT->getPointeeType(); 4810 DestType = Method->getThisType(Context); 4811 FromClassification = Expr::Classification::makeSimpleLValue(); 4812 } else { 4813 FromRecordType = From->getType(); 4814 DestType = ImplicitParamRecordType; 4815 FromClassification = From->Classify(Context); 4816 } 4817 4818 // Note that we always use the true parent context when performing 4819 // the actual argument initialization. 4820 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 4821 *this, From->getType(), FromClassification, Method, Method->getParent()); 4822 if (ICS.isBad()) { 4823 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4824 Qualifiers FromQs = FromRecordType.getQualifiers(); 4825 Qualifiers ToQs = DestType.getQualifiers(); 4826 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4827 if (CVR) { 4828 Diag(From->getLocStart(), 4829 diag::err_member_function_call_bad_cvr) 4830 << Method->getDeclName() << FromRecordType << (CVR - 1) 4831 << From->getSourceRange(); 4832 Diag(Method->getLocation(), diag::note_previous_decl) 4833 << Method->getDeclName(); 4834 return ExprError(); 4835 } 4836 } 4837 4838 return Diag(From->getLocStart(), 4839 diag::err_implicit_object_parameter_init) 4840 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4841 } 4842 4843 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4844 ExprResult FromRes = 4845 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4846 if (FromRes.isInvalid()) 4847 return ExprError(); 4848 From = FromRes.get(); 4849 } 4850 4851 if (!Context.hasSameType(From->getType(), DestType)) 4852 From = ImpCastExprToType(From, DestType, CK_NoOp, 4853 From->getValueKind()).get(); 4854 return From; 4855 } 4856 4857 /// TryContextuallyConvertToBool - Attempt to contextually convert the 4858 /// expression From to bool (C++0x [conv]p3). 4859 static ImplicitConversionSequence 4860 TryContextuallyConvertToBool(Sema &S, Expr *From) { 4861 return TryImplicitConversion(S, From, S.Context.BoolTy, 4862 /*SuppressUserConversions=*/false, 4863 /*AllowExplicit=*/true, 4864 /*InOverloadResolution=*/false, 4865 /*CStyle=*/false, 4866 /*AllowObjCWritebackConversion=*/false, 4867 /*AllowObjCConversionOnExplicit=*/false); 4868 } 4869 4870 /// PerformContextuallyConvertToBool - Perform a contextual conversion 4871 /// of the expression From to bool (C++0x [conv]p3). 4872 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4873 if (checkPlaceholderForOverload(*this, From)) 4874 return ExprError(); 4875 4876 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4877 if (!ICS.isBad()) 4878 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4879 4880 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4881 return Diag(From->getLocStart(), 4882 diag::err_typecheck_bool_condition) 4883 << From->getType() << From->getSourceRange(); 4884 return ExprError(); 4885 } 4886 4887 /// Check that the specified conversion is permitted in a converted constant 4888 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 4889 /// is acceptable. 4890 static bool CheckConvertedConstantConversions(Sema &S, 4891 StandardConversionSequence &SCS) { 4892 // Since we know that the target type is an integral or unscoped enumeration 4893 // type, most conversion kinds are impossible. All possible First and Third 4894 // conversions are fine. 4895 switch (SCS.Second) { 4896 case ICK_Identity: 4897 case ICK_NoReturn_Adjustment: 4898 case ICK_Integral_Promotion: 4899 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 4900 return true; 4901 4902 case ICK_Boolean_Conversion: 4903 // Conversion from an integral or unscoped enumeration type to bool is 4904 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 4905 // conversion, so we allow it in a converted constant expression. 4906 // 4907 // FIXME: Per core issue 1407, we should not allow this, but that breaks 4908 // a lot of popular code. We should at least add a warning for this 4909 // (non-conforming) extension. 4910 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4911 SCS.getToType(2)->isBooleanType(); 4912 4913 case ICK_Pointer_Conversion: 4914 case ICK_Pointer_Member: 4915 // C++1z: null pointer conversions and null member pointer conversions are 4916 // only permitted if the source type is std::nullptr_t. 4917 return SCS.getFromType()->isNullPtrType(); 4918 4919 case ICK_Floating_Promotion: 4920 case ICK_Complex_Promotion: 4921 case ICK_Floating_Conversion: 4922 case ICK_Complex_Conversion: 4923 case ICK_Floating_Integral: 4924 case ICK_Compatible_Conversion: 4925 case ICK_Derived_To_Base: 4926 case ICK_Vector_Conversion: 4927 case ICK_Vector_Splat: 4928 case ICK_Complex_Real: 4929 case ICK_Block_Pointer_Conversion: 4930 case ICK_TransparentUnionConversion: 4931 case ICK_Writeback_Conversion: 4932 case ICK_Zero_Event_Conversion: 4933 return false; 4934 4935 case ICK_Lvalue_To_Rvalue: 4936 case ICK_Array_To_Pointer: 4937 case ICK_Function_To_Pointer: 4938 llvm_unreachable("found a first conversion kind in Second"); 4939 4940 case ICK_Qualification: 4941 llvm_unreachable("found a third conversion kind in Second"); 4942 4943 case ICK_Num_Conversion_Kinds: 4944 break; 4945 } 4946 4947 llvm_unreachable("unknown conversion kind"); 4948 } 4949 4950 /// CheckConvertedConstantExpression - Check that the expression From is a 4951 /// converted constant expression of type T, perform the conversion and produce 4952 /// the converted expression, per C++11 [expr.const]p3. 4953 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 4954 QualType T, APValue &Value, 4955 Sema::CCEKind CCE, 4956 bool RequireInt) { 4957 assert(S.getLangOpts().CPlusPlus11 && 4958 "converted constant expression outside C++11"); 4959 4960 if (checkPlaceholderForOverload(S, From)) 4961 return ExprError(); 4962 4963 // C++1z [expr.const]p3: 4964 // A converted constant expression of type T is an expression, 4965 // implicitly converted to type T, where the converted 4966 // expression is a constant expression and the implicit conversion 4967 // sequence contains only [... list of conversions ...]. 4968 ImplicitConversionSequence ICS = 4969 TryCopyInitialization(S, From, T, 4970 /*SuppressUserConversions=*/false, 4971 /*InOverloadResolution=*/false, 4972 /*AllowObjcWritebackConversion=*/false, 4973 /*AllowExplicit=*/false); 4974 StandardConversionSequence *SCS = nullptr; 4975 switch (ICS.getKind()) { 4976 case ImplicitConversionSequence::StandardConversion: 4977 SCS = &ICS.Standard; 4978 break; 4979 case ImplicitConversionSequence::UserDefinedConversion: 4980 // We are converting to a non-class type, so the Before sequence 4981 // must be trivial. 4982 SCS = &ICS.UserDefined.After; 4983 break; 4984 case ImplicitConversionSequence::AmbiguousConversion: 4985 case ImplicitConversionSequence::BadConversion: 4986 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 4987 return S.Diag(From->getLocStart(), 4988 diag::err_typecheck_converted_constant_expression) 4989 << From->getType() << From->getSourceRange() << T; 4990 return ExprError(); 4991 4992 case ImplicitConversionSequence::EllipsisConversion: 4993 llvm_unreachable("ellipsis conversion in converted constant expression"); 4994 } 4995 4996 // Check that we would only use permitted conversions. 4997 if (!CheckConvertedConstantConversions(S, *SCS)) { 4998 return S.Diag(From->getLocStart(), 4999 diag::err_typecheck_converted_constant_expression_disallowed) 5000 << From->getType() << From->getSourceRange() << T; 5001 } 5002 // [...] and where the reference binding (if any) binds directly. 5003 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5004 return S.Diag(From->getLocStart(), 5005 diag::err_typecheck_converted_constant_expression_indirect) 5006 << From->getType() << From->getSourceRange() << T; 5007 } 5008 5009 ExprResult Result = 5010 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5011 if (Result.isInvalid()) 5012 return Result; 5013 5014 // Check for a narrowing implicit conversion. 5015 APValue PreNarrowingValue; 5016 QualType PreNarrowingType; 5017 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5018 PreNarrowingType)) { 5019 case NK_Variable_Narrowing: 5020 // Implicit conversion to a narrower type, and the value is not a constant 5021 // expression. We'll diagnose this in a moment. 5022 case NK_Not_Narrowing: 5023 break; 5024 5025 case NK_Constant_Narrowing: 5026 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5027 << CCE << /*Constant*/1 5028 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5029 break; 5030 5031 case NK_Type_Narrowing: 5032 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5033 << CCE << /*Constant*/0 << From->getType() << T; 5034 break; 5035 } 5036 5037 // Check the expression is a constant expression. 5038 SmallVector<PartialDiagnosticAt, 8> Notes; 5039 Expr::EvalResult Eval; 5040 Eval.Diag = &Notes; 5041 5042 if ((T->isReferenceType() 5043 ? !Result.get()->EvaluateAsLValue(Eval, S.Context) 5044 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) || 5045 (RequireInt && !Eval.Val.isInt())) { 5046 // The expression can't be folded, so we can't keep it at this position in 5047 // the AST. 5048 Result = ExprError(); 5049 } else { 5050 Value = Eval.Val; 5051 5052 if (Notes.empty()) { 5053 // It's a constant expression. 5054 return Result; 5055 } 5056 } 5057 5058 // It's not a constant expression. Produce an appropriate diagnostic. 5059 if (Notes.size() == 1 && 5060 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5061 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5062 else { 5063 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5064 << CCE << From->getSourceRange(); 5065 for (unsigned I = 0; I < Notes.size(); ++I) 5066 S.Diag(Notes[I].first, Notes[I].second); 5067 } 5068 return ExprError(); 5069 } 5070 5071 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5072 APValue &Value, CCEKind CCE) { 5073 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5074 } 5075 5076 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5077 llvm::APSInt &Value, 5078 CCEKind CCE) { 5079 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5080 5081 APValue V; 5082 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5083 if (!R.isInvalid()) 5084 Value = V.getInt(); 5085 return R; 5086 } 5087 5088 5089 /// dropPointerConversions - If the given standard conversion sequence 5090 /// involves any pointer conversions, remove them. This may change 5091 /// the result type of the conversion sequence. 5092 static void dropPointerConversion(StandardConversionSequence &SCS) { 5093 if (SCS.Second == ICK_Pointer_Conversion) { 5094 SCS.Second = ICK_Identity; 5095 SCS.Third = ICK_Identity; 5096 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5097 } 5098 } 5099 5100 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5101 /// convert the expression From to an Objective-C pointer type. 5102 static ImplicitConversionSequence 5103 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5104 // Do an implicit conversion to 'id'. 5105 QualType Ty = S.Context.getObjCIdType(); 5106 ImplicitConversionSequence ICS 5107 = TryImplicitConversion(S, From, Ty, 5108 // FIXME: Are these flags correct? 5109 /*SuppressUserConversions=*/false, 5110 /*AllowExplicit=*/true, 5111 /*InOverloadResolution=*/false, 5112 /*CStyle=*/false, 5113 /*AllowObjCWritebackConversion=*/false, 5114 /*AllowObjCConversionOnExplicit=*/true); 5115 5116 // Strip off any final conversions to 'id'. 5117 switch (ICS.getKind()) { 5118 case ImplicitConversionSequence::BadConversion: 5119 case ImplicitConversionSequence::AmbiguousConversion: 5120 case ImplicitConversionSequence::EllipsisConversion: 5121 break; 5122 5123 case ImplicitConversionSequence::UserDefinedConversion: 5124 dropPointerConversion(ICS.UserDefined.After); 5125 break; 5126 5127 case ImplicitConversionSequence::StandardConversion: 5128 dropPointerConversion(ICS.Standard); 5129 break; 5130 } 5131 5132 return ICS; 5133 } 5134 5135 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5136 /// conversion of the expression From to an Objective-C pointer type. 5137 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5138 if (checkPlaceholderForOverload(*this, From)) 5139 return ExprError(); 5140 5141 QualType Ty = Context.getObjCIdType(); 5142 ImplicitConversionSequence ICS = 5143 TryContextuallyConvertToObjCPointer(*this, From); 5144 if (!ICS.isBad()) 5145 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5146 return ExprError(); 5147 } 5148 5149 /// Determine whether the provided type is an integral type, or an enumeration 5150 /// type of a permitted flavor. 5151 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5152 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5153 : T->isIntegralOrUnscopedEnumerationType(); 5154 } 5155 5156 static ExprResult 5157 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5158 Sema::ContextualImplicitConverter &Converter, 5159 QualType T, UnresolvedSetImpl &ViableConversions) { 5160 5161 if (Converter.Suppress) 5162 return ExprError(); 5163 5164 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5165 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5166 CXXConversionDecl *Conv = 5167 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5168 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5169 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5170 } 5171 return From; 5172 } 5173 5174 static bool 5175 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5176 Sema::ContextualImplicitConverter &Converter, 5177 QualType T, bool HadMultipleCandidates, 5178 UnresolvedSetImpl &ExplicitConversions) { 5179 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5180 DeclAccessPair Found = ExplicitConversions[0]; 5181 CXXConversionDecl *Conversion = 5182 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5183 5184 // The user probably meant to invoke the given explicit 5185 // conversion; use it. 5186 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5187 std::string TypeStr; 5188 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5189 5190 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5191 << FixItHint::CreateInsertion(From->getLocStart(), 5192 "static_cast<" + TypeStr + ">(") 5193 << FixItHint::CreateInsertion( 5194 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5195 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5196 5197 // If we aren't in a SFINAE context, build a call to the 5198 // explicit conversion function. 5199 if (SemaRef.isSFINAEContext()) 5200 return true; 5201 5202 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5203 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5204 HadMultipleCandidates); 5205 if (Result.isInvalid()) 5206 return true; 5207 // Record usage of conversion in an implicit cast. 5208 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5209 CK_UserDefinedConversion, Result.get(), 5210 nullptr, Result.get()->getValueKind()); 5211 } 5212 return false; 5213 } 5214 5215 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5216 Sema::ContextualImplicitConverter &Converter, 5217 QualType T, bool HadMultipleCandidates, 5218 DeclAccessPair &Found) { 5219 CXXConversionDecl *Conversion = 5220 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5221 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5222 5223 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5224 if (!Converter.SuppressConversion) { 5225 if (SemaRef.isSFINAEContext()) 5226 return true; 5227 5228 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5229 << From->getSourceRange(); 5230 } 5231 5232 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5233 HadMultipleCandidates); 5234 if (Result.isInvalid()) 5235 return true; 5236 // Record usage of conversion in an implicit cast. 5237 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5238 CK_UserDefinedConversion, Result.get(), 5239 nullptr, Result.get()->getValueKind()); 5240 return false; 5241 } 5242 5243 static ExprResult finishContextualImplicitConversion( 5244 Sema &SemaRef, SourceLocation Loc, Expr *From, 5245 Sema::ContextualImplicitConverter &Converter) { 5246 if (!Converter.match(From->getType()) && !Converter.Suppress) 5247 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5248 << From->getSourceRange(); 5249 5250 return SemaRef.DefaultLvalueConversion(From); 5251 } 5252 5253 static void 5254 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5255 UnresolvedSetImpl &ViableConversions, 5256 OverloadCandidateSet &CandidateSet) { 5257 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5258 DeclAccessPair FoundDecl = ViableConversions[I]; 5259 NamedDecl *D = FoundDecl.getDecl(); 5260 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5261 if (isa<UsingShadowDecl>(D)) 5262 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5263 5264 CXXConversionDecl *Conv; 5265 FunctionTemplateDecl *ConvTemplate; 5266 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5267 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5268 else 5269 Conv = cast<CXXConversionDecl>(D); 5270 5271 if (ConvTemplate) 5272 SemaRef.AddTemplateConversionCandidate( 5273 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5274 /*AllowObjCConversionOnExplicit=*/false); 5275 else 5276 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5277 ToType, CandidateSet, 5278 /*AllowObjCConversionOnExplicit=*/false); 5279 } 5280 } 5281 5282 /// \brief Attempt to convert the given expression to a type which is accepted 5283 /// by the given converter. 5284 /// 5285 /// This routine will attempt to convert an expression of class type to a 5286 /// type accepted by the specified converter. In C++11 and before, the class 5287 /// must have a single non-explicit conversion function converting to a matching 5288 /// type. In C++1y, there can be multiple such conversion functions, but only 5289 /// one target type. 5290 /// 5291 /// \param Loc The source location of the construct that requires the 5292 /// conversion. 5293 /// 5294 /// \param From The expression we're converting from. 5295 /// 5296 /// \param Converter Used to control and diagnose the conversion process. 5297 /// 5298 /// \returns The expression, converted to an integral or enumeration type if 5299 /// successful. 5300 ExprResult Sema::PerformContextualImplicitConversion( 5301 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5302 // We can't perform any more checking for type-dependent expressions. 5303 if (From->isTypeDependent()) 5304 return From; 5305 5306 // Process placeholders immediately. 5307 if (From->hasPlaceholderType()) { 5308 ExprResult result = CheckPlaceholderExpr(From); 5309 if (result.isInvalid()) 5310 return result; 5311 From = result.get(); 5312 } 5313 5314 // If the expression already has a matching type, we're golden. 5315 QualType T = From->getType(); 5316 if (Converter.match(T)) 5317 return DefaultLvalueConversion(From); 5318 5319 // FIXME: Check for missing '()' if T is a function type? 5320 5321 // We can only perform contextual implicit conversions on objects of class 5322 // type. 5323 const RecordType *RecordTy = T->getAs<RecordType>(); 5324 if (!RecordTy || !getLangOpts().CPlusPlus) { 5325 if (!Converter.Suppress) 5326 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5327 return From; 5328 } 5329 5330 // We must have a complete class type. 5331 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5332 ContextualImplicitConverter &Converter; 5333 Expr *From; 5334 5335 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5336 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {} 5337 5338 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5339 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5340 } 5341 } IncompleteDiagnoser(Converter, From); 5342 5343 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5344 return From; 5345 5346 // Look for a conversion to an integral or enumeration type. 5347 UnresolvedSet<4> 5348 ViableConversions; // These are *potentially* viable in C++1y. 5349 UnresolvedSet<4> ExplicitConversions; 5350 std::pair<CXXRecordDecl::conversion_iterator, 5351 CXXRecordDecl::conversion_iterator> Conversions = 5352 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5353 5354 bool HadMultipleCandidates = 5355 (std::distance(Conversions.first, Conversions.second) > 1); 5356 5357 // To check that there is only one target type, in C++1y: 5358 QualType ToType; 5359 bool HasUniqueTargetType = true; 5360 5361 // Collect explicit or viable (potentially in C++1y) conversions. 5362 for (CXXRecordDecl::conversion_iterator I = Conversions.first, 5363 E = Conversions.second; 5364 I != E; ++I) { 5365 NamedDecl *D = (*I)->getUnderlyingDecl(); 5366 CXXConversionDecl *Conversion; 5367 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5368 if (ConvTemplate) { 5369 if (getLangOpts().CPlusPlus14) 5370 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5371 else 5372 continue; // C++11 does not consider conversion operator templates(?). 5373 } else 5374 Conversion = cast<CXXConversionDecl>(D); 5375 5376 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5377 "Conversion operator templates are considered potentially " 5378 "viable in C++1y"); 5379 5380 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5381 if (Converter.match(CurToType) || ConvTemplate) { 5382 5383 if (Conversion->isExplicit()) { 5384 // FIXME: For C++1y, do we need this restriction? 5385 // cf. diagnoseNoViableConversion() 5386 if (!ConvTemplate) 5387 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5388 } else { 5389 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5390 if (ToType.isNull()) 5391 ToType = CurToType.getUnqualifiedType(); 5392 else if (HasUniqueTargetType && 5393 (CurToType.getUnqualifiedType() != ToType)) 5394 HasUniqueTargetType = false; 5395 } 5396 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5397 } 5398 } 5399 } 5400 5401 if (getLangOpts().CPlusPlus14) { 5402 // C++1y [conv]p6: 5403 // ... An expression e of class type E appearing in such a context 5404 // is said to be contextually implicitly converted to a specified 5405 // type T and is well-formed if and only if e can be implicitly 5406 // converted to a type T that is determined as follows: E is searched 5407 // for conversion functions whose return type is cv T or reference to 5408 // cv T such that T is allowed by the context. There shall be 5409 // exactly one such T. 5410 5411 // If no unique T is found: 5412 if (ToType.isNull()) { 5413 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5414 HadMultipleCandidates, 5415 ExplicitConversions)) 5416 return ExprError(); 5417 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5418 } 5419 5420 // If more than one unique Ts are found: 5421 if (!HasUniqueTargetType) 5422 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5423 ViableConversions); 5424 5425 // If one unique T is found: 5426 // First, build a candidate set from the previously recorded 5427 // potentially viable conversions. 5428 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5429 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5430 CandidateSet); 5431 5432 // Then, perform overload resolution over the candidate set. 5433 OverloadCandidateSet::iterator Best; 5434 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5435 case OR_Success: { 5436 // Apply this conversion. 5437 DeclAccessPair Found = 5438 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5439 if (recordConversion(*this, Loc, From, Converter, T, 5440 HadMultipleCandidates, Found)) 5441 return ExprError(); 5442 break; 5443 } 5444 case OR_Ambiguous: 5445 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5446 ViableConversions); 5447 case OR_No_Viable_Function: 5448 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5449 HadMultipleCandidates, 5450 ExplicitConversions)) 5451 return ExprError(); 5452 // fall through 'OR_Deleted' case. 5453 case OR_Deleted: 5454 // We'll complain below about a non-integral condition type. 5455 break; 5456 } 5457 } else { 5458 switch (ViableConversions.size()) { 5459 case 0: { 5460 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5461 HadMultipleCandidates, 5462 ExplicitConversions)) 5463 return ExprError(); 5464 5465 // We'll complain below about a non-integral condition type. 5466 break; 5467 } 5468 case 1: { 5469 // Apply this conversion. 5470 DeclAccessPair Found = ViableConversions[0]; 5471 if (recordConversion(*this, Loc, From, Converter, T, 5472 HadMultipleCandidates, Found)) 5473 return ExprError(); 5474 break; 5475 } 5476 default: 5477 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5478 ViableConversions); 5479 } 5480 } 5481 5482 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5483 } 5484 5485 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5486 /// an acceptable non-member overloaded operator for a call whose 5487 /// arguments have types T1 (and, if non-empty, T2). This routine 5488 /// implements the check in C++ [over.match.oper]p3b2 concerning 5489 /// enumeration types. 5490 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5491 FunctionDecl *Fn, 5492 ArrayRef<Expr *> Args) { 5493 QualType T1 = Args[0]->getType(); 5494 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5495 5496 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5497 return true; 5498 5499 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5500 return true; 5501 5502 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5503 if (Proto->getNumParams() < 1) 5504 return false; 5505 5506 if (T1->isEnumeralType()) { 5507 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5508 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5509 return true; 5510 } 5511 5512 if (Proto->getNumParams() < 2) 5513 return false; 5514 5515 if (!T2.isNull() && T2->isEnumeralType()) { 5516 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5517 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5518 return true; 5519 } 5520 5521 return false; 5522 } 5523 5524 /// AddOverloadCandidate - Adds the given function to the set of 5525 /// candidate functions, using the given function call arguments. If 5526 /// @p SuppressUserConversions, then don't allow user-defined 5527 /// conversions via constructors or conversion operators. 5528 /// 5529 /// \param PartialOverloading true if we are performing "partial" overloading 5530 /// based on an incomplete set of function arguments. This feature is used by 5531 /// code completion. 5532 void 5533 Sema::AddOverloadCandidate(FunctionDecl *Function, 5534 DeclAccessPair FoundDecl, 5535 ArrayRef<Expr *> Args, 5536 OverloadCandidateSet &CandidateSet, 5537 bool SuppressUserConversions, 5538 bool PartialOverloading, 5539 bool AllowExplicit) { 5540 const FunctionProtoType *Proto 5541 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5542 assert(Proto && "Functions without a prototype cannot be overloaded"); 5543 assert(!Function->getDescribedFunctionTemplate() && 5544 "Use AddTemplateOverloadCandidate for function templates"); 5545 5546 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5547 if (!isa<CXXConstructorDecl>(Method)) { 5548 // If we get here, it's because we're calling a member function 5549 // that is named without a member access expression (e.g., 5550 // "this->f") that was either written explicitly or created 5551 // implicitly. This can happen with a qualified call to a member 5552 // function, e.g., X::f(). We use an empty type for the implied 5553 // object argument (C++ [over.call.func]p3), and the acting context 5554 // is irrelevant. 5555 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5556 QualType(), Expr::Classification::makeSimpleLValue(), 5557 Args, CandidateSet, SuppressUserConversions); 5558 return; 5559 } 5560 // We treat a constructor like a non-member function, since its object 5561 // argument doesn't participate in overload resolution. 5562 } 5563 5564 if (!CandidateSet.isNewCandidate(Function)) 5565 return; 5566 5567 // C++ [over.match.oper]p3: 5568 // if no operand has a class type, only those non-member functions in the 5569 // lookup set that have a first parameter of type T1 or "reference to 5570 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5571 // is a right operand) a second parameter of type T2 or "reference to 5572 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5573 // candidate functions. 5574 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5575 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5576 return; 5577 5578 // C++11 [class.copy]p11: [DR1402] 5579 // A defaulted move constructor that is defined as deleted is ignored by 5580 // overload resolution. 5581 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5582 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5583 Constructor->isMoveConstructor()) 5584 return; 5585 5586 // Overload resolution is always an unevaluated context. 5587 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5588 5589 if (Constructor) { 5590 // C++ [class.copy]p3: 5591 // A member function template is never instantiated to perform the copy 5592 // of a class object to an object of its class type. 5593 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5594 if (Args.size() == 1 && 5595 Constructor->isSpecializationCopyingObject() && 5596 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5597 IsDerivedFrom(Args[0]->getType(), ClassType))) 5598 return; 5599 } 5600 5601 // Add this candidate 5602 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5603 Candidate.FoundDecl = FoundDecl; 5604 Candidate.Function = Function; 5605 Candidate.Viable = true; 5606 Candidate.IsSurrogate = false; 5607 Candidate.IgnoreObjectArgument = false; 5608 Candidate.ExplicitCallArguments = Args.size(); 5609 5610 unsigned NumParams = Proto->getNumParams(); 5611 5612 // (C++ 13.3.2p2): A candidate function having fewer than m 5613 // parameters is viable only if it has an ellipsis in its parameter 5614 // list (8.3.5). 5615 if ((Args.size() + (PartialOverloading && Args.size())) > NumParams && 5616 !Proto->isVariadic()) { 5617 Candidate.Viable = false; 5618 Candidate.FailureKind = ovl_fail_too_many_arguments; 5619 return; 5620 } 5621 5622 // (C++ 13.3.2p2): A candidate function having more than m parameters 5623 // is viable only if the (m+1)st parameter has a default argument 5624 // (8.3.6). For the purposes of overload resolution, the 5625 // parameter list is truncated on the right, so that there are 5626 // exactly m parameters. 5627 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5628 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5629 // Not enough arguments. 5630 Candidate.Viable = false; 5631 Candidate.FailureKind = ovl_fail_too_few_arguments; 5632 return; 5633 } 5634 5635 // (CUDA B.1): Check for invalid calls between targets. 5636 if (getLangOpts().CUDA) 5637 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5638 // Skip the check for callers that are implicit members, because in this 5639 // case we may not yet know what the member's target is; the target is 5640 // inferred for the member automatically, based on the bases and fields of 5641 // the class. 5642 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) { 5643 Candidate.Viable = false; 5644 Candidate.FailureKind = ovl_fail_bad_target; 5645 return; 5646 } 5647 5648 // Determine the implicit conversion sequences for each of the 5649 // arguments. 5650 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5651 if (ArgIdx < NumParams) { 5652 // (C++ 13.3.2p3): for F to be a viable function, there shall 5653 // exist for each argument an implicit conversion sequence 5654 // (13.3.3.1) that converts that argument to the corresponding 5655 // parameter of F. 5656 QualType ParamType = Proto->getParamType(ArgIdx); 5657 Candidate.Conversions[ArgIdx] 5658 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5659 SuppressUserConversions, 5660 /*InOverloadResolution=*/true, 5661 /*AllowObjCWritebackConversion=*/ 5662 getLangOpts().ObjCAutoRefCount, 5663 AllowExplicit); 5664 if (Candidate.Conversions[ArgIdx].isBad()) { 5665 Candidate.Viable = false; 5666 Candidate.FailureKind = ovl_fail_bad_conversion; 5667 return; 5668 } 5669 } else { 5670 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5671 // argument for which there is no corresponding parameter is 5672 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5673 Candidate.Conversions[ArgIdx].setEllipsis(); 5674 } 5675 } 5676 5677 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5678 Candidate.Viable = false; 5679 Candidate.FailureKind = ovl_fail_enable_if; 5680 Candidate.DeductionFailure.Data = FailedAttr; 5681 return; 5682 } 5683 } 5684 5685 ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, 5686 bool IsInstance) { 5687 SmallVector<ObjCMethodDecl*, 4> Methods; 5688 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance)) 5689 return nullptr; 5690 5691 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5692 bool Match = true; 5693 ObjCMethodDecl *Method = Methods[b]; 5694 unsigned NumNamedArgs = Sel.getNumArgs(); 5695 // Method might have more arguments than selector indicates. This is due 5696 // to addition of c-style arguments in method. 5697 if (Method->param_size() > NumNamedArgs) 5698 NumNamedArgs = Method->param_size(); 5699 if (Args.size() < NumNamedArgs) 5700 continue; 5701 5702 for (unsigned i = 0; i < NumNamedArgs; i++) { 5703 // We can't do any type-checking on a type-dependent argument. 5704 if (Args[i]->isTypeDependent()) { 5705 Match = false; 5706 break; 5707 } 5708 5709 ParmVarDecl *param = Method->parameters()[i]; 5710 Expr *argExpr = Args[i]; 5711 assert(argExpr && "SelectBestMethod(): missing expression"); 5712 5713 // Strip the unbridged-cast placeholder expression off unless it's 5714 // a consumed argument. 5715 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 5716 !param->hasAttr<CFConsumedAttr>()) 5717 argExpr = stripARCUnbridgedCast(argExpr); 5718 5719 // If the parameter is __unknown_anytype, move on to the next method. 5720 if (param->getType() == Context.UnknownAnyTy) { 5721 Match = false; 5722 break; 5723 } 5724 5725 ImplicitConversionSequence ConversionState 5726 = TryCopyInitialization(*this, argExpr, param->getType(), 5727 /*SuppressUserConversions*/false, 5728 /*InOverloadResolution=*/true, 5729 /*AllowObjCWritebackConversion=*/ 5730 getLangOpts().ObjCAutoRefCount, 5731 /*AllowExplicit*/false); 5732 if (ConversionState.isBad()) { 5733 Match = false; 5734 break; 5735 } 5736 } 5737 // Promote additional arguments to variadic methods. 5738 if (Match && Method->isVariadic()) { 5739 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 5740 if (Args[i]->isTypeDependent()) { 5741 Match = false; 5742 break; 5743 } 5744 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 5745 nullptr); 5746 if (Arg.isInvalid()) { 5747 Match = false; 5748 break; 5749 } 5750 } 5751 } else { 5752 // Check for extra arguments to non-variadic methods. 5753 if (Args.size() != NumNamedArgs) 5754 Match = false; 5755 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 5756 // Special case when selectors have no argument. In this case, select 5757 // one with the most general result type of 'id'. 5758 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5759 QualType ReturnT = Methods[b]->getReturnType(); 5760 if (ReturnT->isObjCIdType()) 5761 return Methods[b]; 5762 } 5763 } 5764 } 5765 5766 if (Match) 5767 return Method; 5768 } 5769 return nullptr; 5770 } 5771 5772 static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); } 5773 5774 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 5775 bool MissingImplicitThis) { 5776 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but 5777 // we need to find the first failing one. 5778 if (!Function->hasAttrs()) 5779 return nullptr; 5780 AttrVec Attrs = Function->getAttrs(); 5781 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(), 5782 IsNotEnableIfAttr); 5783 if (Attrs.begin() == E) 5784 return nullptr; 5785 std::reverse(Attrs.begin(), E); 5786 5787 SFINAETrap Trap(*this); 5788 5789 // Convert the arguments. 5790 SmallVector<Expr *, 16> ConvertedArgs; 5791 bool InitializationFailed = false; 5792 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 5793 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 5794 !cast<CXXMethodDecl>(Function)->isStatic() && 5795 !isa<CXXConstructorDecl>(Function)) { 5796 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 5797 ExprResult R = 5798 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 5799 Method, Method); 5800 if (R.isInvalid()) { 5801 InitializationFailed = true; 5802 break; 5803 } 5804 ConvertedArgs.push_back(R.get()); 5805 } else { 5806 ExprResult R = 5807 PerformCopyInitialization(InitializedEntity::InitializeParameter( 5808 Context, 5809 Function->getParamDecl(i)), 5810 SourceLocation(), 5811 Args[i]); 5812 if (R.isInvalid()) { 5813 InitializationFailed = true; 5814 break; 5815 } 5816 ConvertedArgs.push_back(R.get()); 5817 } 5818 } 5819 5820 if (InitializationFailed || Trap.hasErrorOccurred()) 5821 return cast<EnableIfAttr>(Attrs[0]); 5822 5823 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) { 5824 APValue Result; 5825 EnableIfAttr *EIA = cast<EnableIfAttr>(*I); 5826 if (!EIA->getCond()->EvaluateWithSubstitution( 5827 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)) || 5828 !Result.isInt() || !Result.getInt().getBoolValue()) { 5829 return EIA; 5830 } 5831 } 5832 return nullptr; 5833 } 5834 5835 /// \brief Add all of the function declarations in the given function set to 5836 /// the overload candidate set. 5837 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5838 ArrayRef<Expr *> Args, 5839 OverloadCandidateSet& CandidateSet, 5840 bool SuppressUserConversions, 5841 TemplateArgumentListInfo *ExplicitTemplateArgs) { 5842 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5843 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5844 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5845 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5846 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5847 cast<CXXMethodDecl>(FD)->getParent(), 5848 Args[0]->getType(), Args[0]->Classify(Context), 5849 Args.slice(1), CandidateSet, 5850 SuppressUserConversions); 5851 else 5852 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5853 SuppressUserConversions); 5854 } else { 5855 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5856 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5857 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5858 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5859 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5860 ExplicitTemplateArgs, 5861 Args[0]->getType(), 5862 Args[0]->Classify(Context), Args.slice(1), 5863 CandidateSet, SuppressUserConversions); 5864 else 5865 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5866 ExplicitTemplateArgs, Args, 5867 CandidateSet, SuppressUserConversions); 5868 } 5869 } 5870 } 5871 5872 /// AddMethodCandidate - Adds a named decl (which is some kind of 5873 /// method) as a method candidate to the given overload set. 5874 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5875 QualType ObjectType, 5876 Expr::Classification ObjectClassification, 5877 ArrayRef<Expr *> Args, 5878 OverloadCandidateSet& CandidateSet, 5879 bool SuppressUserConversions) { 5880 NamedDecl *Decl = FoundDecl.getDecl(); 5881 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5882 5883 if (isa<UsingShadowDecl>(Decl)) 5884 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5885 5886 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5887 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5888 "Expected a member function template"); 5889 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5890 /*ExplicitArgs*/ nullptr, 5891 ObjectType, ObjectClassification, 5892 Args, CandidateSet, 5893 SuppressUserConversions); 5894 } else { 5895 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5896 ObjectType, ObjectClassification, 5897 Args, 5898 CandidateSet, SuppressUserConversions); 5899 } 5900 } 5901 5902 /// AddMethodCandidate - Adds the given C++ member function to the set 5903 /// of candidate functions, using the given function call arguments 5904 /// and the object argument (@c Object). For example, in a call 5905 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5906 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5907 /// allow user-defined conversions via constructors or conversion 5908 /// operators. 5909 void 5910 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5911 CXXRecordDecl *ActingContext, QualType ObjectType, 5912 Expr::Classification ObjectClassification, 5913 ArrayRef<Expr *> Args, 5914 OverloadCandidateSet &CandidateSet, 5915 bool SuppressUserConversions) { 5916 const FunctionProtoType *Proto 5917 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5918 assert(Proto && "Methods without a prototype cannot be overloaded"); 5919 assert(!isa<CXXConstructorDecl>(Method) && 5920 "Use AddOverloadCandidate for constructors"); 5921 5922 if (!CandidateSet.isNewCandidate(Method)) 5923 return; 5924 5925 // C++11 [class.copy]p23: [DR1402] 5926 // A defaulted move assignment operator that is defined as deleted is 5927 // ignored by overload resolution. 5928 if (Method->isDefaulted() && Method->isDeleted() && 5929 Method->isMoveAssignmentOperator()) 5930 return; 5931 5932 // Overload resolution is always an unevaluated context. 5933 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5934 5935 // Add this candidate 5936 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5937 Candidate.FoundDecl = FoundDecl; 5938 Candidate.Function = Method; 5939 Candidate.IsSurrogate = false; 5940 Candidate.IgnoreObjectArgument = false; 5941 Candidate.ExplicitCallArguments = Args.size(); 5942 5943 unsigned NumParams = Proto->getNumParams(); 5944 5945 // (C++ 13.3.2p2): A candidate function having fewer than m 5946 // parameters is viable only if it has an ellipsis in its parameter 5947 // list (8.3.5). 5948 if (Args.size() > NumParams && !Proto->isVariadic()) { 5949 Candidate.Viable = false; 5950 Candidate.FailureKind = ovl_fail_too_many_arguments; 5951 return; 5952 } 5953 5954 // (C++ 13.3.2p2): A candidate function having more than m parameters 5955 // is viable only if the (m+1)st parameter has a default argument 5956 // (8.3.6). For the purposes of overload resolution, the 5957 // parameter list is truncated on the right, so that there are 5958 // exactly m parameters. 5959 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 5960 if (Args.size() < MinRequiredArgs) { 5961 // Not enough arguments. 5962 Candidate.Viable = false; 5963 Candidate.FailureKind = ovl_fail_too_few_arguments; 5964 return; 5965 } 5966 5967 Candidate.Viable = true; 5968 5969 if (Method->isStatic() || ObjectType.isNull()) 5970 // The implicit object argument is ignored. 5971 Candidate.IgnoreObjectArgument = true; 5972 else { 5973 // Determine the implicit conversion sequence for the object 5974 // parameter. 5975 Candidate.Conversions[0] 5976 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 5977 Method, ActingContext); 5978 if (Candidate.Conversions[0].isBad()) { 5979 Candidate.Viable = false; 5980 Candidate.FailureKind = ovl_fail_bad_conversion; 5981 return; 5982 } 5983 } 5984 5985 // (CUDA B.1): Check for invalid calls between targets. 5986 if (getLangOpts().CUDA) 5987 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5988 if (CheckCUDATarget(Caller, Method)) { 5989 Candidate.Viable = false; 5990 Candidate.FailureKind = ovl_fail_bad_target; 5991 return; 5992 } 5993 5994 // Determine the implicit conversion sequences for each of the 5995 // arguments. 5996 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5997 if (ArgIdx < NumParams) { 5998 // (C++ 13.3.2p3): for F to be a viable function, there shall 5999 // exist for each argument an implicit conversion sequence 6000 // (13.3.3.1) that converts that argument to the corresponding 6001 // parameter of F. 6002 QualType ParamType = Proto->getParamType(ArgIdx); 6003 Candidate.Conversions[ArgIdx + 1] 6004 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6005 SuppressUserConversions, 6006 /*InOverloadResolution=*/true, 6007 /*AllowObjCWritebackConversion=*/ 6008 getLangOpts().ObjCAutoRefCount); 6009 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6010 Candidate.Viable = false; 6011 Candidate.FailureKind = ovl_fail_bad_conversion; 6012 return; 6013 } 6014 } else { 6015 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6016 // argument for which there is no corresponding parameter is 6017 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6018 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6019 } 6020 } 6021 6022 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6023 Candidate.Viable = false; 6024 Candidate.FailureKind = ovl_fail_enable_if; 6025 Candidate.DeductionFailure.Data = FailedAttr; 6026 return; 6027 } 6028 } 6029 6030 /// \brief Add a C++ member function template as a candidate to the candidate 6031 /// set, using template argument deduction to produce an appropriate member 6032 /// function template specialization. 6033 void 6034 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6035 DeclAccessPair FoundDecl, 6036 CXXRecordDecl *ActingContext, 6037 TemplateArgumentListInfo *ExplicitTemplateArgs, 6038 QualType ObjectType, 6039 Expr::Classification ObjectClassification, 6040 ArrayRef<Expr *> Args, 6041 OverloadCandidateSet& CandidateSet, 6042 bool SuppressUserConversions) { 6043 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6044 return; 6045 6046 // C++ [over.match.funcs]p7: 6047 // In each case where a candidate is a function template, candidate 6048 // function template specializations are generated using template argument 6049 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6050 // candidate functions in the usual way.113) A given name can refer to one 6051 // or more function templates and also to a set of overloaded non-template 6052 // functions. In such a case, the candidate functions generated from each 6053 // function template are combined with the set of non-template candidate 6054 // functions. 6055 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6056 FunctionDecl *Specialization = nullptr; 6057 if (TemplateDeductionResult Result 6058 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 6059 Specialization, Info)) { 6060 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6061 Candidate.FoundDecl = FoundDecl; 6062 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6063 Candidate.Viable = false; 6064 Candidate.FailureKind = ovl_fail_bad_deduction; 6065 Candidate.IsSurrogate = false; 6066 Candidate.IgnoreObjectArgument = false; 6067 Candidate.ExplicitCallArguments = Args.size(); 6068 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6069 Info); 6070 return; 6071 } 6072 6073 // Add the function template specialization produced by template argument 6074 // deduction as a candidate. 6075 assert(Specialization && "Missing member function template specialization?"); 6076 assert(isa<CXXMethodDecl>(Specialization) && 6077 "Specialization is not a member function?"); 6078 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6079 ActingContext, ObjectType, ObjectClassification, Args, 6080 CandidateSet, SuppressUserConversions); 6081 } 6082 6083 /// \brief Add a C++ function template specialization as a candidate 6084 /// in the candidate set, using template argument deduction to produce 6085 /// an appropriate function template specialization. 6086 void 6087 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6088 DeclAccessPair FoundDecl, 6089 TemplateArgumentListInfo *ExplicitTemplateArgs, 6090 ArrayRef<Expr *> Args, 6091 OverloadCandidateSet& CandidateSet, 6092 bool SuppressUserConversions) { 6093 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6094 return; 6095 6096 // C++ [over.match.funcs]p7: 6097 // In each case where a candidate is a function template, candidate 6098 // function template specializations are generated using template argument 6099 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6100 // candidate functions in the usual way.113) A given name can refer to one 6101 // or more function templates and also to a set of overloaded non-template 6102 // functions. In such a case, the candidate functions generated from each 6103 // function template are combined with the set of non-template candidate 6104 // functions. 6105 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6106 FunctionDecl *Specialization = nullptr; 6107 if (TemplateDeductionResult Result 6108 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 6109 Specialization, Info)) { 6110 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6111 Candidate.FoundDecl = FoundDecl; 6112 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6113 Candidate.Viable = false; 6114 Candidate.FailureKind = ovl_fail_bad_deduction; 6115 Candidate.IsSurrogate = false; 6116 Candidate.IgnoreObjectArgument = false; 6117 Candidate.ExplicitCallArguments = Args.size(); 6118 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6119 Info); 6120 return; 6121 } 6122 6123 // Add the function template specialization produced by template argument 6124 // deduction as a candidate. 6125 assert(Specialization && "Missing function template specialization?"); 6126 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6127 SuppressUserConversions); 6128 } 6129 6130 /// Determine whether this is an allowable conversion from the result 6131 /// of an explicit conversion operator to the expected type, per C++ 6132 /// [over.match.conv]p1 and [over.match.ref]p1. 6133 /// 6134 /// \param ConvType The return type of the conversion function. 6135 /// 6136 /// \param ToType The type we are converting to. 6137 /// 6138 /// \param AllowObjCPointerConversion Allow a conversion from one 6139 /// Objective-C pointer to another. 6140 /// 6141 /// \returns true if the conversion is allowable, false otherwise. 6142 static bool isAllowableExplicitConversion(Sema &S, 6143 QualType ConvType, QualType ToType, 6144 bool AllowObjCPointerConversion) { 6145 QualType ToNonRefType = ToType.getNonReferenceType(); 6146 6147 // Easy case: the types are the same. 6148 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6149 return true; 6150 6151 // Allow qualification conversions. 6152 bool ObjCLifetimeConversion; 6153 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6154 ObjCLifetimeConversion)) 6155 return true; 6156 6157 // If we're not allowed to consider Objective-C pointer conversions, 6158 // we're done. 6159 if (!AllowObjCPointerConversion) 6160 return false; 6161 6162 // Is this an Objective-C pointer conversion? 6163 bool IncompatibleObjC = false; 6164 QualType ConvertedType; 6165 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6166 IncompatibleObjC); 6167 } 6168 6169 /// AddConversionCandidate - Add a C++ conversion function as a 6170 /// candidate in the candidate set (C++ [over.match.conv], 6171 /// C++ [over.match.copy]). From is the expression we're converting from, 6172 /// and ToType is the type that we're eventually trying to convert to 6173 /// (which may or may not be the same type as the type that the 6174 /// conversion function produces). 6175 void 6176 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6177 DeclAccessPair FoundDecl, 6178 CXXRecordDecl *ActingContext, 6179 Expr *From, QualType ToType, 6180 OverloadCandidateSet& CandidateSet, 6181 bool AllowObjCConversionOnExplicit) { 6182 assert(!Conversion->getDescribedFunctionTemplate() && 6183 "Conversion function templates use AddTemplateConversionCandidate"); 6184 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6185 if (!CandidateSet.isNewCandidate(Conversion)) 6186 return; 6187 6188 // If the conversion function has an undeduced return type, trigger its 6189 // deduction now. 6190 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6191 if (DeduceReturnType(Conversion, From->getExprLoc())) 6192 return; 6193 ConvType = Conversion->getConversionType().getNonReferenceType(); 6194 } 6195 6196 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6197 // operator is only a candidate if its return type is the target type or 6198 // can be converted to the target type with a qualification conversion. 6199 if (Conversion->isExplicit() && 6200 !isAllowableExplicitConversion(*this, ConvType, ToType, 6201 AllowObjCConversionOnExplicit)) 6202 return; 6203 6204 // Overload resolution is always an unevaluated context. 6205 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6206 6207 // Add this candidate 6208 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6209 Candidate.FoundDecl = FoundDecl; 6210 Candidate.Function = Conversion; 6211 Candidate.IsSurrogate = false; 6212 Candidate.IgnoreObjectArgument = false; 6213 Candidate.FinalConversion.setAsIdentityConversion(); 6214 Candidate.FinalConversion.setFromType(ConvType); 6215 Candidate.FinalConversion.setAllToTypes(ToType); 6216 Candidate.Viable = true; 6217 Candidate.ExplicitCallArguments = 1; 6218 6219 // C++ [over.match.funcs]p4: 6220 // For conversion functions, the function is considered to be a member of 6221 // the class of the implicit implied object argument for the purpose of 6222 // defining the type of the implicit object parameter. 6223 // 6224 // Determine the implicit conversion sequence for the implicit 6225 // object parameter. 6226 QualType ImplicitParamType = From->getType(); 6227 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6228 ImplicitParamType = FromPtrType->getPointeeType(); 6229 CXXRecordDecl *ConversionContext 6230 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6231 6232 Candidate.Conversions[0] 6233 = TryObjectArgumentInitialization(*this, From->getType(), 6234 From->Classify(Context), 6235 Conversion, ConversionContext); 6236 6237 if (Candidate.Conversions[0].isBad()) { 6238 Candidate.Viable = false; 6239 Candidate.FailureKind = ovl_fail_bad_conversion; 6240 return; 6241 } 6242 6243 // We won't go through a user-defined type conversion function to convert a 6244 // derived to base as such conversions are given Conversion Rank. They only 6245 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6246 QualType FromCanon 6247 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6248 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6249 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 6250 Candidate.Viable = false; 6251 Candidate.FailureKind = ovl_fail_trivial_conversion; 6252 return; 6253 } 6254 6255 // To determine what the conversion from the result of calling the 6256 // conversion function to the type we're eventually trying to 6257 // convert to (ToType), we need to synthesize a call to the 6258 // conversion function and attempt copy initialization from it. This 6259 // makes sure that we get the right semantics with respect to 6260 // lvalues/rvalues and the type. Fortunately, we can allocate this 6261 // call on the stack and we don't need its arguments to be 6262 // well-formed. 6263 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6264 VK_LValue, From->getLocStart()); 6265 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6266 Context.getPointerType(Conversion->getType()), 6267 CK_FunctionToPointerDecay, 6268 &ConversionRef, VK_RValue); 6269 6270 QualType ConversionType = Conversion->getConversionType(); 6271 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 6272 Candidate.Viable = false; 6273 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6274 return; 6275 } 6276 6277 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6278 6279 // Note that it is safe to allocate CallExpr on the stack here because 6280 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6281 // allocator). 6282 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6283 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6284 From->getLocStart()); 6285 ImplicitConversionSequence ICS = 6286 TryCopyInitialization(*this, &Call, ToType, 6287 /*SuppressUserConversions=*/true, 6288 /*InOverloadResolution=*/false, 6289 /*AllowObjCWritebackConversion=*/false); 6290 6291 switch (ICS.getKind()) { 6292 case ImplicitConversionSequence::StandardConversion: 6293 Candidate.FinalConversion = ICS.Standard; 6294 6295 // C++ [over.ics.user]p3: 6296 // If the user-defined conversion is specified by a specialization of a 6297 // conversion function template, the second standard conversion sequence 6298 // shall have exact match rank. 6299 if (Conversion->getPrimaryTemplate() && 6300 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6301 Candidate.Viable = false; 6302 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6303 return; 6304 } 6305 6306 // C++0x [dcl.init.ref]p5: 6307 // In the second case, if the reference is an rvalue reference and 6308 // the second standard conversion sequence of the user-defined 6309 // conversion sequence includes an lvalue-to-rvalue conversion, the 6310 // program is ill-formed. 6311 if (ToType->isRValueReferenceType() && 6312 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6313 Candidate.Viable = false; 6314 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6315 return; 6316 } 6317 break; 6318 6319 case ImplicitConversionSequence::BadConversion: 6320 Candidate.Viable = false; 6321 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6322 return; 6323 6324 default: 6325 llvm_unreachable( 6326 "Can only end up with a standard conversion sequence or failure"); 6327 } 6328 6329 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6330 Candidate.Viable = false; 6331 Candidate.FailureKind = ovl_fail_enable_if; 6332 Candidate.DeductionFailure.Data = FailedAttr; 6333 return; 6334 } 6335 } 6336 6337 /// \brief Adds a conversion function template specialization 6338 /// candidate to the overload set, using template argument deduction 6339 /// to deduce the template arguments of the conversion function 6340 /// template from the type that we are converting to (C++ 6341 /// [temp.deduct.conv]). 6342 void 6343 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6344 DeclAccessPair FoundDecl, 6345 CXXRecordDecl *ActingDC, 6346 Expr *From, QualType ToType, 6347 OverloadCandidateSet &CandidateSet, 6348 bool AllowObjCConversionOnExplicit) { 6349 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6350 "Only conversion function templates permitted here"); 6351 6352 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6353 return; 6354 6355 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6356 CXXConversionDecl *Specialization = nullptr; 6357 if (TemplateDeductionResult Result 6358 = DeduceTemplateArguments(FunctionTemplate, ToType, 6359 Specialization, Info)) { 6360 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6361 Candidate.FoundDecl = FoundDecl; 6362 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6363 Candidate.Viable = false; 6364 Candidate.FailureKind = ovl_fail_bad_deduction; 6365 Candidate.IsSurrogate = false; 6366 Candidate.IgnoreObjectArgument = false; 6367 Candidate.ExplicitCallArguments = 1; 6368 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6369 Info); 6370 return; 6371 } 6372 6373 // Add the conversion function template specialization produced by 6374 // template argument deduction as a candidate. 6375 assert(Specialization && "Missing function template specialization?"); 6376 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6377 CandidateSet, AllowObjCConversionOnExplicit); 6378 } 6379 6380 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6381 /// converts the given @c Object to a function pointer via the 6382 /// conversion function @c Conversion, and then attempts to call it 6383 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6384 /// the type of function that we'll eventually be calling. 6385 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6386 DeclAccessPair FoundDecl, 6387 CXXRecordDecl *ActingContext, 6388 const FunctionProtoType *Proto, 6389 Expr *Object, 6390 ArrayRef<Expr *> Args, 6391 OverloadCandidateSet& CandidateSet) { 6392 if (!CandidateSet.isNewCandidate(Conversion)) 6393 return; 6394 6395 // Overload resolution is always an unevaluated context. 6396 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6397 6398 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6399 Candidate.FoundDecl = FoundDecl; 6400 Candidate.Function = nullptr; 6401 Candidate.Surrogate = Conversion; 6402 Candidate.Viable = true; 6403 Candidate.IsSurrogate = true; 6404 Candidate.IgnoreObjectArgument = false; 6405 Candidate.ExplicitCallArguments = Args.size(); 6406 6407 // Determine the implicit conversion sequence for the implicit 6408 // object parameter. 6409 ImplicitConversionSequence ObjectInit 6410 = TryObjectArgumentInitialization(*this, Object->getType(), 6411 Object->Classify(Context), 6412 Conversion, ActingContext); 6413 if (ObjectInit.isBad()) { 6414 Candidate.Viable = false; 6415 Candidate.FailureKind = ovl_fail_bad_conversion; 6416 Candidate.Conversions[0] = ObjectInit; 6417 return; 6418 } 6419 6420 // The first conversion is actually a user-defined conversion whose 6421 // first conversion is ObjectInit's standard conversion (which is 6422 // effectively a reference binding). Record it as such. 6423 Candidate.Conversions[0].setUserDefined(); 6424 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6425 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6426 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6427 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6428 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6429 Candidate.Conversions[0].UserDefined.After 6430 = Candidate.Conversions[0].UserDefined.Before; 6431 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6432 6433 // Find the 6434 unsigned NumParams = Proto->getNumParams(); 6435 6436 // (C++ 13.3.2p2): A candidate function having fewer than m 6437 // parameters is viable only if it has an ellipsis in its parameter 6438 // list (8.3.5). 6439 if (Args.size() > NumParams && !Proto->isVariadic()) { 6440 Candidate.Viable = false; 6441 Candidate.FailureKind = ovl_fail_too_many_arguments; 6442 return; 6443 } 6444 6445 // Function types don't have any default arguments, so just check if 6446 // we have enough arguments. 6447 if (Args.size() < NumParams) { 6448 // Not enough arguments. 6449 Candidate.Viable = false; 6450 Candidate.FailureKind = ovl_fail_too_few_arguments; 6451 return; 6452 } 6453 6454 // Determine the implicit conversion sequences for each of the 6455 // arguments. 6456 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6457 if (ArgIdx < NumParams) { 6458 // (C++ 13.3.2p3): for F to be a viable function, there shall 6459 // exist for each argument an implicit conversion sequence 6460 // (13.3.3.1) that converts that argument to the corresponding 6461 // parameter of F. 6462 QualType ParamType = Proto->getParamType(ArgIdx); 6463 Candidate.Conversions[ArgIdx + 1] 6464 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6465 /*SuppressUserConversions=*/false, 6466 /*InOverloadResolution=*/false, 6467 /*AllowObjCWritebackConversion=*/ 6468 getLangOpts().ObjCAutoRefCount); 6469 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6470 Candidate.Viable = false; 6471 Candidate.FailureKind = ovl_fail_bad_conversion; 6472 return; 6473 } 6474 } else { 6475 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6476 // argument for which there is no corresponding parameter is 6477 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6478 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6479 } 6480 } 6481 6482 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6483 Candidate.Viable = false; 6484 Candidate.FailureKind = ovl_fail_enable_if; 6485 Candidate.DeductionFailure.Data = FailedAttr; 6486 return; 6487 } 6488 } 6489 6490 /// \brief Add overload candidates for overloaded operators that are 6491 /// member functions. 6492 /// 6493 /// Add the overloaded operator candidates that are member functions 6494 /// for the operator Op that was used in an operator expression such 6495 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6496 /// CandidateSet will store the added overload candidates. (C++ 6497 /// [over.match.oper]). 6498 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6499 SourceLocation OpLoc, 6500 ArrayRef<Expr *> Args, 6501 OverloadCandidateSet& CandidateSet, 6502 SourceRange OpRange) { 6503 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6504 6505 // C++ [over.match.oper]p3: 6506 // For a unary operator @ with an operand of a type whose 6507 // cv-unqualified version is T1, and for a binary operator @ with 6508 // a left operand of a type whose cv-unqualified version is T1 and 6509 // a right operand of a type whose cv-unqualified version is T2, 6510 // three sets of candidate functions, designated member 6511 // candidates, non-member candidates and built-in candidates, are 6512 // constructed as follows: 6513 QualType T1 = Args[0]->getType(); 6514 6515 // -- If T1 is a complete class type or a class currently being 6516 // defined, the set of member candidates is the result of the 6517 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6518 // the set of member candidates is empty. 6519 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6520 // Complete the type if it can be completed. 6521 RequireCompleteType(OpLoc, T1, 0); 6522 // If the type is neither complete nor being defined, bail out now. 6523 if (!T1Rec->getDecl()->getDefinition()) 6524 return; 6525 6526 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6527 LookupQualifiedName(Operators, T1Rec->getDecl()); 6528 Operators.suppressDiagnostics(); 6529 6530 for (LookupResult::iterator Oper = Operators.begin(), 6531 OperEnd = Operators.end(); 6532 Oper != OperEnd; 6533 ++Oper) 6534 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6535 Args[0]->Classify(Context), 6536 Args.slice(1), 6537 CandidateSet, 6538 /* SuppressUserConversions = */ false); 6539 } 6540 } 6541 6542 /// AddBuiltinCandidate - Add a candidate for a built-in 6543 /// operator. ResultTy and ParamTys are the result and parameter types 6544 /// of the built-in candidate, respectively. Args and NumArgs are the 6545 /// arguments being passed to the candidate. IsAssignmentOperator 6546 /// should be true when this built-in candidate is an assignment 6547 /// operator. NumContextualBoolArguments is the number of arguments 6548 /// (at the beginning of the argument list) that will be contextually 6549 /// converted to bool. 6550 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6551 ArrayRef<Expr *> Args, 6552 OverloadCandidateSet& CandidateSet, 6553 bool IsAssignmentOperator, 6554 unsigned NumContextualBoolArguments) { 6555 // Overload resolution is always an unevaluated context. 6556 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6557 6558 // Add this candidate 6559 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6560 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 6561 Candidate.Function = nullptr; 6562 Candidate.IsSurrogate = false; 6563 Candidate.IgnoreObjectArgument = false; 6564 Candidate.BuiltinTypes.ResultTy = ResultTy; 6565 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6566 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6567 6568 // Determine the implicit conversion sequences for each of the 6569 // arguments. 6570 Candidate.Viable = true; 6571 Candidate.ExplicitCallArguments = Args.size(); 6572 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6573 // C++ [over.match.oper]p4: 6574 // For the built-in assignment operators, conversions of the 6575 // left operand are restricted as follows: 6576 // -- no temporaries are introduced to hold the left operand, and 6577 // -- no user-defined conversions are applied to the left 6578 // operand to achieve a type match with the left-most 6579 // parameter of a built-in candidate. 6580 // 6581 // We block these conversions by turning off user-defined 6582 // conversions, since that is the only way that initialization of 6583 // a reference to a non-class type can occur from something that 6584 // is not of the same type. 6585 if (ArgIdx < NumContextualBoolArguments) { 6586 assert(ParamTys[ArgIdx] == Context.BoolTy && 6587 "Contextual conversion to bool requires bool type"); 6588 Candidate.Conversions[ArgIdx] 6589 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6590 } else { 6591 Candidate.Conversions[ArgIdx] 6592 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6593 ArgIdx == 0 && IsAssignmentOperator, 6594 /*InOverloadResolution=*/false, 6595 /*AllowObjCWritebackConversion=*/ 6596 getLangOpts().ObjCAutoRefCount); 6597 } 6598 if (Candidate.Conversions[ArgIdx].isBad()) { 6599 Candidate.Viable = false; 6600 Candidate.FailureKind = ovl_fail_bad_conversion; 6601 break; 6602 } 6603 } 6604 } 6605 6606 namespace { 6607 6608 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6609 /// candidate operator functions for built-in operators (C++ 6610 /// [over.built]). The types are separated into pointer types and 6611 /// enumeration types. 6612 class BuiltinCandidateTypeSet { 6613 /// TypeSet - A set of types. 6614 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6615 6616 /// PointerTypes - The set of pointer types that will be used in the 6617 /// built-in candidates. 6618 TypeSet PointerTypes; 6619 6620 /// MemberPointerTypes - The set of member pointer types that will be 6621 /// used in the built-in candidates. 6622 TypeSet MemberPointerTypes; 6623 6624 /// EnumerationTypes - The set of enumeration types that will be 6625 /// used in the built-in candidates. 6626 TypeSet EnumerationTypes; 6627 6628 /// \brief The set of vector types that will be used in the built-in 6629 /// candidates. 6630 TypeSet VectorTypes; 6631 6632 /// \brief A flag indicating non-record types are viable candidates 6633 bool HasNonRecordTypes; 6634 6635 /// \brief A flag indicating whether either arithmetic or enumeration types 6636 /// were present in the candidate set. 6637 bool HasArithmeticOrEnumeralTypes; 6638 6639 /// \brief A flag indicating whether the nullptr type was present in the 6640 /// candidate set. 6641 bool HasNullPtrType; 6642 6643 /// Sema - The semantic analysis instance where we are building the 6644 /// candidate type set. 6645 Sema &SemaRef; 6646 6647 /// Context - The AST context in which we will build the type sets. 6648 ASTContext &Context; 6649 6650 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6651 const Qualifiers &VisibleQuals); 6652 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6653 6654 public: 6655 /// iterator - Iterates through the types that are part of the set. 6656 typedef TypeSet::iterator iterator; 6657 6658 BuiltinCandidateTypeSet(Sema &SemaRef) 6659 : HasNonRecordTypes(false), 6660 HasArithmeticOrEnumeralTypes(false), 6661 HasNullPtrType(false), 6662 SemaRef(SemaRef), 6663 Context(SemaRef.Context) { } 6664 6665 void AddTypesConvertedFrom(QualType Ty, 6666 SourceLocation Loc, 6667 bool AllowUserConversions, 6668 bool AllowExplicitConversions, 6669 const Qualifiers &VisibleTypeConversionsQuals); 6670 6671 /// pointer_begin - First pointer type found; 6672 iterator pointer_begin() { return PointerTypes.begin(); } 6673 6674 /// pointer_end - Past the last pointer type found; 6675 iterator pointer_end() { return PointerTypes.end(); } 6676 6677 /// member_pointer_begin - First member pointer type found; 6678 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6679 6680 /// member_pointer_end - Past the last member pointer type found; 6681 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6682 6683 /// enumeration_begin - First enumeration type found; 6684 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6685 6686 /// enumeration_end - Past the last enumeration type found; 6687 iterator enumeration_end() { return EnumerationTypes.end(); } 6688 6689 iterator vector_begin() { return VectorTypes.begin(); } 6690 iterator vector_end() { return VectorTypes.end(); } 6691 6692 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6693 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6694 bool hasNullPtrType() const { return HasNullPtrType; } 6695 }; 6696 6697 } // end anonymous namespace 6698 6699 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6700 /// the set of pointer types along with any more-qualified variants of 6701 /// that type. For example, if @p Ty is "int const *", this routine 6702 /// will add "int const *", "int const volatile *", "int const 6703 /// restrict *", and "int const volatile restrict *" to the set of 6704 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6705 /// false otherwise. 6706 /// 6707 /// FIXME: what to do about extended qualifiers? 6708 bool 6709 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6710 const Qualifiers &VisibleQuals) { 6711 6712 // Insert this type. 6713 if (!PointerTypes.insert(Ty).second) 6714 return false; 6715 6716 QualType PointeeTy; 6717 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6718 bool buildObjCPtr = false; 6719 if (!PointerTy) { 6720 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6721 PointeeTy = PTy->getPointeeType(); 6722 buildObjCPtr = true; 6723 } else { 6724 PointeeTy = PointerTy->getPointeeType(); 6725 } 6726 6727 // Don't add qualified variants of arrays. For one, they're not allowed 6728 // (the qualifier would sink to the element type), and for another, the 6729 // only overload situation where it matters is subscript or pointer +- int, 6730 // and those shouldn't have qualifier variants anyway. 6731 if (PointeeTy->isArrayType()) 6732 return true; 6733 6734 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6735 bool hasVolatile = VisibleQuals.hasVolatile(); 6736 bool hasRestrict = VisibleQuals.hasRestrict(); 6737 6738 // Iterate through all strict supersets of BaseCVR. 6739 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6740 if ((CVR | BaseCVR) != CVR) continue; 6741 // Skip over volatile if no volatile found anywhere in the types. 6742 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6743 6744 // Skip over restrict if no restrict found anywhere in the types, or if 6745 // the type cannot be restrict-qualified. 6746 if ((CVR & Qualifiers::Restrict) && 6747 (!hasRestrict || 6748 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6749 continue; 6750 6751 // Build qualified pointee type. 6752 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6753 6754 // Build qualified pointer type. 6755 QualType QPointerTy; 6756 if (!buildObjCPtr) 6757 QPointerTy = Context.getPointerType(QPointeeTy); 6758 else 6759 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6760 6761 // Insert qualified pointer type. 6762 PointerTypes.insert(QPointerTy); 6763 } 6764 6765 return true; 6766 } 6767 6768 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6769 /// to the set of pointer types along with any more-qualified variants of 6770 /// that type. For example, if @p Ty is "int const *", this routine 6771 /// will add "int const *", "int const volatile *", "int const 6772 /// restrict *", and "int const volatile restrict *" to the set of 6773 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6774 /// false otherwise. 6775 /// 6776 /// FIXME: what to do about extended qualifiers? 6777 bool 6778 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6779 QualType Ty) { 6780 // Insert this type. 6781 if (!MemberPointerTypes.insert(Ty).second) 6782 return false; 6783 6784 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6785 assert(PointerTy && "type was not a member pointer type!"); 6786 6787 QualType PointeeTy = PointerTy->getPointeeType(); 6788 // Don't add qualified variants of arrays. For one, they're not allowed 6789 // (the qualifier would sink to the element type), and for another, the 6790 // only overload situation where it matters is subscript or pointer +- int, 6791 // and those shouldn't have qualifier variants anyway. 6792 if (PointeeTy->isArrayType()) 6793 return true; 6794 const Type *ClassTy = PointerTy->getClass(); 6795 6796 // Iterate through all strict supersets of the pointee type's CVR 6797 // qualifiers. 6798 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6799 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6800 if ((CVR | BaseCVR) != CVR) continue; 6801 6802 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6803 MemberPointerTypes.insert( 6804 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6805 } 6806 6807 return true; 6808 } 6809 6810 /// AddTypesConvertedFrom - Add each of the types to which the type @p 6811 /// Ty can be implicit converted to the given set of @p Types. We're 6812 /// primarily interested in pointer types and enumeration types. We also 6813 /// take member pointer types, for the conditional operator. 6814 /// AllowUserConversions is true if we should look at the conversion 6815 /// functions of a class type, and AllowExplicitConversions if we 6816 /// should also include the explicit conversion functions of a class 6817 /// type. 6818 void 6819 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6820 SourceLocation Loc, 6821 bool AllowUserConversions, 6822 bool AllowExplicitConversions, 6823 const Qualifiers &VisibleQuals) { 6824 // Only deal with canonical types. 6825 Ty = Context.getCanonicalType(Ty); 6826 6827 // Look through reference types; they aren't part of the type of an 6828 // expression for the purposes of conversions. 6829 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6830 Ty = RefTy->getPointeeType(); 6831 6832 // If we're dealing with an array type, decay to the pointer. 6833 if (Ty->isArrayType()) 6834 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6835 6836 // Otherwise, we don't care about qualifiers on the type. 6837 Ty = Ty.getLocalUnqualifiedType(); 6838 6839 // Flag if we ever add a non-record type. 6840 const RecordType *TyRec = Ty->getAs<RecordType>(); 6841 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6842 6843 // Flag if we encounter an arithmetic type. 6844 HasArithmeticOrEnumeralTypes = 6845 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6846 6847 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6848 PointerTypes.insert(Ty); 6849 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6850 // Insert our type, and its more-qualified variants, into the set 6851 // of types. 6852 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6853 return; 6854 } else if (Ty->isMemberPointerType()) { 6855 // Member pointers are far easier, since the pointee can't be converted. 6856 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6857 return; 6858 } else if (Ty->isEnumeralType()) { 6859 HasArithmeticOrEnumeralTypes = true; 6860 EnumerationTypes.insert(Ty); 6861 } else if (Ty->isVectorType()) { 6862 // We treat vector types as arithmetic types in many contexts as an 6863 // extension. 6864 HasArithmeticOrEnumeralTypes = true; 6865 VectorTypes.insert(Ty); 6866 } else if (Ty->isNullPtrType()) { 6867 HasNullPtrType = true; 6868 } else if (AllowUserConversions && TyRec) { 6869 // No conversion functions in incomplete types. 6870 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6871 return; 6872 6873 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6874 std::pair<CXXRecordDecl::conversion_iterator, 6875 CXXRecordDecl::conversion_iterator> 6876 Conversions = ClassDecl->getVisibleConversionFunctions(); 6877 for (CXXRecordDecl::conversion_iterator 6878 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6879 NamedDecl *D = I.getDecl(); 6880 if (isa<UsingShadowDecl>(D)) 6881 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6882 6883 // Skip conversion function templates; they don't tell us anything 6884 // about which builtin types we can convert to. 6885 if (isa<FunctionTemplateDecl>(D)) 6886 continue; 6887 6888 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6889 if (AllowExplicitConversions || !Conv->isExplicit()) { 6890 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6891 VisibleQuals); 6892 } 6893 } 6894 } 6895 } 6896 6897 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6898 /// the volatile- and non-volatile-qualified assignment operators for the 6899 /// given type to the candidate set. 6900 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6901 QualType T, 6902 ArrayRef<Expr *> Args, 6903 OverloadCandidateSet &CandidateSet) { 6904 QualType ParamTypes[2]; 6905 6906 // T& operator=(T&, T) 6907 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6908 ParamTypes[1] = T; 6909 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6910 /*IsAssignmentOperator=*/true); 6911 6912 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6913 // volatile T& operator=(volatile T&, T) 6914 ParamTypes[0] 6915 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6916 ParamTypes[1] = T; 6917 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6918 /*IsAssignmentOperator=*/true); 6919 } 6920 } 6921 6922 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6923 /// if any, found in visible type conversion functions found in ArgExpr's type. 6924 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6925 Qualifiers VRQuals; 6926 const RecordType *TyRec; 6927 if (const MemberPointerType *RHSMPType = 6928 ArgExpr->getType()->getAs<MemberPointerType>()) 6929 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6930 else 6931 TyRec = ArgExpr->getType()->getAs<RecordType>(); 6932 if (!TyRec) { 6933 // Just to be safe, assume the worst case. 6934 VRQuals.addVolatile(); 6935 VRQuals.addRestrict(); 6936 return VRQuals; 6937 } 6938 6939 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6940 if (!ClassDecl->hasDefinition()) 6941 return VRQuals; 6942 6943 std::pair<CXXRecordDecl::conversion_iterator, 6944 CXXRecordDecl::conversion_iterator> 6945 Conversions = ClassDecl->getVisibleConversionFunctions(); 6946 6947 for (CXXRecordDecl::conversion_iterator 6948 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6949 NamedDecl *D = I.getDecl(); 6950 if (isa<UsingShadowDecl>(D)) 6951 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6952 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6953 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 6954 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 6955 CanTy = ResTypeRef->getPointeeType(); 6956 // Need to go down the pointer/mempointer chain and add qualifiers 6957 // as see them. 6958 bool done = false; 6959 while (!done) { 6960 if (CanTy.isRestrictQualified()) 6961 VRQuals.addRestrict(); 6962 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 6963 CanTy = ResTypePtr->getPointeeType(); 6964 else if (const MemberPointerType *ResTypeMPtr = 6965 CanTy->getAs<MemberPointerType>()) 6966 CanTy = ResTypeMPtr->getPointeeType(); 6967 else 6968 done = true; 6969 if (CanTy.isVolatileQualified()) 6970 VRQuals.addVolatile(); 6971 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 6972 return VRQuals; 6973 } 6974 } 6975 } 6976 return VRQuals; 6977 } 6978 6979 namespace { 6980 6981 /// \brief Helper class to manage the addition of builtin operator overload 6982 /// candidates. It provides shared state and utility methods used throughout 6983 /// the process, as well as a helper method to add each group of builtin 6984 /// operator overloads from the standard to a candidate set. 6985 class BuiltinOperatorOverloadBuilder { 6986 // Common instance state available to all overload candidate addition methods. 6987 Sema &S; 6988 ArrayRef<Expr *> Args; 6989 Qualifiers VisibleTypeConversionsQuals; 6990 bool HasArithmeticOrEnumeralCandidateType; 6991 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 6992 OverloadCandidateSet &CandidateSet; 6993 6994 // Define some constants used to index and iterate over the arithemetic types 6995 // provided via the getArithmeticType() method below. 6996 // The "promoted arithmetic types" are the arithmetic 6997 // types are that preserved by promotion (C++ [over.built]p2). 6998 static const unsigned FirstIntegralType = 3; 6999 static const unsigned LastIntegralType = 20; 7000 static const unsigned FirstPromotedIntegralType = 3, 7001 LastPromotedIntegralType = 11; 7002 static const unsigned FirstPromotedArithmeticType = 0, 7003 LastPromotedArithmeticType = 11; 7004 static const unsigned NumArithmeticTypes = 20; 7005 7006 /// \brief Get the canonical type for a given arithmetic type index. 7007 CanQualType getArithmeticType(unsigned index) { 7008 assert(index < NumArithmeticTypes); 7009 static CanQualType ASTContext::* const 7010 ArithmeticTypes[NumArithmeticTypes] = { 7011 // Start of promoted types. 7012 &ASTContext::FloatTy, 7013 &ASTContext::DoubleTy, 7014 &ASTContext::LongDoubleTy, 7015 7016 // Start of integral types. 7017 &ASTContext::IntTy, 7018 &ASTContext::LongTy, 7019 &ASTContext::LongLongTy, 7020 &ASTContext::Int128Ty, 7021 &ASTContext::UnsignedIntTy, 7022 &ASTContext::UnsignedLongTy, 7023 &ASTContext::UnsignedLongLongTy, 7024 &ASTContext::UnsignedInt128Ty, 7025 // End of promoted types. 7026 7027 &ASTContext::BoolTy, 7028 &ASTContext::CharTy, 7029 &ASTContext::WCharTy, 7030 &ASTContext::Char16Ty, 7031 &ASTContext::Char32Ty, 7032 &ASTContext::SignedCharTy, 7033 &ASTContext::ShortTy, 7034 &ASTContext::UnsignedCharTy, 7035 &ASTContext::UnsignedShortTy, 7036 // End of integral types. 7037 // FIXME: What about complex? What about half? 7038 }; 7039 return S.Context.*ArithmeticTypes[index]; 7040 } 7041 7042 /// \brief Gets the canonical type resulting from the usual arithemetic 7043 /// converions for the given arithmetic types. 7044 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 7045 // Accelerator table for performing the usual arithmetic conversions. 7046 // The rules are basically: 7047 // - if either is floating-point, use the wider floating-point 7048 // - if same signedness, use the higher rank 7049 // - if same size, use unsigned of the higher rank 7050 // - use the larger type 7051 // These rules, together with the axiom that higher ranks are 7052 // never smaller, are sufficient to precompute all of these results 7053 // *except* when dealing with signed types of higher rank. 7054 // (we could precompute SLL x UI for all known platforms, but it's 7055 // better not to make any assumptions). 7056 // We assume that int128 has a higher rank than long long on all platforms. 7057 enum PromotedType { 7058 Dep=-1, 7059 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 7060 }; 7061 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 7062 [LastPromotedArithmeticType] = { 7063 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 7064 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 7065 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 7066 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 7067 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 7068 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 7069 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 7070 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 7071 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 7072 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 7073 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 7074 }; 7075 7076 assert(L < LastPromotedArithmeticType); 7077 assert(R < LastPromotedArithmeticType); 7078 int Idx = ConversionsTable[L][R]; 7079 7080 // Fast path: the table gives us a concrete answer. 7081 if (Idx != Dep) return getArithmeticType(Idx); 7082 7083 // Slow path: we need to compare widths. 7084 // An invariant is that the signed type has higher rank. 7085 CanQualType LT = getArithmeticType(L), 7086 RT = getArithmeticType(R); 7087 unsigned LW = S.Context.getIntWidth(LT), 7088 RW = S.Context.getIntWidth(RT); 7089 7090 // If they're different widths, use the signed type. 7091 if (LW > RW) return LT; 7092 else if (LW < RW) return RT; 7093 7094 // Otherwise, use the unsigned type of the signed type's rank. 7095 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 7096 assert(L == SLL || R == SLL); 7097 return S.Context.UnsignedLongLongTy; 7098 } 7099 7100 /// \brief Helper method to factor out the common pattern of adding overloads 7101 /// for '++' and '--' builtin operators. 7102 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7103 bool HasVolatile, 7104 bool HasRestrict) { 7105 QualType ParamTypes[2] = { 7106 S.Context.getLValueReferenceType(CandidateTy), 7107 S.Context.IntTy 7108 }; 7109 7110 // Non-volatile version. 7111 if (Args.size() == 1) 7112 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7113 else 7114 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7115 7116 // Use a heuristic to reduce number of builtin candidates in the set: 7117 // add volatile version only if there are conversions to a volatile type. 7118 if (HasVolatile) { 7119 ParamTypes[0] = 7120 S.Context.getLValueReferenceType( 7121 S.Context.getVolatileType(CandidateTy)); 7122 if (Args.size() == 1) 7123 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7124 else 7125 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7126 } 7127 7128 // Add restrict version only if there are conversions to a restrict type 7129 // and our candidate type is a non-restrict-qualified pointer. 7130 if (HasRestrict && CandidateTy->isAnyPointerType() && 7131 !CandidateTy.isRestrictQualified()) { 7132 ParamTypes[0] 7133 = S.Context.getLValueReferenceType( 7134 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7135 if (Args.size() == 1) 7136 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7137 else 7138 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7139 7140 if (HasVolatile) { 7141 ParamTypes[0] 7142 = S.Context.getLValueReferenceType( 7143 S.Context.getCVRQualifiedType(CandidateTy, 7144 (Qualifiers::Volatile | 7145 Qualifiers::Restrict))); 7146 if (Args.size() == 1) 7147 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7148 else 7149 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7150 } 7151 } 7152 7153 } 7154 7155 public: 7156 BuiltinOperatorOverloadBuilder( 7157 Sema &S, ArrayRef<Expr *> Args, 7158 Qualifiers VisibleTypeConversionsQuals, 7159 bool HasArithmeticOrEnumeralCandidateType, 7160 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7161 OverloadCandidateSet &CandidateSet) 7162 : S(S), Args(Args), 7163 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7164 HasArithmeticOrEnumeralCandidateType( 7165 HasArithmeticOrEnumeralCandidateType), 7166 CandidateTypes(CandidateTypes), 7167 CandidateSet(CandidateSet) { 7168 // Validate some of our static helper constants in debug builds. 7169 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7170 "Invalid first promoted integral type"); 7171 assert(getArithmeticType(LastPromotedIntegralType - 1) 7172 == S.Context.UnsignedInt128Ty && 7173 "Invalid last promoted integral type"); 7174 assert(getArithmeticType(FirstPromotedArithmeticType) 7175 == S.Context.FloatTy && 7176 "Invalid first promoted arithmetic type"); 7177 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7178 == S.Context.UnsignedInt128Ty && 7179 "Invalid last promoted arithmetic type"); 7180 } 7181 7182 // C++ [over.built]p3: 7183 // 7184 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7185 // is either volatile or empty, there exist candidate operator 7186 // functions of the form 7187 // 7188 // VQ T& operator++(VQ T&); 7189 // T operator++(VQ T&, int); 7190 // 7191 // C++ [over.built]p4: 7192 // 7193 // For every pair (T, VQ), where T is an arithmetic type other 7194 // than bool, and VQ is either volatile or empty, there exist 7195 // candidate operator functions of the form 7196 // 7197 // VQ T& operator--(VQ T&); 7198 // T operator--(VQ T&, int); 7199 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7200 if (!HasArithmeticOrEnumeralCandidateType) 7201 return; 7202 7203 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7204 Arith < NumArithmeticTypes; ++Arith) { 7205 addPlusPlusMinusMinusStyleOverloads( 7206 getArithmeticType(Arith), 7207 VisibleTypeConversionsQuals.hasVolatile(), 7208 VisibleTypeConversionsQuals.hasRestrict()); 7209 } 7210 } 7211 7212 // C++ [over.built]p5: 7213 // 7214 // For every pair (T, VQ), where T is a cv-qualified or 7215 // cv-unqualified object type, and VQ is either volatile or 7216 // empty, there exist candidate operator functions of the form 7217 // 7218 // T*VQ& operator++(T*VQ&); 7219 // T*VQ& operator--(T*VQ&); 7220 // T* operator++(T*VQ&, int); 7221 // T* operator--(T*VQ&, int); 7222 void addPlusPlusMinusMinusPointerOverloads() { 7223 for (BuiltinCandidateTypeSet::iterator 7224 Ptr = CandidateTypes[0].pointer_begin(), 7225 PtrEnd = CandidateTypes[0].pointer_end(); 7226 Ptr != PtrEnd; ++Ptr) { 7227 // Skip pointer types that aren't pointers to object types. 7228 if (!(*Ptr)->getPointeeType()->isObjectType()) 7229 continue; 7230 7231 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7232 (!(*Ptr).isVolatileQualified() && 7233 VisibleTypeConversionsQuals.hasVolatile()), 7234 (!(*Ptr).isRestrictQualified() && 7235 VisibleTypeConversionsQuals.hasRestrict())); 7236 } 7237 } 7238 7239 // C++ [over.built]p6: 7240 // For every cv-qualified or cv-unqualified object type T, there 7241 // exist candidate operator functions of the form 7242 // 7243 // T& operator*(T*); 7244 // 7245 // C++ [over.built]p7: 7246 // For every function type T that does not have cv-qualifiers or a 7247 // ref-qualifier, there exist candidate operator functions of the form 7248 // T& operator*(T*); 7249 void addUnaryStarPointerOverloads() { 7250 for (BuiltinCandidateTypeSet::iterator 7251 Ptr = CandidateTypes[0].pointer_begin(), 7252 PtrEnd = CandidateTypes[0].pointer_end(); 7253 Ptr != PtrEnd; ++Ptr) { 7254 QualType ParamTy = *Ptr; 7255 QualType PointeeTy = ParamTy->getPointeeType(); 7256 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7257 continue; 7258 7259 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7260 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7261 continue; 7262 7263 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7264 &ParamTy, Args, CandidateSet); 7265 } 7266 } 7267 7268 // C++ [over.built]p9: 7269 // For every promoted arithmetic type T, there exist candidate 7270 // operator functions of the form 7271 // 7272 // T operator+(T); 7273 // T operator-(T); 7274 void addUnaryPlusOrMinusArithmeticOverloads() { 7275 if (!HasArithmeticOrEnumeralCandidateType) 7276 return; 7277 7278 for (unsigned Arith = FirstPromotedArithmeticType; 7279 Arith < LastPromotedArithmeticType; ++Arith) { 7280 QualType ArithTy = getArithmeticType(Arith); 7281 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7282 } 7283 7284 // Extension: We also add these operators for vector types. 7285 for (BuiltinCandidateTypeSet::iterator 7286 Vec = CandidateTypes[0].vector_begin(), 7287 VecEnd = CandidateTypes[0].vector_end(); 7288 Vec != VecEnd; ++Vec) { 7289 QualType VecTy = *Vec; 7290 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7291 } 7292 } 7293 7294 // C++ [over.built]p8: 7295 // For every type T, there exist candidate operator functions of 7296 // the form 7297 // 7298 // T* operator+(T*); 7299 void addUnaryPlusPointerOverloads() { 7300 for (BuiltinCandidateTypeSet::iterator 7301 Ptr = CandidateTypes[0].pointer_begin(), 7302 PtrEnd = CandidateTypes[0].pointer_end(); 7303 Ptr != PtrEnd; ++Ptr) { 7304 QualType ParamTy = *Ptr; 7305 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7306 } 7307 } 7308 7309 // C++ [over.built]p10: 7310 // For every promoted integral type T, there exist candidate 7311 // operator functions of the form 7312 // 7313 // T operator~(T); 7314 void addUnaryTildePromotedIntegralOverloads() { 7315 if (!HasArithmeticOrEnumeralCandidateType) 7316 return; 7317 7318 for (unsigned Int = FirstPromotedIntegralType; 7319 Int < LastPromotedIntegralType; ++Int) { 7320 QualType IntTy = getArithmeticType(Int); 7321 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7322 } 7323 7324 // Extension: We also add this operator for vector types. 7325 for (BuiltinCandidateTypeSet::iterator 7326 Vec = CandidateTypes[0].vector_begin(), 7327 VecEnd = CandidateTypes[0].vector_end(); 7328 Vec != VecEnd; ++Vec) { 7329 QualType VecTy = *Vec; 7330 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7331 } 7332 } 7333 7334 // C++ [over.match.oper]p16: 7335 // For every pointer to member type T, there exist candidate operator 7336 // functions of the form 7337 // 7338 // bool operator==(T,T); 7339 // bool operator!=(T,T); 7340 void addEqualEqualOrNotEqualMemberPointerOverloads() { 7341 /// Set of (canonical) types that we've already handled. 7342 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7343 7344 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7345 for (BuiltinCandidateTypeSet::iterator 7346 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7347 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7348 MemPtr != MemPtrEnd; 7349 ++MemPtr) { 7350 // Don't add the same builtin candidate twice. 7351 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7352 continue; 7353 7354 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7355 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7356 } 7357 } 7358 } 7359 7360 // C++ [over.built]p15: 7361 // 7362 // For every T, where T is an enumeration type, a pointer type, or 7363 // std::nullptr_t, there exist candidate operator functions of the form 7364 // 7365 // bool operator<(T, T); 7366 // bool operator>(T, T); 7367 // bool operator<=(T, T); 7368 // bool operator>=(T, T); 7369 // bool operator==(T, T); 7370 // bool operator!=(T, T); 7371 void addRelationalPointerOrEnumeralOverloads() { 7372 // C++ [over.match.oper]p3: 7373 // [...]the built-in candidates include all of the candidate operator 7374 // functions defined in 13.6 that, compared to the given operator, [...] 7375 // do not have the same parameter-type-list as any non-template non-member 7376 // candidate. 7377 // 7378 // Note that in practice, this only affects enumeration types because there 7379 // aren't any built-in candidates of record type, and a user-defined operator 7380 // must have an operand of record or enumeration type. Also, the only other 7381 // overloaded operator with enumeration arguments, operator=, 7382 // cannot be overloaded for enumeration types, so this is the only place 7383 // where we must suppress candidates like this. 7384 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7385 UserDefinedBinaryOperators; 7386 7387 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7388 if (CandidateTypes[ArgIdx].enumeration_begin() != 7389 CandidateTypes[ArgIdx].enumeration_end()) { 7390 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7391 CEnd = CandidateSet.end(); 7392 C != CEnd; ++C) { 7393 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7394 continue; 7395 7396 if (C->Function->isFunctionTemplateSpecialization()) 7397 continue; 7398 7399 QualType FirstParamType = 7400 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7401 QualType SecondParamType = 7402 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7403 7404 // Skip if either parameter isn't of enumeral type. 7405 if (!FirstParamType->isEnumeralType() || 7406 !SecondParamType->isEnumeralType()) 7407 continue; 7408 7409 // Add this operator to the set of known user-defined operators. 7410 UserDefinedBinaryOperators.insert( 7411 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7412 S.Context.getCanonicalType(SecondParamType))); 7413 } 7414 } 7415 } 7416 7417 /// Set of (canonical) types that we've already handled. 7418 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7419 7420 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7421 for (BuiltinCandidateTypeSet::iterator 7422 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7423 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7424 Ptr != PtrEnd; ++Ptr) { 7425 // Don't add the same builtin candidate twice. 7426 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7427 continue; 7428 7429 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7430 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7431 } 7432 for (BuiltinCandidateTypeSet::iterator 7433 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7434 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7435 Enum != EnumEnd; ++Enum) { 7436 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7437 7438 // Don't add the same builtin candidate twice, or if a user defined 7439 // candidate exists. 7440 if (!AddedTypes.insert(CanonType).second || 7441 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7442 CanonType))) 7443 continue; 7444 7445 QualType ParamTypes[2] = { *Enum, *Enum }; 7446 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7447 } 7448 7449 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7450 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7451 if (AddedTypes.insert(NullPtrTy).second && 7452 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7453 NullPtrTy))) { 7454 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7455 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7456 CandidateSet); 7457 } 7458 } 7459 } 7460 } 7461 7462 // C++ [over.built]p13: 7463 // 7464 // For every cv-qualified or cv-unqualified object type T 7465 // there exist candidate operator functions of the form 7466 // 7467 // T* operator+(T*, ptrdiff_t); 7468 // T& operator[](T*, ptrdiff_t); [BELOW] 7469 // T* operator-(T*, ptrdiff_t); 7470 // T* operator+(ptrdiff_t, T*); 7471 // T& operator[](ptrdiff_t, T*); [BELOW] 7472 // 7473 // C++ [over.built]p14: 7474 // 7475 // For every T, where T is a pointer to object type, there 7476 // exist candidate operator functions of the form 7477 // 7478 // ptrdiff_t operator-(T, T); 7479 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7480 /// Set of (canonical) types that we've already handled. 7481 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7482 7483 for (int Arg = 0; Arg < 2; ++Arg) { 7484 QualType AsymetricParamTypes[2] = { 7485 S.Context.getPointerDiffType(), 7486 S.Context.getPointerDiffType(), 7487 }; 7488 for (BuiltinCandidateTypeSet::iterator 7489 Ptr = CandidateTypes[Arg].pointer_begin(), 7490 PtrEnd = CandidateTypes[Arg].pointer_end(); 7491 Ptr != PtrEnd; ++Ptr) { 7492 QualType PointeeTy = (*Ptr)->getPointeeType(); 7493 if (!PointeeTy->isObjectType()) 7494 continue; 7495 7496 AsymetricParamTypes[Arg] = *Ptr; 7497 if (Arg == 0 || Op == OO_Plus) { 7498 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7499 // T* operator+(ptrdiff_t, T*); 7500 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet); 7501 } 7502 if (Op == OO_Minus) { 7503 // ptrdiff_t operator-(T, T); 7504 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7505 continue; 7506 7507 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7508 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7509 Args, CandidateSet); 7510 } 7511 } 7512 } 7513 } 7514 7515 // C++ [over.built]p12: 7516 // 7517 // For every pair of promoted arithmetic types L and R, there 7518 // exist candidate operator functions of the form 7519 // 7520 // LR operator*(L, R); 7521 // LR operator/(L, R); 7522 // LR operator+(L, R); 7523 // LR operator-(L, R); 7524 // bool operator<(L, R); 7525 // bool operator>(L, R); 7526 // bool operator<=(L, R); 7527 // bool operator>=(L, R); 7528 // bool operator==(L, R); 7529 // bool operator!=(L, R); 7530 // 7531 // where LR is the result of the usual arithmetic conversions 7532 // between types L and R. 7533 // 7534 // C++ [over.built]p24: 7535 // 7536 // For every pair of promoted arithmetic types L and R, there exist 7537 // candidate operator functions of the form 7538 // 7539 // LR operator?(bool, L, R); 7540 // 7541 // where LR is the result of the usual arithmetic conversions 7542 // between types L and R. 7543 // Our candidates ignore the first parameter. 7544 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7545 if (!HasArithmeticOrEnumeralCandidateType) 7546 return; 7547 7548 for (unsigned Left = FirstPromotedArithmeticType; 7549 Left < LastPromotedArithmeticType; ++Left) { 7550 for (unsigned Right = FirstPromotedArithmeticType; 7551 Right < LastPromotedArithmeticType; ++Right) { 7552 QualType LandR[2] = { getArithmeticType(Left), 7553 getArithmeticType(Right) }; 7554 QualType Result = 7555 isComparison ? S.Context.BoolTy 7556 : getUsualArithmeticConversions(Left, Right); 7557 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7558 } 7559 } 7560 7561 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7562 // conditional operator for vector types. 7563 for (BuiltinCandidateTypeSet::iterator 7564 Vec1 = CandidateTypes[0].vector_begin(), 7565 Vec1End = CandidateTypes[0].vector_end(); 7566 Vec1 != Vec1End; ++Vec1) { 7567 for (BuiltinCandidateTypeSet::iterator 7568 Vec2 = CandidateTypes[1].vector_begin(), 7569 Vec2End = CandidateTypes[1].vector_end(); 7570 Vec2 != Vec2End; ++Vec2) { 7571 QualType LandR[2] = { *Vec1, *Vec2 }; 7572 QualType Result = S.Context.BoolTy; 7573 if (!isComparison) { 7574 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7575 Result = *Vec1; 7576 else 7577 Result = *Vec2; 7578 } 7579 7580 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7581 } 7582 } 7583 } 7584 7585 // C++ [over.built]p17: 7586 // 7587 // For every pair of promoted integral types L and R, there 7588 // exist candidate operator functions of the form 7589 // 7590 // LR operator%(L, R); 7591 // LR operator&(L, R); 7592 // LR operator^(L, R); 7593 // LR operator|(L, R); 7594 // L operator<<(L, R); 7595 // L operator>>(L, R); 7596 // 7597 // where LR is the result of the usual arithmetic conversions 7598 // between types L and R. 7599 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7600 if (!HasArithmeticOrEnumeralCandidateType) 7601 return; 7602 7603 for (unsigned Left = FirstPromotedIntegralType; 7604 Left < LastPromotedIntegralType; ++Left) { 7605 for (unsigned Right = FirstPromotedIntegralType; 7606 Right < LastPromotedIntegralType; ++Right) { 7607 QualType LandR[2] = { getArithmeticType(Left), 7608 getArithmeticType(Right) }; 7609 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7610 ? LandR[0] 7611 : getUsualArithmeticConversions(Left, Right); 7612 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7613 } 7614 } 7615 } 7616 7617 // C++ [over.built]p20: 7618 // 7619 // For every pair (T, VQ), where T is an enumeration or 7620 // pointer to member type and VQ is either volatile or 7621 // empty, there exist candidate operator functions of the form 7622 // 7623 // VQ T& operator=(VQ T&, T); 7624 void addAssignmentMemberPointerOrEnumeralOverloads() { 7625 /// Set of (canonical) types that we've already handled. 7626 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7627 7628 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7629 for (BuiltinCandidateTypeSet::iterator 7630 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7631 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7632 Enum != EnumEnd; ++Enum) { 7633 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 7634 continue; 7635 7636 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7637 } 7638 7639 for (BuiltinCandidateTypeSet::iterator 7640 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7641 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7642 MemPtr != MemPtrEnd; ++MemPtr) { 7643 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7644 continue; 7645 7646 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7647 } 7648 } 7649 } 7650 7651 // C++ [over.built]p19: 7652 // 7653 // For every pair (T, VQ), where T is any type and VQ is either 7654 // volatile or empty, there exist candidate operator functions 7655 // of the form 7656 // 7657 // T*VQ& operator=(T*VQ&, T*); 7658 // 7659 // C++ [over.built]p21: 7660 // 7661 // For every pair (T, VQ), where T is a cv-qualified or 7662 // cv-unqualified object type and VQ is either volatile or 7663 // empty, there exist candidate operator functions of the form 7664 // 7665 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7666 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7667 void addAssignmentPointerOverloads(bool isEqualOp) { 7668 /// Set of (canonical) types that we've already handled. 7669 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7670 7671 for (BuiltinCandidateTypeSet::iterator 7672 Ptr = CandidateTypes[0].pointer_begin(), 7673 PtrEnd = CandidateTypes[0].pointer_end(); 7674 Ptr != PtrEnd; ++Ptr) { 7675 // If this is operator=, keep track of the builtin candidates we added. 7676 if (isEqualOp) 7677 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7678 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7679 continue; 7680 7681 // non-volatile version 7682 QualType ParamTypes[2] = { 7683 S.Context.getLValueReferenceType(*Ptr), 7684 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7685 }; 7686 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7687 /*IsAssigmentOperator=*/ isEqualOp); 7688 7689 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7690 VisibleTypeConversionsQuals.hasVolatile(); 7691 if (NeedVolatile) { 7692 // volatile version 7693 ParamTypes[0] = 7694 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7695 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7696 /*IsAssigmentOperator=*/isEqualOp); 7697 } 7698 7699 if (!(*Ptr).isRestrictQualified() && 7700 VisibleTypeConversionsQuals.hasRestrict()) { 7701 // restrict version 7702 ParamTypes[0] 7703 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7704 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7705 /*IsAssigmentOperator=*/isEqualOp); 7706 7707 if (NeedVolatile) { 7708 // volatile restrict version 7709 ParamTypes[0] 7710 = S.Context.getLValueReferenceType( 7711 S.Context.getCVRQualifiedType(*Ptr, 7712 (Qualifiers::Volatile | 7713 Qualifiers::Restrict))); 7714 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7715 /*IsAssigmentOperator=*/isEqualOp); 7716 } 7717 } 7718 } 7719 7720 if (isEqualOp) { 7721 for (BuiltinCandidateTypeSet::iterator 7722 Ptr = CandidateTypes[1].pointer_begin(), 7723 PtrEnd = CandidateTypes[1].pointer_end(); 7724 Ptr != PtrEnd; ++Ptr) { 7725 // Make sure we don't add the same candidate twice. 7726 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7727 continue; 7728 7729 QualType ParamTypes[2] = { 7730 S.Context.getLValueReferenceType(*Ptr), 7731 *Ptr, 7732 }; 7733 7734 // non-volatile version 7735 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7736 /*IsAssigmentOperator=*/true); 7737 7738 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7739 VisibleTypeConversionsQuals.hasVolatile(); 7740 if (NeedVolatile) { 7741 // volatile version 7742 ParamTypes[0] = 7743 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7744 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7745 /*IsAssigmentOperator=*/true); 7746 } 7747 7748 if (!(*Ptr).isRestrictQualified() && 7749 VisibleTypeConversionsQuals.hasRestrict()) { 7750 // restrict version 7751 ParamTypes[0] 7752 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7753 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7754 /*IsAssigmentOperator=*/true); 7755 7756 if (NeedVolatile) { 7757 // volatile restrict version 7758 ParamTypes[0] 7759 = S.Context.getLValueReferenceType( 7760 S.Context.getCVRQualifiedType(*Ptr, 7761 (Qualifiers::Volatile | 7762 Qualifiers::Restrict))); 7763 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7764 /*IsAssigmentOperator=*/true); 7765 } 7766 } 7767 } 7768 } 7769 } 7770 7771 // C++ [over.built]p18: 7772 // 7773 // For every triple (L, VQ, R), where L is an arithmetic type, 7774 // VQ is either volatile or empty, and R is a promoted 7775 // arithmetic type, there exist candidate operator functions of 7776 // the form 7777 // 7778 // VQ L& operator=(VQ L&, R); 7779 // VQ L& operator*=(VQ L&, R); 7780 // VQ L& operator/=(VQ L&, R); 7781 // VQ L& operator+=(VQ L&, R); 7782 // VQ L& operator-=(VQ L&, R); 7783 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7784 if (!HasArithmeticOrEnumeralCandidateType) 7785 return; 7786 7787 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7788 for (unsigned Right = FirstPromotedArithmeticType; 7789 Right < LastPromotedArithmeticType; ++Right) { 7790 QualType ParamTypes[2]; 7791 ParamTypes[1] = getArithmeticType(Right); 7792 7793 // Add this built-in operator as a candidate (VQ is empty). 7794 ParamTypes[0] = 7795 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7796 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7797 /*IsAssigmentOperator=*/isEqualOp); 7798 7799 // Add this built-in operator as a candidate (VQ is 'volatile'). 7800 if (VisibleTypeConversionsQuals.hasVolatile()) { 7801 ParamTypes[0] = 7802 S.Context.getVolatileType(getArithmeticType(Left)); 7803 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7804 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7805 /*IsAssigmentOperator=*/isEqualOp); 7806 } 7807 } 7808 } 7809 7810 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7811 for (BuiltinCandidateTypeSet::iterator 7812 Vec1 = CandidateTypes[0].vector_begin(), 7813 Vec1End = CandidateTypes[0].vector_end(); 7814 Vec1 != Vec1End; ++Vec1) { 7815 for (BuiltinCandidateTypeSet::iterator 7816 Vec2 = CandidateTypes[1].vector_begin(), 7817 Vec2End = CandidateTypes[1].vector_end(); 7818 Vec2 != Vec2End; ++Vec2) { 7819 QualType ParamTypes[2]; 7820 ParamTypes[1] = *Vec2; 7821 // Add this built-in operator as a candidate (VQ is empty). 7822 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7823 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7824 /*IsAssigmentOperator=*/isEqualOp); 7825 7826 // Add this built-in operator as a candidate (VQ is 'volatile'). 7827 if (VisibleTypeConversionsQuals.hasVolatile()) { 7828 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7829 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7830 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7831 /*IsAssigmentOperator=*/isEqualOp); 7832 } 7833 } 7834 } 7835 } 7836 7837 // C++ [over.built]p22: 7838 // 7839 // For every triple (L, VQ, R), where L is an integral type, VQ 7840 // is either volatile or empty, and R is a promoted integral 7841 // type, there exist candidate operator functions of the form 7842 // 7843 // VQ L& operator%=(VQ L&, R); 7844 // VQ L& operator<<=(VQ L&, R); 7845 // VQ L& operator>>=(VQ L&, R); 7846 // VQ L& operator&=(VQ L&, R); 7847 // VQ L& operator^=(VQ L&, R); 7848 // VQ L& operator|=(VQ L&, R); 7849 void addAssignmentIntegralOverloads() { 7850 if (!HasArithmeticOrEnumeralCandidateType) 7851 return; 7852 7853 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7854 for (unsigned Right = FirstPromotedIntegralType; 7855 Right < LastPromotedIntegralType; ++Right) { 7856 QualType ParamTypes[2]; 7857 ParamTypes[1] = getArithmeticType(Right); 7858 7859 // Add this built-in operator as a candidate (VQ is empty). 7860 ParamTypes[0] = 7861 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7862 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7863 if (VisibleTypeConversionsQuals.hasVolatile()) { 7864 // Add this built-in operator as a candidate (VQ is 'volatile'). 7865 ParamTypes[0] = getArithmeticType(Left); 7866 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7867 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7868 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7869 } 7870 } 7871 } 7872 } 7873 7874 // C++ [over.operator]p23: 7875 // 7876 // There also exist candidate operator functions of the form 7877 // 7878 // bool operator!(bool); 7879 // bool operator&&(bool, bool); 7880 // bool operator||(bool, bool); 7881 void addExclaimOverload() { 7882 QualType ParamTy = S.Context.BoolTy; 7883 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 7884 /*IsAssignmentOperator=*/false, 7885 /*NumContextualBoolArguments=*/1); 7886 } 7887 void addAmpAmpOrPipePipeOverload() { 7888 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7889 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 7890 /*IsAssignmentOperator=*/false, 7891 /*NumContextualBoolArguments=*/2); 7892 } 7893 7894 // C++ [over.built]p13: 7895 // 7896 // For every cv-qualified or cv-unqualified object type T there 7897 // exist candidate operator functions of the form 7898 // 7899 // T* operator+(T*, ptrdiff_t); [ABOVE] 7900 // T& operator[](T*, ptrdiff_t); 7901 // T* operator-(T*, ptrdiff_t); [ABOVE] 7902 // T* operator+(ptrdiff_t, T*); [ABOVE] 7903 // T& operator[](ptrdiff_t, T*); 7904 void addSubscriptOverloads() { 7905 for (BuiltinCandidateTypeSet::iterator 7906 Ptr = CandidateTypes[0].pointer_begin(), 7907 PtrEnd = CandidateTypes[0].pointer_end(); 7908 Ptr != PtrEnd; ++Ptr) { 7909 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7910 QualType PointeeType = (*Ptr)->getPointeeType(); 7911 if (!PointeeType->isObjectType()) 7912 continue; 7913 7914 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7915 7916 // T& operator[](T*, ptrdiff_t) 7917 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7918 } 7919 7920 for (BuiltinCandidateTypeSet::iterator 7921 Ptr = CandidateTypes[1].pointer_begin(), 7922 PtrEnd = CandidateTypes[1].pointer_end(); 7923 Ptr != PtrEnd; ++Ptr) { 7924 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7925 QualType PointeeType = (*Ptr)->getPointeeType(); 7926 if (!PointeeType->isObjectType()) 7927 continue; 7928 7929 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7930 7931 // T& operator[](ptrdiff_t, T*) 7932 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7933 } 7934 } 7935 7936 // C++ [over.built]p11: 7937 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7938 // C1 is the same type as C2 or is a derived class of C2, T is an object 7939 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7940 // there exist candidate operator functions of the form 7941 // 7942 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7943 // 7944 // where CV12 is the union of CV1 and CV2. 7945 void addArrowStarOverloads() { 7946 for (BuiltinCandidateTypeSet::iterator 7947 Ptr = CandidateTypes[0].pointer_begin(), 7948 PtrEnd = CandidateTypes[0].pointer_end(); 7949 Ptr != PtrEnd; ++Ptr) { 7950 QualType C1Ty = (*Ptr); 7951 QualType C1; 7952 QualifierCollector Q1; 7953 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 7954 if (!isa<RecordType>(C1)) 7955 continue; 7956 // heuristic to reduce number of builtin candidates in the set. 7957 // Add volatile/restrict version only if there are conversions to a 7958 // volatile/restrict type. 7959 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 7960 continue; 7961 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 7962 continue; 7963 for (BuiltinCandidateTypeSet::iterator 7964 MemPtr = CandidateTypes[1].member_pointer_begin(), 7965 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 7966 MemPtr != MemPtrEnd; ++MemPtr) { 7967 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 7968 QualType C2 = QualType(mptr->getClass(), 0); 7969 C2 = C2.getUnqualifiedType(); 7970 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 7971 break; 7972 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 7973 // build CV12 T& 7974 QualType T = mptr->getPointeeType(); 7975 if (!VisibleTypeConversionsQuals.hasVolatile() && 7976 T.isVolatileQualified()) 7977 continue; 7978 if (!VisibleTypeConversionsQuals.hasRestrict() && 7979 T.isRestrictQualified()) 7980 continue; 7981 T = Q1.apply(S.Context, T); 7982 QualType ResultTy = S.Context.getLValueReferenceType(T); 7983 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7984 } 7985 } 7986 } 7987 7988 // Note that we don't consider the first argument, since it has been 7989 // contextually converted to bool long ago. The candidates below are 7990 // therefore added as binary. 7991 // 7992 // C++ [over.built]p25: 7993 // For every type T, where T is a pointer, pointer-to-member, or scoped 7994 // enumeration type, there exist candidate operator functions of the form 7995 // 7996 // T operator?(bool, T, T); 7997 // 7998 void addConditionalOperatorOverloads() { 7999 /// Set of (canonical) types that we've already handled. 8000 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8001 8002 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8003 for (BuiltinCandidateTypeSet::iterator 8004 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8005 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8006 Ptr != PtrEnd; ++Ptr) { 8007 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8008 continue; 8009 8010 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8011 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 8012 } 8013 8014 for (BuiltinCandidateTypeSet::iterator 8015 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8016 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8017 MemPtr != MemPtrEnd; ++MemPtr) { 8018 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8019 continue; 8020 8021 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8022 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 8023 } 8024 8025 if (S.getLangOpts().CPlusPlus11) { 8026 for (BuiltinCandidateTypeSet::iterator 8027 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8028 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8029 Enum != EnumEnd; ++Enum) { 8030 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8031 continue; 8032 8033 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8034 continue; 8035 8036 QualType ParamTypes[2] = { *Enum, *Enum }; 8037 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 8038 } 8039 } 8040 } 8041 } 8042 }; 8043 8044 } // end anonymous namespace 8045 8046 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8047 /// operator overloads to the candidate set (C++ [over.built]), based 8048 /// on the operator @p Op and the arguments given. For example, if the 8049 /// operator is a binary '+', this routine might add "int 8050 /// operator+(int, int)" to cover integer addition. 8051 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8052 SourceLocation OpLoc, 8053 ArrayRef<Expr *> Args, 8054 OverloadCandidateSet &CandidateSet) { 8055 // Find all of the types that the arguments can convert to, but only 8056 // if the operator we're looking at has built-in operator candidates 8057 // that make use of these types. Also record whether we encounter non-record 8058 // candidate types or either arithmetic or enumeral candidate types. 8059 Qualifiers VisibleTypeConversionsQuals; 8060 VisibleTypeConversionsQuals.addConst(); 8061 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8062 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8063 8064 bool HasNonRecordCandidateType = false; 8065 bool HasArithmeticOrEnumeralCandidateType = false; 8066 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8067 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8068 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 8069 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8070 OpLoc, 8071 true, 8072 (Op == OO_Exclaim || 8073 Op == OO_AmpAmp || 8074 Op == OO_PipePipe), 8075 VisibleTypeConversionsQuals); 8076 HasNonRecordCandidateType = HasNonRecordCandidateType || 8077 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8078 HasArithmeticOrEnumeralCandidateType = 8079 HasArithmeticOrEnumeralCandidateType || 8080 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8081 } 8082 8083 // Exit early when no non-record types have been added to the candidate set 8084 // for any of the arguments to the operator. 8085 // 8086 // We can't exit early for !, ||, or &&, since there we have always have 8087 // 'bool' overloads. 8088 if (!HasNonRecordCandidateType && 8089 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8090 return; 8091 8092 // Setup an object to manage the common state for building overloads. 8093 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8094 VisibleTypeConversionsQuals, 8095 HasArithmeticOrEnumeralCandidateType, 8096 CandidateTypes, CandidateSet); 8097 8098 // Dispatch over the operation to add in only those overloads which apply. 8099 switch (Op) { 8100 case OO_None: 8101 case NUM_OVERLOADED_OPERATORS: 8102 llvm_unreachable("Expected an overloaded operator"); 8103 8104 case OO_New: 8105 case OO_Delete: 8106 case OO_Array_New: 8107 case OO_Array_Delete: 8108 case OO_Call: 8109 llvm_unreachable( 8110 "Special operators don't use AddBuiltinOperatorCandidates"); 8111 8112 case OO_Comma: 8113 case OO_Arrow: 8114 // C++ [over.match.oper]p3: 8115 // -- For the operator ',', the unary operator '&', or the 8116 // operator '->', the built-in candidates set is empty. 8117 break; 8118 8119 case OO_Plus: // '+' is either unary or binary 8120 if (Args.size() == 1) 8121 OpBuilder.addUnaryPlusPointerOverloads(); 8122 // Fall through. 8123 8124 case OO_Minus: // '-' is either unary or binary 8125 if (Args.size() == 1) { 8126 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8127 } else { 8128 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8129 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8130 } 8131 break; 8132 8133 case OO_Star: // '*' is either unary or binary 8134 if (Args.size() == 1) 8135 OpBuilder.addUnaryStarPointerOverloads(); 8136 else 8137 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8138 break; 8139 8140 case OO_Slash: 8141 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8142 break; 8143 8144 case OO_PlusPlus: 8145 case OO_MinusMinus: 8146 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8147 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8148 break; 8149 8150 case OO_EqualEqual: 8151 case OO_ExclaimEqual: 8152 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 8153 // Fall through. 8154 8155 case OO_Less: 8156 case OO_Greater: 8157 case OO_LessEqual: 8158 case OO_GreaterEqual: 8159 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8160 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8161 break; 8162 8163 case OO_Percent: 8164 case OO_Caret: 8165 case OO_Pipe: 8166 case OO_LessLess: 8167 case OO_GreaterGreater: 8168 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8169 break; 8170 8171 case OO_Amp: // '&' is either unary or binary 8172 if (Args.size() == 1) 8173 // C++ [over.match.oper]p3: 8174 // -- For the operator ',', the unary operator '&', or the 8175 // operator '->', the built-in candidates set is empty. 8176 break; 8177 8178 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8179 break; 8180 8181 case OO_Tilde: 8182 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8183 break; 8184 8185 case OO_Equal: 8186 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8187 // Fall through. 8188 8189 case OO_PlusEqual: 8190 case OO_MinusEqual: 8191 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8192 // Fall through. 8193 8194 case OO_StarEqual: 8195 case OO_SlashEqual: 8196 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8197 break; 8198 8199 case OO_PercentEqual: 8200 case OO_LessLessEqual: 8201 case OO_GreaterGreaterEqual: 8202 case OO_AmpEqual: 8203 case OO_CaretEqual: 8204 case OO_PipeEqual: 8205 OpBuilder.addAssignmentIntegralOverloads(); 8206 break; 8207 8208 case OO_Exclaim: 8209 OpBuilder.addExclaimOverload(); 8210 break; 8211 8212 case OO_AmpAmp: 8213 case OO_PipePipe: 8214 OpBuilder.addAmpAmpOrPipePipeOverload(); 8215 break; 8216 8217 case OO_Subscript: 8218 OpBuilder.addSubscriptOverloads(); 8219 break; 8220 8221 case OO_ArrowStar: 8222 OpBuilder.addArrowStarOverloads(); 8223 break; 8224 8225 case OO_Conditional: 8226 OpBuilder.addConditionalOperatorOverloads(); 8227 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8228 break; 8229 } 8230 } 8231 8232 /// \brief Add function candidates found via argument-dependent lookup 8233 /// to the set of overloading candidates. 8234 /// 8235 /// This routine performs argument-dependent name lookup based on the 8236 /// given function name (which may also be an operator name) and adds 8237 /// all of the overload candidates found by ADL to the overload 8238 /// candidate set (C++ [basic.lookup.argdep]). 8239 void 8240 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8241 SourceLocation Loc, 8242 ArrayRef<Expr *> Args, 8243 TemplateArgumentListInfo *ExplicitTemplateArgs, 8244 OverloadCandidateSet& CandidateSet, 8245 bool PartialOverloading) { 8246 ADLResult Fns; 8247 8248 // FIXME: This approach for uniquing ADL results (and removing 8249 // redundant candidates from the set) relies on pointer-equality, 8250 // which means we need to key off the canonical decl. However, 8251 // always going back to the canonical decl might not get us the 8252 // right set of default arguments. What default arguments are 8253 // we supposed to consider on ADL candidates, anyway? 8254 8255 // FIXME: Pass in the explicit template arguments? 8256 ArgumentDependentLookup(Name, Loc, Args, Fns); 8257 8258 // Erase all of the candidates we already knew about. 8259 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8260 CandEnd = CandidateSet.end(); 8261 Cand != CandEnd; ++Cand) 8262 if (Cand->Function) { 8263 Fns.erase(Cand->Function); 8264 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8265 Fns.erase(FunTmpl); 8266 } 8267 8268 // For each of the ADL candidates we found, add it to the overload 8269 // set. 8270 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8271 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8272 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8273 if (ExplicitTemplateArgs) 8274 continue; 8275 8276 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8277 PartialOverloading); 8278 } else 8279 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8280 FoundDecl, ExplicitTemplateArgs, 8281 Args, CandidateSet); 8282 } 8283 } 8284 8285 /// isBetterOverloadCandidate - Determines whether the first overload 8286 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8287 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, 8288 const OverloadCandidate &Cand2, 8289 SourceLocation Loc, 8290 bool UserDefinedConversion) { 8291 // Define viable functions to be better candidates than non-viable 8292 // functions. 8293 if (!Cand2.Viable) 8294 return Cand1.Viable; 8295 else if (!Cand1.Viable) 8296 return false; 8297 8298 // C++ [over.match.best]p1: 8299 // 8300 // -- if F is a static member function, ICS1(F) is defined such 8301 // that ICS1(F) is neither better nor worse than ICS1(G) for 8302 // any function G, and, symmetrically, ICS1(G) is neither 8303 // better nor worse than ICS1(F). 8304 unsigned StartArg = 0; 8305 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8306 StartArg = 1; 8307 8308 // C++ [over.match.best]p1: 8309 // A viable function F1 is defined to be a better function than another 8310 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8311 // conversion sequence than ICSi(F2), and then... 8312 unsigned NumArgs = Cand1.NumConversions; 8313 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8314 bool HasBetterConversion = false; 8315 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8316 switch (CompareImplicitConversionSequences(S, 8317 Cand1.Conversions[ArgIdx], 8318 Cand2.Conversions[ArgIdx])) { 8319 case ImplicitConversionSequence::Better: 8320 // Cand1 has a better conversion sequence. 8321 HasBetterConversion = true; 8322 break; 8323 8324 case ImplicitConversionSequence::Worse: 8325 // Cand1 can't be better than Cand2. 8326 return false; 8327 8328 case ImplicitConversionSequence::Indistinguishable: 8329 // Do nothing. 8330 break; 8331 } 8332 } 8333 8334 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8335 // ICSj(F2), or, if not that, 8336 if (HasBetterConversion) 8337 return true; 8338 8339 // -- the context is an initialization by user-defined conversion 8340 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8341 // from the return type of F1 to the destination type (i.e., 8342 // the type of the entity being initialized) is a better 8343 // conversion sequence than the standard conversion sequence 8344 // from the return type of F2 to the destination type. 8345 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8346 isa<CXXConversionDecl>(Cand1.Function) && 8347 isa<CXXConversionDecl>(Cand2.Function)) { 8348 // First check whether we prefer one of the conversion functions over the 8349 // other. This only distinguishes the results in non-standard, extension 8350 // cases such as the conversion from a lambda closure type to a function 8351 // pointer or block. 8352 ImplicitConversionSequence::CompareKind Result = 8353 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8354 if (Result == ImplicitConversionSequence::Indistinguishable) 8355 Result = CompareStandardConversionSequences(S, 8356 Cand1.FinalConversion, 8357 Cand2.FinalConversion); 8358 8359 if (Result != ImplicitConversionSequence::Indistinguishable) 8360 return Result == ImplicitConversionSequence::Better; 8361 8362 // FIXME: Compare kind of reference binding if conversion functions 8363 // convert to a reference type used in direct reference binding, per 8364 // C++14 [over.match.best]p1 section 2 bullet 3. 8365 } 8366 8367 // -- F1 is a non-template function and F2 is a function template 8368 // specialization, or, if not that, 8369 bool Cand1IsSpecialization = Cand1.Function && 8370 Cand1.Function->getPrimaryTemplate(); 8371 bool Cand2IsSpecialization = Cand2.Function && 8372 Cand2.Function->getPrimaryTemplate(); 8373 if (Cand1IsSpecialization != Cand2IsSpecialization) 8374 return Cand2IsSpecialization; 8375 8376 // -- F1 and F2 are function template specializations, and the function 8377 // template for F1 is more specialized than the template for F2 8378 // according to the partial ordering rules described in 14.5.5.2, or, 8379 // if not that, 8380 if (Cand1IsSpecialization && Cand2IsSpecialization) { 8381 if (FunctionTemplateDecl *BetterTemplate 8382 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8383 Cand2.Function->getPrimaryTemplate(), 8384 Loc, 8385 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8386 : TPOC_Call, 8387 Cand1.ExplicitCallArguments, 8388 Cand2.ExplicitCallArguments)) 8389 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8390 } 8391 8392 // Check for enable_if value-based overload resolution. 8393 if (Cand1.Function && Cand2.Function && 8394 (Cand1.Function->hasAttr<EnableIfAttr>() || 8395 Cand2.Function->hasAttr<EnableIfAttr>())) { 8396 // FIXME: The next several lines are just 8397 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8398 // instead of reverse order which is how they're stored in the AST. 8399 AttrVec Cand1Attrs; 8400 if (Cand1.Function->hasAttrs()) { 8401 Cand1Attrs = Cand1.Function->getAttrs(); 8402 Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(), 8403 IsNotEnableIfAttr), 8404 Cand1Attrs.end()); 8405 std::reverse(Cand1Attrs.begin(), Cand1Attrs.end()); 8406 } 8407 8408 AttrVec Cand2Attrs; 8409 if (Cand2.Function->hasAttrs()) { 8410 Cand2Attrs = Cand2.Function->getAttrs(); 8411 Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(), 8412 IsNotEnableIfAttr), 8413 Cand2Attrs.end()); 8414 std::reverse(Cand2Attrs.begin(), Cand2Attrs.end()); 8415 } 8416 8417 // Candidate 1 is better if it has strictly more attributes and 8418 // the common sequence is identical. 8419 if (Cand1Attrs.size() <= Cand2Attrs.size()) 8420 return false; 8421 8422 auto Cand1I = Cand1Attrs.begin(); 8423 for (auto &Cand2A : Cand2Attrs) { 8424 auto &Cand1A = *Cand1I++; 8425 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8426 cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID, 8427 S.getASTContext(), true); 8428 cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID, 8429 S.getASTContext(), true); 8430 if (Cand1ID != Cand2ID) 8431 return false; 8432 } 8433 8434 return true; 8435 } 8436 8437 return false; 8438 } 8439 8440 /// \brief Computes the best viable function (C++ 13.3.3) 8441 /// within an overload candidate set. 8442 /// 8443 /// \param Loc The location of the function name (or operator symbol) for 8444 /// which overload resolution occurs. 8445 /// 8446 /// \param Best If overload resolution was successful or found a deleted 8447 /// function, \p Best points to the candidate function found. 8448 /// 8449 /// \returns The result of overload resolution. 8450 OverloadingResult 8451 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8452 iterator &Best, 8453 bool UserDefinedConversion) { 8454 // Find the best viable function. 8455 Best = end(); 8456 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8457 if (Cand->Viable) 8458 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8459 UserDefinedConversion)) 8460 Best = Cand; 8461 } 8462 8463 // If we didn't find any viable functions, abort. 8464 if (Best == end()) 8465 return OR_No_Viable_Function; 8466 8467 // Make sure that this function is better than every other viable 8468 // function. If not, we have an ambiguity. 8469 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8470 if (Cand->Viable && 8471 Cand != Best && 8472 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8473 UserDefinedConversion)) { 8474 Best = end(); 8475 return OR_Ambiguous; 8476 } 8477 } 8478 8479 // Best is the best viable function. 8480 if (Best->Function && 8481 (Best->Function->isDeleted() || 8482 S.isFunctionConsideredUnavailable(Best->Function))) 8483 return OR_Deleted; 8484 8485 return OR_Success; 8486 } 8487 8488 namespace { 8489 8490 enum OverloadCandidateKind { 8491 oc_function, 8492 oc_method, 8493 oc_constructor, 8494 oc_function_template, 8495 oc_method_template, 8496 oc_constructor_template, 8497 oc_implicit_default_constructor, 8498 oc_implicit_copy_constructor, 8499 oc_implicit_move_constructor, 8500 oc_implicit_copy_assignment, 8501 oc_implicit_move_assignment, 8502 oc_implicit_inherited_constructor 8503 }; 8504 8505 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8506 FunctionDecl *Fn, 8507 std::string &Description) { 8508 bool isTemplate = false; 8509 8510 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8511 isTemplate = true; 8512 Description = S.getTemplateArgumentBindingsText( 8513 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8514 } 8515 8516 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8517 if (!Ctor->isImplicit()) 8518 return isTemplate ? oc_constructor_template : oc_constructor; 8519 8520 if (Ctor->getInheritedConstructor()) 8521 return oc_implicit_inherited_constructor; 8522 8523 if (Ctor->isDefaultConstructor()) 8524 return oc_implicit_default_constructor; 8525 8526 if (Ctor->isMoveConstructor()) 8527 return oc_implicit_move_constructor; 8528 8529 assert(Ctor->isCopyConstructor() && 8530 "unexpected sort of implicit constructor"); 8531 return oc_implicit_copy_constructor; 8532 } 8533 8534 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8535 // This actually gets spelled 'candidate function' for now, but 8536 // it doesn't hurt to split it out. 8537 if (!Meth->isImplicit()) 8538 return isTemplate ? oc_method_template : oc_method; 8539 8540 if (Meth->isMoveAssignmentOperator()) 8541 return oc_implicit_move_assignment; 8542 8543 if (Meth->isCopyAssignmentOperator()) 8544 return oc_implicit_copy_assignment; 8545 8546 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8547 return oc_method; 8548 } 8549 8550 return isTemplate ? oc_function_template : oc_function; 8551 } 8552 8553 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) { 8554 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8555 if (!Ctor) return; 8556 8557 Ctor = Ctor->getInheritedConstructor(); 8558 if (!Ctor) return; 8559 8560 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8561 } 8562 8563 } // end anonymous namespace 8564 8565 // Notes the location of an overload candidate. 8566 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 8567 std::string FnDesc; 8568 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8569 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8570 << (unsigned) K << FnDesc; 8571 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8572 Diag(Fn->getLocation(), PD); 8573 MaybeEmitInheritedConstructorNote(*this, Fn); 8574 } 8575 8576 // Notes the location of all overload candidates designated through 8577 // OverloadedExpr 8578 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 8579 assert(OverloadedExpr->getType() == Context.OverloadTy); 8580 8581 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8582 OverloadExpr *OvlExpr = Ovl.Expression; 8583 8584 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8585 IEnd = OvlExpr->decls_end(); 8586 I != IEnd; ++I) { 8587 if (FunctionTemplateDecl *FunTmpl = 8588 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8589 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 8590 } else if (FunctionDecl *Fun 8591 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8592 NoteOverloadCandidate(Fun, DestType); 8593 } 8594 } 8595 } 8596 8597 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 8598 /// "lead" diagnostic; it will be given two arguments, the source and 8599 /// target types of the conversion. 8600 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8601 Sema &S, 8602 SourceLocation CaretLoc, 8603 const PartialDiagnostic &PDiag) const { 8604 S.Diag(CaretLoc, PDiag) 8605 << Ambiguous.getFromType() << Ambiguous.getToType(); 8606 // FIXME: The note limiting machinery is borrowed from 8607 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8608 // refactoring here. 8609 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8610 unsigned CandsShown = 0; 8611 AmbiguousConversionSequence::const_iterator I, E; 8612 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8613 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8614 break; 8615 ++CandsShown; 8616 S.NoteOverloadCandidate(*I); 8617 } 8618 if (I != E) 8619 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8620 } 8621 8622 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 8623 unsigned I) { 8624 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8625 assert(Conv.isBad()); 8626 assert(Cand->Function && "for now, candidate must be a function"); 8627 FunctionDecl *Fn = Cand->Function; 8628 8629 // There's a conversion slot for the object argument if this is a 8630 // non-constructor method. Note that 'I' corresponds the 8631 // conversion-slot index. 8632 bool isObjectArgument = false; 8633 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8634 if (I == 0) 8635 isObjectArgument = true; 8636 else 8637 I--; 8638 } 8639 8640 std::string FnDesc; 8641 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8642 8643 Expr *FromExpr = Conv.Bad.FromExpr; 8644 QualType FromTy = Conv.Bad.getFromType(); 8645 QualType ToTy = Conv.Bad.getToType(); 8646 8647 if (FromTy == S.Context.OverloadTy) { 8648 assert(FromExpr && "overload set argument came from implicit argument?"); 8649 Expr *E = FromExpr->IgnoreParens(); 8650 if (isa<UnaryOperator>(E)) 8651 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8652 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8653 8654 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8655 << (unsigned) FnKind << FnDesc 8656 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8657 << ToTy << Name << I+1; 8658 MaybeEmitInheritedConstructorNote(S, Fn); 8659 return; 8660 } 8661 8662 // Do some hand-waving analysis to see if the non-viability is due 8663 // to a qualifier mismatch. 8664 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8665 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8666 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8667 CToTy = RT->getPointeeType(); 8668 else { 8669 // TODO: detect and diagnose the full richness of const mismatches. 8670 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8671 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8672 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8673 } 8674 8675 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8676 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8677 Qualifiers FromQs = CFromTy.getQualifiers(); 8678 Qualifiers ToQs = CToTy.getQualifiers(); 8679 8680 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8681 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8682 << (unsigned) FnKind << FnDesc 8683 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8684 << FromTy 8685 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8686 << (unsigned) isObjectArgument << I+1; 8687 MaybeEmitInheritedConstructorNote(S, Fn); 8688 return; 8689 } 8690 8691 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8692 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8693 << (unsigned) FnKind << FnDesc 8694 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8695 << FromTy 8696 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8697 << (unsigned) isObjectArgument << I+1; 8698 MaybeEmitInheritedConstructorNote(S, Fn); 8699 return; 8700 } 8701 8702 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8703 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8704 << (unsigned) FnKind << FnDesc 8705 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8706 << FromTy 8707 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8708 << (unsigned) isObjectArgument << I+1; 8709 MaybeEmitInheritedConstructorNote(S, Fn); 8710 return; 8711 } 8712 8713 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8714 assert(CVR && "unexpected qualifiers mismatch"); 8715 8716 if (isObjectArgument) { 8717 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8718 << (unsigned) FnKind << FnDesc 8719 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8720 << FromTy << (CVR - 1); 8721 } else { 8722 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8723 << (unsigned) FnKind << FnDesc 8724 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8725 << FromTy << (CVR - 1) << I+1; 8726 } 8727 MaybeEmitInheritedConstructorNote(S, Fn); 8728 return; 8729 } 8730 8731 // Special diagnostic for failure to convert an initializer list, since 8732 // telling the user that it has type void is not useful. 8733 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8734 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8735 << (unsigned) FnKind << FnDesc 8736 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8737 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8738 MaybeEmitInheritedConstructorNote(S, Fn); 8739 return; 8740 } 8741 8742 // Diagnose references or pointers to incomplete types differently, 8743 // since it's far from impossible that the incompleteness triggered 8744 // the failure. 8745 QualType TempFromTy = FromTy.getNonReferenceType(); 8746 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8747 TempFromTy = PTy->getPointeeType(); 8748 if (TempFromTy->isIncompleteType()) { 8749 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8750 << (unsigned) FnKind << FnDesc 8751 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8752 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8753 MaybeEmitInheritedConstructorNote(S, Fn); 8754 return; 8755 } 8756 8757 // Diagnose base -> derived pointer conversions. 8758 unsigned BaseToDerivedConversion = 0; 8759 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8760 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8761 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8762 FromPtrTy->getPointeeType()) && 8763 !FromPtrTy->getPointeeType()->isIncompleteType() && 8764 !ToPtrTy->getPointeeType()->isIncompleteType() && 8765 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8766 FromPtrTy->getPointeeType())) 8767 BaseToDerivedConversion = 1; 8768 } 8769 } else if (const ObjCObjectPointerType *FromPtrTy 8770 = FromTy->getAs<ObjCObjectPointerType>()) { 8771 if (const ObjCObjectPointerType *ToPtrTy 8772 = ToTy->getAs<ObjCObjectPointerType>()) 8773 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8774 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8775 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8776 FromPtrTy->getPointeeType()) && 8777 FromIface->isSuperClassOf(ToIface)) 8778 BaseToDerivedConversion = 2; 8779 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8780 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8781 !FromTy->isIncompleteType() && 8782 !ToRefTy->getPointeeType()->isIncompleteType() && 8783 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8784 BaseToDerivedConversion = 3; 8785 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8786 ToTy.getNonReferenceType().getCanonicalType() == 8787 FromTy.getNonReferenceType().getCanonicalType()) { 8788 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8789 << (unsigned) FnKind << FnDesc 8790 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8791 << (unsigned) isObjectArgument << I + 1; 8792 MaybeEmitInheritedConstructorNote(S, Fn); 8793 return; 8794 } 8795 } 8796 8797 if (BaseToDerivedConversion) { 8798 S.Diag(Fn->getLocation(), 8799 diag::note_ovl_candidate_bad_base_to_derived_conv) 8800 << (unsigned) FnKind << FnDesc 8801 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8802 << (BaseToDerivedConversion - 1) 8803 << FromTy << ToTy << I+1; 8804 MaybeEmitInheritedConstructorNote(S, Fn); 8805 return; 8806 } 8807 8808 if (isa<ObjCObjectPointerType>(CFromTy) && 8809 isa<PointerType>(CToTy)) { 8810 Qualifiers FromQs = CFromTy.getQualifiers(); 8811 Qualifiers ToQs = CToTy.getQualifiers(); 8812 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8813 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8814 << (unsigned) FnKind << FnDesc 8815 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8816 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8817 MaybeEmitInheritedConstructorNote(S, Fn); 8818 return; 8819 } 8820 } 8821 8822 // Emit the generic diagnostic and, optionally, add the hints to it. 8823 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8824 FDiag << (unsigned) FnKind << FnDesc 8825 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8826 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8827 << (unsigned) (Cand->Fix.Kind); 8828 8829 // If we can fix the conversion, suggest the FixIts. 8830 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8831 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8832 FDiag << *HI; 8833 S.Diag(Fn->getLocation(), FDiag); 8834 8835 MaybeEmitInheritedConstructorNote(S, Fn); 8836 } 8837 8838 /// Additional arity mismatch diagnosis specific to a function overload 8839 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 8840 /// over a candidate in any candidate set. 8841 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 8842 unsigned NumArgs) { 8843 FunctionDecl *Fn = Cand->Function; 8844 unsigned MinParams = Fn->getMinRequiredArguments(); 8845 8846 // With invalid overloaded operators, it's possible that we think we 8847 // have an arity mismatch when in fact it looks like we have the 8848 // right number of arguments, because only overloaded operators have 8849 // the weird behavior of overloading member and non-member functions. 8850 // Just don't report anything. 8851 if (Fn->isInvalidDecl() && 8852 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8853 return true; 8854 8855 if (NumArgs < MinParams) { 8856 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8857 (Cand->FailureKind == ovl_fail_bad_deduction && 8858 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8859 } else { 8860 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8861 (Cand->FailureKind == ovl_fail_bad_deduction && 8862 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8863 } 8864 8865 return false; 8866 } 8867 8868 /// General arity mismatch diagnosis over a candidate in a candidate set. 8869 static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) { 8870 assert(isa<FunctionDecl>(D) && 8871 "The templated declaration should at least be a function" 8872 " when diagnosing bad template argument deduction due to too many" 8873 " or too few arguments"); 8874 8875 FunctionDecl *Fn = cast<FunctionDecl>(D); 8876 8877 // TODO: treat calls to a missing default constructor as a special case 8878 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8879 unsigned MinParams = Fn->getMinRequiredArguments(); 8880 8881 // at least / at most / exactly 8882 unsigned mode, modeCount; 8883 if (NumFormalArgs < MinParams) { 8884 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 8885 FnTy->isTemplateVariadic()) 8886 mode = 0; // "at least" 8887 else 8888 mode = 2; // "exactly" 8889 modeCount = MinParams; 8890 } else { 8891 if (MinParams != FnTy->getNumParams()) 8892 mode = 1; // "at most" 8893 else 8894 mode = 2; // "exactly" 8895 modeCount = FnTy->getNumParams(); 8896 } 8897 8898 std::string Description; 8899 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8900 8901 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8902 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8903 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 8904 << mode << Fn->getParamDecl(0) << NumFormalArgs; 8905 else 8906 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8907 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 8908 << mode << modeCount << NumFormalArgs; 8909 MaybeEmitInheritedConstructorNote(S, Fn); 8910 } 8911 8912 /// Arity mismatch diagnosis specific to a function overload candidate. 8913 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8914 unsigned NumFormalArgs) { 8915 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 8916 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs); 8917 } 8918 8919 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 8920 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated)) 8921 return FD->getDescribedFunctionTemplate(); 8922 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated)) 8923 return RD->getDescribedClassTemplate(); 8924 8925 llvm_unreachable("Unsupported: Getting the described template declaration" 8926 " for bad deduction diagnosis"); 8927 } 8928 8929 /// Diagnose a failed template-argument deduction. 8930 static void DiagnoseBadDeduction(Sema &S, Decl *Templated, 8931 DeductionFailureInfo &DeductionFailure, 8932 unsigned NumArgs) { 8933 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 8934 NamedDecl *ParamD; 8935 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8936 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8937 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8938 switch (DeductionFailure.Result) { 8939 case Sema::TDK_Success: 8940 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8941 8942 case Sema::TDK_Incomplete: { 8943 assert(ParamD && "no parameter found for incomplete deduction result"); 8944 S.Diag(Templated->getLocation(), 8945 diag::note_ovl_candidate_incomplete_deduction) 8946 << ParamD->getDeclName(); 8947 MaybeEmitInheritedConstructorNote(S, Templated); 8948 return; 8949 } 8950 8951 case Sema::TDK_Underqualified: { 8952 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8953 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 8954 8955 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 8956 8957 // Param will have been canonicalized, but it should just be a 8958 // qualified version of ParamD, so move the qualifiers to that. 8959 QualifierCollector Qs; 8960 Qs.strip(Param); 8961 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 8962 assert(S.Context.hasSameType(Param, NonCanonParam)); 8963 8964 // Arg has also been canonicalized, but there's nothing we can do 8965 // about that. It also doesn't matter as much, because it won't 8966 // have any template parameters in it (because deduction isn't 8967 // done on dependent types). 8968 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 8969 8970 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 8971 << ParamD->getDeclName() << Arg << NonCanonParam; 8972 MaybeEmitInheritedConstructorNote(S, Templated); 8973 return; 8974 } 8975 8976 case Sema::TDK_Inconsistent: { 8977 assert(ParamD && "no parameter found for inconsistent deduction result"); 8978 int which = 0; 8979 if (isa<TemplateTypeParmDecl>(ParamD)) 8980 which = 0; 8981 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 8982 which = 1; 8983 else { 8984 which = 2; 8985 } 8986 8987 S.Diag(Templated->getLocation(), 8988 diag::note_ovl_candidate_inconsistent_deduction) 8989 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 8990 << *DeductionFailure.getSecondArg(); 8991 MaybeEmitInheritedConstructorNote(S, Templated); 8992 return; 8993 } 8994 8995 case Sema::TDK_InvalidExplicitArguments: 8996 assert(ParamD && "no parameter found for invalid explicit arguments"); 8997 if (ParamD->getDeclName()) 8998 S.Diag(Templated->getLocation(), 8999 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9000 << ParamD->getDeclName(); 9001 else { 9002 int index = 0; 9003 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9004 index = TTP->getIndex(); 9005 else if (NonTypeTemplateParmDecl *NTTP 9006 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9007 index = NTTP->getIndex(); 9008 else 9009 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9010 S.Diag(Templated->getLocation(), 9011 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9012 << (index + 1); 9013 } 9014 MaybeEmitInheritedConstructorNote(S, Templated); 9015 return; 9016 9017 case Sema::TDK_TooManyArguments: 9018 case Sema::TDK_TooFewArguments: 9019 DiagnoseArityMismatch(S, Templated, NumArgs); 9020 return; 9021 9022 case Sema::TDK_InstantiationDepth: 9023 S.Diag(Templated->getLocation(), 9024 diag::note_ovl_candidate_instantiation_depth); 9025 MaybeEmitInheritedConstructorNote(S, Templated); 9026 return; 9027 9028 case Sema::TDK_SubstitutionFailure: { 9029 // Format the template argument list into the argument string. 9030 SmallString<128> TemplateArgString; 9031 if (TemplateArgumentList *Args = 9032 DeductionFailure.getTemplateArgumentList()) { 9033 TemplateArgString = " "; 9034 TemplateArgString += S.getTemplateArgumentBindingsText( 9035 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9036 } 9037 9038 // If this candidate was disabled by enable_if, say so. 9039 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9040 if (PDiag && PDiag->second.getDiagID() == 9041 diag::err_typename_nested_not_found_enable_if) { 9042 // FIXME: Use the source range of the condition, and the fully-qualified 9043 // name of the enable_if template. These are both present in PDiag. 9044 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9045 << "'enable_if'" << TemplateArgString; 9046 return; 9047 } 9048 9049 // Format the SFINAE diagnostic into the argument string. 9050 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9051 // formatted message in another diagnostic. 9052 SmallString<128> SFINAEArgString; 9053 SourceRange R; 9054 if (PDiag) { 9055 SFINAEArgString = ": "; 9056 R = SourceRange(PDiag->first, PDiag->first); 9057 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9058 } 9059 9060 S.Diag(Templated->getLocation(), 9061 diag::note_ovl_candidate_substitution_failure) 9062 << TemplateArgString << SFINAEArgString << R; 9063 MaybeEmitInheritedConstructorNote(S, Templated); 9064 return; 9065 } 9066 9067 case Sema::TDK_FailedOverloadResolution: { 9068 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 9069 S.Diag(Templated->getLocation(), 9070 diag::note_ovl_candidate_failed_overload_resolution) 9071 << R.Expression->getName(); 9072 return; 9073 } 9074 9075 case Sema::TDK_NonDeducedMismatch: { 9076 // FIXME: Provide a source location to indicate what we couldn't match. 9077 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9078 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9079 if (FirstTA.getKind() == TemplateArgument::Template && 9080 SecondTA.getKind() == TemplateArgument::Template) { 9081 TemplateName FirstTN = FirstTA.getAsTemplate(); 9082 TemplateName SecondTN = SecondTA.getAsTemplate(); 9083 if (FirstTN.getKind() == TemplateName::Template && 9084 SecondTN.getKind() == TemplateName::Template) { 9085 if (FirstTN.getAsTemplateDecl()->getName() == 9086 SecondTN.getAsTemplateDecl()->getName()) { 9087 // FIXME: This fixes a bad diagnostic where both templates are named 9088 // the same. This particular case is a bit difficult since: 9089 // 1) It is passed as a string to the diagnostic printer. 9090 // 2) The diagnostic printer only attempts to find a better 9091 // name for types, not decls. 9092 // Ideally, this should folded into the diagnostic printer. 9093 S.Diag(Templated->getLocation(), 9094 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 9095 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 9096 return; 9097 } 9098 } 9099 } 9100 // FIXME: For generic lambda parameters, check if the function is a lambda 9101 // call operator, and if so, emit a prettier and more informative 9102 // diagnostic that mentions 'auto' and lambda in addition to 9103 // (or instead of?) the canonical template type parameters. 9104 S.Diag(Templated->getLocation(), 9105 diag::note_ovl_candidate_non_deduced_mismatch) 9106 << FirstTA << SecondTA; 9107 return; 9108 } 9109 // TODO: diagnose these individually, then kill off 9110 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9111 case Sema::TDK_MiscellaneousDeductionFailure: 9112 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9113 MaybeEmitInheritedConstructorNote(S, Templated); 9114 return; 9115 } 9116 } 9117 9118 /// Diagnose a failed template-argument deduction, for function calls. 9119 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 9120 unsigned NumArgs) { 9121 unsigned TDK = Cand->DeductionFailure.Result; 9122 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9123 if (CheckArityMismatch(S, Cand, NumArgs)) 9124 return; 9125 } 9126 DiagnoseBadDeduction(S, Cand->Function, // pattern 9127 Cand->DeductionFailure, NumArgs); 9128 } 9129 9130 /// CUDA: diagnose an invalid call across targets. 9131 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9132 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 9133 FunctionDecl *Callee = Cand->Function; 9134 9135 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 9136 CalleeTarget = S.IdentifyCUDATarget(Callee); 9137 9138 std::string FnDesc; 9139 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 9140 9141 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 9142 << (unsigned)FnKind << CalleeTarget << CallerTarget; 9143 9144 // This could be an implicit constructor for which we could not infer the 9145 // target due to a collsion. Diagnose that case. 9146 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 9147 if (Meth != nullptr && Meth->isImplicit()) { 9148 CXXRecordDecl *ParentClass = Meth->getParent(); 9149 Sema::CXXSpecialMember CSM; 9150 9151 switch (FnKind) { 9152 default: 9153 return; 9154 case oc_implicit_default_constructor: 9155 CSM = Sema::CXXDefaultConstructor; 9156 break; 9157 case oc_implicit_copy_constructor: 9158 CSM = Sema::CXXCopyConstructor; 9159 break; 9160 case oc_implicit_move_constructor: 9161 CSM = Sema::CXXMoveConstructor; 9162 break; 9163 case oc_implicit_copy_assignment: 9164 CSM = Sema::CXXCopyAssignment; 9165 break; 9166 case oc_implicit_move_assignment: 9167 CSM = Sema::CXXMoveAssignment; 9168 break; 9169 }; 9170 9171 bool ConstRHS = false; 9172 if (Meth->getNumParams()) { 9173 if (const ReferenceType *RT = 9174 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 9175 ConstRHS = RT->getPointeeType().isConstQualified(); 9176 } 9177 } 9178 9179 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 9180 /* ConstRHS */ ConstRHS, 9181 /* Diagnose */ true); 9182 } 9183 } 9184 9185 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 9186 FunctionDecl *Callee = Cand->Function; 9187 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 9188 9189 S.Diag(Callee->getLocation(), 9190 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9191 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9192 } 9193 9194 /// Generates a 'note' diagnostic for an overload candidate. We've 9195 /// already generated a primary error at the call site. 9196 /// 9197 /// It really does need to be a single diagnostic with its caret 9198 /// pointed at the candidate declaration. Yes, this creates some 9199 /// major challenges of technical writing. Yes, this makes pointing 9200 /// out problems with specific arguments quite awkward. It's still 9201 /// better than generating twenty screens of text for every failed 9202 /// overload. 9203 /// 9204 /// It would be great to be able to express per-candidate problems 9205 /// more richly for those diagnostic clients that cared, but we'd 9206 /// still have to be just as careful with the default diagnostics. 9207 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9208 unsigned NumArgs) { 9209 FunctionDecl *Fn = Cand->Function; 9210 9211 // Note deleted candidates, but only if they're viable. 9212 if (Cand->Viable && (Fn->isDeleted() || 9213 S.isFunctionConsideredUnavailable(Fn))) { 9214 std::string FnDesc; 9215 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 9216 9217 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9218 << FnKind << FnDesc 9219 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9220 MaybeEmitInheritedConstructorNote(S, Fn); 9221 return; 9222 } 9223 9224 // We don't really have anything else to say about viable candidates. 9225 if (Cand->Viable) { 9226 S.NoteOverloadCandidate(Fn); 9227 return; 9228 } 9229 9230 switch (Cand->FailureKind) { 9231 case ovl_fail_too_many_arguments: 9232 case ovl_fail_too_few_arguments: 9233 return DiagnoseArityMismatch(S, Cand, NumArgs); 9234 9235 case ovl_fail_bad_deduction: 9236 return DiagnoseBadDeduction(S, Cand, NumArgs); 9237 9238 case ovl_fail_trivial_conversion: 9239 case ovl_fail_bad_final_conversion: 9240 case ovl_fail_final_conversion_not_exact: 9241 return S.NoteOverloadCandidate(Fn); 9242 9243 case ovl_fail_bad_conversion: { 9244 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9245 for (unsigned N = Cand->NumConversions; I != N; ++I) 9246 if (Cand->Conversions[I].isBad()) 9247 return DiagnoseBadConversion(S, Cand, I); 9248 9249 // FIXME: this currently happens when we're called from SemaInit 9250 // when user-conversion overload fails. Figure out how to handle 9251 // those conditions and diagnose them well. 9252 return S.NoteOverloadCandidate(Fn); 9253 } 9254 9255 case ovl_fail_bad_target: 9256 return DiagnoseBadTarget(S, Cand); 9257 9258 case ovl_fail_enable_if: 9259 return DiagnoseFailedEnableIfAttr(S, Cand); 9260 } 9261 } 9262 9263 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9264 // Desugar the type of the surrogate down to a function type, 9265 // retaining as many typedefs as possible while still showing 9266 // the function type (and, therefore, its parameter types). 9267 QualType FnType = Cand->Surrogate->getConversionType(); 9268 bool isLValueReference = false; 9269 bool isRValueReference = false; 9270 bool isPointer = false; 9271 if (const LValueReferenceType *FnTypeRef = 9272 FnType->getAs<LValueReferenceType>()) { 9273 FnType = FnTypeRef->getPointeeType(); 9274 isLValueReference = true; 9275 } else if (const RValueReferenceType *FnTypeRef = 9276 FnType->getAs<RValueReferenceType>()) { 9277 FnType = FnTypeRef->getPointeeType(); 9278 isRValueReference = true; 9279 } 9280 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9281 FnType = FnTypePtr->getPointeeType(); 9282 isPointer = true; 9283 } 9284 // Desugar down to a function type. 9285 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9286 // Reconstruct the pointer/reference as appropriate. 9287 if (isPointer) FnType = S.Context.getPointerType(FnType); 9288 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9289 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9290 9291 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9292 << FnType; 9293 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 9294 } 9295 9296 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 9297 SourceLocation OpLoc, 9298 OverloadCandidate *Cand) { 9299 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9300 std::string TypeStr("operator"); 9301 TypeStr += Opc; 9302 TypeStr += "("; 9303 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9304 if (Cand->NumConversions == 1) { 9305 TypeStr += ")"; 9306 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9307 } else { 9308 TypeStr += ", "; 9309 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9310 TypeStr += ")"; 9311 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9312 } 9313 } 9314 9315 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9316 OverloadCandidate *Cand) { 9317 unsigned NoOperands = Cand->NumConversions; 9318 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9319 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9320 if (ICS.isBad()) break; // all meaningless after first invalid 9321 if (!ICS.isAmbiguous()) continue; 9322 9323 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 9324 S.PDiag(diag::note_ambiguous_type_conversion)); 9325 } 9326 } 9327 9328 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9329 if (Cand->Function) 9330 return Cand->Function->getLocation(); 9331 if (Cand->IsSurrogate) 9332 return Cand->Surrogate->getLocation(); 9333 return SourceLocation(); 9334 } 9335 9336 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 9337 switch ((Sema::TemplateDeductionResult)DFI.Result) { 9338 case Sema::TDK_Success: 9339 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9340 9341 case Sema::TDK_Invalid: 9342 case Sema::TDK_Incomplete: 9343 return 1; 9344 9345 case Sema::TDK_Underqualified: 9346 case Sema::TDK_Inconsistent: 9347 return 2; 9348 9349 case Sema::TDK_SubstitutionFailure: 9350 case Sema::TDK_NonDeducedMismatch: 9351 case Sema::TDK_MiscellaneousDeductionFailure: 9352 return 3; 9353 9354 case Sema::TDK_InstantiationDepth: 9355 case Sema::TDK_FailedOverloadResolution: 9356 return 4; 9357 9358 case Sema::TDK_InvalidExplicitArguments: 9359 return 5; 9360 9361 case Sema::TDK_TooManyArguments: 9362 case Sema::TDK_TooFewArguments: 9363 return 6; 9364 } 9365 llvm_unreachable("Unhandled deduction result"); 9366 } 9367 9368 namespace { 9369 struct CompareOverloadCandidatesForDisplay { 9370 Sema &S; 9371 size_t NumArgs; 9372 9373 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs) 9374 : S(S), NumArgs(nArgs) {} 9375 9376 bool operator()(const OverloadCandidate *L, 9377 const OverloadCandidate *R) { 9378 // Fast-path this check. 9379 if (L == R) return false; 9380 9381 // Order first by viability. 9382 if (L->Viable) { 9383 if (!R->Viable) return true; 9384 9385 // TODO: introduce a tri-valued comparison for overload 9386 // candidates. Would be more worthwhile if we had a sort 9387 // that could exploit it. 9388 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 9389 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 9390 } else if (R->Viable) 9391 return false; 9392 9393 assert(L->Viable == R->Viable); 9394 9395 // Criteria by which we can sort non-viable candidates: 9396 if (!L->Viable) { 9397 // 1. Arity mismatches come after other candidates. 9398 if (L->FailureKind == ovl_fail_too_many_arguments || 9399 L->FailureKind == ovl_fail_too_few_arguments) { 9400 if (R->FailureKind == ovl_fail_too_many_arguments || 9401 R->FailureKind == ovl_fail_too_few_arguments) { 9402 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 9403 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 9404 if (LDist == RDist) { 9405 if (L->FailureKind == R->FailureKind) 9406 // Sort non-surrogates before surrogates. 9407 return !L->IsSurrogate && R->IsSurrogate; 9408 // Sort candidates requiring fewer parameters than there were 9409 // arguments given after candidates requiring more parameters 9410 // than there were arguments given. 9411 return L->FailureKind == ovl_fail_too_many_arguments; 9412 } 9413 return LDist < RDist; 9414 } 9415 return false; 9416 } 9417 if (R->FailureKind == ovl_fail_too_many_arguments || 9418 R->FailureKind == ovl_fail_too_few_arguments) 9419 return true; 9420 9421 // 2. Bad conversions come first and are ordered by the number 9422 // of bad conversions and quality of good conversions. 9423 if (L->FailureKind == ovl_fail_bad_conversion) { 9424 if (R->FailureKind != ovl_fail_bad_conversion) 9425 return true; 9426 9427 // The conversion that can be fixed with a smaller number of changes, 9428 // comes first. 9429 unsigned numLFixes = L->Fix.NumConversionsFixed; 9430 unsigned numRFixes = R->Fix.NumConversionsFixed; 9431 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 9432 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 9433 if (numLFixes != numRFixes) { 9434 if (numLFixes < numRFixes) 9435 return true; 9436 else 9437 return false; 9438 } 9439 9440 // If there's any ordering between the defined conversions... 9441 // FIXME: this might not be transitive. 9442 assert(L->NumConversions == R->NumConversions); 9443 9444 int leftBetter = 0; 9445 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 9446 for (unsigned E = L->NumConversions; I != E; ++I) { 9447 switch (CompareImplicitConversionSequences(S, 9448 L->Conversions[I], 9449 R->Conversions[I])) { 9450 case ImplicitConversionSequence::Better: 9451 leftBetter++; 9452 break; 9453 9454 case ImplicitConversionSequence::Worse: 9455 leftBetter--; 9456 break; 9457 9458 case ImplicitConversionSequence::Indistinguishable: 9459 break; 9460 } 9461 } 9462 if (leftBetter > 0) return true; 9463 if (leftBetter < 0) return false; 9464 9465 } else if (R->FailureKind == ovl_fail_bad_conversion) 9466 return false; 9467 9468 if (L->FailureKind == ovl_fail_bad_deduction) { 9469 if (R->FailureKind != ovl_fail_bad_deduction) 9470 return true; 9471 9472 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9473 return RankDeductionFailure(L->DeductionFailure) 9474 < RankDeductionFailure(R->DeductionFailure); 9475 } else if (R->FailureKind == ovl_fail_bad_deduction) 9476 return false; 9477 9478 // TODO: others? 9479 } 9480 9481 // Sort everything else by location. 9482 SourceLocation LLoc = GetLocationForCandidate(L); 9483 SourceLocation RLoc = GetLocationForCandidate(R); 9484 9485 // Put candidates without locations (e.g. builtins) at the end. 9486 if (LLoc.isInvalid()) return false; 9487 if (RLoc.isInvalid()) return true; 9488 9489 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9490 } 9491 }; 9492 } 9493 9494 /// CompleteNonViableCandidate - Normally, overload resolution only 9495 /// computes up to the first. Produces the FixIt set if possible. 9496 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 9497 ArrayRef<Expr *> Args) { 9498 assert(!Cand->Viable); 9499 9500 // Don't do anything on failures other than bad conversion. 9501 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 9502 9503 // We only want the FixIts if all the arguments can be corrected. 9504 bool Unfixable = false; 9505 // Use a implicit copy initialization to check conversion fixes. 9506 Cand->Fix.setConversionChecker(TryCopyInitialization); 9507 9508 // Skip forward to the first bad conversion. 9509 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 9510 unsigned ConvCount = Cand->NumConversions; 9511 while (true) { 9512 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 9513 ConvIdx++; 9514 if (Cand->Conversions[ConvIdx - 1].isBad()) { 9515 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 9516 break; 9517 } 9518 } 9519 9520 if (ConvIdx == ConvCount) 9521 return; 9522 9523 assert(!Cand->Conversions[ConvIdx].isInitialized() && 9524 "remaining conversion is initialized?"); 9525 9526 // FIXME: this should probably be preserved from the overload 9527 // operation somehow. 9528 bool SuppressUserConversions = false; 9529 9530 const FunctionProtoType* Proto; 9531 unsigned ArgIdx = ConvIdx; 9532 9533 if (Cand->IsSurrogate) { 9534 QualType ConvType 9535 = Cand->Surrogate->getConversionType().getNonReferenceType(); 9536 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9537 ConvType = ConvPtrType->getPointeeType(); 9538 Proto = ConvType->getAs<FunctionProtoType>(); 9539 ArgIdx--; 9540 } else if (Cand->Function) { 9541 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 9542 if (isa<CXXMethodDecl>(Cand->Function) && 9543 !isa<CXXConstructorDecl>(Cand->Function)) 9544 ArgIdx--; 9545 } else { 9546 // Builtin binary operator with a bad first conversion. 9547 assert(ConvCount <= 3); 9548 for (; ConvIdx != ConvCount; ++ConvIdx) 9549 Cand->Conversions[ConvIdx] 9550 = TryCopyInitialization(S, Args[ConvIdx], 9551 Cand->BuiltinTypes.ParamTypes[ConvIdx], 9552 SuppressUserConversions, 9553 /*InOverloadResolution*/ true, 9554 /*AllowObjCWritebackConversion=*/ 9555 S.getLangOpts().ObjCAutoRefCount); 9556 return; 9557 } 9558 9559 // Fill in the rest of the conversions. 9560 unsigned NumParams = Proto->getNumParams(); 9561 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 9562 if (ArgIdx < NumParams) { 9563 Cand->Conversions[ConvIdx] = TryCopyInitialization( 9564 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 9565 /*InOverloadResolution=*/true, 9566 /*AllowObjCWritebackConversion=*/ 9567 S.getLangOpts().ObjCAutoRefCount); 9568 // Store the FixIt in the candidate if it exists. 9569 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 9570 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 9571 } 9572 else 9573 Cand->Conversions[ConvIdx].setEllipsis(); 9574 } 9575 } 9576 9577 /// PrintOverloadCandidates - When overload resolution fails, prints 9578 /// diagnostic messages containing the candidates in the candidate 9579 /// set. 9580 void OverloadCandidateSet::NoteCandidates(Sema &S, 9581 OverloadCandidateDisplayKind OCD, 9582 ArrayRef<Expr *> Args, 9583 StringRef Opc, 9584 SourceLocation OpLoc) { 9585 // Sort the candidates by viability and position. Sorting directly would 9586 // be prohibitive, so we make a set of pointers and sort those. 9587 SmallVector<OverloadCandidate*, 32> Cands; 9588 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 9589 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9590 if (Cand->Viable) 9591 Cands.push_back(Cand); 9592 else if (OCD == OCD_AllCandidates) { 9593 CompleteNonViableCandidate(S, Cand, Args); 9594 if (Cand->Function || Cand->IsSurrogate) 9595 Cands.push_back(Cand); 9596 // Otherwise, this a non-viable builtin candidate. We do not, in general, 9597 // want to list every possible builtin candidate. 9598 } 9599 } 9600 9601 std::sort(Cands.begin(), Cands.end(), 9602 CompareOverloadCandidatesForDisplay(S, Args.size())); 9603 9604 bool ReportedAmbiguousConversions = false; 9605 9606 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 9607 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9608 unsigned CandsShown = 0; 9609 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9610 OverloadCandidate *Cand = *I; 9611 9612 // Set an arbitrary limit on the number of candidate functions we'll spam 9613 // the user with. FIXME: This limit should depend on details of the 9614 // candidate list. 9615 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 9616 break; 9617 } 9618 ++CandsShown; 9619 9620 if (Cand->Function) 9621 NoteFunctionCandidate(S, Cand, Args.size()); 9622 else if (Cand->IsSurrogate) 9623 NoteSurrogateCandidate(S, Cand); 9624 else { 9625 assert(Cand->Viable && 9626 "Non-viable built-in candidates are not added to Cands."); 9627 // Generally we only see ambiguities including viable builtin 9628 // operators if overload resolution got screwed up by an 9629 // ambiguous user-defined conversion. 9630 // 9631 // FIXME: It's quite possible for different conversions to see 9632 // different ambiguities, though. 9633 if (!ReportedAmbiguousConversions) { 9634 NoteAmbiguousUserConversions(S, OpLoc, Cand); 9635 ReportedAmbiguousConversions = true; 9636 } 9637 9638 // If this is a viable builtin, print it. 9639 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 9640 } 9641 } 9642 9643 if (I != E) 9644 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 9645 } 9646 9647 static SourceLocation 9648 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 9649 return Cand->Specialization ? Cand->Specialization->getLocation() 9650 : SourceLocation(); 9651 } 9652 9653 namespace { 9654 struct CompareTemplateSpecCandidatesForDisplay { 9655 Sema &S; 9656 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 9657 9658 bool operator()(const TemplateSpecCandidate *L, 9659 const TemplateSpecCandidate *R) { 9660 // Fast-path this check. 9661 if (L == R) 9662 return false; 9663 9664 // Assuming that both candidates are not matches... 9665 9666 // Sort by the ranking of deduction failures. 9667 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9668 return RankDeductionFailure(L->DeductionFailure) < 9669 RankDeductionFailure(R->DeductionFailure); 9670 9671 // Sort everything else by location. 9672 SourceLocation LLoc = GetLocationForCandidate(L); 9673 SourceLocation RLoc = GetLocationForCandidate(R); 9674 9675 // Put candidates without locations (e.g. builtins) at the end. 9676 if (LLoc.isInvalid()) 9677 return false; 9678 if (RLoc.isInvalid()) 9679 return true; 9680 9681 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9682 } 9683 }; 9684 } 9685 9686 /// Diagnose a template argument deduction failure. 9687 /// We are treating these failures as overload failures due to bad 9688 /// deductions. 9689 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) { 9690 DiagnoseBadDeduction(S, Specialization, // pattern 9691 DeductionFailure, /*NumArgs=*/0); 9692 } 9693 9694 void TemplateSpecCandidateSet::destroyCandidates() { 9695 for (iterator i = begin(), e = end(); i != e; ++i) { 9696 i->DeductionFailure.Destroy(); 9697 } 9698 } 9699 9700 void TemplateSpecCandidateSet::clear() { 9701 destroyCandidates(); 9702 Candidates.clear(); 9703 } 9704 9705 /// NoteCandidates - When no template specialization match is found, prints 9706 /// diagnostic messages containing the non-matching specializations that form 9707 /// the candidate set. 9708 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 9709 /// OCD == OCD_AllCandidates and Cand->Viable == false. 9710 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 9711 // Sort the candidates by position (assuming no candidate is a match). 9712 // Sorting directly would be prohibitive, so we make a set of pointers 9713 // and sort those. 9714 SmallVector<TemplateSpecCandidate *, 32> Cands; 9715 Cands.reserve(size()); 9716 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9717 if (Cand->Specialization) 9718 Cands.push_back(Cand); 9719 // Otherwise, this is a non-matching builtin candidate. We do not, 9720 // in general, want to list every possible builtin candidate. 9721 } 9722 9723 std::sort(Cands.begin(), Cands.end(), 9724 CompareTemplateSpecCandidatesForDisplay(S)); 9725 9726 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 9727 // for generalization purposes (?). 9728 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9729 9730 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 9731 unsigned CandsShown = 0; 9732 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9733 TemplateSpecCandidate *Cand = *I; 9734 9735 // Set an arbitrary limit on the number of candidates we'll spam 9736 // the user with. FIXME: This limit should depend on details of the 9737 // candidate list. 9738 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9739 break; 9740 ++CandsShown; 9741 9742 assert(Cand->Specialization && 9743 "Non-matching built-in candidates are not added to Cands."); 9744 Cand->NoteDeductionFailure(S); 9745 } 9746 9747 if (I != E) 9748 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 9749 } 9750 9751 // [PossiblyAFunctionType] --> [Return] 9752 // NonFunctionType --> NonFunctionType 9753 // R (A) --> R(A) 9754 // R (*)(A) --> R (A) 9755 // R (&)(A) --> R (A) 9756 // R (S::*)(A) --> R (A) 9757 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 9758 QualType Ret = PossiblyAFunctionType; 9759 if (const PointerType *ToTypePtr = 9760 PossiblyAFunctionType->getAs<PointerType>()) 9761 Ret = ToTypePtr->getPointeeType(); 9762 else if (const ReferenceType *ToTypeRef = 9763 PossiblyAFunctionType->getAs<ReferenceType>()) 9764 Ret = ToTypeRef->getPointeeType(); 9765 else if (const MemberPointerType *MemTypePtr = 9766 PossiblyAFunctionType->getAs<MemberPointerType>()) 9767 Ret = MemTypePtr->getPointeeType(); 9768 Ret = 9769 Context.getCanonicalType(Ret).getUnqualifiedType(); 9770 return Ret; 9771 } 9772 9773 namespace { 9774 // A helper class to help with address of function resolution 9775 // - allows us to avoid passing around all those ugly parameters 9776 class AddressOfFunctionResolver { 9777 Sema& S; 9778 Expr* SourceExpr; 9779 const QualType& TargetType; 9780 QualType TargetFunctionType; // Extracted function type from target type 9781 9782 bool Complain; 9783 //DeclAccessPair& ResultFunctionAccessPair; 9784 ASTContext& Context; 9785 9786 bool TargetTypeIsNonStaticMemberFunction; 9787 bool FoundNonTemplateFunction; 9788 bool StaticMemberFunctionFromBoundPointer; 9789 9790 OverloadExpr::FindResult OvlExprInfo; 9791 OverloadExpr *OvlExpr; 9792 TemplateArgumentListInfo OvlExplicitTemplateArgs; 9793 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 9794 TemplateSpecCandidateSet FailedCandidates; 9795 9796 public: 9797 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 9798 const QualType &TargetType, bool Complain) 9799 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 9800 Complain(Complain), Context(S.getASTContext()), 9801 TargetTypeIsNonStaticMemberFunction( 9802 !!TargetType->getAs<MemberPointerType>()), 9803 FoundNonTemplateFunction(false), 9804 StaticMemberFunctionFromBoundPointer(false), 9805 OvlExprInfo(OverloadExpr::find(SourceExpr)), 9806 OvlExpr(OvlExprInfo.Expression), 9807 FailedCandidates(OvlExpr->getNameLoc()) { 9808 ExtractUnqualifiedFunctionTypeFromTargetType(); 9809 9810 if (TargetFunctionType->isFunctionType()) { 9811 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 9812 if (!UME->isImplicitAccess() && 9813 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 9814 StaticMemberFunctionFromBoundPointer = true; 9815 } else if (OvlExpr->hasExplicitTemplateArgs()) { 9816 DeclAccessPair dap; 9817 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 9818 OvlExpr, false, &dap)) { 9819 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 9820 if (!Method->isStatic()) { 9821 // If the target type is a non-function type and the function found 9822 // is a non-static member function, pretend as if that was the 9823 // target, it's the only possible type to end up with. 9824 TargetTypeIsNonStaticMemberFunction = true; 9825 9826 // And skip adding the function if its not in the proper form. 9827 // We'll diagnose this due to an empty set of functions. 9828 if (!OvlExprInfo.HasFormOfMemberPointer) 9829 return; 9830 } 9831 9832 Matches.push_back(std::make_pair(dap, Fn)); 9833 } 9834 return; 9835 } 9836 9837 if (OvlExpr->hasExplicitTemplateArgs()) 9838 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 9839 9840 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 9841 // C++ [over.over]p4: 9842 // If more than one function is selected, [...] 9843 if (Matches.size() > 1) { 9844 if (FoundNonTemplateFunction) 9845 EliminateAllTemplateMatches(); 9846 else 9847 EliminateAllExceptMostSpecializedTemplate(); 9848 } 9849 } 9850 } 9851 9852 private: 9853 bool isTargetTypeAFunction() const { 9854 return TargetFunctionType->isFunctionType(); 9855 } 9856 9857 // [ToType] [Return] 9858 9859 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 9860 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 9861 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 9862 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 9863 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 9864 } 9865 9866 // return true if any matching specializations were found 9867 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 9868 const DeclAccessPair& CurAccessFunPair) { 9869 if (CXXMethodDecl *Method 9870 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 9871 // Skip non-static function templates when converting to pointer, and 9872 // static when converting to member pointer. 9873 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9874 return false; 9875 } 9876 else if (TargetTypeIsNonStaticMemberFunction) 9877 return false; 9878 9879 // C++ [over.over]p2: 9880 // If the name is a function template, template argument deduction is 9881 // done (14.8.2.2), and if the argument deduction succeeds, the 9882 // resulting template argument list is used to generate a single 9883 // function template specialization, which is added to the set of 9884 // overloaded functions considered. 9885 FunctionDecl *Specialization = nullptr; 9886 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 9887 if (Sema::TemplateDeductionResult Result 9888 = S.DeduceTemplateArguments(FunctionTemplate, 9889 &OvlExplicitTemplateArgs, 9890 TargetFunctionType, Specialization, 9891 Info, /*InOverloadResolution=*/true)) { 9892 // Make a note of the failed deduction for diagnostics. 9893 FailedCandidates.addCandidate() 9894 .set(FunctionTemplate->getTemplatedDecl(), 9895 MakeDeductionFailureInfo(Context, Result, Info)); 9896 return false; 9897 } 9898 9899 // Template argument deduction ensures that we have an exact match or 9900 // compatible pointer-to-function arguments that would be adjusted by ICS. 9901 // This function template specicalization works. 9902 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 9903 assert(S.isSameOrCompatibleFunctionType( 9904 Context.getCanonicalType(Specialization->getType()), 9905 Context.getCanonicalType(TargetFunctionType))); 9906 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 9907 return true; 9908 } 9909 9910 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9911 const DeclAccessPair& CurAccessFunPair) { 9912 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9913 // Skip non-static functions when converting to pointer, and static 9914 // when converting to member pointer. 9915 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9916 return false; 9917 } 9918 else if (TargetTypeIsNonStaticMemberFunction) 9919 return false; 9920 9921 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9922 if (S.getLangOpts().CUDA) 9923 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9924 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl)) 9925 return false; 9926 9927 // If any candidate has a placeholder return type, trigger its deduction 9928 // now. 9929 if (S.getLangOpts().CPlusPlus14 && 9930 FunDecl->getReturnType()->isUndeducedType() && 9931 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) 9932 return false; 9933 9934 QualType ResultTy; 9935 if (Context.hasSameUnqualifiedType(TargetFunctionType, 9936 FunDecl->getType()) || 9937 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9938 ResultTy)) { 9939 Matches.push_back(std::make_pair(CurAccessFunPair, 9940 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9941 FoundNonTemplateFunction = true; 9942 return true; 9943 } 9944 } 9945 9946 return false; 9947 } 9948 9949 bool FindAllFunctionsThatMatchTargetTypeExactly() { 9950 bool Ret = false; 9951 9952 // If the overload expression doesn't have the form of a pointer to 9953 // member, don't try to convert it to a pointer-to-member type. 9954 if (IsInvalidFormOfPointerToMemberFunction()) 9955 return false; 9956 9957 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9958 E = OvlExpr->decls_end(); 9959 I != E; ++I) { 9960 // Look through any using declarations to find the underlying function. 9961 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 9962 9963 // C++ [over.over]p3: 9964 // Non-member functions and static member functions match 9965 // targets of type "pointer-to-function" or "reference-to-function." 9966 // Nonstatic member functions match targets of 9967 // type "pointer-to-member-function." 9968 // Note that according to DR 247, the containing class does not matter. 9969 if (FunctionTemplateDecl *FunctionTemplate 9970 = dyn_cast<FunctionTemplateDecl>(Fn)) { 9971 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 9972 Ret = true; 9973 } 9974 // If we have explicit template arguments supplied, skip non-templates. 9975 else if (!OvlExpr->hasExplicitTemplateArgs() && 9976 AddMatchingNonTemplateFunction(Fn, I.getPair())) 9977 Ret = true; 9978 } 9979 assert(Ret || Matches.empty()); 9980 return Ret; 9981 } 9982 9983 void EliminateAllExceptMostSpecializedTemplate() { 9984 // [...] and any given function template specialization F1 is 9985 // eliminated if the set contains a second function template 9986 // specialization whose function template is more specialized 9987 // than the function template of F1 according to the partial 9988 // ordering rules of 14.5.5.2. 9989 9990 // The algorithm specified above is quadratic. We instead use a 9991 // two-pass algorithm (similar to the one used to identify the 9992 // best viable function in an overload set) that identifies the 9993 // best function template (if it exists). 9994 9995 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 9996 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 9997 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 9998 9999 // TODO: It looks like FailedCandidates does not serve much purpose 10000 // here, since the no_viable diagnostic has index 0. 10001 UnresolvedSetIterator Result = S.getMostSpecialized( 10002 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 10003 SourceExpr->getLocStart(), S.PDiag(), 10004 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0] 10005 .second->getDeclName(), 10006 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template, 10007 Complain, TargetFunctionType); 10008 10009 if (Result != MatchesCopy.end()) { 10010 // Make it the first and only element 10011 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 10012 Matches[0].second = cast<FunctionDecl>(*Result); 10013 Matches.resize(1); 10014 } 10015 } 10016 10017 void EliminateAllTemplateMatches() { 10018 // [...] any function template specializations in the set are 10019 // eliminated if the set also contains a non-template function, [...] 10020 for (unsigned I = 0, N = Matches.size(); I != N; ) { 10021 if (Matches[I].second->getPrimaryTemplate() == nullptr) 10022 ++I; 10023 else { 10024 Matches[I] = Matches[--N]; 10025 Matches.set_size(N); 10026 } 10027 } 10028 } 10029 10030 public: 10031 void ComplainNoMatchesFound() const { 10032 assert(Matches.empty()); 10033 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 10034 << OvlExpr->getName() << TargetFunctionType 10035 << OvlExpr->getSourceRange(); 10036 if (FailedCandidates.empty()) 10037 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 10038 else { 10039 // We have some deduction failure messages. Use them to diagnose 10040 // the function templates, and diagnose the non-template candidates 10041 // normally. 10042 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10043 IEnd = OvlExpr->decls_end(); 10044 I != IEnd; ++I) 10045 if (FunctionDecl *Fun = 10046 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 10047 S.NoteOverloadCandidate(Fun, TargetFunctionType); 10048 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 10049 } 10050 } 10051 10052 bool IsInvalidFormOfPointerToMemberFunction() const { 10053 return TargetTypeIsNonStaticMemberFunction && 10054 !OvlExprInfo.HasFormOfMemberPointer; 10055 } 10056 10057 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 10058 // TODO: Should we condition this on whether any functions might 10059 // have matched, or is it more appropriate to do that in callers? 10060 // TODO: a fixit wouldn't hurt. 10061 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 10062 << TargetType << OvlExpr->getSourceRange(); 10063 } 10064 10065 bool IsStaticMemberFunctionFromBoundPointer() const { 10066 return StaticMemberFunctionFromBoundPointer; 10067 } 10068 10069 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 10070 S.Diag(OvlExpr->getLocStart(), 10071 diag::err_invalid_form_pointer_member_function) 10072 << OvlExpr->getSourceRange(); 10073 } 10074 10075 void ComplainOfInvalidConversion() const { 10076 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 10077 << OvlExpr->getName() << TargetType; 10078 } 10079 10080 void ComplainMultipleMatchesFound() const { 10081 assert(Matches.size() > 1); 10082 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 10083 << OvlExpr->getName() 10084 << OvlExpr->getSourceRange(); 10085 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 10086 } 10087 10088 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 10089 10090 int getNumMatches() const { return Matches.size(); } 10091 10092 FunctionDecl* getMatchingFunctionDecl() const { 10093 if (Matches.size() != 1) return nullptr; 10094 return Matches[0].second; 10095 } 10096 10097 const DeclAccessPair* getMatchingFunctionAccessPair() const { 10098 if (Matches.size() != 1) return nullptr; 10099 return &Matches[0].first; 10100 } 10101 }; 10102 } 10103 10104 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 10105 /// an overloaded function (C++ [over.over]), where @p From is an 10106 /// expression with overloaded function type and @p ToType is the type 10107 /// we're trying to resolve to. For example: 10108 /// 10109 /// @code 10110 /// int f(double); 10111 /// int f(int); 10112 /// 10113 /// int (*pfd)(double) = f; // selects f(double) 10114 /// @endcode 10115 /// 10116 /// This routine returns the resulting FunctionDecl if it could be 10117 /// resolved, and NULL otherwise. When @p Complain is true, this 10118 /// routine will emit diagnostics if there is an error. 10119 FunctionDecl * 10120 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 10121 QualType TargetType, 10122 bool Complain, 10123 DeclAccessPair &FoundResult, 10124 bool *pHadMultipleCandidates) { 10125 assert(AddressOfExpr->getType() == Context.OverloadTy); 10126 10127 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 10128 Complain); 10129 int NumMatches = Resolver.getNumMatches(); 10130 FunctionDecl *Fn = nullptr; 10131 if (NumMatches == 0 && Complain) { 10132 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 10133 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 10134 else 10135 Resolver.ComplainNoMatchesFound(); 10136 } 10137 else if (NumMatches > 1 && Complain) 10138 Resolver.ComplainMultipleMatchesFound(); 10139 else if (NumMatches == 1) { 10140 Fn = Resolver.getMatchingFunctionDecl(); 10141 assert(Fn); 10142 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 10143 if (Complain) { 10144 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 10145 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 10146 else 10147 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 10148 } 10149 } 10150 10151 if (pHadMultipleCandidates) 10152 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 10153 return Fn; 10154 } 10155 10156 /// \brief Given an expression that refers to an overloaded function, try to 10157 /// resolve that overloaded function expression down to a single function. 10158 /// 10159 /// This routine can only resolve template-ids that refer to a single function 10160 /// template, where that template-id refers to a single template whose template 10161 /// arguments are either provided by the template-id or have defaults, 10162 /// as described in C++0x [temp.arg.explicit]p3. 10163 /// 10164 /// If no template-ids are found, no diagnostics are emitted and NULL is 10165 /// returned. 10166 FunctionDecl * 10167 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 10168 bool Complain, 10169 DeclAccessPair *FoundResult) { 10170 // C++ [over.over]p1: 10171 // [...] [Note: any redundant set of parentheses surrounding the 10172 // overloaded function name is ignored (5.1). ] 10173 // C++ [over.over]p1: 10174 // [...] The overloaded function name can be preceded by the & 10175 // operator. 10176 10177 // If we didn't actually find any template-ids, we're done. 10178 if (!ovl->hasExplicitTemplateArgs()) 10179 return nullptr; 10180 10181 TemplateArgumentListInfo ExplicitTemplateArgs; 10182 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 10183 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 10184 10185 // Look through all of the overloaded functions, searching for one 10186 // whose type matches exactly. 10187 FunctionDecl *Matched = nullptr; 10188 for (UnresolvedSetIterator I = ovl->decls_begin(), 10189 E = ovl->decls_end(); I != E; ++I) { 10190 // C++0x [temp.arg.explicit]p3: 10191 // [...] In contexts where deduction is done and fails, or in contexts 10192 // where deduction is not done, if a template argument list is 10193 // specified and it, along with any default template arguments, 10194 // identifies a single function template specialization, then the 10195 // template-id is an lvalue for the function template specialization. 10196 FunctionTemplateDecl *FunctionTemplate 10197 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 10198 10199 // C++ [over.over]p2: 10200 // If the name is a function template, template argument deduction is 10201 // done (14.8.2.2), and if the argument deduction succeeds, the 10202 // resulting template argument list is used to generate a single 10203 // function template specialization, which is added to the set of 10204 // overloaded functions considered. 10205 FunctionDecl *Specialization = nullptr; 10206 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10207 if (TemplateDeductionResult Result 10208 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 10209 Specialization, Info, 10210 /*InOverloadResolution=*/true)) { 10211 // Make a note of the failed deduction for diagnostics. 10212 // TODO: Actually use the failed-deduction info? 10213 FailedCandidates.addCandidate() 10214 .set(FunctionTemplate->getTemplatedDecl(), 10215 MakeDeductionFailureInfo(Context, Result, Info)); 10216 continue; 10217 } 10218 10219 assert(Specialization && "no specialization and no error?"); 10220 10221 // Multiple matches; we can't resolve to a single declaration. 10222 if (Matched) { 10223 if (Complain) { 10224 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 10225 << ovl->getName(); 10226 NoteAllOverloadCandidates(ovl); 10227 } 10228 return nullptr; 10229 } 10230 10231 Matched = Specialization; 10232 if (FoundResult) *FoundResult = I.getPair(); 10233 } 10234 10235 if (Matched && getLangOpts().CPlusPlus14 && 10236 Matched->getReturnType()->isUndeducedType() && 10237 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 10238 return nullptr; 10239 10240 return Matched; 10241 } 10242 10243 10244 10245 10246 // Resolve and fix an overloaded expression that can be resolved 10247 // because it identifies a single function template specialization. 10248 // 10249 // Last three arguments should only be supplied if Complain = true 10250 // 10251 // Return true if it was logically possible to so resolve the 10252 // expression, regardless of whether or not it succeeded. Always 10253 // returns true if 'complain' is set. 10254 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 10255 ExprResult &SrcExpr, bool doFunctionPointerConverion, 10256 bool complain, const SourceRange& OpRangeForComplaining, 10257 QualType DestTypeForComplaining, 10258 unsigned DiagIDForComplaining) { 10259 assert(SrcExpr.get()->getType() == Context.OverloadTy); 10260 10261 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 10262 10263 DeclAccessPair found; 10264 ExprResult SingleFunctionExpression; 10265 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 10266 ovl.Expression, /*complain*/ false, &found)) { 10267 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 10268 SrcExpr = ExprError(); 10269 return true; 10270 } 10271 10272 // It is only correct to resolve to an instance method if we're 10273 // resolving a form that's permitted to be a pointer to member. 10274 // Otherwise we'll end up making a bound member expression, which 10275 // is illegal in all the contexts we resolve like this. 10276 if (!ovl.HasFormOfMemberPointer && 10277 isa<CXXMethodDecl>(fn) && 10278 cast<CXXMethodDecl>(fn)->isInstance()) { 10279 if (!complain) return false; 10280 10281 Diag(ovl.Expression->getExprLoc(), 10282 diag::err_bound_member_function) 10283 << 0 << ovl.Expression->getSourceRange(); 10284 10285 // TODO: I believe we only end up here if there's a mix of 10286 // static and non-static candidates (otherwise the expression 10287 // would have 'bound member' type, not 'overload' type). 10288 // Ideally we would note which candidate was chosen and why 10289 // the static candidates were rejected. 10290 SrcExpr = ExprError(); 10291 return true; 10292 } 10293 10294 // Fix the expression to refer to 'fn'. 10295 SingleFunctionExpression = 10296 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 10297 10298 // If desired, do function-to-pointer decay. 10299 if (doFunctionPointerConverion) { 10300 SingleFunctionExpression = 10301 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 10302 if (SingleFunctionExpression.isInvalid()) { 10303 SrcExpr = ExprError(); 10304 return true; 10305 } 10306 } 10307 } 10308 10309 if (!SingleFunctionExpression.isUsable()) { 10310 if (complain) { 10311 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 10312 << ovl.Expression->getName() 10313 << DestTypeForComplaining 10314 << OpRangeForComplaining 10315 << ovl.Expression->getQualifierLoc().getSourceRange(); 10316 NoteAllOverloadCandidates(SrcExpr.get()); 10317 10318 SrcExpr = ExprError(); 10319 return true; 10320 } 10321 10322 return false; 10323 } 10324 10325 SrcExpr = SingleFunctionExpression; 10326 return true; 10327 } 10328 10329 /// \brief Add a single candidate to the overload set. 10330 static void AddOverloadedCallCandidate(Sema &S, 10331 DeclAccessPair FoundDecl, 10332 TemplateArgumentListInfo *ExplicitTemplateArgs, 10333 ArrayRef<Expr *> Args, 10334 OverloadCandidateSet &CandidateSet, 10335 bool PartialOverloading, 10336 bool KnownValid) { 10337 NamedDecl *Callee = FoundDecl.getDecl(); 10338 if (isa<UsingShadowDecl>(Callee)) 10339 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 10340 10341 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 10342 if (ExplicitTemplateArgs) { 10343 assert(!KnownValid && "Explicit template arguments?"); 10344 return; 10345 } 10346 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false, 10347 PartialOverloading); 10348 return; 10349 } 10350 10351 if (FunctionTemplateDecl *FuncTemplate 10352 = dyn_cast<FunctionTemplateDecl>(Callee)) { 10353 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 10354 ExplicitTemplateArgs, Args, CandidateSet); 10355 return; 10356 } 10357 10358 assert(!KnownValid && "unhandled case in overloaded call candidate"); 10359 } 10360 10361 /// \brief Add the overload candidates named by callee and/or found by argument 10362 /// dependent lookup to the given overload set. 10363 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 10364 ArrayRef<Expr *> Args, 10365 OverloadCandidateSet &CandidateSet, 10366 bool PartialOverloading) { 10367 10368 #ifndef NDEBUG 10369 // Verify that ArgumentDependentLookup is consistent with the rules 10370 // in C++0x [basic.lookup.argdep]p3: 10371 // 10372 // Let X be the lookup set produced by unqualified lookup (3.4.1) 10373 // and let Y be the lookup set produced by argument dependent 10374 // lookup (defined as follows). If X contains 10375 // 10376 // -- a declaration of a class member, or 10377 // 10378 // -- a block-scope function declaration that is not a 10379 // using-declaration, or 10380 // 10381 // -- a declaration that is neither a function or a function 10382 // template 10383 // 10384 // then Y is empty. 10385 10386 if (ULE->requiresADL()) { 10387 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10388 E = ULE->decls_end(); I != E; ++I) { 10389 assert(!(*I)->getDeclContext()->isRecord()); 10390 assert(isa<UsingShadowDecl>(*I) || 10391 !(*I)->getDeclContext()->isFunctionOrMethod()); 10392 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 10393 } 10394 } 10395 #endif 10396 10397 // It would be nice to avoid this copy. 10398 TemplateArgumentListInfo TABuffer; 10399 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 10400 if (ULE->hasExplicitTemplateArgs()) { 10401 ULE->copyTemplateArgumentsInto(TABuffer); 10402 ExplicitTemplateArgs = &TABuffer; 10403 } 10404 10405 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10406 E = ULE->decls_end(); I != E; ++I) 10407 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 10408 CandidateSet, PartialOverloading, 10409 /*KnownValid*/ true); 10410 10411 if (ULE->requiresADL()) 10412 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 10413 Args, ExplicitTemplateArgs, 10414 CandidateSet, PartialOverloading); 10415 } 10416 10417 /// Determine whether a declaration with the specified name could be moved into 10418 /// a different namespace. 10419 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 10420 switch (Name.getCXXOverloadedOperator()) { 10421 case OO_New: case OO_Array_New: 10422 case OO_Delete: case OO_Array_Delete: 10423 return false; 10424 10425 default: 10426 return true; 10427 } 10428 } 10429 10430 /// Attempt to recover from an ill-formed use of a non-dependent name in a 10431 /// template, where the non-dependent name was declared after the template 10432 /// was defined. This is common in code written for a compilers which do not 10433 /// correctly implement two-stage name lookup. 10434 /// 10435 /// Returns true if a viable candidate was found and a diagnostic was issued. 10436 static bool 10437 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 10438 const CXXScopeSpec &SS, LookupResult &R, 10439 OverloadCandidateSet::CandidateSetKind CSK, 10440 TemplateArgumentListInfo *ExplicitTemplateArgs, 10441 ArrayRef<Expr *> Args) { 10442 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 10443 return false; 10444 10445 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 10446 if (DC->isTransparentContext()) 10447 continue; 10448 10449 SemaRef.LookupQualifiedName(R, DC); 10450 10451 if (!R.empty()) { 10452 R.suppressDiagnostics(); 10453 10454 if (isa<CXXRecordDecl>(DC)) { 10455 // Don't diagnose names we find in classes; we get much better 10456 // diagnostics for these from DiagnoseEmptyLookup. 10457 R.clear(); 10458 return false; 10459 } 10460 10461 OverloadCandidateSet Candidates(FnLoc, CSK); 10462 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10463 AddOverloadedCallCandidate(SemaRef, I.getPair(), 10464 ExplicitTemplateArgs, Args, 10465 Candidates, false, /*KnownValid*/ false); 10466 10467 OverloadCandidateSet::iterator Best; 10468 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 10469 // No viable functions. Don't bother the user with notes for functions 10470 // which don't work and shouldn't be found anyway. 10471 R.clear(); 10472 return false; 10473 } 10474 10475 // Find the namespaces where ADL would have looked, and suggest 10476 // declaring the function there instead. 10477 Sema::AssociatedNamespaceSet AssociatedNamespaces; 10478 Sema::AssociatedClassSet AssociatedClasses; 10479 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 10480 AssociatedNamespaces, 10481 AssociatedClasses); 10482 Sema::AssociatedNamespaceSet SuggestedNamespaces; 10483 if (canBeDeclaredInNamespace(R.getLookupName())) { 10484 DeclContext *Std = SemaRef.getStdNamespace(); 10485 for (Sema::AssociatedNamespaceSet::iterator 10486 it = AssociatedNamespaces.begin(), 10487 end = AssociatedNamespaces.end(); it != end; ++it) { 10488 // Never suggest declaring a function within namespace 'std'. 10489 if (Std && Std->Encloses(*it)) 10490 continue; 10491 10492 // Never suggest declaring a function within a namespace with a 10493 // reserved name, like __gnu_cxx. 10494 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 10495 if (NS && 10496 NS->getQualifiedNameAsString().find("__") != std::string::npos) 10497 continue; 10498 10499 SuggestedNamespaces.insert(*it); 10500 } 10501 } 10502 10503 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 10504 << R.getLookupName(); 10505 if (SuggestedNamespaces.empty()) { 10506 SemaRef.Diag(Best->Function->getLocation(), 10507 diag::note_not_found_by_two_phase_lookup) 10508 << R.getLookupName() << 0; 10509 } else if (SuggestedNamespaces.size() == 1) { 10510 SemaRef.Diag(Best->Function->getLocation(), 10511 diag::note_not_found_by_two_phase_lookup) 10512 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 10513 } else { 10514 // FIXME: It would be useful to list the associated namespaces here, 10515 // but the diagnostics infrastructure doesn't provide a way to produce 10516 // a localized representation of a list of items. 10517 SemaRef.Diag(Best->Function->getLocation(), 10518 diag::note_not_found_by_two_phase_lookup) 10519 << R.getLookupName() << 2; 10520 } 10521 10522 // Try to recover by calling this function. 10523 return true; 10524 } 10525 10526 R.clear(); 10527 } 10528 10529 return false; 10530 } 10531 10532 /// Attempt to recover from ill-formed use of a non-dependent operator in a 10533 /// template, where the non-dependent operator was declared after the template 10534 /// was defined. 10535 /// 10536 /// Returns true if a viable candidate was found and a diagnostic was issued. 10537 static bool 10538 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 10539 SourceLocation OpLoc, 10540 ArrayRef<Expr *> Args) { 10541 DeclarationName OpName = 10542 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 10543 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 10544 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 10545 OverloadCandidateSet::CSK_Operator, 10546 /*ExplicitTemplateArgs=*/nullptr, Args); 10547 } 10548 10549 namespace { 10550 class BuildRecoveryCallExprRAII { 10551 Sema &SemaRef; 10552 public: 10553 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 10554 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 10555 SemaRef.IsBuildingRecoveryCallExpr = true; 10556 } 10557 10558 ~BuildRecoveryCallExprRAII() { 10559 SemaRef.IsBuildingRecoveryCallExpr = false; 10560 } 10561 }; 10562 10563 } 10564 10565 static std::unique_ptr<CorrectionCandidateCallback> 10566 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 10567 bool HasTemplateArgs, bool AllowTypoCorrection) { 10568 if (!AllowTypoCorrection) 10569 return llvm::make_unique<NoTypoCorrectionCCC>(); 10570 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 10571 HasTemplateArgs, ME); 10572 } 10573 10574 /// Attempts to recover from a call where no functions were found. 10575 /// 10576 /// Returns true if new candidates were found. 10577 static ExprResult 10578 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10579 UnresolvedLookupExpr *ULE, 10580 SourceLocation LParenLoc, 10581 MutableArrayRef<Expr *> Args, 10582 SourceLocation RParenLoc, 10583 bool EmptyLookup, bool AllowTypoCorrection) { 10584 // Do not try to recover if it is already building a recovery call. 10585 // This stops infinite loops for template instantiations like 10586 // 10587 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 10588 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 10589 // 10590 if (SemaRef.IsBuildingRecoveryCallExpr) 10591 return ExprError(); 10592 BuildRecoveryCallExprRAII RCE(SemaRef); 10593 10594 CXXScopeSpec SS; 10595 SS.Adopt(ULE->getQualifierLoc()); 10596 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 10597 10598 TemplateArgumentListInfo TABuffer; 10599 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 10600 if (ULE->hasExplicitTemplateArgs()) { 10601 ULE->copyTemplateArgumentsInto(TABuffer); 10602 ExplicitTemplateArgs = &TABuffer; 10603 } 10604 10605 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 10606 Sema::LookupOrdinaryName); 10607 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 10608 OverloadCandidateSet::CSK_Normal, 10609 ExplicitTemplateArgs, Args) && 10610 (!EmptyLookup || 10611 SemaRef.DiagnoseEmptyLookup( 10612 S, SS, R, 10613 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 10614 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 10615 ExplicitTemplateArgs, Args))) 10616 return ExprError(); 10617 10618 assert(!R.empty() && "lookup results empty despite recovery"); 10619 10620 // Build an implicit member call if appropriate. Just drop the 10621 // casts and such from the call, we don't really care. 10622 ExprResult NewFn = ExprError(); 10623 if ((*R.begin())->isCXXClassMember()) 10624 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 10625 R, ExplicitTemplateArgs); 10626 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 10627 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 10628 ExplicitTemplateArgs); 10629 else 10630 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 10631 10632 if (NewFn.isInvalid()) 10633 return ExprError(); 10634 10635 // This shouldn't cause an infinite loop because we're giving it 10636 // an expression with viable lookup results, which should never 10637 // end up here. 10638 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 10639 MultiExprArg(Args.data(), Args.size()), 10640 RParenLoc); 10641 } 10642 10643 /// \brief Constructs and populates an OverloadedCandidateSet from 10644 /// the given function. 10645 /// \returns true when an the ExprResult output parameter has been set. 10646 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 10647 UnresolvedLookupExpr *ULE, 10648 MultiExprArg Args, 10649 SourceLocation RParenLoc, 10650 OverloadCandidateSet *CandidateSet, 10651 ExprResult *Result) { 10652 #ifndef NDEBUG 10653 if (ULE->requiresADL()) { 10654 // To do ADL, we must have found an unqualified name. 10655 assert(!ULE->getQualifier() && "qualified name with ADL"); 10656 10657 // We don't perform ADL for implicit declarations of builtins. 10658 // Verify that this was correctly set up. 10659 FunctionDecl *F; 10660 if (ULE->decls_begin() + 1 == ULE->decls_end() && 10661 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 10662 F->getBuiltinID() && F->isImplicit()) 10663 llvm_unreachable("performing ADL for builtin"); 10664 10665 // We don't perform ADL in C. 10666 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 10667 } 10668 #endif 10669 10670 UnbridgedCastsSet UnbridgedCasts; 10671 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 10672 *Result = ExprError(); 10673 return true; 10674 } 10675 10676 // Add the functions denoted by the callee to the set of candidate 10677 // functions, including those from argument-dependent lookup. 10678 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 10679 10680 // If we found nothing, try to recover. 10681 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 10682 // out if it fails. 10683 if (CandidateSet->empty()) { 10684 // In Microsoft mode, if we are inside a template class member function then 10685 // create a type dependent CallExpr. The goal is to postpone name lookup 10686 // to instantiation time to be able to search into type dependent base 10687 // classes. 10688 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() && 10689 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 10690 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, 10691 Context.DependentTy, VK_RValue, 10692 RParenLoc); 10693 CE->setTypeDependent(true); 10694 *Result = CE; 10695 return true; 10696 } 10697 return false; 10698 } 10699 10700 UnbridgedCasts.restore(); 10701 return false; 10702 } 10703 10704 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 10705 /// the completed call expression. If overload resolution fails, emits 10706 /// diagnostics and returns ExprError() 10707 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10708 UnresolvedLookupExpr *ULE, 10709 SourceLocation LParenLoc, 10710 MultiExprArg Args, 10711 SourceLocation RParenLoc, 10712 Expr *ExecConfig, 10713 OverloadCandidateSet *CandidateSet, 10714 OverloadCandidateSet::iterator *Best, 10715 OverloadingResult OverloadResult, 10716 bool AllowTypoCorrection) { 10717 if (CandidateSet->empty()) 10718 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 10719 RParenLoc, /*EmptyLookup=*/true, 10720 AllowTypoCorrection); 10721 10722 switch (OverloadResult) { 10723 case OR_Success: { 10724 FunctionDecl *FDecl = (*Best)->Function; 10725 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 10726 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 10727 return ExprError(); 10728 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10729 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10730 ExecConfig); 10731 } 10732 10733 case OR_No_Viable_Function: { 10734 // Try to recover by looking for viable functions which the user might 10735 // have meant to call. 10736 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 10737 Args, RParenLoc, 10738 /*EmptyLookup=*/false, 10739 AllowTypoCorrection); 10740 if (!Recovery.isInvalid()) 10741 return Recovery; 10742 10743 SemaRef.Diag(Fn->getLocStart(), 10744 diag::err_ovl_no_viable_function_in_call) 10745 << ULE->getName() << Fn->getSourceRange(); 10746 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10747 break; 10748 } 10749 10750 case OR_Ambiguous: 10751 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 10752 << ULE->getName() << Fn->getSourceRange(); 10753 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 10754 break; 10755 10756 case OR_Deleted: { 10757 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 10758 << (*Best)->Function->isDeleted() 10759 << ULE->getName() 10760 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 10761 << Fn->getSourceRange(); 10762 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10763 10764 // We emitted an error for the unvailable/deleted function call but keep 10765 // the call in the AST. 10766 FunctionDecl *FDecl = (*Best)->Function; 10767 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10768 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10769 ExecConfig); 10770 } 10771 } 10772 10773 // Overload resolution failed. 10774 return ExprError(); 10775 } 10776 10777 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 10778 /// (which eventually refers to the declaration Func) and the call 10779 /// arguments Args/NumArgs, attempt to resolve the function call down 10780 /// to a specific function. If overload resolution succeeds, returns 10781 /// the call expression produced by overload resolution. 10782 /// Otherwise, emits diagnostics and returns ExprError. 10783 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 10784 UnresolvedLookupExpr *ULE, 10785 SourceLocation LParenLoc, 10786 MultiExprArg Args, 10787 SourceLocation RParenLoc, 10788 Expr *ExecConfig, 10789 bool AllowTypoCorrection) { 10790 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 10791 OverloadCandidateSet::CSK_Normal); 10792 ExprResult result; 10793 10794 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 10795 &result)) 10796 return result; 10797 10798 OverloadCandidateSet::iterator Best; 10799 OverloadingResult OverloadResult = 10800 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 10801 10802 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 10803 RParenLoc, ExecConfig, &CandidateSet, 10804 &Best, OverloadResult, 10805 AllowTypoCorrection); 10806 } 10807 10808 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 10809 return Functions.size() > 1 || 10810 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 10811 } 10812 10813 /// \brief Create a unary operation that may resolve to an overloaded 10814 /// operator. 10815 /// 10816 /// \param OpLoc The location of the operator itself (e.g., '*'). 10817 /// 10818 /// \param OpcIn The UnaryOperator::Opcode that describes this 10819 /// operator. 10820 /// 10821 /// \param Fns The set of non-member functions that will be 10822 /// considered by overload resolution. The caller needs to build this 10823 /// set based on the context using, e.g., 10824 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10825 /// set should not contain any member functions; those will be added 10826 /// by CreateOverloadedUnaryOp(). 10827 /// 10828 /// \param Input The input argument. 10829 ExprResult 10830 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 10831 const UnresolvedSetImpl &Fns, 10832 Expr *Input) { 10833 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 10834 10835 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 10836 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 10837 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10838 // TODO: provide better source location info. 10839 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10840 10841 if (checkPlaceholderForOverload(*this, Input)) 10842 return ExprError(); 10843 10844 Expr *Args[2] = { Input, nullptr }; 10845 unsigned NumArgs = 1; 10846 10847 // For post-increment and post-decrement, add the implicit '0' as 10848 // the second argument, so that we know this is a post-increment or 10849 // post-decrement. 10850 if (Opc == UO_PostInc || Opc == UO_PostDec) { 10851 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 10852 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 10853 SourceLocation()); 10854 NumArgs = 2; 10855 } 10856 10857 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 10858 10859 if (Input->isTypeDependent()) { 10860 if (Fns.empty()) 10861 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 10862 VK_RValue, OK_Ordinary, OpLoc); 10863 10864 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 10865 UnresolvedLookupExpr *Fn 10866 = UnresolvedLookupExpr::Create(Context, NamingClass, 10867 NestedNameSpecifierLoc(), OpNameInfo, 10868 /*ADL*/ true, IsOverloaded(Fns), 10869 Fns.begin(), Fns.end()); 10870 return new (Context) 10871 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 10872 VK_RValue, OpLoc, false); 10873 } 10874 10875 // Build an empty overload set. 10876 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 10877 10878 // Add the candidates from the given function set. 10879 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false); 10880 10881 // Add operator candidates that are member functions. 10882 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10883 10884 // Add candidates from ADL. 10885 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 10886 /*ExplicitTemplateArgs*/nullptr, 10887 CandidateSet); 10888 10889 // Add builtin operator candidates. 10890 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10891 10892 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10893 10894 // Perform overload resolution. 10895 OverloadCandidateSet::iterator Best; 10896 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10897 case OR_Success: { 10898 // We found a built-in operator or an overloaded operator. 10899 FunctionDecl *FnDecl = Best->Function; 10900 10901 if (FnDecl) { 10902 // We matched an overloaded operator. Build a call to that 10903 // operator. 10904 10905 // Convert the arguments. 10906 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10907 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 10908 10909 ExprResult InputRes = 10910 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 10911 Best->FoundDecl, Method); 10912 if (InputRes.isInvalid()) 10913 return ExprError(); 10914 Input = InputRes.get(); 10915 } else { 10916 // Convert the arguments. 10917 ExprResult InputInit 10918 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10919 Context, 10920 FnDecl->getParamDecl(0)), 10921 SourceLocation(), 10922 Input); 10923 if (InputInit.isInvalid()) 10924 return ExprError(); 10925 Input = InputInit.get(); 10926 } 10927 10928 // Build the actual expression node. 10929 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 10930 HadMultipleCandidates, OpLoc); 10931 if (FnExpr.isInvalid()) 10932 return ExprError(); 10933 10934 // Determine the result type. 10935 QualType ResultTy = FnDecl->getReturnType(); 10936 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10937 ResultTy = ResultTy.getNonLValueExprType(Context); 10938 10939 Args[0] = Input; 10940 CallExpr *TheCall = 10941 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 10942 ResultTy, VK, OpLoc, false); 10943 10944 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 10945 return ExprError(); 10946 10947 return MaybeBindToTemporary(TheCall); 10948 } else { 10949 // We matched a built-in operator. Convert the arguments, then 10950 // break out so that we will build the appropriate built-in 10951 // operator node. 10952 ExprResult InputRes = 10953 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 10954 Best->Conversions[0], AA_Passing); 10955 if (InputRes.isInvalid()) 10956 return ExprError(); 10957 Input = InputRes.get(); 10958 break; 10959 } 10960 } 10961 10962 case OR_No_Viable_Function: 10963 // This is an erroneous use of an operator which can be overloaded by 10964 // a non-member function. Check for non-member operators which were 10965 // defined too late to be candidates. 10966 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 10967 // FIXME: Recover by calling the found function. 10968 return ExprError(); 10969 10970 // No viable function; fall through to handling this as a 10971 // built-in operator, which will produce an error message for us. 10972 break; 10973 10974 case OR_Ambiguous: 10975 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 10976 << UnaryOperator::getOpcodeStr(Opc) 10977 << Input->getType() 10978 << Input->getSourceRange(); 10979 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 10980 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10981 return ExprError(); 10982 10983 case OR_Deleted: 10984 Diag(OpLoc, diag::err_ovl_deleted_oper) 10985 << Best->Function->isDeleted() 10986 << UnaryOperator::getOpcodeStr(Opc) 10987 << getDeletedOrUnavailableSuffix(Best->Function) 10988 << Input->getSourceRange(); 10989 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 10990 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10991 return ExprError(); 10992 } 10993 10994 // Either we found no viable overloaded operator or we matched a 10995 // built-in operator. In either case, fall through to trying to 10996 // build a built-in operation. 10997 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10998 } 10999 11000 /// \brief Create a binary operation that may resolve to an overloaded 11001 /// operator. 11002 /// 11003 /// \param OpLoc The location of the operator itself (e.g., '+'). 11004 /// 11005 /// \param OpcIn The BinaryOperator::Opcode that describes this 11006 /// operator. 11007 /// 11008 /// \param Fns The set of non-member functions that will be 11009 /// considered by overload resolution. The caller needs to build this 11010 /// set based on the context using, e.g., 11011 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11012 /// set should not contain any member functions; those will be added 11013 /// by CreateOverloadedBinOp(). 11014 /// 11015 /// \param LHS Left-hand argument. 11016 /// \param RHS Right-hand argument. 11017 ExprResult 11018 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 11019 unsigned OpcIn, 11020 const UnresolvedSetImpl &Fns, 11021 Expr *LHS, Expr *RHS) { 11022 Expr *Args[2] = { LHS, RHS }; 11023 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 11024 11025 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 11026 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 11027 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11028 11029 // If either side is type-dependent, create an appropriate dependent 11030 // expression. 11031 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11032 if (Fns.empty()) { 11033 // If there are no functions to store, just build a dependent 11034 // BinaryOperator or CompoundAssignment. 11035 if (Opc <= BO_Assign || Opc > BO_OrAssign) 11036 return new (Context) BinaryOperator( 11037 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 11038 OpLoc, FPFeatures.fp_contract); 11039 11040 return new (Context) CompoundAssignOperator( 11041 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 11042 Context.DependentTy, Context.DependentTy, OpLoc, 11043 FPFeatures.fp_contract); 11044 } 11045 11046 // FIXME: save results of ADL from here? 11047 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11048 // TODO: provide better source location info in DNLoc component. 11049 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11050 UnresolvedLookupExpr *Fn 11051 = UnresolvedLookupExpr::Create(Context, NamingClass, 11052 NestedNameSpecifierLoc(), OpNameInfo, 11053 /*ADL*/ true, IsOverloaded(Fns), 11054 Fns.begin(), Fns.end()); 11055 return new (Context) 11056 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 11057 VK_RValue, OpLoc, FPFeatures.fp_contract); 11058 } 11059 11060 // Always do placeholder-like conversions on the RHS. 11061 if (checkPlaceholderForOverload(*this, Args[1])) 11062 return ExprError(); 11063 11064 // Do placeholder-like conversion on the LHS; note that we should 11065 // not get here with a PseudoObject LHS. 11066 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 11067 if (checkPlaceholderForOverload(*this, Args[0])) 11068 return ExprError(); 11069 11070 // If this is the assignment operator, we only perform overload resolution 11071 // if the left-hand side is a class or enumeration type. This is actually 11072 // a hack. The standard requires that we do overload resolution between the 11073 // various built-in candidates, but as DR507 points out, this can lead to 11074 // problems. So we do it this way, which pretty much follows what GCC does. 11075 // Note that we go the traditional code path for compound assignment forms. 11076 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 11077 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11078 11079 // If this is the .* operator, which is not overloadable, just 11080 // create a built-in binary operator. 11081 if (Opc == BO_PtrMemD) 11082 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11083 11084 // Build an empty overload set. 11085 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11086 11087 // Add the candidates from the given function set. 11088 AddFunctionCandidates(Fns, Args, CandidateSet, false); 11089 11090 // Add operator candidates that are member functions. 11091 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11092 11093 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 11094 // performed for an assignment operator (nor for operator[] nor operator->, 11095 // which don't get here). 11096 if (Opc != BO_Assign) 11097 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 11098 /*ExplicitTemplateArgs*/ nullptr, 11099 CandidateSet); 11100 11101 // Add builtin operator candidates. 11102 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11103 11104 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11105 11106 // Perform overload resolution. 11107 OverloadCandidateSet::iterator Best; 11108 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11109 case OR_Success: { 11110 // We found a built-in operator or an overloaded operator. 11111 FunctionDecl *FnDecl = Best->Function; 11112 11113 if (FnDecl) { 11114 // We matched an overloaded operator. Build a call to that 11115 // operator. 11116 11117 // Convert the arguments. 11118 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11119 // Best->Access is only meaningful for class members. 11120 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 11121 11122 ExprResult Arg1 = 11123 PerformCopyInitialization( 11124 InitializedEntity::InitializeParameter(Context, 11125 FnDecl->getParamDecl(0)), 11126 SourceLocation(), Args[1]); 11127 if (Arg1.isInvalid()) 11128 return ExprError(); 11129 11130 ExprResult Arg0 = 11131 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11132 Best->FoundDecl, Method); 11133 if (Arg0.isInvalid()) 11134 return ExprError(); 11135 Args[0] = Arg0.getAs<Expr>(); 11136 Args[1] = RHS = Arg1.getAs<Expr>(); 11137 } else { 11138 // Convert the arguments. 11139 ExprResult Arg0 = PerformCopyInitialization( 11140 InitializedEntity::InitializeParameter(Context, 11141 FnDecl->getParamDecl(0)), 11142 SourceLocation(), Args[0]); 11143 if (Arg0.isInvalid()) 11144 return ExprError(); 11145 11146 ExprResult Arg1 = 11147 PerformCopyInitialization( 11148 InitializedEntity::InitializeParameter(Context, 11149 FnDecl->getParamDecl(1)), 11150 SourceLocation(), Args[1]); 11151 if (Arg1.isInvalid()) 11152 return ExprError(); 11153 Args[0] = LHS = Arg0.getAs<Expr>(); 11154 Args[1] = RHS = Arg1.getAs<Expr>(); 11155 } 11156 11157 // Build the actual expression node. 11158 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11159 Best->FoundDecl, 11160 HadMultipleCandidates, OpLoc); 11161 if (FnExpr.isInvalid()) 11162 return ExprError(); 11163 11164 // Determine the result type. 11165 QualType ResultTy = FnDecl->getReturnType(); 11166 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11167 ResultTy = ResultTy.getNonLValueExprType(Context); 11168 11169 CXXOperatorCallExpr *TheCall = 11170 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 11171 Args, ResultTy, VK, OpLoc, 11172 FPFeatures.fp_contract); 11173 11174 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 11175 FnDecl)) 11176 return ExprError(); 11177 11178 ArrayRef<const Expr *> ArgsArray(Args, 2); 11179 // Cut off the implicit 'this'. 11180 if (isa<CXXMethodDecl>(FnDecl)) 11181 ArgsArray = ArgsArray.slice(1); 11182 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc, 11183 TheCall->getSourceRange(), VariadicDoesNotApply); 11184 11185 return MaybeBindToTemporary(TheCall); 11186 } else { 11187 // We matched a built-in operator. Convert the arguments, then 11188 // break out so that we will build the appropriate built-in 11189 // operator node. 11190 ExprResult ArgsRes0 = 11191 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11192 Best->Conversions[0], AA_Passing); 11193 if (ArgsRes0.isInvalid()) 11194 return ExprError(); 11195 Args[0] = ArgsRes0.get(); 11196 11197 ExprResult ArgsRes1 = 11198 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11199 Best->Conversions[1], AA_Passing); 11200 if (ArgsRes1.isInvalid()) 11201 return ExprError(); 11202 Args[1] = ArgsRes1.get(); 11203 break; 11204 } 11205 } 11206 11207 case OR_No_Viable_Function: { 11208 // C++ [over.match.oper]p9: 11209 // If the operator is the operator , [...] and there are no 11210 // viable functions, then the operator is assumed to be the 11211 // built-in operator and interpreted according to clause 5. 11212 if (Opc == BO_Comma) 11213 break; 11214 11215 // For class as left operand for assignment or compound assigment 11216 // operator do not fall through to handling in built-in, but report that 11217 // no overloaded assignment operator found 11218 ExprResult Result = ExprError(); 11219 if (Args[0]->getType()->isRecordType() && 11220 Opc >= BO_Assign && Opc <= BO_OrAssign) { 11221 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11222 << BinaryOperator::getOpcodeStr(Opc) 11223 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11224 if (Args[0]->getType()->isIncompleteType()) { 11225 Diag(OpLoc, diag::note_assign_lhs_incomplete) 11226 << Args[0]->getType() 11227 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11228 } 11229 } else { 11230 // This is an erroneous use of an operator which can be overloaded by 11231 // a non-member function. Check for non-member operators which were 11232 // defined too late to be candidates. 11233 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 11234 // FIXME: Recover by calling the found function. 11235 return ExprError(); 11236 11237 // No viable function; try to create a built-in operation, which will 11238 // produce an error. Then, show the non-viable candidates. 11239 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11240 } 11241 assert(Result.isInvalid() && 11242 "C++ binary operator overloading is missing candidates!"); 11243 if (Result.isInvalid()) 11244 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11245 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11246 return Result; 11247 } 11248 11249 case OR_Ambiguous: 11250 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 11251 << BinaryOperator::getOpcodeStr(Opc) 11252 << Args[0]->getType() << Args[1]->getType() 11253 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11254 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11255 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11256 return ExprError(); 11257 11258 case OR_Deleted: 11259 if (isImplicitlyDeleted(Best->Function)) { 11260 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11261 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 11262 << Context.getRecordType(Method->getParent()) 11263 << getSpecialMember(Method); 11264 11265 // The user probably meant to call this special member. Just 11266 // explain why it's deleted. 11267 NoteDeletedFunction(Method); 11268 return ExprError(); 11269 } else { 11270 Diag(OpLoc, diag::err_ovl_deleted_oper) 11271 << Best->Function->isDeleted() 11272 << BinaryOperator::getOpcodeStr(Opc) 11273 << getDeletedOrUnavailableSuffix(Best->Function) 11274 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11275 } 11276 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11277 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11278 return ExprError(); 11279 } 11280 11281 // We matched a built-in operator; build it. 11282 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11283 } 11284 11285 ExprResult 11286 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 11287 SourceLocation RLoc, 11288 Expr *Base, Expr *Idx) { 11289 Expr *Args[2] = { Base, Idx }; 11290 DeclarationName OpName = 11291 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 11292 11293 // If either side is type-dependent, create an appropriate dependent 11294 // expression. 11295 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11296 11297 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11298 // CHECKME: no 'operator' keyword? 11299 DeclarationNameInfo OpNameInfo(OpName, LLoc); 11300 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11301 UnresolvedLookupExpr *Fn 11302 = UnresolvedLookupExpr::Create(Context, NamingClass, 11303 NestedNameSpecifierLoc(), OpNameInfo, 11304 /*ADL*/ true, /*Overloaded*/ false, 11305 UnresolvedSetIterator(), 11306 UnresolvedSetIterator()); 11307 // Can't add any actual overloads yet 11308 11309 return new (Context) 11310 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 11311 Context.DependentTy, VK_RValue, RLoc, false); 11312 } 11313 11314 // Handle placeholders on both operands. 11315 if (checkPlaceholderForOverload(*this, Args[0])) 11316 return ExprError(); 11317 if (checkPlaceholderForOverload(*this, Args[1])) 11318 return ExprError(); 11319 11320 // Build an empty overload set. 11321 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 11322 11323 // Subscript can only be overloaded as a member function. 11324 11325 // Add operator candidates that are member functions. 11326 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11327 11328 // Add builtin operator candidates. 11329 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11330 11331 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11332 11333 // Perform overload resolution. 11334 OverloadCandidateSet::iterator Best; 11335 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 11336 case OR_Success: { 11337 // We found a built-in operator or an overloaded operator. 11338 FunctionDecl *FnDecl = Best->Function; 11339 11340 if (FnDecl) { 11341 // We matched an overloaded operator. Build a call to that 11342 // operator. 11343 11344 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 11345 11346 // Convert the arguments. 11347 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 11348 ExprResult Arg0 = 11349 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11350 Best->FoundDecl, Method); 11351 if (Arg0.isInvalid()) 11352 return ExprError(); 11353 Args[0] = Arg0.get(); 11354 11355 // Convert the arguments. 11356 ExprResult InputInit 11357 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11358 Context, 11359 FnDecl->getParamDecl(0)), 11360 SourceLocation(), 11361 Args[1]); 11362 if (InputInit.isInvalid()) 11363 return ExprError(); 11364 11365 Args[1] = InputInit.getAs<Expr>(); 11366 11367 // Build the actual expression node. 11368 DeclarationNameInfo OpLocInfo(OpName, LLoc); 11369 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11370 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11371 Best->FoundDecl, 11372 HadMultipleCandidates, 11373 OpLocInfo.getLoc(), 11374 OpLocInfo.getInfo()); 11375 if (FnExpr.isInvalid()) 11376 return ExprError(); 11377 11378 // Determine the result type 11379 QualType ResultTy = FnDecl->getReturnType(); 11380 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11381 ResultTy = ResultTy.getNonLValueExprType(Context); 11382 11383 CXXOperatorCallExpr *TheCall = 11384 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 11385 FnExpr.get(), Args, 11386 ResultTy, VK, RLoc, 11387 false); 11388 11389 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 11390 return ExprError(); 11391 11392 return MaybeBindToTemporary(TheCall); 11393 } else { 11394 // We matched a built-in operator. Convert the arguments, then 11395 // break out so that we will build the appropriate built-in 11396 // operator node. 11397 ExprResult ArgsRes0 = 11398 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11399 Best->Conversions[0], AA_Passing); 11400 if (ArgsRes0.isInvalid()) 11401 return ExprError(); 11402 Args[0] = ArgsRes0.get(); 11403 11404 ExprResult ArgsRes1 = 11405 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11406 Best->Conversions[1], AA_Passing); 11407 if (ArgsRes1.isInvalid()) 11408 return ExprError(); 11409 Args[1] = ArgsRes1.get(); 11410 11411 break; 11412 } 11413 } 11414 11415 case OR_No_Viable_Function: { 11416 if (CandidateSet.empty()) 11417 Diag(LLoc, diag::err_ovl_no_oper) 11418 << Args[0]->getType() << /*subscript*/ 0 11419 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11420 else 11421 Diag(LLoc, diag::err_ovl_no_viable_subscript) 11422 << Args[0]->getType() 11423 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11424 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11425 "[]", LLoc); 11426 return ExprError(); 11427 } 11428 11429 case OR_Ambiguous: 11430 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 11431 << "[]" 11432 << Args[0]->getType() << Args[1]->getType() 11433 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11434 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11435 "[]", LLoc); 11436 return ExprError(); 11437 11438 case OR_Deleted: 11439 Diag(LLoc, diag::err_ovl_deleted_oper) 11440 << Best->Function->isDeleted() << "[]" 11441 << getDeletedOrUnavailableSuffix(Best->Function) 11442 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11443 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11444 "[]", LLoc); 11445 return ExprError(); 11446 } 11447 11448 // We matched a built-in operator; build it. 11449 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 11450 } 11451 11452 /// BuildCallToMemberFunction - Build a call to a member 11453 /// function. MemExpr is the expression that refers to the member 11454 /// function (and includes the object parameter), Args/NumArgs are the 11455 /// arguments to the function call (not including the object 11456 /// parameter). The caller needs to validate that the member 11457 /// expression refers to a non-static member function or an overloaded 11458 /// member function. 11459 ExprResult 11460 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 11461 SourceLocation LParenLoc, 11462 MultiExprArg Args, 11463 SourceLocation RParenLoc) { 11464 assert(MemExprE->getType() == Context.BoundMemberTy || 11465 MemExprE->getType() == Context.OverloadTy); 11466 11467 // Dig out the member expression. This holds both the object 11468 // argument and the member function we're referring to. 11469 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 11470 11471 // Determine whether this is a call to a pointer-to-member function. 11472 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 11473 assert(op->getType() == Context.BoundMemberTy); 11474 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 11475 11476 QualType fnType = 11477 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 11478 11479 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 11480 QualType resultType = proto->getCallResultType(Context); 11481 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 11482 11483 // Check that the object type isn't more qualified than the 11484 // member function we're calling. 11485 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 11486 11487 QualType objectType = op->getLHS()->getType(); 11488 if (op->getOpcode() == BO_PtrMemI) 11489 objectType = objectType->castAs<PointerType>()->getPointeeType(); 11490 Qualifiers objectQuals = objectType.getQualifiers(); 11491 11492 Qualifiers difference = objectQuals - funcQuals; 11493 difference.removeObjCGCAttr(); 11494 difference.removeAddressSpace(); 11495 if (difference) { 11496 std::string qualsString = difference.getAsString(); 11497 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 11498 << fnType.getUnqualifiedType() 11499 << qualsString 11500 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 11501 } 11502 11503 if (resultType->isMemberPointerType()) 11504 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 11505 RequireCompleteType(LParenLoc, resultType, 0); 11506 11507 CXXMemberCallExpr *call 11508 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11509 resultType, valueKind, RParenLoc); 11510 11511 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 11512 call, nullptr)) 11513 return ExprError(); 11514 11515 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 11516 return ExprError(); 11517 11518 if (CheckOtherCall(call, proto)) 11519 return ExprError(); 11520 11521 return MaybeBindToTemporary(call); 11522 } 11523 11524 UnbridgedCastsSet UnbridgedCasts; 11525 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11526 return ExprError(); 11527 11528 MemberExpr *MemExpr; 11529 CXXMethodDecl *Method = nullptr; 11530 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 11531 NestedNameSpecifier *Qualifier = nullptr; 11532 if (isa<MemberExpr>(NakedMemExpr)) { 11533 MemExpr = cast<MemberExpr>(NakedMemExpr); 11534 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 11535 FoundDecl = MemExpr->getFoundDecl(); 11536 Qualifier = MemExpr->getQualifier(); 11537 UnbridgedCasts.restore(); 11538 } else { 11539 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 11540 Qualifier = UnresExpr->getQualifier(); 11541 11542 QualType ObjectType = UnresExpr->getBaseType(); 11543 Expr::Classification ObjectClassification 11544 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 11545 : UnresExpr->getBase()->Classify(Context); 11546 11547 // Add overload candidates 11548 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 11549 OverloadCandidateSet::CSK_Normal); 11550 11551 // FIXME: avoid copy. 11552 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 11553 if (UnresExpr->hasExplicitTemplateArgs()) { 11554 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11555 TemplateArgs = &TemplateArgsBuffer; 11556 } 11557 11558 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 11559 E = UnresExpr->decls_end(); I != E; ++I) { 11560 11561 NamedDecl *Func = *I; 11562 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 11563 if (isa<UsingShadowDecl>(Func)) 11564 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 11565 11566 11567 // Microsoft supports direct constructor calls. 11568 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 11569 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 11570 Args, CandidateSet); 11571 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 11572 // If explicit template arguments were provided, we can't call a 11573 // non-template member function. 11574 if (TemplateArgs) 11575 continue; 11576 11577 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 11578 ObjectClassification, Args, CandidateSet, 11579 /*SuppressUserConversions=*/false); 11580 } else { 11581 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 11582 I.getPair(), ActingDC, TemplateArgs, 11583 ObjectType, ObjectClassification, 11584 Args, CandidateSet, 11585 /*SuppressUsedConversions=*/false); 11586 } 11587 } 11588 11589 DeclarationName DeclName = UnresExpr->getMemberName(); 11590 11591 UnbridgedCasts.restore(); 11592 11593 OverloadCandidateSet::iterator Best; 11594 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 11595 Best)) { 11596 case OR_Success: 11597 Method = cast<CXXMethodDecl>(Best->Function); 11598 FoundDecl = Best->FoundDecl; 11599 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 11600 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 11601 return ExprError(); 11602 // If FoundDecl is different from Method (such as if one is a template 11603 // and the other a specialization), make sure DiagnoseUseOfDecl is 11604 // called on both. 11605 // FIXME: This would be more comprehensively addressed by modifying 11606 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 11607 // being used. 11608 if (Method != FoundDecl.getDecl() && 11609 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 11610 return ExprError(); 11611 break; 11612 11613 case OR_No_Viable_Function: 11614 Diag(UnresExpr->getMemberLoc(), 11615 diag::err_ovl_no_viable_member_function_in_call) 11616 << DeclName << MemExprE->getSourceRange(); 11617 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11618 // FIXME: Leaking incoming expressions! 11619 return ExprError(); 11620 11621 case OR_Ambiguous: 11622 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 11623 << DeclName << MemExprE->getSourceRange(); 11624 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11625 // FIXME: Leaking incoming expressions! 11626 return ExprError(); 11627 11628 case OR_Deleted: 11629 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 11630 << Best->Function->isDeleted() 11631 << DeclName 11632 << getDeletedOrUnavailableSuffix(Best->Function) 11633 << MemExprE->getSourceRange(); 11634 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11635 // FIXME: Leaking incoming expressions! 11636 return ExprError(); 11637 } 11638 11639 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 11640 11641 // If overload resolution picked a static member, build a 11642 // non-member call based on that function. 11643 if (Method->isStatic()) { 11644 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 11645 RParenLoc); 11646 } 11647 11648 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 11649 } 11650 11651 QualType ResultType = Method->getReturnType(); 11652 ExprValueKind VK = Expr::getValueKindForType(ResultType); 11653 ResultType = ResultType.getNonLValueExprType(Context); 11654 11655 assert(Method && "Member call to something that isn't a method?"); 11656 CXXMemberCallExpr *TheCall = 11657 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11658 ResultType, VK, RParenLoc); 11659 11660 // (CUDA B.1): Check for invalid calls between targets. 11661 if (getLangOpts().CUDA) { 11662 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) { 11663 if (CheckCUDATarget(Caller, Method)) { 11664 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target) 11665 << IdentifyCUDATarget(Method) << Method->getIdentifier() 11666 << IdentifyCUDATarget(Caller); 11667 return ExprError(); 11668 } 11669 } 11670 } 11671 11672 // Check for a valid return type. 11673 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 11674 TheCall, Method)) 11675 return ExprError(); 11676 11677 // Convert the object argument (for a non-static member function call). 11678 // We only need to do this if there was actually an overload; otherwise 11679 // it was done at lookup. 11680 if (!Method->isStatic()) { 11681 ExprResult ObjectArg = 11682 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 11683 FoundDecl, Method); 11684 if (ObjectArg.isInvalid()) 11685 return ExprError(); 11686 MemExpr->setBase(ObjectArg.get()); 11687 } 11688 11689 // Convert the rest of the arguments 11690 const FunctionProtoType *Proto = 11691 Method->getType()->getAs<FunctionProtoType>(); 11692 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 11693 RParenLoc)) 11694 return ExprError(); 11695 11696 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11697 11698 if (CheckFunctionCall(Method, TheCall, Proto)) 11699 return ExprError(); 11700 11701 if ((isa<CXXConstructorDecl>(CurContext) || 11702 isa<CXXDestructorDecl>(CurContext)) && 11703 TheCall->getMethodDecl()->isPure()) { 11704 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 11705 11706 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 11707 Diag(MemExpr->getLocStart(), 11708 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 11709 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 11710 << MD->getParent()->getDeclName(); 11711 11712 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 11713 } 11714 } 11715 return MaybeBindToTemporary(TheCall); 11716 } 11717 11718 /// BuildCallToObjectOfClassType - Build a call to an object of class 11719 /// type (C++ [over.call.object]), which can end up invoking an 11720 /// overloaded function call operator (@c operator()) or performing a 11721 /// user-defined conversion on the object argument. 11722 ExprResult 11723 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 11724 SourceLocation LParenLoc, 11725 MultiExprArg Args, 11726 SourceLocation RParenLoc) { 11727 if (checkPlaceholderForOverload(*this, Obj)) 11728 return ExprError(); 11729 ExprResult Object = Obj; 11730 11731 UnbridgedCastsSet UnbridgedCasts; 11732 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11733 return ExprError(); 11734 11735 assert(Object.get()->getType()->isRecordType() && 11736 "Requires object type argument"); 11737 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 11738 11739 // C++ [over.call.object]p1: 11740 // If the primary-expression E in the function call syntax 11741 // evaluates to a class object of type "cv T", then the set of 11742 // candidate functions includes at least the function call 11743 // operators of T. The function call operators of T are obtained by 11744 // ordinary lookup of the name operator() in the context of 11745 // (E).operator(). 11746 OverloadCandidateSet CandidateSet(LParenLoc, 11747 OverloadCandidateSet::CSK_Operator); 11748 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 11749 11750 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 11751 diag::err_incomplete_object_call, Object.get())) 11752 return true; 11753 11754 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 11755 LookupQualifiedName(R, Record->getDecl()); 11756 R.suppressDiagnostics(); 11757 11758 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11759 Oper != OperEnd; ++Oper) { 11760 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 11761 Object.get()->Classify(Context), 11762 Args, CandidateSet, 11763 /*SuppressUserConversions=*/ false); 11764 } 11765 11766 // C++ [over.call.object]p2: 11767 // In addition, for each (non-explicit in C++0x) conversion function 11768 // declared in T of the form 11769 // 11770 // operator conversion-type-id () cv-qualifier; 11771 // 11772 // where cv-qualifier is the same cv-qualification as, or a 11773 // greater cv-qualification than, cv, and where conversion-type-id 11774 // denotes the type "pointer to function of (P1,...,Pn) returning 11775 // R", or the type "reference to pointer to function of 11776 // (P1,...,Pn) returning R", or the type "reference to function 11777 // of (P1,...,Pn) returning R", a surrogate call function [...] 11778 // is also considered as a candidate function. Similarly, 11779 // surrogate call functions are added to the set of candidate 11780 // functions for each conversion function declared in an 11781 // accessible base class provided the function is not hidden 11782 // within T by another intervening declaration. 11783 std::pair<CXXRecordDecl::conversion_iterator, 11784 CXXRecordDecl::conversion_iterator> Conversions 11785 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 11786 for (CXXRecordDecl::conversion_iterator 11787 I = Conversions.first, E = Conversions.second; I != E; ++I) { 11788 NamedDecl *D = *I; 11789 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 11790 if (isa<UsingShadowDecl>(D)) 11791 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 11792 11793 // Skip over templated conversion functions; they aren't 11794 // surrogates. 11795 if (isa<FunctionTemplateDecl>(D)) 11796 continue; 11797 11798 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 11799 if (!Conv->isExplicit()) { 11800 // Strip the reference type (if any) and then the pointer type (if 11801 // any) to get down to what might be a function type. 11802 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 11803 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11804 ConvType = ConvPtrType->getPointeeType(); 11805 11806 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 11807 { 11808 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 11809 Object.get(), Args, CandidateSet); 11810 } 11811 } 11812 } 11813 11814 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11815 11816 // Perform overload resolution. 11817 OverloadCandidateSet::iterator Best; 11818 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 11819 Best)) { 11820 case OR_Success: 11821 // Overload resolution succeeded; we'll build the appropriate call 11822 // below. 11823 break; 11824 11825 case OR_No_Viable_Function: 11826 if (CandidateSet.empty()) 11827 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 11828 << Object.get()->getType() << /*call*/ 1 11829 << Object.get()->getSourceRange(); 11830 else 11831 Diag(Object.get()->getLocStart(), 11832 diag::err_ovl_no_viable_object_call) 11833 << Object.get()->getType() << Object.get()->getSourceRange(); 11834 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11835 break; 11836 11837 case OR_Ambiguous: 11838 Diag(Object.get()->getLocStart(), 11839 diag::err_ovl_ambiguous_object_call) 11840 << Object.get()->getType() << Object.get()->getSourceRange(); 11841 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11842 break; 11843 11844 case OR_Deleted: 11845 Diag(Object.get()->getLocStart(), 11846 diag::err_ovl_deleted_object_call) 11847 << Best->Function->isDeleted() 11848 << Object.get()->getType() 11849 << getDeletedOrUnavailableSuffix(Best->Function) 11850 << Object.get()->getSourceRange(); 11851 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11852 break; 11853 } 11854 11855 if (Best == CandidateSet.end()) 11856 return true; 11857 11858 UnbridgedCasts.restore(); 11859 11860 if (Best->Function == nullptr) { 11861 // Since there is no function declaration, this is one of the 11862 // surrogate candidates. Dig out the conversion function. 11863 CXXConversionDecl *Conv 11864 = cast<CXXConversionDecl>( 11865 Best->Conversions[0].UserDefined.ConversionFunction); 11866 11867 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 11868 Best->FoundDecl); 11869 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 11870 return ExprError(); 11871 assert(Conv == Best->FoundDecl.getDecl() && 11872 "Found Decl & conversion-to-functionptr should be same, right?!"); 11873 // We selected one of the surrogate functions that converts the 11874 // object parameter to a function pointer. Perform the conversion 11875 // on the object argument, then let ActOnCallExpr finish the job. 11876 11877 // Create an implicit member expr to refer to the conversion operator. 11878 // and then call it. 11879 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 11880 Conv, HadMultipleCandidates); 11881 if (Call.isInvalid()) 11882 return ExprError(); 11883 // Record usage of conversion in an implicit cast. 11884 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 11885 CK_UserDefinedConversion, Call.get(), 11886 nullptr, VK_RValue); 11887 11888 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 11889 } 11890 11891 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 11892 11893 // We found an overloaded operator(). Build a CXXOperatorCallExpr 11894 // that calls this method, using Object for the implicit object 11895 // parameter and passing along the remaining arguments. 11896 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11897 11898 // An error diagnostic has already been printed when parsing the declaration. 11899 if (Method->isInvalidDecl()) 11900 return ExprError(); 11901 11902 const FunctionProtoType *Proto = 11903 Method->getType()->getAs<FunctionProtoType>(); 11904 11905 unsigned NumParams = Proto->getNumParams(); 11906 11907 DeclarationNameInfo OpLocInfo( 11908 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 11909 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 11910 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11911 HadMultipleCandidates, 11912 OpLocInfo.getLoc(), 11913 OpLocInfo.getInfo()); 11914 if (NewFn.isInvalid()) 11915 return true; 11916 11917 // Build the full argument list for the method call (the implicit object 11918 // parameter is placed at the beginning of the list). 11919 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]); 11920 MethodArgs[0] = Object.get(); 11921 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 11922 11923 // Once we've built TheCall, all of the expressions are properly 11924 // owned. 11925 QualType ResultTy = Method->getReturnType(); 11926 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11927 ResultTy = ResultTy.getNonLValueExprType(Context); 11928 11929 CXXOperatorCallExpr *TheCall = new (Context) 11930 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), 11931 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 11932 ResultTy, VK, RParenLoc, false); 11933 MethodArgs.reset(); 11934 11935 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 11936 return true; 11937 11938 // We may have default arguments. If so, we need to allocate more 11939 // slots in the call for them. 11940 if (Args.size() < NumParams) 11941 TheCall->setNumArgs(Context, NumParams + 1); 11942 11943 bool IsError = false; 11944 11945 // Initialize the implicit object parameter. 11946 ExprResult ObjRes = 11947 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 11948 Best->FoundDecl, Method); 11949 if (ObjRes.isInvalid()) 11950 IsError = true; 11951 else 11952 Object = ObjRes; 11953 TheCall->setArg(0, Object.get()); 11954 11955 // Check the argument types. 11956 for (unsigned i = 0; i != NumParams; i++) { 11957 Expr *Arg; 11958 if (i < Args.size()) { 11959 Arg = Args[i]; 11960 11961 // Pass the argument. 11962 11963 ExprResult InputInit 11964 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11965 Context, 11966 Method->getParamDecl(i)), 11967 SourceLocation(), Arg); 11968 11969 IsError |= InputInit.isInvalid(); 11970 Arg = InputInit.getAs<Expr>(); 11971 } else { 11972 ExprResult DefArg 11973 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 11974 if (DefArg.isInvalid()) { 11975 IsError = true; 11976 break; 11977 } 11978 11979 Arg = DefArg.getAs<Expr>(); 11980 } 11981 11982 TheCall->setArg(i + 1, Arg); 11983 } 11984 11985 // If this is a variadic call, handle args passed through "...". 11986 if (Proto->isVariadic()) { 11987 // Promote the arguments (C99 6.5.2.2p7). 11988 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 11989 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 11990 nullptr); 11991 IsError |= Arg.isInvalid(); 11992 TheCall->setArg(i + 1, Arg.get()); 11993 } 11994 } 11995 11996 if (IsError) return true; 11997 11998 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11999 12000 if (CheckFunctionCall(Method, TheCall, Proto)) 12001 return true; 12002 12003 return MaybeBindToTemporary(TheCall); 12004 } 12005 12006 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 12007 /// (if one exists), where @c Base is an expression of class type and 12008 /// @c Member is the name of the member we're trying to find. 12009 ExprResult 12010 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 12011 bool *NoArrowOperatorFound) { 12012 assert(Base->getType()->isRecordType() && 12013 "left-hand side must have class type"); 12014 12015 if (checkPlaceholderForOverload(*this, Base)) 12016 return ExprError(); 12017 12018 SourceLocation Loc = Base->getExprLoc(); 12019 12020 // C++ [over.ref]p1: 12021 // 12022 // [...] An expression x->m is interpreted as (x.operator->())->m 12023 // for a class object x of type T if T::operator->() exists and if 12024 // the operator is selected as the best match function by the 12025 // overload resolution mechanism (13.3). 12026 DeclarationName OpName = 12027 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 12028 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 12029 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 12030 12031 if (RequireCompleteType(Loc, Base->getType(), 12032 diag::err_typecheck_incomplete_tag, Base)) 12033 return ExprError(); 12034 12035 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 12036 LookupQualifiedName(R, BaseRecord->getDecl()); 12037 R.suppressDiagnostics(); 12038 12039 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12040 Oper != OperEnd; ++Oper) { 12041 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 12042 None, CandidateSet, /*SuppressUserConversions=*/false); 12043 } 12044 12045 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12046 12047 // Perform overload resolution. 12048 OverloadCandidateSet::iterator Best; 12049 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12050 case OR_Success: 12051 // Overload resolution succeeded; we'll build the call below. 12052 break; 12053 12054 case OR_No_Viable_Function: 12055 if (CandidateSet.empty()) { 12056 QualType BaseType = Base->getType(); 12057 if (NoArrowOperatorFound) { 12058 // Report this specific error to the caller instead of emitting a 12059 // diagnostic, as requested. 12060 *NoArrowOperatorFound = true; 12061 return ExprError(); 12062 } 12063 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 12064 << BaseType << Base->getSourceRange(); 12065 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 12066 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 12067 << FixItHint::CreateReplacement(OpLoc, "."); 12068 } 12069 } else 12070 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12071 << "operator->" << Base->getSourceRange(); 12072 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12073 return ExprError(); 12074 12075 case OR_Ambiguous: 12076 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12077 << "->" << Base->getType() << Base->getSourceRange(); 12078 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 12079 return ExprError(); 12080 12081 case OR_Deleted: 12082 Diag(OpLoc, diag::err_ovl_deleted_oper) 12083 << Best->Function->isDeleted() 12084 << "->" 12085 << getDeletedOrUnavailableSuffix(Best->Function) 12086 << Base->getSourceRange(); 12087 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12088 return ExprError(); 12089 } 12090 12091 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 12092 12093 // Convert the object parameter. 12094 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12095 ExprResult BaseResult = 12096 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 12097 Best->FoundDecl, Method); 12098 if (BaseResult.isInvalid()) 12099 return ExprError(); 12100 Base = BaseResult.get(); 12101 12102 // Build the operator call. 12103 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12104 HadMultipleCandidates, OpLoc); 12105 if (FnExpr.isInvalid()) 12106 return ExprError(); 12107 12108 QualType ResultTy = Method->getReturnType(); 12109 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12110 ResultTy = ResultTy.getNonLValueExprType(Context); 12111 CXXOperatorCallExpr *TheCall = 12112 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 12113 Base, ResultTy, VK, OpLoc, false); 12114 12115 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 12116 return ExprError(); 12117 12118 return MaybeBindToTemporary(TheCall); 12119 } 12120 12121 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 12122 /// a literal operator described by the provided lookup results. 12123 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 12124 DeclarationNameInfo &SuffixInfo, 12125 ArrayRef<Expr*> Args, 12126 SourceLocation LitEndLoc, 12127 TemplateArgumentListInfo *TemplateArgs) { 12128 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 12129 12130 OverloadCandidateSet CandidateSet(UDSuffixLoc, 12131 OverloadCandidateSet::CSK_Normal); 12132 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true, 12133 TemplateArgs); 12134 12135 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12136 12137 // Perform overload resolution. This will usually be trivial, but might need 12138 // to perform substitutions for a literal operator template. 12139 OverloadCandidateSet::iterator Best; 12140 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 12141 case OR_Success: 12142 case OR_Deleted: 12143 break; 12144 12145 case OR_No_Viable_Function: 12146 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 12147 << R.getLookupName(); 12148 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12149 return ExprError(); 12150 12151 case OR_Ambiguous: 12152 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 12153 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12154 return ExprError(); 12155 } 12156 12157 FunctionDecl *FD = Best->Function; 12158 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 12159 HadMultipleCandidates, 12160 SuffixInfo.getLoc(), 12161 SuffixInfo.getInfo()); 12162 if (Fn.isInvalid()) 12163 return true; 12164 12165 // Check the argument types. This should almost always be a no-op, except 12166 // that array-to-pointer decay is applied to string literals. 12167 Expr *ConvArgs[2]; 12168 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 12169 ExprResult InputInit = PerformCopyInitialization( 12170 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 12171 SourceLocation(), Args[ArgIdx]); 12172 if (InputInit.isInvalid()) 12173 return true; 12174 ConvArgs[ArgIdx] = InputInit.get(); 12175 } 12176 12177 QualType ResultTy = FD->getReturnType(); 12178 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12179 ResultTy = ResultTy.getNonLValueExprType(Context); 12180 12181 UserDefinedLiteral *UDL = 12182 new (Context) UserDefinedLiteral(Context, Fn.get(), 12183 llvm::makeArrayRef(ConvArgs, Args.size()), 12184 ResultTy, VK, LitEndLoc, UDSuffixLoc); 12185 12186 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 12187 return ExprError(); 12188 12189 if (CheckFunctionCall(FD, UDL, nullptr)) 12190 return ExprError(); 12191 12192 return MaybeBindToTemporary(UDL); 12193 } 12194 12195 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 12196 /// given LookupResult is non-empty, it is assumed to describe a member which 12197 /// will be invoked. Otherwise, the function will be found via argument 12198 /// dependent lookup. 12199 /// CallExpr is set to a valid expression and FRS_Success returned on success, 12200 /// otherwise CallExpr is set to ExprError() and some non-success value 12201 /// is returned. 12202 Sema::ForRangeStatus 12203 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 12204 SourceLocation RangeLoc, VarDecl *Decl, 12205 BeginEndFunction BEF, 12206 const DeclarationNameInfo &NameInfo, 12207 LookupResult &MemberLookup, 12208 OverloadCandidateSet *CandidateSet, 12209 Expr *Range, ExprResult *CallExpr) { 12210 CandidateSet->clear(); 12211 if (!MemberLookup.empty()) { 12212 ExprResult MemberRef = 12213 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 12214 /*IsPtr=*/false, CXXScopeSpec(), 12215 /*TemplateKWLoc=*/SourceLocation(), 12216 /*FirstQualifierInScope=*/nullptr, 12217 MemberLookup, 12218 /*TemplateArgs=*/nullptr); 12219 if (MemberRef.isInvalid()) { 12220 *CallExpr = ExprError(); 12221 Diag(Range->getLocStart(), diag::note_in_for_range) 12222 << RangeLoc << BEF << Range->getType(); 12223 return FRS_DiagnosticIssued; 12224 } 12225 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 12226 if (CallExpr->isInvalid()) { 12227 *CallExpr = ExprError(); 12228 Diag(Range->getLocStart(), diag::note_in_for_range) 12229 << RangeLoc << BEF << Range->getType(); 12230 return FRS_DiagnosticIssued; 12231 } 12232 } else { 12233 UnresolvedSet<0> FoundNames; 12234 UnresolvedLookupExpr *Fn = 12235 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 12236 NestedNameSpecifierLoc(), NameInfo, 12237 /*NeedsADL=*/true, /*Overloaded=*/false, 12238 FoundNames.begin(), FoundNames.end()); 12239 12240 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 12241 CandidateSet, CallExpr); 12242 if (CandidateSet->empty() || CandidateSetError) { 12243 *CallExpr = ExprError(); 12244 return FRS_NoViableFunction; 12245 } 12246 OverloadCandidateSet::iterator Best; 12247 OverloadingResult OverloadResult = 12248 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 12249 12250 if (OverloadResult == OR_No_Viable_Function) { 12251 *CallExpr = ExprError(); 12252 return FRS_NoViableFunction; 12253 } 12254 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 12255 Loc, nullptr, CandidateSet, &Best, 12256 OverloadResult, 12257 /*AllowTypoCorrection=*/false); 12258 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 12259 *CallExpr = ExprError(); 12260 Diag(Range->getLocStart(), diag::note_in_for_range) 12261 << RangeLoc << BEF << Range->getType(); 12262 return FRS_DiagnosticIssued; 12263 } 12264 } 12265 return FRS_Success; 12266 } 12267 12268 12269 /// FixOverloadedFunctionReference - E is an expression that refers to 12270 /// a C++ overloaded function (possibly with some parentheses and 12271 /// perhaps a '&' around it). We have resolved the overloaded function 12272 /// to the function declaration Fn, so patch up the expression E to 12273 /// refer (possibly indirectly) to Fn. Returns the new expr. 12274 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 12275 FunctionDecl *Fn) { 12276 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 12277 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 12278 Found, Fn); 12279 if (SubExpr == PE->getSubExpr()) 12280 return PE; 12281 12282 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 12283 } 12284 12285 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 12286 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 12287 Found, Fn); 12288 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 12289 SubExpr->getType()) && 12290 "Implicit cast type cannot be determined from overload"); 12291 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 12292 if (SubExpr == ICE->getSubExpr()) 12293 return ICE; 12294 12295 return ImplicitCastExpr::Create(Context, ICE->getType(), 12296 ICE->getCastKind(), 12297 SubExpr, nullptr, 12298 ICE->getValueKind()); 12299 } 12300 12301 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 12302 assert(UnOp->getOpcode() == UO_AddrOf && 12303 "Can only take the address of an overloaded function"); 12304 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12305 if (Method->isStatic()) { 12306 // Do nothing: static member functions aren't any different 12307 // from non-member functions. 12308 } else { 12309 // Fix the subexpression, which really has to be an 12310 // UnresolvedLookupExpr holding an overloaded member function 12311 // or template. 12312 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12313 Found, Fn); 12314 if (SubExpr == UnOp->getSubExpr()) 12315 return UnOp; 12316 12317 assert(isa<DeclRefExpr>(SubExpr) 12318 && "fixed to something other than a decl ref"); 12319 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 12320 && "fixed to a member ref with no nested name qualifier"); 12321 12322 // We have taken the address of a pointer to member 12323 // function. Perform the computation here so that we get the 12324 // appropriate pointer to member type. 12325 QualType ClassType 12326 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 12327 QualType MemPtrType 12328 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 12329 12330 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 12331 VK_RValue, OK_Ordinary, 12332 UnOp->getOperatorLoc()); 12333 } 12334 } 12335 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12336 Found, Fn); 12337 if (SubExpr == UnOp->getSubExpr()) 12338 return UnOp; 12339 12340 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 12341 Context.getPointerType(SubExpr->getType()), 12342 VK_RValue, OK_Ordinary, 12343 UnOp->getOperatorLoc()); 12344 } 12345 12346 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12347 // FIXME: avoid copy. 12348 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12349 if (ULE->hasExplicitTemplateArgs()) { 12350 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 12351 TemplateArgs = &TemplateArgsBuffer; 12352 } 12353 12354 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12355 ULE->getQualifierLoc(), 12356 ULE->getTemplateKeywordLoc(), 12357 Fn, 12358 /*enclosing*/ false, // FIXME? 12359 ULE->getNameLoc(), 12360 Fn->getType(), 12361 VK_LValue, 12362 Found.getDecl(), 12363 TemplateArgs); 12364 MarkDeclRefReferenced(DRE); 12365 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 12366 return DRE; 12367 } 12368 12369 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 12370 // FIXME: avoid copy. 12371 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12372 if (MemExpr->hasExplicitTemplateArgs()) { 12373 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12374 TemplateArgs = &TemplateArgsBuffer; 12375 } 12376 12377 Expr *Base; 12378 12379 // If we're filling in a static method where we used to have an 12380 // implicit member access, rewrite to a simple decl ref. 12381 if (MemExpr->isImplicitAccess()) { 12382 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12383 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12384 MemExpr->getQualifierLoc(), 12385 MemExpr->getTemplateKeywordLoc(), 12386 Fn, 12387 /*enclosing*/ false, 12388 MemExpr->getMemberLoc(), 12389 Fn->getType(), 12390 VK_LValue, 12391 Found.getDecl(), 12392 TemplateArgs); 12393 MarkDeclRefReferenced(DRE); 12394 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 12395 return DRE; 12396 } else { 12397 SourceLocation Loc = MemExpr->getMemberLoc(); 12398 if (MemExpr->getQualifier()) 12399 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 12400 CheckCXXThisCapture(Loc); 12401 Base = new (Context) CXXThisExpr(Loc, 12402 MemExpr->getBaseType(), 12403 /*isImplicit=*/true); 12404 } 12405 } else 12406 Base = MemExpr->getBase(); 12407 12408 ExprValueKind valueKind; 12409 QualType type; 12410 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12411 valueKind = VK_LValue; 12412 type = Fn->getType(); 12413 } else { 12414 valueKind = VK_RValue; 12415 type = Context.BoundMemberTy; 12416 } 12417 12418 MemberExpr *ME = MemberExpr::Create(Context, Base, 12419 MemExpr->isArrow(), 12420 MemExpr->getQualifierLoc(), 12421 MemExpr->getTemplateKeywordLoc(), 12422 Fn, 12423 Found, 12424 MemExpr->getMemberNameInfo(), 12425 TemplateArgs, 12426 type, valueKind, OK_Ordinary); 12427 ME->setHadMultipleCandidates(true); 12428 MarkMemberReferenced(ME); 12429 return ME; 12430 } 12431 12432 llvm_unreachable("Invalid reference to overloaded function"); 12433 } 12434 12435 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 12436 DeclAccessPair Found, 12437 FunctionDecl *Fn) { 12438 return FixOverloadedFunctionReference(E.get(), Found, Fn); 12439 } 12440