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/PartialDiagnostic.h" 24 #include "clang/Basic/TargetInfo.h" 25 #include "clang/Lex/Preprocessor.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 37 namespace clang { 38 using namespace sema; 39 40 /// A convenience routine for creating a decayed reference to a function. 41 static ExprResult 42 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 43 bool HadMultipleCandidates, 44 SourceLocation Loc = SourceLocation(), 45 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 46 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 47 return ExprError(); 48 // If FoundDecl is different from Fn (such as if one is a template 49 // and the other a specialization), make sure DiagnoseUseOfDecl is 50 // called on both. 51 // FIXME: This would be more comprehensively addressed by modifying 52 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 53 // being used. 54 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 55 return ExprError(); 56 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 57 VK_LValue, Loc, LocInfo); 58 if (HadMultipleCandidates) 59 DRE->setHadMultipleCandidates(true); 60 61 S.MarkDeclRefReferenced(DRE); 62 63 ExprResult E = S.Owned(DRE); 64 E = S.DefaultFunctionArrayConversion(E.take()); 65 if (E.isInvalid()) 66 return ExprError(); 67 return E; 68 } 69 70 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 71 bool InOverloadResolution, 72 StandardConversionSequence &SCS, 73 bool CStyle, 74 bool AllowObjCWritebackConversion); 75 76 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 77 QualType &ToType, 78 bool InOverloadResolution, 79 StandardConversionSequence &SCS, 80 bool CStyle); 81 static OverloadingResult 82 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 83 UserDefinedConversionSequence& User, 84 OverloadCandidateSet& Conversions, 85 bool AllowExplicit, 86 bool AllowObjCConversionOnExplicit); 87 88 89 static ImplicitConversionSequence::CompareKind 90 CompareStandardConversionSequences(Sema &S, 91 const StandardConversionSequence& SCS1, 92 const StandardConversionSequence& SCS2); 93 94 static ImplicitConversionSequence::CompareKind 95 CompareQualificationConversions(Sema &S, 96 const StandardConversionSequence& SCS1, 97 const StandardConversionSequence& SCS2); 98 99 static ImplicitConversionSequence::CompareKind 100 CompareDerivedToBaseConversions(Sema &S, 101 const StandardConversionSequence& SCS1, 102 const StandardConversionSequence& SCS2); 103 104 105 106 /// GetConversionCategory - Retrieve the implicit conversion 107 /// category corresponding to the given implicit conversion kind. 108 ImplicitConversionCategory 109 GetConversionCategory(ImplicitConversionKind Kind) { 110 static const ImplicitConversionCategory 111 Category[(int)ICK_Num_Conversion_Kinds] = { 112 ICC_Identity, 113 ICC_Lvalue_Transformation, 114 ICC_Lvalue_Transformation, 115 ICC_Lvalue_Transformation, 116 ICC_Identity, 117 ICC_Qualification_Adjustment, 118 ICC_Promotion, 119 ICC_Promotion, 120 ICC_Promotion, 121 ICC_Conversion, 122 ICC_Conversion, 123 ICC_Conversion, 124 ICC_Conversion, 125 ICC_Conversion, 126 ICC_Conversion, 127 ICC_Conversion, 128 ICC_Conversion, 129 ICC_Conversion, 130 ICC_Conversion, 131 ICC_Conversion, 132 ICC_Conversion, 133 ICC_Conversion 134 }; 135 return Category[(int)Kind]; 136 } 137 138 /// GetConversionRank - Retrieve the implicit conversion rank 139 /// corresponding to the given implicit conversion kind. 140 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 141 static const ImplicitConversionRank 142 Rank[(int)ICK_Num_Conversion_Kinds] = { 143 ICR_Exact_Match, 144 ICR_Exact_Match, 145 ICR_Exact_Match, 146 ICR_Exact_Match, 147 ICR_Exact_Match, 148 ICR_Exact_Match, 149 ICR_Promotion, 150 ICR_Promotion, 151 ICR_Promotion, 152 ICR_Conversion, 153 ICR_Conversion, 154 ICR_Conversion, 155 ICR_Conversion, 156 ICR_Conversion, 157 ICR_Conversion, 158 ICR_Conversion, 159 ICR_Conversion, 160 ICR_Conversion, 161 ICR_Conversion, 162 ICR_Conversion, 163 ICR_Complex_Real_Conversion, 164 ICR_Conversion, 165 ICR_Conversion, 166 ICR_Writeback_Conversion 167 }; 168 return Rank[(int)Kind]; 169 } 170 171 /// GetImplicitConversionName - Return the name of this kind of 172 /// implicit conversion. 173 const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 174 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 175 "No conversion", 176 "Lvalue-to-rvalue", 177 "Array-to-pointer", 178 "Function-to-pointer", 179 "Noreturn adjustment", 180 "Qualification", 181 "Integral promotion", 182 "Floating point promotion", 183 "Complex promotion", 184 "Integral conversion", 185 "Floating conversion", 186 "Complex conversion", 187 "Floating-integral conversion", 188 "Pointer conversion", 189 "Pointer-to-member conversion", 190 "Boolean conversion", 191 "Compatible-types conversion", 192 "Derived-to-base conversion", 193 "Vector conversion", 194 "Vector splat", 195 "Complex-real conversion", 196 "Block Pointer conversion", 197 "Transparent Union Conversion" 198 "Writeback conversion" 199 }; 200 return Name[Kind]; 201 } 202 203 /// StandardConversionSequence - Set the standard conversion 204 /// sequence to the identity conversion. 205 void StandardConversionSequence::setAsIdentityConversion() { 206 First = ICK_Identity; 207 Second = ICK_Identity; 208 Third = ICK_Identity; 209 DeprecatedStringLiteralToCharPtr = false; 210 QualificationIncludesObjCLifetime = false; 211 ReferenceBinding = false; 212 DirectBinding = false; 213 IsLvalueReference = true; 214 BindsToFunctionLvalue = false; 215 BindsToRvalue = false; 216 BindsImplicitObjectArgumentWithoutRefQualifier = false; 217 ObjCLifetimeConversionBinding = false; 218 CopyConstructor = 0; 219 } 220 221 /// getRank - Retrieve the rank of this standard conversion sequence 222 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 223 /// implicit conversions. 224 ImplicitConversionRank StandardConversionSequence::getRank() const { 225 ImplicitConversionRank Rank = ICR_Exact_Match; 226 if (GetConversionRank(First) > Rank) 227 Rank = GetConversionRank(First); 228 if (GetConversionRank(Second) > Rank) 229 Rank = GetConversionRank(Second); 230 if (GetConversionRank(Third) > Rank) 231 Rank = GetConversionRank(Third); 232 return Rank; 233 } 234 235 /// isPointerConversionToBool - Determines whether this conversion is 236 /// a conversion of a pointer or pointer-to-member to bool. This is 237 /// used as part of the ranking of standard conversion sequences 238 /// (C++ 13.3.3.2p4). 239 bool StandardConversionSequence::isPointerConversionToBool() const { 240 // Note that FromType has not necessarily been transformed by the 241 // array-to-pointer or function-to-pointer implicit conversions, so 242 // check for their presence as well as checking whether FromType is 243 // a pointer. 244 if (getToType(1)->isBooleanType() && 245 (getFromType()->isPointerType() || 246 getFromType()->isObjCObjectPointerType() || 247 getFromType()->isBlockPointerType() || 248 getFromType()->isNullPtrType() || 249 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 250 return true; 251 252 return false; 253 } 254 255 /// isPointerConversionToVoidPointer - Determines whether this 256 /// conversion is a conversion of a pointer to a void pointer. This is 257 /// used as part of the ranking of standard conversion sequences (C++ 258 /// 13.3.3.2p4). 259 bool 260 StandardConversionSequence:: 261 isPointerConversionToVoidPointer(ASTContext& Context) const { 262 QualType FromType = getFromType(); 263 QualType ToType = getToType(1); 264 265 // Note that FromType has not necessarily been transformed by the 266 // array-to-pointer implicit conversion, so check for its presence 267 // and redo the conversion to get a pointer. 268 if (First == ICK_Array_To_Pointer) 269 FromType = Context.getArrayDecayedType(FromType); 270 271 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 272 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 273 return ToPtrType->getPointeeType()->isVoidType(); 274 275 return false; 276 } 277 278 /// Skip any implicit casts which could be either part of a narrowing conversion 279 /// or after one in an implicit conversion. 280 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 281 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 282 switch (ICE->getCastKind()) { 283 case CK_NoOp: 284 case CK_IntegralCast: 285 case CK_IntegralToBoolean: 286 case CK_IntegralToFloating: 287 case CK_FloatingToIntegral: 288 case CK_FloatingToBoolean: 289 case CK_FloatingCast: 290 Converted = ICE->getSubExpr(); 291 continue; 292 293 default: 294 return Converted; 295 } 296 } 297 298 return Converted; 299 } 300 301 /// Check if this standard conversion sequence represents a narrowing 302 /// conversion, according to C++11 [dcl.init.list]p7. 303 /// 304 /// \param Ctx The AST context. 305 /// \param Converted The result of applying this standard conversion sequence. 306 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 307 /// value of the expression prior to the narrowing conversion. 308 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 309 /// type of the expression prior to the narrowing conversion. 310 NarrowingKind 311 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 312 const Expr *Converted, 313 APValue &ConstantValue, 314 QualType &ConstantType) const { 315 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 316 317 // C++11 [dcl.init.list]p7: 318 // A narrowing conversion is an implicit conversion ... 319 QualType FromType = getToType(0); 320 QualType ToType = getToType(1); 321 switch (Second) { 322 // -- from a floating-point type to an integer type, or 323 // 324 // -- from an integer type or unscoped enumeration type to a floating-point 325 // type, except where the source is a constant expression and the actual 326 // value after conversion will fit into the target type and will produce 327 // the original value when converted back to the original type, or 328 case ICK_Floating_Integral: 329 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 330 return NK_Type_Narrowing; 331 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 332 llvm::APSInt IntConstantValue; 333 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 334 if (Initializer && 335 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 336 // Convert the integer to the floating type. 337 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 338 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 339 llvm::APFloat::rmNearestTiesToEven); 340 // And back. 341 llvm::APSInt ConvertedValue = IntConstantValue; 342 bool ignored; 343 Result.convertToInteger(ConvertedValue, 344 llvm::APFloat::rmTowardZero, &ignored); 345 // If the resulting value is different, this was a narrowing conversion. 346 if (IntConstantValue != ConvertedValue) { 347 ConstantValue = APValue(IntConstantValue); 348 ConstantType = Initializer->getType(); 349 return NK_Constant_Narrowing; 350 } 351 } else { 352 // Variables are always narrowings. 353 return NK_Variable_Narrowing; 354 } 355 } 356 return NK_Not_Narrowing; 357 358 // -- from long double to double or float, or from double to float, except 359 // where the source is a constant expression and the actual value after 360 // conversion is within the range of values that can be represented (even 361 // if it cannot be represented exactly), or 362 case ICK_Floating_Conversion: 363 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 364 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 365 // FromType is larger than ToType. 366 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 367 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 368 // Constant! 369 assert(ConstantValue.isFloat()); 370 llvm::APFloat FloatVal = ConstantValue.getFloat(); 371 // Convert the source value into the target type. 372 bool ignored; 373 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 374 Ctx.getFloatTypeSemantics(ToType), 375 llvm::APFloat::rmNearestTiesToEven, &ignored); 376 // If there was no overflow, the source value is within the range of 377 // values that can be represented. 378 if (ConvertStatus & llvm::APFloat::opOverflow) { 379 ConstantType = Initializer->getType(); 380 return NK_Constant_Narrowing; 381 } 382 } else { 383 return NK_Variable_Narrowing; 384 } 385 } 386 return NK_Not_Narrowing; 387 388 // -- from an integer type or unscoped enumeration type to an integer type 389 // that cannot represent all the values of the original type, except where 390 // the source is a constant expression and the actual value after 391 // conversion will fit into the target type and will produce the original 392 // value when converted back to the original type. 393 case ICK_Boolean_Conversion: // Bools are integers too. 394 if (!FromType->isIntegralOrUnscopedEnumerationType()) { 395 // Boolean conversions can be from pointers and pointers to members 396 // [conv.bool], and those aren't considered narrowing conversions. 397 return NK_Not_Narrowing; 398 } // Otherwise, fall through to the integral case. 399 case ICK_Integral_Conversion: { 400 assert(FromType->isIntegralOrUnscopedEnumerationType()); 401 assert(ToType->isIntegralOrUnscopedEnumerationType()); 402 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 403 const unsigned FromWidth = Ctx.getIntWidth(FromType); 404 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 405 const unsigned ToWidth = Ctx.getIntWidth(ToType); 406 407 if (FromWidth > ToWidth || 408 (FromWidth == ToWidth && FromSigned != ToSigned) || 409 (FromSigned && !ToSigned)) { 410 // Not all values of FromType can be represented in ToType. 411 llvm::APSInt InitializerValue; 412 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 413 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 414 // Such conversions on variables are always narrowing. 415 return NK_Variable_Narrowing; 416 } 417 bool Narrowing = false; 418 if (FromWidth < ToWidth) { 419 // Negative -> unsigned is narrowing. Otherwise, more bits is never 420 // narrowing. 421 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 422 Narrowing = true; 423 } else { 424 // Add a bit to the InitializerValue so we don't have to worry about 425 // signed vs. unsigned comparisons. 426 InitializerValue = InitializerValue.extend( 427 InitializerValue.getBitWidth() + 1); 428 // Convert the initializer to and from the target width and signed-ness. 429 llvm::APSInt ConvertedValue = InitializerValue; 430 ConvertedValue = ConvertedValue.trunc(ToWidth); 431 ConvertedValue.setIsSigned(ToSigned); 432 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 433 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 434 // If the result is different, this was a narrowing conversion. 435 if (ConvertedValue != InitializerValue) 436 Narrowing = true; 437 } 438 if (Narrowing) { 439 ConstantType = Initializer->getType(); 440 ConstantValue = APValue(InitializerValue); 441 return NK_Constant_Narrowing; 442 } 443 } 444 return NK_Not_Narrowing; 445 } 446 447 default: 448 // Other kinds of conversions are not narrowings. 449 return NK_Not_Narrowing; 450 } 451 } 452 453 /// dump - Print this standard conversion sequence to standard 454 /// error. Useful for debugging overloading issues. 455 void StandardConversionSequence::dump() const { 456 raw_ostream &OS = llvm::errs(); 457 bool PrintedSomething = false; 458 if (First != ICK_Identity) { 459 OS << GetImplicitConversionName(First); 460 PrintedSomething = true; 461 } 462 463 if (Second != ICK_Identity) { 464 if (PrintedSomething) { 465 OS << " -> "; 466 } 467 OS << GetImplicitConversionName(Second); 468 469 if (CopyConstructor) { 470 OS << " (by copy constructor)"; 471 } else if (DirectBinding) { 472 OS << " (direct reference binding)"; 473 } else if (ReferenceBinding) { 474 OS << " (reference binding)"; 475 } 476 PrintedSomething = true; 477 } 478 479 if (Third != ICK_Identity) { 480 if (PrintedSomething) { 481 OS << " -> "; 482 } 483 OS << GetImplicitConversionName(Third); 484 PrintedSomething = true; 485 } 486 487 if (!PrintedSomething) { 488 OS << "No conversions required"; 489 } 490 } 491 492 /// dump - Print this user-defined conversion sequence to standard 493 /// error. Useful for debugging overloading issues. 494 void UserDefinedConversionSequence::dump() const { 495 raw_ostream &OS = llvm::errs(); 496 if (Before.First || Before.Second || Before.Third) { 497 Before.dump(); 498 OS << " -> "; 499 } 500 if (ConversionFunction) 501 OS << '\'' << *ConversionFunction << '\''; 502 else 503 OS << "aggregate initialization"; 504 if (After.First || After.Second || After.Third) { 505 OS << " -> "; 506 After.dump(); 507 } 508 } 509 510 /// dump - Print this implicit conversion sequence to standard 511 /// error. Useful for debugging overloading issues. 512 void ImplicitConversionSequence::dump() const { 513 raw_ostream &OS = llvm::errs(); 514 if (isStdInitializerListElement()) 515 OS << "Worst std::initializer_list element conversion: "; 516 switch (ConversionKind) { 517 case StandardConversion: 518 OS << "Standard conversion: "; 519 Standard.dump(); 520 break; 521 case UserDefinedConversion: 522 OS << "User-defined conversion: "; 523 UserDefined.dump(); 524 break; 525 case EllipsisConversion: 526 OS << "Ellipsis conversion"; 527 break; 528 case AmbiguousConversion: 529 OS << "Ambiguous conversion"; 530 break; 531 case BadConversion: 532 OS << "Bad conversion"; 533 break; 534 } 535 536 OS << "\n"; 537 } 538 539 void AmbiguousConversionSequence::construct() { 540 new (&conversions()) ConversionSet(); 541 } 542 543 void AmbiguousConversionSequence::destruct() { 544 conversions().~ConversionSet(); 545 } 546 547 void 548 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 549 FromTypePtr = O.FromTypePtr; 550 ToTypePtr = O.ToTypePtr; 551 new (&conversions()) ConversionSet(O.conversions()); 552 } 553 554 namespace { 555 // Structure used by DeductionFailureInfo to store 556 // template argument information. 557 struct DFIArguments { 558 TemplateArgument FirstArg; 559 TemplateArgument SecondArg; 560 }; 561 // Structure used by DeductionFailureInfo to store 562 // template parameter and template argument information. 563 struct DFIParamWithArguments : DFIArguments { 564 TemplateParameter Param; 565 }; 566 } 567 568 /// \brief Convert from Sema's representation of template deduction information 569 /// to the form used in overload-candidate information. 570 DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, 571 Sema::TemplateDeductionResult TDK, 572 TemplateDeductionInfo &Info) { 573 DeductionFailureInfo Result; 574 Result.Result = static_cast<unsigned>(TDK); 575 Result.HasDiagnostic = false; 576 Result.Data = 0; 577 switch (TDK) { 578 case Sema::TDK_Success: 579 case Sema::TDK_Invalid: 580 case Sema::TDK_InstantiationDepth: 581 case Sema::TDK_TooManyArguments: 582 case Sema::TDK_TooFewArguments: 583 break; 584 585 case Sema::TDK_Incomplete: 586 case Sema::TDK_InvalidExplicitArguments: 587 Result.Data = Info.Param.getOpaqueValue(); 588 break; 589 590 case Sema::TDK_NonDeducedMismatch: { 591 // FIXME: Should allocate from normal heap so that we can free this later. 592 DFIArguments *Saved = new (Context) DFIArguments; 593 Saved->FirstArg = Info.FirstArg; 594 Saved->SecondArg = Info.SecondArg; 595 Result.Data = Saved; 596 break; 597 } 598 599 case Sema::TDK_Inconsistent: 600 case Sema::TDK_Underqualified: { 601 // FIXME: Should allocate from normal heap so that we can free this later. 602 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 603 Saved->Param = Info.Param; 604 Saved->FirstArg = Info.FirstArg; 605 Saved->SecondArg = Info.SecondArg; 606 Result.Data = Saved; 607 break; 608 } 609 610 case Sema::TDK_SubstitutionFailure: 611 Result.Data = Info.take(); 612 if (Info.hasSFINAEDiagnostic()) { 613 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 614 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 615 Info.takeSFINAEDiagnostic(*Diag); 616 Result.HasDiagnostic = true; 617 } 618 break; 619 620 case Sema::TDK_FailedOverloadResolution: 621 Result.Data = Info.Expression; 622 break; 623 624 case Sema::TDK_MiscellaneousDeductionFailure: 625 break; 626 } 627 628 return Result; 629 } 630 631 void DeductionFailureInfo::Destroy() { 632 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 633 case Sema::TDK_Success: 634 case Sema::TDK_Invalid: 635 case Sema::TDK_InstantiationDepth: 636 case Sema::TDK_Incomplete: 637 case Sema::TDK_TooManyArguments: 638 case Sema::TDK_TooFewArguments: 639 case Sema::TDK_InvalidExplicitArguments: 640 case Sema::TDK_FailedOverloadResolution: 641 break; 642 643 case Sema::TDK_Inconsistent: 644 case Sema::TDK_Underqualified: 645 case Sema::TDK_NonDeducedMismatch: 646 // FIXME: Destroy the data? 647 Data = 0; 648 break; 649 650 case Sema::TDK_SubstitutionFailure: 651 // FIXME: Destroy the template argument list? 652 Data = 0; 653 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 654 Diag->~PartialDiagnosticAt(); 655 HasDiagnostic = false; 656 } 657 break; 658 659 // Unhandled 660 case Sema::TDK_MiscellaneousDeductionFailure: 661 break; 662 } 663 } 664 665 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 666 if (HasDiagnostic) 667 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 668 return 0; 669 } 670 671 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 672 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 673 case Sema::TDK_Success: 674 case Sema::TDK_Invalid: 675 case Sema::TDK_InstantiationDepth: 676 case Sema::TDK_TooManyArguments: 677 case Sema::TDK_TooFewArguments: 678 case Sema::TDK_SubstitutionFailure: 679 case Sema::TDK_NonDeducedMismatch: 680 case Sema::TDK_FailedOverloadResolution: 681 return TemplateParameter(); 682 683 case Sema::TDK_Incomplete: 684 case Sema::TDK_InvalidExplicitArguments: 685 return TemplateParameter::getFromOpaqueValue(Data); 686 687 case Sema::TDK_Inconsistent: 688 case Sema::TDK_Underqualified: 689 return static_cast<DFIParamWithArguments*>(Data)->Param; 690 691 // Unhandled 692 case Sema::TDK_MiscellaneousDeductionFailure: 693 break; 694 } 695 696 return TemplateParameter(); 697 } 698 699 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 700 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 701 case Sema::TDK_Success: 702 case Sema::TDK_Invalid: 703 case Sema::TDK_InstantiationDepth: 704 case Sema::TDK_TooManyArguments: 705 case Sema::TDK_TooFewArguments: 706 case Sema::TDK_Incomplete: 707 case Sema::TDK_InvalidExplicitArguments: 708 case Sema::TDK_Inconsistent: 709 case Sema::TDK_Underqualified: 710 case Sema::TDK_NonDeducedMismatch: 711 case Sema::TDK_FailedOverloadResolution: 712 return 0; 713 714 case Sema::TDK_SubstitutionFailure: 715 return static_cast<TemplateArgumentList*>(Data); 716 717 // Unhandled 718 case Sema::TDK_MiscellaneousDeductionFailure: 719 break; 720 } 721 722 return 0; 723 } 724 725 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 726 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 727 case Sema::TDK_Success: 728 case Sema::TDK_Invalid: 729 case Sema::TDK_InstantiationDepth: 730 case Sema::TDK_Incomplete: 731 case Sema::TDK_TooManyArguments: 732 case Sema::TDK_TooFewArguments: 733 case Sema::TDK_InvalidExplicitArguments: 734 case Sema::TDK_SubstitutionFailure: 735 case Sema::TDK_FailedOverloadResolution: 736 return 0; 737 738 case Sema::TDK_Inconsistent: 739 case Sema::TDK_Underqualified: 740 case Sema::TDK_NonDeducedMismatch: 741 return &static_cast<DFIArguments*>(Data)->FirstArg; 742 743 // Unhandled 744 case Sema::TDK_MiscellaneousDeductionFailure: 745 break; 746 } 747 748 return 0; 749 } 750 751 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 752 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 753 case Sema::TDK_Success: 754 case Sema::TDK_Invalid: 755 case Sema::TDK_InstantiationDepth: 756 case Sema::TDK_Incomplete: 757 case Sema::TDK_TooManyArguments: 758 case Sema::TDK_TooFewArguments: 759 case Sema::TDK_InvalidExplicitArguments: 760 case Sema::TDK_SubstitutionFailure: 761 case Sema::TDK_FailedOverloadResolution: 762 return 0; 763 764 case Sema::TDK_Inconsistent: 765 case Sema::TDK_Underqualified: 766 case Sema::TDK_NonDeducedMismatch: 767 return &static_cast<DFIArguments*>(Data)->SecondArg; 768 769 // Unhandled 770 case Sema::TDK_MiscellaneousDeductionFailure: 771 break; 772 } 773 774 return 0; 775 } 776 777 Expr *DeductionFailureInfo::getExpr() { 778 if (static_cast<Sema::TemplateDeductionResult>(Result) == 779 Sema::TDK_FailedOverloadResolution) 780 return static_cast<Expr*>(Data); 781 782 return 0; 783 } 784 785 void OverloadCandidateSet::destroyCandidates() { 786 for (iterator i = begin(), e = end(); i != e; ++i) { 787 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 788 i->Conversions[ii].~ImplicitConversionSequence(); 789 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 790 i->DeductionFailure.Destroy(); 791 } 792 } 793 794 void OverloadCandidateSet::clear() { 795 destroyCandidates(); 796 NumInlineSequences = 0; 797 Candidates.clear(); 798 Functions.clear(); 799 } 800 801 namespace { 802 class UnbridgedCastsSet { 803 struct Entry { 804 Expr **Addr; 805 Expr *Saved; 806 }; 807 SmallVector<Entry, 2> Entries; 808 809 public: 810 void save(Sema &S, Expr *&E) { 811 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 812 Entry entry = { &E, E }; 813 Entries.push_back(entry); 814 E = S.stripARCUnbridgedCast(E); 815 } 816 817 void restore() { 818 for (SmallVectorImpl<Entry>::iterator 819 i = Entries.begin(), e = Entries.end(); i != e; ++i) 820 *i->Addr = i->Saved; 821 } 822 }; 823 } 824 825 /// checkPlaceholderForOverload - Do any interesting placeholder-like 826 /// preprocessing on the given expression. 827 /// 828 /// \param unbridgedCasts a collection to which to add unbridged casts; 829 /// without this, they will be immediately diagnosed as errors 830 /// 831 /// Return true on unrecoverable error. 832 static bool checkPlaceholderForOverload(Sema &S, Expr *&E, 833 UnbridgedCastsSet *unbridgedCasts = 0) { 834 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 835 // We can't handle overloaded expressions here because overload 836 // resolution might reasonably tweak them. 837 if (placeholder->getKind() == BuiltinType::Overload) return false; 838 839 // If the context potentially accepts unbridged ARC casts, strip 840 // the unbridged cast and add it to the collection for later restoration. 841 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 842 unbridgedCasts) { 843 unbridgedCasts->save(S, E); 844 return false; 845 } 846 847 // Go ahead and check everything else. 848 ExprResult result = S.CheckPlaceholderExpr(E); 849 if (result.isInvalid()) 850 return true; 851 852 E = result.take(); 853 return false; 854 } 855 856 // Nothing to do. 857 return false; 858 } 859 860 /// checkArgPlaceholdersForOverload - Check a set of call operands for 861 /// placeholders. 862 static bool checkArgPlaceholdersForOverload(Sema &S, 863 MultiExprArg Args, 864 UnbridgedCastsSet &unbridged) { 865 for (unsigned i = 0, e = Args.size(); i != e; ++i) 866 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 867 return true; 868 869 return false; 870 } 871 872 // IsOverload - Determine whether the given New declaration is an 873 // overload of the declarations in Old. This routine returns false if 874 // New and Old cannot be overloaded, e.g., if New has the same 875 // signature as some function in Old (C++ 1.3.10) or if the Old 876 // declarations aren't functions (or function templates) at all. When 877 // it does return false, MatchedDecl will point to the decl that New 878 // cannot be overloaded with. This decl may be a UsingShadowDecl on 879 // top of the underlying declaration. 880 // 881 // Example: Given the following input: 882 // 883 // void f(int, float); // #1 884 // void f(int, int); // #2 885 // int f(int, int); // #3 886 // 887 // When we process #1, there is no previous declaration of "f", 888 // so IsOverload will not be used. 889 // 890 // When we process #2, Old contains only the FunctionDecl for #1. By 891 // comparing the parameter types, we see that #1 and #2 are overloaded 892 // (since they have different signatures), so this routine returns 893 // false; MatchedDecl is unchanged. 894 // 895 // When we process #3, Old is an overload set containing #1 and #2. We 896 // compare the signatures of #3 to #1 (they're overloaded, so we do 897 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 898 // identical (return types of functions are not part of the 899 // signature), IsOverload returns false and MatchedDecl will be set to 900 // point to the FunctionDecl for #2. 901 // 902 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 903 // into a class by a using declaration. The rules for whether to hide 904 // shadow declarations ignore some properties which otherwise figure 905 // into a function template's signature. 906 Sema::OverloadKind 907 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 908 NamedDecl *&Match, bool NewIsUsingDecl) { 909 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 910 I != E; ++I) { 911 NamedDecl *OldD = *I; 912 913 bool OldIsUsingDecl = false; 914 if (isa<UsingShadowDecl>(OldD)) { 915 OldIsUsingDecl = true; 916 917 // We can always introduce two using declarations into the same 918 // context, even if they have identical signatures. 919 if (NewIsUsingDecl) continue; 920 921 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 922 } 923 924 // If either declaration was introduced by a using declaration, 925 // we'll need to use slightly different rules for matching. 926 // Essentially, these rules are the normal rules, except that 927 // function templates hide function templates with different 928 // return types or template parameter lists. 929 bool UseMemberUsingDeclRules = 930 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 931 !New->getFriendObjectKind(); 932 933 if (FunctionDecl *OldF = OldD->getAsFunction()) { 934 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 935 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 936 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 937 continue; 938 } 939 940 if (!isa<FunctionTemplateDecl>(OldD) && 941 !shouldLinkPossiblyHiddenDecl(*I, New)) 942 continue; 943 944 Match = *I; 945 return Ovl_Match; 946 } 947 } else if (isa<UsingDecl>(OldD)) { 948 // We can overload with these, which can show up when doing 949 // redeclaration checks for UsingDecls. 950 assert(Old.getLookupKind() == LookupUsingDeclName); 951 } else if (isa<TagDecl>(OldD)) { 952 // We can always overload with tags by hiding them. 953 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 954 // Optimistically assume that an unresolved using decl will 955 // overload; if it doesn't, we'll have to diagnose during 956 // template instantiation. 957 } else { 958 // (C++ 13p1): 959 // Only function declarations can be overloaded; object and type 960 // declarations cannot be overloaded. 961 Match = *I; 962 return Ovl_NonFunction; 963 } 964 } 965 966 return Ovl_Overload; 967 } 968 969 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 970 bool UseUsingDeclRules) { 971 // C++ [basic.start.main]p2: This function shall not be overloaded. 972 if (New->isMain()) 973 return false; 974 975 // MSVCRT user defined entry points cannot be overloaded. 976 if (New->isMSVCRTEntryPoint()) 977 return false; 978 979 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 980 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 981 982 // C++ [temp.fct]p2: 983 // A function template can be overloaded with other function templates 984 // and with normal (non-template) functions. 985 if ((OldTemplate == 0) != (NewTemplate == 0)) 986 return true; 987 988 // Is the function New an overload of the function Old? 989 QualType OldQType = Context.getCanonicalType(Old->getType()); 990 QualType NewQType = Context.getCanonicalType(New->getType()); 991 992 // Compare the signatures (C++ 1.3.10) of the two functions to 993 // determine whether they are overloads. If we find any mismatch 994 // in the signature, they are overloads. 995 996 // If either of these functions is a K&R-style function (no 997 // prototype), then we consider them to have matching signatures. 998 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 999 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1000 return false; 1001 1002 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1003 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1004 1005 // The signature of a function includes the types of its 1006 // parameters (C++ 1.3.10), which includes the presence or absence 1007 // of the ellipsis; see C++ DR 357). 1008 if (OldQType != NewQType && 1009 (OldType->getNumParams() != NewType->getNumParams() || 1010 OldType->isVariadic() != NewType->isVariadic() || 1011 !FunctionParamTypesAreEqual(OldType, NewType))) 1012 return true; 1013 1014 // C++ [temp.over.link]p4: 1015 // The signature of a function template consists of its function 1016 // signature, its return type and its template parameter list. The names 1017 // of the template parameters are significant only for establishing the 1018 // relationship between the template parameters and the rest of the 1019 // signature. 1020 // 1021 // We check the return type and template parameter lists for function 1022 // templates first; the remaining checks follow. 1023 // 1024 // However, we don't consider either of these when deciding whether 1025 // a member introduced by a shadow declaration is hidden. 1026 if (!UseUsingDeclRules && NewTemplate && 1027 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1028 OldTemplate->getTemplateParameters(), 1029 false, TPL_TemplateMatch) || 1030 OldType->getReturnType() != NewType->getReturnType())) 1031 return true; 1032 1033 // If the function is a class member, its signature includes the 1034 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1035 // 1036 // As part of this, also check whether one of the member functions 1037 // is static, in which case they are not overloads (C++ 1038 // 13.1p2). While not part of the definition of the signature, 1039 // this check is important to determine whether these functions 1040 // can be overloaded. 1041 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1042 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1043 if (OldMethod && NewMethod && 1044 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1045 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1046 if (!UseUsingDeclRules && 1047 (OldMethod->getRefQualifier() == RQ_None || 1048 NewMethod->getRefQualifier() == RQ_None)) { 1049 // C++0x [over.load]p2: 1050 // - Member function declarations with the same name and the same 1051 // parameter-type-list as well as member function template 1052 // declarations with the same name, the same parameter-type-list, and 1053 // the same template parameter lists cannot be overloaded if any of 1054 // them, but not all, have a ref-qualifier (8.3.5). 1055 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1056 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1057 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1058 } 1059 return true; 1060 } 1061 1062 // We may not have applied the implicit const for a constexpr member 1063 // function yet (because we haven't yet resolved whether this is a static 1064 // or non-static member function). Add it now, on the assumption that this 1065 // is a redeclaration of OldMethod. 1066 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1067 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1068 if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() && 1069 !isa<CXXConstructorDecl>(NewMethod)) 1070 NewQuals |= Qualifiers::Const; 1071 1072 // We do not allow overloading based off of '__restrict'. 1073 OldQuals &= ~Qualifiers::Restrict; 1074 NewQuals &= ~Qualifiers::Restrict; 1075 if (OldQuals != NewQuals) 1076 return true; 1077 } 1078 1079 // enable_if attributes are an order-sensitive part of the signature. 1080 for (specific_attr_iterator<EnableIfAttr> 1081 NewI = New->specific_attr_begin<EnableIfAttr>(), 1082 NewE = New->specific_attr_end<EnableIfAttr>(), 1083 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1084 OldE = Old->specific_attr_end<EnableIfAttr>(); 1085 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1086 if (NewI == NewE || OldI == OldE) 1087 return true; 1088 llvm::FoldingSetNodeID NewID, OldID; 1089 NewI->getCond()->Profile(NewID, Context, true); 1090 OldI->getCond()->Profile(OldID, Context, true); 1091 if (NewID != OldID) 1092 return true; 1093 } 1094 1095 // The signatures match; this is not an overload. 1096 return false; 1097 } 1098 1099 /// \brief Checks availability of the function depending on the current 1100 /// function context. Inside an unavailable function, unavailability is ignored. 1101 /// 1102 /// \returns true if \arg FD is unavailable and current context is inside 1103 /// an available function, false otherwise. 1104 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1105 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1106 } 1107 1108 /// \brief Tries a user-defined conversion from From to ToType. 1109 /// 1110 /// Produces an implicit conversion sequence for when a standard conversion 1111 /// is not an option. See TryImplicitConversion for more information. 1112 static ImplicitConversionSequence 1113 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1114 bool SuppressUserConversions, 1115 bool AllowExplicit, 1116 bool InOverloadResolution, 1117 bool CStyle, 1118 bool AllowObjCWritebackConversion, 1119 bool AllowObjCConversionOnExplicit) { 1120 ImplicitConversionSequence ICS; 1121 1122 if (SuppressUserConversions) { 1123 // We're not in the case above, so there is no conversion that 1124 // we can perform. 1125 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1126 return ICS; 1127 } 1128 1129 // Attempt user-defined conversion. 1130 OverloadCandidateSet Conversions(From->getExprLoc(), 1131 OverloadCandidateSet::CSK_Normal); 1132 OverloadingResult UserDefResult 1133 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 1134 AllowExplicit, AllowObjCConversionOnExplicit); 1135 1136 if (UserDefResult == OR_Success) { 1137 ICS.setUserDefined(); 1138 ICS.UserDefined.Before.setAsIdentityConversion(); 1139 // C++ [over.ics.user]p4: 1140 // A conversion of an expression of class type to the same class 1141 // type is given Exact Match rank, and a conversion of an 1142 // expression of class type to a base class of that type is 1143 // given Conversion rank, in spite of the fact that a copy 1144 // constructor (i.e., a user-defined conversion function) is 1145 // called for those cases. 1146 if (CXXConstructorDecl *Constructor 1147 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1148 QualType FromCanon 1149 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1150 QualType ToCanon 1151 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1152 if (Constructor->isCopyConstructor() && 1153 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1154 // Turn this into a "standard" conversion sequence, so that it 1155 // gets ranked with standard conversion sequences. 1156 ICS.setStandard(); 1157 ICS.Standard.setAsIdentityConversion(); 1158 ICS.Standard.setFromType(From->getType()); 1159 ICS.Standard.setAllToTypes(ToType); 1160 ICS.Standard.CopyConstructor = Constructor; 1161 if (ToCanon != FromCanon) 1162 ICS.Standard.Second = ICK_Derived_To_Base; 1163 } 1164 } 1165 1166 // C++ [over.best.ics]p4: 1167 // However, when considering the argument of a user-defined 1168 // conversion function that is a candidate by 13.3.1.3 when 1169 // invoked for the copying of the temporary in the second step 1170 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 1171 // 13.3.1.6 in all cases, only standard conversion sequences and 1172 // ellipsis conversion sequences are allowed. 1173 if (SuppressUserConversions && ICS.isUserDefined()) { 1174 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 1175 } 1176 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 1177 ICS.setAmbiguous(); 1178 ICS.Ambiguous.setFromType(From->getType()); 1179 ICS.Ambiguous.setToType(ToType); 1180 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1181 Cand != Conversions.end(); ++Cand) 1182 if (Cand->Viable) 1183 ICS.Ambiguous.addConversion(Cand->Function); 1184 } else { 1185 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1186 } 1187 1188 return ICS; 1189 } 1190 1191 /// TryImplicitConversion - Attempt to perform an implicit conversion 1192 /// from the given expression (Expr) to the given type (ToType). This 1193 /// function returns an implicit conversion sequence that can be used 1194 /// to perform the initialization. Given 1195 /// 1196 /// void f(float f); 1197 /// void g(int i) { f(i); } 1198 /// 1199 /// this routine would produce an implicit conversion sequence to 1200 /// describe the initialization of f from i, which will be a standard 1201 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1202 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1203 // 1204 /// Note that this routine only determines how the conversion can be 1205 /// performed; it does not actually perform the conversion. As such, 1206 /// it will not produce any diagnostics if no conversion is available, 1207 /// but will instead return an implicit conversion sequence of kind 1208 /// "BadConversion". 1209 /// 1210 /// If @p SuppressUserConversions, then user-defined conversions are 1211 /// not permitted. 1212 /// If @p AllowExplicit, then explicit user-defined conversions are 1213 /// permitted. 1214 /// 1215 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1216 /// writeback conversion, which allows __autoreleasing id* parameters to 1217 /// be initialized with __strong id* or __weak id* arguments. 1218 static ImplicitConversionSequence 1219 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1220 bool SuppressUserConversions, 1221 bool AllowExplicit, 1222 bool InOverloadResolution, 1223 bool CStyle, 1224 bool AllowObjCWritebackConversion, 1225 bool AllowObjCConversionOnExplicit) { 1226 ImplicitConversionSequence ICS; 1227 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1228 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1229 ICS.setStandard(); 1230 return ICS; 1231 } 1232 1233 if (!S.getLangOpts().CPlusPlus) { 1234 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1235 return ICS; 1236 } 1237 1238 // C++ [over.ics.user]p4: 1239 // A conversion of an expression of class type to the same class 1240 // type is given Exact Match rank, and a conversion of an 1241 // expression of class type to a base class of that type is 1242 // given Conversion rank, in spite of the fact that a copy/move 1243 // constructor (i.e., a user-defined conversion function) is 1244 // called for those cases. 1245 QualType FromType = From->getType(); 1246 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1247 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1248 S.IsDerivedFrom(FromType, ToType))) { 1249 ICS.setStandard(); 1250 ICS.Standard.setAsIdentityConversion(); 1251 ICS.Standard.setFromType(FromType); 1252 ICS.Standard.setAllToTypes(ToType); 1253 1254 // We don't actually check at this point whether there is a valid 1255 // copy/move constructor, since overloading just assumes that it 1256 // exists. When we actually perform initialization, we'll find the 1257 // appropriate constructor to copy the returned object, if needed. 1258 ICS.Standard.CopyConstructor = 0; 1259 1260 // Determine whether this is considered a derived-to-base conversion. 1261 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1262 ICS.Standard.Second = ICK_Derived_To_Base; 1263 1264 return ICS; 1265 } 1266 1267 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1268 AllowExplicit, InOverloadResolution, CStyle, 1269 AllowObjCWritebackConversion, 1270 AllowObjCConversionOnExplicit); 1271 } 1272 1273 ImplicitConversionSequence 1274 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1275 bool SuppressUserConversions, 1276 bool AllowExplicit, 1277 bool InOverloadResolution, 1278 bool CStyle, 1279 bool AllowObjCWritebackConversion) { 1280 return clang::TryImplicitConversion(*this, From, ToType, 1281 SuppressUserConversions, AllowExplicit, 1282 InOverloadResolution, CStyle, 1283 AllowObjCWritebackConversion, 1284 /*AllowObjCConversionOnExplicit=*/false); 1285 } 1286 1287 /// PerformImplicitConversion - Perform an implicit conversion of the 1288 /// expression From to the type ToType. Returns the 1289 /// converted expression. Flavor is the kind of conversion we're 1290 /// performing, used in the error message. If @p AllowExplicit, 1291 /// explicit user-defined conversions are permitted. 1292 ExprResult 1293 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1294 AssignmentAction Action, bool AllowExplicit) { 1295 ImplicitConversionSequence ICS; 1296 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1297 } 1298 1299 ExprResult 1300 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1301 AssignmentAction Action, bool AllowExplicit, 1302 ImplicitConversionSequence& ICS) { 1303 if (checkPlaceholderForOverload(*this, From)) 1304 return ExprError(); 1305 1306 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1307 bool AllowObjCWritebackConversion 1308 = getLangOpts().ObjCAutoRefCount && 1309 (Action == AA_Passing || Action == AA_Sending); 1310 if (getLangOpts().ObjC1) 1311 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1312 ToType, From->getType(), From); 1313 ICS = clang::TryImplicitConversion(*this, From, ToType, 1314 /*SuppressUserConversions=*/false, 1315 AllowExplicit, 1316 /*InOverloadResolution=*/false, 1317 /*CStyle=*/false, 1318 AllowObjCWritebackConversion, 1319 /*AllowObjCConversionOnExplicit=*/false); 1320 return PerformImplicitConversion(From, ToType, ICS, Action); 1321 } 1322 1323 /// \brief Determine whether the conversion from FromType to ToType is a valid 1324 /// conversion that strips "noreturn" off the nested function type. 1325 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1326 QualType &ResultTy) { 1327 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1328 return false; 1329 1330 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1331 // where F adds one of the following at most once: 1332 // - a pointer 1333 // - a member pointer 1334 // - a block pointer 1335 CanQualType CanTo = Context.getCanonicalType(ToType); 1336 CanQualType CanFrom = Context.getCanonicalType(FromType); 1337 Type::TypeClass TyClass = CanTo->getTypeClass(); 1338 if (TyClass != CanFrom->getTypeClass()) return false; 1339 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1340 if (TyClass == Type::Pointer) { 1341 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1342 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1343 } else if (TyClass == Type::BlockPointer) { 1344 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1345 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1346 } else if (TyClass == Type::MemberPointer) { 1347 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1348 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1349 } else { 1350 return false; 1351 } 1352 1353 TyClass = CanTo->getTypeClass(); 1354 if (TyClass != CanFrom->getTypeClass()) return false; 1355 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1356 return false; 1357 } 1358 1359 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1360 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1361 if (!EInfo.getNoReturn()) return false; 1362 1363 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1364 assert(QualType(FromFn, 0).isCanonical()); 1365 if (QualType(FromFn, 0) != CanTo) return false; 1366 1367 ResultTy = ToType; 1368 return true; 1369 } 1370 1371 /// \brief Determine whether the conversion from FromType to ToType is a valid 1372 /// vector conversion. 1373 /// 1374 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1375 /// conversion. 1376 static bool IsVectorConversion(Sema &S, QualType FromType, 1377 QualType ToType, ImplicitConversionKind &ICK) { 1378 // We need at least one of these types to be a vector type to have a vector 1379 // conversion. 1380 if (!ToType->isVectorType() && !FromType->isVectorType()) 1381 return false; 1382 1383 // Identical types require no conversions. 1384 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1385 return false; 1386 1387 // There are no conversions between extended vector types, only identity. 1388 if (ToType->isExtVectorType()) { 1389 // There are no conversions between extended vector types other than the 1390 // identity conversion. 1391 if (FromType->isExtVectorType()) 1392 return false; 1393 1394 // Vector splat from any arithmetic type to a vector. 1395 if (FromType->isArithmeticType()) { 1396 ICK = ICK_Vector_Splat; 1397 return true; 1398 } 1399 } 1400 1401 // We can perform the conversion between vector types in the following cases: 1402 // 1)vector types are equivalent AltiVec and GCC vector types 1403 // 2)lax vector conversions are permitted and the vector types are of the 1404 // same size 1405 if (ToType->isVectorType() && FromType->isVectorType()) { 1406 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1407 S.isLaxVectorConversion(FromType, ToType)) { 1408 ICK = ICK_Vector_Conversion; 1409 return true; 1410 } 1411 } 1412 1413 return false; 1414 } 1415 1416 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1417 bool InOverloadResolution, 1418 StandardConversionSequence &SCS, 1419 bool CStyle); 1420 1421 /// IsStandardConversion - Determines whether there is a standard 1422 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1423 /// expression From to the type ToType. Standard conversion sequences 1424 /// only consider non-class types; for conversions that involve class 1425 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1426 /// contain the standard conversion sequence required to perform this 1427 /// conversion and this routine will return true. Otherwise, this 1428 /// routine will return false and the value of SCS is unspecified. 1429 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1430 bool InOverloadResolution, 1431 StandardConversionSequence &SCS, 1432 bool CStyle, 1433 bool AllowObjCWritebackConversion) { 1434 QualType FromType = From->getType(); 1435 1436 // Standard conversions (C++ [conv]) 1437 SCS.setAsIdentityConversion(); 1438 SCS.IncompatibleObjC = false; 1439 SCS.setFromType(FromType); 1440 SCS.CopyConstructor = 0; 1441 1442 // There are no standard conversions for class types in C++, so 1443 // abort early. When overloading in C, however, we do permit 1444 if (FromType->isRecordType() || ToType->isRecordType()) { 1445 if (S.getLangOpts().CPlusPlus) 1446 return false; 1447 1448 // When we're overloading in C, we allow, as standard conversions, 1449 } 1450 1451 // The first conversion can be an lvalue-to-rvalue conversion, 1452 // array-to-pointer conversion, or function-to-pointer conversion 1453 // (C++ 4p1). 1454 1455 if (FromType == S.Context.OverloadTy) { 1456 DeclAccessPair AccessPair; 1457 if (FunctionDecl *Fn 1458 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1459 AccessPair)) { 1460 // We were able to resolve the address of the overloaded function, 1461 // so we can convert to the type of that function. 1462 FromType = Fn->getType(); 1463 1464 // we can sometimes resolve &foo<int> regardless of ToType, so check 1465 // if the type matches (identity) or we are converting to bool 1466 if (!S.Context.hasSameUnqualifiedType( 1467 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1468 QualType resultTy; 1469 // if the function type matches except for [[noreturn]], it's ok 1470 if (!S.IsNoReturnConversion(FromType, 1471 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1472 // otherwise, only a boolean conversion is standard 1473 if (!ToType->isBooleanType()) 1474 return false; 1475 } 1476 1477 // Check if the "from" expression is taking the address of an overloaded 1478 // function and recompute the FromType accordingly. Take advantage of the 1479 // fact that non-static member functions *must* have such an address-of 1480 // expression. 1481 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1482 if (Method && !Method->isStatic()) { 1483 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1484 "Non-unary operator on non-static member address"); 1485 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1486 == UO_AddrOf && 1487 "Non-address-of operator on non-static member address"); 1488 const Type *ClassType 1489 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1490 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1491 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1492 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1493 UO_AddrOf && 1494 "Non-address-of operator for overloaded function expression"); 1495 FromType = S.Context.getPointerType(FromType); 1496 } 1497 1498 // Check that we've computed the proper type after overload resolution. 1499 assert(S.Context.hasSameType( 1500 FromType, 1501 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1502 } else { 1503 return false; 1504 } 1505 } 1506 // Lvalue-to-rvalue conversion (C++11 4.1): 1507 // A glvalue (3.10) of a non-function, non-array type T can 1508 // be converted to a prvalue. 1509 bool argIsLValue = From->isGLValue(); 1510 if (argIsLValue && 1511 !FromType->isFunctionType() && !FromType->isArrayType() && 1512 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1513 SCS.First = ICK_Lvalue_To_Rvalue; 1514 1515 // C11 6.3.2.1p2: 1516 // ... if the lvalue has atomic type, the value has the non-atomic version 1517 // of the type of the lvalue ... 1518 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1519 FromType = Atomic->getValueType(); 1520 1521 // If T is a non-class type, the type of the rvalue is the 1522 // cv-unqualified version of T. Otherwise, the type of the rvalue 1523 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1524 // just strip the qualifiers because they don't matter. 1525 FromType = FromType.getUnqualifiedType(); 1526 } else if (FromType->isArrayType()) { 1527 // Array-to-pointer conversion (C++ 4.2) 1528 SCS.First = ICK_Array_To_Pointer; 1529 1530 // An lvalue or rvalue of type "array of N T" or "array of unknown 1531 // bound of T" can be converted to an rvalue of type "pointer to 1532 // T" (C++ 4.2p1). 1533 FromType = S.Context.getArrayDecayedType(FromType); 1534 1535 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1536 // This conversion is deprecated in C++03 (D.4) 1537 SCS.DeprecatedStringLiteralToCharPtr = true; 1538 1539 // For the purpose of ranking in overload resolution 1540 // (13.3.3.1.1), this conversion is considered an 1541 // array-to-pointer conversion followed by a qualification 1542 // conversion (4.4). (C++ 4.2p2) 1543 SCS.Second = ICK_Identity; 1544 SCS.Third = ICK_Qualification; 1545 SCS.QualificationIncludesObjCLifetime = false; 1546 SCS.setAllToTypes(FromType); 1547 return true; 1548 } 1549 } else if (FromType->isFunctionType() && argIsLValue) { 1550 // Function-to-pointer conversion (C++ 4.3). 1551 SCS.First = ICK_Function_To_Pointer; 1552 1553 // An lvalue of function type T can be converted to an rvalue of 1554 // type "pointer to T." The result is a pointer to the 1555 // function. (C++ 4.3p1). 1556 FromType = S.Context.getPointerType(FromType); 1557 } else { 1558 // We don't require any conversions for the first step. 1559 SCS.First = ICK_Identity; 1560 } 1561 SCS.setToType(0, FromType); 1562 1563 // The second conversion can be an integral promotion, floating 1564 // point promotion, integral conversion, floating point conversion, 1565 // floating-integral conversion, pointer conversion, 1566 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1567 // For overloading in C, this can also be a "compatible-type" 1568 // conversion. 1569 bool IncompatibleObjC = false; 1570 ImplicitConversionKind SecondICK = ICK_Identity; 1571 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1572 // The unqualified versions of the types are the same: there's no 1573 // conversion to do. 1574 SCS.Second = ICK_Identity; 1575 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1576 // Integral promotion (C++ 4.5). 1577 SCS.Second = ICK_Integral_Promotion; 1578 FromType = ToType.getUnqualifiedType(); 1579 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1580 // Floating point promotion (C++ 4.6). 1581 SCS.Second = ICK_Floating_Promotion; 1582 FromType = ToType.getUnqualifiedType(); 1583 } else if (S.IsComplexPromotion(FromType, ToType)) { 1584 // Complex promotion (Clang extension) 1585 SCS.Second = ICK_Complex_Promotion; 1586 FromType = ToType.getUnqualifiedType(); 1587 } else if (ToType->isBooleanType() && 1588 (FromType->isArithmeticType() || 1589 FromType->isAnyPointerType() || 1590 FromType->isBlockPointerType() || 1591 FromType->isMemberPointerType() || 1592 FromType->isNullPtrType())) { 1593 // Boolean conversions (C++ 4.12). 1594 SCS.Second = ICK_Boolean_Conversion; 1595 FromType = S.Context.BoolTy; 1596 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1597 ToType->isIntegralType(S.Context)) { 1598 // Integral conversions (C++ 4.7). 1599 SCS.Second = ICK_Integral_Conversion; 1600 FromType = ToType.getUnqualifiedType(); 1601 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1602 // Complex conversions (C99 6.3.1.6) 1603 SCS.Second = ICK_Complex_Conversion; 1604 FromType = ToType.getUnqualifiedType(); 1605 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1606 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1607 // Complex-real conversions (C99 6.3.1.7) 1608 SCS.Second = ICK_Complex_Real; 1609 FromType = ToType.getUnqualifiedType(); 1610 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1611 // Floating point conversions (C++ 4.8). 1612 SCS.Second = ICK_Floating_Conversion; 1613 FromType = ToType.getUnqualifiedType(); 1614 } else if ((FromType->isRealFloatingType() && 1615 ToType->isIntegralType(S.Context)) || 1616 (FromType->isIntegralOrUnscopedEnumerationType() && 1617 ToType->isRealFloatingType())) { 1618 // Floating-integral conversions (C++ 4.9). 1619 SCS.Second = ICK_Floating_Integral; 1620 FromType = ToType.getUnqualifiedType(); 1621 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1622 SCS.Second = ICK_Block_Pointer_Conversion; 1623 } else if (AllowObjCWritebackConversion && 1624 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1625 SCS.Second = ICK_Writeback_Conversion; 1626 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1627 FromType, IncompatibleObjC)) { 1628 // Pointer conversions (C++ 4.10). 1629 SCS.Second = ICK_Pointer_Conversion; 1630 SCS.IncompatibleObjC = IncompatibleObjC; 1631 FromType = FromType.getUnqualifiedType(); 1632 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1633 InOverloadResolution, FromType)) { 1634 // Pointer to member conversions (4.11). 1635 SCS.Second = ICK_Pointer_Member; 1636 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1637 SCS.Second = SecondICK; 1638 FromType = ToType.getUnqualifiedType(); 1639 } else if (!S.getLangOpts().CPlusPlus && 1640 S.Context.typesAreCompatible(ToType, FromType)) { 1641 // Compatible conversions (Clang extension for C function overloading) 1642 SCS.Second = ICK_Compatible_Conversion; 1643 FromType = ToType.getUnqualifiedType(); 1644 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1645 // Treat a conversion that strips "noreturn" as an identity conversion. 1646 SCS.Second = ICK_NoReturn_Adjustment; 1647 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1648 InOverloadResolution, 1649 SCS, CStyle)) { 1650 SCS.Second = ICK_TransparentUnionConversion; 1651 FromType = ToType; 1652 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1653 CStyle)) { 1654 // tryAtomicConversion has updated the standard conversion sequence 1655 // appropriately. 1656 return true; 1657 } else if (ToType->isEventT() && 1658 From->isIntegerConstantExpr(S.getASTContext()) && 1659 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1660 SCS.Second = ICK_Zero_Event_Conversion; 1661 FromType = ToType; 1662 } else { 1663 // No second conversion required. 1664 SCS.Second = ICK_Identity; 1665 } 1666 SCS.setToType(1, FromType); 1667 1668 QualType CanonFrom; 1669 QualType CanonTo; 1670 // The third conversion can be a qualification conversion (C++ 4p1). 1671 bool ObjCLifetimeConversion; 1672 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1673 ObjCLifetimeConversion)) { 1674 SCS.Third = ICK_Qualification; 1675 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1676 FromType = ToType; 1677 CanonFrom = S.Context.getCanonicalType(FromType); 1678 CanonTo = S.Context.getCanonicalType(ToType); 1679 } else { 1680 // No conversion required 1681 SCS.Third = ICK_Identity; 1682 1683 // C++ [over.best.ics]p6: 1684 // [...] Any difference in top-level cv-qualification is 1685 // subsumed by the initialization itself and does not constitute 1686 // a conversion. [...] 1687 CanonFrom = S.Context.getCanonicalType(FromType); 1688 CanonTo = S.Context.getCanonicalType(ToType); 1689 if (CanonFrom.getLocalUnqualifiedType() 1690 == CanonTo.getLocalUnqualifiedType() && 1691 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1692 FromType = ToType; 1693 CanonFrom = CanonTo; 1694 } 1695 } 1696 SCS.setToType(2, FromType); 1697 1698 // If we have not converted the argument type to the parameter type, 1699 // this is a bad conversion sequence. 1700 if (CanonFrom != CanonTo) 1701 return false; 1702 1703 return true; 1704 } 1705 1706 static bool 1707 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1708 QualType &ToType, 1709 bool InOverloadResolution, 1710 StandardConversionSequence &SCS, 1711 bool CStyle) { 1712 1713 const RecordType *UT = ToType->getAsUnionType(); 1714 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1715 return false; 1716 // The field to initialize within the transparent union. 1717 RecordDecl *UD = UT->getDecl(); 1718 // It's compatible if the expression matches any of the fields. 1719 for (const auto *it : UD->fields()) { 1720 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1721 CStyle, /*ObjCWritebackConversion=*/false)) { 1722 ToType = it->getType(); 1723 return true; 1724 } 1725 } 1726 return false; 1727 } 1728 1729 /// IsIntegralPromotion - Determines whether the conversion from the 1730 /// expression From (whose potentially-adjusted type is FromType) to 1731 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1732 /// sets PromotedType to the promoted type. 1733 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1734 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1735 // All integers are built-in. 1736 if (!To) { 1737 return false; 1738 } 1739 1740 // An rvalue of type char, signed char, unsigned char, short int, or 1741 // unsigned short int can be converted to an rvalue of type int if 1742 // int can represent all the values of the source type; otherwise, 1743 // the source rvalue can be converted to an rvalue of type unsigned 1744 // int (C++ 4.5p1). 1745 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1746 !FromType->isEnumeralType()) { 1747 if (// We can promote any signed, promotable integer type to an int 1748 (FromType->isSignedIntegerType() || 1749 // We can promote any unsigned integer type whose size is 1750 // less than int to an int. 1751 (!FromType->isSignedIntegerType() && 1752 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1753 return To->getKind() == BuiltinType::Int; 1754 } 1755 1756 return To->getKind() == BuiltinType::UInt; 1757 } 1758 1759 // C++11 [conv.prom]p3: 1760 // A prvalue of an unscoped enumeration type whose underlying type is not 1761 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1762 // following types that can represent all the values of the enumeration 1763 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1764 // unsigned int, long int, unsigned long int, long long int, or unsigned 1765 // long long int. If none of the types in that list can represent all the 1766 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1767 // type can be converted to an rvalue a prvalue of the extended integer type 1768 // with lowest integer conversion rank (4.13) greater than the rank of long 1769 // long in which all the values of the enumeration can be represented. If 1770 // there are two such extended types, the signed one is chosen. 1771 // C++11 [conv.prom]p4: 1772 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1773 // can be converted to a prvalue of its underlying type. Moreover, if 1774 // integral promotion can be applied to its underlying type, a prvalue of an 1775 // unscoped enumeration type whose underlying type is fixed can also be 1776 // converted to a prvalue of the promoted underlying type. 1777 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1778 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1779 // provided for a scoped enumeration. 1780 if (FromEnumType->getDecl()->isScoped()) 1781 return false; 1782 1783 // We can perform an integral promotion to the underlying type of the enum, 1784 // even if that's not the promoted type. 1785 if (FromEnumType->getDecl()->isFixed()) { 1786 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1787 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1788 IsIntegralPromotion(From, Underlying, ToType); 1789 } 1790 1791 // We have already pre-calculated the promotion type, so this is trivial. 1792 if (ToType->isIntegerType() && 1793 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1794 return Context.hasSameUnqualifiedType(ToType, 1795 FromEnumType->getDecl()->getPromotionType()); 1796 } 1797 1798 // C++0x [conv.prom]p2: 1799 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1800 // to an rvalue a prvalue of the first of the following types that can 1801 // represent all the values of its underlying type: int, unsigned int, 1802 // long int, unsigned long int, long long int, or unsigned long long int. 1803 // If none of the types in that list can represent all the values of its 1804 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1805 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1806 // type. 1807 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1808 ToType->isIntegerType()) { 1809 // Determine whether the type we're converting from is signed or 1810 // unsigned. 1811 bool FromIsSigned = FromType->isSignedIntegerType(); 1812 uint64_t FromSize = Context.getTypeSize(FromType); 1813 1814 // The types we'll try to promote to, in the appropriate 1815 // order. Try each of these types. 1816 QualType PromoteTypes[6] = { 1817 Context.IntTy, Context.UnsignedIntTy, 1818 Context.LongTy, Context.UnsignedLongTy , 1819 Context.LongLongTy, Context.UnsignedLongLongTy 1820 }; 1821 for (int Idx = 0; Idx < 6; ++Idx) { 1822 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1823 if (FromSize < ToSize || 1824 (FromSize == ToSize && 1825 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1826 // We found the type that we can promote to. If this is the 1827 // type we wanted, we have a promotion. Otherwise, no 1828 // promotion. 1829 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1830 } 1831 } 1832 } 1833 1834 // An rvalue for an integral bit-field (9.6) can be converted to an 1835 // rvalue of type int if int can represent all the values of the 1836 // bit-field; otherwise, it can be converted to unsigned int if 1837 // unsigned int can represent all the values of the bit-field. If 1838 // the bit-field is larger yet, no integral promotion applies to 1839 // it. If the bit-field has an enumerated type, it is treated as any 1840 // other value of that type for promotion purposes (C++ 4.5p3). 1841 // FIXME: We should delay checking of bit-fields until we actually perform the 1842 // conversion. 1843 using llvm::APSInt; 1844 if (From) 1845 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1846 APSInt BitWidth; 1847 if (FromType->isIntegralType(Context) && 1848 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1849 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1850 ToSize = Context.getTypeSize(ToType); 1851 1852 // Are we promoting to an int from a bitfield that fits in an int? 1853 if (BitWidth < ToSize || 1854 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1855 return To->getKind() == BuiltinType::Int; 1856 } 1857 1858 // Are we promoting to an unsigned int from an unsigned bitfield 1859 // that fits into an unsigned int? 1860 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1861 return To->getKind() == BuiltinType::UInt; 1862 } 1863 1864 return false; 1865 } 1866 } 1867 1868 // An rvalue of type bool can be converted to an rvalue of type int, 1869 // with false becoming zero and true becoming one (C++ 4.5p4). 1870 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1871 return true; 1872 } 1873 1874 return false; 1875 } 1876 1877 /// IsFloatingPointPromotion - Determines whether the conversion from 1878 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1879 /// returns true and sets PromotedType to the promoted type. 1880 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1881 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1882 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1883 /// An rvalue of type float can be converted to an rvalue of type 1884 /// double. (C++ 4.6p1). 1885 if (FromBuiltin->getKind() == BuiltinType::Float && 1886 ToBuiltin->getKind() == BuiltinType::Double) 1887 return true; 1888 1889 // C99 6.3.1.5p1: 1890 // When a float is promoted to double or long double, or a 1891 // double is promoted to long double [...]. 1892 if (!getLangOpts().CPlusPlus && 1893 (FromBuiltin->getKind() == BuiltinType::Float || 1894 FromBuiltin->getKind() == BuiltinType::Double) && 1895 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1896 return true; 1897 1898 // Half can be promoted to float. 1899 if (!getLangOpts().NativeHalfType && 1900 FromBuiltin->getKind() == BuiltinType::Half && 1901 ToBuiltin->getKind() == BuiltinType::Float) 1902 return true; 1903 } 1904 1905 return false; 1906 } 1907 1908 /// \brief Determine if a conversion is a complex promotion. 1909 /// 1910 /// A complex promotion is defined as a complex -> complex conversion 1911 /// where the conversion between the underlying real types is a 1912 /// floating-point or integral promotion. 1913 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1914 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1915 if (!FromComplex) 1916 return false; 1917 1918 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1919 if (!ToComplex) 1920 return false; 1921 1922 return IsFloatingPointPromotion(FromComplex->getElementType(), 1923 ToComplex->getElementType()) || 1924 IsIntegralPromotion(0, FromComplex->getElementType(), 1925 ToComplex->getElementType()); 1926 } 1927 1928 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1929 /// the pointer type FromPtr to a pointer to type ToPointee, with the 1930 /// same type qualifiers as FromPtr has on its pointee type. ToType, 1931 /// if non-empty, will be a pointer to ToType that may or may not have 1932 /// the right set of qualifiers on its pointee. 1933 /// 1934 static QualType 1935 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1936 QualType ToPointee, QualType ToType, 1937 ASTContext &Context, 1938 bool StripObjCLifetime = false) { 1939 assert((FromPtr->getTypeClass() == Type::Pointer || 1940 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1941 "Invalid similarly-qualified pointer type"); 1942 1943 /// Conversions to 'id' subsume cv-qualifier conversions. 1944 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1945 return ToType.getUnqualifiedType(); 1946 1947 QualType CanonFromPointee 1948 = Context.getCanonicalType(FromPtr->getPointeeType()); 1949 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1950 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1951 1952 if (StripObjCLifetime) 1953 Quals.removeObjCLifetime(); 1954 1955 // Exact qualifier match -> return the pointer type we're converting to. 1956 if (CanonToPointee.getLocalQualifiers() == Quals) { 1957 // ToType is exactly what we need. Return it. 1958 if (!ToType.isNull()) 1959 return ToType.getUnqualifiedType(); 1960 1961 // Build a pointer to ToPointee. It has the right qualifiers 1962 // already. 1963 if (isa<ObjCObjectPointerType>(ToType)) 1964 return Context.getObjCObjectPointerType(ToPointee); 1965 return Context.getPointerType(ToPointee); 1966 } 1967 1968 // Just build a canonical type that has the right qualifiers. 1969 QualType QualifiedCanonToPointee 1970 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1971 1972 if (isa<ObjCObjectPointerType>(ToType)) 1973 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1974 return Context.getPointerType(QualifiedCanonToPointee); 1975 } 1976 1977 static bool isNullPointerConstantForConversion(Expr *Expr, 1978 bool InOverloadResolution, 1979 ASTContext &Context) { 1980 // Handle value-dependent integral null pointer constants correctly. 1981 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1982 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1983 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1984 return !InOverloadResolution; 1985 1986 return Expr->isNullPointerConstant(Context, 1987 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1988 : Expr::NPC_ValueDependentIsNull); 1989 } 1990 1991 /// IsPointerConversion - Determines whether the conversion of the 1992 /// expression From, which has the (possibly adjusted) type FromType, 1993 /// can be converted to the type ToType via a pointer conversion (C++ 1994 /// 4.10). If so, returns true and places the converted type (that 1995 /// might differ from ToType in its cv-qualifiers at some level) into 1996 /// ConvertedType. 1997 /// 1998 /// This routine also supports conversions to and from block pointers 1999 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2000 /// pointers to interfaces. FIXME: Once we've determined the 2001 /// appropriate overloading rules for Objective-C, we may want to 2002 /// split the Objective-C checks into a different routine; however, 2003 /// GCC seems to consider all of these conversions to be pointer 2004 /// conversions, so for now they live here. IncompatibleObjC will be 2005 /// set if the conversion is an allowed Objective-C conversion that 2006 /// should result in a warning. 2007 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2008 bool InOverloadResolution, 2009 QualType& ConvertedType, 2010 bool &IncompatibleObjC) { 2011 IncompatibleObjC = false; 2012 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2013 IncompatibleObjC)) 2014 return true; 2015 2016 // Conversion from a null pointer constant to any Objective-C pointer type. 2017 if (ToType->isObjCObjectPointerType() && 2018 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2019 ConvertedType = ToType; 2020 return true; 2021 } 2022 2023 // Blocks: Block pointers can be converted to void*. 2024 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2025 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2026 ConvertedType = ToType; 2027 return true; 2028 } 2029 // Blocks: A null pointer constant can be converted to a block 2030 // pointer type. 2031 if (ToType->isBlockPointerType() && 2032 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2033 ConvertedType = ToType; 2034 return true; 2035 } 2036 2037 // If the left-hand-side is nullptr_t, the right side can be a null 2038 // pointer constant. 2039 if (ToType->isNullPtrType() && 2040 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2041 ConvertedType = ToType; 2042 return true; 2043 } 2044 2045 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2046 if (!ToTypePtr) 2047 return false; 2048 2049 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2050 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2051 ConvertedType = ToType; 2052 return true; 2053 } 2054 2055 // Beyond this point, both types need to be pointers 2056 // , including objective-c pointers. 2057 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2058 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2059 !getLangOpts().ObjCAutoRefCount) { 2060 ConvertedType = BuildSimilarlyQualifiedPointerType( 2061 FromType->getAs<ObjCObjectPointerType>(), 2062 ToPointeeType, 2063 ToType, Context); 2064 return true; 2065 } 2066 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2067 if (!FromTypePtr) 2068 return false; 2069 2070 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2071 2072 // If the unqualified pointee types are the same, this can't be a 2073 // pointer conversion, so don't do all of the work below. 2074 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2075 return false; 2076 2077 // An rvalue of type "pointer to cv T," where T is an object type, 2078 // can be converted to an rvalue of type "pointer to cv void" (C++ 2079 // 4.10p2). 2080 if (FromPointeeType->isIncompleteOrObjectType() && 2081 ToPointeeType->isVoidType()) { 2082 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2083 ToPointeeType, 2084 ToType, Context, 2085 /*StripObjCLifetime=*/true); 2086 return true; 2087 } 2088 2089 // MSVC allows implicit function to void* type conversion. 2090 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 2091 ToPointeeType->isVoidType()) { 2092 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2093 ToPointeeType, 2094 ToType, Context); 2095 return true; 2096 } 2097 2098 // When we're overloading in C, we allow a special kind of pointer 2099 // conversion for compatible-but-not-identical pointee types. 2100 if (!getLangOpts().CPlusPlus && 2101 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2102 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2103 ToPointeeType, 2104 ToType, Context); 2105 return true; 2106 } 2107 2108 // C++ [conv.ptr]p3: 2109 // 2110 // An rvalue of type "pointer to cv D," where D is a class type, 2111 // can be converted to an rvalue of type "pointer to cv B," where 2112 // B is a base class (clause 10) of D. If B is an inaccessible 2113 // (clause 11) or ambiguous (10.2) base class of D, a program that 2114 // necessitates this conversion is ill-formed. The result of the 2115 // conversion is a pointer to the base class sub-object of the 2116 // derived class object. The null pointer value is converted to 2117 // the null pointer value of the destination type. 2118 // 2119 // Note that we do not check for ambiguity or inaccessibility 2120 // here. That is handled by CheckPointerConversion. 2121 if (getLangOpts().CPlusPlus && 2122 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2123 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2124 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2125 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2126 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2127 ToPointeeType, 2128 ToType, Context); 2129 return true; 2130 } 2131 2132 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2133 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2134 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2135 ToPointeeType, 2136 ToType, Context); 2137 return true; 2138 } 2139 2140 return false; 2141 } 2142 2143 /// \brief Adopt the given qualifiers for the given type. 2144 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2145 Qualifiers TQs = T.getQualifiers(); 2146 2147 // Check whether qualifiers already match. 2148 if (TQs == Qs) 2149 return T; 2150 2151 if (Qs.compatiblyIncludes(TQs)) 2152 return Context.getQualifiedType(T, Qs); 2153 2154 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2155 } 2156 2157 /// isObjCPointerConversion - Determines whether this is an 2158 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2159 /// with the same arguments and return values. 2160 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2161 QualType& ConvertedType, 2162 bool &IncompatibleObjC) { 2163 if (!getLangOpts().ObjC1) 2164 return false; 2165 2166 // The set of qualifiers on the type we're converting from. 2167 Qualifiers FromQualifiers = FromType.getQualifiers(); 2168 2169 // First, we handle all conversions on ObjC object pointer types. 2170 const ObjCObjectPointerType* ToObjCPtr = 2171 ToType->getAs<ObjCObjectPointerType>(); 2172 const ObjCObjectPointerType *FromObjCPtr = 2173 FromType->getAs<ObjCObjectPointerType>(); 2174 2175 if (ToObjCPtr && FromObjCPtr) { 2176 // If the pointee types are the same (ignoring qualifications), 2177 // then this is not a pointer conversion. 2178 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2179 FromObjCPtr->getPointeeType())) 2180 return false; 2181 2182 // Check for compatible 2183 // Objective C++: We're able to convert between "id" or "Class" and a 2184 // pointer to any interface (in both directions). 2185 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2186 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2187 return true; 2188 } 2189 // Conversions with Objective-C's id<...>. 2190 if ((FromObjCPtr->isObjCQualifiedIdType() || 2191 ToObjCPtr->isObjCQualifiedIdType()) && 2192 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2193 /*compare=*/false)) { 2194 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2195 return true; 2196 } 2197 // Objective C++: We're able to convert from a pointer to an 2198 // interface to a pointer to a different interface. 2199 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2200 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2201 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2202 if (getLangOpts().CPlusPlus && LHS && RHS && 2203 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2204 FromObjCPtr->getPointeeType())) 2205 return false; 2206 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2207 ToObjCPtr->getPointeeType(), 2208 ToType, Context); 2209 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2210 return true; 2211 } 2212 2213 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2214 // Okay: this is some kind of implicit downcast of Objective-C 2215 // interfaces, which is permitted. However, we're going to 2216 // complain about it. 2217 IncompatibleObjC = true; 2218 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2219 ToObjCPtr->getPointeeType(), 2220 ToType, Context); 2221 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2222 return true; 2223 } 2224 } 2225 // Beyond this point, both types need to be C pointers or block pointers. 2226 QualType ToPointeeType; 2227 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2228 ToPointeeType = ToCPtr->getPointeeType(); 2229 else if (const BlockPointerType *ToBlockPtr = 2230 ToType->getAs<BlockPointerType>()) { 2231 // Objective C++: We're able to convert from a pointer to any object 2232 // to a block pointer type. 2233 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2234 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2235 return true; 2236 } 2237 ToPointeeType = ToBlockPtr->getPointeeType(); 2238 } 2239 else if (FromType->getAs<BlockPointerType>() && 2240 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2241 // Objective C++: We're able to convert from a block pointer type to a 2242 // pointer to any object. 2243 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2244 return true; 2245 } 2246 else 2247 return false; 2248 2249 QualType FromPointeeType; 2250 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2251 FromPointeeType = FromCPtr->getPointeeType(); 2252 else if (const BlockPointerType *FromBlockPtr = 2253 FromType->getAs<BlockPointerType>()) 2254 FromPointeeType = FromBlockPtr->getPointeeType(); 2255 else 2256 return false; 2257 2258 // If we have pointers to pointers, recursively check whether this 2259 // is an Objective-C conversion. 2260 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2261 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2262 IncompatibleObjC)) { 2263 // We always complain about this conversion. 2264 IncompatibleObjC = true; 2265 ConvertedType = Context.getPointerType(ConvertedType); 2266 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2267 return true; 2268 } 2269 // Allow conversion of pointee being objective-c pointer to another one; 2270 // as in I* to id. 2271 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2272 ToPointeeType->getAs<ObjCObjectPointerType>() && 2273 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2274 IncompatibleObjC)) { 2275 2276 ConvertedType = Context.getPointerType(ConvertedType); 2277 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2278 return true; 2279 } 2280 2281 // If we have pointers to functions or blocks, check whether the only 2282 // differences in the argument and result types are in Objective-C 2283 // pointer conversions. If so, we permit the conversion (but 2284 // complain about it). 2285 const FunctionProtoType *FromFunctionType 2286 = FromPointeeType->getAs<FunctionProtoType>(); 2287 const FunctionProtoType *ToFunctionType 2288 = ToPointeeType->getAs<FunctionProtoType>(); 2289 if (FromFunctionType && ToFunctionType) { 2290 // If the function types are exactly the same, this isn't an 2291 // Objective-C pointer conversion. 2292 if (Context.getCanonicalType(FromPointeeType) 2293 == Context.getCanonicalType(ToPointeeType)) 2294 return false; 2295 2296 // Perform the quick checks that will tell us whether these 2297 // function types are obviously different. 2298 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2299 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2300 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2301 return false; 2302 2303 bool HasObjCConversion = false; 2304 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2305 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2306 // Okay, the types match exactly. Nothing to do. 2307 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2308 ToFunctionType->getReturnType(), 2309 ConvertedType, IncompatibleObjC)) { 2310 // Okay, we have an Objective-C pointer conversion. 2311 HasObjCConversion = true; 2312 } else { 2313 // Function types are too different. Abort. 2314 return false; 2315 } 2316 2317 // Check argument types. 2318 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2319 ArgIdx != NumArgs; ++ArgIdx) { 2320 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2321 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2322 if (Context.getCanonicalType(FromArgType) 2323 == Context.getCanonicalType(ToArgType)) { 2324 // Okay, the types match exactly. Nothing to do. 2325 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2326 ConvertedType, IncompatibleObjC)) { 2327 // Okay, we have an Objective-C pointer conversion. 2328 HasObjCConversion = true; 2329 } else { 2330 // Argument types are too different. Abort. 2331 return false; 2332 } 2333 } 2334 2335 if (HasObjCConversion) { 2336 // We had an Objective-C conversion. Allow this pointer 2337 // conversion, but complain about it. 2338 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2339 IncompatibleObjC = true; 2340 return true; 2341 } 2342 } 2343 2344 return false; 2345 } 2346 2347 /// \brief Determine whether this is an Objective-C writeback conversion, 2348 /// used for parameter passing when performing automatic reference counting. 2349 /// 2350 /// \param FromType The type we're converting form. 2351 /// 2352 /// \param ToType The type we're converting to. 2353 /// 2354 /// \param ConvertedType The type that will be produced after applying 2355 /// this conversion. 2356 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2357 QualType &ConvertedType) { 2358 if (!getLangOpts().ObjCAutoRefCount || 2359 Context.hasSameUnqualifiedType(FromType, ToType)) 2360 return false; 2361 2362 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2363 QualType ToPointee; 2364 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2365 ToPointee = ToPointer->getPointeeType(); 2366 else 2367 return false; 2368 2369 Qualifiers ToQuals = ToPointee.getQualifiers(); 2370 if (!ToPointee->isObjCLifetimeType() || 2371 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2372 !ToQuals.withoutObjCLifetime().empty()) 2373 return false; 2374 2375 // Argument must be a pointer to __strong to __weak. 2376 QualType FromPointee; 2377 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2378 FromPointee = FromPointer->getPointeeType(); 2379 else 2380 return false; 2381 2382 Qualifiers FromQuals = FromPointee.getQualifiers(); 2383 if (!FromPointee->isObjCLifetimeType() || 2384 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2385 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2386 return false; 2387 2388 // Make sure that we have compatible qualifiers. 2389 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2390 if (!ToQuals.compatiblyIncludes(FromQuals)) 2391 return false; 2392 2393 // Remove qualifiers from the pointee type we're converting from; they 2394 // aren't used in the compatibility check belong, and we'll be adding back 2395 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2396 FromPointee = FromPointee.getUnqualifiedType(); 2397 2398 // The unqualified form of the pointee types must be compatible. 2399 ToPointee = ToPointee.getUnqualifiedType(); 2400 bool IncompatibleObjC; 2401 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2402 FromPointee = ToPointee; 2403 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2404 IncompatibleObjC)) 2405 return false; 2406 2407 /// \brief Construct the type we're converting to, which is a pointer to 2408 /// __autoreleasing pointee. 2409 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2410 ConvertedType = Context.getPointerType(FromPointee); 2411 return true; 2412 } 2413 2414 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2415 QualType& ConvertedType) { 2416 QualType ToPointeeType; 2417 if (const BlockPointerType *ToBlockPtr = 2418 ToType->getAs<BlockPointerType>()) 2419 ToPointeeType = ToBlockPtr->getPointeeType(); 2420 else 2421 return false; 2422 2423 QualType FromPointeeType; 2424 if (const BlockPointerType *FromBlockPtr = 2425 FromType->getAs<BlockPointerType>()) 2426 FromPointeeType = FromBlockPtr->getPointeeType(); 2427 else 2428 return false; 2429 // We have pointer to blocks, check whether the only 2430 // differences in the argument and result types are in Objective-C 2431 // pointer conversions. If so, we permit the conversion. 2432 2433 const FunctionProtoType *FromFunctionType 2434 = FromPointeeType->getAs<FunctionProtoType>(); 2435 const FunctionProtoType *ToFunctionType 2436 = ToPointeeType->getAs<FunctionProtoType>(); 2437 2438 if (!FromFunctionType || !ToFunctionType) 2439 return false; 2440 2441 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2442 return true; 2443 2444 // Perform the quick checks that will tell us whether these 2445 // function types are obviously different. 2446 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2447 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2448 return false; 2449 2450 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2451 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2452 if (FromEInfo != ToEInfo) 2453 return false; 2454 2455 bool IncompatibleObjC = false; 2456 if (Context.hasSameType(FromFunctionType->getReturnType(), 2457 ToFunctionType->getReturnType())) { 2458 // Okay, the types match exactly. Nothing to do. 2459 } else { 2460 QualType RHS = FromFunctionType->getReturnType(); 2461 QualType LHS = ToFunctionType->getReturnType(); 2462 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2463 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2464 LHS = LHS.getUnqualifiedType(); 2465 2466 if (Context.hasSameType(RHS,LHS)) { 2467 // OK exact match. 2468 } else if (isObjCPointerConversion(RHS, LHS, 2469 ConvertedType, IncompatibleObjC)) { 2470 if (IncompatibleObjC) 2471 return false; 2472 // Okay, we have an Objective-C pointer conversion. 2473 } 2474 else 2475 return false; 2476 } 2477 2478 // Check argument types. 2479 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2480 ArgIdx != NumArgs; ++ArgIdx) { 2481 IncompatibleObjC = false; 2482 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2483 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2484 if (Context.hasSameType(FromArgType, ToArgType)) { 2485 // Okay, the types match exactly. Nothing to do. 2486 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2487 ConvertedType, IncompatibleObjC)) { 2488 if (IncompatibleObjC) 2489 return false; 2490 // Okay, we have an Objective-C pointer conversion. 2491 } else 2492 // Argument types are too different. Abort. 2493 return false; 2494 } 2495 if (LangOpts.ObjCAutoRefCount && 2496 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2497 ToFunctionType)) 2498 return false; 2499 2500 ConvertedType = ToType; 2501 return true; 2502 } 2503 2504 enum { 2505 ft_default, 2506 ft_different_class, 2507 ft_parameter_arity, 2508 ft_parameter_mismatch, 2509 ft_return_type, 2510 ft_qualifer_mismatch 2511 }; 2512 2513 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2514 /// function types. Catches different number of parameter, mismatch in 2515 /// parameter types, and different return types. 2516 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2517 QualType FromType, QualType ToType) { 2518 // If either type is not valid, include no extra info. 2519 if (FromType.isNull() || ToType.isNull()) { 2520 PDiag << ft_default; 2521 return; 2522 } 2523 2524 // Get the function type from the pointers. 2525 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2526 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2527 *ToMember = ToType->getAs<MemberPointerType>(); 2528 if (FromMember->getClass() != ToMember->getClass()) { 2529 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2530 << QualType(FromMember->getClass(), 0); 2531 return; 2532 } 2533 FromType = FromMember->getPointeeType(); 2534 ToType = ToMember->getPointeeType(); 2535 } 2536 2537 if (FromType->isPointerType()) 2538 FromType = FromType->getPointeeType(); 2539 if (ToType->isPointerType()) 2540 ToType = ToType->getPointeeType(); 2541 2542 // Remove references. 2543 FromType = FromType.getNonReferenceType(); 2544 ToType = ToType.getNonReferenceType(); 2545 2546 // Don't print extra info for non-specialized template functions. 2547 if (FromType->isInstantiationDependentType() && 2548 !FromType->getAs<TemplateSpecializationType>()) { 2549 PDiag << ft_default; 2550 return; 2551 } 2552 2553 // No extra info for same types. 2554 if (Context.hasSameType(FromType, ToType)) { 2555 PDiag << ft_default; 2556 return; 2557 } 2558 2559 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2560 *ToFunction = ToType->getAs<FunctionProtoType>(); 2561 2562 // Both types need to be function types. 2563 if (!FromFunction || !ToFunction) { 2564 PDiag << ft_default; 2565 return; 2566 } 2567 2568 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2569 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2570 << FromFunction->getNumParams(); 2571 return; 2572 } 2573 2574 // Handle different parameter types. 2575 unsigned ArgPos; 2576 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2577 PDiag << ft_parameter_mismatch << ArgPos + 1 2578 << ToFunction->getParamType(ArgPos) 2579 << FromFunction->getParamType(ArgPos); 2580 return; 2581 } 2582 2583 // Handle different return type. 2584 if (!Context.hasSameType(FromFunction->getReturnType(), 2585 ToFunction->getReturnType())) { 2586 PDiag << ft_return_type << ToFunction->getReturnType() 2587 << FromFunction->getReturnType(); 2588 return; 2589 } 2590 2591 unsigned FromQuals = FromFunction->getTypeQuals(), 2592 ToQuals = ToFunction->getTypeQuals(); 2593 if (FromQuals != ToQuals) { 2594 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2595 return; 2596 } 2597 2598 // Unable to find a difference, so add no extra info. 2599 PDiag << ft_default; 2600 } 2601 2602 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2603 /// for equality of their argument types. Caller has already checked that 2604 /// they have same number of arguments. If the parameters are different, 2605 /// ArgPos will have the parameter index of the first different parameter. 2606 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2607 const FunctionProtoType *NewType, 2608 unsigned *ArgPos) { 2609 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2610 N = NewType->param_type_begin(), 2611 E = OldType->param_type_end(); 2612 O && (O != E); ++O, ++N) { 2613 if (!Context.hasSameType(O->getUnqualifiedType(), 2614 N->getUnqualifiedType())) { 2615 if (ArgPos) 2616 *ArgPos = O - OldType->param_type_begin(); 2617 return false; 2618 } 2619 } 2620 return true; 2621 } 2622 2623 /// CheckPointerConversion - Check the pointer conversion from the 2624 /// expression From to the type ToType. This routine checks for 2625 /// ambiguous or inaccessible derived-to-base pointer 2626 /// conversions for which IsPointerConversion has already returned 2627 /// true. It returns true and produces a diagnostic if there was an 2628 /// error, or returns false otherwise. 2629 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2630 CastKind &Kind, 2631 CXXCastPath& BasePath, 2632 bool IgnoreBaseAccess) { 2633 QualType FromType = From->getType(); 2634 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2635 2636 Kind = CK_BitCast; 2637 2638 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2639 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2640 Expr::NPCK_ZeroExpression) { 2641 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2642 DiagRuntimeBehavior(From->getExprLoc(), From, 2643 PDiag(diag::warn_impcast_bool_to_null_pointer) 2644 << ToType << From->getSourceRange()); 2645 else if (!isUnevaluatedContext()) 2646 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2647 << ToType << From->getSourceRange(); 2648 } 2649 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2650 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2651 QualType FromPointeeType = FromPtrType->getPointeeType(), 2652 ToPointeeType = ToPtrType->getPointeeType(); 2653 2654 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2655 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2656 // We must have a derived-to-base conversion. Check an 2657 // ambiguous or inaccessible conversion. 2658 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2659 From->getExprLoc(), 2660 From->getSourceRange(), &BasePath, 2661 IgnoreBaseAccess)) 2662 return true; 2663 2664 // The conversion was successful. 2665 Kind = CK_DerivedToBase; 2666 } 2667 } 2668 } else if (const ObjCObjectPointerType *ToPtrType = 2669 ToType->getAs<ObjCObjectPointerType>()) { 2670 if (const ObjCObjectPointerType *FromPtrType = 2671 FromType->getAs<ObjCObjectPointerType>()) { 2672 // Objective-C++ conversions are always okay. 2673 // FIXME: We should have a different class of conversions for the 2674 // Objective-C++ implicit conversions. 2675 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2676 return false; 2677 } else if (FromType->isBlockPointerType()) { 2678 Kind = CK_BlockPointerToObjCPointerCast; 2679 } else { 2680 Kind = CK_CPointerToObjCPointerCast; 2681 } 2682 } else if (ToType->isBlockPointerType()) { 2683 if (!FromType->isBlockPointerType()) 2684 Kind = CK_AnyPointerToBlockPointerCast; 2685 } 2686 2687 // We shouldn't fall into this case unless it's valid for other 2688 // reasons. 2689 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2690 Kind = CK_NullToPointer; 2691 2692 return false; 2693 } 2694 2695 /// IsMemberPointerConversion - Determines whether the conversion of the 2696 /// expression From, which has the (possibly adjusted) type FromType, can be 2697 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2698 /// If so, returns true and places the converted type (that might differ from 2699 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2700 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2701 QualType ToType, 2702 bool InOverloadResolution, 2703 QualType &ConvertedType) { 2704 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2705 if (!ToTypePtr) 2706 return false; 2707 2708 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2709 if (From->isNullPointerConstant(Context, 2710 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2711 : Expr::NPC_ValueDependentIsNull)) { 2712 ConvertedType = ToType; 2713 return true; 2714 } 2715 2716 // Otherwise, both types have to be member pointers. 2717 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2718 if (!FromTypePtr) 2719 return false; 2720 2721 // A pointer to member of B can be converted to a pointer to member of D, 2722 // where D is derived from B (C++ 4.11p2). 2723 QualType FromClass(FromTypePtr->getClass(), 0); 2724 QualType ToClass(ToTypePtr->getClass(), 0); 2725 2726 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2727 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2728 IsDerivedFrom(ToClass, FromClass)) { 2729 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2730 ToClass.getTypePtr()); 2731 return true; 2732 } 2733 2734 return false; 2735 } 2736 2737 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2738 /// expression From to the type ToType. This routine checks for ambiguous or 2739 /// virtual or inaccessible base-to-derived member pointer conversions 2740 /// for which IsMemberPointerConversion has already returned true. It returns 2741 /// true and produces a diagnostic if there was an error, or returns false 2742 /// otherwise. 2743 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2744 CastKind &Kind, 2745 CXXCastPath &BasePath, 2746 bool IgnoreBaseAccess) { 2747 QualType FromType = From->getType(); 2748 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2749 if (!FromPtrType) { 2750 // This must be a null pointer to member pointer conversion 2751 assert(From->isNullPointerConstant(Context, 2752 Expr::NPC_ValueDependentIsNull) && 2753 "Expr must be null pointer constant!"); 2754 Kind = CK_NullToMemberPointer; 2755 return false; 2756 } 2757 2758 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2759 assert(ToPtrType && "No member pointer cast has a target type " 2760 "that is not a member pointer."); 2761 2762 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2763 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2764 2765 // FIXME: What about dependent types? 2766 assert(FromClass->isRecordType() && "Pointer into non-class."); 2767 assert(ToClass->isRecordType() && "Pointer into non-class."); 2768 2769 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2770 /*DetectVirtual=*/true); 2771 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2772 assert(DerivationOkay && 2773 "Should not have been called if derivation isn't OK."); 2774 (void)DerivationOkay; 2775 2776 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2777 getUnqualifiedType())) { 2778 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2779 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2780 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2781 return true; 2782 } 2783 2784 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2785 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2786 << FromClass << ToClass << QualType(VBase, 0) 2787 << From->getSourceRange(); 2788 return true; 2789 } 2790 2791 if (!IgnoreBaseAccess) 2792 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2793 Paths.front(), 2794 diag::err_downcast_from_inaccessible_base); 2795 2796 // Must be a base to derived member conversion. 2797 BuildBasePathArray(Paths, BasePath); 2798 Kind = CK_BaseToDerivedMemberPointer; 2799 return false; 2800 } 2801 2802 /// Determine whether the lifetime conversion between the two given 2803 /// qualifiers sets is nontrivial. 2804 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 2805 Qualifiers ToQuals) { 2806 // Converting anything to const __unsafe_unretained is trivial. 2807 if (ToQuals.hasConst() && 2808 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 2809 return false; 2810 2811 return true; 2812 } 2813 2814 /// IsQualificationConversion - Determines whether the conversion from 2815 /// an rvalue of type FromType to ToType is a qualification conversion 2816 /// (C++ 4.4). 2817 /// 2818 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2819 /// when the qualification conversion involves a change in the Objective-C 2820 /// object lifetime. 2821 bool 2822 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2823 bool CStyle, bool &ObjCLifetimeConversion) { 2824 FromType = Context.getCanonicalType(FromType); 2825 ToType = Context.getCanonicalType(ToType); 2826 ObjCLifetimeConversion = false; 2827 2828 // If FromType and ToType are the same type, this is not a 2829 // qualification conversion. 2830 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2831 return false; 2832 2833 // (C++ 4.4p4): 2834 // A conversion can add cv-qualifiers at levels other than the first 2835 // in multi-level pointers, subject to the following rules: [...] 2836 bool PreviousToQualsIncludeConst = true; 2837 bool UnwrappedAnyPointer = false; 2838 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2839 // Within each iteration of the loop, we check the qualifiers to 2840 // determine if this still looks like a qualification 2841 // conversion. Then, if all is well, we unwrap one more level of 2842 // pointers or pointers-to-members and do it all again 2843 // until there are no more pointers or pointers-to-members left to 2844 // unwrap. 2845 UnwrappedAnyPointer = true; 2846 2847 Qualifiers FromQuals = FromType.getQualifiers(); 2848 Qualifiers ToQuals = ToType.getQualifiers(); 2849 2850 // Objective-C ARC: 2851 // Check Objective-C lifetime conversions. 2852 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2853 UnwrappedAnyPointer) { 2854 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2855 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 2856 ObjCLifetimeConversion = true; 2857 FromQuals.removeObjCLifetime(); 2858 ToQuals.removeObjCLifetime(); 2859 } else { 2860 // Qualification conversions cannot cast between different 2861 // Objective-C lifetime qualifiers. 2862 return false; 2863 } 2864 } 2865 2866 // Allow addition/removal of GC attributes but not changing GC attributes. 2867 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2868 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2869 FromQuals.removeObjCGCAttr(); 2870 ToQuals.removeObjCGCAttr(); 2871 } 2872 2873 // -- for every j > 0, if const is in cv 1,j then const is in cv 2874 // 2,j, and similarly for volatile. 2875 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2876 return false; 2877 2878 // -- if the cv 1,j and cv 2,j are different, then const is in 2879 // every cv for 0 < k < j. 2880 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2881 && !PreviousToQualsIncludeConst) 2882 return false; 2883 2884 // Keep track of whether all prior cv-qualifiers in the "to" type 2885 // include const. 2886 PreviousToQualsIncludeConst 2887 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2888 } 2889 2890 // We are left with FromType and ToType being the pointee types 2891 // after unwrapping the original FromType and ToType the same number 2892 // of types. If we unwrapped any pointers, and if FromType and 2893 // ToType have the same unqualified type (since we checked 2894 // qualifiers above), then this is a qualification conversion. 2895 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2896 } 2897 2898 /// \brief - Determine whether this is a conversion from a scalar type to an 2899 /// atomic type. 2900 /// 2901 /// If successful, updates \c SCS's second and third steps in the conversion 2902 /// sequence to finish the conversion. 2903 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2904 bool InOverloadResolution, 2905 StandardConversionSequence &SCS, 2906 bool CStyle) { 2907 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2908 if (!ToAtomic) 2909 return false; 2910 2911 StandardConversionSequence InnerSCS; 2912 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2913 InOverloadResolution, InnerSCS, 2914 CStyle, /*AllowObjCWritebackConversion=*/false)) 2915 return false; 2916 2917 SCS.Second = InnerSCS.Second; 2918 SCS.setToType(1, InnerSCS.getToType(1)); 2919 SCS.Third = InnerSCS.Third; 2920 SCS.QualificationIncludesObjCLifetime 2921 = InnerSCS.QualificationIncludesObjCLifetime; 2922 SCS.setToType(2, InnerSCS.getToType(2)); 2923 return true; 2924 } 2925 2926 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2927 CXXConstructorDecl *Constructor, 2928 QualType Type) { 2929 const FunctionProtoType *CtorType = 2930 Constructor->getType()->getAs<FunctionProtoType>(); 2931 if (CtorType->getNumParams() > 0) { 2932 QualType FirstArg = CtorType->getParamType(0); 2933 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2934 return true; 2935 } 2936 return false; 2937 } 2938 2939 static OverloadingResult 2940 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2941 CXXRecordDecl *To, 2942 UserDefinedConversionSequence &User, 2943 OverloadCandidateSet &CandidateSet, 2944 bool AllowExplicit) { 2945 DeclContext::lookup_result R = S.LookupConstructors(To); 2946 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 2947 Con != ConEnd; ++Con) { 2948 NamedDecl *D = *Con; 2949 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2950 2951 // Find the constructor (which may be a template). 2952 CXXConstructorDecl *Constructor = 0; 2953 FunctionTemplateDecl *ConstructorTmpl 2954 = dyn_cast<FunctionTemplateDecl>(D); 2955 if (ConstructorTmpl) 2956 Constructor 2957 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2958 else 2959 Constructor = cast<CXXConstructorDecl>(D); 2960 2961 bool Usable = !Constructor->isInvalidDecl() && 2962 S.isInitListConstructor(Constructor) && 2963 (AllowExplicit || !Constructor->isExplicit()); 2964 if (Usable) { 2965 // If the first argument is (a reference to) the target type, 2966 // suppress conversions. 2967 bool SuppressUserConversions = 2968 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2969 if (ConstructorTmpl) 2970 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2971 /*ExplicitArgs*/ 0, 2972 From, CandidateSet, 2973 SuppressUserConversions); 2974 else 2975 S.AddOverloadCandidate(Constructor, FoundDecl, 2976 From, CandidateSet, 2977 SuppressUserConversions); 2978 } 2979 } 2980 2981 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2982 2983 OverloadCandidateSet::iterator Best; 2984 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2985 case OR_Success: { 2986 // Record the standard conversion we used and the conversion function. 2987 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2988 QualType ThisType = Constructor->getThisType(S.Context); 2989 // Initializer lists don't have conversions as such. 2990 User.Before.setAsIdentityConversion(); 2991 User.HadMultipleCandidates = HadMultipleCandidates; 2992 User.ConversionFunction = Constructor; 2993 User.FoundConversionFunction = Best->FoundDecl; 2994 User.After.setAsIdentityConversion(); 2995 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2996 User.After.setAllToTypes(ToType); 2997 return OR_Success; 2998 } 2999 3000 case OR_No_Viable_Function: 3001 return OR_No_Viable_Function; 3002 case OR_Deleted: 3003 return OR_Deleted; 3004 case OR_Ambiguous: 3005 return OR_Ambiguous; 3006 } 3007 3008 llvm_unreachable("Invalid OverloadResult!"); 3009 } 3010 3011 /// Determines whether there is a user-defined conversion sequence 3012 /// (C++ [over.ics.user]) that converts expression From to the type 3013 /// ToType. If such a conversion exists, User will contain the 3014 /// user-defined conversion sequence that performs such a conversion 3015 /// and this routine will return true. Otherwise, this routine returns 3016 /// false and User is unspecified. 3017 /// 3018 /// \param AllowExplicit true if the conversion should consider C++0x 3019 /// "explicit" conversion functions as well as non-explicit conversion 3020 /// functions (C++0x [class.conv.fct]p2). 3021 /// 3022 /// \param AllowObjCConversionOnExplicit true if the conversion should 3023 /// allow an extra Objective-C pointer conversion on uses of explicit 3024 /// constructors. Requires \c AllowExplicit to also be set. 3025 static OverloadingResult 3026 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3027 UserDefinedConversionSequence &User, 3028 OverloadCandidateSet &CandidateSet, 3029 bool AllowExplicit, 3030 bool AllowObjCConversionOnExplicit) { 3031 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3032 3033 // Whether we will only visit constructors. 3034 bool ConstructorsOnly = false; 3035 3036 // If the type we are conversion to is a class type, enumerate its 3037 // constructors. 3038 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3039 // C++ [over.match.ctor]p1: 3040 // When objects of class type are direct-initialized (8.5), or 3041 // copy-initialized from an expression of the same or a 3042 // derived class type (8.5), overload resolution selects the 3043 // constructor. [...] For copy-initialization, the candidate 3044 // functions are all the converting constructors (12.3.1) of 3045 // that class. The argument list is the expression-list within 3046 // the parentheses of the initializer. 3047 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3048 (From->getType()->getAs<RecordType>() && 3049 S.IsDerivedFrom(From->getType(), ToType))) 3050 ConstructorsOnly = true; 3051 3052 S.RequireCompleteType(From->getExprLoc(), ToType, 0); 3053 // RequireCompleteType may have returned true due to some invalid decl 3054 // during template instantiation, but ToType may be complete enough now 3055 // to try to recover. 3056 if (ToType->isIncompleteType()) { 3057 // We're not going to find any constructors. 3058 } else if (CXXRecordDecl *ToRecordDecl 3059 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3060 3061 Expr **Args = &From; 3062 unsigned NumArgs = 1; 3063 bool ListInitializing = false; 3064 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3065 // But first, see if there is an init-list-constructor that will work. 3066 OverloadingResult Result = IsInitializerListConstructorConversion( 3067 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3068 if (Result != OR_No_Viable_Function) 3069 return Result; 3070 // Never mind. 3071 CandidateSet.clear(); 3072 3073 // If we're list-initializing, we pass the individual elements as 3074 // arguments, not the entire list. 3075 Args = InitList->getInits(); 3076 NumArgs = InitList->getNumInits(); 3077 ListInitializing = true; 3078 } 3079 3080 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3081 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3082 Con != ConEnd; ++Con) { 3083 NamedDecl *D = *Con; 3084 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3085 3086 // Find the constructor (which may be a template). 3087 CXXConstructorDecl *Constructor = 0; 3088 FunctionTemplateDecl *ConstructorTmpl 3089 = dyn_cast<FunctionTemplateDecl>(D); 3090 if (ConstructorTmpl) 3091 Constructor 3092 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3093 else 3094 Constructor = cast<CXXConstructorDecl>(D); 3095 3096 bool Usable = !Constructor->isInvalidDecl(); 3097 if (ListInitializing) 3098 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3099 else 3100 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3101 if (Usable) { 3102 bool SuppressUserConversions = !ConstructorsOnly; 3103 if (SuppressUserConversions && ListInitializing) { 3104 SuppressUserConversions = false; 3105 if (NumArgs == 1) { 3106 // If the first argument is (a reference to) the target type, 3107 // suppress conversions. 3108 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3109 S.Context, Constructor, ToType); 3110 } 3111 } 3112 if (ConstructorTmpl) 3113 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3114 /*ExplicitArgs*/ 0, 3115 llvm::makeArrayRef(Args, NumArgs), 3116 CandidateSet, SuppressUserConversions); 3117 else 3118 // Allow one user-defined conversion when user specifies a 3119 // From->ToType conversion via an static cast (c-style, etc). 3120 S.AddOverloadCandidate(Constructor, FoundDecl, 3121 llvm::makeArrayRef(Args, NumArgs), 3122 CandidateSet, SuppressUserConversions); 3123 } 3124 } 3125 } 3126 } 3127 3128 // Enumerate conversion functions, if we're allowed to. 3129 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3130 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3131 // No conversion functions from incomplete types. 3132 } else if (const RecordType *FromRecordType 3133 = From->getType()->getAs<RecordType>()) { 3134 if (CXXRecordDecl *FromRecordDecl 3135 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3136 // Add all of the conversion functions as candidates. 3137 std::pair<CXXRecordDecl::conversion_iterator, 3138 CXXRecordDecl::conversion_iterator> 3139 Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3140 for (CXXRecordDecl::conversion_iterator 3141 I = Conversions.first, E = Conversions.second; I != E; ++I) { 3142 DeclAccessPair FoundDecl = I.getPair(); 3143 NamedDecl *D = FoundDecl.getDecl(); 3144 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3145 if (isa<UsingShadowDecl>(D)) 3146 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3147 3148 CXXConversionDecl *Conv; 3149 FunctionTemplateDecl *ConvTemplate; 3150 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3151 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3152 else 3153 Conv = cast<CXXConversionDecl>(D); 3154 3155 if (AllowExplicit || !Conv->isExplicit()) { 3156 if (ConvTemplate) 3157 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3158 ActingContext, From, ToType, 3159 CandidateSet, 3160 AllowObjCConversionOnExplicit); 3161 else 3162 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3163 From, ToType, CandidateSet, 3164 AllowObjCConversionOnExplicit); 3165 } 3166 } 3167 } 3168 } 3169 3170 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3171 3172 OverloadCandidateSet::iterator Best; 3173 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3174 case OR_Success: 3175 // Record the standard conversion we used and the conversion function. 3176 if (CXXConstructorDecl *Constructor 3177 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3178 // C++ [over.ics.user]p1: 3179 // If the user-defined conversion is specified by a 3180 // constructor (12.3.1), the initial standard conversion 3181 // sequence converts the source type to the type required by 3182 // the argument of the constructor. 3183 // 3184 QualType ThisType = Constructor->getThisType(S.Context); 3185 if (isa<InitListExpr>(From)) { 3186 // Initializer lists don't have conversions as such. 3187 User.Before.setAsIdentityConversion(); 3188 } else { 3189 if (Best->Conversions[0].isEllipsis()) 3190 User.EllipsisConversion = true; 3191 else { 3192 User.Before = Best->Conversions[0].Standard; 3193 User.EllipsisConversion = false; 3194 } 3195 } 3196 User.HadMultipleCandidates = HadMultipleCandidates; 3197 User.ConversionFunction = Constructor; 3198 User.FoundConversionFunction = Best->FoundDecl; 3199 User.After.setAsIdentityConversion(); 3200 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3201 User.After.setAllToTypes(ToType); 3202 return OR_Success; 3203 } 3204 if (CXXConversionDecl *Conversion 3205 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3206 // C++ [over.ics.user]p1: 3207 // 3208 // [...] If the user-defined conversion is specified by a 3209 // conversion function (12.3.2), the initial standard 3210 // conversion sequence converts the source type to the 3211 // implicit object parameter of the conversion function. 3212 User.Before = Best->Conversions[0].Standard; 3213 User.HadMultipleCandidates = HadMultipleCandidates; 3214 User.ConversionFunction = Conversion; 3215 User.FoundConversionFunction = Best->FoundDecl; 3216 User.EllipsisConversion = false; 3217 3218 // C++ [over.ics.user]p2: 3219 // The second standard conversion sequence converts the 3220 // result of the user-defined conversion to the target type 3221 // for the sequence. Since an implicit conversion sequence 3222 // is an initialization, the special rules for 3223 // initialization by user-defined conversion apply when 3224 // selecting the best user-defined conversion for a 3225 // user-defined conversion sequence (see 13.3.3 and 3226 // 13.3.3.1). 3227 User.After = Best->FinalConversion; 3228 return OR_Success; 3229 } 3230 llvm_unreachable("Not a constructor or conversion function?"); 3231 3232 case OR_No_Viable_Function: 3233 return OR_No_Viable_Function; 3234 case OR_Deleted: 3235 // No conversion here! We're done. 3236 return OR_Deleted; 3237 3238 case OR_Ambiguous: 3239 return OR_Ambiguous; 3240 } 3241 3242 llvm_unreachable("Invalid OverloadResult!"); 3243 } 3244 3245 bool 3246 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3247 ImplicitConversionSequence ICS; 3248 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3249 OverloadCandidateSet::CSK_Normal); 3250 OverloadingResult OvResult = 3251 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3252 CandidateSet, false, false); 3253 if (OvResult == OR_Ambiguous) 3254 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3255 << From->getType() << ToType << From->getSourceRange(); 3256 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3257 if (!RequireCompleteType(From->getLocStart(), ToType, 3258 diag::err_typecheck_nonviable_condition_incomplete, 3259 From->getType(), From->getSourceRange())) 3260 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3261 << From->getType() << From->getSourceRange() << ToType; 3262 } else 3263 return false; 3264 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3265 return true; 3266 } 3267 3268 /// \brief Compare the user-defined conversion functions or constructors 3269 /// of two user-defined conversion sequences to determine whether any ordering 3270 /// is possible. 3271 static ImplicitConversionSequence::CompareKind 3272 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3273 FunctionDecl *Function2) { 3274 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3275 return ImplicitConversionSequence::Indistinguishable; 3276 3277 // Objective-C++: 3278 // If both conversion functions are implicitly-declared conversions from 3279 // a lambda closure type to a function pointer and a block pointer, 3280 // respectively, always prefer the conversion to a function pointer, 3281 // because the function pointer is more lightweight and is more likely 3282 // to keep code working. 3283 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3284 if (!Conv1) 3285 return ImplicitConversionSequence::Indistinguishable; 3286 3287 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3288 if (!Conv2) 3289 return ImplicitConversionSequence::Indistinguishable; 3290 3291 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3292 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3293 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3294 if (Block1 != Block2) 3295 return Block1 ? ImplicitConversionSequence::Worse 3296 : ImplicitConversionSequence::Better; 3297 } 3298 3299 return ImplicitConversionSequence::Indistinguishable; 3300 } 3301 3302 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3303 const ImplicitConversionSequence &ICS) { 3304 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3305 (ICS.isUserDefined() && 3306 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3307 } 3308 3309 /// CompareImplicitConversionSequences - Compare two implicit 3310 /// conversion sequences to determine whether one is better than the 3311 /// other or if they are indistinguishable (C++ 13.3.3.2). 3312 static ImplicitConversionSequence::CompareKind 3313 CompareImplicitConversionSequences(Sema &S, 3314 const ImplicitConversionSequence& ICS1, 3315 const ImplicitConversionSequence& ICS2) 3316 { 3317 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3318 // conversion sequences (as defined in 13.3.3.1) 3319 // -- a standard conversion sequence (13.3.3.1.1) is a better 3320 // conversion sequence than a user-defined conversion sequence or 3321 // an ellipsis conversion sequence, and 3322 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3323 // conversion sequence than an ellipsis conversion sequence 3324 // (13.3.3.1.3). 3325 // 3326 // C++0x [over.best.ics]p10: 3327 // For the purpose of ranking implicit conversion sequences as 3328 // described in 13.3.3.2, the ambiguous conversion sequence is 3329 // treated as a user-defined sequence that is indistinguishable 3330 // from any other user-defined conversion sequence. 3331 3332 // String literal to 'char *' conversion has been deprecated in C++03. It has 3333 // been removed from C++11. We still accept this conversion, if it happens at 3334 // the best viable function. Otherwise, this conversion is considered worse 3335 // than ellipsis conversion. Consider this as an extension; this is not in the 3336 // standard. For example: 3337 // 3338 // int &f(...); // #1 3339 // void f(char*); // #2 3340 // void g() { int &r = f("foo"); } 3341 // 3342 // In C++03, we pick #2 as the best viable function. 3343 // In C++11, we pick #1 as the best viable function, because ellipsis 3344 // conversion is better than string-literal to char* conversion (since there 3345 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3346 // convert arguments, #2 would be the best viable function in C++11. 3347 // If the best viable function has this conversion, a warning will be issued 3348 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3349 3350 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3351 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3352 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3353 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3354 ? ImplicitConversionSequence::Worse 3355 : ImplicitConversionSequence::Better; 3356 3357 if (ICS1.getKindRank() < ICS2.getKindRank()) 3358 return ImplicitConversionSequence::Better; 3359 if (ICS2.getKindRank() < ICS1.getKindRank()) 3360 return ImplicitConversionSequence::Worse; 3361 3362 // The following checks require both conversion sequences to be of 3363 // the same kind. 3364 if (ICS1.getKind() != ICS2.getKind()) 3365 return ImplicitConversionSequence::Indistinguishable; 3366 3367 ImplicitConversionSequence::CompareKind Result = 3368 ImplicitConversionSequence::Indistinguishable; 3369 3370 // Two implicit conversion sequences of the same form are 3371 // indistinguishable conversion sequences unless one of the 3372 // following rules apply: (C++ 13.3.3.2p3): 3373 if (ICS1.isStandard()) 3374 Result = CompareStandardConversionSequences(S, 3375 ICS1.Standard, ICS2.Standard); 3376 else if (ICS1.isUserDefined()) { 3377 // User-defined conversion sequence U1 is a better conversion 3378 // sequence than another user-defined conversion sequence U2 if 3379 // they contain the same user-defined conversion function or 3380 // constructor and if the second standard conversion sequence of 3381 // U1 is better than the second standard conversion sequence of 3382 // U2 (C++ 13.3.3.2p3). 3383 if (ICS1.UserDefined.ConversionFunction == 3384 ICS2.UserDefined.ConversionFunction) 3385 Result = CompareStandardConversionSequences(S, 3386 ICS1.UserDefined.After, 3387 ICS2.UserDefined.After); 3388 else 3389 Result = compareConversionFunctions(S, 3390 ICS1.UserDefined.ConversionFunction, 3391 ICS2.UserDefined.ConversionFunction); 3392 } 3393 3394 // List-initialization sequence L1 is a better conversion sequence than 3395 // list-initialization sequence L2 if L1 converts to std::initializer_list<X> 3396 // for some X and L2 does not. 3397 if (Result == ImplicitConversionSequence::Indistinguishable && 3398 !ICS1.isBad()) { 3399 if (ICS1.isStdInitializerListElement() && 3400 !ICS2.isStdInitializerListElement()) 3401 return ImplicitConversionSequence::Better; 3402 if (!ICS1.isStdInitializerListElement() && 3403 ICS2.isStdInitializerListElement()) 3404 return ImplicitConversionSequence::Worse; 3405 } 3406 3407 return Result; 3408 } 3409 3410 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3411 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3412 Qualifiers Quals; 3413 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3414 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3415 } 3416 3417 return Context.hasSameUnqualifiedType(T1, T2); 3418 } 3419 3420 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3421 // determine if one is a proper subset of the other. 3422 static ImplicitConversionSequence::CompareKind 3423 compareStandardConversionSubsets(ASTContext &Context, 3424 const StandardConversionSequence& SCS1, 3425 const StandardConversionSequence& SCS2) { 3426 ImplicitConversionSequence::CompareKind Result 3427 = ImplicitConversionSequence::Indistinguishable; 3428 3429 // the identity conversion sequence is considered to be a subsequence of 3430 // any non-identity conversion sequence 3431 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3432 return ImplicitConversionSequence::Better; 3433 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3434 return ImplicitConversionSequence::Worse; 3435 3436 if (SCS1.Second != SCS2.Second) { 3437 if (SCS1.Second == ICK_Identity) 3438 Result = ImplicitConversionSequence::Better; 3439 else if (SCS2.Second == ICK_Identity) 3440 Result = ImplicitConversionSequence::Worse; 3441 else 3442 return ImplicitConversionSequence::Indistinguishable; 3443 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3444 return ImplicitConversionSequence::Indistinguishable; 3445 3446 if (SCS1.Third == SCS2.Third) { 3447 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3448 : ImplicitConversionSequence::Indistinguishable; 3449 } 3450 3451 if (SCS1.Third == ICK_Identity) 3452 return Result == ImplicitConversionSequence::Worse 3453 ? ImplicitConversionSequence::Indistinguishable 3454 : ImplicitConversionSequence::Better; 3455 3456 if (SCS2.Third == ICK_Identity) 3457 return Result == ImplicitConversionSequence::Better 3458 ? ImplicitConversionSequence::Indistinguishable 3459 : ImplicitConversionSequence::Worse; 3460 3461 return ImplicitConversionSequence::Indistinguishable; 3462 } 3463 3464 /// \brief Determine whether one of the given reference bindings is better 3465 /// than the other based on what kind of bindings they are. 3466 static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3467 const StandardConversionSequence &SCS2) { 3468 // C++0x [over.ics.rank]p3b4: 3469 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3470 // implicit object parameter of a non-static member function declared 3471 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3472 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3473 // lvalue reference to a function lvalue and S2 binds an rvalue 3474 // reference*. 3475 // 3476 // FIXME: Rvalue references. We're going rogue with the above edits, 3477 // because the semantics in the current C++0x working paper (N3225 at the 3478 // time of this writing) break the standard definition of std::forward 3479 // and std::reference_wrapper when dealing with references to functions. 3480 // Proposed wording changes submitted to CWG for consideration. 3481 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3482 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3483 return false; 3484 3485 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3486 SCS2.IsLvalueReference) || 3487 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3488 !SCS2.IsLvalueReference); 3489 } 3490 3491 /// CompareStandardConversionSequences - Compare two standard 3492 /// conversion sequences to determine whether one is better than the 3493 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3494 static ImplicitConversionSequence::CompareKind 3495 CompareStandardConversionSequences(Sema &S, 3496 const StandardConversionSequence& SCS1, 3497 const StandardConversionSequence& SCS2) 3498 { 3499 // Standard conversion sequence S1 is a better conversion sequence 3500 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3501 3502 // -- S1 is a proper subsequence of S2 (comparing the conversion 3503 // sequences in the canonical form defined by 13.3.3.1.1, 3504 // excluding any Lvalue Transformation; the identity conversion 3505 // sequence is considered to be a subsequence of any 3506 // non-identity conversion sequence) or, if not that, 3507 if (ImplicitConversionSequence::CompareKind CK 3508 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3509 return CK; 3510 3511 // -- the rank of S1 is better than the rank of S2 (by the rules 3512 // defined below), or, if not that, 3513 ImplicitConversionRank Rank1 = SCS1.getRank(); 3514 ImplicitConversionRank Rank2 = SCS2.getRank(); 3515 if (Rank1 < Rank2) 3516 return ImplicitConversionSequence::Better; 3517 else if (Rank2 < Rank1) 3518 return ImplicitConversionSequence::Worse; 3519 3520 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3521 // are indistinguishable unless one of the following rules 3522 // applies: 3523 3524 // A conversion that is not a conversion of a pointer, or 3525 // pointer to member, to bool is better than another conversion 3526 // that is such a conversion. 3527 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3528 return SCS2.isPointerConversionToBool() 3529 ? ImplicitConversionSequence::Better 3530 : ImplicitConversionSequence::Worse; 3531 3532 // C++ [over.ics.rank]p4b2: 3533 // 3534 // If class B is derived directly or indirectly from class A, 3535 // conversion of B* to A* is better than conversion of B* to 3536 // void*, and conversion of A* to void* is better than conversion 3537 // of B* to void*. 3538 bool SCS1ConvertsToVoid 3539 = SCS1.isPointerConversionToVoidPointer(S.Context); 3540 bool SCS2ConvertsToVoid 3541 = SCS2.isPointerConversionToVoidPointer(S.Context); 3542 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3543 // Exactly one of the conversion sequences is a conversion to 3544 // a void pointer; it's the worse conversion. 3545 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3546 : ImplicitConversionSequence::Worse; 3547 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3548 // Neither conversion sequence converts to a void pointer; compare 3549 // their derived-to-base conversions. 3550 if (ImplicitConversionSequence::CompareKind DerivedCK 3551 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3552 return DerivedCK; 3553 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3554 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3555 // Both conversion sequences are conversions to void 3556 // pointers. Compare the source types to determine if there's an 3557 // inheritance relationship in their sources. 3558 QualType FromType1 = SCS1.getFromType(); 3559 QualType FromType2 = SCS2.getFromType(); 3560 3561 // Adjust the types we're converting from via the array-to-pointer 3562 // conversion, if we need to. 3563 if (SCS1.First == ICK_Array_To_Pointer) 3564 FromType1 = S.Context.getArrayDecayedType(FromType1); 3565 if (SCS2.First == ICK_Array_To_Pointer) 3566 FromType2 = S.Context.getArrayDecayedType(FromType2); 3567 3568 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3569 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3570 3571 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3572 return ImplicitConversionSequence::Better; 3573 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3574 return ImplicitConversionSequence::Worse; 3575 3576 // Objective-C++: If one interface is more specific than the 3577 // other, it is the better one. 3578 const ObjCObjectPointerType* FromObjCPtr1 3579 = FromType1->getAs<ObjCObjectPointerType>(); 3580 const ObjCObjectPointerType* FromObjCPtr2 3581 = FromType2->getAs<ObjCObjectPointerType>(); 3582 if (FromObjCPtr1 && FromObjCPtr2) { 3583 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3584 FromObjCPtr2); 3585 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3586 FromObjCPtr1); 3587 if (AssignLeft != AssignRight) { 3588 return AssignLeft? ImplicitConversionSequence::Better 3589 : ImplicitConversionSequence::Worse; 3590 } 3591 } 3592 } 3593 3594 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3595 // bullet 3). 3596 if (ImplicitConversionSequence::CompareKind QualCK 3597 = CompareQualificationConversions(S, SCS1, SCS2)) 3598 return QualCK; 3599 3600 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3601 // Check for a better reference binding based on the kind of bindings. 3602 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3603 return ImplicitConversionSequence::Better; 3604 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3605 return ImplicitConversionSequence::Worse; 3606 3607 // C++ [over.ics.rank]p3b4: 3608 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3609 // which the references refer are the same type except for 3610 // top-level cv-qualifiers, and the type to which the reference 3611 // initialized by S2 refers is more cv-qualified than the type 3612 // to which the reference initialized by S1 refers. 3613 QualType T1 = SCS1.getToType(2); 3614 QualType T2 = SCS2.getToType(2); 3615 T1 = S.Context.getCanonicalType(T1); 3616 T2 = S.Context.getCanonicalType(T2); 3617 Qualifiers T1Quals, T2Quals; 3618 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3619 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3620 if (UnqualT1 == UnqualT2) { 3621 // Objective-C++ ARC: If the references refer to objects with different 3622 // lifetimes, prefer bindings that don't change lifetime. 3623 if (SCS1.ObjCLifetimeConversionBinding != 3624 SCS2.ObjCLifetimeConversionBinding) { 3625 return SCS1.ObjCLifetimeConversionBinding 3626 ? ImplicitConversionSequence::Worse 3627 : ImplicitConversionSequence::Better; 3628 } 3629 3630 // If the type is an array type, promote the element qualifiers to the 3631 // type for comparison. 3632 if (isa<ArrayType>(T1) && T1Quals) 3633 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3634 if (isa<ArrayType>(T2) && T2Quals) 3635 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3636 if (T2.isMoreQualifiedThan(T1)) 3637 return ImplicitConversionSequence::Better; 3638 else if (T1.isMoreQualifiedThan(T2)) 3639 return ImplicitConversionSequence::Worse; 3640 } 3641 } 3642 3643 // In Microsoft mode, prefer an integral conversion to a 3644 // floating-to-integral conversion if the integral conversion 3645 // is between types of the same size. 3646 // For example: 3647 // void f(float); 3648 // void f(int); 3649 // int main { 3650 // long a; 3651 // f(a); 3652 // } 3653 // Here, MSVC will call f(int) instead of generating a compile error 3654 // as clang will do in standard mode. 3655 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3656 SCS2.Second == ICK_Floating_Integral && 3657 S.Context.getTypeSize(SCS1.getFromType()) == 3658 S.Context.getTypeSize(SCS1.getToType(2))) 3659 return ImplicitConversionSequence::Better; 3660 3661 return ImplicitConversionSequence::Indistinguishable; 3662 } 3663 3664 /// CompareQualificationConversions - Compares two standard conversion 3665 /// sequences to determine whether they can be ranked based on their 3666 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3667 ImplicitConversionSequence::CompareKind 3668 CompareQualificationConversions(Sema &S, 3669 const StandardConversionSequence& SCS1, 3670 const StandardConversionSequence& SCS2) { 3671 // C++ 13.3.3.2p3: 3672 // -- S1 and S2 differ only in their qualification conversion and 3673 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3674 // cv-qualification signature of type T1 is a proper subset of 3675 // the cv-qualification signature of type T2, and S1 is not the 3676 // deprecated string literal array-to-pointer conversion (4.2). 3677 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3678 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3679 return ImplicitConversionSequence::Indistinguishable; 3680 3681 // FIXME: the example in the standard doesn't use a qualification 3682 // conversion (!) 3683 QualType T1 = SCS1.getToType(2); 3684 QualType T2 = SCS2.getToType(2); 3685 T1 = S.Context.getCanonicalType(T1); 3686 T2 = S.Context.getCanonicalType(T2); 3687 Qualifiers T1Quals, T2Quals; 3688 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3689 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3690 3691 // If the types are the same, we won't learn anything by unwrapped 3692 // them. 3693 if (UnqualT1 == UnqualT2) 3694 return ImplicitConversionSequence::Indistinguishable; 3695 3696 // If the type is an array type, promote the element qualifiers to the type 3697 // for comparison. 3698 if (isa<ArrayType>(T1) && T1Quals) 3699 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3700 if (isa<ArrayType>(T2) && T2Quals) 3701 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3702 3703 ImplicitConversionSequence::CompareKind Result 3704 = ImplicitConversionSequence::Indistinguishable; 3705 3706 // Objective-C++ ARC: 3707 // Prefer qualification conversions not involving a change in lifetime 3708 // to qualification conversions that do not change lifetime. 3709 if (SCS1.QualificationIncludesObjCLifetime != 3710 SCS2.QualificationIncludesObjCLifetime) { 3711 Result = SCS1.QualificationIncludesObjCLifetime 3712 ? ImplicitConversionSequence::Worse 3713 : ImplicitConversionSequence::Better; 3714 } 3715 3716 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3717 // Within each iteration of the loop, we check the qualifiers to 3718 // determine if this still looks like a qualification 3719 // conversion. Then, if all is well, we unwrap one more level of 3720 // pointers or pointers-to-members and do it all again 3721 // until there are no more pointers or pointers-to-members left 3722 // to unwrap. This essentially mimics what 3723 // IsQualificationConversion does, but here we're checking for a 3724 // strict subset of qualifiers. 3725 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3726 // The qualifiers are the same, so this doesn't tell us anything 3727 // about how the sequences rank. 3728 ; 3729 else if (T2.isMoreQualifiedThan(T1)) { 3730 // T1 has fewer qualifiers, so it could be the better sequence. 3731 if (Result == ImplicitConversionSequence::Worse) 3732 // Neither has qualifiers that are a subset of the other's 3733 // qualifiers. 3734 return ImplicitConversionSequence::Indistinguishable; 3735 3736 Result = ImplicitConversionSequence::Better; 3737 } else if (T1.isMoreQualifiedThan(T2)) { 3738 // T2 has fewer qualifiers, so it could be the better sequence. 3739 if (Result == ImplicitConversionSequence::Better) 3740 // Neither has qualifiers that are a subset of the other's 3741 // qualifiers. 3742 return ImplicitConversionSequence::Indistinguishable; 3743 3744 Result = ImplicitConversionSequence::Worse; 3745 } else { 3746 // Qualifiers are disjoint. 3747 return ImplicitConversionSequence::Indistinguishable; 3748 } 3749 3750 // If the types after this point are equivalent, we're done. 3751 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3752 break; 3753 } 3754 3755 // Check that the winning standard conversion sequence isn't using 3756 // the deprecated string literal array to pointer conversion. 3757 switch (Result) { 3758 case ImplicitConversionSequence::Better: 3759 if (SCS1.DeprecatedStringLiteralToCharPtr) 3760 Result = ImplicitConversionSequence::Indistinguishable; 3761 break; 3762 3763 case ImplicitConversionSequence::Indistinguishable: 3764 break; 3765 3766 case ImplicitConversionSequence::Worse: 3767 if (SCS2.DeprecatedStringLiteralToCharPtr) 3768 Result = ImplicitConversionSequence::Indistinguishable; 3769 break; 3770 } 3771 3772 return Result; 3773 } 3774 3775 /// CompareDerivedToBaseConversions - Compares two standard conversion 3776 /// sequences to determine whether they can be ranked based on their 3777 /// various kinds of derived-to-base conversions (C++ 3778 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3779 /// conversions between Objective-C interface types. 3780 ImplicitConversionSequence::CompareKind 3781 CompareDerivedToBaseConversions(Sema &S, 3782 const StandardConversionSequence& SCS1, 3783 const StandardConversionSequence& SCS2) { 3784 QualType FromType1 = SCS1.getFromType(); 3785 QualType ToType1 = SCS1.getToType(1); 3786 QualType FromType2 = SCS2.getFromType(); 3787 QualType ToType2 = SCS2.getToType(1); 3788 3789 // Adjust the types we're converting from via the array-to-pointer 3790 // conversion, if we need to. 3791 if (SCS1.First == ICK_Array_To_Pointer) 3792 FromType1 = S.Context.getArrayDecayedType(FromType1); 3793 if (SCS2.First == ICK_Array_To_Pointer) 3794 FromType2 = S.Context.getArrayDecayedType(FromType2); 3795 3796 // Canonicalize all of the types. 3797 FromType1 = S.Context.getCanonicalType(FromType1); 3798 ToType1 = S.Context.getCanonicalType(ToType1); 3799 FromType2 = S.Context.getCanonicalType(FromType2); 3800 ToType2 = S.Context.getCanonicalType(ToType2); 3801 3802 // C++ [over.ics.rank]p4b3: 3803 // 3804 // If class B is derived directly or indirectly from class A and 3805 // class C is derived directly or indirectly from B, 3806 // 3807 // Compare based on pointer conversions. 3808 if (SCS1.Second == ICK_Pointer_Conversion && 3809 SCS2.Second == ICK_Pointer_Conversion && 3810 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3811 FromType1->isPointerType() && FromType2->isPointerType() && 3812 ToType1->isPointerType() && ToType2->isPointerType()) { 3813 QualType FromPointee1 3814 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3815 QualType ToPointee1 3816 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3817 QualType FromPointee2 3818 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3819 QualType ToPointee2 3820 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3821 3822 // -- conversion of C* to B* is better than conversion of C* to A*, 3823 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3824 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3825 return ImplicitConversionSequence::Better; 3826 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3827 return ImplicitConversionSequence::Worse; 3828 } 3829 3830 // -- conversion of B* to A* is better than conversion of C* to A*, 3831 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3832 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3833 return ImplicitConversionSequence::Better; 3834 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3835 return ImplicitConversionSequence::Worse; 3836 } 3837 } else if (SCS1.Second == ICK_Pointer_Conversion && 3838 SCS2.Second == ICK_Pointer_Conversion) { 3839 const ObjCObjectPointerType *FromPtr1 3840 = FromType1->getAs<ObjCObjectPointerType>(); 3841 const ObjCObjectPointerType *FromPtr2 3842 = FromType2->getAs<ObjCObjectPointerType>(); 3843 const ObjCObjectPointerType *ToPtr1 3844 = ToType1->getAs<ObjCObjectPointerType>(); 3845 const ObjCObjectPointerType *ToPtr2 3846 = ToType2->getAs<ObjCObjectPointerType>(); 3847 3848 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3849 // Apply the same conversion ranking rules for Objective-C pointer types 3850 // that we do for C++ pointers to class types. However, we employ the 3851 // Objective-C pseudo-subtyping relationship used for assignment of 3852 // Objective-C pointer types. 3853 bool FromAssignLeft 3854 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3855 bool FromAssignRight 3856 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3857 bool ToAssignLeft 3858 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3859 bool ToAssignRight 3860 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3861 3862 // A conversion to an a non-id object pointer type or qualified 'id' 3863 // type is better than a conversion to 'id'. 3864 if (ToPtr1->isObjCIdType() && 3865 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3866 return ImplicitConversionSequence::Worse; 3867 if (ToPtr2->isObjCIdType() && 3868 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3869 return ImplicitConversionSequence::Better; 3870 3871 // A conversion to a non-id object pointer type is better than a 3872 // conversion to a qualified 'id' type 3873 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3874 return ImplicitConversionSequence::Worse; 3875 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3876 return ImplicitConversionSequence::Better; 3877 3878 // A conversion to an a non-Class object pointer type or qualified 'Class' 3879 // type is better than a conversion to 'Class'. 3880 if (ToPtr1->isObjCClassType() && 3881 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3882 return ImplicitConversionSequence::Worse; 3883 if (ToPtr2->isObjCClassType() && 3884 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3885 return ImplicitConversionSequence::Better; 3886 3887 // A conversion to a non-Class object pointer type is better than a 3888 // conversion to a qualified 'Class' type. 3889 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3890 return ImplicitConversionSequence::Worse; 3891 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3892 return ImplicitConversionSequence::Better; 3893 3894 // -- "conversion of C* to B* is better than conversion of C* to A*," 3895 if (S.Context.hasSameType(FromType1, FromType2) && 3896 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3897 (ToAssignLeft != ToAssignRight)) 3898 return ToAssignLeft? ImplicitConversionSequence::Worse 3899 : ImplicitConversionSequence::Better; 3900 3901 // -- "conversion of B* to A* is better than conversion of C* to A*," 3902 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3903 (FromAssignLeft != FromAssignRight)) 3904 return FromAssignLeft? ImplicitConversionSequence::Better 3905 : ImplicitConversionSequence::Worse; 3906 } 3907 } 3908 3909 // Ranking of member-pointer types. 3910 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3911 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3912 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3913 const MemberPointerType * FromMemPointer1 = 3914 FromType1->getAs<MemberPointerType>(); 3915 const MemberPointerType * ToMemPointer1 = 3916 ToType1->getAs<MemberPointerType>(); 3917 const MemberPointerType * FromMemPointer2 = 3918 FromType2->getAs<MemberPointerType>(); 3919 const MemberPointerType * ToMemPointer2 = 3920 ToType2->getAs<MemberPointerType>(); 3921 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3922 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3923 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3924 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3925 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3926 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3927 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3928 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3929 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3930 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3931 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3932 return ImplicitConversionSequence::Worse; 3933 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3934 return ImplicitConversionSequence::Better; 3935 } 3936 // conversion of B::* to C::* is better than conversion of A::* to C::* 3937 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3938 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3939 return ImplicitConversionSequence::Better; 3940 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3941 return ImplicitConversionSequence::Worse; 3942 } 3943 } 3944 3945 if (SCS1.Second == ICK_Derived_To_Base) { 3946 // -- conversion of C to B is better than conversion of C to A, 3947 // -- binding of an expression of type C to a reference of type 3948 // B& is better than binding an expression of type C to a 3949 // reference of type A&, 3950 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3951 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3952 if (S.IsDerivedFrom(ToType1, ToType2)) 3953 return ImplicitConversionSequence::Better; 3954 else if (S.IsDerivedFrom(ToType2, ToType1)) 3955 return ImplicitConversionSequence::Worse; 3956 } 3957 3958 // -- conversion of B to A is better than conversion of C to A. 3959 // -- binding of an expression of type B to a reference of type 3960 // A& is better than binding an expression of type C to a 3961 // reference of type A&, 3962 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3963 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3964 if (S.IsDerivedFrom(FromType2, FromType1)) 3965 return ImplicitConversionSequence::Better; 3966 else if (S.IsDerivedFrom(FromType1, FromType2)) 3967 return ImplicitConversionSequence::Worse; 3968 } 3969 } 3970 3971 return ImplicitConversionSequence::Indistinguishable; 3972 } 3973 3974 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 3975 /// C++ class. 3976 static bool isTypeValid(QualType T) { 3977 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 3978 return !Record->isInvalidDecl(); 3979 3980 return true; 3981 } 3982 3983 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 3984 /// determine whether they are reference-related, 3985 /// reference-compatible, reference-compatible with added 3986 /// qualification, or incompatible, for use in C++ initialization by 3987 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3988 /// type, and the first type (T1) is the pointee type of the reference 3989 /// type being initialized. 3990 Sema::ReferenceCompareResult 3991 Sema::CompareReferenceRelationship(SourceLocation Loc, 3992 QualType OrigT1, QualType OrigT2, 3993 bool &DerivedToBase, 3994 bool &ObjCConversion, 3995 bool &ObjCLifetimeConversion) { 3996 assert(!OrigT1->isReferenceType() && 3997 "T1 must be the pointee type of the reference type"); 3998 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3999 4000 QualType T1 = Context.getCanonicalType(OrigT1); 4001 QualType T2 = Context.getCanonicalType(OrigT2); 4002 Qualifiers T1Quals, T2Quals; 4003 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4004 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4005 4006 // C++ [dcl.init.ref]p4: 4007 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4008 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4009 // T1 is a base class of T2. 4010 DerivedToBase = false; 4011 ObjCConversion = false; 4012 ObjCLifetimeConversion = false; 4013 if (UnqualT1 == UnqualT2) { 4014 // Nothing to do. 4015 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 4016 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4017 IsDerivedFrom(UnqualT2, UnqualT1)) 4018 DerivedToBase = true; 4019 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4020 UnqualT2->isObjCObjectOrInterfaceType() && 4021 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4022 ObjCConversion = true; 4023 else 4024 return Ref_Incompatible; 4025 4026 // At this point, we know that T1 and T2 are reference-related (at 4027 // least). 4028 4029 // If the type is an array type, promote the element qualifiers to the type 4030 // for comparison. 4031 if (isa<ArrayType>(T1) && T1Quals) 4032 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4033 if (isa<ArrayType>(T2) && T2Quals) 4034 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4035 4036 // C++ [dcl.init.ref]p4: 4037 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4038 // reference-related to T2 and cv1 is the same cv-qualification 4039 // as, or greater cv-qualification than, cv2. For purposes of 4040 // overload resolution, cases for which cv1 is greater 4041 // cv-qualification than cv2 are identified as 4042 // reference-compatible with added qualification (see 13.3.3.2). 4043 // 4044 // Note that we also require equivalence of Objective-C GC and address-space 4045 // qualifiers when performing these computations, so that e.g., an int in 4046 // address space 1 is not reference-compatible with an int in address 4047 // space 2. 4048 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4049 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4050 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4051 ObjCLifetimeConversion = true; 4052 4053 T1Quals.removeObjCLifetime(); 4054 T2Quals.removeObjCLifetime(); 4055 } 4056 4057 if (T1Quals == T2Quals) 4058 return Ref_Compatible; 4059 else if (T1Quals.compatiblyIncludes(T2Quals)) 4060 return Ref_Compatible_With_Added_Qualification; 4061 else 4062 return Ref_Related; 4063 } 4064 4065 /// \brief Look for a user-defined conversion to an value reference-compatible 4066 /// with DeclType. Return true if something definite is found. 4067 static bool 4068 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4069 QualType DeclType, SourceLocation DeclLoc, 4070 Expr *Init, QualType T2, bool AllowRvalues, 4071 bool AllowExplicit) { 4072 assert(T2->isRecordType() && "Can only find conversions of record types."); 4073 CXXRecordDecl *T2RecordDecl 4074 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4075 4076 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4077 std::pair<CXXRecordDecl::conversion_iterator, 4078 CXXRecordDecl::conversion_iterator> 4079 Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4080 for (CXXRecordDecl::conversion_iterator 4081 I = Conversions.first, E = Conversions.second; I != E; ++I) { 4082 NamedDecl *D = *I; 4083 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4084 if (isa<UsingShadowDecl>(D)) 4085 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4086 4087 FunctionTemplateDecl *ConvTemplate 4088 = dyn_cast<FunctionTemplateDecl>(D); 4089 CXXConversionDecl *Conv; 4090 if (ConvTemplate) 4091 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4092 else 4093 Conv = cast<CXXConversionDecl>(D); 4094 4095 // If this is an explicit conversion, and we're not allowed to consider 4096 // explicit conversions, skip it. 4097 if (!AllowExplicit && Conv->isExplicit()) 4098 continue; 4099 4100 if (AllowRvalues) { 4101 bool DerivedToBase = false; 4102 bool ObjCConversion = false; 4103 bool ObjCLifetimeConversion = false; 4104 4105 // If we are initializing an rvalue reference, don't permit conversion 4106 // functions that return lvalues. 4107 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4108 const ReferenceType *RefType 4109 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4110 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4111 continue; 4112 } 4113 4114 if (!ConvTemplate && 4115 S.CompareReferenceRelationship( 4116 DeclLoc, 4117 Conv->getConversionType().getNonReferenceType() 4118 .getUnqualifiedType(), 4119 DeclType.getNonReferenceType().getUnqualifiedType(), 4120 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4121 Sema::Ref_Incompatible) 4122 continue; 4123 } else { 4124 // If the conversion function doesn't return a reference type, 4125 // it can't be considered for this conversion. An rvalue reference 4126 // is only acceptable if its referencee is a function type. 4127 4128 const ReferenceType *RefType = 4129 Conv->getConversionType()->getAs<ReferenceType>(); 4130 if (!RefType || 4131 (!RefType->isLValueReferenceType() && 4132 !RefType->getPointeeType()->isFunctionType())) 4133 continue; 4134 } 4135 4136 if (ConvTemplate) 4137 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4138 Init, DeclType, CandidateSet, 4139 /*AllowObjCConversionOnExplicit=*/false); 4140 else 4141 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4142 DeclType, CandidateSet, 4143 /*AllowObjCConversionOnExplicit=*/false); 4144 } 4145 4146 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4147 4148 OverloadCandidateSet::iterator Best; 4149 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4150 case OR_Success: 4151 // C++ [over.ics.ref]p1: 4152 // 4153 // [...] If the parameter binds directly to the result of 4154 // applying a conversion function to the argument 4155 // expression, the implicit conversion sequence is a 4156 // user-defined conversion sequence (13.3.3.1.2), with the 4157 // second standard conversion sequence either an identity 4158 // conversion or, if the conversion function returns an 4159 // entity of a type that is a derived class of the parameter 4160 // type, a derived-to-base Conversion. 4161 if (!Best->FinalConversion.DirectBinding) 4162 return false; 4163 4164 ICS.setUserDefined(); 4165 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4166 ICS.UserDefined.After = Best->FinalConversion; 4167 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4168 ICS.UserDefined.ConversionFunction = Best->Function; 4169 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4170 ICS.UserDefined.EllipsisConversion = false; 4171 assert(ICS.UserDefined.After.ReferenceBinding && 4172 ICS.UserDefined.After.DirectBinding && 4173 "Expected a direct reference binding!"); 4174 return true; 4175 4176 case OR_Ambiguous: 4177 ICS.setAmbiguous(); 4178 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4179 Cand != CandidateSet.end(); ++Cand) 4180 if (Cand->Viable) 4181 ICS.Ambiguous.addConversion(Cand->Function); 4182 return true; 4183 4184 case OR_No_Viable_Function: 4185 case OR_Deleted: 4186 // There was no suitable conversion, or we found a deleted 4187 // conversion; continue with other checks. 4188 return false; 4189 } 4190 4191 llvm_unreachable("Invalid OverloadResult!"); 4192 } 4193 4194 /// \brief Compute an implicit conversion sequence for reference 4195 /// initialization. 4196 static ImplicitConversionSequence 4197 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4198 SourceLocation DeclLoc, 4199 bool SuppressUserConversions, 4200 bool AllowExplicit) { 4201 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4202 4203 // Most paths end in a failed conversion. 4204 ImplicitConversionSequence ICS; 4205 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4206 4207 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4208 QualType T2 = Init->getType(); 4209 4210 // If the initializer is the address of an overloaded function, try 4211 // to resolve the overloaded function. If all goes well, T2 is the 4212 // type of the resulting function. 4213 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4214 DeclAccessPair Found; 4215 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4216 false, Found)) 4217 T2 = Fn->getType(); 4218 } 4219 4220 // Compute some basic properties of the types and the initializer. 4221 bool isRValRef = DeclType->isRValueReferenceType(); 4222 bool DerivedToBase = false; 4223 bool ObjCConversion = false; 4224 bool ObjCLifetimeConversion = false; 4225 Expr::Classification InitCategory = Init->Classify(S.Context); 4226 Sema::ReferenceCompareResult RefRelationship 4227 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4228 ObjCConversion, ObjCLifetimeConversion); 4229 4230 4231 // C++0x [dcl.init.ref]p5: 4232 // A reference to type "cv1 T1" is initialized by an expression 4233 // of type "cv2 T2" as follows: 4234 4235 // -- If reference is an lvalue reference and the initializer expression 4236 if (!isRValRef) { 4237 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4238 // reference-compatible with "cv2 T2," or 4239 // 4240 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4241 if (InitCategory.isLValue() && 4242 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4243 // C++ [over.ics.ref]p1: 4244 // When a parameter of reference type binds directly (8.5.3) 4245 // to an argument expression, the implicit conversion sequence 4246 // is the identity conversion, unless the argument expression 4247 // has a type that is a derived class of the parameter type, 4248 // in which case the implicit conversion sequence is a 4249 // derived-to-base Conversion (13.3.3.1). 4250 ICS.setStandard(); 4251 ICS.Standard.First = ICK_Identity; 4252 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4253 : ObjCConversion? ICK_Compatible_Conversion 4254 : ICK_Identity; 4255 ICS.Standard.Third = ICK_Identity; 4256 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4257 ICS.Standard.setToType(0, T2); 4258 ICS.Standard.setToType(1, T1); 4259 ICS.Standard.setToType(2, T1); 4260 ICS.Standard.ReferenceBinding = true; 4261 ICS.Standard.DirectBinding = true; 4262 ICS.Standard.IsLvalueReference = !isRValRef; 4263 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4264 ICS.Standard.BindsToRvalue = false; 4265 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4266 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4267 ICS.Standard.CopyConstructor = 0; 4268 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4269 4270 // Nothing more to do: the inaccessibility/ambiguity check for 4271 // derived-to-base conversions is suppressed when we're 4272 // computing the implicit conversion sequence (C++ 4273 // [over.best.ics]p2). 4274 return ICS; 4275 } 4276 4277 // -- has a class type (i.e., T2 is a class type), where T1 is 4278 // not reference-related to T2, and can be implicitly 4279 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4280 // is reference-compatible with "cv3 T3" 92) (this 4281 // conversion is selected by enumerating the applicable 4282 // conversion functions (13.3.1.6) and choosing the best 4283 // one through overload resolution (13.3)), 4284 if (!SuppressUserConversions && T2->isRecordType() && 4285 !S.RequireCompleteType(DeclLoc, T2, 0) && 4286 RefRelationship == Sema::Ref_Incompatible) { 4287 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4288 Init, T2, /*AllowRvalues=*/false, 4289 AllowExplicit)) 4290 return ICS; 4291 } 4292 } 4293 4294 // -- Otherwise, the reference shall be an lvalue reference to a 4295 // non-volatile const type (i.e., cv1 shall be const), or the reference 4296 // shall be an rvalue reference. 4297 // 4298 // We actually handle one oddity of C++ [over.ics.ref] at this 4299 // point, which is that, due to p2 (which short-circuits reference 4300 // binding by only attempting a simple conversion for non-direct 4301 // bindings) and p3's strange wording, we allow a const volatile 4302 // reference to bind to an rvalue. Hence the check for the presence 4303 // of "const" rather than checking for "const" being the only 4304 // qualifier. 4305 // This is also the point where rvalue references and lvalue inits no longer 4306 // go together. 4307 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4308 return ICS; 4309 4310 // -- If the initializer expression 4311 // 4312 // -- is an xvalue, class prvalue, array prvalue or function 4313 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4314 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4315 (InitCategory.isXValue() || 4316 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4317 (InitCategory.isLValue() && T2->isFunctionType()))) { 4318 ICS.setStandard(); 4319 ICS.Standard.First = ICK_Identity; 4320 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4321 : ObjCConversion? ICK_Compatible_Conversion 4322 : ICK_Identity; 4323 ICS.Standard.Third = ICK_Identity; 4324 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4325 ICS.Standard.setToType(0, T2); 4326 ICS.Standard.setToType(1, T1); 4327 ICS.Standard.setToType(2, T1); 4328 ICS.Standard.ReferenceBinding = true; 4329 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4330 // binding unless we're binding to a class prvalue. 4331 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4332 // allow the use of rvalue references in C++98/03 for the benefit of 4333 // standard library implementors; therefore, we need the xvalue check here. 4334 ICS.Standard.DirectBinding = 4335 S.getLangOpts().CPlusPlus11 || 4336 (InitCategory.isPRValue() && !T2->isRecordType()); 4337 ICS.Standard.IsLvalueReference = !isRValRef; 4338 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4339 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4340 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4341 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4342 ICS.Standard.CopyConstructor = 0; 4343 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4344 return ICS; 4345 } 4346 4347 // -- has a class type (i.e., T2 is a class type), where T1 is not 4348 // reference-related to T2, and can be implicitly converted to 4349 // an xvalue, class prvalue, or function lvalue of type 4350 // "cv3 T3", where "cv1 T1" is reference-compatible with 4351 // "cv3 T3", 4352 // 4353 // then the reference is bound to the value of the initializer 4354 // expression in the first case and to the result of the conversion 4355 // in the second case (or, in either case, to an appropriate base 4356 // class subobject). 4357 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4358 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4359 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4360 Init, T2, /*AllowRvalues=*/true, 4361 AllowExplicit)) { 4362 // In the second case, if the reference is an rvalue reference 4363 // and the second standard conversion sequence of the 4364 // user-defined conversion sequence includes an lvalue-to-rvalue 4365 // conversion, the program is ill-formed. 4366 if (ICS.isUserDefined() && isRValRef && 4367 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4368 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4369 4370 return ICS; 4371 } 4372 4373 // -- Otherwise, a temporary of type "cv1 T1" is created and 4374 // initialized from the initializer expression using the 4375 // rules for a non-reference copy initialization (8.5). The 4376 // reference is then bound to the temporary. If T1 is 4377 // reference-related to T2, cv1 must be the same 4378 // cv-qualification as, or greater cv-qualification than, 4379 // cv2; otherwise, the program is ill-formed. 4380 if (RefRelationship == Sema::Ref_Related) { 4381 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4382 // we would be reference-compatible or reference-compatible with 4383 // added qualification. But that wasn't the case, so the reference 4384 // initialization fails. 4385 // 4386 // Note that we only want to check address spaces and cvr-qualifiers here. 4387 // ObjC GC and lifetime qualifiers aren't important. 4388 Qualifiers T1Quals = T1.getQualifiers(); 4389 Qualifiers T2Quals = T2.getQualifiers(); 4390 T1Quals.removeObjCGCAttr(); 4391 T1Quals.removeObjCLifetime(); 4392 T2Quals.removeObjCGCAttr(); 4393 T2Quals.removeObjCLifetime(); 4394 if (!T1Quals.compatiblyIncludes(T2Quals)) 4395 return ICS; 4396 } 4397 4398 // If at least one of the types is a class type, the types are not 4399 // related, and we aren't allowed any user conversions, the 4400 // reference binding fails. This case is important for breaking 4401 // recursion, since TryImplicitConversion below will attempt to 4402 // create a temporary through the use of a copy constructor. 4403 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4404 (T1->isRecordType() || T2->isRecordType())) 4405 return ICS; 4406 4407 // If T1 is reference-related to T2 and the reference is an rvalue 4408 // reference, the initializer expression shall not be an lvalue. 4409 if (RefRelationship >= Sema::Ref_Related && 4410 isRValRef && Init->Classify(S.Context).isLValue()) 4411 return ICS; 4412 4413 // C++ [over.ics.ref]p2: 4414 // When a parameter of reference type is not bound directly to 4415 // an argument expression, the conversion sequence is the one 4416 // required to convert the argument expression to the 4417 // underlying type of the reference according to 4418 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4419 // to copy-initializing a temporary of the underlying type with 4420 // the argument expression. Any difference in top-level 4421 // cv-qualification is subsumed by the initialization itself 4422 // and does not constitute a conversion. 4423 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4424 /*AllowExplicit=*/false, 4425 /*InOverloadResolution=*/false, 4426 /*CStyle=*/false, 4427 /*AllowObjCWritebackConversion=*/false, 4428 /*AllowObjCConversionOnExplicit=*/false); 4429 4430 // Of course, that's still a reference binding. 4431 if (ICS.isStandard()) { 4432 ICS.Standard.ReferenceBinding = true; 4433 ICS.Standard.IsLvalueReference = !isRValRef; 4434 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4435 ICS.Standard.BindsToRvalue = true; 4436 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4437 ICS.Standard.ObjCLifetimeConversionBinding = false; 4438 } else if (ICS.isUserDefined()) { 4439 // Don't allow rvalue references to bind to lvalues. 4440 if (DeclType->isRValueReferenceType()) { 4441 if (const ReferenceType *RefType = 4442 ICS.UserDefined.ConversionFunction->getReturnType() 4443 ->getAs<LValueReferenceType>()) { 4444 if (!RefType->getPointeeType()->isFunctionType()) { 4445 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, 4446 DeclType); 4447 return ICS; 4448 } 4449 } 4450 } 4451 ICS.UserDefined.Before.setAsIdentityConversion(); 4452 ICS.UserDefined.After.ReferenceBinding = true; 4453 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4454 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType(); 4455 ICS.UserDefined.After.BindsToRvalue = true; 4456 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4457 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4458 } 4459 4460 return ICS; 4461 } 4462 4463 static ImplicitConversionSequence 4464 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4465 bool SuppressUserConversions, 4466 bool InOverloadResolution, 4467 bool AllowObjCWritebackConversion, 4468 bool AllowExplicit = false); 4469 4470 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4471 /// initializer list From. 4472 static ImplicitConversionSequence 4473 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4474 bool SuppressUserConversions, 4475 bool InOverloadResolution, 4476 bool AllowObjCWritebackConversion) { 4477 // C++11 [over.ics.list]p1: 4478 // When an argument is an initializer list, it is not an expression and 4479 // special rules apply for converting it to a parameter type. 4480 4481 ImplicitConversionSequence Result; 4482 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4483 4484 // We need a complete type for what follows. Incomplete types can never be 4485 // initialized from init lists. 4486 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4487 return Result; 4488 4489 // C++11 [over.ics.list]p2: 4490 // If the parameter type is std::initializer_list<X> or "array of X" and 4491 // all the elements can be implicitly converted to X, the implicit 4492 // conversion sequence is the worst conversion necessary to convert an 4493 // element of the list to X. 4494 bool toStdInitializerList = false; 4495 QualType X; 4496 if (ToType->isArrayType()) 4497 X = S.Context.getAsArrayType(ToType)->getElementType(); 4498 else 4499 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4500 if (!X.isNull()) { 4501 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4502 Expr *Init = From->getInit(i); 4503 ImplicitConversionSequence ICS = 4504 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4505 InOverloadResolution, 4506 AllowObjCWritebackConversion); 4507 // If a single element isn't convertible, fail. 4508 if (ICS.isBad()) { 4509 Result = ICS; 4510 break; 4511 } 4512 // Otherwise, look for the worst conversion. 4513 if (Result.isBad() || 4514 CompareImplicitConversionSequences(S, ICS, Result) == 4515 ImplicitConversionSequence::Worse) 4516 Result = ICS; 4517 } 4518 4519 // For an empty list, we won't have computed any conversion sequence. 4520 // Introduce the identity conversion sequence. 4521 if (From->getNumInits() == 0) { 4522 Result.setStandard(); 4523 Result.Standard.setAsIdentityConversion(); 4524 Result.Standard.setFromType(ToType); 4525 Result.Standard.setAllToTypes(ToType); 4526 } 4527 4528 Result.setStdInitializerListElement(toStdInitializerList); 4529 return Result; 4530 } 4531 4532 // C++11 [over.ics.list]p3: 4533 // Otherwise, if the parameter is a non-aggregate class X and overload 4534 // resolution chooses a single best constructor [...] the implicit 4535 // conversion sequence is a user-defined conversion sequence. If multiple 4536 // constructors are viable but none is better than the others, the 4537 // implicit conversion sequence is a user-defined conversion sequence. 4538 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4539 // This function can deal with initializer lists. 4540 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4541 /*AllowExplicit=*/false, 4542 InOverloadResolution, /*CStyle=*/false, 4543 AllowObjCWritebackConversion, 4544 /*AllowObjCConversionOnExplicit=*/false); 4545 } 4546 4547 // C++11 [over.ics.list]p4: 4548 // Otherwise, if the parameter has an aggregate type which can be 4549 // initialized from the initializer list [...] the implicit conversion 4550 // sequence is a user-defined conversion sequence. 4551 if (ToType->isAggregateType()) { 4552 // Type is an aggregate, argument is an init list. At this point it comes 4553 // down to checking whether the initialization works. 4554 // FIXME: Find out whether this parameter is consumed or not. 4555 InitializedEntity Entity = 4556 InitializedEntity::InitializeParameter(S.Context, ToType, 4557 /*Consumed=*/false); 4558 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) { 4559 Result.setUserDefined(); 4560 Result.UserDefined.Before.setAsIdentityConversion(); 4561 // Initializer lists don't have a type. 4562 Result.UserDefined.Before.setFromType(QualType()); 4563 Result.UserDefined.Before.setAllToTypes(QualType()); 4564 4565 Result.UserDefined.After.setAsIdentityConversion(); 4566 Result.UserDefined.After.setFromType(ToType); 4567 Result.UserDefined.After.setAllToTypes(ToType); 4568 Result.UserDefined.ConversionFunction = 0; 4569 } 4570 return Result; 4571 } 4572 4573 // C++11 [over.ics.list]p5: 4574 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4575 if (ToType->isReferenceType()) { 4576 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4577 // mention initializer lists in any way. So we go by what list- 4578 // initialization would do and try to extrapolate from that. 4579 4580 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4581 4582 // If the initializer list has a single element that is reference-related 4583 // to the parameter type, we initialize the reference from that. 4584 if (From->getNumInits() == 1) { 4585 Expr *Init = From->getInit(0); 4586 4587 QualType T2 = Init->getType(); 4588 4589 // If the initializer is the address of an overloaded function, try 4590 // to resolve the overloaded function. If all goes well, T2 is the 4591 // type of the resulting function. 4592 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4593 DeclAccessPair Found; 4594 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4595 Init, ToType, false, Found)) 4596 T2 = Fn->getType(); 4597 } 4598 4599 // Compute some basic properties of the types and the initializer. 4600 bool dummy1 = false; 4601 bool dummy2 = false; 4602 bool dummy3 = false; 4603 Sema::ReferenceCompareResult RefRelationship 4604 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4605 dummy2, dummy3); 4606 4607 if (RefRelationship >= Sema::Ref_Related) { 4608 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4609 SuppressUserConversions, 4610 /*AllowExplicit=*/false); 4611 } 4612 } 4613 4614 // Otherwise, we bind the reference to a temporary created from the 4615 // initializer list. 4616 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4617 InOverloadResolution, 4618 AllowObjCWritebackConversion); 4619 if (Result.isFailure()) 4620 return Result; 4621 assert(!Result.isEllipsis() && 4622 "Sub-initialization cannot result in ellipsis conversion."); 4623 4624 // Can we even bind to a temporary? 4625 if (ToType->isRValueReferenceType() || 4626 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4627 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4628 Result.UserDefined.After; 4629 SCS.ReferenceBinding = true; 4630 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4631 SCS.BindsToRvalue = true; 4632 SCS.BindsToFunctionLvalue = false; 4633 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4634 SCS.ObjCLifetimeConversionBinding = false; 4635 } else 4636 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4637 From, ToType); 4638 return Result; 4639 } 4640 4641 // C++11 [over.ics.list]p6: 4642 // Otherwise, if the parameter type is not a class: 4643 if (!ToType->isRecordType()) { 4644 // - if the initializer list has one element, the implicit conversion 4645 // sequence is the one required to convert the element to the 4646 // parameter type. 4647 unsigned NumInits = From->getNumInits(); 4648 if (NumInits == 1) 4649 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4650 SuppressUserConversions, 4651 InOverloadResolution, 4652 AllowObjCWritebackConversion); 4653 // - if the initializer list has no elements, the implicit conversion 4654 // sequence is the identity conversion. 4655 else if (NumInits == 0) { 4656 Result.setStandard(); 4657 Result.Standard.setAsIdentityConversion(); 4658 Result.Standard.setFromType(ToType); 4659 Result.Standard.setAllToTypes(ToType); 4660 } 4661 return Result; 4662 } 4663 4664 // C++11 [over.ics.list]p7: 4665 // In all cases other than those enumerated above, no conversion is possible 4666 return Result; 4667 } 4668 4669 /// TryCopyInitialization - Try to copy-initialize a value of type 4670 /// ToType from the expression From. Return the implicit conversion 4671 /// sequence required to pass this argument, which may be a bad 4672 /// conversion sequence (meaning that the argument cannot be passed to 4673 /// a parameter of this type). If @p SuppressUserConversions, then we 4674 /// do not permit any user-defined conversion sequences. 4675 static ImplicitConversionSequence 4676 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4677 bool SuppressUserConversions, 4678 bool InOverloadResolution, 4679 bool AllowObjCWritebackConversion, 4680 bool AllowExplicit) { 4681 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4682 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4683 InOverloadResolution,AllowObjCWritebackConversion); 4684 4685 if (ToType->isReferenceType()) 4686 return TryReferenceInit(S, From, ToType, 4687 /*FIXME:*/From->getLocStart(), 4688 SuppressUserConversions, 4689 AllowExplicit); 4690 4691 return TryImplicitConversion(S, From, ToType, 4692 SuppressUserConversions, 4693 /*AllowExplicit=*/false, 4694 InOverloadResolution, 4695 /*CStyle=*/false, 4696 AllowObjCWritebackConversion, 4697 /*AllowObjCConversionOnExplicit=*/false); 4698 } 4699 4700 static bool TryCopyInitialization(const CanQualType FromQTy, 4701 const CanQualType ToQTy, 4702 Sema &S, 4703 SourceLocation Loc, 4704 ExprValueKind FromVK) { 4705 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4706 ImplicitConversionSequence ICS = 4707 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4708 4709 return !ICS.isBad(); 4710 } 4711 4712 /// TryObjectArgumentInitialization - Try to initialize the object 4713 /// parameter of the given member function (@c Method) from the 4714 /// expression @p From. 4715 static ImplicitConversionSequence 4716 TryObjectArgumentInitialization(Sema &S, QualType FromType, 4717 Expr::Classification FromClassification, 4718 CXXMethodDecl *Method, 4719 CXXRecordDecl *ActingContext) { 4720 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4721 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4722 // const volatile object. 4723 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4724 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4725 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4726 4727 // Set up the conversion sequence as a "bad" conversion, to allow us 4728 // to exit early. 4729 ImplicitConversionSequence ICS; 4730 4731 // We need to have an object of class type. 4732 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4733 FromType = PT->getPointeeType(); 4734 4735 // When we had a pointer, it's implicitly dereferenced, so we 4736 // better have an lvalue. 4737 assert(FromClassification.isLValue()); 4738 } 4739 4740 assert(FromType->isRecordType()); 4741 4742 // C++0x [over.match.funcs]p4: 4743 // For non-static member functions, the type of the implicit object 4744 // parameter is 4745 // 4746 // - "lvalue reference to cv X" for functions declared without a 4747 // ref-qualifier or with the & ref-qualifier 4748 // - "rvalue reference to cv X" for functions declared with the && 4749 // ref-qualifier 4750 // 4751 // where X is the class of which the function is a member and cv is the 4752 // cv-qualification on the member function declaration. 4753 // 4754 // However, when finding an implicit conversion sequence for the argument, we 4755 // are not allowed to create temporaries or perform user-defined conversions 4756 // (C++ [over.match.funcs]p5). We perform a simplified version of 4757 // reference binding here, that allows class rvalues to bind to 4758 // non-constant references. 4759 4760 // First check the qualifiers. 4761 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4762 if (ImplicitParamType.getCVRQualifiers() 4763 != FromTypeCanon.getLocalCVRQualifiers() && 4764 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4765 ICS.setBad(BadConversionSequence::bad_qualifiers, 4766 FromType, ImplicitParamType); 4767 return ICS; 4768 } 4769 4770 // Check that we have either the same type or a derived type. It 4771 // affects the conversion rank. 4772 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4773 ImplicitConversionKind SecondKind; 4774 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4775 SecondKind = ICK_Identity; 4776 } else if (S.IsDerivedFrom(FromType, ClassType)) 4777 SecondKind = ICK_Derived_To_Base; 4778 else { 4779 ICS.setBad(BadConversionSequence::unrelated_class, 4780 FromType, ImplicitParamType); 4781 return ICS; 4782 } 4783 4784 // Check the ref-qualifier. 4785 switch (Method->getRefQualifier()) { 4786 case RQ_None: 4787 // Do nothing; we don't care about lvalueness or rvalueness. 4788 break; 4789 4790 case RQ_LValue: 4791 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4792 // non-const lvalue reference cannot bind to an rvalue 4793 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4794 ImplicitParamType); 4795 return ICS; 4796 } 4797 break; 4798 4799 case RQ_RValue: 4800 if (!FromClassification.isRValue()) { 4801 // rvalue reference cannot bind to an lvalue 4802 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4803 ImplicitParamType); 4804 return ICS; 4805 } 4806 break; 4807 } 4808 4809 // Success. Mark this as a reference binding. 4810 ICS.setStandard(); 4811 ICS.Standard.setAsIdentityConversion(); 4812 ICS.Standard.Second = SecondKind; 4813 ICS.Standard.setFromType(FromType); 4814 ICS.Standard.setAllToTypes(ImplicitParamType); 4815 ICS.Standard.ReferenceBinding = true; 4816 ICS.Standard.DirectBinding = true; 4817 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4818 ICS.Standard.BindsToFunctionLvalue = false; 4819 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4820 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4821 = (Method->getRefQualifier() == RQ_None); 4822 return ICS; 4823 } 4824 4825 /// PerformObjectArgumentInitialization - Perform initialization of 4826 /// the implicit object parameter for the given Method with the given 4827 /// expression. 4828 ExprResult 4829 Sema::PerformObjectArgumentInitialization(Expr *From, 4830 NestedNameSpecifier *Qualifier, 4831 NamedDecl *FoundDecl, 4832 CXXMethodDecl *Method) { 4833 QualType FromRecordType, DestType; 4834 QualType ImplicitParamRecordType = 4835 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4836 4837 Expr::Classification FromClassification; 4838 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4839 FromRecordType = PT->getPointeeType(); 4840 DestType = Method->getThisType(Context); 4841 FromClassification = Expr::Classification::makeSimpleLValue(); 4842 } else { 4843 FromRecordType = From->getType(); 4844 DestType = ImplicitParamRecordType; 4845 FromClassification = From->Classify(Context); 4846 } 4847 4848 // Note that we always use the true parent context when performing 4849 // the actual argument initialization. 4850 ImplicitConversionSequence ICS 4851 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification, 4852 Method, Method->getParent()); 4853 if (ICS.isBad()) { 4854 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4855 Qualifiers FromQs = FromRecordType.getQualifiers(); 4856 Qualifiers ToQs = DestType.getQualifiers(); 4857 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4858 if (CVR) { 4859 Diag(From->getLocStart(), 4860 diag::err_member_function_call_bad_cvr) 4861 << Method->getDeclName() << FromRecordType << (CVR - 1) 4862 << From->getSourceRange(); 4863 Diag(Method->getLocation(), diag::note_previous_decl) 4864 << Method->getDeclName(); 4865 return ExprError(); 4866 } 4867 } 4868 4869 return Diag(From->getLocStart(), 4870 diag::err_implicit_object_parameter_init) 4871 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4872 } 4873 4874 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4875 ExprResult FromRes = 4876 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4877 if (FromRes.isInvalid()) 4878 return ExprError(); 4879 From = FromRes.take(); 4880 } 4881 4882 if (!Context.hasSameType(From->getType(), DestType)) 4883 From = ImpCastExprToType(From, DestType, CK_NoOp, 4884 From->getValueKind()).take(); 4885 return Owned(From); 4886 } 4887 4888 /// TryContextuallyConvertToBool - Attempt to contextually convert the 4889 /// expression From to bool (C++0x [conv]p3). 4890 static ImplicitConversionSequence 4891 TryContextuallyConvertToBool(Sema &S, Expr *From) { 4892 return TryImplicitConversion(S, From, S.Context.BoolTy, 4893 /*SuppressUserConversions=*/false, 4894 /*AllowExplicit=*/true, 4895 /*InOverloadResolution=*/false, 4896 /*CStyle=*/false, 4897 /*AllowObjCWritebackConversion=*/false, 4898 /*AllowObjCConversionOnExplicit=*/false); 4899 } 4900 4901 /// PerformContextuallyConvertToBool - Perform a contextual conversion 4902 /// of the expression From to bool (C++0x [conv]p3). 4903 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4904 if (checkPlaceholderForOverload(*this, From)) 4905 return ExprError(); 4906 4907 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4908 if (!ICS.isBad()) 4909 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4910 4911 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4912 return Diag(From->getLocStart(), 4913 diag::err_typecheck_bool_condition) 4914 << From->getType() << From->getSourceRange(); 4915 return ExprError(); 4916 } 4917 4918 /// Check that the specified conversion is permitted in a converted constant 4919 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 4920 /// is acceptable. 4921 static bool CheckConvertedConstantConversions(Sema &S, 4922 StandardConversionSequence &SCS) { 4923 // Since we know that the target type is an integral or unscoped enumeration 4924 // type, most conversion kinds are impossible. All possible First and Third 4925 // conversions are fine. 4926 switch (SCS.Second) { 4927 case ICK_Identity: 4928 case ICK_Integral_Promotion: 4929 case ICK_Integral_Conversion: 4930 case ICK_Zero_Event_Conversion: 4931 return true; 4932 4933 case ICK_Boolean_Conversion: 4934 // Conversion from an integral or unscoped enumeration type to bool is 4935 // classified as ICK_Boolean_Conversion, but it's also an integral 4936 // conversion, so it's permitted in a converted constant expression. 4937 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4938 SCS.getToType(2)->isBooleanType(); 4939 4940 case ICK_Floating_Integral: 4941 case ICK_Complex_Real: 4942 return false; 4943 4944 case ICK_Lvalue_To_Rvalue: 4945 case ICK_Array_To_Pointer: 4946 case ICK_Function_To_Pointer: 4947 case ICK_NoReturn_Adjustment: 4948 case ICK_Qualification: 4949 case ICK_Compatible_Conversion: 4950 case ICK_Vector_Conversion: 4951 case ICK_Vector_Splat: 4952 case ICK_Derived_To_Base: 4953 case ICK_Pointer_Conversion: 4954 case ICK_Pointer_Member: 4955 case ICK_Block_Pointer_Conversion: 4956 case ICK_Writeback_Conversion: 4957 case ICK_Floating_Promotion: 4958 case ICK_Complex_Promotion: 4959 case ICK_Complex_Conversion: 4960 case ICK_Floating_Conversion: 4961 case ICK_TransparentUnionConversion: 4962 llvm_unreachable("unexpected second conversion kind"); 4963 4964 case ICK_Num_Conversion_Kinds: 4965 break; 4966 } 4967 4968 llvm_unreachable("unknown conversion kind"); 4969 } 4970 4971 /// CheckConvertedConstantExpression - Check that the expression From is a 4972 /// converted constant expression of type T, perform the conversion and produce 4973 /// the converted expression, per C++11 [expr.const]p3. 4974 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 4975 llvm::APSInt &Value, 4976 CCEKind CCE) { 4977 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11"); 4978 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 4979 4980 if (checkPlaceholderForOverload(*this, From)) 4981 return ExprError(); 4982 4983 // C++11 [expr.const]p3 with proposed wording fixes: 4984 // A converted constant expression of type T is a core constant expression, 4985 // implicitly converted to a prvalue of type T, where the converted 4986 // expression is a literal constant expression and the implicit conversion 4987 // sequence contains only user-defined conversions, lvalue-to-rvalue 4988 // conversions, integral promotions, and integral conversions other than 4989 // narrowing conversions. 4990 ImplicitConversionSequence ICS = 4991 TryImplicitConversion(From, T, 4992 /*SuppressUserConversions=*/false, 4993 /*AllowExplicit=*/false, 4994 /*InOverloadResolution=*/false, 4995 /*CStyle=*/false, 4996 /*AllowObjcWritebackConversion=*/false); 4997 StandardConversionSequence *SCS = 0; 4998 switch (ICS.getKind()) { 4999 case ImplicitConversionSequence::StandardConversion: 5000 if (!CheckConvertedConstantConversions(*this, ICS.Standard)) 5001 return Diag(From->getLocStart(), 5002 diag::err_typecheck_converted_constant_expression_disallowed) 5003 << From->getType() << From->getSourceRange() << T; 5004 SCS = &ICS.Standard; 5005 break; 5006 case ImplicitConversionSequence::UserDefinedConversion: 5007 // We are converting from class type to an integral or enumeration type, so 5008 // the Before sequence must be trivial. 5009 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After)) 5010 return Diag(From->getLocStart(), 5011 diag::err_typecheck_converted_constant_expression_disallowed) 5012 << From->getType() << From->getSourceRange() << T; 5013 SCS = &ICS.UserDefined.After; 5014 break; 5015 case ImplicitConversionSequence::AmbiguousConversion: 5016 case ImplicitConversionSequence::BadConversion: 5017 if (!DiagnoseMultipleUserDefinedConversion(From, T)) 5018 return Diag(From->getLocStart(), 5019 diag::err_typecheck_converted_constant_expression) 5020 << From->getType() << From->getSourceRange() << T; 5021 return ExprError(); 5022 5023 case ImplicitConversionSequence::EllipsisConversion: 5024 llvm_unreachable("ellipsis conversion in converted constant expression"); 5025 } 5026 5027 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting); 5028 if (Result.isInvalid()) 5029 return Result; 5030 5031 // Check for a narrowing implicit conversion. 5032 APValue PreNarrowingValue; 5033 QualType PreNarrowingType; 5034 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue, 5035 PreNarrowingType)) { 5036 case NK_Variable_Narrowing: 5037 // Implicit conversion to a narrower type, and the value is not a constant 5038 // expression. We'll diagnose this in a moment. 5039 case NK_Not_Narrowing: 5040 break; 5041 5042 case NK_Constant_Narrowing: 5043 Diag(From->getLocStart(), diag::ext_cce_narrowing) 5044 << CCE << /*Constant*/1 5045 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T; 5046 break; 5047 5048 case NK_Type_Narrowing: 5049 Diag(From->getLocStart(), diag::ext_cce_narrowing) 5050 << CCE << /*Constant*/0 << From->getType() << T; 5051 break; 5052 } 5053 5054 // Check the expression is a constant expression. 5055 SmallVector<PartialDiagnosticAt, 8> Notes; 5056 Expr::EvalResult Eval; 5057 Eval.Diag = &Notes; 5058 5059 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) { 5060 // The expression can't be folded, so we can't keep it at this position in 5061 // the AST. 5062 Result = ExprError(); 5063 } else { 5064 Value = Eval.Val.getInt(); 5065 5066 if (Notes.empty()) { 5067 // It's a constant expression. 5068 return Result; 5069 } 5070 } 5071 5072 // It's not a constant expression. Produce an appropriate diagnostic. 5073 if (Notes.size() == 1 && 5074 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5075 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5076 else { 5077 Diag(From->getLocStart(), diag::err_expr_not_cce) 5078 << CCE << From->getSourceRange(); 5079 for (unsigned I = 0; I < Notes.size(); ++I) 5080 Diag(Notes[I].first, Notes[I].second); 5081 } 5082 return Result; 5083 } 5084 5085 /// dropPointerConversions - If the given standard conversion sequence 5086 /// involves any pointer conversions, remove them. This may change 5087 /// the result type of the conversion sequence. 5088 static void dropPointerConversion(StandardConversionSequence &SCS) { 5089 if (SCS.Second == ICK_Pointer_Conversion) { 5090 SCS.Second = ICK_Identity; 5091 SCS.Third = ICK_Identity; 5092 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5093 } 5094 } 5095 5096 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5097 /// convert the expression From to an Objective-C pointer type. 5098 static ImplicitConversionSequence 5099 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5100 // Do an implicit conversion to 'id'. 5101 QualType Ty = S.Context.getObjCIdType(); 5102 ImplicitConversionSequence ICS 5103 = TryImplicitConversion(S, From, Ty, 5104 // FIXME: Are these flags correct? 5105 /*SuppressUserConversions=*/false, 5106 /*AllowExplicit=*/true, 5107 /*InOverloadResolution=*/false, 5108 /*CStyle=*/false, 5109 /*AllowObjCWritebackConversion=*/false, 5110 /*AllowObjCConversionOnExplicit=*/true); 5111 5112 // Strip off any final conversions to 'id'. 5113 switch (ICS.getKind()) { 5114 case ImplicitConversionSequence::BadConversion: 5115 case ImplicitConversionSequence::AmbiguousConversion: 5116 case ImplicitConversionSequence::EllipsisConversion: 5117 break; 5118 5119 case ImplicitConversionSequence::UserDefinedConversion: 5120 dropPointerConversion(ICS.UserDefined.After); 5121 break; 5122 5123 case ImplicitConversionSequence::StandardConversion: 5124 dropPointerConversion(ICS.Standard); 5125 break; 5126 } 5127 5128 return ICS; 5129 } 5130 5131 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5132 /// conversion of the expression From to an Objective-C pointer type. 5133 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5134 if (checkPlaceholderForOverload(*this, From)) 5135 return ExprError(); 5136 5137 QualType Ty = Context.getObjCIdType(); 5138 ImplicitConversionSequence ICS = 5139 TryContextuallyConvertToObjCPointer(*this, From); 5140 if (!ICS.isBad()) 5141 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5142 return ExprError(); 5143 } 5144 5145 /// Determine whether the provided type is an integral type, or an enumeration 5146 /// type of a permitted flavor. 5147 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5148 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5149 : T->isIntegralOrUnscopedEnumerationType(); 5150 } 5151 5152 static ExprResult 5153 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5154 Sema::ContextualImplicitConverter &Converter, 5155 QualType T, UnresolvedSetImpl &ViableConversions) { 5156 5157 if (Converter.Suppress) 5158 return ExprError(); 5159 5160 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5161 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5162 CXXConversionDecl *Conv = 5163 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5164 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5165 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5166 } 5167 return SemaRef.Owned(From); 5168 } 5169 5170 static bool 5171 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5172 Sema::ContextualImplicitConverter &Converter, 5173 QualType T, bool HadMultipleCandidates, 5174 UnresolvedSetImpl &ExplicitConversions) { 5175 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5176 DeclAccessPair Found = ExplicitConversions[0]; 5177 CXXConversionDecl *Conversion = 5178 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5179 5180 // The user probably meant to invoke the given explicit 5181 // conversion; use it. 5182 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5183 std::string TypeStr; 5184 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5185 5186 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5187 << FixItHint::CreateInsertion(From->getLocStart(), 5188 "static_cast<" + TypeStr + ">(") 5189 << FixItHint::CreateInsertion( 5190 SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")"); 5191 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5192 5193 // If we aren't in a SFINAE context, build a call to the 5194 // explicit conversion function. 5195 if (SemaRef.isSFINAEContext()) 5196 return true; 5197 5198 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5199 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5200 HadMultipleCandidates); 5201 if (Result.isInvalid()) 5202 return true; 5203 // Record usage of conversion in an implicit cast. 5204 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5205 CK_UserDefinedConversion, Result.get(), 0, 5206 Result.get()->getValueKind()); 5207 } 5208 return false; 5209 } 5210 5211 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5212 Sema::ContextualImplicitConverter &Converter, 5213 QualType T, bool HadMultipleCandidates, 5214 DeclAccessPair &Found) { 5215 CXXConversionDecl *Conversion = 5216 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5217 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5218 5219 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5220 if (!Converter.SuppressConversion) { 5221 if (SemaRef.isSFINAEContext()) 5222 return true; 5223 5224 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5225 << From->getSourceRange(); 5226 } 5227 5228 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5229 HadMultipleCandidates); 5230 if (Result.isInvalid()) 5231 return true; 5232 // Record usage of conversion in an implicit cast. 5233 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5234 CK_UserDefinedConversion, Result.get(), 0, 5235 Result.get()->getValueKind()); 5236 return false; 5237 } 5238 5239 static ExprResult finishContextualImplicitConversion( 5240 Sema &SemaRef, SourceLocation Loc, Expr *From, 5241 Sema::ContextualImplicitConverter &Converter) { 5242 if (!Converter.match(From->getType()) && !Converter.Suppress) 5243 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5244 << From->getSourceRange(); 5245 5246 return SemaRef.DefaultLvalueConversion(From); 5247 } 5248 5249 static void 5250 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5251 UnresolvedSetImpl &ViableConversions, 5252 OverloadCandidateSet &CandidateSet) { 5253 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5254 DeclAccessPair FoundDecl = ViableConversions[I]; 5255 NamedDecl *D = FoundDecl.getDecl(); 5256 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5257 if (isa<UsingShadowDecl>(D)) 5258 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5259 5260 CXXConversionDecl *Conv; 5261 FunctionTemplateDecl *ConvTemplate; 5262 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5263 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5264 else 5265 Conv = cast<CXXConversionDecl>(D); 5266 5267 if (ConvTemplate) 5268 SemaRef.AddTemplateConversionCandidate( 5269 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5270 /*AllowObjCConversionOnExplicit=*/false); 5271 else 5272 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5273 ToType, CandidateSet, 5274 /*AllowObjCConversionOnExplicit=*/false); 5275 } 5276 } 5277 5278 /// \brief Attempt to convert the given expression to a type which is accepted 5279 /// by the given converter. 5280 /// 5281 /// This routine will attempt to convert an expression of class type to a 5282 /// type accepted by the specified converter. In C++11 and before, the class 5283 /// must have a single non-explicit conversion function converting to a matching 5284 /// type. In C++1y, there can be multiple such conversion functions, but only 5285 /// one target type. 5286 /// 5287 /// \param Loc The source location of the construct that requires the 5288 /// conversion. 5289 /// 5290 /// \param From The expression we're converting from. 5291 /// 5292 /// \param Converter Used to control and diagnose the conversion process. 5293 /// 5294 /// \returns The expression, converted to an integral or enumeration type if 5295 /// successful. 5296 ExprResult Sema::PerformContextualImplicitConversion( 5297 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5298 // We can't perform any more checking for type-dependent expressions. 5299 if (From->isTypeDependent()) 5300 return Owned(From); 5301 5302 // Process placeholders immediately. 5303 if (From->hasPlaceholderType()) { 5304 ExprResult result = CheckPlaceholderExpr(From); 5305 if (result.isInvalid()) 5306 return result; 5307 From = result.take(); 5308 } 5309 5310 // If the expression already has a matching type, we're golden. 5311 QualType T = From->getType(); 5312 if (Converter.match(T)) 5313 return DefaultLvalueConversion(From); 5314 5315 // FIXME: Check for missing '()' if T is a function type? 5316 5317 // We can only perform contextual implicit conversions on objects of class 5318 // type. 5319 const RecordType *RecordTy = T->getAs<RecordType>(); 5320 if (!RecordTy || !getLangOpts().CPlusPlus) { 5321 if (!Converter.Suppress) 5322 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5323 return Owned(From); 5324 } 5325 5326 // We must have a complete class type. 5327 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5328 ContextualImplicitConverter &Converter; 5329 Expr *From; 5330 5331 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5332 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {} 5333 5334 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5335 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5336 } 5337 } IncompleteDiagnoser(Converter, From); 5338 5339 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5340 return Owned(From); 5341 5342 // Look for a conversion to an integral or enumeration type. 5343 UnresolvedSet<4> 5344 ViableConversions; // These are *potentially* viable in C++1y. 5345 UnresolvedSet<4> ExplicitConversions; 5346 std::pair<CXXRecordDecl::conversion_iterator, 5347 CXXRecordDecl::conversion_iterator> Conversions = 5348 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5349 5350 bool HadMultipleCandidates = 5351 (std::distance(Conversions.first, Conversions.second) > 1); 5352 5353 // To check that there is only one target type, in C++1y: 5354 QualType ToType; 5355 bool HasUniqueTargetType = true; 5356 5357 // Collect explicit or viable (potentially in C++1y) conversions. 5358 for (CXXRecordDecl::conversion_iterator I = Conversions.first, 5359 E = Conversions.second; 5360 I != E; ++I) { 5361 NamedDecl *D = (*I)->getUnderlyingDecl(); 5362 CXXConversionDecl *Conversion; 5363 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5364 if (ConvTemplate) { 5365 if (getLangOpts().CPlusPlus1y) 5366 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5367 else 5368 continue; // C++11 does not consider conversion operator templates(?). 5369 } else 5370 Conversion = cast<CXXConversionDecl>(D); 5371 5372 assert((!ConvTemplate || getLangOpts().CPlusPlus1y) && 5373 "Conversion operator templates are considered potentially " 5374 "viable in C++1y"); 5375 5376 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5377 if (Converter.match(CurToType) || ConvTemplate) { 5378 5379 if (Conversion->isExplicit()) { 5380 // FIXME: For C++1y, do we need this restriction? 5381 // cf. diagnoseNoViableConversion() 5382 if (!ConvTemplate) 5383 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5384 } else { 5385 if (!ConvTemplate && getLangOpts().CPlusPlus1y) { 5386 if (ToType.isNull()) 5387 ToType = CurToType.getUnqualifiedType(); 5388 else if (HasUniqueTargetType && 5389 (CurToType.getUnqualifiedType() != ToType)) 5390 HasUniqueTargetType = false; 5391 } 5392 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5393 } 5394 } 5395 } 5396 5397 if (getLangOpts().CPlusPlus1y) { 5398 // C++1y [conv]p6: 5399 // ... An expression e of class type E appearing in such a context 5400 // is said to be contextually implicitly converted to a specified 5401 // type T and is well-formed if and only if e can be implicitly 5402 // converted to a type T that is determined as follows: E is searched 5403 // for conversion functions whose return type is cv T or reference to 5404 // cv T such that T is allowed by the context. There shall be 5405 // exactly one such T. 5406 5407 // If no unique T is found: 5408 if (ToType.isNull()) { 5409 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5410 HadMultipleCandidates, 5411 ExplicitConversions)) 5412 return ExprError(); 5413 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5414 } 5415 5416 // If more than one unique Ts are found: 5417 if (!HasUniqueTargetType) 5418 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5419 ViableConversions); 5420 5421 // If one unique T is found: 5422 // First, build a candidate set from the previously recorded 5423 // potentially viable conversions. 5424 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5425 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5426 CandidateSet); 5427 5428 // Then, perform overload resolution over the candidate set. 5429 OverloadCandidateSet::iterator Best; 5430 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5431 case OR_Success: { 5432 // Apply this conversion. 5433 DeclAccessPair Found = 5434 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5435 if (recordConversion(*this, Loc, From, Converter, T, 5436 HadMultipleCandidates, Found)) 5437 return ExprError(); 5438 break; 5439 } 5440 case OR_Ambiguous: 5441 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5442 ViableConversions); 5443 case OR_No_Viable_Function: 5444 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5445 HadMultipleCandidates, 5446 ExplicitConversions)) 5447 return ExprError(); 5448 // fall through 'OR_Deleted' case. 5449 case OR_Deleted: 5450 // We'll complain below about a non-integral condition type. 5451 break; 5452 } 5453 } else { 5454 switch (ViableConversions.size()) { 5455 case 0: { 5456 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5457 HadMultipleCandidates, 5458 ExplicitConversions)) 5459 return ExprError(); 5460 5461 // We'll complain below about a non-integral condition type. 5462 break; 5463 } 5464 case 1: { 5465 // Apply this conversion. 5466 DeclAccessPair Found = ViableConversions[0]; 5467 if (recordConversion(*this, Loc, From, Converter, T, 5468 HadMultipleCandidates, Found)) 5469 return ExprError(); 5470 break; 5471 } 5472 default: 5473 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5474 ViableConversions); 5475 } 5476 } 5477 5478 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5479 } 5480 5481 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5482 /// an acceptable non-member overloaded operator for a call whose 5483 /// arguments have types T1 (and, if non-empty, T2). This routine 5484 /// implements the check in C++ [over.match.oper]p3b2 concerning 5485 /// enumeration types. 5486 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5487 FunctionDecl *Fn, 5488 ArrayRef<Expr *> Args) { 5489 QualType T1 = Args[0]->getType(); 5490 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5491 5492 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5493 return true; 5494 5495 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5496 return true; 5497 5498 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5499 if (Proto->getNumParams() < 1) 5500 return false; 5501 5502 if (T1->isEnumeralType()) { 5503 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5504 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5505 return true; 5506 } 5507 5508 if (Proto->getNumParams() < 2) 5509 return false; 5510 5511 if (!T2.isNull() && T2->isEnumeralType()) { 5512 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5513 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5514 return true; 5515 } 5516 5517 return false; 5518 } 5519 5520 /// AddOverloadCandidate - Adds the given function to the set of 5521 /// candidate functions, using the given function call arguments. If 5522 /// @p SuppressUserConversions, then don't allow user-defined 5523 /// conversions via constructors or conversion operators. 5524 /// 5525 /// \param PartialOverloading true if we are performing "partial" overloading 5526 /// based on an incomplete set of function arguments. This feature is used by 5527 /// code completion. 5528 void 5529 Sema::AddOverloadCandidate(FunctionDecl *Function, 5530 DeclAccessPair FoundDecl, 5531 ArrayRef<Expr *> Args, 5532 OverloadCandidateSet &CandidateSet, 5533 bool SuppressUserConversions, 5534 bool PartialOverloading, 5535 bool AllowExplicit) { 5536 const FunctionProtoType *Proto 5537 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5538 assert(Proto && "Functions without a prototype cannot be overloaded"); 5539 assert(!Function->getDescribedFunctionTemplate() && 5540 "Use AddTemplateOverloadCandidate for function templates"); 5541 5542 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5543 if (!isa<CXXConstructorDecl>(Method)) { 5544 // If we get here, it's because we're calling a member function 5545 // that is named without a member access expression (e.g., 5546 // "this->f") that was either written explicitly or created 5547 // implicitly. This can happen with a qualified call to a member 5548 // function, e.g., X::f(). We use an empty type for the implied 5549 // object argument (C++ [over.call.func]p3), and the acting context 5550 // is irrelevant. 5551 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5552 QualType(), Expr::Classification::makeSimpleLValue(), 5553 Args, CandidateSet, SuppressUserConversions); 5554 return; 5555 } 5556 // We treat a constructor like a non-member function, since its object 5557 // argument doesn't participate in overload resolution. 5558 } 5559 5560 if (!CandidateSet.isNewCandidate(Function)) 5561 return; 5562 5563 // C++ [over.match.oper]p3: 5564 // if no operand has a class type, only those non-member functions in the 5565 // lookup set that have a first parameter of type T1 or "reference to 5566 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5567 // is a right operand) a second parameter of type T2 or "reference to 5568 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5569 // candidate functions. 5570 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5571 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5572 return; 5573 5574 // C++11 [class.copy]p11: [DR1402] 5575 // A defaulted move constructor that is defined as deleted is ignored by 5576 // overload resolution. 5577 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5578 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5579 Constructor->isMoveConstructor()) 5580 return; 5581 5582 // Overload resolution is always an unevaluated context. 5583 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5584 5585 if (Constructor) { 5586 // C++ [class.copy]p3: 5587 // A member function template is never instantiated to perform the copy 5588 // of a class object to an object of its class type. 5589 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5590 if (Args.size() == 1 && 5591 Constructor->isSpecializationCopyingObject() && 5592 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5593 IsDerivedFrom(Args[0]->getType(), ClassType))) 5594 return; 5595 } 5596 5597 // Add this candidate 5598 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5599 Candidate.FoundDecl = FoundDecl; 5600 Candidate.Function = Function; 5601 Candidate.Viable = true; 5602 Candidate.IsSurrogate = false; 5603 Candidate.IgnoreObjectArgument = false; 5604 Candidate.ExplicitCallArguments = Args.size(); 5605 5606 unsigned NumParams = Proto->getNumParams(); 5607 5608 // (C++ 13.3.2p2): A candidate function having fewer than m 5609 // parameters is viable only if it has an ellipsis in its parameter 5610 // list (8.3.5). 5611 if ((Args.size() + (PartialOverloading && Args.size())) > NumParams && 5612 !Proto->isVariadic()) { 5613 Candidate.Viable = false; 5614 Candidate.FailureKind = ovl_fail_too_many_arguments; 5615 return; 5616 } 5617 5618 // (C++ 13.3.2p2): A candidate function having more than m parameters 5619 // is viable only if the (m+1)st parameter has a default argument 5620 // (8.3.6). For the purposes of overload resolution, the 5621 // parameter list is truncated on the right, so that there are 5622 // exactly m parameters. 5623 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5624 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5625 // Not enough arguments. 5626 Candidate.Viable = false; 5627 Candidate.FailureKind = ovl_fail_too_few_arguments; 5628 return; 5629 } 5630 5631 // (CUDA B.1): Check for invalid calls between targets. 5632 if (getLangOpts().CUDA) 5633 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5634 if (CheckCUDATarget(Caller, Function)) { 5635 Candidate.Viable = false; 5636 Candidate.FailureKind = ovl_fail_bad_target; 5637 return; 5638 } 5639 5640 // Determine the implicit conversion sequences for each of the 5641 // arguments. 5642 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5643 if (ArgIdx < NumParams) { 5644 // (C++ 13.3.2p3): for F to be a viable function, there shall 5645 // exist for each argument an implicit conversion sequence 5646 // (13.3.3.1) that converts that argument to the corresponding 5647 // parameter of F. 5648 QualType ParamType = Proto->getParamType(ArgIdx); 5649 Candidate.Conversions[ArgIdx] 5650 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5651 SuppressUserConversions, 5652 /*InOverloadResolution=*/true, 5653 /*AllowObjCWritebackConversion=*/ 5654 getLangOpts().ObjCAutoRefCount, 5655 AllowExplicit); 5656 if (Candidate.Conversions[ArgIdx].isBad()) { 5657 Candidate.Viable = false; 5658 Candidate.FailureKind = ovl_fail_bad_conversion; 5659 return; 5660 } 5661 } else { 5662 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5663 // argument for which there is no corresponding parameter is 5664 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5665 Candidate.Conversions[ArgIdx].setEllipsis(); 5666 } 5667 } 5668 5669 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5670 Candidate.Viable = false; 5671 Candidate.FailureKind = ovl_fail_enable_if; 5672 Candidate.DeductionFailure.Data = FailedAttr; 5673 return; 5674 } 5675 } 5676 5677 static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); } 5678 5679 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 5680 bool MissingImplicitThis) { 5681 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but 5682 // we need to find the first failing one. 5683 if (!Function->hasAttrs()) 5684 return 0; 5685 AttrVec Attrs = Function->getAttrs(); 5686 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(), 5687 IsNotEnableIfAttr); 5688 if (Attrs.begin() == E) 5689 return 0; 5690 std::reverse(Attrs.begin(), E); 5691 5692 SFINAETrap Trap(*this); 5693 5694 // Convert the arguments. 5695 SmallVector<Expr *, 16> ConvertedArgs; 5696 bool InitializationFailed = false; 5697 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 5698 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 5699 !cast<CXXMethodDecl>(Function)->isStatic() && 5700 !isa<CXXConstructorDecl>(Function)) { 5701 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 5702 ExprResult R = 5703 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 5704 Method, Method); 5705 if (R.isInvalid()) { 5706 InitializationFailed = true; 5707 break; 5708 } 5709 ConvertedArgs.push_back(R.take()); 5710 } else { 5711 ExprResult R = 5712 PerformCopyInitialization(InitializedEntity::InitializeParameter( 5713 Context, 5714 Function->getParamDecl(i)), 5715 SourceLocation(), 5716 Args[i]); 5717 if (R.isInvalid()) { 5718 InitializationFailed = true; 5719 break; 5720 } 5721 ConvertedArgs.push_back(R.take()); 5722 } 5723 } 5724 5725 if (InitializationFailed || Trap.hasErrorOccurred()) 5726 return cast<EnableIfAttr>(Attrs[0]); 5727 5728 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) { 5729 APValue Result; 5730 EnableIfAttr *EIA = cast<EnableIfAttr>(*I); 5731 if (!EIA->getCond()->EvaluateWithSubstitution( 5732 Result, Context, Function, 5733 llvm::ArrayRef<const Expr*>(ConvertedArgs.data(), 5734 ConvertedArgs.size())) || 5735 !Result.isInt() || !Result.getInt().getBoolValue()) { 5736 return EIA; 5737 } 5738 } 5739 return 0; 5740 } 5741 5742 /// \brief Add all of the function declarations in the given function set to 5743 /// the overload candidate set. 5744 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5745 ArrayRef<Expr *> Args, 5746 OverloadCandidateSet& CandidateSet, 5747 bool SuppressUserConversions, 5748 TemplateArgumentListInfo *ExplicitTemplateArgs) { 5749 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5750 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5751 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5752 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5753 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5754 cast<CXXMethodDecl>(FD)->getParent(), 5755 Args[0]->getType(), Args[0]->Classify(Context), 5756 Args.slice(1), CandidateSet, 5757 SuppressUserConversions); 5758 else 5759 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5760 SuppressUserConversions); 5761 } else { 5762 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5763 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5764 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5765 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5766 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5767 ExplicitTemplateArgs, 5768 Args[0]->getType(), 5769 Args[0]->Classify(Context), Args.slice(1), 5770 CandidateSet, SuppressUserConversions); 5771 else 5772 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5773 ExplicitTemplateArgs, Args, 5774 CandidateSet, SuppressUserConversions); 5775 } 5776 } 5777 } 5778 5779 /// AddMethodCandidate - Adds a named decl (which is some kind of 5780 /// method) as a method candidate to the given overload set. 5781 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5782 QualType ObjectType, 5783 Expr::Classification ObjectClassification, 5784 ArrayRef<Expr *> Args, 5785 OverloadCandidateSet& CandidateSet, 5786 bool SuppressUserConversions) { 5787 NamedDecl *Decl = FoundDecl.getDecl(); 5788 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5789 5790 if (isa<UsingShadowDecl>(Decl)) 5791 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5792 5793 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5794 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5795 "Expected a member function template"); 5796 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5797 /*ExplicitArgs*/ 0, 5798 ObjectType, ObjectClassification, 5799 Args, CandidateSet, 5800 SuppressUserConversions); 5801 } else { 5802 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5803 ObjectType, ObjectClassification, 5804 Args, 5805 CandidateSet, SuppressUserConversions); 5806 } 5807 } 5808 5809 /// AddMethodCandidate - Adds the given C++ member function to the set 5810 /// of candidate functions, using the given function call arguments 5811 /// and the object argument (@c Object). For example, in a call 5812 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5813 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5814 /// allow user-defined conversions via constructors or conversion 5815 /// operators. 5816 void 5817 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5818 CXXRecordDecl *ActingContext, QualType ObjectType, 5819 Expr::Classification ObjectClassification, 5820 ArrayRef<Expr *> Args, 5821 OverloadCandidateSet &CandidateSet, 5822 bool SuppressUserConversions) { 5823 const FunctionProtoType *Proto 5824 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5825 assert(Proto && "Methods without a prototype cannot be overloaded"); 5826 assert(!isa<CXXConstructorDecl>(Method) && 5827 "Use AddOverloadCandidate for constructors"); 5828 5829 if (!CandidateSet.isNewCandidate(Method)) 5830 return; 5831 5832 // C++11 [class.copy]p23: [DR1402] 5833 // A defaulted move assignment operator that is defined as deleted is 5834 // ignored by overload resolution. 5835 if (Method->isDefaulted() && Method->isDeleted() && 5836 Method->isMoveAssignmentOperator()) 5837 return; 5838 5839 // Overload resolution is always an unevaluated context. 5840 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5841 5842 // Add this candidate 5843 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5844 Candidate.FoundDecl = FoundDecl; 5845 Candidate.Function = Method; 5846 Candidate.IsSurrogate = false; 5847 Candidate.IgnoreObjectArgument = false; 5848 Candidate.ExplicitCallArguments = Args.size(); 5849 5850 unsigned NumParams = Proto->getNumParams(); 5851 5852 // (C++ 13.3.2p2): A candidate function having fewer than m 5853 // parameters is viable only if it has an ellipsis in its parameter 5854 // list (8.3.5). 5855 if (Args.size() > NumParams && !Proto->isVariadic()) { 5856 Candidate.Viable = false; 5857 Candidate.FailureKind = ovl_fail_too_many_arguments; 5858 return; 5859 } 5860 5861 // (C++ 13.3.2p2): A candidate function having more than m parameters 5862 // is viable only if the (m+1)st parameter has a default argument 5863 // (8.3.6). For the purposes of overload resolution, the 5864 // parameter list is truncated on the right, so that there are 5865 // exactly m parameters. 5866 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 5867 if (Args.size() < MinRequiredArgs) { 5868 // Not enough arguments. 5869 Candidate.Viable = false; 5870 Candidate.FailureKind = ovl_fail_too_few_arguments; 5871 return; 5872 } 5873 5874 Candidate.Viable = true; 5875 5876 if (Method->isStatic() || ObjectType.isNull()) 5877 // The implicit object argument is ignored. 5878 Candidate.IgnoreObjectArgument = true; 5879 else { 5880 // Determine the implicit conversion sequence for the object 5881 // parameter. 5882 Candidate.Conversions[0] 5883 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 5884 Method, ActingContext); 5885 if (Candidate.Conversions[0].isBad()) { 5886 Candidate.Viable = false; 5887 Candidate.FailureKind = ovl_fail_bad_conversion; 5888 return; 5889 } 5890 } 5891 5892 // Determine the implicit conversion sequences for each of the 5893 // arguments. 5894 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5895 if (ArgIdx < NumParams) { 5896 // (C++ 13.3.2p3): for F to be a viable function, there shall 5897 // exist for each argument an implicit conversion sequence 5898 // (13.3.3.1) that converts that argument to the corresponding 5899 // parameter of F. 5900 QualType ParamType = Proto->getParamType(ArgIdx); 5901 Candidate.Conversions[ArgIdx + 1] 5902 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5903 SuppressUserConversions, 5904 /*InOverloadResolution=*/true, 5905 /*AllowObjCWritebackConversion=*/ 5906 getLangOpts().ObjCAutoRefCount); 5907 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5908 Candidate.Viable = false; 5909 Candidate.FailureKind = ovl_fail_bad_conversion; 5910 return; 5911 } 5912 } else { 5913 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5914 // argument for which there is no corresponding parameter is 5915 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 5916 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5917 } 5918 } 5919 5920 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 5921 Candidate.Viable = false; 5922 Candidate.FailureKind = ovl_fail_enable_if; 5923 Candidate.DeductionFailure.Data = FailedAttr; 5924 return; 5925 } 5926 } 5927 5928 /// \brief Add a C++ member function template as a candidate to the candidate 5929 /// set, using template argument deduction to produce an appropriate member 5930 /// function template specialization. 5931 void 5932 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 5933 DeclAccessPair FoundDecl, 5934 CXXRecordDecl *ActingContext, 5935 TemplateArgumentListInfo *ExplicitTemplateArgs, 5936 QualType ObjectType, 5937 Expr::Classification ObjectClassification, 5938 ArrayRef<Expr *> Args, 5939 OverloadCandidateSet& CandidateSet, 5940 bool SuppressUserConversions) { 5941 if (!CandidateSet.isNewCandidate(MethodTmpl)) 5942 return; 5943 5944 // C++ [over.match.funcs]p7: 5945 // In each case where a candidate is a function template, candidate 5946 // function template specializations are generated using template argument 5947 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5948 // candidate functions in the usual way.113) A given name can refer to one 5949 // or more function templates and also to a set of overloaded non-template 5950 // functions. In such a case, the candidate functions generated from each 5951 // function template are combined with the set of non-template candidate 5952 // functions. 5953 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5954 FunctionDecl *Specialization = 0; 5955 if (TemplateDeductionResult Result 5956 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 5957 Specialization, Info)) { 5958 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5959 Candidate.FoundDecl = FoundDecl; 5960 Candidate.Function = MethodTmpl->getTemplatedDecl(); 5961 Candidate.Viable = false; 5962 Candidate.FailureKind = ovl_fail_bad_deduction; 5963 Candidate.IsSurrogate = false; 5964 Candidate.IgnoreObjectArgument = false; 5965 Candidate.ExplicitCallArguments = Args.size(); 5966 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5967 Info); 5968 return; 5969 } 5970 5971 // Add the function template specialization produced by template argument 5972 // deduction as a candidate. 5973 assert(Specialization && "Missing member function template specialization?"); 5974 assert(isa<CXXMethodDecl>(Specialization) && 5975 "Specialization is not a member function?"); 5976 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 5977 ActingContext, ObjectType, ObjectClassification, Args, 5978 CandidateSet, SuppressUserConversions); 5979 } 5980 5981 /// \brief Add a C++ function template specialization as a candidate 5982 /// in the candidate set, using template argument deduction to produce 5983 /// an appropriate function template specialization. 5984 void 5985 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 5986 DeclAccessPair FoundDecl, 5987 TemplateArgumentListInfo *ExplicitTemplateArgs, 5988 ArrayRef<Expr *> Args, 5989 OverloadCandidateSet& CandidateSet, 5990 bool SuppressUserConversions) { 5991 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5992 return; 5993 5994 // C++ [over.match.funcs]p7: 5995 // In each case where a candidate is a function template, candidate 5996 // function template specializations are generated using template argument 5997 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5998 // candidate functions in the usual way.113) A given name can refer to one 5999 // or more function templates and also to a set of overloaded non-template 6000 // functions. In such a case, the candidate functions generated from each 6001 // function template are combined with the set of non-template candidate 6002 // functions. 6003 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6004 FunctionDecl *Specialization = 0; 6005 if (TemplateDeductionResult Result 6006 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 6007 Specialization, Info)) { 6008 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6009 Candidate.FoundDecl = FoundDecl; 6010 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6011 Candidate.Viable = false; 6012 Candidate.FailureKind = ovl_fail_bad_deduction; 6013 Candidate.IsSurrogate = false; 6014 Candidate.IgnoreObjectArgument = false; 6015 Candidate.ExplicitCallArguments = Args.size(); 6016 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6017 Info); 6018 return; 6019 } 6020 6021 // Add the function template specialization produced by template argument 6022 // deduction as a candidate. 6023 assert(Specialization && "Missing function template specialization?"); 6024 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6025 SuppressUserConversions); 6026 } 6027 6028 /// Determine whether this is an allowable conversion from the result 6029 /// of an explicit conversion operator to the expected type, per C++ 6030 /// [over.match.conv]p1 and [over.match.ref]p1. 6031 /// 6032 /// \param ConvType The return type of the conversion function. 6033 /// 6034 /// \param ToType The type we are converting to. 6035 /// 6036 /// \param AllowObjCPointerConversion Allow a conversion from one 6037 /// Objective-C pointer to another. 6038 /// 6039 /// \returns true if the conversion is allowable, false otherwise. 6040 static bool isAllowableExplicitConversion(Sema &S, 6041 QualType ConvType, QualType ToType, 6042 bool AllowObjCPointerConversion) { 6043 QualType ToNonRefType = ToType.getNonReferenceType(); 6044 6045 // Easy case: the types are the same. 6046 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6047 return true; 6048 6049 // Allow qualification conversions. 6050 bool ObjCLifetimeConversion; 6051 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6052 ObjCLifetimeConversion)) 6053 return true; 6054 6055 // If we're not allowed to consider Objective-C pointer conversions, 6056 // we're done. 6057 if (!AllowObjCPointerConversion) 6058 return false; 6059 6060 // Is this an Objective-C pointer conversion? 6061 bool IncompatibleObjC = false; 6062 QualType ConvertedType; 6063 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6064 IncompatibleObjC); 6065 } 6066 6067 /// AddConversionCandidate - Add a C++ conversion function as a 6068 /// candidate in the candidate set (C++ [over.match.conv], 6069 /// C++ [over.match.copy]). From is the expression we're converting from, 6070 /// and ToType is the type that we're eventually trying to convert to 6071 /// (which may or may not be the same type as the type that the 6072 /// conversion function produces). 6073 void 6074 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6075 DeclAccessPair FoundDecl, 6076 CXXRecordDecl *ActingContext, 6077 Expr *From, QualType ToType, 6078 OverloadCandidateSet& CandidateSet, 6079 bool AllowObjCConversionOnExplicit) { 6080 assert(!Conversion->getDescribedFunctionTemplate() && 6081 "Conversion function templates use AddTemplateConversionCandidate"); 6082 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6083 if (!CandidateSet.isNewCandidate(Conversion)) 6084 return; 6085 6086 // If the conversion function has an undeduced return type, trigger its 6087 // deduction now. 6088 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) { 6089 if (DeduceReturnType(Conversion, From->getExprLoc())) 6090 return; 6091 ConvType = Conversion->getConversionType().getNonReferenceType(); 6092 } 6093 6094 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6095 // operator is only a candidate if its return type is the target type or 6096 // can be converted to the target type with a qualification conversion. 6097 if (Conversion->isExplicit() && 6098 !isAllowableExplicitConversion(*this, ConvType, ToType, 6099 AllowObjCConversionOnExplicit)) 6100 return; 6101 6102 // Overload resolution is always an unevaluated context. 6103 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6104 6105 // Add this candidate 6106 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6107 Candidate.FoundDecl = FoundDecl; 6108 Candidate.Function = Conversion; 6109 Candidate.IsSurrogate = false; 6110 Candidate.IgnoreObjectArgument = false; 6111 Candidate.FinalConversion.setAsIdentityConversion(); 6112 Candidate.FinalConversion.setFromType(ConvType); 6113 Candidate.FinalConversion.setAllToTypes(ToType); 6114 Candidate.Viable = true; 6115 Candidate.ExplicitCallArguments = 1; 6116 6117 // C++ [over.match.funcs]p4: 6118 // For conversion functions, the function is considered to be a member of 6119 // the class of the implicit implied object argument for the purpose of 6120 // defining the type of the implicit object parameter. 6121 // 6122 // Determine the implicit conversion sequence for the implicit 6123 // object parameter. 6124 QualType ImplicitParamType = From->getType(); 6125 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6126 ImplicitParamType = FromPtrType->getPointeeType(); 6127 CXXRecordDecl *ConversionContext 6128 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6129 6130 Candidate.Conversions[0] 6131 = TryObjectArgumentInitialization(*this, From->getType(), 6132 From->Classify(Context), 6133 Conversion, ConversionContext); 6134 6135 if (Candidate.Conversions[0].isBad()) { 6136 Candidate.Viable = false; 6137 Candidate.FailureKind = ovl_fail_bad_conversion; 6138 return; 6139 } 6140 6141 // We won't go through a user-defined type conversion function to convert a 6142 // derived to base as such conversions are given Conversion Rank. They only 6143 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6144 QualType FromCanon 6145 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6146 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6147 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 6148 Candidate.Viable = false; 6149 Candidate.FailureKind = ovl_fail_trivial_conversion; 6150 return; 6151 } 6152 6153 // To determine what the conversion from the result of calling the 6154 // conversion function to the type we're eventually trying to 6155 // convert to (ToType), we need to synthesize a call to the 6156 // conversion function and attempt copy initialization from it. This 6157 // makes sure that we get the right semantics with respect to 6158 // lvalues/rvalues and the type. Fortunately, we can allocate this 6159 // call on the stack and we don't need its arguments to be 6160 // well-formed. 6161 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6162 VK_LValue, From->getLocStart()); 6163 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6164 Context.getPointerType(Conversion->getType()), 6165 CK_FunctionToPointerDecay, 6166 &ConversionRef, VK_RValue); 6167 6168 QualType ConversionType = Conversion->getConversionType(); 6169 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 6170 Candidate.Viable = false; 6171 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6172 return; 6173 } 6174 6175 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6176 6177 // Note that it is safe to allocate CallExpr on the stack here because 6178 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6179 // allocator). 6180 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6181 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6182 From->getLocStart()); 6183 ImplicitConversionSequence ICS = 6184 TryCopyInitialization(*this, &Call, ToType, 6185 /*SuppressUserConversions=*/true, 6186 /*InOverloadResolution=*/false, 6187 /*AllowObjCWritebackConversion=*/false); 6188 6189 switch (ICS.getKind()) { 6190 case ImplicitConversionSequence::StandardConversion: 6191 Candidate.FinalConversion = ICS.Standard; 6192 6193 // C++ [over.ics.user]p3: 6194 // If the user-defined conversion is specified by a specialization of a 6195 // conversion function template, the second standard conversion sequence 6196 // shall have exact match rank. 6197 if (Conversion->getPrimaryTemplate() && 6198 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6199 Candidate.Viable = false; 6200 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6201 return; 6202 } 6203 6204 // C++0x [dcl.init.ref]p5: 6205 // In the second case, if the reference is an rvalue reference and 6206 // the second standard conversion sequence of the user-defined 6207 // conversion sequence includes an lvalue-to-rvalue conversion, the 6208 // program is ill-formed. 6209 if (ToType->isRValueReferenceType() && 6210 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6211 Candidate.Viable = false; 6212 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6213 return; 6214 } 6215 break; 6216 6217 case ImplicitConversionSequence::BadConversion: 6218 Candidate.Viable = false; 6219 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6220 return; 6221 6222 default: 6223 llvm_unreachable( 6224 "Can only end up with a standard conversion sequence or failure"); 6225 } 6226 6227 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) { 6228 Candidate.Viable = false; 6229 Candidate.FailureKind = ovl_fail_enable_if; 6230 Candidate.DeductionFailure.Data = FailedAttr; 6231 return; 6232 } 6233 } 6234 6235 /// \brief Adds a conversion function template specialization 6236 /// candidate to the overload set, using template argument deduction 6237 /// to deduce the template arguments of the conversion function 6238 /// template from the type that we are converting to (C++ 6239 /// [temp.deduct.conv]). 6240 void 6241 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6242 DeclAccessPair FoundDecl, 6243 CXXRecordDecl *ActingDC, 6244 Expr *From, QualType ToType, 6245 OverloadCandidateSet &CandidateSet, 6246 bool AllowObjCConversionOnExplicit) { 6247 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6248 "Only conversion function templates permitted here"); 6249 6250 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6251 return; 6252 6253 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6254 CXXConversionDecl *Specialization = 0; 6255 if (TemplateDeductionResult Result 6256 = DeduceTemplateArguments(FunctionTemplate, ToType, 6257 Specialization, Info)) { 6258 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6259 Candidate.FoundDecl = FoundDecl; 6260 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6261 Candidate.Viable = false; 6262 Candidate.FailureKind = ovl_fail_bad_deduction; 6263 Candidate.IsSurrogate = false; 6264 Candidate.IgnoreObjectArgument = false; 6265 Candidate.ExplicitCallArguments = 1; 6266 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6267 Info); 6268 return; 6269 } 6270 6271 // Add the conversion function template specialization produced by 6272 // template argument deduction as a candidate. 6273 assert(Specialization && "Missing function template specialization?"); 6274 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6275 CandidateSet, AllowObjCConversionOnExplicit); 6276 } 6277 6278 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6279 /// converts the given @c Object to a function pointer via the 6280 /// conversion function @c Conversion, and then attempts to call it 6281 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6282 /// the type of function that we'll eventually be calling. 6283 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6284 DeclAccessPair FoundDecl, 6285 CXXRecordDecl *ActingContext, 6286 const FunctionProtoType *Proto, 6287 Expr *Object, 6288 ArrayRef<Expr *> Args, 6289 OverloadCandidateSet& CandidateSet) { 6290 if (!CandidateSet.isNewCandidate(Conversion)) 6291 return; 6292 6293 // Overload resolution is always an unevaluated context. 6294 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6295 6296 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6297 Candidate.FoundDecl = FoundDecl; 6298 Candidate.Function = 0; 6299 Candidate.Surrogate = Conversion; 6300 Candidate.Viable = true; 6301 Candidate.IsSurrogate = true; 6302 Candidate.IgnoreObjectArgument = false; 6303 Candidate.ExplicitCallArguments = Args.size(); 6304 6305 // Determine the implicit conversion sequence for the implicit 6306 // object parameter. 6307 ImplicitConversionSequence ObjectInit 6308 = TryObjectArgumentInitialization(*this, Object->getType(), 6309 Object->Classify(Context), 6310 Conversion, ActingContext); 6311 if (ObjectInit.isBad()) { 6312 Candidate.Viable = false; 6313 Candidate.FailureKind = ovl_fail_bad_conversion; 6314 Candidate.Conversions[0] = ObjectInit; 6315 return; 6316 } 6317 6318 // The first conversion is actually a user-defined conversion whose 6319 // first conversion is ObjectInit's standard conversion (which is 6320 // effectively a reference binding). Record it as such. 6321 Candidate.Conversions[0].setUserDefined(); 6322 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6323 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6324 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6325 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6326 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6327 Candidate.Conversions[0].UserDefined.After 6328 = Candidate.Conversions[0].UserDefined.Before; 6329 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6330 6331 // Find the 6332 unsigned NumParams = Proto->getNumParams(); 6333 6334 // (C++ 13.3.2p2): A candidate function having fewer than m 6335 // parameters is viable only if it has an ellipsis in its parameter 6336 // list (8.3.5). 6337 if (Args.size() > NumParams && !Proto->isVariadic()) { 6338 Candidate.Viable = false; 6339 Candidate.FailureKind = ovl_fail_too_many_arguments; 6340 return; 6341 } 6342 6343 // Function types don't have any default arguments, so just check if 6344 // we have enough arguments. 6345 if (Args.size() < NumParams) { 6346 // Not enough arguments. 6347 Candidate.Viable = false; 6348 Candidate.FailureKind = ovl_fail_too_few_arguments; 6349 return; 6350 } 6351 6352 // Determine the implicit conversion sequences for each of the 6353 // arguments. 6354 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6355 if (ArgIdx < NumParams) { 6356 // (C++ 13.3.2p3): for F to be a viable function, there shall 6357 // exist for each argument an implicit conversion sequence 6358 // (13.3.3.1) that converts that argument to the corresponding 6359 // parameter of F. 6360 QualType ParamType = Proto->getParamType(ArgIdx); 6361 Candidate.Conversions[ArgIdx + 1] 6362 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6363 /*SuppressUserConversions=*/false, 6364 /*InOverloadResolution=*/false, 6365 /*AllowObjCWritebackConversion=*/ 6366 getLangOpts().ObjCAutoRefCount); 6367 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6368 Candidate.Viable = false; 6369 Candidate.FailureKind = ovl_fail_bad_conversion; 6370 return; 6371 } 6372 } else { 6373 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6374 // argument for which there is no corresponding parameter is 6375 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6376 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6377 } 6378 } 6379 6380 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) { 6381 Candidate.Viable = false; 6382 Candidate.FailureKind = ovl_fail_enable_if; 6383 Candidate.DeductionFailure.Data = FailedAttr; 6384 return; 6385 } 6386 } 6387 6388 /// \brief Add overload candidates for overloaded operators that are 6389 /// member functions. 6390 /// 6391 /// Add the overloaded operator candidates that are member functions 6392 /// for the operator Op that was used in an operator expression such 6393 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6394 /// CandidateSet will store the added overload candidates. (C++ 6395 /// [over.match.oper]). 6396 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6397 SourceLocation OpLoc, 6398 ArrayRef<Expr *> Args, 6399 OverloadCandidateSet& CandidateSet, 6400 SourceRange OpRange) { 6401 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6402 6403 // C++ [over.match.oper]p3: 6404 // For a unary operator @ with an operand of a type whose 6405 // cv-unqualified version is T1, and for a binary operator @ with 6406 // a left operand of a type whose cv-unqualified version is T1 and 6407 // a right operand of a type whose cv-unqualified version is T2, 6408 // three sets of candidate functions, designated member 6409 // candidates, non-member candidates and built-in candidates, are 6410 // constructed as follows: 6411 QualType T1 = Args[0]->getType(); 6412 6413 // -- If T1 is a complete class type or a class currently being 6414 // defined, the set of member candidates is the result of the 6415 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6416 // the set of member candidates is empty. 6417 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6418 // Complete the type if it can be completed. 6419 RequireCompleteType(OpLoc, T1, 0); 6420 // If the type is neither complete nor being defined, bail out now. 6421 if (!T1Rec->getDecl()->getDefinition()) 6422 return; 6423 6424 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6425 LookupQualifiedName(Operators, T1Rec->getDecl()); 6426 Operators.suppressDiagnostics(); 6427 6428 for (LookupResult::iterator Oper = Operators.begin(), 6429 OperEnd = Operators.end(); 6430 Oper != OperEnd; 6431 ++Oper) 6432 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6433 Args[0]->Classify(Context), 6434 Args.slice(1), 6435 CandidateSet, 6436 /* SuppressUserConversions = */ false); 6437 } 6438 } 6439 6440 /// AddBuiltinCandidate - Add a candidate for a built-in 6441 /// operator. ResultTy and ParamTys are the result and parameter types 6442 /// of the built-in candidate, respectively. Args and NumArgs are the 6443 /// arguments being passed to the candidate. IsAssignmentOperator 6444 /// should be true when this built-in candidate is an assignment 6445 /// operator. NumContextualBoolArguments is the number of arguments 6446 /// (at the beginning of the argument list) that will be contextually 6447 /// converted to bool. 6448 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6449 ArrayRef<Expr *> Args, 6450 OverloadCandidateSet& CandidateSet, 6451 bool IsAssignmentOperator, 6452 unsigned NumContextualBoolArguments) { 6453 // Overload resolution is always an unevaluated context. 6454 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6455 6456 // Add this candidate 6457 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6458 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 6459 Candidate.Function = 0; 6460 Candidate.IsSurrogate = false; 6461 Candidate.IgnoreObjectArgument = false; 6462 Candidate.BuiltinTypes.ResultTy = ResultTy; 6463 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6464 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6465 6466 // Determine the implicit conversion sequences for each of the 6467 // arguments. 6468 Candidate.Viable = true; 6469 Candidate.ExplicitCallArguments = Args.size(); 6470 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6471 // C++ [over.match.oper]p4: 6472 // For the built-in assignment operators, conversions of the 6473 // left operand are restricted as follows: 6474 // -- no temporaries are introduced to hold the left operand, and 6475 // -- no user-defined conversions are applied to the left 6476 // operand to achieve a type match with the left-most 6477 // parameter of a built-in candidate. 6478 // 6479 // We block these conversions by turning off user-defined 6480 // conversions, since that is the only way that initialization of 6481 // a reference to a non-class type can occur from something that 6482 // is not of the same type. 6483 if (ArgIdx < NumContextualBoolArguments) { 6484 assert(ParamTys[ArgIdx] == Context.BoolTy && 6485 "Contextual conversion to bool requires bool type"); 6486 Candidate.Conversions[ArgIdx] 6487 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6488 } else { 6489 Candidate.Conversions[ArgIdx] 6490 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6491 ArgIdx == 0 && IsAssignmentOperator, 6492 /*InOverloadResolution=*/false, 6493 /*AllowObjCWritebackConversion=*/ 6494 getLangOpts().ObjCAutoRefCount); 6495 } 6496 if (Candidate.Conversions[ArgIdx].isBad()) { 6497 Candidate.Viable = false; 6498 Candidate.FailureKind = ovl_fail_bad_conversion; 6499 break; 6500 } 6501 } 6502 } 6503 6504 namespace { 6505 6506 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6507 /// candidate operator functions for built-in operators (C++ 6508 /// [over.built]). The types are separated into pointer types and 6509 /// enumeration types. 6510 class BuiltinCandidateTypeSet { 6511 /// TypeSet - A set of types. 6512 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6513 6514 /// PointerTypes - The set of pointer types that will be used in the 6515 /// built-in candidates. 6516 TypeSet PointerTypes; 6517 6518 /// MemberPointerTypes - The set of member pointer types that will be 6519 /// used in the built-in candidates. 6520 TypeSet MemberPointerTypes; 6521 6522 /// EnumerationTypes - The set of enumeration types that will be 6523 /// used in the built-in candidates. 6524 TypeSet EnumerationTypes; 6525 6526 /// \brief The set of vector types that will be used in the built-in 6527 /// candidates. 6528 TypeSet VectorTypes; 6529 6530 /// \brief A flag indicating non-record types are viable candidates 6531 bool HasNonRecordTypes; 6532 6533 /// \brief A flag indicating whether either arithmetic or enumeration types 6534 /// were present in the candidate set. 6535 bool HasArithmeticOrEnumeralTypes; 6536 6537 /// \brief A flag indicating whether the nullptr type was present in the 6538 /// candidate set. 6539 bool HasNullPtrType; 6540 6541 /// Sema - The semantic analysis instance where we are building the 6542 /// candidate type set. 6543 Sema &SemaRef; 6544 6545 /// Context - The AST context in which we will build the type sets. 6546 ASTContext &Context; 6547 6548 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6549 const Qualifiers &VisibleQuals); 6550 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6551 6552 public: 6553 /// iterator - Iterates through the types that are part of the set. 6554 typedef TypeSet::iterator iterator; 6555 6556 BuiltinCandidateTypeSet(Sema &SemaRef) 6557 : HasNonRecordTypes(false), 6558 HasArithmeticOrEnumeralTypes(false), 6559 HasNullPtrType(false), 6560 SemaRef(SemaRef), 6561 Context(SemaRef.Context) { } 6562 6563 void AddTypesConvertedFrom(QualType Ty, 6564 SourceLocation Loc, 6565 bool AllowUserConversions, 6566 bool AllowExplicitConversions, 6567 const Qualifiers &VisibleTypeConversionsQuals); 6568 6569 /// pointer_begin - First pointer type found; 6570 iterator pointer_begin() { return PointerTypes.begin(); } 6571 6572 /// pointer_end - Past the last pointer type found; 6573 iterator pointer_end() { return PointerTypes.end(); } 6574 6575 /// member_pointer_begin - First member pointer type found; 6576 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6577 6578 /// member_pointer_end - Past the last member pointer type found; 6579 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6580 6581 /// enumeration_begin - First enumeration type found; 6582 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6583 6584 /// enumeration_end - Past the last enumeration type found; 6585 iterator enumeration_end() { return EnumerationTypes.end(); } 6586 6587 iterator vector_begin() { return VectorTypes.begin(); } 6588 iterator vector_end() { return VectorTypes.end(); } 6589 6590 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6591 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6592 bool hasNullPtrType() const { return HasNullPtrType; } 6593 }; 6594 6595 } // end anonymous namespace 6596 6597 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6598 /// the set of pointer types along with any more-qualified variants of 6599 /// that type. For example, if @p Ty is "int const *", this routine 6600 /// will add "int const *", "int const volatile *", "int const 6601 /// restrict *", and "int const volatile restrict *" to the set of 6602 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6603 /// false otherwise. 6604 /// 6605 /// FIXME: what to do about extended qualifiers? 6606 bool 6607 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6608 const Qualifiers &VisibleQuals) { 6609 6610 // Insert this type. 6611 if (!PointerTypes.insert(Ty)) 6612 return false; 6613 6614 QualType PointeeTy; 6615 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6616 bool buildObjCPtr = false; 6617 if (!PointerTy) { 6618 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6619 PointeeTy = PTy->getPointeeType(); 6620 buildObjCPtr = true; 6621 } else { 6622 PointeeTy = PointerTy->getPointeeType(); 6623 } 6624 6625 // Don't add qualified variants of arrays. For one, they're not allowed 6626 // (the qualifier would sink to the element type), and for another, the 6627 // only overload situation where it matters is subscript or pointer +- int, 6628 // and those shouldn't have qualifier variants anyway. 6629 if (PointeeTy->isArrayType()) 6630 return true; 6631 6632 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6633 bool hasVolatile = VisibleQuals.hasVolatile(); 6634 bool hasRestrict = VisibleQuals.hasRestrict(); 6635 6636 // Iterate through all strict supersets of BaseCVR. 6637 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6638 if ((CVR | BaseCVR) != CVR) continue; 6639 // Skip over volatile if no volatile found anywhere in the types. 6640 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6641 6642 // Skip over restrict if no restrict found anywhere in the types, or if 6643 // the type cannot be restrict-qualified. 6644 if ((CVR & Qualifiers::Restrict) && 6645 (!hasRestrict || 6646 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6647 continue; 6648 6649 // Build qualified pointee type. 6650 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6651 6652 // Build qualified pointer type. 6653 QualType QPointerTy; 6654 if (!buildObjCPtr) 6655 QPointerTy = Context.getPointerType(QPointeeTy); 6656 else 6657 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6658 6659 // Insert qualified pointer type. 6660 PointerTypes.insert(QPointerTy); 6661 } 6662 6663 return true; 6664 } 6665 6666 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6667 /// to the set of pointer types along with any more-qualified variants of 6668 /// that type. For example, if @p Ty is "int const *", this routine 6669 /// will add "int const *", "int const volatile *", "int const 6670 /// restrict *", and "int const volatile restrict *" to the set of 6671 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6672 /// false otherwise. 6673 /// 6674 /// FIXME: what to do about extended qualifiers? 6675 bool 6676 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6677 QualType Ty) { 6678 // Insert this type. 6679 if (!MemberPointerTypes.insert(Ty)) 6680 return false; 6681 6682 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6683 assert(PointerTy && "type was not a member pointer type!"); 6684 6685 QualType PointeeTy = PointerTy->getPointeeType(); 6686 // Don't add qualified variants of arrays. For one, they're not allowed 6687 // (the qualifier would sink to the element type), and for another, the 6688 // only overload situation where it matters is subscript or pointer +- int, 6689 // and those shouldn't have qualifier variants anyway. 6690 if (PointeeTy->isArrayType()) 6691 return true; 6692 const Type *ClassTy = PointerTy->getClass(); 6693 6694 // Iterate through all strict supersets of the pointee type's CVR 6695 // qualifiers. 6696 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6697 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6698 if ((CVR | BaseCVR) != CVR) continue; 6699 6700 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6701 MemberPointerTypes.insert( 6702 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6703 } 6704 6705 return true; 6706 } 6707 6708 /// AddTypesConvertedFrom - Add each of the types to which the type @p 6709 /// Ty can be implicit converted to the given set of @p Types. We're 6710 /// primarily interested in pointer types and enumeration types. We also 6711 /// take member pointer types, for the conditional operator. 6712 /// AllowUserConversions is true if we should look at the conversion 6713 /// functions of a class type, and AllowExplicitConversions if we 6714 /// should also include the explicit conversion functions of a class 6715 /// type. 6716 void 6717 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6718 SourceLocation Loc, 6719 bool AllowUserConversions, 6720 bool AllowExplicitConversions, 6721 const Qualifiers &VisibleQuals) { 6722 // Only deal with canonical types. 6723 Ty = Context.getCanonicalType(Ty); 6724 6725 // Look through reference types; they aren't part of the type of an 6726 // expression for the purposes of conversions. 6727 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6728 Ty = RefTy->getPointeeType(); 6729 6730 // If we're dealing with an array type, decay to the pointer. 6731 if (Ty->isArrayType()) 6732 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6733 6734 // Otherwise, we don't care about qualifiers on the type. 6735 Ty = Ty.getLocalUnqualifiedType(); 6736 6737 // Flag if we ever add a non-record type. 6738 const RecordType *TyRec = Ty->getAs<RecordType>(); 6739 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6740 6741 // Flag if we encounter an arithmetic type. 6742 HasArithmeticOrEnumeralTypes = 6743 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6744 6745 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6746 PointerTypes.insert(Ty); 6747 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6748 // Insert our type, and its more-qualified variants, into the set 6749 // of types. 6750 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6751 return; 6752 } else if (Ty->isMemberPointerType()) { 6753 // Member pointers are far easier, since the pointee can't be converted. 6754 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6755 return; 6756 } else if (Ty->isEnumeralType()) { 6757 HasArithmeticOrEnumeralTypes = true; 6758 EnumerationTypes.insert(Ty); 6759 } else if (Ty->isVectorType()) { 6760 // We treat vector types as arithmetic types in many contexts as an 6761 // extension. 6762 HasArithmeticOrEnumeralTypes = true; 6763 VectorTypes.insert(Ty); 6764 } else if (Ty->isNullPtrType()) { 6765 HasNullPtrType = true; 6766 } else if (AllowUserConversions && TyRec) { 6767 // No conversion functions in incomplete types. 6768 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6769 return; 6770 6771 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6772 std::pair<CXXRecordDecl::conversion_iterator, 6773 CXXRecordDecl::conversion_iterator> 6774 Conversions = ClassDecl->getVisibleConversionFunctions(); 6775 for (CXXRecordDecl::conversion_iterator 6776 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6777 NamedDecl *D = I.getDecl(); 6778 if (isa<UsingShadowDecl>(D)) 6779 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6780 6781 // Skip conversion function templates; they don't tell us anything 6782 // about which builtin types we can convert to. 6783 if (isa<FunctionTemplateDecl>(D)) 6784 continue; 6785 6786 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6787 if (AllowExplicitConversions || !Conv->isExplicit()) { 6788 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6789 VisibleQuals); 6790 } 6791 } 6792 } 6793 } 6794 6795 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6796 /// the volatile- and non-volatile-qualified assignment operators for the 6797 /// given type to the candidate set. 6798 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6799 QualType T, 6800 ArrayRef<Expr *> Args, 6801 OverloadCandidateSet &CandidateSet) { 6802 QualType ParamTypes[2]; 6803 6804 // T& operator=(T&, T) 6805 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6806 ParamTypes[1] = T; 6807 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6808 /*IsAssignmentOperator=*/true); 6809 6810 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6811 // volatile T& operator=(volatile T&, T) 6812 ParamTypes[0] 6813 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6814 ParamTypes[1] = T; 6815 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6816 /*IsAssignmentOperator=*/true); 6817 } 6818 } 6819 6820 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6821 /// if any, found in visible type conversion functions found in ArgExpr's type. 6822 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6823 Qualifiers VRQuals; 6824 const RecordType *TyRec; 6825 if (const MemberPointerType *RHSMPType = 6826 ArgExpr->getType()->getAs<MemberPointerType>()) 6827 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6828 else 6829 TyRec = ArgExpr->getType()->getAs<RecordType>(); 6830 if (!TyRec) { 6831 // Just to be safe, assume the worst case. 6832 VRQuals.addVolatile(); 6833 VRQuals.addRestrict(); 6834 return VRQuals; 6835 } 6836 6837 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6838 if (!ClassDecl->hasDefinition()) 6839 return VRQuals; 6840 6841 std::pair<CXXRecordDecl::conversion_iterator, 6842 CXXRecordDecl::conversion_iterator> 6843 Conversions = ClassDecl->getVisibleConversionFunctions(); 6844 6845 for (CXXRecordDecl::conversion_iterator 6846 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6847 NamedDecl *D = I.getDecl(); 6848 if (isa<UsingShadowDecl>(D)) 6849 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6850 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6851 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 6852 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 6853 CanTy = ResTypeRef->getPointeeType(); 6854 // Need to go down the pointer/mempointer chain and add qualifiers 6855 // as see them. 6856 bool done = false; 6857 while (!done) { 6858 if (CanTy.isRestrictQualified()) 6859 VRQuals.addRestrict(); 6860 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 6861 CanTy = ResTypePtr->getPointeeType(); 6862 else if (const MemberPointerType *ResTypeMPtr = 6863 CanTy->getAs<MemberPointerType>()) 6864 CanTy = ResTypeMPtr->getPointeeType(); 6865 else 6866 done = true; 6867 if (CanTy.isVolatileQualified()) 6868 VRQuals.addVolatile(); 6869 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 6870 return VRQuals; 6871 } 6872 } 6873 } 6874 return VRQuals; 6875 } 6876 6877 namespace { 6878 6879 /// \brief Helper class to manage the addition of builtin operator overload 6880 /// candidates. It provides shared state and utility methods used throughout 6881 /// the process, as well as a helper method to add each group of builtin 6882 /// operator overloads from the standard to a candidate set. 6883 class BuiltinOperatorOverloadBuilder { 6884 // Common instance state available to all overload candidate addition methods. 6885 Sema &S; 6886 ArrayRef<Expr *> Args; 6887 Qualifiers VisibleTypeConversionsQuals; 6888 bool HasArithmeticOrEnumeralCandidateType; 6889 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 6890 OverloadCandidateSet &CandidateSet; 6891 6892 // Define some constants used to index and iterate over the arithemetic types 6893 // provided via the getArithmeticType() method below. 6894 // The "promoted arithmetic types" are the arithmetic 6895 // types are that preserved by promotion (C++ [over.built]p2). 6896 static const unsigned FirstIntegralType = 3; 6897 static const unsigned LastIntegralType = 20; 6898 static const unsigned FirstPromotedIntegralType = 3, 6899 LastPromotedIntegralType = 11; 6900 static const unsigned FirstPromotedArithmeticType = 0, 6901 LastPromotedArithmeticType = 11; 6902 static const unsigned NumArithmeticTypes = 20; 6903 6904 /// \brief Get the canonical type for a given arithmetic type index. 6905 CanQualType getArithmeticType(unsigned index) { 6906 assert(index < NumArithmeticTypes); 6907 static CanQualType ASTContext::* const 6908 ArithmeticTypes[NumArithmeticTypes] = { 6909 // Start of promoted types. 6910 &ASTContext::FloatTy, 6911 &ASTContext::DoubleTy, 6912 &ASTContext::LongDoubleTy, 6913 6914 // Start of integral types. 6915 &ASTContext::IntTy, 6916 &ASTContext::LongTy, 6917 &ASTContext::LongLongTy, 6918 &ASTContext::Int128Ty, 6919 &ASTContext::UnsignedIntTy, 6920 &ASTContext::UnsignedLongTy, 6921 &ASTContext::UnsignedLongLongTy, 6922 &ASTContext::UnsignedInt128Ty, 6923 // End of promoted types. 6924 6925 &ASTContext::BoolTy, 6926 &ASTContext::CharTy, 6927 &ASTContext::WCharTy, 6928 &ASTContext::Char16Ty, 6929 &ASTContext::Char32Ty, 6930 &ASTContext::SignedCharTy, 6931 &ASTContext::ShortTy, 6932 &ASTContext::UnsignedCharTy, 6933 &ASTContext::UnsignedShortTy, 6934 // End of integral types. 6935 // FIXME: What about complex? What about half? 6936 }; 6937 return S.Context.*ArithmeticTypes[index]; 6938 } 6939 6940 /// \brief Gets the canonical type resulting from the usual arithemetic 6941 /// converions for the given arithmetic types. 6942 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 6943 // Accelerator table for performing the usual arithmetic conversions. 6944 // The rules are basically: 6945 // - if either is floating-point, use the wider floating-point 6946 // - if same signedness, use the higher rank 6947 // - if same size, use unsigned of the higher rank 6948 // - use the larger type 6949 // These rules, together with the axiom that higher ranks are 6950 // never smaller, are sufficient to precompute all of these results 6951 // *except* when dealing with signed types of higher rank. 6952 // (we could precompute SLL x UI for all known platforms, but it's 6953 // better not to make any assumptions). 6954 // We assume that int128 has a higher rank than long long on all platforms. 6955 enum PromotedType { 6956 Dep=-1, 6957 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 6958 }; 6959 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 6960 [LastPromotedArithmeticType] = { 6961 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 6962 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 6963 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 6964 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 6965 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 6966 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 6967 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 6968 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 6969 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 6970 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 6971 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 6972 }; 6973 6974 assert(L < LastPromotedArithmeticType); 6975 assert(R < LastPromotedArithmeticType); 6976 int Idx = ConversionsTable[L][R]; 6977 6978 // Fast path: the table gives us a concrete answer. 6979 if (Idx != Dep) return getArithmeticType(Idx); 6980 6981 // Slow path: we need to compare widths. 6982 // An invariant is that the signed type has higher rank. 6983 CanQualType LT = getArithmeticType(L), 6984 RT = getArithmeticType(R); 6985 unsigned LW = S.Context.getIntWidth(LT), 6986 RW = S.Context.getIntWidth(RT); 6987 6988 // If they're different widths, use the signed type. 6989 if (LW > RW) return LT; 6990 else if (LW < RW) return RT; 6991 6992 // Otherwise, use the unsigned type of the signed type's rank. 6993 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 6994 assert(L == SLL || R == SLL); 6995 return S.Context.UnsignedLongLongTy; 6996 } 6997 6998 /// \brief Helper method to factor out the common pattern of adding overloads 6999 /// for '++' and '--' builtin operators. 7000 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7001 bool HasVolatile, 7002 bool HasRestrict) { 7003 QualType ParamTypes[2] = { 7004 S.Context.getLValueReferenceType(CandidateTy), 7005 S.Context.IntTy 7006 }; 7007 7008 // Non-volatile version. 7009 if (Args.size() == 1) 7010 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7011 else 7012 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7013 7014 // Use a heuristic to reduce number of builtin candidates in the set: 7015 // add volatile version only if there are conversions to a volatile type. 7016 if (HasVolatile) { 7017 ParamTypes[0] = 7018 S.Context.getLValueReferenceType( 7019 S.Context.getVolatileType(CandidateTy)); 7020 if (Args.size() == 1) 7021 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7022 else 7023 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7024 } 7025 7026 // Add restrict version only if there are conversions to a restrict type 7027 // and our candidate type is a non-restrict-qualified pointer. 7028 if (HasRestrict && CandidateTy->isAnyPointerType() && 7029 !CandidateTy.isRestrictQualified()) { 7030 ParamTypes[0] 7031 = S.Context.getLValueReferenceType( 7032 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7033 if (Args.size() == 1) 7034 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7035 else 7036 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7037 7038 if (HasVolatile) { 7039 ParamTypes[0] 7040 = S.Context.getLValueReferenceType( 7041 S.Context.getCVRQualifiedType(CandidateTy, 7042 (Qualifiers::Volatile | 7043 Qualifiers::Restrict))); 7044 if (Args.size() == 1) 7045 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7046 else 7047 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7048 } 7049 } 7050 7051 } 7052 7053 public: 7054 BuiltinOperatorOverloadBuilder( 7055 Sema &S, ArrayRef<Expr *> Args, 7056 Qualifiers VisibleTypeConversionsQuals, 7057 bool HasArithmeticOrEnumeralCandidateType, 7058 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7059 OverloadCandidateSet &CandidateSet) 7060 : S(S), Args(Args), 7061 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7062 HasArithmeticOrEnumeralCandidateType( 7063 HasArithmeticOrEnumeralCandidateType), 7064 CandidateTypes(CandidateTypes), 7065 CandidateSet(CandidateSet) { 7066 // Validate some of our static helper constants in debug builds. 7067 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7068 "Invalid first promoted integral type"); 7069 assert(getArithmeticType(LastPromotedIntegralType - 1) 7070 == S.Context.UnsignedInt128Ty && 7071 "Invalid last promoted integral type"); 7072 assert(getArithmeticType(FirstPromotedArithmeticType) 7073 == S.Context.FloatTy && 7074 "Invalid first promoted arithmetic type"); 7075 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7076 == S.Context.UnsignedInt128Ty && 7077 "Invalid last promoted arithmetic type"); 7078 } 7079 7080 // C++ [over.built]p3: 7081 // 7082 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7083 // is either volatile or empty, there exist candidate operator 7084 // functions of the form 7085 // 7086 // VQ T& operator++(VQ T&); 7087 // T operator++(VQ T&, int); 7088 // 7089 // C++ [over.built]p4: 7090 // 7091 // For every pair (T, VQ), where T is an arithmetic type other 7092 // than bool, and VQ is either volatile or empty, there exist 7093 // candidate operator functions of the form 7094 // 7095 // VQ T& operator--(VQ T&); 7096 // T operator--(VQ T&, int); 7097 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7098 if (!HasArithmeticOrEnumeralCandidateType) 7099 return; 7100 7101 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7102 Arith < NumArithmeticTypes; ++Arith) { 7103 addPlusPlusMinusMinusStyleOverloads( 7104 getArithmeticType(Arith), 7105 VisibleTypeConversionsQuals.hasVolatile(), 7106 VisibleTypeConversionsQuals.hasRestrict()); 7107 } 7108 } 7109 7110 // C++ [over.built]p5: 7111 // 7112 // For every pair (T, VQ), where T is a cv-qualified or 7113 // cv-unqualified object type, and VQ is either volatile or 7114 // empty, there exist candidate operator functions of the form 7115 // 7116 // T*VQ& operator++(T*VQ&); 7117 // T*VQ& operator--(T*VQ&); 7118 // T* operator++(T*VQ&, int); 7119 // T* operator--(T*VQ&, int); 7120 void addPlusPlusMinusMinusPointerOverloads() { 7121 for (BuiltinCandidateTypeSet::iterator 7122 Ptr = CandidateTypes[0].pointer_begin(), 7123 PtrEnd = CandidateTypes[0].pointer_end(); 7124 Ptr != PtrEnd; ++Ptr) { 7125 // Skip pointer types that aren't pointers to object types. 7126 if (!(*Ptr)->getPointeeType()->isObjectType()) 7127 continue; 7128 7129 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7130 (!(*Ptr).isVolatileQualified() && 7131 VisibleTypeConversionsQuals.hasVolatile()), 7132 (!(*Ptr).isRestrictQualified() && 7133 VisibleTypeConversionsQuals.hasRestrict())); 7134 } 7135 } 7136 7137 // C++ [over.built]p6: 7138 // For every cv-qualified or cv-unqualified object type T, there 7139 // exist candidate operator functions of the form 7140 // 7141 // T& operator*(T*); 7142 // 7143 // C++ [over.built]p7: 7144 // For every function type T that does not have cv-qualifiers or a 7145 // ref-qualifier, there exist candidate operator functions of the form 7146 // T& operator*(T*); 7147 void addUnaryStarPointerOverloads() { 7148 for (BuiltinCandidateTypeSet::iterator 7149 Ptr = CandidateTypes[0].pointer_begin(), 7150 PtrEnd = CandidateTypes[0].pointer_end(); 7151 Ptr != PtrEnd; ++Ptr) { 7152 QualType ParamTy = *Ptr; 7153 QualType PointeeTy = ParamTy->getPointeeType(); 7154 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7155 continue; 7156 7157 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7158 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7159 continue; 7160 7161 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7162 &ParamTy, Args, CandidateSet); 7163 } 7164 } 7165 7166 // C++ [over.built]p9: 7167 // For every promoted arithmetic type T, there exist candidate 7168 // operator functions of the form 7169 // 7170 // T operator+(T); 7171 // T operator-(T); 7172 void addUnaryPlusOrMinusArithmeticOverloads() { 7173 if (!HasArithmeticOrEnumeralCandidateType) 7174 return; 7175 7176 for (unsigned Arith = FirstPromotedArithmeticType; 7177 Arith < LastPromotedArithmeticType; ++Arith) { 7178 QualType ArithTy = getArithmeticType(Arith); 7179 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7180 } 7181 7182 // Extension: We also add these operators for vector types. 7183 for (BuiltinCandidateTypeSet::iterator 7184 Vec = CandidateTypes[0].vector_begin(), 7185 VecEnd = CandidateTypes[0].vector_end(); 7186 Vec != VecEnd; ++Vec) { 7187 QualType VecTy = *Vec; 7188 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7189 } 7190 } 7191 7192 // C++ [over.built]p8: 7193 // For every type T, there exist candidate operator functions of 7194 // the form 7195 // 7196 // T* operator+(T*); 7197 void addUnaryPlusPointerOverloads() { 7198 for (BuiltinCandidateTypeSet::iterator 7199 Ptr = CandidateTypes[0].pointer_begin(), 7200 PtrEnd = CandidateTypes[0].pointer_end(); 7201 Ptr != PtrEnd; ++Ptr) { 7202 QualType ParamTy = *Ptr; 7203 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7204 } 7205 } 7206 7207 // C++ [over.built]p10: 7208 // For every promoted integral type T, there exist candidate 7209 // operator functions of the form 7210 // 7211 // T operator~(T); 7212 void addUnaryTildePromotedIntegralOverloads() { 7213 if (!HasArithmeticOrEnumeralCandidateType) 7214 return; 7215 7216 for (unsigned Int = FirstPromotedIntegralType; 7217 Int < LastPromotedIntegralType; ++Int) { 7218 QualType IntTy = getArithmeticType(Int); 7219 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7220 } 7221 7222 // Extension: We also add this operator for vector types. 7223 for (BuiltinCandidateTypeSet::iterator 7224 Vec = CandidateTypes[0].vector_begin(), 7225 VecEnd = CandidateTypes[0].vector_end(); 7226 Vec != VecEnd; ++Vec) { 7227 QualType VecTy = *Vec; 7228 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7229 } 7230 } 7231 7232 // C++ [over.match.oper]p16: 7233 // For every pointer to member type T, there exist candidate operator 7234 // functions of the form 7235 // 7236 // bool operator==(T,T); 7237 // bool operator!=(T,T); 7238 void addEqualEqualOrNotEqualMemberPointerOverloads() { 7239 /// Set of (canonical) types that we've already handled. 7240 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7241 7242 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7243 for (BuiltinCandidateTypeSet::iterator 7244 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7245 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7246 MemPtr != MemPtrEnd; 7247 ++MemPtr) { 7248 // Don't add the same builtin candidate twice. 7249 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7250 continue; 7251 7252 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7253 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7254 } 7255 } 7256 } 7257 7258 // C++ [over.built]p15: 7259 // 7260 // For every T, where T is an enumeration type, a pointer type, or 7261 // std::nullptr_t, there exist candidate operator functions of the form 7262 // 7263 // bool operator<(T, T); 7264 // bool operator>(T, T); 7265 // bool operator<=(T, T); 7266 // bool operator>=(T, T); 7267 // bool operator==(T, T); 7268 // bool operator!=(T, T); 7269 void addRelationalPointerOrEnumeralOverloads() { 7270 // C++ [over.match.oper]p3: 7271 // [...]the built-in candidates include all of the candidate operator 7272 // functions defined in 13.6 that, compared to the given operator, [...] 7273 // do not have the same parameter-type-list as any non-template non-member 7274 // candidate. 7275 // 7276 // Note that in practice, this only affects enumeration types because there 7277 // aren't any built-in candidates of record type, and a user-defined operator 7278 // must have an operand of record or enumeration type. Also, the only other 7279 // overloaded operator with enumeration arguments, operator=, 7280 // cannot be overloaded for enumeration types, so this is the only place 7281 // where we must suppress candidates like this. 7282 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7283 UserDefinedBinaryOperators; 7284 7285 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7286 if (CandidateTypes[ArgIdx].enumeration_begin() != 7287 CandidateTypes[ArgIdx].enumeration_end()) { 7288 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7289 CEnd = CandidateSet.end(); 7290 C != CEnd; ++C) { 7291 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7292 continue; 7293 7294 if (C->Function->isFunctionTemplateSpecialization()) 7295 continue; 7296 7297 QualType FirstParamType = 7298 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7299 QualType SecondParamType = 7300 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7301 7302 // Skip if either parameter isn't of enumeral type. 7303 if (!FirstParamType->isEnumeralType() || 7304 !SecondParamType->isEnumeralType()) 7305 continue; 7306 7307 // Add this operator to the set of known user-defined operators. 7308 UserDefinedBinaryOperators.insert( 7309 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7310 S.Context.getCanonicalType(SecondParamType))); 7311 } 7312 } 7313 } 7314 7315 /// Set of (canonical) types that we've already handled. 7316 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7317 7318 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7319 for (BuiltinCandidateTypeSet::iterator 7320 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7321 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7322 Ptr != PtrEnd; ++Ptr) { 7323 // Don't add the same builtin candidate twice. 7324 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7325 continue; 7326 7327 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7328 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7329 } 7330 for (BuiltinCandidateTypeSet::iterator 7331 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7332 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7333 Enum != EnumEnd; ++Enum) { 7334 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7335 7336 // Don't add the same builtin candidate twice, or if a user defined 7337 // candidate exists. 7338 if (!AddedTypes.insert(CanonType) || 7339 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7340 CanonType))) 7341 continue; 7342 7343 QualType ParamTypes[2] = { *Enum, *Enum }; 7344 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7345 } 7346 7347 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7348 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7349 if (AddedTypes.insert(NullPtrTy) && 7350 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7351 NullPtrTy))) { 7352 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7353 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7354 CandidateSet); 7355 } 7356 } 7357 } 7358 } 7359 7360 // C++ [over.built]p13: 7361 // 7362 // For every cv-qualified or cv-unqualified object type T 7363 // there exist candidate operator functions of the form 7364 // 7365 // T* operator+(T*, ptrdiff_t); 7366 // T& operator[](T*, ptrdiff_t); [BELOW] 7367 // T* operator-(T*, ptrdiff_t); 7368 // T* operator+(ptrdiff_t, T*); 7369 // T& operator[](ptrdiff_t, T*); [BELOW] 7370 // 7371 // C++ [over.built]p14: 7372 // 7373 // For every T, where T is a pointer to object type, there 7374 // exist candidate operator functions of the form 7375 // 7376 // ptrdiff_t operator-(T, T); 7377 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7378 /// Set of (canonical) types that we've already handled. 7379 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7380 7381 for (int Arg = 0; Arg < 2; ++Arg) { 7382 QualType AsymetricParamTypes[2] = { 7383 S.Context.getPointerDiffType(), 7384 S.Context.getPointerDiffType(), 7385 }; 7386 for (BuiltinCandidateTypeSet::iterator 7387 Ptr = CandidateTypes[Arg].pointer_begin(), 7388 PtrEnd = CandidateTypes[Arg].pointer_end(); 7389 Ptr != PtrEnd; ++Ptr) { 7390 QualType PointeeTy = (*Ptr)->getPointeeType(); 7391 if (!PointeeTy->isObjectType()) 7392 continue; 7393 7394 AsymetricParamTypes[Arg] = *Ptr; 7395 if (Arg == 0 || Op == OO_Plus) { 7396 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7397 // T* operator+(ptrdiff_t, T*); 7398 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet); 7399 } 7400 if (Op == OO_Minus) { 7401 // ptrdiff_t operator-(T, T); 7402 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7403 continue; 7404 7405 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7406 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7407 Args, CandidateSet); 7408 } 7409 } 7410 } 7411 } 7412 7413 // C++ [over.built]p12: 7414 // 7415 // For every pair of promoted arithmetic types L and R, there 7416 // exist candidate operator functions of the form 7417 // 7418 // LR operator*(L, R); 7419 // LR operator/(L, R); 7420 // LR operator+(L, R); 7421 // LR operator-(L, R); 7422 // bool operator<(L, R); 7423 // bool operator>(L, R); 7424 // bool operator<=(L, R); 7425 // bool operator>=(L, R); 7426 // bool operator==(L, R); 7427 // bool operator!=(L, R); 7428 // 7429 // where LR is the result of the usual arithmetic conversions 7430 // between types L and R. 7431 // 7432 // C++ [over.built]p24: 7433 // 7434 // For every pair of promoted arithmetic types L and R, there exist 7435 // candidate operator functions of the form 7436 // 7437 // LR operator?(bool, L, R); 7438 // 7439 // where LR is the result of the usual arithmetic conversions 7440 // between types L and R. 7441 // Our candidates ignore the first parameter. 7442 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7443 if (!HasArithmeticOrEnumeralCandidateType) 7444 return; 7445 7446 for (unsigned Left = FirstPromotedArithmeticType; 7447 Left < LastPromotedArithmeticType; ++Left) { 7448 for (unsigned Right = FirstPromotedArithmeticType; 7449 Right < LastPromotedArithmeticType; ++Right) { 7450 QualType LandR[2] = { getArithmeticType(Left), 7451 getArithmeticType(Right) }; 7452 QualType Result = 7453 isComparison ? S.Context.BoolTy 7454 : getUsualArithmeticConversions(Left, Right); 7455 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7456 } 7457 } 7458 7459 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7460 // conditional operator for vector types. 7461 for (BuiltinCandidateTypeSet::iterator 7462 Vec1 = CandidateTypes[0].vector_begin(), 7463 Vec1End = CandidateTypes[0].vector_end(); 7464 Vec1 != Vec1End; ++Vec1) { 7465 for (BuiltinCandidateTypeSet::iterator 7466 Vec2 = CandidateTypes[1].vector_begin(), 7467 Vec2End = CandidateTypes[1].vector_end(); 7468 Vec2 != Vec2End; ++Vec2) { 7469 QualType LandR[2] = { *Vec1, *Vec2 }; 7470 QualType Result = S.Context.BoolTy; 7471 if (!isComparison) { 7472 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7473 Result = *Vec1; 7474 else 7475 Result = *Vec2; 7476 } 7477 7478 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7479 } 7480 } 7481 } 7482 7483 // C++ [over.built]p17: 7484 // 7485 // For every pair of promoted integral types L and R, there 7486 // exist candidate operator functions of the form 7487 // 7488 // LR operator%(L, R); 7489 // LR operator&(L, R); 7490 // LR operator^(L, R); 7491 // LR operator|(L, R); 7492 // L operator<<(L, R); 7493 // L operator>>(L, R); 7494 // 7495 // where LR is the result of the usual arithmetic conversions 7496 // between types L and R. 7497 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7498 if (!HasArithmeticOrEnumeralCandidateType) 7499 return; 7500 7501 for (unsigned Left = FirstPromotedIntegralType; 7502 Left < LastPromotedIntegralType; ++Left) { 7503 for (unsigned Right = FirstPromotedIntegralType; 7504 Right < LastPromotedIntegralType; ++Right) { 7505 QualType LandR[2] = { getArithmeticType(Left), 7506 getArithmeticType(Right) }; 7507 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7508 ? LandR[0] 7509 : getUsualArithmeticConversions(Left, Right); 7510 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7511 } 7512 } 7513 } 7514 7515 // C++ [over.built]p20: 7516 // 7517 // For every pair (T, VQ), where T is an enumeration or 7518 // pointer to member type and VQ is either volatile or 7519 // empty, there exist candidate operator functions of the form 7520 // 7521 // VQ T& operator=(VQ T&, T); 7522 void addAssignmentMemberPointerOrEnumeralOverloads() { 7523 /// Set of (canonical) types that we've already handled. 7524 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7525 7526 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7527 for (BuiltinCandidateTypeSet::iterator 7528 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7529 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7530 Enum != EnumEnd; ++Enum) { 7531 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7532 continue; 7533 7534 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7535 } 7536 7537 for (BuiltinCandidateTypeSet::iterator 7538 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7539 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7540 MemPtr != MemPtrEnd; ++MemPtr) { 7541 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7542 continue; 7543 7544 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7545 } 7546 } 7547 } 7548 7549 // C++ [over.built]p19: 7550 // 7551 // For every pair (T, VQ), where T is any type and VQ is either 7552 // volatile or empty, there exist candidate operator functions 7553 // of the form 7554 // 7555 // T*VQ& operator=(T*VQ&, T*); 7556 // 7557 // C++ [over.built]p21: 7558 // 7559 // For every pair (T, VQ), where T is a cv-qualified or 7560 // cv-unqualified object type and VQ is either volatile or 7561 // empty, there exist candidate operator functions of the form 7562 // 7563 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7564 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7565 void addAssignmentPointerOverloads(bool isEqualOp) { 7566 /// Set of (canonical) types that we've already handled. 7567 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7568 7569 for (BuiltinCandidateTypeSet::iterator 7570 Ptr = CandidateTypes[0].pointer_begin(), 7571 PtrEnd = CandidateTypes[0].pointer_end(); 7572 Ptr != PtrEnd; ++Ptr) { 7573 // If this is operator=, keep track of the builtin candidates we added. 7574 if (isEqualOp) 7575 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7576 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7577 continue; 7578 7579 // non-volatile version 7580 QualType ParamTypes[2] = { 7581 S.Context.getLValueReferenceType(*Ptr), 7582 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7583 }; 7584 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7585 /*IsAssigmentOperator=*/ isEqualOp); 7586 7587 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7588 VisibleTypeConversionsQuals.hasVolatile(); 7589 if (NeedVolatile) { 7590 // volatile version 7591 ParamTypes[0] = 7592 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7593 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7594 /*IsAssigmentOperator=*/isEqualOp); 7595 } 7596 7597 if (!(*Ptr).isRestrictQualified() && 7598 VisibleTypeConversionsQuals.hasRestrict()) { 7599 // restrict version 7600 ParamTypes[0] 7601 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7602 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7603 /*IsAssigmentOperator=*/isEqualOp); 7604 7605 if (NeedVolatile) { 7606 // volatile restrict version 7607 ParamTypes[0] 7608 = S.Context.getLValueReferenceType( 7609 S.Context.getCVRQualifiedType(*Ptr, 7610 (Qualifiers::Volatile | 7611 Qualifiers::Restrict))); 7612 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7613 /*IsAssigmentOperator=*/isEqualOp); 7614 } 7615 } 7616 } 7617 7618 if (isEqualOp) { 7619 for (BuiltinCandidateTypeSet::iterator 7620 Ptr = CandidateTypes[1].pointer_begin(), 7621 PtrEnd = CandidateTypes[1].pointer_end(); 7622 Ptr != PtrEnd; ++Ptr) { 7623 // Make sure we don't add the same candidate twice. 7624 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7625 continue; 7626 7627 QualType ParamTypes[2] = { 7628 S.Context.getLValueReferenceType(*Ptr), 7629 *Ptr, 7630 }; 7631 7632 // non-volatile version 7633 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7634 /*IsAssigmentOperator=*/true); 7635 7636 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7637 VisibleTypeConversionsQuals.hasVolatile(); 7638 if (NeedVolatile) { 7639 // volatile version 7640 ParamTypes[0] = 7641 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7642 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7643 /*IsAssigmentOperator=*/true); 7644 } 7645 7646 if (!(*Ptr).isRestrictQualified() && 7647 VisibleTypeConversionsQuals.hasRestrict()) { 7648 // restrict version 7649 ParamTypes[0] 7650 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7651 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7652 /*IsAssigmentOperator=*/true); 7653 7654 if (NeedVolatile) { 7655 // volatile restrict version 7656 ParamTypes[0] 7657 = S.Context.getLValueReferenceType( 7658 S.Context.getCVRQualifiedType(*Ptr, 7659 (Qualifiers::Volatile | 7660 Qualifiers::Restrict))); 7661 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7662 /*IsAssigmentOperator=*/true); 7663 } 7664 } 7665 } 7666 } 7667 } 7668 7669 // C++ [over.built]p18: 7670 // 7671 // For every triple (L, VQ, R), where L is an arithmetic type, 7672 // VQ is either volatile or empty, and R is a promoted 7673 // arithmetic type, there exist candidate operator functions of 7674 // the form 7675 // 7676 // VQ L& operator=(VQ L&, R); 7677 // VQ L& operator*=(VQ L&, R); 7678 // VQ L& operator/=(VQ L&, R); 7679 // VQ L& operator+=(VQ L&, R); 7680 // VQ L& operator-=(VQ L&, R); 7681 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7682 if (!HasArithmeticOrEnumeralCandidateType) 7683 return; 7684 7685 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7686 for (unsigned Right = FirstPromotedArithmeticType; 7687 Right < LastPromotedArithmeticType; ++Right) { 7688 QualType ParamTypes[2]; 7689 ParamTypes[1] = getArithmeticType(Right); 7690 7691 // Add this built-in operator as a candidate (VQ is empty). 7692 ParamTypes[0] = 7693 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7694 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7695 /*IsAssigmentOperator=*/isEqualOp); 7696 7697 // Add this built-in operator as a candidate (VQ is 'volatile'). 7698 if (VisibleTypeConversionsQuals.hasVolatile()) { 7699 ParamTypes[0] = 7700 S.Context.getVolatileType(getArithmeticType(Left)); 7701 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7702 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7703 /*IsAssigmentOperator=*/isEqualOp); 7704 } 7705 } 7706 } 7707 7708 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7709 for (BuiltinCandidateTypeSet::iterator 7710 Vec1 = CandidateTypes[0].vector_begin(), 7711 Vec1End = CandidateTypes[0].vector_end(); 7712 Vec1 != Vec1End; ++Vec1) { 7713 for (BuiltinCandidateTypeSet::iterator 7714 Vec2 = CandidateTypes[1].vector_begin(), 7715 Vec2End = CandidateTypes[1].vector_end(); 7716 Vec2 != Vec2End; ++Vec2) { 7717 QualType ParamTypes[2]; 7718 ParamTypes[1] = *Vec2; 7719 // Add this built-in operator as a candidate (VQ is empty). 7720 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7721 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7722 /*IsAssigmentOperator=*/isEqualOp); 7723 7724 // Add this built-in operator as a candidate (VQ is 'volatile'). 7725 if (VisibleTypeConversionsQuals.hasVolatile()) { 7726 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7727 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7728 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7729 /*IsAssigmentOperator=*/isEqualOp); 7730 } 7731 } 7732 } 7733 } 7734 7735 // C++ [over.built]p22: 7736 // 7737 // For every triple (L, VQ, R), where L is an integral type, VQ 7738 // is either volatile or empty, and R is a promoted integral 7739 // type, there exist candidate operator functions of the form 7740 // 7741 // VQ L& operator%=(VQ L&, R); 7742 // VQ L& operator<<=(VQ L&, R); 7743 // VQ L& operator>>=(VQ L&, R); 7744 // VQ L& operator&=(VQ L&, R); 7745 // VQ L& operator^=(VQ L&, R); 7746 // VQ L& operator|=(VQ L&, R); 7747 void addAssignmentIntegralOverloads() { 7748 if (!HasArithmeticOrEnumeralCandidateType) 7749 return; 7750 7751 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7752 for (unsigned Right = FirstPromotedIntegralType; 7753 Right < LastPromotedIntegralType; ++Right) { 7754 QualType ParamTypes[2]; 7755 ParamTypes[1] = getArithmeticType(Right); 7756 7757 // Add this built-in operator as a candidate (VQ is empty). 7758 ParamTypes[0] = 7759 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7760 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7761 if (VisibleTypeConversionsQuals.hasVolatile()) { 7762 // Add this built-in operator as a candidate (VQ is 'volatile'). 7763 ParamTypes[0] = getArithmeticType(Left); 7764 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7765 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7766 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7767 } 7768 } 7769 } 7770 } 7771 7772 // C++ [over.operator]p23: 7773 // 7774 // There also exist candidate operator functions of the form 7775 // 7776 // bool operator!(bool); 7777 // bool operator&&(bool, bool); 7778 // bool operator||(bool, bool); 7779 void addExclaimOverload() { 7780 QualType ParamTy = S.Context.BoolTy; 7781 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 7782 /*IsAssignmentOperator=*/false, 7783 /*NumContextualBoolArguments=*/1); 7784 } 7785 void addAmpAmpOrPipePipeOverload() { 7786 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7787 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 7788 /*IsAssignmentOperator=*/false, 7789 /*NumContextualBoolArguments=*/2); 7790 } 7791 7792 // C++ [over.built]p13: 7793 // 7794 // For every cv-qualified or cv-unqualified object type T there 7795 // exist candidate operator functions of the form 7796 // 7797 // T* operator+(T*, ptrdiff_t); [ABOVE] 7798 // T& operator[](T*, ptrdiff_t); 7799 // T* operator-(T*, ptrdiff_t); [ABOVE] 7800 // T* operator+(ptrdiff_t, T*); [ABOVE] 7801 // T& operator[](ptrdiff_t, T*); 7802 void addSubscriptOverloads() { 7803 for (BuiltinCandidateTypeSet::iterator 7804 Ptr = CandidateTypes[0].pointer_begin(), 7805 PtrEnd = CandidateTypes[0].pointer_end(); 7806 Ptr != PtrEnd; ++Ptr) { 7807 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7808 QualType PointeeType = (*Ptr)->getPointeeType(); 7809 if (!PointeeType->isObjectType()) 7810 continue; 7811 7812 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7813 7814 // T& operator[](T*, ptrdiff_t) 7815 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7816 } 7817 7818 for (BuiltinCandidateTypeSet::iterator 7819 Ptr = CandidateTypes[1].pointer_begin(), 7820 PtrEnd = CandidateTypes[1].pointer_end(); 7821 Ptr != PtrEnd; ++Ptr) { 7822 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7823 QualType PointeeType = (*Ptr)->getPointeeType(); 7824 if (!PointeeType->isObjectType()) 7825 continue; 7826 7827 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7828 7829 // T& operator[](ptrdiff_t, T*) 7830 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7831 } 7832 } 7833 7834 // C++ [over.built]p11: 7835 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7836 // C1 is the same type as C2 or is a derived class of C2, T is an object 7837 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7838 // there exist candidate operator functions of the form 7839 // 7840 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7841 // 7842 // where CV12 is the union of CV1 and CV2. 7843 void addArrowStarOverloads() { 7844 for (BuiltinCandidateTypeSet::iterator 7845 Ptr = CandidateTypes[0].pointer_begin(), 7846 PtrEnd = CandidateTypes[0].pointer_end(); 7847 Ptr != PtrEnd; ++Ptr) { 7848 QualType C1Ty = (*Ptr); 7849 QualType C1; 7850 QualifierCollector Q1; 7851 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 7852 if (!isa<RecordType>(C1)) 7853 continue; 7854 // heuristic to reduce number of builtin candidates in the set. 7855 // Add volatile/restrict version only if there are conversions to a 7856 // volatile/restrict type. 7857 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 7858 continue; 7859 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 7860 continue; 7861 for (BuiltinCandidateTypeSet::iterator 7862 MemPtr = CandidateTypes[1].member_pointer_begin(), 7863 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 7864 MemPtr != MemPtrEnd; ++MemPtr) { 7865 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 7866 QualType C2 = QualType(mptr->getClass(), 0); 7867 C2 = C2.getUnqualifiedType(); 7868 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 7869 break; 7870 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 7871 // build CV12 T& 7872 QualType T = mptr->getPointeeType(); 7873 if (!VisibleTypeConversionsQuals.hasVolatile() && 7874 T.isVolatileQualified()) 7875 continue; 7876 if (!VisibleTypeConversionsQuals.hasRestrict() && 7877 T.isRestrictQualified()) 7878 continue; 7879 T = Q1.apply(S.Context, T); 7880 QualType ResultTy = S.Context.getLValueReferenceType(T); 7881 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7882 } 7883 } 7884 } 7885 7886 // Note that we don't consider the first argument, since it has been 7887 // contextually converted to bool long ago. The candidates below are 7888 // therefore added as binary. 7889 // 7890 // C++ [over.built]p25: 7891 // For every type T, where T is a pointer, pointer-to-member, or scoped 7892 // enumeration type, there exist candidate operator functions of the form 7893 // 7894 // T operator?(bool, T, T); 7895 // 7896 void addConditionalOperatorOverloads() { 7897 /// Set of (canonical) types that we've already handled. 7898 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7899 7900 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7901 for (BuiltinCandidateTypeSet::iterator 7902 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7903 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7904 Ptr != PtrEnd; ++Ptr) { 7905 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7906 continue; 7907 7908 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7909 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 7910 } 7911 7912 for (BuiltinCandidateTypeSet::iterator 7913 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7914 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7915 MemPtr != MemPtrEnd; ++MemPtr) { 7916 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7917 continue; 7918 7919 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7920 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 7921 } 7922 7923 if (S.getLangOpts().CPlusPlus11) { 7924 for (BuiltinCandidateTypeSet::iterator 7925 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7926 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7927 Enum != EnumEnd; ++Enum) { 7928 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 7929 continue; 7930 7931 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7932 continue; 7933 7934 QualType ParamTypes[2] = { *Enum, *Enum }; 7935 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 7936 } 7937 } 7938 } 7939 } 7940 }; 7941 7942 } // end anonymous namespace 7943 7944 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 7945 /// operator overloads to the candidate set (C++ [over.built]), based 7946 /// on the operator @p Op and the arguments given. For example, if the 7947 /// operator is a binary '+', this routine might add "int 7948 /// operator+(int, int)" to cover integer addition. 7949 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 7950 SourceLocation OpLoc, 7951 ArrayRef<Expr *> Args, 7952 OverloadCandidateSet &CandidateSet) { 7953 // Find all of the types that the arguments can convert to, but only 7954 // if the operator we're looking at has built-in operator candidates 7955 // that make use of these types. Also record whether we encounter non-record 7956 // candidate types or either arithmetic or enumeral candidate types. 7957 Qualifiers VisibleTypeConversionsQuals; 7958 VisibleTypeConversionsQuals.addConst(); 7959 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 7960 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 7961 7962 bool HasNonRecordCandidateType = false; 7963 bool HasArithmeticOrEnumeralCandidateType = false; 7964 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 7965 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7966 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 7967 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 7968 OpLoc, 7969 true, 7970 (Op == OO_Exclaim || 7971 Op == OO_AmpAmp || 7972 Op == OO_PipePipe), 7973 VisibleTypeConversionsQuals); 7974 HasNonRecordCandidateType = HasNonRecordCandidateType || 7975 CandidateTypes[ArgIdx].hasNonRecordTypes(); 7976 HasArithmeticOrEnumeralCandidateType = 7977 HasArithmeticOrEnumeralCandidateType || 7978 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 7979 } 7980 7981 // Exit early when no non-record types have been added to the candidate set 7982 // for any of the arguments to the operator. 7983 // 7984 // We can't exit early for !, ||, or &&, since there we have always have 7985 // 'bool' overloads. 7986 if (!HasNonRecordCandidateType && 7987 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 7988 return; 7989 7990 // Setup an object to manage the common state for building overloads. 7991 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 7992 VisibleTypeConversionsQuals, 7993 HasArithmeticOrEnumeralCandidateType, 7994 CandidateTypes, CandidateSet); 7995 7996 // Dispatch over the operation to add in only those overloads which apply. 7997 switch (Op) { 7998 case OO_None: 7999 case NUM_OVERLOADED_OPERATORS: 8000 llvm_unreachable("Expected an overloaded operator"); 8001 8002 case OO_New: 8003 case OO_Delete: 8004 case OO_Array_New: 8005 case OO_Array_Delete: 8006 case OO_Call: 8007 llvm_unreachable( 8008 "Special operators don't use AddBuiltinOperatorCandidates"); 8009 8010 case OO_Comma: 8011 case OO_Arrow: 8012 // C++ [over.match.oper]p3: 8013 // -- For the operator ',', the unary operator '&', or the 8014 // operator '->', the built-in candidates set is empty. 8015 break; 8016 8017 case OO_Plus: // '+' is either unary or binary 8018 if (Args.size() == 1) 8019 OpBuilder.addUnaryPlusPointerOverloads(); 8020 // Fall through. 8021 8022 case OO_Minus: // '-' is either unary or binary 8023 if (Args.size() == 1) { 8024 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8025 } else { 8026 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8027 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8028 } 8029 break; 8030 8031 case OO_Star: // '*' is either unary or binary 8032 if (Args.size() == 1) 8033 OpBuilder.addUnaryStarPointerOverloads(); 8034 else 8035 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8036 break; 8037 8038 case OO_Slash: 8039 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8040 break; 8041 8042 case OO_PlusPlus: 8043 case OO_MinusMinus: 8044 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8045 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8046 break; 8047 8048 case OO_EqualEqual: 8049 case OO_ExclaimEqual: 8050 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 8051 // Fall through. 8052 8053 case OO_Less: 8054 case OO_Greater: 8055 case OO_LessEqual: 8056 case OO_GreaterEqual: 8057 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8058 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8059 break; 8060 8061 case OO_Percent: 8062 case OO_Caret: 8063 case OO_Pipe: 8064 case OO_LessLess: 8065 case OO_GreaterGreater: 8066 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8067 break; 8068 8069 case OO_Amp: // '&' is either unary or binary 8070 if (Args.size() == 1) 8071 // C++ [over.match.oper]p3: 8072 // -- For the operator ',', the unary operator '&', or the 8073 // operator '->', the built-in candidates set is empty. 8074 break; 8075 8076 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8077 break; 8078 8079 case OO_Tilde: 8080 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8081 break; 8082 8083 case OO_Equal: 8084 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8085 // Fall through. 8086 8087 case OO_PlusEqual: 8088 case OO_MinusEqual: 8089 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8090 // Fall through. 8091 8092 case OO_StarEqual: 8093 case OO_SlashEqual: 8094 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8095 break; 8096 8097 case OO_PercentEqual: 8098 case OO_LessLessEqual: 8099 case OO_GreaterGreaterEqual: 8100 case OO_AmpEqual: 8101 case OO_CaretEqual: 8102 case OO_PipeEqual: 8103 OpBuilder.addAssignmentIntegralOverloads(); 8104 break; 8105 8106 case OO_Exclaim: 8107 OpBuilder.addExclaimOverload(); 8108 break; 8109 8110 case OO_AmpAmp: 8111 case OO_PipePipe: 8112 OpBuilder.addAmpAmpOrPipePipeOverload(); 8113 break; 8114 8115 case OO_Subscript: 8116 OpBuilder.addSubscriptOverloads(); 8117 break; 8118 8119 case OO_ArrowStar: 8120 OpBuilder.addArrowStarOverloads(); 8121 break; 8122 8123 case OO_Conditional: 8124 OpBuilder.addConditionalOperatorOverloads(); 8125 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8126 break; 8127 } 8128 } 8129 8130 /// \brief Add function candidates found via argument-dependent lookup 8131 /// to the set of overloading candidates. 8132 /// 8133 /// This routine performs argument-dependent name lookup based on the 8134 /// given function name (which may also be an operator name) and adds 8135 /// all of the overload candidates found by ADL to the overload 8136 /// candidate set (C++ [basic.lookup.argdep]). 8137 void 8138 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8139 SourceLocation Loc, 8140 ArrayRef<Expr *> Args, 8141 TemplateArgumentListInfo *ExplicitTemplateArgs, 8142 OverloadCandidateSet& CandidateSet, 8143 bool PartialOverloading) { 8144 ADLResult Fns; 8145 8146 // FIXME: This approach for uniquing ADL results (and removing 8147 // redundant candidates from the set) relies on pointer-equality, 8148 // which means we need to key off the canonical decl. However, 8149 // always going back to the canonical decl might not get us the 8150 // right set of default arguments. What default arguments are 8151 // we supposed to consider on ADL candidates, anyway? 8152 8153 // FIXME: Pass in the explicit template arguments? 8154 ArgumentDependentLookup(Name, Loc, Args, Fns); 8155 8156 // Erase all of the candidates we already knew about. 8157 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8158 CandEnd = CandidateSet.end(); 8159 Cand != CandEnd; ++Cand) 8160 if (Cand->Function) { 8161 Fns.erase(Cand->Function); 8162 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8163 Fns.erase(FunTmpl); 8164 } 8165 8166 // For each of the ADL candidates we found, add it to the overload 8167 // set. 8168 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8169 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8170 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8171 if (ExplicitTemplateArgs) 8172 continue; 8173 8174 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8175 PartialOverloading); 8176 } else 8177 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8178 FoundDecl, ExplicitTemplateArgs, 8179 Args, CandidateSet); 8180 } 8181 } 8182 8183 /// isBetterOverloadCandidate - Determines whether the first overload 8184 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8185 bool 8186 isBetterOverloadCandidate(Sema &S, 8187 const OverloadCandidate &Cand1, 8188 const OverloadCandidate &Cand2, 8189 SourceLocation Loc, 8190 bool UserDefinedConversion) { 8191 // Define viable functions to be better candidates than non-viable 8192 // functions. 8193 if (!Cand2.Viable) 8194 return Cand1.Viable; 8195 else if (!Cand1.Viable) 8196 return false; 8197 8198 // C++ [over.match.best]p1: 8199 // 8200 // -- if F is a static member function, ICS1(F) is defined such 8201 // that ICS1(F) is neither better nor worse than ICS1(G) for 8202 // any function G, and, symmetrically, ICS1(G) is neither 8203 // better nor worse than ICS1(F). 8204 unsigned StartArg = 0; 8205 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8206 StartArg = 1; 8207 8208 // C++ [over.match.best]p1: 8209 // A viable function F1 is defined to be a better function than another 8210 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8211 // conversion sequence than ICSi(F2), and then... 8212 unsigned NumArgs = Cand1.NumConversions; 8213 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8214 bool HasBetterConversion = false; 8215 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8216 switch (CompareImplicitConversionSequences(S, 8217 Cand1.Conversions[ArgIdx], 8218 Cand2.Conversions[ArgIdx])) { 8219 case ImplicitConversionSequence::Better: 8220 // Cand1 has a better conversion sequence. 8221 HasBetterConversion = true; 8222 break; 8223 8224 case ImplicitConversionSequence::Worse: 8225 // Cand1 can't be better than Cand2. 8226 return false; 8227 8228 case ImplicitConversionSequence::Indistinguishable: 8229 // Do nothing. 8230 break; 8231 } 8232 } 8233 8234 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8235 // ICSj(F2), or, if not that, 8236 if (HasBetterConversion) 8237 return true; 8238 8239 // - F1 is a non-template function and F2 is a function template 8240 // specialization, or, if not that, 8241 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 8242 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 8243 return true; 8244 8245 // -- F1 and F2 are function template specializations, and the function 8246 // template for F1 is more specialized than the template for F2 8247 // according to the partial ordering rules described in 14.5.5.2, or, 8248 // if not that, 8249 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 8250 Cand2.Function && Cand2.Function->getPrimaryTemplate()) { 8251 if (FunctionTemplateDecl *BetterTemplate 8252 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8253 Cand2.Function->getPrimaryTemplate(), 8254 Loc, 8255 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8256 : TPOC_Call, 8257 Cand1.ExplicitCallArguments, 8258 Cand2.ExplicitCallArguments)) 8259 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8260 } 8261 8262 // -- the context is an initialization by user-defined conversion 8263 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8264 // from the return type of F1 to the destination type (i.e., 8265 // the type of the entity being initialized) is a better 8266 // conversion sequence than the standard conversion sequence 8267 // from the return type of F2 to the destination type. 8268 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8269 isa<CXXConversionDecl>(Cand1.Function) && 8270 isa<CXXConversionDecl>(Cand2.Function)) { 8271 // First check whether we prefer one of the conversion functions over the 8272 // other. This only distinguishes the results in non-standard, extension 8273 // cases such as the conversion from a lambda closure type to a function 8274 // pointer or block. 8275 ImplicitConversionSequence::CompareKind FuncResult 8276 = compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8277 if (FuncResult != ImplicitConversionSequence::Indistinguishable) 8278 return FuncResult; 8279 8280 switch (CompareStandardConversionSequences(S, 8281 Cand1.FinalConversion, 8282 Cand2.FinalConversion)) { 8283 case ImplicitConversionSequence::Better: 8284 // Cand1 has a better conversion sequence. 8285 return true; 8286 8287 case ImplicitConversionSequence::Worse: 8288 // Cand1 can't be better than Cand2. 8289 return false; 8290 8291 case ImplicitConversionSequence::Indistinguishable: 8292 // Do nothing 8293 break; 8294 } 8295 } 8296 8297 // Check for enable_if value-based overload resolution. 8298 if (Cand1.Function && Cand2.Function && 8299 (Cand1.Function->hasAttr<EnableIfAttr>() || 8300 Cand2.Function->hasAttr<EnableIfAttr>())) { 8301 // FIXME: The next several lines are just 8302 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8303 // instead of reverse order which is how they're stored in the AST. 8304 AttrVec Cand1Attrs; 8305 AttrVec::iterator Cand1E = Cand1Attrs.end(); 8306 if (Cand1.Function->hasAttrs()) { 8307 Cand1Attrs = Cand1.Function->getAttrs(); 8308 Cand1E = std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(), 8309 IsNotEnableIfAttr); 8310 std::reverse(Cand1Attrs.begin(), Cand1E); 8311 } 8312 8313 AttrVec Cand2Attrs; 8314 AttrVec::iterator Cand2E = Cand2Attrs.end(); 8315 if (Cand2.Function->hasAttrs()) { 8316 Cand2Attrs = Cand2.Function->getAttrs(); 8317 Cand2E = std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(), 8318 IsNotEnableIfAttr); 8319 std::reverse(Cand2Attrs.begin(), Cand2E); 8320 } 8321 for (AttrVec::iterator 8322 Cand1I = Cand1Attrs.begin(), Cand2I = Cand2Attrs.begin(); 8323 Cand1I != Cand1E || Cand2I != Cand2E; ++Cand1I, ++Cand2I) { 8324 if (Cand1I == Cand1E) 8325 return false; 8326 if (Cand2I == Cand2E) 8327 return true; 8328 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8329 cast<EnableIfAttr>(*Cand1I)->getCond()->Profile(Cand1ID, 8330 S.getASTContext(), true); 8331 cast<EnableIfAttr>(*Cand2I)->getCond()->Profile(Cand2ID, 8332 S.getASTContext(), true); 8333 if (Cand1ID != Cand2ID) 8334 return false; 8335 } 8336 } 8337 8338 return false; 8339 } 8340 8341 /// \brief Computes the best viable function (C++ 13.3.3) 8342 /// within an overload candidate set. 8343 /// 8344 /// \param Loc The location of the function name (or operator symbol) for 8345 /// which overload resolution occurs. 8346 /// 8347 /// \param Best If overload resolution was successful or found a deleted 8348 /// function, \p Best points to the candidate function found. 8349 /// 8350 /// \returns The result of overload resolution. 8351 OverloadingResult 8352 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8353 iterator &Best, 8354 bool UserDefinedConversion) { 8355 // Find the best viable function. 8356 Best = end(); 8357 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8358 if (Cand->Viable) 8359 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8360 UserDefinedConversion)) 8361 Best = Cand; 8362 } 8363 8364 // If we didn't find any viable functions, abort. 8365 if (Best == end()) 8366 return OR_No_Viable_Function; 8367 8368 // Make sure that this function is better than every other viable 8369 // function. If not, we have an ambiguity. 8370 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8371 if (Cand->Viable && 8372 Cand != Best && 8373 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8374 UserDefinedConversion)) { 8375 Best = end(); 8376 return OR_Ambiguous; 8377 } 8378 } 8379 8380 // Best is the best viable function. 8381 if (Best->Function && 8382 (Best->Function->isDeleted() || 8383 S.isFunctionConsideredUnavailable(Best->Function))) 8384 return OR_Deleted; 8385 8386 return OR_Success; 8387 } 8388 8389 namespace { 8390 8391 enum OverloadCandidateKind { 8392 oc_function, 8393 oc_method, 8394 oc_constructor, 8395 oc_function_template, 8396 oc_method_template, 8397 oc_constructor_template, 8398 oc_implicit_default_constructor, 8399 oc_implicit_copy_constructor, 8400 oc_implicit_move_constructor, 8401 oc_implicit_copy_assignment, 8402 oc_implicit_move_assignment, 8403 oc_implicit_inherited_constructor 8404 }; 8405 8406 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8407 FunctionDecl *Fn, 8408 std::string &Description) { 8409 bool isTemplate = false; 8410 8411 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8412 isTemplate = true; 8413 Description = S.getTemplateArgumentBindingsText( 8414 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8415 } 8416 8417 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8418 if (!Ctor->isImplicit()) 8419 return isTemplate ? oc_constructor_template : oc_constructor; 8420 8421 if (Ctor->getInheritedConstructor()) 8422 return oc_implicit_inherited_constructor; 8423 8424 if (Ctor->isDefaultConstructor()) 8425 return oc_implicit_default_constructor; 8426 8427 if (Ctor->isMoveConstructor()) 8428 return oc_implicit_move_constructor; 8429 8430 assert(Ctor->isCopyConstructor() && 8431 "unexpected sort of implicit constructor"); 8432 return oc_implicit_copy_constructor; 8433 } 8434 8435 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8436 // This actually gets spelled 'candidate function' for now, but 8437 // it doesn't hurt to split it out. 8438 if (!Meth->isImplicit()) 8439 return isTemplate ? oc_method_template : oc_method; 8440 8441 if (Meth->isMoveAssignmentOperator()) 8442 return oc_implicit_move_assignment; 8443 8444 if (Meth->isCopyAssignmentOperator()) 8445 return oc_implicit_copy_assignment; 8446 8447 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8448 return oc_method; 8449 } 8450 8451 return isTemplate ? oc_function_template : oc_function; 8452 } 8453 8454 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) { 8455 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8456 if (!Ctor) return; 8457 8458 Ctor = Ctor->getInheritedConstructor(); 8459 if (!Ctor) return; 8460 8461 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8462 } 8463 8464 } // end anonymous namespace 8465 8466 // Notes the location of an overload candidate. 8467 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 8468 std::string FnDesc; 8469 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8470 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8471 << (unsigned) K << FnDesc; 8472 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8473 Diag(Fn->getLocation(), PD); 8474 MaybeEmitInheritedConstructorNote(*this, Fn); 8475 } 8476 8477 // Notes the location of all overload candidates designated through 8478 // OverloadedExpr 8479 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 8480 assert(OverloadedExpr->getType() == Context.OverloadTy); 8481 8482 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8483 OverloadExpr *OvlExpr = Ovl.Expression; 8484 8485 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8486 IEnd = OvlExpr->decls_end(); 8487 I != IEnd; ++I) { 8488 if (FunctionTemplateDecl *FunTmpl = 8489 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8490 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 8491 } else if (FunctionDecl *Fun 8492 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8493 NoteOverloadCandidate(Fun, DestType); 8494 } 8495 } 8496 } 8497 8498 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 8499 /// "lead" diagnostic; it will be given two arguments, the source and 8500 /// target types of the conversion. 8501 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8502 Sema &S, 8503 SourceLocation CaretLoc, 8504 const PartialDiagnostic &PDiag) const { 8505 S.Diag(CaretLoc, PDiag) 8506 << Ambiguous.getFromType() << Ambiguous.getToType(); 8507 // FIXME: The note limiting machinery is borrowed from 8508 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8509 // refactoring here. 8510 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8511 unsigned CandsShown = 0; 8512 AmbiguousConversionSequence::const_iterator I, E; 8513 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8514 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8515 break; 8516 ++CandsShown; 8517 S.NoteOverloadCandidate(*I); 8518 } 8519 if (I != E) 8520 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8521 } 8522 8523 namespace { 8524 8525 void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 8526 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8527 assert(Conv.isBad()); 8528 assert(Cand->Function && "for now, candidate must be a function"); 8529 FunctionDecl *Fn = Cand->Function; 8530 8531 // There's a conversion slot for the object argument if this is a 8532 // non-constructor method. Note that 'I' corresponds the 8533 // conversion-slot index. 8534 bool isObjectArgument = false; 8535 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8536 if (I == 0) 8537 isObjectArgument = true; 8538 else 8539 I--; 8540 } 8541 8542 std::string FnDesc; 8543 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8544 8545 Expr *FromExpr = Conv.Bad.FromExpr; 8546 QualType FromTy = Conv.Bad.getFromType(); 8547 QualType ToTy = Conv.Bad.getToType(); 8548 8549 if (FromTy == S.Context.OverloadTy) { 8550 assert(FromExpr && "overload set argument came from implicit argument?"); 8551 Expr *E = FromExpr->IgnoreParens(); 8552 if (isa<UnaryOperator>(E)) 8553 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8554 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8555 8556 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8557 << (unsigned) FnKind << FnDesc 8558 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8559 << ToTy << Name << I+1; 8560 MaybeEmitInheritedConstructorNote(S, Fn); 8561 return; 8562 } 8563 8564 // Do some hand-waving analysis to see if the non-viability is due 8565 // to a qualifier mismatch. 8566 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8567 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8568 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8569 CToTy = RT->getPointeeType(); 8570 else { 8571 // TODO: detect and diagnose the full richness of const mismatches. 8572 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8573 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8574 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8575 } 8576 8577 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8578 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8579 Qualifiers FromQs = CFromTy.getQualifiers(); 8580 Qualifiers ToQs = CToTy.getQualifiers(); 8581 8582 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8583 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8584 << (unsigned) FnKind << FnDesc 8585 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8586 << FromTy 8587 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8588 << (unsigned) isObjectArgument << I+1; 8589 MaybeEmitInheritedConstructorNote(S, Fn); 8590 return; 8591 } 8592 8593 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8594 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8595 << (unsigned) FnKind << FnDesc 8596 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8597 << FromTy 8598 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8599 << (unsigned) isObjectArgument << I+1; 8600 MaybeEmitInheritedConstructorNote(S, Fn); 8601 return; 8602 } 8603 8604 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8605 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8606 << (unsigned) FnKind << FnDesc 8607 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8608 << FromTy 8609 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8610 << (unsigned) isObjectArgument << I+1; 8611 MaybeEmitInheritedConstructorNote(S, Fn); 8612 return; 8613 } 8614 8615 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8616 assert(CVR && "unexpected qualifiers mismatch"); 8617 8618 if (isObjectArgument) { 8619 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8620 << (unsigned) FnKind << FnDesc 8621 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8622 << FromTy << (CVR - 1); 8623 } else { 8624 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8625 << (unsigned) FnKind << FnDesc 8626 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8627 << FromTy << (CVR - 1) << I+1; 8628 } 8629 MaybeEmitInheritedConstructorNote(S, Fn); 8630 return; 8631 } 8632 8633 // Special diagnostic for failure to convert an initializer list, since 8634 // telling the user that it has type void is not useful. 8635 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8636 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8637 << (unsigned) FnKind << FnDesc 8638 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8639 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8640 MaybeEmitInheritedConstructorNote(S, Fn); 8641 return; 8642 } 8643 8644 // Diagnose references or pointers to incomplete types differently, 8645 // since it's far from impossible that the incompleteness triggered 8646 // the failure. 8647 QualType TempFromTy = FromTy.getNonReferenceType(); 8648 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8649 TempFromTy = PTy->getPointeeType(); 8650 if (TempFromTy->isIncompleteType()) { 8651 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8652 << (unsigned) FnKind << FnDesc 8653 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8654 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8655 MaybeEmitInheritedConstructorNote(S, Fn); 8656 return; 8657 } 8658 8659 // Diagnose base -> derived pointer conversions. 8660 unsigned BaseToDerivedConversion = 0; 8661 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8662 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8663 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8664 FromPtrTy->getPointeeType()) && 8665 !FromPtrTy->getPointeeType()->isIncompleteType() && 8666 !ToPtrTy->getPointeeType()->isIncompleteType() && 8667 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8668 FromPtrTy->getPointeeType())) 8669 BaseToDerivedConversion = 1; 8670 } 8671 } else if (const ObjCObjectPointerType *FromPtrTy 8672 = FromTy->getAs<ObjCObjectPointerType>()) { 8673 if (const ObjCObjectPointerType *ToPtrTy 8674 = ToTy->getAs<ObjCObjectPointerType>()) 8675 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8676 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8677 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8678 FromPtrTy->getPointeeType()) && 8679 FromIface->isSuperClassOf(ToIface)) 8680 BaseToDerivedConversion = 2; 8681 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8682 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8683 !FromTy->isIncompleteType() && 8684 !ToRefTy->getPointeeType()->isIncompleteType() && 8685 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8686 BaseToDerivedConversion = 3; 8687 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8688 ToTy.getNonReferenceType().getCanonicalType() == 8689 FromTy.getNonReferenceType().getCanonicalType()) { 8690 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8691 << (unsigned) FnKind << FnDesc 8692 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8693 << (unsigned) isObjectArgument << I + 1; 8694 MaybeEmitInheritedConstructorNote(S, Fn); 8695 return; 8696 } 8697 } 8698 8699 if (BaseToDerivedConversion) { 8700 S.Diag(Fn->getLocation(), 8701 diag::note_ovl_candidate_bad_base_to_derived_conv) 8702 << (unsigned) FnKind << FnDesc 8703 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8704 << (BaseToDerivedConversion - 1) 8705 << FromTy << ToTy << I+1; 8706 MaybeEmitInheritedConstructorNote(S, Fn); 8707 return; 8708 } 8709 8710 if (isa<ObjCObjectPointerType>(CFromTy) && 8711 isa<PointerType>(CToTy)) { 8712 Qualifiers FromQs = CFromTy.getQualifiers(); 8713 Qualifiers ToQs = CToTy.getQualifiers(); 8714 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8715 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8716 << (unsigned) FnKind << FnDesc 8717 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8718 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8719 MaybeEmitInheritedConstructorNote(S, Fn); 8720 return; 8721 } 8722 } 8723 8724 // Emit the generic diagnostic and, optionally, add the hints to it. 8725 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8726 FDiag << (unsigned) FnKind << FnDesc 8727 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8728 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8729 << (unsigned) (Cand->Fix.Kind); 8730 8731 // If we can fix the conversion, suggest the FixIts. 8732 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8733 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8734 FDiag << *HI; 8735 S.Diag(Fn->getLocation(), FDiag); 8736 8737 MaybeEmitInheritedConstructorNote(S, Fn); 8738 } 8739 8740 /// Additional arity mismatch diagnosis specific to a function overload 8741 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 8742 /// over a candidate in any candidate set. 8743 bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 8744 unsigned NumArgs) { 8745 FunctionDecl *Fn = Cand->Function; 8746 unsigned MinParams = Fn->getMinRequiredArguments(); 8747 8748 // With invalid overloaded operators, it's possible that we think we 8749 // have an arity mismatch when in fact it looks like we have the 8750 // right number of arguments, because only overloaded operators have 8751 // the weird behavior of overloading member and non-member functions. 8752 // Just don't report anything. 8753 if (Fn->isInvalidDecl() && 8754 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8755 return true; 8756 8757 if (NumArgs < MinParams) { 8758 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8759 (Cand->FailureKind == ovl_fail_bad_deduction && 8760 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8761 } else { 8762 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8763 (Cand->FailureKind == ovl_fail_bad_deduction && 8764 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8765 } 8766 8767 return false; 8768 } 8769 8770 /// General arity mismatch diagnosis over a candidate in a candidate set. 8771 void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) { 8772 assert(isa<FunctionDecl>(D) && 8773 "The templated declaration should at least be a function" 8774 " when diagnosing bad template argument deduction due to too many" 8775 " or too few arguments"); 8776 8777 FunctionDecl *Fn = cast<FunctionDecl>(D); 8778 8779 // TODO: treat calls to a missing default constructor as a special case 8780 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8781 unsigned MinParams = Fn->getMinRequiredArguments(); 8782 8783 // at least / at most / exactly 8784 unsigned mode, modeCount; 8785 if (NumFormalArgs < MinParams) { 8786 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 8787 FnTy->isTemplateVariadic()) 8788 mode = 0; // "at least" 8789 else 8790 mode = 2; // "exactly" 8791 modeCount = MinParams; 8792 } else { 8793 if (MinParams != FnTy->getNumParams()) 8794 mode = 1; // "at most" 8795 else 8796 mode = 2; // "exactly" 8797 modeCount = FnTy->getNumParams(); 8798 } 8799 8800 std::string Description; 8801 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8802 8803 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8804 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8805 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8806 << Fn->getParamDecl(0) << NumFormalArgs; 8807 else 8808 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8809 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8810 << modeCount << NumFormalArgs; 8811 MaybeEmitInheritedConstructorNote(S, Fn); 8812 } 8813 8814 /// Arity mismatch diagnosis specific to a function overload candidate. 8815 void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8816 unsigned NumFormalArgs) { 8817 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 8818 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs); 8819 } 8820 8821 TemplateDecl *getDescribedTemplate(Decl *Templated) { 8822 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated)) 8823 return FD->getDescribedFunctionTemplate(); 8824 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated)) 8825 return RD->getDescribedClassTemplate(); 8826 8827 llvm_unreachable("Unsupported: Getting the described template declaration" 8828 " for bad deduction diagnosis"); 8829 } 8830 8831 /// Diagnose a failed template-argument deduction. 8832 void DiagnoseBadDeduction(Sema &S, Decl *Templated, 8833 DeductionFailureInfo &DeductionFailure, 8834 unsigned NumArgs) { 8835 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 8836 NamedDecl *ParamD; 8837 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8838 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8839 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8840 switch (DeductionFailure.Result) { 8841 case Sema::TDK_Success: 8842 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8843 8844 case Sema::TDK_Incomplete: { 8845 assert(ParamD && "no parameter found for incomplete deduction result"); 8846 S.Diag(Templated->getLocation(), 8847 diag::note_ovl_candidate_incomplete_deduction) 8848 << ParamD->getDeclName(); 8849 MaybeEmitInheritedConstructorNote(S, Templated); 8850 return; 8851 } 8852 8853 case Sema::TDK_Underqualified: { 8854 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8855 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 8856 8857 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 8858 8859 // Param will have been canonicalized, but it should just be a 8860 // qualified version of ParamD, so move the qualifiers to that. 8861 QualifierCollector Qs; 8862 Qs.strip(Param); 8863 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 8864 assert(S.Context.hasSameType(Param, NonCanonParam)); 8865 8866 // Arg has also been canonicalized, but there's nothing we can do 8867 // about that. It also doesn't matter as much, because it won't 8868 // have any template parameters in it (because deduction isn't 8869 // done on dependent types). 8870 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 8871 8872 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 8873 << ParamD->getDeclName() << Arg << NonCanonParam; 8874 MaybeEmitInheritedConstructorNote(S, Templated); 8875 return; 8876 } 8877 8878 case Sema::TDK_Inconsistent: { 8879 assert(ParamD && "no parameter found for inconsistent deduction result"); 8880 int which = 0; 8881 if (isa<TemplateTypeParmDecl>(ParamD)) 8882 which = 0; 8883 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 8884 which = 1; 8885 else { 8886 which = 2; 8887 } 8888 8889 S.Diag(Templated->getLocation(), 8890 diag::note_ovl_candidate_inconsistent_deduction) 8891 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 8892 << *DeductionFailure.getSecondArg(); 8893 MaybeEmitInheritedConstructorNote(S, Templated); 8894 return; 8895 } 8896 8897 case Sema::TDK_InvalidExplicitArguments: 8898 assert(ParamD && "no parameter found for invalid explicit arguments"); 8899 if (ParamD->getDeclName()) 8900 S.Diag(Templated->getLocation(), 8901 diag::note_ovl_candidate_explicit_arg_mismatch_named) 8902 << ParamD->getDeclName(); 8903 else { 8904 int index = 0; 8905 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 8906 index = TTP->getIndex(); 8907 else if (NonTypeTemplateParmDecl *NTTP 8908 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 8909 index = NTTP->getIndex(); 8910 else 8911 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 8912 S.Diag(Templated->getLocation(), 8913 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 8914 << (index + 1); 8915 } 8916 MaybeEmitInheritedConstructorNote(S, Templated); 8917 return; 8918 8919 case Sema::TDK_TooManyArguments: 8920 case Sema::TDK_TooFewArguments: 8921 DiagnoseArityMismatch(S, Templated, NumArgs); 8922 return; 8923 8924 case Sema::TDK_InstantiationDepth: 8925 S.Diag(Templated->getLocation(), 8926 diag::note_ovl_candidate_instantiation_depth); 8927 MaybeEmitInheritedConstructorNote(S, Templated); 8928 return; 8929 8930 case Sema::TDK_SubstitutionFailure: { 8931 // Format the template argument list into the argument string. 8932 SmallString<128> TemplateArgString; 8933 if (TemplateArgumentList *Args = 8934 DeductionFailure.getTemplateArgumentList()) { 8935 TemplateArgString = " "; 8936 TemplateArgString += S.getTemplateArgumentBindingsText( 8937 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 8938 } 8939 8940 // If this candidate was disabled by enable_if, say so. 8941 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 8942 if (PDiag && PDiag->second.getDiagID() == 8943 diag::err_typename_nested_not_found_enable_if) { 8944 // FIXME: Use the source range of the condition, and the fully-qualified 8945 // name of the enable_if template. These are both present in PDiag. 8946 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 8947 << "'enable_if'" << TemplateArgString; 8948 return; 8949 } 8950 8951 // Format the SFINAE diagnostic into the argument string. 8952 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 8953 // formatted message in another diagnostic. 8954 SmallString<128> SFINAEArgString; 8955 SourceRange R; 8956 if (PDiag) { 8957 SFINAEArgString = ": "; 8958 R = SourceRange(PDiag->first, PDiag->first); 8959 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 8960 } 8961 8962 S.Diag(Templated->getLocation(), 8963 diag::note_ovl_candidate_substitution_failure) 8964 << TemplateArgString << SFINAEArgString << R; 8965 MaybeEmitInheritedConstructorNote(S, Templated); 8966 return; 8967 } 8968 8969 case Sema::TDK_FailedOverloadResolution: { 8970 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 8971 S.Diag(Templated->getLocation(), 8972 diag::note_ovl_candidate_failed_overload_resolution) 8973 << R.Expression->getName(); 8974 return; 8975 } 8976 8977 case Sema::TDK_NonDeducedMismatch: { 8978 // FIXME: Provide a source location to indicate what we couldn't match. 8979 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 8980 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 8981 if (FirstTA.getKind() == TemplateArgument::Template && 8982 SecondTA.getKind() == TemplateArgument::Template) { 8983 TemplateName FirstTN = FirstTA.getAsTemplate(); 8984 TemplateName SecondTN = SecondTA.getAsTemplate(); 8985 if (FirstTN.getKind() == TemplateName::Template && 8986 SecondTN.getKind() == TemplateName::Template) { 8987 if (FirstTN.getAsTemplateDecl()->getName() == 8988 SecondTN.getAsTemplateDecl()->getName()) { 8989 // FIXME: This fixes a bad diagnostic where both templates are named 8990 // the same. This particular case is a bit difficult since: 8991 // 1) It is passed as a string to the diagnostic printer. 8992 // 2) The diagnostic printer only attempts to find a better 8993 // name for types, not decls. 8994 // Ideally, this should folded into the diagnostic printer. 8995 S.Diag(Templated->getLocation(), 8996 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 8997 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 8998 return; 8999 } 9000 } 9001 } 9002 // FIXME: For generic lambda parameters, check if the function is a lambda 9003 // call operator, and if so, emit a prettier and more informative 9004 // diagnostic that mentions 'auto' and lambda in addition to 9005 // (or instead of?) the canonical template type parameters. 9006 S.Diag(Templated->getLocation(), 9007 diag::note_ovl_candidate_non_deduced_mismatch) 9008 << FirstTA << SecondTA; 9009 return; 9010 } 9011 // TODO: diagnose these individually, then kill off 9012 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9013 case Sema::TDK_MiscellaneousDeductionFailure: 9014 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9015 MaybeEmitInheritedConstructorNote(S, Templated); 9016 return; 9017 } 9018 } 9019 9020 /// Diagnose a failed template-argument deduction, for function calls. 9021 void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) { 9022 unsigned TDK = Cand->DeductionFailure.Result; 9023 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9024 if (CheckArityMismatch(S, Cand, NumArgs)) 9025 return; 9026 } 9027 DiagnoseBadDeduction(S, Cand->Function, // pattern 9028 Cand->DeductionFailure, NumArgs); 9029 } 9030 9031 /// CUDA: diagnose an invalid call across targets. 9032 void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9033 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 9034 FunctionDecl *Callee = Cand->Function; 9035 9036 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 9037 CalleeTarget = S.IdentifyCUDATarget(Callee); 9038 9039 std::string FnDesc; 9040 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 9041 9042 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 9043 << (unsigned) FnKind << CalleeTarget << CallerTarget; 9044 } 9045 9046 void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 9047 FunctionDecl *Callee = Cand->Function; 9048 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 9049 9050 S.Diag(Callee->getLocation(), 9051 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9052 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9053 } 9054 9055 /// Generates a 'note' diagnostic for an overload candidate. We've 9056 /// already generated a primary error at the call site. 9057 /// 9058 /// It really does need to be a single diagnostic with its caret 9059 /// pointed at the candidate declaration. Yes, this creates some 9060 /// major challenges of technical writing. Yes, this makes pointing 9061 /// out problems with specific arguments quite awkward. It's still 9062 /// better than generating twenty screens of text for every failed 9063 /// overload. 9064 /// 9065 /// It would be great to be able to express per-candidate problems 9066 /// more richly for those diagnostic clients that cared, but we'd 9067 /// still have to be just as careful with the default diagnostics. 9068 void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9069 unsigned NumArgs) { 9070 FunctionDecl *Fn = Cand->Function; 9071 9072 // Note deleted candidates, but only if they're viable. 9073 if (Cand->Viable && (Fn->isDeleted() || 9074 S.isFunctionConsideredUnavailable(Fn))) { 9075 std::string FnDesc; 9076 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 9077 9078 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9079 << FnKind << FnDesc 9080 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9081 MaybeEmitInheritedConstructorNote(S, Fn); 9082 return; 9083 } 9084 9085 // We don't really have anything else to say about viable candidates. 9086 if (Cand->Viable) { 9087 S.NoteOverloadCandidate(Fn); 9088 return; 9089 } 9090 9091 switch (Cand->FailureKind) { 9092 case ovl_fail_too_many_arguments: 9093 case ovl_fail_too_few_arguments: 9094 return DiagnoseArityMismatch(S, Cand, NumArgs); 9095 9096 case ovl_fail_bad_deduction: 9097 return DiagnoseBadDeduction(S, Cand, NumArgs); 9098 9099 case ovl_fail_trivial_conversion: 9100 case ovl_fail_bad_final_conversion: 9101 case ovl_fail_final_conversion_not_exact: 9102 return S.NoteOverloadCandidate(Fn); 9103 9104 case ovl_fail_bad_conversion: { 9105 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9106 for (unsigned N = Cand->NumConversions; I != N; ++I) 9107 if (Cand->Conversions[I].isBad()) 9108 return DiagnoseBadConversion(S, Cand, I); 9109 9110 // FIXME: this currently happens when we're called from SemaInit 9111 // when user-conversion overload fails. Figure out how to handle 9112 // those conditions and diagnose them well. 9113 return S.NoteOverloadCandidate(Fn); 9114 } 9115 9116 case ovl_fail_bad_target: 9117 return DiagnoseBadTarget(S, Cand); 9118 9119 case ovl_fail_enable_if: 9120 return DiagnoseFailedEnableIfAttr(S, Cand); 9121 } 9122 } 9123 9124 void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9125 // Desugar the type of the surrogate down to a function type, 9126 // retaining as many typedefs as possible while still showing 9127 // the function type (and, therefore, its parameter types). 9128 QualType FnType = Cand->Surrogate->getConversionType(); 9129 bool isLValueReference = false; 9130 bool isRValueReference = false; 9131 bool isPointer = false; 9132 if (const LValueReferenceType *FnTypeRef = 9133 FnType->getAs<LValueReferenceType>()) { 9134 FnType = FnTypeRef->getPointeeType(); 9135 isLValueReference = true; 9136 } else if (const RValueReferenceType *FnTypeRef = 9137 FnType->getAs<RValueReferenceType>()) { 9138 FnType = FnTypeRef->getPointeeType(); 9139 isRValueReference = true; 9140 } 9141 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9142 FnType = FnTypePtr->getPointeeType(); 9143 isPointer = true; 9144 } 9145 // Desugar down to a function type. 9146 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9147 // Reconstruct the pointer/reference as appropriate. 9148 if (isPointer) FnType = S.Context.getPointerType(FnType); 9149 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9150 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9151 9152 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9153 << FnType; 9154 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 9155 } 9156 9157 void NoteBuiltinOperatorCandidate(Sema &S, 9158 StringRef Opc, 9159 SourceLocation OpLoc, 9160 OverloadCandidate *Cand) { 9161 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9162 std::string TypeStr("operator"); 9163 TypeStr += Opc; 9164 TypeStr += "("; 9165 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9166 if (Cand->NumConversions == 1) { 9167 TypeStr += ")"; 9168 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9169 } else { 9170 TypeStr += ", "; 9171 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9172 TypeStr += ")"; 9173 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9174 } 9175 } 9176 9177 void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9178 OverloadCandidate *Cand) { 9179 unsigned NoOperands = Cand->NumConversions; 9180 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9181 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9182 if (ICS.isBad()) break; // all meaningless after first invalid 9183 if (!ICS.isAmbiguous()) continue; 9184 9185 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 9186 S.PDiag(diag::note_ambiguous_type_conversion)); 9187 } 9188 } 9189 9190 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9191 if (Cand->Function) 9192 return Cand->Function->getLocation(); 9193 if (Cand->IsSurrogate) 9194 return Cand->Surrogate->getLocation(); 9195 return SourceLocation(); 9196 } 9197 9198 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 9199 switch ((Sema::TemplateDeductionResult)DFI.Result) { 9200 case Sema::TDK_Success: 9201 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9202 9203 case Sema::TDK_Invalid: 9204 case Sema::TDK_Incomplete: 9205 return 1; 9206 9207 case Sema::TDK_Underqualified: 9208 case Sema::TDK_Inconsistent: 9209 return 2; 9210 9211 case Sema::TDK_SubstitutionFailure: 9212 case Sema::TDK_NonDeducedMismatch: 9213 case Sema::TDK_MiscellaneousDeductionFailure: 9214 return 3; 9215 9216 case Sema::TDK_InstantiationDepth: 9217 case Sema::TDK_FailedOverloadResolution: 9218 return 4; 9219 9220 case Sema::TDK_InvalidExplicitArguments: 9221 return 5; 9222 9223 case Sema::TDK_TooManyArguments: 9224 case Sema::TDK_TooFewArguments: 9225 return 6; 9226 } 9227 llvm_unreachable("Unhandled deduction result"); 9228 } 9229 9230 struct CompareOverloadCandidatesForDisplay { 9231 Sema &S; 9232 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 9233 9234 bool operator()(const OverloadCandidate *L, 9235 const OverloadCandidate *R) { 9236 // Fast-path this check. 9237 if (L == R) return false; 9238 9239 // Order first by viability. 9240 if (L->Viable) { 9241 if (!R->Viable) return true; 9242 9243 // TODO: introduce a tri-valued comparison for overload 9244 // candidates. Would be more worthwhile if we had a sort 9245 // that could exploit it. 9246 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 9247 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 9248 } else if (R->Viable) 9249 return false; 9250 9251 assert(L->Viable == R->Viable); 9252 9253 // Criteria by which we can sort non-viable candidates: 9254 if (!L->Viable) { 9255 // 1. Arity mismatches come after other candidates. 9256 if (L->FailureKind == ovl_fail_too_many_arguments || 9257 L->FailureKind == ovl_fail_too_few_arguments) 9258 return false; 9259 if (R->FailureKind == ovl_fail_too_many_arguments || 9260 R->FailureKind == ovl_fail_too_few_arguments) 9261 return true; 9262 9263 // 2. Bad conversions come first and are ordered by the number 9264 // of bad conversions and quality of good conversions. 9265 if (L->FailureKind == ovl_fail_bad_conversion) { 9266 if (R->FailureKind != ovl_fail_bad_conversion) 9267 return true; 9268 9269 // The conversion that can be fixed with a smaller number of changes, 9270 // comes first. 9271 unsigned numLFixes = L->Fix.NumConversionsFixed; 9272 unsigned numRFixes = R->Fix.NumConversionsFixed; 9273 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 9274 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 9275 if (numLFixes != numRFixes) { 9276 if (numLFixes < numRFixes) 9277 return true; 9278 else 9279 return false; 9280 } 9281 9282 // If there's any ordering between the defined conversions... 9283 // FIXME: this might not be transitive. 9284 assert(L->NumConversions == R->NumConversions); 9285 9286 int leftBetter = 0; 9287 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 9288 for (unsigned E = L->NumConversions; I != E; ++I) { 9289 switch (CompareImplicitConversionSequences(S, 9290 L->Conversions[I], 9291 R->Conversions[I])) { 9292 case ImplicitConversionSequence::Better: 9293 leftBetter++; 9294 break; 9295 9296 case ImplicitConversionSequence::Worse: 9297 leftBetter--; 9298 break; 9299 9300 case ImplicitConversionSequence::Indistinguishable: 9301 break; 9302 } 9303 } 9304 if (leftBetter > 0) return true; 9305 if (leftBetter < 0) return false; 9306 9307 } else if (R->FailureKind == ovl_fail_bad_conversion) 9308 return false; 9309 9310 if (L->FailureKind == ovl_fail_bad_deduction) { 9311 if (R->FailureKind != ovl_fail_bad_deduction) 9312 return true; 9313 9314 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9315 return RankDeductionFailure(L->DeductionFailure) 9316 < RankDeductionFailure(R->DeductionFailure); 9317 } else if (R->FailureKind == ovl_fail_bad_deduction) 9318 return false; 9319 9320 // TODO: others? 9321 } 9322 9323 // Sort everything else by location. 9324 SourceLocation LLoc = GetLocationForCandidate(L); 9325 SourceLocation RLoc = GetLocationForCandidate(R); 9326 9327 // Put candidates without locations (e.g. builtins) at the end. 9328 if (LLoc.isInvalid()) return false; 9329 if (RLoc.isInvalid()) return true; 9330 9331 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9332 } 9333 }; 9334 9335 /// CompleteNonViableCandidate - Normally, overload resolution only 9336 /// computes up to the first. Produces the FixIt set if possible. 9337 void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 9338 ArrayRef<Expr *> Args) { 9339 assert(!Cand->Viable); 9340 9341 // Don't do anything on failures other than bad conversion. 9342 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 9343 9344 // We only want the FixIts if all the arguments can be corrected. 9345 bool Unfixable = false; 9346 // Use a implicit copy initialization to check conversion fixes. 9347 Cand->Fix.setConversionChecker(TryCopyInitialization); 9348 9349 // Skip forward to the first bad conversion. 9350 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 9351 unsigned ConvCount = Cand->NumConversions; 9352 while (true) { 9353 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 9354 ConvIdx++; 9355 if (Cand->Conversions[ConvIdx - 1].isBad()) { 9356 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 9357 break; 9358 } 9359 } 9360 9361 if (ConvIdx == ConvCount) 9362 return; 9363 9364 assert(!Cand->Conversions[ConvIdx].isInitialized() && 9365 "remaining conversion is initialized?"); 9366 9367 // FIXME: this should probably be preserved from the overload 9368 // operation somehow. 9369 bool SuppressUserConversions = false; 9370 9371 const FunctionProtoType* Proto; 9372 unsigned ArgIdx = ConvIdx; 9373 9374 if (Cand->IsSurrogate) { 9375 QualType ConvType 9376 = Cand->Surrogate->getConversionType().getNonReferenceType(); 9377 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9378 ConvType = ConvPtrType->getPointeeType(); 9379 Proto = ConvType->getAs<FunctionProtoType>(); 9380 ArgIdx--; 9381 } else if (Cand->Function) { 9382 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 9383 if (isa<CXXMethodDecl>(Cand->Function) && 9384 !isa<CXXConstructorDecl>(Cand->Function)) 9385 ArgIdx--; 9386 } else { 9387 // Builtin binary operator with a bad first conversion. 9388 assert(ConvCount <= 3); 9389 for (; ConvIdx != ConvCount; ++ConvIdx) 9390 Cand->Conversions[ConvIdx] 9391 = TryCopyInitialization(S, Args[ConvIdx], 9392 Cand->BuiltinTypes.ParamTypes[ConvIdx], 9393 SuppressUserConversions, 9394 /*InOverloadResolution*/ true, 9395 /*AllowObjCWritebackConversion=*/ 9396 S.getLangOpts().ObjCAutoRefCount); 9397 return; 9398 } 9399 9400 // Fill in the rest of the conversions. 9401 unsigned NumParams = Proto->getNumParams(); 9402 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 9403 if (ArgIdx < NumParams) { 9404 Cand->Conversions[ConvIdx] = TryCopyInitialization( 9405 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 9406 /*InOverloadResolution=*/true, 9407 /*AllowObjCWritebackConversion=*/ 9408 S.getLangOpts().ObjCAutoRefCount); 9409 // Store the FixIt in the candidate if it exists. 9410 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 9411 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 9412 } 9413 else 9414 Cand->Conversions[ConvIdx].setEllipsis(); 9415 } 9416 } 9417 9418 } // end anonymous namespace 9419 9420 /// PrintOverloadCandidates - When overload resolution fails, prints 9421 /// diagnostic messages containing the candidates in the candidate 9422 /// set. 9423 void OverloadCandidateSet::NoteCandidates(Sema &S, 9424 OverloadCandidateDisplayKind OCD, 9425 ArrayRef<Expr *> Args, 9426 StringRef Opc, 9427 SourceLocation OpLoc) { 9428 // Sort the candidates by viability and position. Sorting directly would 9429 // be prohibitive, so we make a set of pointers and sort those. 9430 SmallVector<OverloadCandidate*, 32> Cands; 9431 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 9432 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9433 if (Cand->Viable) 9434 Cands.push_back(Cand); 9435 else if (OCD == OCD_AllCandidates) { 9436 CompleteNonViableCandidate(S, Cand, Args); 9437 if (Cand->Function || Cand->IsSurrogate) 9438 Cands.push_back(Cand); 9439 // Otherwise, this a non-viable builtin candidate. We do not, in general, 9440 // want to list every possible builtin candidate. 9441 } 9442 } 9443 9444 std::sort(Cands.begin(), Cands.end(), 9445 CompareOverloadCandidatesForDisplay(S)); 9446 9447 bool ReportedAmbiguousConversions = false; 9448 9449 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 9450 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9451 unsigned CandsShown = 0; 9452 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9453 OverloadCandidate *Cand = *I; 9454 9455 // Set an arbitrary limit on the number of candidate functions we'll spam 9456 // the user with. FIXME: This limit should depend on details of the 9457 // candidate list. 9458 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 9459 break; 9460 } 9461 ++CandsShown; 9462 9463 if (Cand->Function) 9464 NoteFunctionCandidate(S, Cand, Args.size()); 9465 else if (Cand->IsSurrogate) 9466 NoteSurrogateCandidate(S, Cand); 9467 else { 9468 assert(Cand->Viable && 9469 "Non-viable built-in candidates are not added to Cands."); 9470 // Generally we only see ambiguities including viable builtin 9471 // operators if overload resolution got screwed up by an 9472 // ambiguous user-defined conversion. 9473 // 9474 // FIXME: It's quite possible for different conversions to see 9475 // different ambiguities, though. 9476 if (!ReportedAmbiguousConversions) { 9477 NoteAmbiguousUserConversions(S, OpLoc, Cand); 9478 ReportedAmbiguousConversions = true; 9479 } 9480 9481 // If this is a viable builtin, print it. 9482 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 9483 } 9484 } 9485 9486 if (I != E) 9487 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 9488 } 9489 9490 static SourceLocation 9491 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 9492 return Cand->Specialization ? Cand->Specialization->getLocation() 9493 : SourceLocation(); 9494 } 9495 9496 struct CompareTemplateSpecCandidatesForDisplay { 9497 Sema &S; 9498 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 9499 9500 bool operator()(const TemplateSpecCandidate *L, 9501 const TemplateSpecCandidate *R) { 9502 // Fast-path this check. 9503 if (L == R) 9504 return false; 9505 9506 // Assuming that both candidates are not matches... 9507 9508 // Sort by the ranking of deduction failures. 9509 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9510 return RankDeductionFailure(L->DeductionFailure) < 9511 RankDeductionFailure(R->DeductionFailure); 9512 9513 // Sort everything else by location. 9514 SourceLocation LLoc = GetLocationForCandidate(L); 9515 SourceLocation RLoc = GetLocationForCandidate(R); 9516 9517 // Put candidates without locations (e.g. builtins) at the end. 9518 if (LLoc.isInvalid()) 9519 return false; 9520 if (RLoc.isInvalid()) 9521 return true; 9522 9523 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9524 } 9525 }; 9526 9527 /// Diagnose a template argument deduction failure. 9528 /// We are treating these failures as overload failures due to bad 9529 /// deductions. 9530 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) { 9531 DiagnoseBadDeduction(S, Specialization, // pattern 9532 DeductionFailure, /*NumArgs=*/0); 9533 } 9534 9535 void TemplateSpecCandidateSet::destroyCandidates() { 9536 for (iterator i = begin(), e = end(); i != e; ++i) { 9537 i->DeductionFailure.Destroy(); 9538 } 9539 } 9540 9541 void TemplateSpecCandidateSet::clear() { 9542 destroyCandidates(); 9543 Candidates.clear(); 9544 } 9545 9546 /// NoteCandidates - When no template specialization match is found, prints 9547 /// diagnostic messages containing the non-matching specializations that form 9548 /// the candidate set. 9549 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 9550 /// OCD == OCD_AllCandidates and Cand->Viable == false. 9551 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 9552 // Sort the candidates by position (assuming no candidate is a match). 9553 // Sorting directly would be prohibitive, so we make a set of pointers 9554 // and sort those. 9555 SmallVector<TemplateSpecCandidate *, 32> Cands; 9556 Cands.reserve(size()); 9557 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9558 if (Cand->Specialization) 9559 Cands.push_back(Cand); 9560 // Otherwise, this is a non-matching builtin candidate. We do not, 9561 // in general, want to list every possible builtin candidate. 9562 } 9563 9564 std::sort(Cands.begin(), Cands.end(), 9565 CompareTemplateSpecCandidatesForDisplay(S)); 9566 9567 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 9568 // for generalization purposes (?). 9569 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9570 9571 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 9572 unsigned CandsShown = 0; 9573 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9574 TemplateSpecCandidate *Cand = *I; 9575 9576 // Set an arbitrary limit on the number of candidates we'll spam 9577 // the user with. FIXME: This limit should depend on details of the 9578 // candidate list. 9579 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9580 break; 9581 ++CandsShown; 9582 9583 assert(Cand->Specialization && 9584 "Non-matching built-in candidates are not added to Cands."); 9585 Cand->NoteDeductionFailure(S); 9586 } 9587 9588 if (I != E) 9589 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 9590 } 9591 9592 // [PossiblyAFunctionType] --> [Return] 9593 // NonFunctionType --> NonFunctionType 9594 // R (A) --> R(A) 9595 // R (*)(A) --> R (A) 9596 // R (&)(A) --> R (A) 9597 // R (S::*)(A) --> R (A) 9598 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 9599 QualType Ret = PossiblyAFunctionType; 9600 if (const PointerType *ToTypePtr = 9601 PossiblyAFunctionType->getAs<PointerType>()) 9602 Ret = ToTypePtr->getPointeeType(); 9603 else if (const ReferenceType *ToTypeRef = 9604 PossiblyAFunctionType->getAs<ReferenceType>()) 9605 Ret = ToTypeRef->getPointeeType(); 9606 else if (const MemberPointerType *MemTypePtr = 9607 PossiblyAFunctionType->getAs<MemberPointerType>()) 9608 Ret = MemTypePtr->getPointeeType(); 9609 Ret = 9610 Context.getCanonicalType(Ret).getUnqualifiedType(); 9611 return Ret; 9612 } 9613 9614 // A helper class to help with address of function resolution 9615 // - allows us to avoid passing around all those ugly parameters 9616 class AddressOfFunctionResolver 9617 { 9618 Sema& S; 9619 Expr* SourceExpr; 9620 const QualType& TargetType; 9621 QualType TargetFunctionType; // Extracted function type from target type 9622 9623 bool Complain; 9624 //DeclAccessPair& ResultFunctionAccessPair; 9625 ASTContext& Context; 9626 9627 bool TargetTypeIsNonStaticMemberFunction; 9628 bool FoundNonTemplateFunction; 9629 bool StaticMemberFunctionFromBoundPointer; 9630 9631 OverloadExpr::FindResult OvlExprInfo; 9632 OverloadExpr *OvlExpr; 9633 TemplateArgumentListInfo OvlExplicitTemplateArgs; 9634 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 9635 TemplateSpecCandidateSet FailedCandidates; 9636 9637 public: 9638 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 9639 const QualType &TargetType, bool Complain) 9640 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 9641 Complain(Complain), Context(S.getASTContext()), 9642 TargetTypeIsNonStaticMemberFunction( 9643 !!TargetType->getAs<MemberPointerType>()), 9644 FoundNonTemplateFunction(false), 9645 StaticMemberFunctionFromBoundPointer(false), 9646 OvlExprInfo(OverloadExpr::find(SourceExpr)), 9647 OvlExpr(OvlExprInfo.Expression), 9648 FailedCandidates(OvlExpr->getNameLoc()) { 9649 ExtractUnqualifiedFunctionTypeFromTargetType(); 9650 9651 if (TargetFunctionType->isFunctionType()) { 9652 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 9653 if (!UME->isImplicitAccess() && 9654 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 9655 StaticMemberFunctionFromBoundPointer = true; 9656 } else if (OvlExpr->hasExplicitTemplateArgs()) { 9657 DeclAccessPair dap; 9658 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 9659 OvlExpr, false, &dap)) { 9660 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 9661 if (!Method->isStatic()) { 9662 // If the target type is a non-function type and the function found 9663 // is a non-static member function, pretend as if that was the 9664 // target, it's the only possible type to end up with. 9665 TargetTypeIsNonStaticMemberFunction = true; 9666 9667 // And skip adding the function if its not in the proper form. 9668 // We'll diagnose this due to an empty set of functions. 9669 if (!OvlExprInfo.HasFormOfMemberPointer) 9670 return; 9671 } 9672 9673 Matches.push_back(std::make_pair(dap, Fn)); 9674 } 9675 return; 9676 } 9677 9678 if (OvlExpr->hasExplicitTemplateArgs()) 9679 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 9680 9681 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 9682 // C++ [over.over]p4: 9683 // If more than one function is selected, [...] 9684 if (Matches.size() > 1) { 9685 if (FoundNonTemplateFunction) 9686 EliminateAllTemplateMatches(); 9687 else 9688 EliminateAllExceptMostSpecializedTemplate(); 9689 } 9690 } 9691 } 9692 9693 private: 9694 bool isTargetTypeAFunction() const { 9695 return TargetFunctionType->isFunctionType(); 9696 } 9697 9698 // [ToType] [Return] 9699 9700 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 9701 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 9702 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 9703 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 9704 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 9705 } 9706 9707 // return true if any matching specializations were found 9708 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 9709 const DeclAccessPair& CurAccessFunPair) { 9710 if (CXXMethodDecl *Method 9711 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 9712 // Skip non-static function templates when converting to pointer, and 9713 // static when converting to member pointer. 9714 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9715 return false; 9716 } 9717 else if (TargetTypeIsNonStaticMemberFunction) 9718 return false; 9719 9720 // C++ [over.over]p2: 9721 // If the name is a function template, template argument deduction is 9722 // done (14.8.2.2), and if the argument deduction succeeds, the 9723 // resulting template argument list is used to generate a single 9724 // function template specialization, which is added to the set of 9725 // overloaded functions considered. 9726 FunctionDecl *Specialization = 0; 9727 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 9728 if (Sema::TemplateDeductionResult Result 9729 = S.DeduceTemplateArguments(FunctionTemplate, 9730 &OvlExplicitTemplateArgs, 9731 TargetFunctionType, Specialization, 9732 Info, /*InOverloadResolution=*/true)) { 9733 // Make a note of the failed deduction for diagnostics. 9734 FailedCandidates.addCandidate() 9735 .set(FunctionTemplate->getTemplatedDecl(), 9736 MakeDeductionFailureInfo(Context, Result, Info)); 9737 return false; 9738 } 9739 9740 // Template argument deduction ensures that we have an exact match or 9741 // compatible pointer-to-function arguments that would be adjusted by ICS. 9742 // This function template specicalization works. 9743 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 9744 assert(S.isSameOrCompatibleFunctionType( 9745 Context.getCanonicalType(Specialization->getType()), 9746 Context.getCanonicalType(TargetFunctionType))); 9747 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 9748 return true; 9749 } 9750 9751 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9752 const DeclAccessPair& CurAccessFunPair) { 9753 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9754 // Skip non-static functions when converting to pointer, and static 9755 // when converting to member pointer. 9756 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9757 return false; 9758 } 9759 else if (TargetTypeIsNonStaticMemberFunction) 9760 return false; 9761 9762 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9763 if (S.getLangOpts().CUDA) 9764 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9765 if (S.CheckCUDATarget(Caller, FunDecl)) 9766 return false; 9767 9768 // If any candidate has a placeholder return type, trigger its deduction 9769 // now. 9770 if (S.getLangOpts().CPlusPlus1y && 9771 FunDecl->getReturnType()->isUndeducedType() && 9772 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) 9773 return false; 9774 9775 QualType ResultTy; 9776 if (Context.hasSameUnqualifiedType(TargetFunctionType, 9777 FunDecl->getType()) || 9778 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9779 ResultTy)) { 9780 Matches.push_back(std::make_pair(CurAccessFunPair, 9781 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9782 FoundNonTemplateFunction = true; 9783 return true; 9784 } 9785 } 9786 9787 return false; 9788 } 9789 9790 bool FindAllFunctionsThatMatchTargetTypeExactly() { 9791 bool Ret = false; 9792 9793 // If the overload expression doesn't have the form of a pointer to 9794 // member, don't try to convert it to a pointer-to-member type. 9795 if (IsInvalidFormOfPointerToMemberFunction()) 9796 return false; 9797 9798 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9799 E = OvlExpr->decls_end(); 9800 I != E; ++I) { 9801 // Look through any using declarations to find the underlying function. 9802 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 9803 9804 // C++ [over.over]p3: 9805 // Non-member functions and static member functions match 9806 // targets of type "pointer-to-function" or "reference-to-function." 9807 // Nonstatic member functions match targets of 9808 // type "pointer-to-member-function." 9809 // Note that according to DR 247, the containing class does not matter. 9810 if (FunctionTemplateDecl *FunctionTemplate 9811 = dyn_cast<FunctionTemplateDecl>(Fn)) { 9812 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 9813 Ret = true; 9814 } 9815 // If we have explicit template arguments supplied, skip non-templates. 9816 else if (!OvlExpr->hasExplicitTemplateArgs() && 9817 AddMatchingNonTemplateFunction(Fn, I.getPair())) 9818 Ret = true; 9819 } 9820 assert(Ret || Matches.empty()); 9821 return Ret; 9822 } 9823 9824 void EliminateAllExceptMostSpecializedTemplate() { 9825 // [...] and any given function template specialization F1 is 9826 // eliminated if the set contains a second function template 9827 // specialization whose function template is more specialized 9828 // than the function template of F1 according to the partial 9829 // ordering rules of 14.5.5.2. 9830 9831 // The algorithm specified above is quadratic. We instead use a 9832 // two-pass algorithm (similar to the one used to identify the 9833 // best viable function in an overload set) that identifies the 9834 // best function template (if it exists). 9835 9836 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 9837 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 9838 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 9839 9840 // TODO: It looks like FailedCandidates does not serve much purpose 9841 // here, since the no_viable diagnostic has index 0. 9842 UnresolvedSetIterator Result = S.getMostSpecialized( 9843 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 9844 SourceExpr->getLocStart(), S.PDiag(), 9845 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0] 9846 .second->getDeclName(), 9847 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template, 9848 Complain, TargetFunctionType); 9849 9850 if (Result != MatchesCopy.end()) { 9851 // Make it the first and only element 9852 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 9853 Matches[0].second = cast<FunctionDecl>(*Result); 9854 Matches.resize(1); 9855 } 9856 } 9857 9858 void EliminateAllTemplateMatches() { 9859 // [...] any function template specializations in the set are 9860 // eliminated if the set also contains a non-template function, [...] 9861 for (unsigned I = 0, N = Matches.size(); I != N; ) { 9862 if (Matches[I].second->getPrimaryTemplate() == 0) 9863 ++I; 9864 else { 9865 Matches[I] = Matches[--N]; 9866 Matches.set_size(N); 9867 } 9868 } 9869 } 9870 9871 public: 9872 void ComplainNoMatchesFound() const { 9873 assert(Matches.empty()); 9874 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 9875 << OvlExpr->getName() << TargetFunctionType 9876 << OvlExpr->getSourceRange(); 9877 if (FailedCandidates.empty()) 9878 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9879 else { 9880 // We have some deduction failure messages. Use them to diagnose 9881 // the function templates, and diagnose the non-template candidates 9882 // normally. 9883 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9884 IEnd = OvlExpr->decls_end(); 9885 I != IEnd; ++I) 9886 if (FunctionDecl *Fun = 9887 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 9888 S.NoteOverloadCandidate(Fun, TargetFunctionType); 9889 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 9890 } 9891 } 9892 9893 bool IsInvalidFormOfPointerToMemberFunction() const { 9894 return TargetTypeIsNonStaticMemberFunction && 9895 !OvlExprInfo.HasFormOfMemberPointer; 9896 } 9897 9898 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 9899 // TODO: Should we condition this on whether any functions might 9900 // have matched, or is it more appropriate to do that in callers? 9901 // TODO: a fixit wouldn't hurt. 9902 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 9903 << TargetType << OvlExpr->getSourceRange(); 9904 } 9905 9906 bool IsStaticMemberFunctionFromBoundPointer() const { 9907 return StaticMemberFunctionFromBoundPointer; 9908 } 9909 9910 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 9911 S.Diag(OvlExpr->getLocStart(), 9912 diag::err_invalid_form_pointer_member_function) 9913 << OvlExpr->getSourceRange(); 9914 } 9915 9916 void ComplainOfInvalidConversion() const { 9917 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 9918 << OvlExpr->getName() << TargetType; 9919 } 9920 9921 void ComplainMultipleMatchesFound() const { 9922 assert(Matches.size() > 1); 9923 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 9924 << OvlExpr->getName() 9925 << OvlExpr->getSourceRange(); 9926 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9927 } 9928 9929 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 9930 9931 int getNumMatches() const { return Matches.size(); } 9932 9933 FunctionDecl* getMatchingFunctionDecl() const { 9934 if (Matches.size() != 1) return 0; 9935 return Matches[0].second; 9936 } 9937 9938 const DeclAccessPair* getMatchingFunctionAccessPair() const { 9939 if (Matches.size() != 1) return 0; 9940 return &Matches[0].first; 9941 } 9942 }; 9943 9944 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 9945 /// an overloaded function (C++ [over.over]), where @p From is an 9946 /// expression with overloaded function type and @p ToType is the type 9947 /// we're trying to resolve to. For example: 9948 /// 9949 /// @code 9950 /// int f(double); 9951 /// int f(int); 9952 /// 9953 /// int (*pfd)(double) = f; // selects f(double) 9954 /// @endcode 9955 /// 9956 /// This routine returns the resulting FunctionDecl if it could be 9957 /// resolved, and NULL otherwise. When @p Complain is true, this 9958 /// routine will emit diagnostics if there is an error. 9959 FunctionDecl * 9960 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 9961 QualType TargetType, 9962 bool Complain, 9963 DeclAccessPair &FoundResult, 9964 bool *pHadMultipleCandidates) { 9965 assert(AddressOfExpr->getType() == Context.OverloadTy); 9966 9967 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 9968 Complain); 9969 int NumMatches = Resolver.getNumMatches(); 9970 FunctionDecl* Fn = 0; 9971 if (NumMatches == 0 && Complain) { 9972 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 9973 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 9974 else 9975 Resolver.ComplainNoMatchesFound(); 9976 } 9977 else if (NumMatches > 1 && Complain) 9978 Resolver.ComplainMultipleMatchesFound(); 9979 else if (NumMatches == 1) { 9980 Fn = Resolver.getMatchingFunctionDecl(); 9981 assert(Fn); 9982 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 9983 if (Complain) { 9984 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 9985 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 9986 else 9987 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 9988 } 9989 } 9990 9991 if (pHadMultipleCandidates) 9992 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 9993 return Fn; 9994 } 9995 9996 /// \brief Given an expression that refers to an overloaded function, try to 9997 /// resolve that overloaded function expression down to a single function. 9998 /// 9999 /// This routine can only resolve template-ids that refer to a single function 10000 /// template, where that template-id refers to a single template whose template 10001 /// arguments are either provided by the template-id or have defaults, 10002 /// as described in C++0x [temp.arg.explicit]p3. 10003 /// 10004 /// If no template-ids are found, no diagnostics are emitted and NULL is 10005 /// returned. 10006 FunctionDecl * 10007 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 10008 bool Complain, 10009 DeclAccessPair *FoundResult) { 10010 // C++ [over.over]p1: 10011 // [...] [Note: any redundant set of parentheses surrounding the 10012 // overloaded function name is ignored (5.1). ] 10013 // C++ [over.over]p1: 10014 // [...] The overloaded function name can be preceded by the & 10015 // operator. 10016 10017 // If we didn't actually find any template-ids, we're done. 10018 if (!ovl->hasExplicitTemplateArgs()) 10019 return 0; 10020 10021 TemplateArgumentListInfo ExplicitTemplateArgs; 10022 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 10023 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 10024 10025 // Look through all of the overloaded functions, searching for one 10026 // whose type matches exactly. 10027 FunctionDecl *Matched = 0; 10028 for (UnresolvedSetIterator I = ovl->decls_begin(), 10029 E = ovl->decls_end(); I != E; ++I) { 10030 // C++0x [temp.arg.explicit]p3: 10031 // [...] In contexts where deduction is done and fails, or in contexts 10032 // where deduction is not done, if a template argument list is 10033 // specified and it, along with any default template arguments, 10034 // identifies a single function template specialization, then the 10035 // template-id is an lvalue for the function template specialization. 10036 FunctionTemplateDecl *FunctionTemplate 10037 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 10038 10039 // C++ [over.over]p2: 10040 // If the name is a function template, template argument deduction is 10041 // done (14.8.2.2), and if the argument deduction succeeds, the 10042 // resulting template argument list is used to generate a single 10043 // function template specialization, which is added to the set of 10044 // overloaded functions considered. 10045 FunctionDecl *Specialization = 0; 10046 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10047 if (TemplateDeductionResult Result 10048 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 10049 Specialization, Info, 10050 /*InOverloadResolution=*/true)) { 10051 // Make a note of the failed deduction for diagnostics. 10052 // TODO: Actually use the failed-deduction info? 10053 FailedCandidates.addCandidate() 10054 .set(FunctionTemplate->getTemplatedDecl(), 10055 MakeDeductionFailureInfo(Context, Result, Info)); 10056 continue; 10057 } 10058 10059 assert(Specialization && "no specialization and no error?"); 10060 10061 // Multiple matches; we can't resolve to a single declaration. 10062 if (Matched) { 10063 if (Complain) { 10064 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 10065 << ovl->getName(); 10066 NoteAllOverloadCandidates(ovl); 10067 } 10068 return 0; 10069 } 10070 10071 Matched = Specialization; 10072 if (FoundResult) *FoundResult = I.getPair(); 10073 } 10074 10075 if (Matched && getLangOpts().CPlusPlus1y && 10076 Matched->getReturnType()->isUndeducedType() && 10077 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 10078 return 0; 10079 10080 return Matched; 10081 } 10082 10083 10084 10085 10086 // Resolve and fix an overloaded expression that can be resolved 10087 // because it identifies a single function template specialization. 10088 // 10089 // Last three arguments should only be supplied if Complain = true 10090 // 10091 // Return true if it was logically possible to so resolve the 10092 // expression, regardless of whether or not it succeeded. Always 10093 // returns true if 'complain' is set. 10094 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 10095 ExprResult &SrcExpr, bool doFunctionPointerConverion, 10096 bool complain, const SourceRange& OpRangeForComplaining, 10097 QualType DestTypeForComplaining, 10098 unsigned DiagIDForComplaining) { 10099 assert(SrcExpr.get()->getType() == Context.OverloadTy); 10100 10101 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 10102 10103 DeclAccessPair found; 10104 ExprResult SingleFunctionExpression; 10105 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 10106 ovl.Expression, /*complain*/ false, &found)) { 10107 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 10108 SrcExpr = ExprError(); 10109 return true; 10110 } 10111 10112 // It is only correct to resolve to an instance method if we're 10113 // resolving a form that's permitted to be a pointer to member. 10114 // Otherwise we'll end up making a bound member expression, which 10115 // is illegal in all the contexts we resolve like this. 10116 if (!ovl.HasFormOfMemberPointer && 10117 isa<CXXMethodDecl>(fn) && 10118 cast<CXXMethodDecl>(fn)->isInstance()) { 10119 if (!complain) return false; 10120 10121 Diag(ovl.Expression->getExprLoc(), 10122 diag::err_bound_member_function) 10123 << 0 << ovl.Expression->getSourceRange(); 10124 10125 // TODO: I believe we only end up here if there's a mix of 10126 // static and non-static candidates (otherwise the expression 10127 // would have 'bound member' type, not 'overload' type). 10128 // Ideally we would note which candidate was chosen and why 10129 // the static candidates were rejected. 10130 SrcExpr = ExprError(); 10131 return true; 10132 } 10133 10134 // Fix the expression to refer to 'fn'. 10135 SingleFunctionExpression = 10136 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn)); 10137 10138 // If desired, do function-to-pointer decay. 10139 if (doFunctionPointerConverion) { 10140 SingleFunctionExpression = 10141 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take()); 10142 if (SingleFunctionExpression.isInvalid()) { 10143 SrcExpr = ExprError(); 10144 return true; 10145 } 10146 } 10147 } 10148 10149 if (!SingleFunctionExpression.isUsable()) { 10150 if (complain) { 10151 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 10152 << ovl.Expression->getName() 10153 << DestTypeForComplaining 10154 << OpRangeForComplaining 10155 << ovl.Expression->getQualifierLoc().getSourceRange(); 10156 NoteAllOverloadCandidates(SrcExpr.get()); 10157 10158 SrcExpr = ExprError(); 10159 return true; 10160 } 10161 10162 return false; 10163 } 10164 10165 SrcExpr = SingleFunctionExpression; 10166 return true; 10167 } 10168 10169 /// \brief Add a single candidate to the overload set. 10170 static void AddOverloadedCallCandidate(Sema &S, 10171 DeclAccessPair FoundDecl, 10172 TemplateArgumentListInfo *ExplicitTemplateArgs, 10173 ArrayRef<Expr *> Args, 10174 OverloadCandidateSet &CandidateSet, 10175 bool PartialOverloading, 10176 bool KnownValid) { 10177 NamedDecl *Callee = FoundDecl.getDecl(); 10178 if (isa<UsingShadowDecl>(Callee)) 10179 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 10180 10181 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 10182 if (ExplicitTemplateArgs) { 10183 assert(!KnownValid && "Explicit template arguments?"); 10184 return; 10185 } 10186 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false, 10187 PartialOverloading); 10188 return; 10189 } 10190 10191 if (FunctionTemplateDecl *FuncTemplate 10192 = dyn_cast<FunctionTemplateDecl>(Callee)) { 10193 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 10194 ExplicitTemplateArgs, Args, CandidateSet); 10195 return; 10196 } 10197 10198 assert(!KnownValid && "unhandled case in overloaded call candidate"); 10199 } 10200 10201 /// \brief Add the overload candidates named by callee and/or found by argument 10202 /// dependent lookup to the given overload set. 10203 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 10204 ArrayRef<Expr *> Args, 10205 OverloadCandidateSet &CandidateSet, 10206 bool PartialOverloading) { 10207 10208 #ifndef NDEBUG 10209 // Verify that ArgumentDependentLookup is consistent with the rules 10210 // in C++0x [basic.lookup.argdep]p3: 10211 // 10212 // Let X be the lookup set produced by unqualified lookup (3.4.1) 10213 // and let Y be the lookup set produced by argument dependent 10214 // lookup (defined as follows). If X contains 10215 // 10216 // -- a declaration of a class member, or 10217 // 10218 // -- a block-scope function declaration that is not a 10219 // using-declaration, or 10220 // 10221 // -- a declaration that is neither a function or a function 10222 // template 10223 // 10224 // then Y is empty. 10225 10226 if (ULE->requiresADL()) { 10227 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10228 E = ULE->decls_end(); I != E; ++I) { 10229 assert(!(*I)->getDeclContext()->isRecord()); 10230 assert(isa<UsingShadowDecl>(*I) || 10231 !(*I)->getDeclContext()->isFunctionOrMethod()); 10232 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 10233 } 10234 } 10235 #endif 10236 10237 // It would be nice to avoid this copy. 10238 TemplateArgumentListInfo TABuffer; 10239 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 10240 if (ULE->hasExplicitTemplateArgs()) { 10241 ULE->copyTemplateArgumentsInto(TABuffer); 10242 ExplicitTemplateArgs = &TABuffer; 10243 } 10244 10245 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10246 E = ULE->decls_end(); I != E; ++I) 10247 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 10248 CandidateSet, PartialOverloading, 10249 /*KnownValid*/ true); 10250 10251 if (ULE->requiresADL()) 10252 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 10253 Args, ExplicitTemplateArgs, 10254 CandidateSet, PartialOverloading); 10255 } 10256 10257 /// Determine whether a declaration with the specified name could be moved into 10258 /// a different namespace. 10259 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 10260 switch (Name.getCXXOverloadedOperator()) { 10261 case OO_New: case OO_Array_New: 10262 case OO_Delete: case OO_Array_Delete: 10263 return false; 10264 10265 default: 10266 return true; 10267 } 10268 } 10269 10270 /// Attempt to recover from an ill-formed use of a non-dependent name in a 10271 /// template, where the non-dependent name was declared after the template 10272 /// was defined. This is common in code written for a compilers which do not 10273 /// correctly implement two-stage name lookup. 10274 /// 10275 /// Returns true if a viable candidate was found and a diagnostic was issued. 10276 static bool 10277 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 10278 const CXXScopeSpec &SS, LookupResult &R, 10279 OverloadCandidateSet::CandidateSetKind CSK, 10280 TemplateArgumentListInfo *ExplicitTemplateArgs, 10281 ArrayRef<Expr *> Args) { 10282 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 10283 return false; 10284 10285 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 10286 if (DC->isTransparentContext()) 10287 continue; 10288 10289 SemaRef.LookupQualifiedName(R, DC); 10290 10291 if (!R.empty()) { 10292 R.suppressDiagnostics(); 10293 10294 if (isa<CXXRecordDecl>(DC)) { 10295 // Don't diagnose names we find in classes; we get much better 10296 // diagnostics for these from DiagnoseEmptyLookup. 10297 R.clear(); 10298 return false; 10299 } 10300 10301 OverloadCandidateSet Candidates(FnLoc, CSK); 10302 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10303 AddOverloadedCallCandidate(SemaRef, I.getPair(), 10304 ExplicitTemplateArgs, Args, 10305 Candidates, false, /*KnownValid*/ false); 10306 10307 OverloadCandidateSet::iterator Best; 10308 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 10309 // No viable functions. Don't bother the user with notes for functions 10310 // which don't work and shouldn't be found anyway. 10311 R.clear(); 10312 return false; 10313 } 10314 10315 // Find the namespaces where ADL would have looked, and suggest 10316 // declaring the function there instead. 10317 Sema::AssociatedNamespaceSet AssociatedNamespaces; 10318 Sema::AssociatedClassSet AssociatedClasses; 10319 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 10320 AssociatedNamespaces, 10321 AssociatedClasses); 10322 Sema::AssociatedNamespaceSet SuggestedNamespaces; 10323 if (canBeDeclaredInNamespace(R.getLookupName())) { 10324 DeclContext *Std = SemaRef.getStdNamespace(); 10325 for (Sema::AssociatedNamespaceSet::iterator 10326 it = AssociatedNamespaces.begin(), 10327 end = AssociatedNamespaces.end(); it != end; ++it) { 10328 // Never suggest declaring a function within namespace 'std'. 10329 if (Std && Std->Encloses(*it)) 10330 continue; 10331 10332 // Never suggest declaring a function within a namespace with a 10333 // reserved name, like __gnu_cxx. 10334 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 10335 if (NS && 10336 NS->getQualifiedNameAsString().find("__") != std::string::npos) 10337 continue; 10338 10339 SuggestedNamespaces.insert(*it); 10340 } 10341 } 10342 10343 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 10344 << R.getLookupName(); 10345 if (SuggestedNamespaces.empty()) { 10346 SemaRef.Diag(Best->Function->getLocation(), 10347 diag::note_not_found_by_two_phase_lookup) 10348 << R.getLookupName() << 0; 10349 } else if (SuggestedNamespaces.size() == 1) { 10350 SemaRef.Diag(Best->Function->getLocation(), 10351 diag::note_not_found_by_two_phase_lookup) 10352 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 10353 } else { 10354 // FIXME: It would be useful to list the associated namespaces here, 10355 // but the diagnostics infrastructure doesn't provide a way to produce 10356 // a localized representation of a list of items. 10357 SemaRef.Diag(Best->Function->getLocation(), 10358 diag::note_not_found_by_two_phase_lookup) 10359 << R.getLookupName() << 2; 10360 } 10361 10362 // Try to recover by calling this function. 10363 return true; 10364 } 10365 10366 R.clear(); 10367 } 10368 10369 return false; 10370 } 10371 10372 /// Attempt to recover from ill-formed use of a non-dependent operator in a 10373 /// template, where the non-dependent operator was declared after the template 10374 /// was defined. 10375 /// 10376 /// Returns true if a viable candidate was found and a diagnostic was issued. 10377 static bool 10378 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 10379 SourceLocation OpLoc, 10380 ArrayRef<Expr *> Args) { 10381 DeclarationName OpName = 10382 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 10383 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 10384 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 10385 OverloadCandidateSet::CSK_Operator, 10386 /*ExplicitTemplateArgs=*/0, Args); 10387 } 10388 10389 namespace { 10390 class BuildRecoveryCallExprRAII { 10391 Sema &SemaRef; 10392 public: 10393 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 10394 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 10395 SemaRef.IsBuildingRecoveryCallExpr = true; 10396 } 10397 10398 ~BuildRecoveryCallExprRAII() { 10399 SemaRef.IsBuildingRecoveryCallExpr = false; 10400 } 10401 }; 10402 10403 } 10404 10405 /// Attempts to recover from a call where no functions were found. 10406 /// 10407 /// Returns true if new candidates were found. 10408 static ExprResult 10409 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10410 UnresolvedLookupExpr *ULE, 10411 SourceLocation LParenLoc, 10412 llvm::MutableArrayRef<Expr *> Args, 10413 SourceLocation RParenLoc, 10414 bool EmptyLookup, bool AllowTypoCorrection) { 10415 // Do not try to recover if it is already building a recovery call. 10416 // This stops infinite loops for template instantiations like 10417 // 10418 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 10419 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 10420 // 10421 if (SemaRef.IsBuildingRecoveryCallExpr) 10422 return ExprError(); 10423 BuildRecoveryCallExprRAII RCE(SemaRef); 10424 10425 CXXScopeSpec SS; 10426 SS.Adopt(ULE->getQualifierLoc()); 10427 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 10428 10429 TemplateArgumentListInfo TABuffer; 10430 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 10431 if (ULE->hasExplicitTemplateArgs()) { 10432 ULE->copyTemplateArgumentsInto(TABuffer); 10433 ExplicitTemplateArgs = &TABuffer; 10434 } 10435 10436 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 10437 Sema::LookupOrdinaryName); 10438 FunctionCallFilterCCC Validator(SemaRef, Args.size(), 10439 ExplicitTemplateArgs != 0, 10440 dyn_cast<MemberExpr>(Fn)); 10441 NoTypoCorrectionCCC RejectAll; 10442 CorrectionCandidateCallback *CCC = AllowTypoCorrection ? 10443 (CorrectionCandidateCallback*)&Validator : 10444 (CorrectionCandidateCallback*)&RejectAll; 10445 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 10446 OverloadCandidateSet::CSK_Normal, 10447 ExplicitTemplateArgs, Args) && 10448 (!EmptyLookup || 10449 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC, 10450 ExplicitTemplateArgs, Args))) 10451 return ExprError(); 10452 10453 assert(!R.empty() && "lookup results empty despite recovery"); 10454 10455 // Build an implicit member call if appropriate. Just drop the 10456 // casts and such from the call, we don't really care. 10457 ExprResult NewFn = ExprError(); 10458 if ((*R.begin())->isCXXClassMember()) 10459 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 10460 R, ExplicitTemplateArgs); 10461 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 10462 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 10463 ExplicitTemplateArgs); 10464 else 10465 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 10466 10467 if (NewFn.isInvalid()) 10468 return ExprError(); 10469 10470 // This shouldn't cause an infinite loop because we're giving it 10471 // an expression with viable lookup results, which should never 10472 // end up here. 10473 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 10474 MultiExprArg(Args.data(), Args.size()), 10475 RParenLoc); 10476 } 10477 10478 /// \brief Constructs and populates an OverloadedCandidateSet from 10479 /// the given function. 10480 /// \returns true when an the ExprResult output parameter has been set. 10481 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 10482 UnresolvedLookupExpr *ULE, 10483 MultiExprArg Args, 10484 SourceLocation RParenLoc, 10485 OverloadCandidateSet *CandidateSet, 10486 ExprResult *Result) { 10487 #ifndef NDEBUG 10488 if (ULE->requiresADL()) { 10489 // To do ADL, we must have found an unqualified name. 10490 assert(!ULE->getQualifier() && "qualified name with ADL"); 10491 10492 // We don't perform ADL for implicit declarations of builtins. 10493 // Verify that this was correctly set up. 10494 FunctionDecl *F; 10495 if (ULE->decls_begin() + 1 == ULE->decls_end() && 10496 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 10497 F->getBuiltinID() && F->isImplicit()) 10498 llvm_unreachable("performing ADL for builtin"); 10499 10500 // We don't perform ADL in C. 10501 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 10502 } 10503 #endif 10504 10505 UnbridgedCastsSet UnbridgedCasts; 10506 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 10507 *Result = ExprError(); 10508 return true; 10509 } 10510 10511 // Add the functions denoted by the callee to the set of candidate 10512 // functions, including those from argument-dependent lookup. 10513 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 10514 10515 // If we found nothing, try to recover. 10516 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 10517 // out if it fails. 10518 if (CandidateSet->empty()) { 10519 // In Microsoft mode, if we are inside a template class member function then 10520 // create a type dependent CallExpr. The goal is to postpone name lookup 10521 // to instantiation time to be able to search into type dependent base 10522 // classes. 10523 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() && 10524 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 10525 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, 10526 Context.DependentTy, VK_RValue, 10527 RParenLoc); 10528 CE->setTypeDependent(true); 10529 *Result = Owned(CE); 10530 return true; 10531 } 10532 return false; 10533 } 10534 10535 UnbridgedCasts.restore(); 10536 return false; 10537 } 10538 10539 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 10540 /// the completed call expression. If overload resolution fails, emits 10541 /// diagnostics and returns ExprError() 10542 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10543 UnresolvedLookupExpr *ULE, 10544 SourceLocation LParenLoc, 10545 MultiExprArg Args, 10546 SourceLocation RParenLoc, 10547 Expr *ExecConfig, 10548 OverloadCandidateSet *CandidateSet, 10549 OverloadCandidateSet::iterator *Best, 10550 OverloadingResult OverloadResult, 10551 bool AllowTypoCorrection) { 10552 if (CandidateSet->empty()) 10553 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 10554 RParenLoc, /*EmptyLookup=*/true, 10555 AllowTypoCorrection); 10556 10557 switch (OverloadResult) { 10558 case OR_Success: { 10559 FunctionDecl *FDecl = (*Best)->Function; 10560 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 10561 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 10562 return ExprError(); 10563 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10564 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10565 ExecConfig); 10566 } 10567 10568 case OR_No_Viable_Function: { 10569 // Try to recover by looking for viable functions which the user might 10570 // have meant to call. 10571 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 10572 Args, RParenLoc, 10573 /*EmptyLookup=*/false, 10574 AllowTypoCorrection); 10575 if (!Recovery.isInvalid()) 10576 return Recovery; 10577 10578 SemaRef.Diag(Fn->getLocStart(), 10579 diag::err_ovl_no_viable_function_in_call) 10580 << ULE->getName() << Fn->getSourceRange(); 10581 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10582 break; 10583 } 10584 10585 case OR_Ambiguous: 10586 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 10587 << ULE->getName() << Fn->getSourceRange(); 10588 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 10589 break; 10590 10591 case OR_Deleted: { 10592 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 10593 << (*Best)->Function->isDeleted() 10594 << ULE->getName() 10595 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 10596 << Fn->getSourceRange(); 10597 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10598 10599 // We emitted an error for the unvailable/deleted function call but keep 10600 // the call in the AST. 10601 FunctionDecl *FDecl = (*Best)->Function; 10602 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10603 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10604 ExecConfig); 10605 } 10606 } 10607 10608 // Overload resolution failed. 10609 return ExprError(); 10610 } 10611 10612 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 10613 /// (which eventually refers to the declaration Func) and the call 10614 /// arguments Args/NumArgs, attempt to resolve the function call down 10615 /// to a specific function. If overload resolution succeeds, returns 10616 /// the call expression produced by overload resolution. 10617 /// Otherwise, emits diagnostics and returns ExprError. 10618 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 10619 UnresolvedLookupExpr *ULE, 10620 SourceLocation LParenLoc, 10621 MultiExprArg Args, 10622 SourceLocation RParenLoc, 10623 Expr *ExecConfig, 10624 bool AllowTypoCorrection) { 10625 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 10626 OverloadCandidateSet::CSK_Normal); 10627 ExprResult result; 10628 10629 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 10630 &result)) 10631 return result; 10632 10633 OverloadCandidateSet::iterator Best; 10634 OverloadingResult OverloadResult = 10635 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 10636 10637 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 10638 RParenLoc, ExecConfig, &CandidateSet, 10639 &Best, OverloadResult, 10640 AllowTypoCorrection); 10641 } 10642 10643 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 10644 return Functions.size() > 1 || 10645 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 10646 } 10647 10648 /// \brief Create a unary operation that may resolve to an overloaded 10649 /// operator. 10650 /// 10651 /// \param OpLoc The location of the operator itself (e.g., '*'). 10652 /// 10653 /// \param OpcIn The UnaryOperator::Opcode that describes this 10654 /// operator. 10655 /// 10656 /// \param Fns The set of non-member functions that will be 10657 /// considered by overload resolution. The caller needs to build this 10658 /// set based on the context using, e.g., 10659 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10660 /// set should not contain any member functions; those will be added 10661 /// by CreateOverloadedUnaryOp(). 10662 /// 10663 /// \param Input The input argument. 10664 ExprResult 10665 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 10666 const UnresolvedSetImpl &Fns, 10667 Expr *Input) { 10668 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 10669 10670 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 10671 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 10672 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10673 // TODO: provide better source location info. 10674 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10675 10676 if (checkPlaceholderForOverload(*this, Input)) 10677 return ExprError(); 10678 10679 Expr *Args[2] = { Input, 0 }; 10680 unsigned NumArgs = 1; 10681 10682 // For post-increment and post-decrement, add the implicit '0' as 10683 // the second argument, so that we know this is a post-increment or 10684 // post-decrement. 10685 if (Opc == UO_PostInc || Opc == UO_PostDec) { 10686 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 10687 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 10688 SourceLocation()); 10689 NumArgs = 2; 10690 } 10691 10692 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 10693 10694 if (Input->isTypeDependent()) { 10695 if (Fns.empty()) 10696 return Owned(new (Context) UnaryOperator(Input, 10697 Opc, 10698 Context.DependentTy, 10699 VK_RValue, OK_Ordinary, 10700 OpLoc)); 10701 10702 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10703 UnresolvedLookupExpr *Fn 10704 = UnresolvedLookupExpr::Create(Context, NamingClass, 10705 NestedNameSpecifierLoc(), OpNameInfo, 10706 /*ADL*/ true, IsOverloaded(Fns), 10707 Fns.begin(), Fns.end()); 10708 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, 10709 Context.DependentTy, 10710 VK_RValue, 10711 OpLoc, false)); 10712 } 10713 10714 // Build an empty overload set. 10715 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 10716 10717 // Add the candidates from the given function set. 10718 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false); 10719 10720 // Add operator candidates that are member functions. 10721 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10722 10723 // Add candidates from ADL. 10724 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 10725 /*ExplicitTemplateArgs*/0, CandidateSet); 10726 10727 // Add builtin operator candidates. 10728 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10729 10730 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10731 10732 // Perform overload resolution. 10733 OverloadCandidateSet::iterator Best; 10734 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10735 case OR_Success: { 10736 // We found a built-in operator or an overloaded operator. 10737 FunctionDecl *FnDecl = Best->Function; 10738 10739 if (FnDecl) { 10740 // We matched an overloaded operator. Build a call to that 10741 // operator. 10742 10743 // Convert the arguments. 10744 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10745 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 10746 10747 ExprResult InputRes = 10748 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 10749 Best->FoundDecl, Method); 10750 if (InputRes.isInvalid()) 10751 return ExprError(); 10752 Input = InputRes.take(); 10753 } else { 10754 // Convert the arguments. 10755 ExprResult InputInit 10756 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10757 Context, 10758 FnDecl->getParamDecl(0)), 10759 SourceLocation(), 10760 Input); 10761 if (InputInit.isInvalid()) 10762 return ExprError(); 10763 Input = InputInit.take(); 10764 } 10765 10766 // Build the actual expression node. 10767 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 10768 HadMultipleCandidates, OpLoc); 10769 if (FnExpr.isInvalid()) 10770 return ExprError(); 10771 10772 // Determine the result type. 10773 QualType ResultTy = FnDecl->getReturnType(); 10774 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10775 ResultTy = ResultTy.getNonLValueExprType(Context); 10776 10777 Args[0] = Input; 10778 CallExpr *TheCall = 10779 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray, 10780 ResultTy, VK, OpLoc, false); 10781 10782 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 10783 return ExprError(); 10784 10785 return MaybeBindToTemporary(TheCall); 10786 } else { 10787 // We matched a built-in operator. Convert the arguments, then 10788 // break out so that we will build the appropriate built-in 10789 // operator node. 10790 ExprResult InputRes = 10791 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 10792 Best->Conversions[0], AA_Passing); 10793 if (InputRes.isInvalid()) 10794 return ExprError(); 10795 Input = InputRes.take(); 10796 break; 10797 } 10798 } 10799 10800 case OR_No_Viable_Function: 10801 // This is an erroneous use of an operator which can be overloaded by 10802 // a non-member function. Check for non-member operators which were 10803 // defined too late to be candidates. 10804 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 10805 // FIXME: Recover by calling the found function. 10806 return ExprError(); 10807 10808 // No viable function; fall through to handling this as a 10809 // built-in operator, which will produce an error message for us. 10810 break; 10811 10812 case OR_Ambiguous: 10813 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 10814 << UnaryOperator::getOpcodeStr(Opc) 10815 << Input->getType() 10816 << Input->getSourceRange(); 10817 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 10818 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10819 return ExprError(); 10820 10821 case OR_Deleted: 10822 Diag(OpLoc, diag::err_ovl_deleted_oper) 10823 << Best->Function->isDeleted() 10824 << UnaryOperator::getOpcodeStr(Opc) 10825 << getDeletedOrUnavailableSuffix(Best->Function) 10826 << Input->getSourceRange(); 10827 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 10828 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10829 return ExprError(); 10830 } 10831 10832 // Either we found no viable overloaded operator or we matched a 10833 // built-in operator. In either case, fall through to trying to 10834 // build a built-in operation. 10835 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10836 } 10837 10838 /// \brief Create a binary operation that may resolve to an overloaded 10839 /// operator. 10840 /// 10841 /// \param OpLoc The location of the operator itself (e.g., '+'). 10842 /// 10843 /// \param OpcIn The BinaryOperator::Opcode that describes this 10844 /// operator. 10845 /// 10846 /// \param Fns The set of non-member functions that will be 10847 /// considered by overload resolution. The caller needs to build this 10848 /// set based on the context using, e.g., 10849 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10850 /// set should not contain any member functions; those will be added 10851 /// by CreateOverloadedBinOp(). 10852 /// 10853 /// \param LHS Left-hand argument. 10854 /// \param RHS Right-hand argument. 10855 ExprResult 10856 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 10857 unsigned OpcIn, 10858 const UnresolvedSetImpl &Fns, 10859 Expr *LHS, Expr *RHS) { 10860 Expr *Args[2] = { LHS, RHS }; 10861 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 10862 10863 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 10864 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 10865 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10866 10867 // If either side is type-dependent, create an appropriate dependent 10868 // expression. 10869 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10870 if (Fns.empty()) { 10871 // If there are no functions to store, just build a dependent 10872 // BinaryOperator or CompoundAssignment. 10873 if (Opc <= BO_Assign || Opc > BO_OrAssign) 10874 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 10875 Context.DependentTy, 10876 VK_RValue, OK_Ordinary, 10877 OpLoc, 10878 FPFeatures.fp_contract)); 10879 10880 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 10881 Context.DependentTy, 10882 VK_LValue, 10883 OK_Ordinary, 10884 Context.DependentTy, 10885 Context.DependentTy, 10886 OpLoc, 10887 FPFeatures.fp_contract)); 10888 } 10889 10890 // FIXME: save results of ADL from here? 10891 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10892 // TODO: provide better source location info in DNLoc component. 10893 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10894 UnresolvedLookupExpr *Fn 10895 = UnresolvedLookupExpr::Create(Context, NamingClass, 10896 NestedNameSpecifierLoc(), OpNameInfo, 10897 /*ADL*/ true, IsOverloaded(Fns), 10898 Fns.begin(), Fns.end()); 10899 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args, 10900 Context.DependentTy, VK_RValue, 10901 OpLoc, FPFeatures.fp_contract)); 10902 } 10903 10904 // Always do placeholder-like conversions on the RHS. 10905 if (checkPlaceholderForOverload(*this, Args[1])) 10906 return ExprError(); 10907 10908 // Do placeholder-like conversion on the LHS; note that we should 10909 // not get here with a PseudoObject LHS. 10910 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 10911 if (checkPlaceholderForOverload(*this, Args[0])) 10912 return ExprError(); 10913 10914 // If this is the assignment operator, we only perform overload resolution 10915 // if the left-hand side is a class or enumeration type. This is actually 10916 // a hack. The standard requires that we do overload resolution between the 10917 // various built-in candidates, but as DR507 points out, this can lead to 10918 // problems. So we do it this way, which pretty much follows what GCC does. 10919 // Note that we go the traditional code path for compound assignment forms. 10920 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 10921 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10922 10923 // If this is the .* operator, which is not overloadable, just 10924 // create a built-in binary operator. 10925 if (Opc == BO_PtrMemD) 10926 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10927 10928 // Build an empty overload set. 10929 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 10930 10931 // Add the candidates from the given function set. 10932 AddFunctionCandidates(Fns, Args, CandidateSet, false); 10933 10934 // Add operator candidates that are member functions. 10935 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 10936 10937 // Add candidates from ADL. 10938 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 10939 /*ExplicitTemplateArgs*/ 0, 10940 CandidateSet); 10941 10942 // Add builtin operator candidates. 10943 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 10944 10945 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10946 10947 // Perform overload resolution. 10948 OverloadCandidateSet::iterator Best; 10949 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10950 case OR_Success: { 10951 // We found a built-in operator or an overloaded operator. 10952 FunctionDecl *FnDecl = Best->Function; 10953 10954 if (FnDecl) { 10955 // We matched an overloaded operator. Build a call to that 10956 // operator. 10957 10958 // Convert the arguments. 10959 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10960 // Best->Access is only meaningful for class members. 10961 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 10962 10963 ExprResult Arg1 = 10964 PerformCopyInitialization( 10965 InitializedEntity::InitializeParameter(Context, 10966 FnDecl->getParamDecl(0)), 10967 SourceLocation(), Owned(Args[1])); 10968 if (Arg1.isInvalid()) 10969 return ExprError(); 10970 10971 ExprResult Arg0 = 10972 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10973 Best->FoundDecl, Method); 10974 if (Arg0.isInvalid()) 10975 return ExprError(); 10976 Args[0] = Arg0.takeAs<Expr>(); 10977 Args[1] = RHS = Arg1.takeAs<Expr>(); 10978 } else { 10979 // Convert the arguments. 10980 ExprResult Arg0 = PerformCopyInitialization( 10981 InitializedEntity::InitializeParameter(Context, 10982 FnDecl->getParamDecl(0)), 10983 SourceLocation(), Owned(Args[0])); 10984 if (Arg0.isInvalid()) 10985 return ExprError(); 10986 10987 ExprResult Arg1 = 10988 PerformCopyInitialization( 10989 InitializedEntity::InitializeParameter(Context, 10990 FnDecl->getParamDecl(1)), 10991 SourceLocation(), Owned(Args[1])); 10992 if (Arg1.isInvalid()) 10993 return ExprError(); 10994 Args[0] = LHS = Arg0.takeAs<Expr>(); 10995 Args[1] = RHS = Arg1.takeAs<Expr>(); 10996 } 10997 10998 // Build the actual expression node. 10999 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11000 Best->FoundDecl, 11001 HadMultipleCandidates, OpLoc); 11002 if (FnExpr.isInvalid()) 11003 return ExprError(); 11004 11005 // Determine the result type. 11006 QualType ResultTy = FnDecl->getReturnType(); 11007 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11008 ResultTy = ResultTy.getNonLValueExprType(Context); 11009 11010 CXXOperatorCallExpr *TheCall = 11011 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 11012 Args, ResultTy, VK, OpLoc, 11013 FPFeatures.fp_contract); 11014 11015 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 11016 FnDecl)) 11017 return ExprError(); 11018 11019 ArrayRef<const Expr *> ArgsArray(Args, 2); 11020 // Cut off the implicit 'this'. 11021 if (isa<CXXMethodDecl>(FnDecl)) 11022 ArgsArray = ArgsArray.slice(1); 11023 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc, 11024 TheCall->getSourceRange(), VariadicDoesNotApply); 11025 11026 return MaybeBindToTemporary(TheCall); 11027 } else { 11028 // We matched a built-in operator. Convert the arguments, then 11029 // break out so that we will build the appropriate built-in 11030 // operator node. 11031 ExprResult ArgsRes0 = 11032 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11033 Best->Conversions[0], AA_Passing); 11034 if (ArgsRes0.isInvalid()) 11035 return ExprError(); 11036 Args[0] = ArgsRes0.take(); 11037 11038 ExprResult ArgsRes1 = 11039 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11040 Best->Conversions[1], AA_Passing); 11041 if (ArgsRes1.isInvalid()) 11042 return ExprError(); 11043 Args[1] = ArgsRes1.take(); 11044 break; 11045 } 11046 } 11047 11048 case OR_No_Viable_Function: { 11049 // C++ [over.match.oper]p9: 11050 // If the operator is the operator , [...] and there are no 11051 // viable functions, then the operator is assumed to be the 11052 // built-in operator and interpreted according to clause 5. 11053 if (Opc == BO_Comma) 11054 break; 11055 11056 // For class as left operand for assignment or compound assigment 11057 // operator do not fall through to handling in built-in, but report that 11058 // no overloaded assignment operator found 11059 ExprResult Result = ExprError(); 11060 if (Args[0]->getType()->isRecordType() && 11061 Opc >= BO_Assign && Opc <= BO_OrAssign) { 11062 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11063 << BinaryOperator::getOpcodeStr(Opc) 11064 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11065 if (Args[0]->getType()->isIncompleteType()) { 11066 Diag(OpLoc, diag::note_assign_lhs_incomplete) 11067 << Args[0]->getType() 11068 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11069 } 11070 } else { 11071 // This is an erroneous use of an operator which can be overloaded by 11072 // a non-member function. Check for non-member operators which were 11073 // defined too late to be candidates. 11074 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 11075 // FIXME: Recover by calling the found function. 11076 return ExprError(); 11077 11078 // No viable function; try to create a built-in operation, which will 11079 // produce an error. Then, show the non-viable candidates. 11080 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11081 } 11082 assert(Result.isInvalid() && 11083 "C++ binary operator overloading is missing candidates!"); 11084 if (Result.isInvalid()) 11085 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11086 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11087 return Result; 11088 } 11089 11090 case OR_Ambiguous: 11091 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 11092 << BinaryOperator::getOpcodeStr(Opc) 11093 << Args[0]->getType() << Args[1]->getType() 11094 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11095 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11096 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11097 return ExprError(); 11098 11099 case OR_Deleted: 11100 if (isImplicitlyDeleted(Best->Function)) { 11101 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11102 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 11103 << Context.getRecordType(Method->getParent()) 11104 << getSpecialMember(Method); 11105 11106 // The user probably meant to call this special member. Just 11107 // explain why it's deleted. 11108 NoteDeletedFunction(Method); 11109 return ExprError(); 11110 } else { 11111 Diag(OpLoc, diag::err_ovl_deleted_oper) 11112 << Best->Function->isDeleted() 11113 << BinaryOperator::getOpcodeStr(Opc) 11114 << getDeletedOrUnavailableSuffix(Best->Function) 11115 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11116 } 11117 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11118 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11119 return ExprError(); 11120 } 11121 11122 // We matched a built-in operator; build it. 11123 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11124 } 11125 11126 ExprResult 11127 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 11128 SourceLocation RLoc, 11129 Expr *Base, Expr *Idx) { 11130 Expr *Args[2] = { Base, Idx }; 11131 DeclarationName OpName = 11132 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 11133 11134 // If either side is type-dependent, create an appropriate dependent 11135 // expression. 11136 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11137 11138 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 11139 // CHECKME: no 'operator' keyword? 11140 DeclarationNameInfo OpNameInfo(OpName, LLoc); 11141 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11142 UnresolvedLookupExpr *Fn 11143 = UnresolvedLookupExpr::Create(Context, NamingClass, 11144 NestedNameSpecifierLoc(), OpNameInfo, 11145 /*ADL*/ true, /*Overloaded*/ false, 11146 UnresolvedSetIterator(), 11147 UnresolvedSetIterator()); 11148 // Can't add any actual overloads yet 11149 11150 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 11151 Args, 11152 Context.DependentTy, 11153 VK_RValue, 11154 RLoc, false)); 11155 } 11156 11157 // Handle placeholders on both operands. 11158 if (checkPlaceholderForOverload(*this, Args[0])) 11159 return ExprError(); 11160 if (checkPlaceholderForOverload(*this, Args[1])) 11161 return ExprError(); 11162 11163 // Build an empty overload set. 11164 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 11165 11166 // Subscript can only be overloaded as a member function. 11167 11168 // Add operator candidates that are member functions. 11169 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11170 11171 // Add builtin operator candidates. 11172 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11173 11174 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11175 11176 // Perform overload resolution. 11177 OverloadCandidateSet::iterator Best; 11178 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 11179 case OR_Success: { 11180 // We found a built-in operator or an overloaded operator. 11181 FunctionDecl *FnDecl = Best->Function; 11182 11183 if (FnDecl) { 11184 // We matched an overloaded operator. Build a call to that 11185 // operator. 11186 11187 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 11188 11189 // Convert the arguments. 11190 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 11191 ExprResult Arg0 = 11192 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 11193 Best->FoundDecl, Method); 11194 if (Arg0.isInvalid()) 11195 return ExprError(); 11196 Args[0] = Arg0.take(); 11197 11198 // Convert the arguments. 11199 ExprResult InputInit 11200 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11201 Context, 11202 FnDecl->getParamDecl(0)), 11203 SourceLocation(), 11204 Owned(Args[1])); 11205 if (InputInit.isInvalid()) 11206 return ExprError(); 11207 11208 Args[1] = InputInit.takeAs<Expr>(); 11209 11210 // Build the actual expression node. 11211 DeclarationNameInfo OpLocInfo(OpName, LLoc); 11212 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11213 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11214 Best->FoundDecl, 11215 HadMultipleCandidates, 11216 OpLocInfo.getLoc(), 11217 OpLocInfo.getInfo()); 11218 if (FnExpr.isInvalid()) 11219 return ExprError(); 11220 11221 // Determine the result type 11222 QualType ResultTy = FnDecl->getReturnType(); 11223 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11224 ResultTy = ResultTy.getNonLValueExprType(Context); 11225 11226 CXXOperatorCallExpr *TheCall = 11227 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 11228 FnExpr.take(), Args, 11229 ResultTy, VK, RLoc, 11230 false); 11231 11232 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 11233 return ExprError(); 11234 11235 return MaybeBindToTemporary(TheCall); 11236 } else { 11237 // We matched a built-in operator. Convert the arguments, then 11238 // break out so that we will build the appropriate built-in 11239 // operator node. 11240 ExprResult ArgsRes0 = 11241 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11242 Best->Conversions[0], AA_Passing); 11243 if (ArgsRes0.isInvalid()) 11244 return ExprError(); 11245 Args[0] = ArgsRes0.take(); 11246 11247 ExprResult ArgsRes1 = 11248 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11249 Best->Conversions[1], AA_Passing); 11250 if (ArgsRes1.isInvalid()) 11251 return ExprError(); 11252 Args[1] = ArgsRes1.take(); 11253 11254 break; 11255 } 11256 } 11257 11258 case OR_No_Viable_Function: { 11259 if (CandidateSet.empty()) 11260 Diag(LLoc, diag::err_ovl_no_oper) 11261 << Args[0]->getType() << /*subscript*/ 0 11262 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11263 else 11264 Diag(LLoc, diag::err_ovl_no_viable_subscript) 11265 << Args[0]->getType() 11266 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11267 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11268 "[]", LLoc); 11269 return ExprError(); 11270 } 11271 11272 case OR_Ambiguous: 11273 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 11274 << "[]" 11275 << Args[0]->getType() << Args[1]->getType() 11276 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11277 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11278 "[]", LLoc); 11279 return ExprError(); 11280 11281 case OR_Deleted: 11282 Diag(LLoc, diag::err_ovl_deleted_oper) 11283 << Best->Function->isDeleted() << "[]" 11284 << getDeletedOrUnavailableSuffix(Best->Function) 11285 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11286 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11287 "[]", LLoc); 11288 return ExprError(); 11289 } 11290 11291 // We matched a built-in operator; build it. 11292 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 11293 } 11294 11295 /// BuildCallToMemberFunction - Build a call to a member 11296 /// function. MemExpr is the expression that refers to the member 11297 /// function (and includes the object parameter), Args/NumArgs are the 11298 /// arguments to the function call (not including the object 11299 /// parameter). The caller needs to validate that the member 11300 /// expression refers to a non-static member function or an overloaded 11301 /// member function. 11302 ExprResult 11303 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 11304 SourceLocation LParenLoc, 11305 MultiExprArg Args, 11306 SourceLocation RParenLoc) { 11307 assert(MemExprE->getType() == Context.BoundMemberTy || 11308 MemExprE->getType() == Context.OverloadTy); 11309 11310 // Dig out the member expression. This holds both the object 11311 // argument and the member function we're referring to. 11312 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 11313 11314 // Determine whether this is a call to a pointer-to-member function. 11315 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 11316 assert(op->getType() == Context.BoundMemberTy); 11317 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 11318 11319 QualType fnType = 11320 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 11321 11322 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 11323 QualType resultType = proto->getCallResultType(Context); 11324 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 11325 11326 // Check that the object type isn't more qualified than the 11327 // member function we're calling. 11328 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 11329 11330 QualType objectType = op->getLHS()->getType(); 11331 if (op->getOpcode() == BO_PtrMemI) 11332 objectType = objectType->castAs<PointerType>()->getPointeeType(); 11333 Qualifiers objectQuals = objectType.getQualifiers(); 11334 11335 Qualifiers difference = objectQuals - funcQuals; 11336 difference.removeObjCGCAttr(); 11337 difference.removeAddressSpace(); 11338 if (difference) { 11339 std::string qualsString = difference.getAsString(); 11340 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 11341 << fnType.getUnqualifiedType() 11342 << qualsString 11343 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 11344 } 11345 11346 CXXMemberCallExpr *call 11347 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11348 resultType, valueKind, RParenLoc); 11349 11350 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 11351 call, 0)) 11352 return ExprError(); 11353 11354 if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc)) 11355 return ExprError(); 11356 11357 if (CheckOtherCall(call, proto)) 11358 return ExprError(); 11359 11360 return MaybeBindToTemporary(call); 11361 } 11362 11363 UnbridgedCastsSet UnbridgedCasts; 11364 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11365 return ExprError(); 11366 11367 MemberExpr *MemExpr; 11368 CXXMethodDecl *Method = 0; 11369 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 11370 NestedNameSpecifier *Qualifier = 0; 11371 if (isa<MemberExpr>(NakedMemExpr)) { 11372 MemExpr = cast<MemberExpr>(NakedMemExpr); 11373 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 11374 FoundDecl = MemExpr->getFoundDecl(); 11375 Qualifier = MemExpr->getQualifier(); 11376 UnbridgedCasts.restore(); 11377 } else { 11378 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 11379 Qualifier = UnresExpr->getQualifier(); 11380 11381 QualType ObjectType = UnresExpr->getBaseType(); 11382 Expr::Classification ObjectClassification 11383 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 11384 : UnresExpr->getBase()->Classify(Context); 11385 11386 // Add overload candidates 11387 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 11388 OverloadCandidateSet::CSK_Normal); 11389 11390 // FIXME: avoid copy. 11391 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11392 if (UnresExpr->hasExplicitTemplateArgs()) { 11393 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11394 TemplateArgs = &TemplateArgsBuffer; 11395 } 11396 11397 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 11398 E = UnresExpr->decls_end(); I != E; ++I) { 11399 11400 NamedDecl *Func = *I; 11401 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 11402 if (isa<UsingShadowDecl>(Func)) 11403 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 11404 11405 11406 // Microsoft supports direct constructor calls. 11407 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 11408 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 11409 Args, CandidateSet); 11410 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 11411 // If explicit template arguments were provided, we can't call a 11412 // non-template member function. 11413 if (TemplateArgs) 11414 continue; 11415 11416 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 11417 ObjectClassification, Args, CandidateSet, 11418 /*SuppressUserConversions=*/false); 11419 } else { 11420 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 11421 I.getPair(), ActingDC, TemplateArgs, 11422 ObjectType, ObjectClassification, 11423 Args, CandidateSet, 11424 /*SuppressUsedConversions=*/false); 11425 } 11426 } 11427 11428 DeclarationName DeclName = UnresExpr->getMemberName(); 11429 11430 UnbridgedCasts.restore(); 11431 11432 OverloadCandidateSet::iterator Best; 11433 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 11434 Best)) { 11435 case OR_Success: 11436 Method = cast<CXXMethodDecl>(Best->Function); 11437 FoundDecl = Best->FoundDecl; 11438 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 11439 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 11440 return ExprError(); 11441 // If FoundDecl is different from Method (such as if one is a template 11442 // and the other a specialization), make sure DiagnoseUseOfDecl is 11443 // called on both. 11444 // FIXME: This would be more comprehensively addressed by modifying 11445 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 11446 // being used. 11447 if (Method != FoundDecl.getDecl() && 11448 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 11449 return ExprError(); 11450 break; 11451 11452 case OR_No_Viable_Function: 11453 Diag(UnresExpr->getMemberLoc(), 11454 diag::err_ovl_no_viable_member_function_in_call) 11455 << DeclName << MemExprE->getSourceRange(); 11456 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11457 // FIXME: Leaking incoming expressions! 11458 return ExprError(); 11459 11460 case OR_Ambiguous: 11461 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 11462 << DeclName << MemExprE->getSourceRange(); 11463 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11464 // FIXME: Leaking incoming expressions! 11465 return ExprError(); 11466 11467 case OR_Deleted: 11468 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 11469 << Best->Function->isDeleted() 11470 << DeclName 11471 << getDeletedOrUnavailableSuffix(Best->Function) 11472 << MemExprE->getSourceRange(); 11473 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11474 // FIXME: Leaking incoming expressions! 11475 return ExprError(); 11476 } 11477 11478 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 11479 11480 // If overload resolution picked a static member, build a 11481 // non-member call based on that function. 11482 if (Method->isStatic()) { 11483 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 11484 RParenLoc); 11485 } 11486 11487 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 11488 } 11489 11490 QualType ResultType = Method->getReturnType(); 11491 ExprValueKind VK = Expr::getValueKindForType(ResultType); 11492 ResultType = ResultType.getNonLValueExprType(Context); 11493 11494 assert(Method && "Member call to something that isn't a method?"); 11495 CXXMemberCallExpr *TheCall = 11496 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11497 ResultType, VK, RParenLoc); 11498 11499 // Check for a valid return type. 11500 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 11501 TheCall, Method)) 11502 return ExprError(); 11503 11504 // Convert the object argument (for a non-static member function call). 11505 // We only need to do this if there was actually an overload; otherwise 11506 // it was done at lookup. 11507 if (!Method->isStatic()) { 11508 ExprResult ObjectArg = 11509 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 11510 FoundDecl, Method); 11511 if (ObjectArg.isInvalid()) 11512 return ExprError(); 11513 MemExpr->setBase(ObjectArg.take()); 11514 } 11515 11516 // Convert the rest of the arguments 11517 const FunctionProtoType *Proto = 11518 Method->getType()->getAs<FunctionProtoType>(); 11519 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 11520 RParenLoc)) 11521 return ExprError(); 11522 11523 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11524 11525 if (CheckFunctionCall(Method, TheCall, Proto)) 11526 return ExprError(); 11527 11528 if ((isa<CXXConstructorDecl>(CurContext) || 11529 isa<CXXDestructorDecl>(CurContext)) && 11530 TheCall->getMethodDecl()->isPure()) { 11531 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 11532 11533 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 11534 Diag(MemExpr->getLocStart(), 11535 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 11536 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 11537 << MD->getParent()->getDeclName(); 11538 11539 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 11540 } 11541 } 11542 return MaybeBindToTemporary(TheCall); 11543 } 11544 11545 /// BuildCallToObjectOfClassType - Build a call to an object of class 11546 /// type (C++ [over.call.object]), which can end up invoking an 11547 /// overloaded function call operator (@c operator()) or performing a 11548 /// user-defined conversion on the object argument. 11549 ExprResult 11550 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 11551 SourceLocation LParenLoc, 11552 MultiExprArg Args, 11553 SourceLocation RParenLoc) { 11554 if (checkPlaceholderForOverload(*this, Obj)) 11555 return ExprError(); 11556 ExprResult Object = Owned(Obj); 11557 11558 UnbridgedCastsSet UnbridgedCasts; 11559 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11560 return ExprError(); 11561 11562 assert(Object.get()->getType()->isRecordType() && "Requires object type argument"); 11563 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 11564 11565 // C++ [over.call.object]p1: 11566 // If the primary-expression E in the function call syntax 11567 // evaluates to a class object of type "cv T", then the set of 11568 // candidate functions includes at least the function call 11569 // operators of T. The function call operators of T are obtained by 11570 // ordinary lookup of the name operator() in the context of 11571 // (E).operator(). 11572 OverloadCandidateSet CandidateSet(LParenLoc, 11573 OverloadCandidateSet::CSK_Operator); 11574 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 11575 11576 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 11577 diag::err_incomplete_object_call, Object.get())) 11578 return true; 11579 11580 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 11581 LookupQualifiedName(R, Record->getDecl()); 11582 R.suppressDiagnostics(); 11583 11584 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11585 Oper != OperEnd; ++Oper) { 11586 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 11587 Object.get()->Classify(Context), 11588 Args, CandidateSet, 11589 /*SuppressUserConversions=*/ false); 11590 } 11591 11592 // C++ [over.call.object]p2: 11593 // In addition, for each (non-explicit in C++0x) conversion function 11594 // declared in T of the form 11595 // 11596 // operator conversion-type-id () cv-qualifier; 11597 // 11598 // where cv-qualifier is the same cv-qualification as, or a 11599 // greater cv-qualification than, cv, and where conversion-type-id 11600 // denotes the type "pointer to function of (P1,...,Pn) returning 11601 // R", or the type "reference to pointer to function of 11602 // (P1,...,Pn) returning R", or the type "reference to function 11603 // of (P1,...,Pn) returning R", a surrogate call function [...] 11604 // is also considered as a candidate function. Similarly, 11605 // surrogate call functions are added to the set of candidate 11606 // functions for each conversion function declared in an 11607 // accessible base class provided the function is not hidden 11608 // within T by another intervening declaration. 11609 std::pair<CXXRecordDecl::conversion_iterator, 11610 CXXRecordDecl::conversion_iterator> Conversions 11611 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 11612 for (CXXRecordDecl::conversion_iterator 11613 I = Conversions.first, E = Conversions.second; I != E; ++I) { 11614 NamedDecl *D = *I; 11615 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 11616 if (isa<UsingShadowDecl>(D)) 11617 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 11618 11619 // Skip over templated conversion functions; they aren't 11620 // surrogates. 11621 if (isa<FunctionTemplateDecl>(D)) 11622 continue; 11623 11624 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 11625 if (!Conv->isExplicit()) { 11626 // Strip the reference type (if any) and then the pointer type (if 11627 // any) to get down to what might be a function type. 11628 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 11629 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11630 ConvType = ConvPtrType->getPointeeType(); 11631 11632 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 11633 { 11634 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 11635 Object.get(), Args, CandidateSet); 11636 } 11637 } 11638 } 11639 11640 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11641 11642 // Perform overload resolution. 11643 OverloadCandidateSet::iterator Best; 11644 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 11645 Best)) { 11646 case OR_Success: 11647 // Overload resolution succeeded; we'll build the appropriate call 11648 // below. 11649 break; 11650 11651 case OR_No_Viable_Function: 11652 if (CandidateSet.empty()) 11653 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 11654 << Object.get()->getType() << /*call*/ 1 11655 << Object.get()->getSourceRange(); 11656 else 11657 Diag(Object.get()->getLocStart(), 11658 diag::err_ovl_no_viable_object_call) 11659 << Object.get()->getType() << Object.get()->getSourceRange(); 11660 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11661 break; 11662 11663 case OR_Ambiguous: 11664 Diag(Object.get()->getLocStart(), 11665 diag::err_ovl_ambiguous_object_call) 11666 << Object.get()->getType() << Object.get()->getSourceRange(); 11667 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11668 break; 11669 11670 case OR_Deleted: 11671 Diag(Object.get()->getLocStart(), 11672 diag::err_ovl_deleted_object_call) 11673 << Best->Function->isDeleted() 11674 << Object.get()->getType() 11675 << getDeletedOrUnavailableSuffix(Best->Function) 11676 << Object.get()->getSourceRange(); 11677 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11678 break; 11679 } 11680 11681 if (Best == CandidateSet.end()) 11682 return true; 11683 11684 UnbridgedCasts.restore(); 11685 11686 if (Best->Function == 0) { 11687 // Since there is no function declaration, this is one of the 11688 // surrogate candidates. Dig out the conversion function. 11689 CXXConversionDecl *Conv 11690 = cast<CXXConversionDecl>( 11691 Best->Conversions[0].UserDefined.ConversionFunction); 11692 11693 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11694 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 11695 return ExprError(); 11696 assert(Conv == Best->FoundDecl.getDecl() && 11697 "Found Decl & conversion-to-functionptr should be same, right?!"); 11698 // We selected one of the surrogate functions that converts the 11699 // object parameter to a function pointer. Perform the conversion 11700 // on the object argument, then let ActOnCallExpr finish the job. 11701 11702 // Create an implicit member expr to refer to the conversion operator. 11703 // and then call it. 11704 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 11705 Conv, HadMultipleCandidates); 11706 if (Call.isInvalid()) 11707 return ExprError(); 11708 // Record usage of conversion in an implicit cast. 11709 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(), 11710 CK_UserDefinedConversion, 11711 Call.get(), 0, VK_RValue)); 11712 11713 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 11714 } 11715 11716 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11717 11718 // We found an overloaded operator(). Build a CXXOperatorCallExpr 11719 // that calls this method, using Object for the implicit object 11720 // parameter and passing along the remaining arguments. 11721 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11722 11723 // An error diagnostic has already been printed when parsing the declaration. 11724 if (Method->isInvalidDecl()) 11725 return ExprError(); 11726 11727 const FunctionProtoType *Proto = 11728 Method->getType()->getAs<FunctionProtoType>(); 11729 11730 unsigned NumParams = Proto->getNumParams(); 11731 11732 DeclarationNameInfo OpLocInfo( 11733 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 11734 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 11735 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11736 HadMultipleCandidates, 11737 OpLocInfo.getLoc(), 11738 OpLocInfo.getInfo()); 11739 if (NewFn.isInvalid()) 11740 return true; 11741 11742 // Build the full argument list for the method call (the implicit object 11743 // parameter is placed at the beginning of the list). 11744 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]); 11745 MethodArgs[0] = Object.get(); 11746 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 11747 11748 // Once we've built TheCall, all of the expressions are properly 11749 // owned. 11750 QualType ResultTy = Method->getReturnType(); 11751 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11752 ResultTy = ResultTy.getNonLValueExprType(Context); 11753 11754 CXXOperatorCallExpr *TheCall = new (Context) 11755 CXXOperatorCallExpr(Context, OO_Call, NewFn.take(), 11756 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 11757 ResultTy, VK, RParenLoc, false); 11758 MethodArgs.reset(); 11759 11760 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 11761 return true; 11762 11763 // We may have default arguments. If so, we need to allocate more 11764 // slots in the call for them. 11765 if (Args.size() < NumParams) 11766 TheCall->setNumArgs(Context, NumParams + 1); 11767 11768 bool IsError = false; 11769 11770 // Initialize the implicit object parameter. 11771 ExprResult ObjRes = 11772 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0, 11773 Best->FoundDecl, Method); 11774 if (ObjRes.isInvalid()) 11775 IsError = true; 11776 else 11777 Object = ObjRes; 11778 TheCall->setArg(0, Object.take()); 11779 11780 // Check the argument types. 11781 for (unsigned i = 0; i != NumParams; i++) { 11782 Expr *Arg; 11783 if (i < Args.size()) { 11784 Arg = Args[i]; 11785 11786 // Pass the argument. 11787 11788 ExprResult InputInit 11789 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11790 Context, 11791 Method->getParamDecl(i)), 11792 SourceLocation(), Arg); 11793 11794 IsError |= InputInit.isInvalid(); 11795 Arg = InputInit.takeAs<Expr>(); 11796 } else { 11797 ExprResult DefArg 11798 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 11799 if (DefArg.isInvalid()) { 11800 IsError = true; 11801 break; 11802 } 11803 11804 Arg = DefArg.takeAs<Expr>(); 11805 } 11806 11807 TheCall->setArg(i + 1, Arg); 11808 } 11809 11810 // If this is a variadic call, handle args passed through "...". 11811 if (Proto->isVariadic()) { 11812 // Promote the arguments (C99 6.5.2.2p7). 11813 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 11814 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); 11815 IsError |= Arg.isInvalid(); 11816 TheCall->setArg(i + 1, Arg.take()); 11817 } 11818 } 11819 11820 if (IsError) return true; 11821 11822 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11823 11824 if (CheckFunctionCall(Method, TheCall, Proto)) 11825 return true; 11826 11827 return MaybeBindToTemporary(TheCall); 11828 } 11829 11830 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 11831 /// (if one exists), where @c Base is an expression of class type and 11832 /// @c Member is the name of the member we're trying to find. 11833 ExprResult 11834 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 11835 bool *NoArrowOperatorFound) { 11836 assert(Base->getType()->isRecordType() && 11837 "left-hand side must have class type"); 11838 11839 if (checkPlaceholderForOverload(*this, Base)) 11840 return ExprError(); 11841 11842 SourceLocation Loc = Base->getExprLoc(); 11843 11844 // C++ [over.ref]p1: 11845 // 11846 // [...] An expression x->m is interpreted as (x.operator->())->m 11847 // for a class object x of type T if T::operator->() exists and if 11848 // the operator is selected as the best match function by the 11849 // overload resolution mechanism (13.3). 11850 DeclarationName OpName = 11851 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 11852 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 11853 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 11854 11855 if (RequireCompleteType(Loc, Base->getType(), 11856 diag::err_typecheck_incomplete_tag, Base)) 11857 return ExprError(); 11858 11859 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 11860 LookupQualifiedName(R, BaseRecord->getDecl()); 11861 R.suppressDiagnostics(); 11862 11863 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11864 Oper != OperEnd; ++Oper) { 11865 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 11866 None, CandidateSet, /*SuppressUserConversions=*/false); 11867 } 11868 11869 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11870 11871 // Perform overload resolution. 11872 OverloadCandidateSet::iterator Best; 11873 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11874 case OR_Success: 11875 // Overload resolution succeeded; we'll build the call below. 11876 break; 11877 11878 case OR_No_Viable_Function: 11879 if (CandidateSet.empty()) { 11880 QualType BaseType = Base->getType(); 11881 if (NoArrowOperatorFound) { 11882 // Report this specific error to the caller instead of emitting a 11883 // diagnostic, as requested. 11884 *NoArrowOperatorFound = true; 11885 return ExprError(); 11886 } 11887 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 11888 << BaseType << Base->getSourceRange(); 11889 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 11890 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 11891 << FixItHint::CreateReplacement(OpLoc, "."); 11892 } 11893 } else 11894 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11895 << "operator->" << Base->getSourceRange(); 11896 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11897 return ExprError(); 11898 11899 case OR_Ambiguous: 11900 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11901 << "->" << Base->getType() << Base->getSourceRange(); 11902 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 11903 return ExprError(); 11904 11905 case OR_Deleted: 11906 Diag(OpLoc, diag::err_ovl_deleted_oper) 11907 << Best->Function->isDeleted() 11908 << "->" 11909 << getDeletedOrUnavailableSuffix(Best->Function) 11910 << Base->getSourceRange(); 11911 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11912 return ExprError(); 11913 } 11914 11915 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 11916 11917 // Convert the object parameter. 11918 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11919 ExprResult BaseResult = 11920 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 11921 Best->FoundDecl, Method); 11922 if (BaseResult.isInvalid()) 11923 return ExprError(); 11924 Base = BaseResult.take(); 11925 11926 // Build the operator call. 11927 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11928 HadMultipleCandidates, OpLoc); 11929 if (FnExpr.isInvalid()) 11930 return ExprError(); 11931 11932 QualType ResultTy = Method->getReturnType(); 11933 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11934 ResultTy = ResultTy.getNonLValueExprType(Context); 11935 CXXOperatorCallExpr *TheCall = 11936 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(), 11937 Base, ResultTy, VK, OpLoc, false); 11938 11939 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 11940 return ExprError(); 11941 11942 return MaybeBindToTemporary(TheCall); 11943 } 11944 11945 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 11946 /// a literal operator described by the provided lookup results. 11947 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 11948 DeclarationNameInfo &SuffixInfo, 11949 ArrayRef<Expr*> Args, 11950 SourceLocation LitEndLoc, 11951 TemplateArgumentListInfo *TemplateArgs) { 11952 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 11953 11954 OverloadCandidateSet CandidateSet(UDSuffixLoc, 11955 OverloadCandidateSet::CSK_Normal); 11956 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true, 11957 TemplateArgs); 11958 11959 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11960 11961 // Perform overload resolution. This will usually be trivial, but might need 11962 // to perform substitutions for a literal operator template. 11963 OverloadCandidateSet::iterator Best; 11964 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 11965 case OR_Success: 11966 case OR_Deleted: 11967 break; 11968 11969 case OR_No_Viable_Function: 11970 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 11971 << R.getLookupName(); 11972 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11973 return ExprError(); 11974 11975 case OR_Ambiguous: 11976 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 11977 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11978 return ExprError(); 11979 } 11980 11981 FunctionDecl *FD = Best->Function; 11982 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 11983 HadMultipleCandidates, 11984 SuffixInfo.getLoc(), 11985 SuffixInfo.getInfo()); 11986 if (Fn.isInvalid()) 11987 return true; 11988 11989 // Check the argument types. This should almost always be a no-op, except 11990 // that array-to-pointer decay is applied to string literals. 11991 Expr *ConvArgs[2]; 11992 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 11993 ExprResult InputInit = PerformCopyInitialization( 11994 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 11995 SourceLocation(), Args[ArgIdx]); 11996 if (InputInit.isInvalid()) 11997 return true; 11998 ConvArgs[ArgIdx] = InputInit.take(); 11999 } 12000 12001 QualType ResultTy = FD->getReturnType(); 12002 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12003 ResultTy = ResultTy.getNonLValueExprType(Context); 12004 12005 UserDefinedLiteral *UDL = 12006 new (Context) UserDefinedLiteral(Context, Fn.take(), 12007 llvm::makeArrayRef(ConvArgs, Args.size()), 12008 ResultTy, VK, LitEndLoc, UDSuffixLoc); 12009 12010 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 12011 return ExprError(); 12012 12013 if (CheckFunctionCall(FD, UDL, NULL)) 12014 return ExprError(); 12015 12016 return MaybeBindToTemporary(UDL); 12017 } 12018 12019 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 12020 /// given LookupResult is non-empty, it is assumed to describe a member which 12021 /// will be invoked. Otherwise, the function will be found via argument 12022 /// dependent lookup. 12023 /// CallExpr is set to a valid expression and FRS_Success returned on success, 12024 /// otherwise CallExpr is set to ExprError() and some non-success value 12025 /// is returned. 12026 Sema::ForRangeStatus 12027 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 12028 SourceLocation RangeLoc, VarDecl *Decl, 12029 BeginEndFunction BEF, 12030 const DeclarationNameInfo &NameInfo, 12031 LookupResult &MemberLookup, 12032 OverloadCandidateSet *CandidateSet, 12033 Expr *Range, ExprResult *CallExpr) { 12034 CandidateSet->clear(); 12035 if (!MemberLookup.empty()) { 12036 ExprResult MemberRef = 12037 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 12038 /*IsPtr=*/false, CXXScopeSpec(), 12039 /*TemplateKWLoc=*/SourceLocation(), 12040 /*FirstQualifierInScope=*/0, 12041 MemberLookup, 12042 /*TemplateArgs=*/0); 12043 if (MemberRef.isInvalid()) { 12044 *CallExpr = ExprError(); 12045 Diag(Range->getLocStart(), diag::note_in_for_range) 12046 << RangeLoc << BEF << Range->getType(); 12047 return FRS_DiagnosticIssued; 12048 } 12049 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0); 12050 if (CallExpr->isInvalid()) { 12051 *CallExpr = ExprError(); 12052 Diag(Range->getLocStart(), diag::note_in_for_range) 12053 << RangeLoc << BEF << Range->getType(); 12054 return FRS_DiagnosticIssued; 12055 } 12056 } else { 12057 UnresolvedSet<0> FoundNames; 12058 UnresolvedLookupExpr *Fn = 12059 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0, 12060 NestedNameSpecifierLoc(), NameInfo, 12061 /*NeedsADL=*/true, /*Overloaded=*/false, 12062 FoundNames.begin(), FoundNames.end()); 12063 12064 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 12065 CandidateSet, CallExpr); 12066 if (CandidateSet->empty() || CandidateSetError) { 12067 *CallExpr = ExprError(); 12068 return FRS_NoViableFunction; 12069 } 12070 OverloadCandidateSet::iterator Best; 12071 OverloadingResult OverloadResult = 12072 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 12073 12074 if (OverloadResult == OR_No_Viable_Function) { 12075 *CallExpr = ExprError(); 12076 return FRS_NoViableFunction; 12077 } 12078 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 12079 Loc, 0, CandidateSet, &Best, 12080 OverloadResult, 12081 /*AllowTypoCorrection=*/false); 12082 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 12083 *CallExpr = ExprError(); 12084 Diag(Range->getLocStart(), diag::note_in_for_range) 12085 << RangeLoc << BEF << Range->getType(); 12086 return FRS_DiagnosticIssued; 12087 } 12088 } 12089 return FRS_Success; 12090 } 12091 12092 12093 /// FixOverloadedFunctionReference - E is an expression that refers to 12094 /// a C++ overloaded function (possibly with some parentheses and 12095 /// perhaps a '&' around it). We have resolved the overloaded function 12096 /// to the function declaration Fn, so patch up the expression E to 12097 /// refer (possibly indirectly) to Fn. Returns the new expr. 12098 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 12099 FunctionDecl *Fn) { 12100 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 12101 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 12102 Found, Fn); 12103 if (SubExpr == PE->getSubExpr()) 12104 return PE; 12105 12106 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 12107 } 12108 12109 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 12110 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 12111 Found, Fn); 12112 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 12113 SubExpr->getType()) && 12114 "Implicit cast type cannot be determined from overload"); 12115 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 12116 if (SubExpr == ICE->getSubExpr()) 12117 return ICE; 12118 12119 return ImplicitCastExpr::Create(Context, ICE->getType(), 12120 ICE->getCastKind(), 12121 SubExpr, 0, 12122 ICE->getValueKind()); 12123 } 12124 12125 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 12126 assert(UnOp->getOpcode() == UO_AddrOf && 12127 "Can only take the address of an overloaded function"); 12128 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12129 if (Method->isStatic()) { 12130 // Do nothing: static member functions aren't any different 12131 // from non-member functions. 12132 } else { 12133 // Fix the subexpression, which really has to be an 12134 // UnresolvedLookupExpr holding an overloaded member function 12135 // or template. 12136 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12137 Found, Fn); 12138 if (SubExpr == UnOp->getSubExpr()) 12139 return UnOp; 12140 12141 assert(isa<DeclRefExpr>(SubExpr) 12142 && "fixed to something other than a decl ref"); 12143 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 12144 && "fixed to a member ref with no nested name qualifier"); 12145 12146 // We have taken the address of a pointer to member 12147 // function. Perform the computation here so that we get the 12148 // appropriate pointer to member type. 12149 QualType ClassType 12150 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 12151 QualType MemPtrType 12152 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 12153 12154 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 12155 VK_RValue, OK_Ordinary, 12156 UnOp->getOperatorLoc()); 12157 } 12158 } 12159 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12160 Found, Fn); 12161 if (SubExpr == UnOp->getSubExpr()) 12162 return UnOp; 12163 12164 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 12165 Context.getPointerType(SubExpr->getType()), 12166 VK_RValue, OK_Ordinary, 12167 UnOp->getOperatorLoc()); 12168 } 12169 12170 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12171 // FIXME: avoid copy. 12172 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 12173 if (ULE->hasExplicitTemplateArgs()) { 12174 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 12175 TemplateArgs = &TemplateArgsBuffer; 12176 } 12177 12178 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12179 ULE->getQualifierLoc(), 12180 ULE->getTemplateKeywordLoc(), 12181 Fn, 12182 /*enclosing*/ false, // FIXME? 12183 ULE->getNameLoc(), 12184 Fn->getType(), 12185 VK_LValue, 12186 Found.getDecl(), 12187 TemplateArgs); 12188 MarkDeclRefReferenced(DRE); 12189 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 12190 return DRE; 12191 } 12192 12193 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 12194 // FIXME: avoid copy. 12195 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 12196 if (MemExpr->hasExplicitTemplateArgs()) { 12197 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12198 TemplateArgs = &TemplateArgsBuffer; 12199 } 12200 12201 Expr *Base; 12202 12203 // If we're filling in a static method where we used to have an 12204 // implicit member access, rewrite to a simple decl ref. 12205 if (MemExpr->isImplicitAccess()) { 12206 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12207 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12208 MemExpr->getQualifierLoc(), 12209 MemExpr->getTemplateKeywordLoc(), 12210 Fn, 12211 /*enclosing*/ false, 12212 MemExpr->getMemberLoc(), 12213 Fn->getType(), 12214 VK_LValue, 12215 Found.getDecl(), 12216 TemplateArgs); 12217 MarkDeclRefReferenced(DRE); 12218 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 12219 return DRE; 12220 } else { 12221 SourceLocation Loc = MemExpr->getMemberLoc(); 12222 if (MemExpr->getQualifier()) 12223 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 12224 CheckCXXThisCapture(Loc); 12225 Base = new (Context) CXXThisExpr(Loc, 12226 MemExpr->getBaseType(), 12227 /*isImplicit=*/true); 12228 } 12229 } else 12230 Base = MemExpr->getBase(); 12231 12232 ExprValueKind valueKind; 12233 QualType type; 12234 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12235 valueKind = VK_LValue; 12236 type = Fn->getType(); 12237 } else { 12238 valueKind = VK_RValue; 12239 type = Context.BoundMemberTy; 12240 } 12241 12242 MemberExpr *ME = MemberExpr::Create(Context, Base, 12243 MemExpr->isArrow(), 12244 MemExpr->getQualifierLoc(), 12245 MemExpr->getTemplateKeywordLoc(), 12246 Fn, 12247 Found, 12248 MemExpr->getMemberNameInfo(), 12249 TemplateArgs, 12250 type, valueKind, OK_Ordinary); 12251 ME->setHadMultipleCandidates(true); 12252 MarkMemberReferenced(ME); 12253 return ME; 12254 } 12255 12256 llvm_unreachable("Invalid reference to overloaded function"); 12257 } 12258 12259 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 12260 DeclAccessPair Found, 12261 FunctionDecl *Fn) { 12262 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 12263 } 12264 12265 } // end namespace clang 12266