1 //===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===// 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/SemaInternal.h" 15 #include "clang/Sema/Lookup.h" 16 #include "clang/Sema/Initialization.h" 17 #include "clang/Sema/Template.h" 18 #include "clang/Sema/TemplateDeduction.h" 19 #include "clang/Basic/Diagnostic.h" 20 #include "clang/Lex/Preprocessor.h" 21 #include "clang/AST/ASTContext.h" 22 #include "clang/AST/CXXInheritance.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/ExprObjC.h" 27 #include "clang/AST/TypeOrdering.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "llvm/ADT/DenseSet.h" 30 #include "llvm/ADT/SmallPtrSet.h" 31 #include "llvm/ADT/SmallString.h" 32 #include "llvm/ADT/STLExtras.h" 33 #include <algorithm> 34 35 namespace clang { 36 using namespace sema; 37 38 /// A convenience routine for creating a decayed reference to a 39 /// function. 40 static ExprResult 41 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates, 42 SourceLocation Loc = SourceLocation(), 43 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 44 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 45 VK_LValue, Loc, LocInfo); 46 if (HadMultipleCandidates) 47 DRE->setHadMultipleCandidates(true); 48 ExprResult E = S.Owned(DRE); 49 E = S.DefaultFunctionArrayConversion(E.take()); 50 if (E.isInvalid()) 51 return ExprError(); 52 return E; 53 } 54 55 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 56 bool InOverloadResolution, 57 StandardConversionSequence &SCS, 58 bool CStyle, 59 bool AllowObjCWritebackConversion); 60 61 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 62 QualType &ToType, 63 bool InOverloadResolution, 64 StandardConversionSequence &SCS, 65 bool CStyle); 66 static OverloadingResult 67 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 68 UserDefinedConversionSequence& User, 69 OverloadCandidateSet& Conversions, 70 bool AllowExplicit); 71 72 73 static ImplicitConversionSequence::CompareKind 74 CompareStandardConversionSequences(Sema &S, 75 const StandardConversionSequence& SCS1, 76 const StandardConversionSequence& SCS2); 77 78 static ImplicitConversionSequence::CompareKind 79 CompareQualificationConversions(Sema &S, 80 const StandardConversionSequence& SCS1, 81 const StandardConversionSequence& SCS2); 82 83 static ImplicitConversionSequence::CompareKind 84 CompareDerivedToBaseConversions(Sema &S, 85 const StandardConversionSequence& SCS1, 86 const StandardConversionSequence& SCS2); 87 88 89 90 /// GetConversionCategory - Retrieve the implicit conversion 91 /// category corresponding to the given implicit conversion kind. 92 ImplicitConversionCategory 93 GetConversionCategory(ImplicitConversionKind Kind) { 94 static const ImplicitConversionCategory 95 Category[(int)ICK_Num_Conversion_Kinds] = { 96 ICC_Identity, 97 ICC_Lvalue_Transformation, 98 ICC_Lvalue_Transformation, 99 ICC_Lvalue_Transformation, 100 ICC_Identity, 101 ICC_Qualification_Adjustment, 102 ICC_Promotion, 103 ICC_Promotion, 104 ICC_Promotion, 105 ICC_Conversion, 106 ICC_Conversion, 107 ICC_Conversion, 108 ICC_Conversion, 109 ICC_Conversion, 110 ICC_Conversion, 111 ICC_Conversion, 112 ICC_Conversion, 113 ICC_Conversion, 114 ICC_Conversion, 115 ICC_Conversion, 116 ICC_Conversion, 117 ICC_Conversion 118 }; 119 return Category[(int)Kind]; 120 } 121 122 /// GetConversionRank - Retrieve the implicit conversion rank 123 /// corresponding to the given implicit conversion kind. 124 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 125 static const ImplicitConversionRank 126 Rank[(int)ICK_Num_Conversion_Kinds] = { 127 ICR_Exact_Match, 128 ICR_Exact_Match, 129 ICR_Exact_Match, 130 ICR_Exact_Match, 131 ICR_Exact_Match, 132 ICR_Exact_Match, 133 ICR_Promotion, 134 ICR_Promotion, 135 ICR_Promotion, 136 ICR_Conversion, 137 ICR_Conversion, 138 ICR_Conversion, 139 ICR_Conversion, 140 ICR_Conversion, 141 ICR_Conversion, 142 ICR_Conversion, 143 ICR_Conversion, 144 ICR_Conversion, 145 ICR_Conversion, 146 ICR_Conversion, 147 ICR_Complex_Real_Conversion, 148 ICR_Conversion, 149 ICR_Conversion, 150 ICR_Writeback_Conversion 151 }; 152 return Rank[(int)Kind]; 153 } 154 155 /// GetImplicitConversionName - Return the name of this kind of 156 /// implicit conversion. 157 const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 158 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 159 "No conversion", 160 "Lvalue-to-rvalue", 161 "Array-to-pointer", 162 "Function-to-pointer", 163 "Noreturn adjustment", 164 "Qualification", 165 "Integral promotion", 166 "Floating point promotion", 167 "Complex promotion", 168 "Integral conversion", 169 "Floating conversion", 170 "Complex conversion", 171 "Floating-integral conversion", 172 "Pointer conversion", 173 "Pointer-to-member conversion", 174 "Boolean conversion", 175 "Compatible-types conversion", 176 "Derived-to-base conversion", 177 "Vector conversion", 178 "Vector splat", 179 "Complex-real conversion", 180 "Block Pointer conversion", 181 "Transparent Union Conversion" 182 "Writeback conversion" 183 }; 184 return Name[Kind]; 185 } 186 187 /// StandardConversionSequence - Set the standard conversion 188 /// sequence to the identity conversion. 189 void StandardConversionSequence::setAsIdentityConversion() { 190 First = ICK_Identity; 191 Second = ICK_Identity; 192 Third = ICK_Identity; 193 DeprecatedStringLiteralToCharPtr = false; 194 QualificationIncludesObjCLifetime = false; 195 ReferenceBinding = false; 196 DirectBinding = false; 197 IsLvalueReference = true; 198 BindsToFunctionLvalue = false; 199 BindsToRvalue = false; 200 BindsImplicitObjectArgumentWithoutRefQualifier = false; 201 ObjCLifetimeConversionBinding = false; 202 CopyConstructor = 0; 203 } 204 205 /// getRank - Retrieve the rank of this standard conversion sequence 206 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 207 /// implicit conversions. 208 ImplicitConversionRank StandardConversionSequence::getRank() const { 209 ImplicitConversionRank Rank = ICR_Exact_Match; 210 if (GetConversionRank(First) > Rank) 211 Rank = GetConversionRank(First); 212 if (GetConversionRank(Second) > Rank) 213 Rank = GetConversionRank(Second); 214 if (GetConversionRank(Third) > Rank) 215 Rank = GetConversionRank(Third); 216 return Rank; 217 } 218 219 /// isPointerConversionToBool - Determines whether this conversion is 220 /// a conversion of a pointer or pointer-to-member to bool. This is 221 /// used as part of the ranking of standard conversion sequences 222 /// (C++ 13.3.3.2p4). 223 bool StandardConversionSequence::isPointerConversionToBool() const { 224 // Note that FromType has not necessarily been transformed by the 225 // array-to-pointer or function-to-pointer implicit conversions, so 226 // check for their presence as well as checking whether FromType is 227 // a pointer. 228 if (getToType(1)->isBooleanType() && 229 (getFromType()->isPointerType() || 230 getFromType()->isObjCObjectPointerType() || 231 getFromType()->isBlockPointerType() || 232 getFromType()->isNullPtrType() || 233 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 234 return true; 235 236 return false; 237 } 238 239 /// isPointerConversionToVoidPointer - Determines whether this 240 /// conversion is a conversion of a pointer to a void pointer. This is 241 /// used as part of the ranking of standard conversion sequences (C++ 242 /// 13.3.3.2p4). 243 bool 244 StandardConversionSequence:: 245 isPointerConversionToVoidPointer(ASTContext& Context) const { 246 QualType FromType = getFromType(); 247 QualType ToType = getToType(1); 248 249 // Note that FromType has not necessarily been transformed by the 250 // array-to-pointer implicit conversion, so check for its presence 251 // and redo the conversion to get a pointer. 252 if (First == ICK_Array_To_Pointer) 253 FromType = Context.getArrayDecayedType(FromType); 254 255 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 256 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 257 return ToPtrType->getPointeeType()->isVoidType(); 258 259 return false; 260 } 261 262 /// Skip any implicit casts which could be either part of a narrowing conversion 263 /// or after one in an implicit conversion. 264 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 265 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 266 switch (ICE->getCastKind()) { 267 case CK_NoOp: 268 case CK_IntegralCast: 269 case CK_IntegralToBoolean: 270 case CK_IntegralToFloating: 271 case CK_FloatingToIntegral: 272 case CK_FloatingToBoolean: 273 case CK_FloatingCast: 274 Converted = ICE->getSubExpr(); 275 continue; 276 277 default: 278 return Converted; 279 } 280 } 281 282 return Converted; 283 } 284 285 /// Check if this standard conversion sequence represents a narrowing 286 /// conversion, according to C++11 [dcl.init.list]p7. 287 /// 288 /// \param Ctx The AST context. 289 /// \param Converted The result of applying this standard conversion sequence. 290 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 291 /// value of the expression prior to the narrowing conversion. 292 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 293 /// type of the expression prior to the narrowing conversion. 294 NarrowingKind 295 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 296 const Expr *Converted, 297 APValue &ConstantValue, 298 QualType &ConstantType) const { 299 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 300 301 // C++11 [dcl.init.list]p7: 302 // A narrowing conversion is an implicit conversion ... 303 QualType FromType = getToType(0); 304 QualType ToType = getToType(1); 305 switch (Second) { 306 // -- from a floating-point type to an integer type, or 307 // 308 // -- from an integer type or unscoped enumeration type to a floating-point 309 // type, except where the source is a constant expression and the actual 310 // value after conversion will fit into the target type and will produce 311 // the original value when converted back to the original type, or 312 case ICK_Floating_Integral: 313 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 314 return NK_Type_Narrowing; 315 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 316 llvm::APSInt IntConstantValue; 317 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 318 if (Initializer && 319 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 320 // Convert the integer to the floating type. 321 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 322 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 323 llvm::APFloat::rmNearestTiesToEven); 324 // And back. 325 llvm::APSInt ConvertedValue = IntConstantValue; 326 bool ignored; 327 Result.convertToInteger(ConvertedValue, 328 llvm::APFloat::rmTowardZero, &ignored); 329 // If the resulting value is different, this was a narrowing conversion. 330 if (IntConstantValue != ConvertedValue) { 331 ConstantValue = APValue(IntConstantValue); 332 ConstantType = Initializer->getType(); 333 return NK_Constant_Narrowing; 334 } 335 } else { 336 // Variables are always narrowings. 337 return NK_Variable_Narrowing; 338 } 339 } 340 return NK_Not_Narrowing; 341 342 // -- from long double to double or float, or from double to float, except 343 // where the source is a constant expression and the actual value after 344 // conversion is within the range of values that can be represented (even 345 // if it cannot be represented exactly), or 346 case ICK_Floating_Conversion: 347 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 348 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 349 // FromType is larger than ToType. 350 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 351 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 352 // Constant! 353 assert(ConstantValue.isFloat()); 354 llvm::APFloat FloatVal = ConstantValue.getFloat(); 355 // Convert the source value into the target type. 356 bool ignored; 357 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 358 Ctx.getFloatTypeSemantics(ToType), 359 llvm::APFloat::rmNearestTiesToEven, &ignored); 360 // If there was no overflow, the source value is within the range of 361 // values that can be represented. 362 if (ConvertStatus & llvm::APFloat::opOverflow) { 363 ConstantType = Initializer->getType(); 364 return NK_Constant_Narrowing; 365 } 366 } else { 367 return NK_Variable_Narrowing; 368 } 369 } 370 return NK_Not_Narrowing; 371 372 // -- from an integer type or unscoped enumeration type to an integer type 373 // that cannot represent all the values of the original type, except where 374 // the source is a constant expression and the actual value after 375 // conversion will fit into the target type and will produce the original 376 // value when converted back to the original type. 377 case ICK_Boolean_Conversion: // Bools are integers too. 378 if (!FromType->isIntegralOrUnscopedEnumerationType()) { 379 // Boolean conversions can be from pointers and pointers to members 380 // [conv.bool], and those aren't considered narrowing conversions. 381 return NK_Not_Narrowing; 382 } // Otherwise, fall through to the integral case. 383 case ICK_Integral_Conversion: { 384 assert(FromType->isIntegralOrUnscopedEnumerationType()); 385 assert(ToType->isIntegralOrUnscopedEnumerationType()); 386 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 387 const unsigned FromWidth = Ctx.getIntWidth(FromType); 388 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 389 const unsigned ToWidth = Ctx.getIntWidth(ToType); 390 391 if (FromWidth > ToWidth || 392 (FromWidth == ToWidth && FromSigned != ToSigned) || 393 (FromSigned && !ToSigned)) { 394 // Not all values of FromType can be represented in ToType. 395 llvm::APSInt InitializerValue; 396 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 397 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 398 // Such conversions on variables are always narrowing. 399 return NK_Variable_Narrowing; 400 } 401 bool Narrowing = false; 402 if (FromWidth < ToWidth) { 403 // Negative -> unsigned is narrowing. Otherwise, more bits is never 404 // narrowing. 405 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 406 Narrowing = true; 407 } else { 408 // Add a bit to the InitializerValue so we don't have to worry about 409 // signed vs. unsigned comparisons. 410 InitializerValue = InitializerValue.extend( 411 InitializerValue.getBitWidth() + 1); 412 // Convert the initializer to and from the target width and signed-ness. 413 llvm::APSInt ConvertedValue = InitializerValue; 414 ConvertedValue = ConvertedValue.trunc(ToWidth); 415 ConvertedValue.setIsSigned(ToSigned); 416 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 417 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 418 // If the result is different, this was a narrowing conversion. 419 if (ConvertedValue != InitializerValue) 420 Narrowing = true; 421 } 422 if (Narrowing) { 423 ConstantType = Initializer->getType(); 424 ConstantValue = APValue(InitializerValue); 425 return NK_Constant_Narrowing; 426 } 427 } 428 return NK_Not_Narrowing; 429 } 430 431 default: 432 // Other kinds of conversions are not narrowings. 433 return NK_Not_Narrowing; 434 } 435 } 436 437 /// DebugPrint - Print this standard conversion sequence to standard 438 /// error. Useful for debugging overloading issues. 439 void StandardConversionSequence::DebugPrint() const { 440 raw_ostream &OS = llvm::errs(); 441 bool PrintedSomething = false; 442 if (First != ICK_Identity) { 443 OS << GetImplicitConversionName(First); 444 PrintedSomething = true; 445 } 446 447 if (Second != ICK_Identity) { 448 if (PrintedSomething) { 449 OS << " -> "; 450 } 451 OS << GetImplicitConversionName(Second); 452 453 if (CopyConstructor) { 454 OS << " (by copy constructor)"; 455 } else if (DirectBinding) { 456 OS << " (direct reference binding)"; 457 } else if (ReferenceBinding) { 458 OS << " (reference binding)"; 459 } 460 PrintedSomething = true; 461 } 462 463 if (Third != ICK_Identity) { 464 if (PrintedSomething) { 465 OS << " -> "; 466 } 467 OS << GetImplicitConversionName(Third); 468 PrintedSomething = true; 469 } 470 471 if (!PrintedSomething) { 472 OS << "No conversions required"; 473 } 474 } 475 476 /// DebugPrint - Print this user-defined conversion sequence to standard 477 /// error. Useful for debugging overloading issues. 478 void UserDefinedConversionSequence::DebugPrint() const { 479 raw_ostream &OS = llvm::errs(); 480 if (Before.First || Before.Second || Before.Third) { 481 Before.DebugPrint(); 482 OS << " -> "; 483 } 484 if (ConversionFunction) 485 OS << '\'' << *ConversionFunction << '\''; 486 else 487 OS << "aggregate initialization"; 488 if (After.First || After.Second || After.Third) { 489 OS << " -> "; 490 After.DebugPrint(); 491 } 492 } 493 494 /// DebugPrint - Print this implicit conversion sequence to standard 495 /// error. Useful for debugging overloading issues. 496 void ImplicitConversionSequence::DebugPrint() const { 497 raw_ostream &OS = llvm::errs(); 498 switch (ConversionKind) { 499 case StandardConversion: 500 OS << "Standard conversion: "; 501 Standard.DebugPrint(); 502 break; 503 case UserDefinedConversion: 504 OS << "User-defined conversion: "; 505 UserDefined.DebugPrint(); 506 break; 507 case EllipsisConversion: 508 OS << "Ellipsis conversion"; 509 break; 510 case AmbiguousConversion: 511 OS << "Ambiguous conversion"; 512 break; 513 case BadConversion: 514 OS << "Bad conversion"; 515 break; 516 } 517 518 OS << "\n"; 519 } 520 521 void AmbiguousConversionSequence::construct() { 522 new (&conversions()) ConversionSet(); 523 } 524 525 void AmbiguousConversionSequence::destruct() { 526 conversions().~ConversionSet(); 527 } 528 529 void 530 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 531 FromTypePtr = O.FromTypePtr; 532 ToTypePtr = O.ToTypePtr; 533 new (&conversions()) ConversionSet(O.conversions()); 534 } 535 536 namespace { 537 // Structure used by OverloadCandidate::DeductionFailureInfo to store 538 // template parameter and template argument information. 539 struct DFIParamWithArguments { 540 TemplateParameter Param; 541 TemplateArgument FirstArg; 542 TemplateArgument SecondArg; 543 }; 544 } 545 546 /// \brief Convert from Sema's representation of template deduction information 547 /// to the form used in overload-candidate information. 548 OverloadCandidate::DeductionFailureInfo 549 static MakeDeductionFailureInfo(ASTContext &Context, 550 Sema::TemplateDeductionResult TDK, 551 TemplateDeductionInfo &Info) { 552 OverloadCandidate::DeductionFailureInfo Result; 553 Result.Result = static_cast<unsigned>(TDK); 554 Result.HasDiagnostic = false; 555 Result.Data = 0; 556 switch (TDK) { 557 case Sema::TDK_Success: 558 case Sema::TDK_InstantiationDepth: 559 case Sema::TDK_TooManyArguments: 560 case Sema::TDK_TooFewArguments: 561 break; 562 563 case Sema::TDK_Incomplete: 564 case Sema::TDK_InvalidExplicitArguments: 565 Result.Data = Info.Param.getOpaqueValue(); 566 break; 567 568 case Sema::TDK_Inconsistent: 569 case Sema::TDK_Underqualified: { 570 // FIXME: Should allocate from normal heap so that we can free this later. 571 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 572 Saved->Param = Info.Param; 573 Saved->FirstArg = Info.FirstArg; 574 Saved->SecondArg = Info.SecondArg; 575 Result.Data = Saved; 576 break; 577 } 578 579 case Sema::TDK_SubstitutionFailure: 580 Result.Data = Info.take(); 581 if (Info.hasSFINAEDiagnostic()) { 582 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 583 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 584 Info.takeSFINAEDiagnostic(*Diag); 585 Result.HasDiagnostic = true; 586 } 587 break; 588 589 case Sema::TDK_NonDeducedMismatch: 590 case Sema::TDK_FailedOverloadResolution: 591 break; 592 } 593 594 return Result; 595 } 596 597 void OverloadCandidate::DeductionFailureInfo::Destroy() { 598 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 599 case Sema::TDK_Success: 600 case Sema::TDK_InstantiationDepth: 601 case Sema::TDK_Incomplete: 602 case Sema::TDK_TooManyArguments: 603 case Sema::TDK_TooFewArguments: 604 case Sema::TDK_InvalidExplicitArguments: 605 break; 606 607 case Sema::TDK_Inconsistent: 608 case Sema::TDK_Underqualified: 609 // FIXME: Destroy the data? 610 Data = 0; 611 break; 612 613 case Sema::TDK_SubstitutionFailure: 614 // FIXME: Destroy the template argument list? 615 Data = 0; 616 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 617 Diag->~PartialDiagnosticAt(); 618 HasDiagnostic = false; 619 } 620 break; 621 622 // Unhandled 623 case Sema::TDK_NonDeducedMismatch: 624 case Sema::TDK_FailedOverloadResolution: 625 break; 626 } 627 } 628 629 PartialDiagnosticAt * 630 OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() { 631 if (HasDiagnostic) 632 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 633 return 0; 634 } 635 636 TemplateParameter 637 OverloadCandidate::DeductionFailureInfo::getTemplateParameter() { 638 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 639 case Sema::TDK_Success: 640 case Sema::TDK_InstantiationDepth: 641 case Sema::TDK_TooManyArguments: 642 case Sema::TDK_TooFewArguments: 643 case Sema::TDK_SubstitutionFailure: 644 return TemplateParameter(); 645 646 case Sema::TDK_Incomplete: 647 case Sema::TDK_InvalidExplicitArguments: 648 return TemplateParameter::getFromOpaqueValue(Data); 649 650 case Sema::TDK_Inconsistent: 651 case Sema::TDK_Underqualified: 652 return static_cast<DFIParamWithArguments*>(Data)->Param; 653 654 // Unhandled 655 case Sema::TDK_NonDeducedMismatch: 656 case Sema::TDK_FailedOverloadResolution: 657 break; 658 } 659 660 return TemplateParameter(); 661 } 662 663 TemplateArgumentList * 664 OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() { 665 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 666 case Sema::TDK_Success: 667 case Sema::TDK_InstantiationDepth: 668 case Sema::TDK_TooManyArguments: 669 case Sema::TDK_TooFewArguments: 670 case Sema::TDK_Incomplete: 671 case Sema::TDK_InvalidExplicitArguments: 672 case Sema::TDK_Inconsistent: 673 case Sema::TDK_Underqualified: 674 return 0; 675 676 case Sema::TDK_SubstitutionFailure: 677 return static_cast<TemplateArgumentList*>(Data); 678 679 // Unhandled 680 case Sema::TDK_NonDeducedMismatch: 681 case Sema::TDK_FailedOverloadResolution: 682 break; 683 } 684 685 return 0; 686 } 687 688 const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() { 689 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 690 case Sema::TDK_Success: 691 case Sema::TDK_InstantiationDepth: 692 case Sema::TDK_Incomplete: 693 case Sema::TDK_TooManyArguments: 694 case Sema::TDK_TooFewArguments: 695 case Sema::TDK_InvalidExplicitArguments: 696 case Sema::TDK_SubstitutionFailure: 697 return 0; 698 699 case Sema::TDK_Inconsistent: 700 case Sema::TDK_Underqualified: 701 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg; 702 703 // Unhandled 704 case Sema::TDK_NonDeducedMismatch: 705 case Sema::TDK_FailedOverloadResolution: 706 break; 707 } 708 709 return 0; 710 } 711 712 const TemplateArgument * 713 OverloadCandidate::DeductionFailureInfo::getSecondArg() { 714 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 715 case Sema::TDK_Success: 716 case Sema::TDK_InstantiationDepth: 717 case Sema::TDK_Incomplete: 718 case Sema::TDK_TooManyArguments: 719 case Sema::TDK_TooFewArguments: 720 case Sema::TDK_InvalidExplicitArguments: 721 case Sema::TDK_SubstitutionFailure: 722 return 0; 723 724 case Sema::TDK_Inconsistent: 725 case Sema::TDK_Underqualified: 726 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg; 727 728 // Unhandled 729 case Sema::TDK_NonDeducedMismatch: 730 case Sema::TDK_FailedOverloadResolution: 731 break; 732 } 733 734 return 0; 735 } 736 737 void OverloadCandidateSet::clear() { 738 for (iterator i = begin(), e = end(); i != e; ++i) { 739 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 740 i->Conversions[ii].~ImplicitConversionSequence(); 741 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 742 i->DeductionFailure.Destroy(); 743 } 744 NumInlineSequences = 0; 745 Candidates.clear(); 746 Functions.clear(); 747 } 748 749 namespace { 750 class UnbridgedCastsSet { 751 struct Entry { 752 Expr **Addr; 753 Expr *Saved; 754 }; 755 SmallVector<Entry, 2> Entries; 756 757 public: 758 void save(Sema &S, Expr *&E) { 759 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 760 Entry entry = { &E, E }; 761 Entries.push_back(entry); 762 E = S.stripARCUnbridgedCast(E); 763 } 764 765 void restore() { 766 for (SmallVectorImpl<Entry>::iterator 767 i = Entries.begin(), e = Entries.end(); i != e; ++i) 768 *i->Addr = i->Saved; 769 } 770 }; 771 } 772 773 /// checkPlaceholderForOverload - Do any interesting placeholder-like 774 /// preprocessing on the given expression. 775 /// 776 /// \param unbridgedCasts a collection to which to add unbridged casts; 777 /// without this, they will be immediately diagnosed as errors 778 /// 779 /// Return true on unrecoverable error. 780 static bool checkPlaceholderForOverload(Sema &S, Expr *&E, 781 UnbridgedCastsSet *unbridgedCasts = 0) { 782 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 783 // We can't handle overloaded expressions here because overload 784 // resolution might reasonably tweak them. 785 if (placeholder->getKind() == BuiltinType::Overload) return false; 786 787 // If the context potentially accepts unbridged ARC casts, strip 788 // the unbridged cast and add it to the collection for later restoration. 789 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 790 unbridgedCasts) { 791 unbridgedCasts->save(S, E); 792 return false; 793 } 794 795 // Go ahead and check everything else. 796 ExprResult result = S.CheckPlaceholderExpr(E); 797 if (result.isInvalid()) 798 return true; 799 800 E = result.take(); 801 return false; 802 } 803 804 // Nothing to do. 805 return false; 806 } 807 808 /// checkArgPlaceholdersForOverload - Check a set of call operands for 809 /// placeholders. 810 static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args, 811 unsigned numArgs, 812 UnbridgedCastsSet &unbridged) { 813 for (unsigned i = 0; i != numArgs; ++i) 814 if (checkPlaceholderForOverload(S, args[i], &unbridged)) 815 return true; 816 817 return false; 818 } 819 820 // IsOverload - Determine whether the given New declaration is an 821 // overload of the declarations in Old. This routine returns false if 822 // New and Old cannot be overloaded, e.g., if New has the same 823 // signature as some function in Old (C++ 1.3.10) or if the Old 824 // declarations aren't functions (or function templates) at all. When 825 // it does return false, MatchedDecl will point to the decl that New 826 // cannot be overloaded with. This decl may be a UsingShadowDecl on 827 // top of the underlying declaration. 828 // 829 // Example: Given the following input: 830 // 831 // void f(int, float); // #1 832 // void f(int, int); // #2 833 // int f(int, int); // #3 834 // 835 // When we process #1, there is no previous declaration of "f", 836 // so IsOverload will not be used. 837 // 838 // When we process #2, Old contains only the FunctionDecl for #1. By 839 // comparing the parameter types, we see that #1 and #2 are overloaded 840 // (since they have different signatures), so this routine returns 841 // false; MatchedDecl is unchanged. 842 // 843 // When we process #3, Old is an overload set containing #1 and #2. We 844 // compare the signatures of #3 to #1 (they're overloaded, so we do 845 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 846 // identical (return types of functions are not part of the 847 // signature), IsOverload returns false and MatchedDecl will be set to 848 // point to the FunctionDecl for #2. 849 // 850 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 851 // into a class by a using declaration. The rules for whether to hide 852 // shadow declarations ignore some properties which otherwise figure 853 // into a function template's signature. 854 Sema::OverloadKind 855 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 856 NamedDecl *&Match, bool NewIsUsingDecl) { 857 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 858 I != E; ++I) { 859 NamedDecl *OldD = *I; 860 861 bool OldIsUsingDecl = false; 862 if (isa<UsingShadowDecl>(OldD)) { 863 OldIsUsingDecl = true; 864 865 // We can always introduce two using declarations into the same 866 // context, even if they have identical signatures. 867 if (NewIsUsingDecl) continue; 868 869 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 870 } 871 872 // If either declaration was introduced by a using declaration, 873 // we'll need to use slightly different rules for matching. 874 // Essentially, these rules are the normal rules, except that 875 // function templates hide function templates with different 876 // return types or template parameter lists. 877 bool UseMemberUsingDeclRules = 878 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord(); 879 880 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) { 881 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) { 882 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 883 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 884 continue; 885 } 886 887 Match = *I; 888 return Ovl_Match; 889 } 890 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) { 891 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 892 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 893 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 894 continue; 895 } 896 897 Match = *I; 898 return Ovl_Match; 899 } 900 } else if (isa<UsingDecl>(OldD)) { 901 // We can overload with these, which can show up when doing 902 // redeclaration checks for UsingDecls. 903 assert(Old.getLookupKind() == LookupUsingDeclName); 904 } else if (isa<TagDecl>(OldD)) { 905 // We can always overload with tags by hiding them. 906 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 907 // Optimistically assume that an unresolved using decl will 908 // overload; if it doesn't, we'll have to diagnose during 909 // template instantiation. 910 } else { 911 // (C++ 13p1): 912 // Only function declarations can be overloaded; object and type 913 // declarations cannot be overloaded. 914 Match = *I; 915 return Ovl_NonFunction; 916 } 917 } 918 919 return Ovl_Overload; 920 } 921 922 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 923 bool UseUsingDeclRules) { 924 // If both of the functions are extern "C", then they are not 925 // overloads. 926 if (Old->isExternC() && New->isExternC()) 927 return false; 928 929 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 930 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 931 932 // C++ [temp.fct]p2: 933 // A function template can be overloaded with other function templates 934 // and with normal (non-template) functions. 935 if ((OldTemplate == 0) != (NewTemplate == 0)) 936 return true; 937 938 // Is the function New an overload of the function Old? 939 QualType OldQType = Context.getCanonicalType(Old->getType()); 940 QualType NewQType = Context.getCanonicalType(New->getType()); 941 942 // Compare the signatures (C++ 1.3.10) of the two functions to 943 // determine whether they are overloads. If we find any mismatch 944 // in the signature, they are overloads. 945 946 // If either of these functions is a K&R-style function (no 947 // prototype), then we consider them to have matching signatures. 948 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 949 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 950 return false; 951 952 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType); 953 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType); 954 955 // The signature of a function includes the types of its 956 // parameters (C++ 1.3.10), which includes the presence or absence 957 // of the ellipsis; see C++ DR 357). 958 if (OldQType != NewQType && 959 (OldType->getNumArgs() != NewType->getNumArgs() || 960 OldType->isVariadic() != NewType->isVariadic() || 961 !FunctionArgTypesAreEqual(OldType, NewType))) 962 return true; 963 964 // C++ [temp.over.link]p4: 965 // The signature of a function template consists of its function 966 // signature, its return type and its template parameter list. The names 967 // of the template parameters are significant only for establishing the 968 // relationship between the template parameters and the rest of the 969 // signature. 970 // 971 // We check the return type and template parameter lists for function 972 // templates first; the remaining checks follow. 973 // 974 // However, we don't consider either of these when deciding whether 975 // a member introduced by a shadow declaration is hidden. 976 if (!UseUsingDeclRules && NewTemplate && 977 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 978 OldTemplate->getTemplateParameters(), 979 false, TPL_TemplateMatch) || 980 OldType->getResultType() != NewType->getResultType())) 981 return true; 982 983 // If the function is a class member, its signature includes the 984 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 985 // 986 // As part of this, also check whether one of the member functions 987 // is static, in which case they are not overloads (C++ 988 // 13.1p2). While not part of the definition of the signature, 989 // this check is important to determine whether these functions 990 // can be overloaded. 991 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 992 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 993 if (OldMethod && NewMethod && 994 !OldMethod->isStatic() && !NewMethod->isStatic() && 995 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() || 996 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) { 997 if (!UseUsingDeclRules && 998 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() && 999 (OldMethod->getRefQualifier() == RQ_None || 1000 NewMethod->getRefQualifier() == RQ_None)) { 1001 // C++0x [over.load]p2: 1002 // - Member function declarations with the same name and the same 1003 // parameter-type-list as well as member function template 1004 // declarations with the same name, the same parameter-type-list, and 1005 // the same template parameter lists cannot be overloaded if any of 1006 // them, but not all, have a ref-qualifier (8.3.5). 1007 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1008 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1009 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1010 } 1011 1012 return true; 1013 } 1014 1015 // The signatures match; this is not an overload. 1016 return false; 1017 } 1018 1019 /// \brief Checks availability of the function depending on the current 1020 /// function context. Inside an unavailable function, unavailability is ignored. 1021 /// 1022 /// \returns true if \arg FD is unavailable and current context is inside 1023 /// an available function, false otherwise. 1024 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1025 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1026 } 1027 1028 /// \brief Tries a user-defined conversion from From to ToType. 1029 /// 1030 /// Produces an implicit conversion sequence for when a standard conversion 1031 /// is not an option. See TryImplicitConversion for more information. 1032 static ImplicitConversionSequence 1033 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1034 bool SuppressUserConversions, 1035 bool AllowExplicit, 1036 bool InOverloadResolution, 1037 bool CStyle, 1038 bool AllowObjCWritebackConversion) { 1039 ImplicitConversionSequence ICS; 1040 1041 if (SuppressUserConversions) { 1042 // We're not in the case above, so there is no conversion that 1043 // we can perform. 1044 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1045 return ICS; 1046 } 1047 1048 // Attempt user-defined conversion. 1049 OverloadCandidateSet Conversions(From->getExprLoc()); 1050 OverloadingResult UserDefResult 1051 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 1052 AllowExplicit); 1053 1054 if (UserDefResult == OR_Success) { 1055 ICS.setUserDefined(); 1056 // C++ [over.ics.user]p4: 1057 // A conversion of an expression of class type to the same class 1058 // type is given Exact Match rank, and a conversion of an 1059 // expression of class type to a base class of that type is 1060 // given Conversion rank, in spite of the fact that a copy 1061 // constructor (i.e., a user-defined conversion function) is 1062 // called for those cases. 1063 if (CXXConstructorDecl *Constructor 1064 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1065 QualType FromCanon 1066 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1067 QualType ToCanon 1068 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1069 if (Constructor->isCopyConstructor() && 1070 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1071 // Turn this into a "standard" conversion sequence, so that it 1072 // gets ranked with standard conversion sequences. 1073 ICS.setStandard(); 1074 ICS.Standard.setAsIdentityConversion(); 1075 ICS.Standard.setFromType(From->getType()); 1076 ICS.Standard.setAllToTypes(ToType); 1077 ICS.Standard.CopyConstructor = Constructor; 1078 if (ToCanon != FromCanon) 1079 ICS.Standard.Second = ICK_Derived_To_Base; 1080 } 1081 } 1082 1083 // C++ [over.best.ics]p4: 1084 // However, when considering the argument of a user-defined 1085 // conversion function that is a candidate by 13.3.1.3 when 1086 // invoked for the copying of the temporary in the second step 1087 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 1088 // 13.3.1.6 in all cases, only standard conversion sequences and 1089 // ellipsis conversion sequences are allowed. 1090 if (SuppressUserConversions && ICS.isUserDefined()) { 1091 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 1092 } 1093 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 1094 ICS.setAmbiguous(); 1095 ICS.Ambiguous.setFromType(From->getType()); 1096 ICS.Ambiguous.setToType(ToType); 1097 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1098 Cand != Conversions.end(); ++Cand) 1099 if (Cand->Viable) 1100 ICS.Ambiguous.addConversion(Cand->Function); 1101 } else { 1102 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1103 } 1104 1105 return ICS; 1106 } 1107 1108 /// TryImplicitConversion - Attempt to perform an implicit conversion 1109 /// from the given expression (Expr) to the given type (ToType). This 1110 /// function returns an implicit conversion sequence that can be used 1111 /// to perform the initialization. Given 1112 /// 1113 /// void f(float f); 1114 /// void g(int i) { f(i); } 1115 /// 1116 /// this routine would produce an implicit conversion sequence to 1117 /// describe the initialization of f from i, which will be a standard 1118 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1119 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1120 // 1121 /// Note that this routine only determines how the conversion can be 1122 /// performed; it does not actually perform the conversion. As such, 1123 /// it will not produce any diagnostics if no conversion is available, 1124 /// but will instead return an implicit conversion sequence of kind 1125 /// "BadConversion". 1126 /// 1127 /// If @p SuppressUserConversions, then user-defined conversions are 1128 /// not permitted. 1129 /// If @p AllowExplicit, then explicit user-defined conversions are 1130 /// permitted. 1131 /// 1132 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1133 /// writeback conversion, which allows __autoreleasing id* parameters to 1134 /// be initialized with __strong id* or __weak id* arguments. 1135 static ImplicitConversionSequence 1136 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1137 bool SuppressUserConversions, 1138 bool AllowExplicit, 1139 bool InOverloadResolution, 1140 bool CStyle, 1141 bool AllowObjCWritebackConversion) { 1142 ImplicitConversionSequence ICS; 1143 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1144 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1145 ICS.setStandard(); 1146 return ICS; 1147 } 1148 1149 if (!S.getLangOpts().CPlusPlus) { 1150 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1151 return ICS; 1152 } 1153 1154 // C++ [over.ics.user]p4: 1155 // A conversion of an expression of class type to the same class 1156 // type is given Exact Match rank, and a conversion of an 1157 // expression of class type to a base class of that type is 1158 // given Conversion rank, in spite of the fact that a copy/move 1159 // constructor (i.e., a user-defined conversion function) is 1160 // called for those cases. 1161 QualType FromType = From->getType(); 1162 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1163 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1164 S.IsDerivedFrom(FromType, ToType))) { 1165 ICS.setStandard(); 1166 ICS.Standard.setAsIdentityConversion(); 1167 ICS.Standard.setFromType(FromType); 1168 ICS.Standard.setAllToTypes(ToType); 1169 1170 // We don't actually check at this point whether there is a valid 1171 // copy/move constructor, since overloading just assumes that it 1172 // exists. When we actually perform initialization, we'll find the 1173 // appropriate constructor to copy the returned object, if needed. 1174 ICS.Standard.CopyConstructor = 0; 1175 1176 // Determine whether this is considered a derived-to-base conversion. 1177 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1178 ICS.Standard.Second = ICK_Derived_To_Base; 1179 1180 return ICS; 1181 } 1182 1183 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1184 AllowExplicit, InOverloadResolution, CStyle, 1185 AllowObjCWritebackConversion); 1186 } 1187 1188 ImplicitConversionSequence 1189 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1190 bool SuppressUserConversions, 1191 bool AllowExplicit, 1192 bool InOverloadResolution, 1193 bool CStyle, 1194 bool AllowObjCWritebackConversion) { 1195 return clang::TryImplicitConversion(*this, From, ToType, 1196 SuppressUserConversions, AllowExplicit, 1197 InOverloadResolution, CStyle, 1198 AllowObjCWritebackConversion); 1199 } 1200 1201 /// PerformImplicitConversion - Perform an implicit conversion of the 1202 /// expression From to the type ToType. Returns the 1203 /// converted expression. Flavor is the kind of conversion we're 1204 /// performing, used in the error message. If @p AllowExplicit, 1205 /// explicit user-defined conversions are permitted. 1206 ExprResult 1207 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1208 AssignmentAction Action, bool AllowExplicit) { 1209 ImplicitConversionSequence ICS; 1210 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1211 } 1212 1213 ExprResult 1214 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1215 AssignmentAction Action, bool AllowExplicit, 1216 ImplicitConversionSequence& ICS) { 1217 if (checkPlaceholderForOverload(*this, From)) 1218 return ExprError(); 1219 1220 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1221 bool AllowObjCWritebackConversion 1222 = getLangOpts().ObjCAutoRefCount && 1223 (Action == AA_Passing || Action == AA_Sending); 1224 1225 ICS = clang::TryImplicitConversion(*this, From, ToType, 1226 /*SuppressUserConversions=*/false, 1227 AllowExplicit, 1228 /*InOverloadResolution=*/false, 1229 /*CStyle=*/false, 1230 AllowObjCWritebackConversion); 1231 return PerformImplicitConversion(From, ToType, ICS, Action); 1232 } 1233 1234 /// \brief Determine whether the conversion from FromType to ToType is a valid 1235 /// conversion that strips "noreturn" off the nested function type. 1236 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1237 QualType &ResultTy) { 1238 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1239 return false; 1240 1241 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1242 // where F adds one of the following at most once: 1243 // - a pointer 1244 // - a member pointer 1245 // - a block pointer 1246 CanQualType CanTo = Context.getCanonicalType(ToType); 1247 CanQualType CanFrom = Context.getCanonicalType(FromType); 1248 Type::TypeClass TyClass = CanTo->getTypeClass(); 1249 if (TyClass != CanFrom->getTypeClass()) return false; 1250 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1251 if (TyClass == Type::Pointer) { 1252 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1253 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1254 } else if (TyClass == Type::BlockPointer) { 1255 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1256 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1257 } else if (TyClass == Type::MemberPointer) { 1258 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1259 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1260 } else { 1261 return false; 1262 } 1263 1264 TyClass = CanTo->getTypeClass(); 1265 if (TyClass != CanFrom->getTypeClass()) return false; 1266 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1267 return false; 1268 } 1269 1270 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1271 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1272 if (!EInfo.getNoReturn()) return false; 1273 1274 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1275 assert(QualType(FromFn, 0).isCanonical()); 1276 if (QualType(FromFn, 0) != CanTo) return false; 1277 1278 ResultTy = ToType; 1279 return true; 1280 } 1281 1282 /// \brief Determine whether the conversion from FromType to ToType is a valid 1283 /// vector conversion. 1284 /// 1285 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1286 /// conversion. 1287 static bool IsVectorConversion(ASTContext &Context, QualType FromType, 1288 QualType ToType, ImplicitConversionKind &ICK) { 1289 // We need at least one of these types to be a vector type to have a vector 1290 // conversion. 1291 if (!ToType->isVectorType() && !FromType->isVectorType()) 1292 return false; 1293 1294 // Identical types require no conversions. 1295 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1296 return false; 1297 1298 // There are no conversions between extended vector types, only identity. 1299 if (ToType->isExtVectorType()) { 1300 // There are no conversions between extended vector types other than the 1301 // identity conversion. 1302 if (FromType->isExtVectorType()) 1303 return false; 1304 1305 // Vector splat from any arithmetic type to a vector. 1306 if (FromType->isArithmeticType()) { 1307 ICK = ICK_Vector_Splat; 1308 return true; 1309 } 1310 } 1311 1312 // We can perform the conversion between vector types in the following cases: 1313 // 1)vector types are equivalent AltiVec and GCC vector types 1314 // 2)lax vector conversions are permitted and the vector types are of the 1315 // same size 1316 if (ToType->isVectorType() && FromType->isVectorType()) { 1317 if (Context.areCompatibleVectorTypes(FromType, ToType) || 1318 (Context.getLangOpts().LaxVectorConversions && 1319 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) { 1320 ICK = ICK_Vector_Conversion; 1321 return true; 1322 } 1323 } 1324 1325 return false; 1326 } 1327 1328 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1329 bool InOverloadResolution, 1330 StandardConversionSequence &SCS, 1331 bool CStyle); 1332 1333 /// IsStandardConversion - Determines whether there is a standard 1334 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1335 /// expression From to the type ToType. Standard conversion sequences 1336 /// only consider non-class types; for conversions that involve class 1337 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1338 /// contain the standard conversion sequence required to perform this 1339 /// conversion and this routine will return true. Otherwise, this 1340 /// routine will return false and the value of SCS is unspecified. 1341 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1342 bool InOverloadResolution, 1343 StandardConversionSequence &SCS, 1344 bool CStyle, 1345 bool AllowObjCWritebackConversion) { 1346 QualType FromType = From->getType(); 1347 1348 // Standard conversions (C++ [conv]) 1349 SCS.setAsIdentityConversion(); 1350 SCS.DeprecatedStringLiteralToCharPtr = false; 1351 SCS.IncompatibleObjC = false; 1352 SCS.setFromType(FromType); 1353 SCS.CopyConstructor = 0; 1354 1355 // There are no standard conversions for class types in C++, so 1356 // abort early. When overloading in C, however, we do permit 1357 if (FromType->isRecordType() || ToType->isRecordType()) { 1358 if (S.getLangOpts().CPlusPlus) 1359 return false; 1360 1361 // When we're overloading in C, we allow, as standard conversions, 1362 } 1363 1364 // The first conversion can be an lvalue-to-rvalue conversion, 1365 // array-to-pointer conversion, or function-to-pointer conversion 1366 // (C++ 4p1). 1367 1368 if (FromType == S.Context.OverloadTy) { 1369 DeclAccessPair AccessPair; 1370 if (FunctionDecl *Fn 1371 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1372 AccessPair)) { 1373 // We were able to resolve the address of the overloaded function, 1374 // so we can convert to the type of that function. 1375 FromType = Fn->getType(); 1376 1377 // we can sometimes resolve &foo<int> regardless of ToType, so check 1378 // if the type matches (identity) or we are converting to bool 1379 if (!S.Context.hasSameUnqualifiedType( 1380 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1381 QualType resultTy; 1382 // if the function type matches except for [[noreturn]], it's ok 1383 if (!S.IsNoReturnConversion(FromType, 1384 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1385 // otherwise, only a boolean conversion is standard 1386 if (!ToType->isBooleanType()) 1387 return false; 1388 } 1389 1390 // Check if the "from" expression is taking the address of an overloaded 1391 // function and recompute the FromType accordingly. Take advantage of the 1392 // fact that non-static member functions *must* have such an address-of 1393 // expression. 1394 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1395 if (Method && !Method->isStatic()) { 1396 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1397 "Non-unary operator on non-static member address"); 1398 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1399 == UO_AddrOf && 1400 "Non-address-of operator on non-static member address"); 1401 const Type *ClassType 1402 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1403 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1404 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1405 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1406 UO_AddrOf && 1407 "Non-address-of operator for overloaded function expression"); 1408 FromType = S.Context.getPointerType(FromType); 1409 } 1410 1411 // Check that we've computed the proper type after overload resolution. 1412 assert(S.Context.hasSameType( 1413 FromType, 1414 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1415 } else { 1416 return false; 1417 } 1418 } 1419 // Lvalue-to-rvalue conversion (C++11 4.1): 1420 // A glvalue (3.10) of a non-function, non-array type T can 1421 // be converted to a prvalue. 1422 bool argIsLValue = From->isGLValue(); 1423 if (argIsLValue && 1424 !FromType->isFunctionType() && !FromType->isArrayType() && 1425 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1426 SCS.First = ICK_Lvalue_To_Rvalue; 1427 1428 // C11 6.3.2.1p2: 1429 // ... if the lvalue has atomic type, the value has the non-atomic version 1430 // of the type of the lvalue ... 1431 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1432 FromType = Atomic->getValueType(); 1433 1434 // If T is a non-class type, the type of the rvalue is the 1435 // cv-unqualified version of T. Otherwise, the type of the rvalue 1436 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1437 // just strip the qualifiers because they don't matter. 1438 FromType = FromType.getUnqualifiedType(); 1439 } else if (FromType->isArrayType()) { 1440 // Array-to-pointer conversion (C++ 4.2) 1441 SCS.First = ICK_Array_To_Pointer; 1442 1443 // An lvalue or rvalue of type "array of N T" or "array of unknown 1444 // bound of T" can be converted to an rvalue of type "pointer to 1445 // T" (C++ 4.2p1). 1446 FromType = S.Context.getArrayDecayedType(FromType); 1447 1448 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1449 // This conversion is deprecated. (C++ D.4). 1450 SCS.DeprecatedStringLiteralToCharPtr = true; 1451 1452 // For the purpose of ranking in overload resolution 1453 // (13.3.3.1.1), this conversion is considered an 1454 // array-to-pointer conversion followed by a qualification 1455 // conversion (4.4). (C++ 4.2p2) 1456 SCS.Second = ICK_Identity; 1457 SCS.Third = ICK_Qualification; 1458 SCS.QualificationIncludesObjCLifetime = false; 1459 SCS.setAllToTypes(FromType); 1460 return true; 1461 } 1462 } else if (FromType->isFunctionType() && argIsLValue) { 1463 // Function-to-pointer conversion (C++ 4.3). 1464 SCS.First = ICK_Function_To_Pointer; 1465 1466 // An lvalue of function type T can be converted to an rvalue of 1467 // type "pointer to T." The result is a pointer to the 1468 // function. (C++ 4.3p1). 1469 FromType = S.Context.getPointerType(FromType); 1470 } else { 1471 // We don't require any conversions for the first step. 1472 SCS.First = ICK_Identity; 1473 } 1474 SCS.setToType(0, FromType); 1475 1476 // The second conversion can be an integral promotion, floating 1477 // point promotion, integral conversion, floating point conversion, 1478 // floating-integral conversion, pointer conversion, 1479 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1480 // For overloading in C, this can also be a "compatible-type" 1481 // conversion. 1482 bool IncompatibleObjC = false; 1483 ImplicitConversionKind SecondICK = ICK_Identity; 1484 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1485 // The unqualified versions of the types are the same: there's no 1486 // conversion to do. 1487 SCS.Second = ICK_Identity; 1488 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1489 // Integral promotion (C++ 4.5). 1490 SCS.Second = ICK_Integral_Promotion; 1491 FromType = ToType.getUnqualifiedType(); 1492 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1493 // Floating point promotion (C++ 4.6). 1494 SCS.Second = ICK_Floating_Promotion; 1495 FromType = ToType.getUnqualifiedType(); 1496 } else if (S.IsComplexPromotion(FromType, ToType)) { 1497 // Complex promotion (Clang extension) 1498 SCS.Second = ICK_Complex_Promotion; 1499 FromType = ToType.getUnqualifiedType(); 1500 } else if (ToType->isBooleanType() && 1501 (FromType->isArithmeticType() || 1502 FromType->isAnyPointerType() || 1503 FromType->isBlockPointerType() || 1504 FromType->isMemberPointerType() || 1505 FromType->isNullPtrType())) { 1506 // Boolean conversions (C++ 4.12). 1507 SCS.Second = ICK_Boolean_Conversion; 1508 FromType = S.Context.BoolTy; 1509 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1510 ToType->isIntegralType(S.Context)) { 1511 // Integral conversions (C++ 4.7). 1512 SCS.Second = ICK_Integral_Conversion; 1513 FromType = ToType.getUnqualifiedType(); 1514 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) { 1515 // Complex conversions (C99 6.3.1.6) 1516 SCS.Second = ICK_Complex_Conversion; 1517 FromType = ToType.getUnqualifiedType(); 1518 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1519 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1520 // Complex-real conversions (C99 6.3.1.7) 1521 SCS.Second = ICK_Complex_Real; 1522 FromType = ToType.getUnqualifiedType(); 1523 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1524 // Floating point conversions (C++ 4.8). 1525 SCS.Second = ICK_Floating_Conversion; 1526 FromType = ToType.getUnqualifiedType(); 1527 } else if ((FromType->isRealFloatingType() && 1528 ToType->isIntegralType(S.Context)) || 1529 (FromType->isIntegralOrUnscopedEnumerationType() && 1530 ToType->isRealFloatingType())) { 1531 // Floating-integral conversions (C++ 4.9). 1532 SCS.Second = ICK_Floating_Integral; 1533 FromType = ToType.getUnqualifiedType(); 1534 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1535 SCS.Second = ICK_Block_Pointer_Conversion; 1536 } else if (AllowObjCWritebackConversion && 1537 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1538 SCS.Second = ICK_Writeback_Conversion; 1539 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1540 FromType, IncompatibleObjC)) { 1541 // Pointer conversions (C++ 4.10). 1542 SCS.Second = ICK_Pointer_Conversion; 1543 SCS.IncompatibleObjC = IncompatibleObjC; 1544 FromType = FromType.getUnqualifiedType(); 1545 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1546 InOverloadResolution, FromType)) { 1547 // Pointer to member conversions (4.11). 1548 SCS.Second = ICK_Pointer_Member; 1549 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) { 1550 SCS.Second = SecondICK; 1551 FromType = ToType.getUnqualifiedType(); 1552 } else if (!S.getLangOpts().CPlusPlus && 1553 S.Context.typesAreCompatible(ToType, FromType)) { 1554 // Compatible conversions (Clang extension for C function overloading) 1555 SCS.Second = ICK_Compatible_Conversion; 1556 FromType = ToType.getUnqualifiedType(); 1557 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1558 // Treat a conversion that strips "noreturn" as an identity conversion. 1559 SCS.Second = ICK_NoReturn_Adjustment; 1560 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1561 InOverloadResolution, 1562 SCS, CStyle)) { 1563 SCS.Second = ICK_TransparentUnionConversion; 1564 FromType = ToType; 1565 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1566 CStyle)) { 1567 // tryAtomicConversion has updated the standard conversion sequence 1568 // appropriately. 1569 return true; 1570 } else { 1571 // No second conversion required. 1572 SCS.Second = ICK_Identity; 1573 } 1574 SCS.setToType(1, FromType); 1575 1576 QualType CanonFrom; 1577 QualType CanonTo; 1578 // The third conversion can be a qualification conversion (C++ 4p1). 1579 bool ObjCLifetimeConversion; 1580 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1581 ObjCLifetimeConversion)) { 1582 SCS.Third = ICK_Qualification; 1583 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1584 FromType = ToType; 1585 CanonFrom = S.Context.getCanonicalType(FromType); 1586 CanonTo = S.Context.getCanonicalType(ToType); 1587 } else { 1588 // No conversion required 1589 SCS.Third = ICK_Identity; 1590 1591 // C++ [over.best.ics]p6: 1592 // [...] Any difference in top-level cv-qualification is 1593 // subsumed by the initialization itself and does not constitute 1594 // a conversion. [...] 1595 CanonFrom = S.Context.getCanonicalType(FromType); 1596 CanonTo = S.Context.getCanonicalType(ToType); 1597 if (CanonFrom.getLocalUnqualifiedType() 1598 == CanonTo.getLocalUnqualifiedType() && 1599 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers() 1600 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr() 1601 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) { 1602 FromType = ToType; 1603 CanonFrom = CanonTo; 1604 } 1605 } 1606 SCS.setToType(2, FromType); 1607 1608 // If we have not converted the argument type to the parameter type, 1609 // this is a bad conversion sequence. 1610 if (CanonFrom != CanonTo) 1611 return false; 1612 1613 return true; 1614 } 1615 1616 static bool 1617 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1618 QualType &ToType, 1619 bool InOverloadResolution, 1620 StandardConversionSequence &SCS, 1621 bool CStyle) { 1622 1623 const RecordType *UT = ToType->getAsUnionType(); 1624 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1625 return false; 1626 // The field to initialize within the transparent union. 1627 RecordDecl *UD = UT->getDecl(); 1628 // It's compatible if the expression matches any of the fields. 1629 for (RecordDecl::field_iterator it = UD->field_begin(), 1630 itend = UD->field_end(); 1631 it != itend; ++it) { 1632 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1633 CStyle, /*ObjCWritebackConversion=*/false)) { 1634 ToType = it->getType(); 1635 return true; 1636 } 1637 } 1638 return false; 1639 } 1640 1641 /// IsIntegralPromotion - Determines whether the conversion from the 1642 /// expression From (whose potentially-adjusted type is FromType) to 1643 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1644 /// sets PromotedType to the promoted type. 1645 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1646 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1647 // All integers are built-in. 1648 if (!To) { 1649 return false; 1650 } 1651 1652 // An rvalue of type char, signed char, unsigned char, short int, or 1653 // unsigned short int can be converted to an rvalue of type int if 1654 // int can represent all the values of the source type; otherwise, 1655 // the source rvalue can be converted to an rvalue of type unsigned 1656 // int (C++ 4.5p1). 1657 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1658 !FromType->isEnumeralType()) { 1659 if (// We can promote any signed, promotable integer type to an int 1660 (FromType->isSignedIntegerType() || 1661 // We can promote any unsigned integer type whose size is 1662 // less than int to an int. 1663 (!FromType->isSignedIntegerType() && 1664 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1665 return To->getKind() == BuiltinType::Int; 1666 } 1667 1668 return To->getKind() == BuiltinType::UInt; 1669 } 1670 1671 // C++0x [conv.prom]p3: 1672 // A prvalue of an unscoped enumeration type whose underlying type is not 1673 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1674 // following types that can represent all the values of the enumeration 1675 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1676 // unsigned int, long int, unsigned long int, long long int, or unsigned 1677 // long long int. If none of the types in that list can represent all the 1678 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1679 // type can be converted to an rvalue a prvalue of the extended integer type 1680 // with lowest integer conversion rank (4.13) greater than the rank of long 1681 // long in which all the values of the enumeration can be represented. If 1682 // there are two such extended types, the signed one is chosen. 1683 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1684 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1685 // provided for a scoped enumeration. 1686 if (FromEnumType->getDecl()->isScoped()) 1687 return false; 1688 1689 // We have already pre-calculated the promotion type, so this is trivial. 1690 if (ToType->isIntegerType() && 1691 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1692 return Context.hasSameUnqualifiedType(ToType, 1693 FromEnumType->getDecl()->getPromotionType()); 1694 } 1695 1696 // C++0x [conv.prom]p2: 1697 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1698 // to an rvalue a prvalue of the first of the following types that can 1699 // represent all the values of its underlying type: int, unsigned int, 1700 // long int, unsigned long int, long long int, or unsigned long long int. 1701 // If none of the types in that list can represent all the values of its 1702 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1703 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1704 // type. 1705 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1706 ToType->isIntegerType()) { 1707 // Determine whether the type we're converting from is signed or 1708 // unsigned. 1709 bool FromIsSigned = FromType->isSignedIntegerType(); 1710 uint64_t FromSize = Context.getTypeSize(FromType); 1711 1712 // The types we'll try to promote to, in the appropriate 1713 // order. Try each of these types. 1714 QualType PromoteTypes[6] = { 1715 Context.IntTy, Context.UnsignedIntTy, 1716 Context.LongTy, Context.UnsignedLongTy , 1717 Context.LongLongTy, Context.UnsignedLongLongTy 1718 }; 1719 for (int Idx = 0; Idx < 6; ++Idx) { 1720 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1721 if (FromSize < ToSize || 1722 (FromSize == ToSize && 1723 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1724 // We found the type that we can promote to. If this is the 1725 // type we wanted, we have a promotion. Otherwise, no 1726 // promotion. 1727 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1728 } 1729 } 1730 } 1731 1732 // An rvalue for an integral bit-field (9.6) can be converted to an 1733 // rvalue of type int if int can represent all the values of the 1734 // bit-field; otherwise, it can be converted to unsigned int if 1735 // unsigned int can represent all the values of the bit-field. If 1736 // the bit-field is larger yet, no integral promotion applies to 1737 // it. If the bit-field has an enumerated type, it is treated as any 1738 // other value of that type for promotion purposes (C++ 4.5p3). 1739 // FIXME: We should delay checking of bit-fields until we actually perform the 1740 // conversion. 1741 using llvm::APSInt; 1742 if (From) 1743 if (FieldDecl *MemberDecl = From->getBitField()) { 1744 APSInt BitWidth; 1745 if (FromType->isIntegralType(Context) && 1746 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1747 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1748 ToSize = Context.getTypeSize(ToType); 1749 1750 // Are we promoting to an int from a bitfield that fits in an int? 1751 if (BitWidth < ToSize || 1752 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1753 return To->getKind() == BuiltinType::Int; 1754 } 1755 1756 // Are we promoting to an unsigned int from an unsigned bitfield 1757 // that fits into an unsigned int? 1758 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1759 return To->getKind() == BuiltinType::UInt; 1760 } 1761 1762 return false; 1763 } 1764 } 1765 1766 // An rvalue of type bool can be converted to an rvalue of type int, 1767 // with false becoming zero and true becoming one (C++ 4.5p4). 1768 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1769 return true; 1770 } 1771 1772 return false; 1773 } 1774 1775 /// IsFloatingPointPromotion - Determines whether the conversion from 1776 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1777 /// returns true and sets PromotedType to the promoted type. 1778 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1779 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1780 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1781 /// An rvalue of type float can be converted to an rvalue of type 1782 /// double. (C++ 4.6p1). 1783 if (FromBuiltin->getKind() == BuiltinType::Float && 1784 ToBuiltin->getKind() == BuiltinType::Double) 1785 return true; 1786 1787 // C99 6.3.1.5p1: 1788 // When a float is promoted to double or long double, or a 1789 // double is promoted to long double [...]. 1790 if (!getLangOpts().CPlusPlus && 1791 (FromBuiltin->getKind() == BuiltinType::Float || 1792 FromBuiltin->getKind() == BuiltinType::Double) && 1793 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1794 return true; 1795 1796 // Half can be promoted to float. 1797 if (FromBuiltin->getKind() == BuiltinType::Half && 1798 ToBuiltin->getKind() == BuiltinType::Float) 1799 return true; 1800 } 1801 1802 return false; 1803 } 1804 1805 /// \brief Determine if a conversion is a complex promotion. 1806 /// 1807 /// A complex promotion is defined as a complex -> complex conversion 1808 /// where the conversion between the underlying real types is a 1809 /// floating-point or integral promotion. 1810 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1811 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1812 if (!FromComplex) 1813 return false; 1814 1815 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1816 if (!ToComplex) 1817 return false; 1818 1819 return IsFloatingPointPromotion(FromComplex->getElementType(), 1820 ToComplex->getElementType()) || 1821 IsIntegralPromotion(0, FromComplex->getElementType(), 1822 ToComplex->getElementType()); 1823 } 1824 1825 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1826 /// the pointer type FromPtr to a pointer to type ToPointee, with the 1827 /// same type qualifiers as FromPtr has on its pointee type. ToType, 1828 /// if non-empty, will be a pointer to ToType that may or may not have 1829 /// the right set of qualifiers on its pointee. 1830 /// 1831 static QualType 1832 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1833 QualType ToPointee, QualType ToType, 1834 ASTContext &Context, 1835 bool StripObjCLifetime = false) { 1836 assert((FromPtr->getTypeClass() == Type::Pointer || 1837 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1838 "Invalid similarly-qualified pointer type"); 1839 1840 /// Conversions to 'id' subsume cv-qualifier conversions. 1841 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1842 return ToType.getUnqualifiedType(); 1843 1844 QualType CanonFromPointee 1845 = Context.getCanonicalType(FromPtr->getPointeeType()); 1846 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1847 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1848 1849 if (StripObjCLifetime) 1850 Quals.removeObjCLifetime(); 1851 1852 // Exact qualifier match -> return the pointer type we're converting to. 1853 if (CanonToPointee.getLocalQualifiers() == Quals) { 1854 // ToType is exactly what we need. Return it. 1855 if (!ToType.isNull()) 1856 return ToType.getUnqualifiedType(); 1857 1858 // Build a pointer to ToPointee. It has the right qualifiers 1859 // already. 1860 if (isa<ObjCObjectPointerType>(ToType)) 1861 return Context.getObjCObjectPointerType(ToPointee); 1862 return Context.getPointerType(ToPointee); 1863 } 1864 1865 // Just build a canonical type that has the right qualifiers. 1866 QualType QualifiedCanonToPointee 1867 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1868 1869 if (isa<ObjCObjectPointerType>(ToType)) 1870 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1871 return Context.getPointerType(QualifiedCanonToPointee); 1872 } 1873 1874 static bool isNullPointerConstantForConversion(Expr *Expr, 1875 bool InOverloadResolution, 1876 ASTContext &Context) { 1877 // Handle value-dependent integral null pointer constants correctly. 1878 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1879 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1880 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1881 return !InOverloadResolution; 1882 1883 return Expr->isNullPointerConstant(Context, 1884 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1885 : Expr::NPC_ValueDependentIsNull); 1886 } 1887 1888 /// IsPointerConversion - Determines whether the conversion of the 1889 /// expression From, which has the (possibly adjusted) type FromType, 1890 /// can be converted to the type ToType via a pointer conversion (C++ 1891 /// 4.10). If so, returns true and places the converted type (that 1892 /// might differ from ToType in its cv-qualifiers at some level) into 1893 /// ConvertedType. 1894 /// 1895 /// This routine also supports conversions to and from block pointers 1896 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 1897 /// pointers to interfaces. FIXME: Once we've determined the 1898 /// appropriate overloading rules for Objective-C, we may want to 1899 /// split the Objective-C checks into a different routine; however, 1900 /// GCC seems to consider all of these conversions to be pointer 1901 /// conversions, so for now they live here. IncompatibleObjC will be 1902 /// set if the conversion is an allowed Objective-C conversion that 1903 /// should result in a warning. 1904 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1905 bool InOverloadResolution, 1906 QualType& ConvertedType, 1907 bool &IncompatibleObjC) { 1908 IncompatibleObjC = false; 1909 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 1910 IncompatibleObjC)) 1911 return true; 1912 1913 // Conversion from a null pointer constant to any Objective-C pointer type. 1914 if (ToType->isObjCObjectPointerType() && 1915 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1916 ConvertedType = ToType; 1917 return true; 1918 } 1919 1920 // Blocks: Block pointers can be converted to void*. 1921 if (FromType->isBlockPointerType() && ToType->isPointerType() && 1922 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 1923 ConvertedType = ToType; 1924 return true; 1925 } 1926 // Blocks: A null pointer constant can be converted to a block 1927 // pointer type. 1928 if (ToType->isBlockPointerType() && 1929 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1930 ConvertedType = ToType; 1931 return true; 1932 } 1933 1934 // If the left-hand-side is nullptr_t, the right side can be a null 1935 // pointer constant. 1936 if (ToType->isNullPtrType() && 1937 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1938 ConvertedType = ToType; 1939 return true; 1940 } 1941 1942 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 1943 if (!ToTypePtr) 1944 return false; 1945 1946 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 1947 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1948 ConvertedType = ToType; 1949 return true; 1950 } 1951 1952 // Beyond this point, both types need to be pointers 1953 // , including objective-c pointers. 1954 QualType ToPointeeType = ToTypePtr->getPointeeType(); 1955 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 1956 !getLangOpts().ObjCAutoRefCount) { 1957 ConvertedType = BuildSimilarlyQualifiedPointerType( 1958 FromType->getAs<ObjCObjectPointerType>(), 1959 ToPointeeType, 1960 ToType, Context); 1961 return true; 1962 } 1963 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 1964 if (!FromTypePtr) 1965 return false; 1966 1967 QualType FromPointeeType = FromTypePtr->getPointeeType(); 1968 1969 // If the unqualified pointee types are the same, this can't be a 1970 // pointer conversion, so don't do all of the work below. 1971 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 1972 return false; 1973 1974 // An rvalue of type "pointer to cv T," where T is an object type, 1975 // can be converted to an rvalue of type "pointer to cv void" (C++ 1976 // 4.10p2). 1977 if (FromPointeeType->isIncompleteOrObjectType() && 1978 ToPointeeType->isVoidType()) { 1979 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1980 ToPointeeType, 1981 ToType, Context, 1982 /*StripObjCLifetime=*/true); 1983 return true; 1984 } 1985 1986 // MSVC allows implicit function to void* type conversion. 1987 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 1988 ToPointeeType->isVoidType()) { 1989 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1990 ToPointeeType, 1991 ToType, Context); 1992 return true; 1993 } 1994 1995 // When we're overloading in C, we allow a special kind of pointer 1996 // conversion for compatible-but-not-identical pointee types. 1997 if (!getLangOpts().CPlusPlus && 1998 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 1999 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2000 ToPointeeType, 2001 ToType, Context); 2002 return true; 2003 } 2004 2005 // C++ [conv.ptr]p3: 2006 // 2007 // An rvalue of type "pointer to cv D," where D is a class type, 2008 // can be converted to an rvalue of type "pointer to cv B," where 2009 // B is a base class (clause 10) of D. If B is an inaccessible 2010 // (clause 11) or ambiguous (10.2) base class of D, a program that 2011 // necessitates this conversion is ill-formed. The result of the 2012 // conversion is a pointer to the base class sub-object of the 2013 // derived class object. The null pointer value is converted to 2014 // the null pointer value of the destination type. 2015 // 2016 // Note that we do not check for ambiguity or inaccessibility 2017 // here. That is handled by CheckPointerConversion. 2018 if (getLangOpts().CPlusPlus && 2019 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2020 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2021 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2022 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2023 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2024 ToPointeeType, 2025 ToType, Context); 2026 return true; 2027 } 2028 2029 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2030 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2031 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2032 ToPointeeType, 2033 ToType, Context); 2034 return true; 2035 } 2036 2037 return false; 2038 } 2039 2040 /// \brief Adopt the given qualifiers for the given type. 2041 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2042 Qualifiers TQs = T.getQualifiers(); 2043 2044 // Check whether qualifiers already match. 2045 if (TQs == Qs) 2046 return T; 2047 2048 if (Qs.compatiblyIncludes(TQs)) 2049 return Context.getQualifiedType(T, Qs); 2050 2051 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2052 } 2053 2054 /// isObjCPointerConversion - Determines whether this is an 2055 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2056 /// with the same arguments and return values. 2057 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2058 QualType& ConvertedType, 2059 bool &IncompatibleObjC) { 2060 if (!getLangOpts().ObjC1) 2061 return false; 2062 2063 // The set of qualifiers on the type we're converting from. 2064 Qualifiers FromQualifiers = FromType.getQualifiers(); 2065 2066 // First, we handle all conversions on ObjC object pointer types. 2067 const ObjCObjectPointerType* ToObjCPtr = 2068 ToType->getAs<ObjCObjectPointerType>(); 2069 const ObjCObjectPointerType *FromObjCPtr = 2070 FromType->getAs<ObjCObjectPointerType>(); 2071 2072 if (ToObjCPtr && FromObjCPtr) { 2073 // If the pointee types are the same (ignoring qualifications), 2074 // then this is not a pointer conversion. 2075 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2076 FromObjCPtr->getPointeeType())) 2077 return false; 2078 2079 // Check for compatible 2080 // Objective C++: We're able to convert between "id" or "Class" and a 2081 // pointer to any interface (in both directions). 2082 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2083 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2084 return true; 2085 } 2086 // Conversions with Objective-C's id<...>. 2087 if ((FromObjCPtr->isObjCQualifiedIdType() || 2088 ToObjCPtr->isObjCQualifiedIdType()) && 2089 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2090 /*compare=*/false)) { 2091 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2092 return true; 2093 } 2094 // Objective C++: We're able to convert from a pointer to an 2095 // interface to a pointer to a different interface. 2096 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2097 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2098 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2099 if (getLangOpts().CPlusPlus && LHS && RHS && 2100 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2101 FromObjCPtr->getPointeeType())) 2102 return false; 2103 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2104 ToObjCPtr->getPointeeType(), 2105 ToType, Context); 2106 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2107 return true; 2108 } 2109 2110 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2111 // Okay: this is some kind of implicit downcast of Objective-C 2112 // interfaces, which is permitted. However, we're going to 2113 // complain about it. 2114 IncompatibleObjC = true; 2115 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2116 ToObjCPtr->getPointeeType(), 2117 ToType, Context); 2118 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2119 return true; 2120 } 2121 } 2122 // Beyond this point, both types need to be C pointers or block pointers. 2123 QualType ToPointeeType; 2124 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2125 ToPointeeType = ToCPtr->getPointeeType(); 2126 else if (const BlockPointerType *ToBlockPtr = 2127 ToType->getAs<BlockPointerType>()) { 2128 // Objective C++: We're able to convert from a pointer to any object 2129 // to a block pointer type. 2130 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2131 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2132 return true; 2133 } 2134 ToPointeeType = ToBlockPtr->getPointeeType(); 2135 } 2136 else if (FromType->getAs<BlockPointerType>() && 2137 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2138 // Objective C++: We're able to convert from a block pointer type to a 2139 // pointer to any object. 2140 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2141 return true; 2142 } 2143 else 2144 return false; 2145 2146 QualType FromPointeeType; 2147 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2148 FromPointeeType = FromCPtr->getPointeeType(); 2149 else if (const BlockPointerType *FromBlockPtr = 2150 FromType->getAs<BlockPointerType>()) 2151 FromPointeeType = FromBlockPtr->getPointeeType(); 2152 else 2153 return false; 2154 2155 // If we have pointers to pointers, recursively check whether this 2156 // is an Objective-C conversion. 2157 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2158 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2159 IncompatibleObjC)) { 2160 // We always complain about this conversion. 2161 IncompatibleObjC = true; 2162 ConvertedType = Context.getPointerType(ConvertedType); 2163 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2164 return true; 2165 } 2166 // Allow conversion of pointee being objective-c pointer to another one; 2167 // as in I* to id. 2168 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2169 ToPointeeType->getAs<ObjCObjectPointerType>() && 2170 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2171 IncompatibleObjC)) { 2172 2173 ConvertedType = Context.getPointerType(ConvertedType); 2174 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2175 return true; 2176 } 2177 2178 // If we have pointers to functions or blocks, check whether the only 2179 // differences in the argument and result types are in Objective-C 2180 // pointer conversions. If so, we permit the conversion (but 2181 // complain about it). 2182 const FunctionProtoType *FromFunctionType 2183 = FromPointeeType->getAs<FunctionProtoType>(); 2184 const FunctionProtoType *ToFunctionType 2185 = ToPointeeType->getAs<FunctionProtoType>(); 2186 if (FromFunctionType && ToFunctionType) { 2187 // If the function types are exactly the same, this isn't an 2188 // Objective-C pointer conversion. 2189 if (Context.getCanonicalType(FromPointeeType) 2190 == Context.getCanonicalType(ToPointeeType)) 2191 return false; 2192 2193 // Perform the quick checks that will tell us whether these 2194 // function types are obviously different. 2195 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2196 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2197 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2198 return false; 2199 2200 bool HasObjCConversion = false; 2201 if (Context.getCanonicalType(FromFunctionType->getResultType()) 2202 == Context.getCanonicalType(ToFunctionType->getResultType())) { 2203 // Okay, the types match exactly. Nothing to do. 2204 } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 2205 ToFunctionType->getResultType(), 2206 ConvertedType, IncompatibleObjC)) { 2207 // Okay, we have an Objective-C pointer conversion. 2208 HasObjCConversion = true; 2209 } else { 2210 // Function types are too different. Abort. 2211 return false; 2212 } 2213 2214 // Check argument types. 2215 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2216 ArgIdx != NumArgs; ++ArgIdx) { 2217 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2218 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2219 if (Context.getCanonicalType(FromArgType) 2220 == Context.getCanonicalType(ToArgType)) { 2221 // Okay, the types match exactly. Nothing to do. 2222 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2223 ConvertedType, IncompatibleObjC)) { 2224 // Okay, we have an Objective-C pointer conversion. 2225 HasObjCConversion = true; 2226 } else { 2227 // Argument types are too different. Abort. 2228 return false; 2229 } 2230 } 2231 2232 if (HasObjCConversion) { 2233 // We had an Objective-C conversion. Allow this pointer 2234 // conversion, but complain about it. 2235 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2236 IncompatibleObjC = true; 2237 return true; 2238 } 2239 } 2240 2241 return false; 2242 } 2243 2244 /// \brief Determine whether this is an Objective-C writeback conversion, 2245 /// used for parameter passing when performing automatic reference counting. 2246 /// 2247 /// \param FromType The type we're converting form. 2248 /// 2249 /// \param ToType The type we're converting to. 2250 /// 2251 /// \param ConvertedType The type that will be produced after applying 2252 /// this conversion. 2253 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2254 QualType &ConvertedType) { 2255 if (!getLangOpts().ObjCAutoRefCount || 2256 Context.hasSameUnqualifiedType(FromType, ToType)) 2257 return false; 2258 2259 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2260 QualType ToPointee; 2261 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2262 ToPointee = ToPointer->getPointeeType(); 2263 else 2264 return false; 2265 2266 Qualifiers ToQuals = ToPointee.getQualifiers(); 2267 if (!ToPointee->isObjCLifetimeType() || 2268 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2269 !ToQuals.withoutObjCLifetime().empty()) 2270 return false; 2271 2272 // Argument must be a pointer to __strong to __weak. 2273 QualType FromPointee; 2274 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2275 FromPointee = FromPointer->getPointeeType(); 2276 else 2277 return false; 2278 2279 Qualifiers FromQuals = FromPointee.getQualifiers(); 2280 if (!FromPointee->isObjCLifetimeType() || 2281 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2282 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2283 return false; 2284 2285 // Make sure that we have compatible qualifiers. 2286 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2287 if (!ToQuals.compatiblyIncludes(FromQuals)) 2288 return false; 2289 2290 // Remove qualifiers from the pointee type we're converting from; they 2291 // aren't used in the compatibility check belong, and we'll be adding back 2292 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2293 FromPointee = FromPointee.getUnqualifiedType(); 2294 2295 // The unqualified form of the pointee types must be compatible. 2296 ToPointee = ToPointee.getUnqualifiedType(); 2297 bool IncompatibleObjC; 2298 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2299 FromPointee = ToPointee; 2300 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2301 IncompatibleObjC)) 2302 return false; 2303 2304 /// \brief Construct the type we're converting to, which is a pointer to 2305 /// __autoreleasing pointee. 2306 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2307 ConvertedType = Context.getPointerType(FromPointee); 2308 return true; 2309 } 2310 2311 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2312 QualType& ConvertedType) { 2313 QualType ToPointeeType; 2314 if (const BlockPointerType *ToBlockPtr = 2315 ToType->getAs<BlockPointerType>()) 2316 ToPointeeType = ToBlockPtr->getPointeeType(); 2317 else 2318 return false; 2319 2320 QualType FromPointeeType; 2321 if (const BlockPointerType *FromBlockPtr = 2322 FromType->getAs<BlockPointerType>()) 2323 FromPointeeType = FromBlockPtr->getPointeeType(); 2324 else 2325 return false; 2326 // We have pointer to blocks, check whether the only 2327 // differences in the argument and result types are in Objective-C 2328 // pointer conversions. If so, we permit the conversion. 2329 2330 const FunctionProtoType *FromFunctionType 2331 = FromPointeeType->getAs<FunctionProtoType>(); 2332 const FunctionProtoType *ToFunctionType 2333 = ToPointeeType->getAs<FunctionProtoType>(); 2334 2335 if (!FromFunctionType || !ToFunctionType) 2336 return false; 2337 2338 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2339 return true; 2340 2341 // Perform the quick checks that will tell us whether these 2342 // function types are obviously different. 2343 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2344 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2345 return false; 2346 2347 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2348 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2349 if (FromEInfo != ToEInfo) 2350 return false; 2351 2352 bool IncompatibleObjC = false; 2353 if (Context.hasSameType(FromFunctionType->getResultType(), 2354 ToFunctionType->getResultType())) { 2355 // Okay, the types match exactly. Nothing to do. 2356 } else { 2357 QualType RHS = FromFunctionType->getResultType(); 2358 QualType LHS = ToFunctionType->getResultType(); 2359 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2360 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2361 LHS = LHS.getUnqualifiedType(); 2362 2363 if (Context.hasSameType(RHS,LHS)) { 2364 // OK exact match. 2365 } else if (isObjCPointerConversion(RHS, LHS, 2366 ConvertedType, IncompatibleObjC)) { 2367 if (IncompatibleObjC) 2368 return false; 2369 // Okay, we have an Objective-C pointer conversion. 2370 } 2371 else 2372 return false; 2373 } 2374 2375 // Check argument types. 2376 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2377 ArgIdx != NumArgs; ++ArgIdx) { 2378 IncompatibleObjC = false; 2379 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2380 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2381 if (Context.hasSameType(FromArgType, ToArgType)) { 2382 // Okay, the types match exactly. Nothing to do. 2383 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2384 ConvertedType, IncompatibleObjC)) { 2385 if (IncompatibleObjC) 2386 return false; 2387 // Okay, we have an Objective-C pointer conversion. 2388 } else 2389 // Argument types are too different. Abort. 2390 return false; 2391 } 2392 if (LangOpts.ObjCAutoRefCount && 2393 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2394 ToFunctionType)) 2395 return false; 2396 2397 ConvertedType = ToType; 2398 return true; 2399 } 2400 2401 enum { 2402 ft_default, 2403 ft_different_class, 2404 ft_parameter_arity, 2405 ft_parameter_mismatch, 2406 ft_return_type, 2407 ft_qualifer_mismatch 2408 }; 2409 2410 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2411 /// function types. Catches different number of parameter, mismatch in 2412 /// parameter types, and different return types. 2413 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2414 QualType FromType, QualType ToType) { 2415 // If either type is not valid, include no extra info. 2416 if (FromType.isNull() || ToType.isNull()) { 2417 PDiag << ft_default; 2418 return; 2419 } 2420 2421 // Get the function type from the pointers. 2422 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2423 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2424 *ToMember = ToType->getAs<MemberPointerType>(); 2425 if (FromMember->getClass() != ToMember->getClass()) { 2426 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2427 << QualType(FromMember->getClass(), 0); 2428 return; 2429 } 2430 FromType = FromMember->getPointeeType(); 2431 ToType = ToMember->getPointeeType(); 2432 } 2433 2434 if (FromType->isPointerType()) 2435 FromType = FromType->getPointeeType(); 2436 if (ToType->isPointerType()) 2437 ToType = ToType->getPointeeType(); 2438 2439 // Remove references. 2440 FromType = FromType.getNonReferenceType(); 2441 ToType = ToType.getNonReferenceType(); 2442 2443 // Don't print extra info for non-specialized template functions. 2444 if (FromType->isInstantiationDependentType() && 2445 !FromType->getAs<TemplateSpecializationType>()) { 2446 PDiag << ft_default; 2447 return; 2448 } 2449 2450 // No extra info for same types. 2451 if (Context.hasSameType(FromType, ToType)) { 2452 PDiag << ft_default; 2453 return; 2454 } 2455 2456 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2457 *ToFunction = ToType->getAs<FunctionProtoType>(); 2458 2459 // Both types need to be function types. 2460 if (!FromFunction || !ToFunction) { 2461 PDiag << ft_default; 2462 return; 2463 } 2464 2465 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) { 2466 PDiag << ft_parameter_arity << ToFunction->getNumArgs() 2467 << FromFunction->getNumArgs(); 2468 return; 2469 } 2470 2471 // Handle different parameter types. 2472 unsigned ArgPos; 2473 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2474 PDiag << ft_parameter_mismatch << ArgPos + 1 2475 << ToFunction->getArgType(ArgPos) 2476 << FromFunction->getArgType(ArgPos); 2477 return; 2478 } 2479 2480 // Handle different return type. 2481 if (!Context.hasSameType(FromFunction->getResultType(), 2482 ToFunction->getResultType())) { 2483 PDiag << ft_return_type << ToFunction->getResultType() 2484 << FromFunction->getResultType(); 2485 return; 2486 } 2487 2488 unsigned FromQuals = FromFunction->getTypeQuals(), 2489 ToQuals = ToFunction->getTypeQuals(); 2490 if (FromQuals != ToQuals) { 2491 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2492 return; 2493 } 2494 2495 // Unable to find a difference, so add no extra info. 2496 PDiag << ft_default; 2497 } 2498 2499 /// FunctionArgTypesAreEqual - This routine checks two function proto types 2500 /// for equality of their argument types. Caller has already checked that 2501 /// they have same number of arguments. This routine assumes that Objective-C 2502 /// pointer types which only differ in their protocol qualifiers are equal. 2503 /// If the parameters are different, ArgPos will have the parameter index 2504 /// of the first different parameter. 2505 bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 2506 const FunctionProtoType *NewType, 2507 unsigned *ArgPos) { 2508 if (!getLangOpts().ObjC1) { 2509 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2510 N = NewType->arg_type_begin(), 2511 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2512 if (!Context.hasSameType(*O, *N)) { 2513 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2514 return false; 2515 } 2516 } 2517 return true; 2518 } 2519 2520 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2521 N = NewType->arg_type_begin(), 2522 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2523 QualType ToType = (*O); 2524 QualType FromType = (*N); 2525 if (!Context.hasSameType(ToType, FromType)) { 2526 if (const PointerType *PTTo = ToType->getAs<PointerType>()) { 2527 if (const PointerType *PTFr = FromType->getAs<PointerType>()) 2528 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() && 2529 PTFr->getPointeeType()->isObjCQualifiedIdType()) || 2530 (PTTo->getPointeeType()->isObjCQualifiedClassType() && 2531 PTFr->getPointeeType()->isObjCQualifiedClassType())) 2532 continue; 2533 } 2534 else if (const ObjCObjectPointerType *PTTo = 2535 ToType->getAs<ObjCObjectPointerType>()) { 2536 if (const ObjCObjectPointerType *PTFr = 2537 FromType->getAs<ObjCObjectPointerType>()) 2538 if (Context.hasSameUnqualifiedType( 2539 PTTo->getObjectType()->getBaseType(), 2540 PTFr->getObjectType()->getBaseType())) 2541 continue; 2542 } 2543 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2544 return false; 2545 } 2546 } 2547 return true; 2548 } 2549 2550 /// CheckPointerConversion - Check the pointer conversion from the 2551 /// expression From to the type ToType. This routine checks for 2552 /// ambiguous or inaccessible derived-to-base pointer 2553 /// conversions for which IsPointerConversion has already returned 2554 /// true. It returns true and produces a diagnostic if there was an 2555 /// error, or returns false otherwise. 2556 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2557 CastKind &Kind, 2558 CXXCastPath& BasePath, 2559 bool IgnoreBaseAccess) { 2560 QualType FromType = From->getType(); 2561 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2562 2563 Kind = CK_BitCast; 2564 2565 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2566 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2567 Expr::NPCK_ZeroExpression) { 2568 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2569 DiagRuntimeBehavior(From->getExprLoc(), From, 2570 PDiag(diag::warn_impcast_bool_to_null_pointer) 2571 << ToType << From->getSourceRange()); 2572 else if (!isUnevaluatedContext()) 2573 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2574 << ToType << From->getSourceRange(); 2575 } 2576 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2577 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2578 QualType FromPointeeType = FromPtrType->getPointeeType(), 2579 ToPointeeType = ToPtrType->getPointeeType(); 2580 2581 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2582 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2583 // We must have a derived-to-base conversion. Check an 2584 // ambiguous or inaccessible conversion. 2585 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2586 From->getExprLoc(), 2587 From->getSourceRange(), &BasePath, 2588 IgnoreBaseAccess)) 2589 return true; 2590 2591 // The conversion was successful. 2592 Kind = CK_DerivedToBase; 2593 } 2594 } 2595 } else if (const ObjCObjectPointerType *ToPtrType = 2596 ToType->getAs<ObjCObjectPointerType>()) { 2597 if (const ObjCObjectPointerType *FromPtrType = 2598 FromType->getAs<ObjCObjectPointerType>()) { 2599 // Objective-C++ conversions are always okay. 2600 // FIXME: We should have a different class of conversions for the 2601 // Objective-C++ implicit conversions. 2602 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2603 return false; 2604 } else if (FromType->isBlockPointerType()) { 2605 Kind = CK_BlockPointerToObjCPointerCast; 2606 } else { 2607 Kind = CK_CPointerToObjCPointerCast; 2608 } 2609 } else if (ToType->isBlockPointerType()) { 2610 if (!FromType->isBlockPointerType()) 2611 Kind = CK_AnyPointerToBlockPointerCast; 2612 } 2613 2614 // We shouldn't fall into this case unless it's valid for other 2615 // reasons. 2616 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2617 Kind = CK_NullToPointer; 2618 2619 return false; 2620 } 2621 2622 /// IsMemberPointerConversion - Determines whether the conversion of the 2623 /// expression From, which has the (possibly adjusted) type FromType, can be 2624 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2625 /// If so, returns true and places the converted type (that might differ from 2626 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2627 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2628 QualType ToType, 2629 bool InOverloadResolution, 2630 QualType &ConvertedType) { 2631 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2632 if (!ToTypePtr) 2633 return false; 2634 2635 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2636 if (From->isNullPointerConstant(Context, 2637 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2638 : Expr::NPC_ValueDependentIsNull)) { 2639 ConvertedType = ToType; 2640 return true; 2641 } 2642 2643 // Otherwise, both types have to be member pointers. 2644 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2645 if (!FromTypePtr) 2646 return false; 2647 2648 // A pointer to member of B can be converted to a pointer to member of D, 2649 // where D is derived from B (C++ 4.11p2). 2650 QualType FromClass(FromTypePtr->getClass(), 0); 2651 QualType ToClass(ToTypePtr->getClass(), 0); 2652 2653 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2654 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2655 IsDerivedFrom(ToClass, FromClass)) { 2656 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2657 ToClass.getTypePtr()); 2658 return true; 2659 } 2660 2661 return false; 2662 } 2663 2664 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2665 /// expression From to the type ToType. This routine checks for ambiguous or 2666 /// virtual or inaccessible base-to-derived member pointer conversions 2667 /// for which IsMemberPointerConversion has already returned true. It returns 2668 /// true and produces a diagnostic if there was an error, or returns false 2669 /// otherwise. 2670 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2671 CastKind &Kind, 2672 CXXCastPath &BasePath, 2673 bool IgnoreBaseAccess) { 2674 QualType FromType = From->getType(); 2675 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2676 if (!FromPtrType) { 2677 // This must be a null pointer to member pointer conversion 2678 assert(From->isNullPointerConstant(Context, 2679 Expr::NPC_ValueDependentIsNull) && 2680 "Expr must be null pointer constant!"); 2681 Kind = CK_NullToMemberPointer; 2682 return false; 2683 } 2684 2685 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2686 assert(ToPtrType && "No member pointer cast has a target type " 2687 "that is not a member pointer."); 2688 2689 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2690 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2691 2692 // FIXME: What about dependent types? 2693 assert(FromClass->isRecordType() && "Pointer into non-class."); 2694 assert(ToClass->isRecordType() && "Pointer into non-class."); 2695 2696 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2697 /*DetectVirtual=*/true); 2698 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2699 assert(DerivationOkay && 2700 "Should not have been called if derivation isn't OK."); 2701 (void)DerivationOkay; 2702 2703 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2704 getUnqualifiedType())) { 2705 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2706 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2707 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2708 return true; 2709 } 2710 2711 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2712 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2713 << FromClass << ToClass << QualType(VBase, 0) 2714 << From->getSourceRange(); 2715 return true; 2716 } 2717 2718 if (!IgnoreBaseAccess) 2719 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2720 Paths.front(), 2721 diag::err_downcast_from_inaccessible_base); 2722 2723 // Must be a base to derived member conversion. 2724 BuildBasePathArray(Paths, BasePath); 2725 Kind = CK_BaseToDerivedMemberPointer; 2726 return false; 2727 } 2728 2729 /// IsQualificationConversion - Determines whether the conversion from 2730 /// an rvalue of type FromType to ToType is a qualification conversion 2731 /// (C++ 4.4). 2732 /// 2733 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2734 /// when the qualification conversion involves a change in the Objective-C 2735 /// object lifetime. 2736 bool 2737 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2738 bool CStyle, bool &ObjCLifetimeConversion) { 2739 FromType = Context.getCanonicalType(FromType); 2740 ToType = Context.getCanonicalType(ToType); 2741 ObjCLifetimeConversion = false; 2742 2743 // If FromType and ToType are the same type, this is not a 2744 // qualification conversion. 2745 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2746 return false; 2747 2748 // (C++ 4.4p4): 2749 // A conversion can add cv-qualifiers at levels other than the first 2750 // in multi-level pointers, subject to the following rules: [...] 2751 bool PreviousToQualsIncludeConst = true; 2752 bool UnwrappedAnyPointer = false; 2753 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2754 // Within each iteration of the loop, we check the qualifiers to 2755 // determine if this still looks like a qualification 2756 // conversion. Then, if all is well, we unwrap one more level of 2757 // pointers or pointers-to-members and do it all again 2758 // until there are no more pointers or pointers-to-members left to 2759 // unwrap. 2760 UnwrappedAnyPointer = true; 2761 2762 Qualifiers FromQuals = FromType.getQualifiers(); 2763 Qualifiers ToQuals = ToType.getQualifiers(); 2764 2765 // Objective-C ARC: 2766 // Check Objective-C lifetime conversions. 2767 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2768 UnwrappedAnyPointer) { 2769 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2770 ObjCLifetimeConversion = true; 2771 FromQuals.removeObjCLifetime(); 2772 ToQuals.removeObjCLifetime(); 2773 } else { 2774 // Qualification conversions cannot cast between different 2775 // Objective-C lifetime qualifiers. 2776 return false; 2777 } 2778 } 2779 2780 // Allow addition/removal of GC attributes but not changing GC attributes. 2781 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2782 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2783 FromQuals.removeObjCGCAttr(); 2784 ToQuals.removeObjCGCAttr(); 2785 } 2786 2787 // -- for every j > 0, if const is in cv 1,j then const is in cv 2788 // 2,j, and similarly for volatile. 2789 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2790 return false; 2791 2792 // -- if the cv 1,j and cv 2,j are different, then const is in 2793 // every cv for 0 < k < j. 2794 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2795 && !PreviousToQualsIncludeConst) 2796 return false; 2797 2798 // Keep track of whether all prior cv-qualifiers in the "to" type 2799 // include const. 2800 PreviousToQualsIncludeConst 2801 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2802 } 2803 2804 // We are left with FromType and ToType being the pointee types 2805 // after unwrapping the original FromType and ToType the same number 2806 // of types. If we unwrapped any pointers, and if FromType and 2807 // ToType have the same unqualified type (since we checked 2808 // qualifiers above), then this is a qualification conversion. 2809 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2810 } 2811 2812 /// \brief - Determine whether this is a conversion from a scalar type to an 2813 /// atomic type. 2814 /// 2815 /// If successful, updates \c SCS's second and third steps in the conversion 2816 /// sequence to finish the conversion. 2817 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2818 bool InOverloadResolution, 2819 StandardConversionSequence &SCS, 2820 bool CStyle) { 2821 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2822 if (!ToAtomic) 2823 return false; 2824 2825 StandardConversionSequence InnerSCS; 2826 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2827 InOverloadResolution, InnerSCS, 2828 CStyle, /*AllowObjCWritebackConversion=*/false)) 2829 return false; 2830 2831 SCS.Second = InnerSCS.Second; 2832 SCS.setToType(1, InnerSCS.getToType(1)); 2833 SCS.Third = InnerSCS.Third; 2834 SCS.QualificationIncludesObjCLifetime 2835 = InnerSCS.QualificationIncludesObjCLifetime; 2836 SCS.setToType(2, InnerSCS.getToType(2)); 2837 return true; 2838 } 2839 2840 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2841 CXXConstructorDecl *Constructor, 2842 QualType Type) { 2843 const FunctionProtoType *CtorType = 2844 Constructor->getType()->getAs<FunctionProtoType>(); 2845 if (CtorType->getNumArgs() > 0) { 2846 QualType FirstArg = CtorType->getArgType(0); 2847 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2848 return true; 2849 } 2850 return false; 2851 } 2852 2853 static OverloadingResult 2854 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2855 CXXRecordDecl *To, 2856 UserDefinedConversionSequence &User, 2857 OverloadCandidateSet &CandidateSet, 2858 bool AllowExplicit) { 2859 DeclContext::lookup_iterator Con, ConEnd; 2860 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To); 2861 Con != ConEnd; ++Con) { 2862 NamedDecl *D = *Con; 2863 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2864 2865 // Find the constructor (which may be a template). 2866 CXXConstructorDecl *Constructor = 0; 2867 FunctionTemplateDecl *ConstructorTmpl 2868 = dyn_cast<FunctionTemplateDecl>(D); 2869 if (ConstructorTmpl) 2870 Constructor 2871 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2872 else 2873 Constructor = cast<CXXConstructorDecl>(D); 2874 2875 bool Usable = !Constructor->isInvalidDecl() && 2876 S.isInitListConstructor(Constructor) && 2877 (AllowExplicit || !Constructor->isExplicit()); 2878 if (Usable) { 2879 // If the first argument is (a reference to) the target type, 2880 // suppress conversions. 2881 bool SuppressUserConversions = 2882 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2883 if (ConstructorTmpl) 2884 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2885 /*ExplicitArgs*/ 0, 2886 From, CandidateSet, 2887 SuppressUserConversions); 2888 else 2889 S.AddOverloadCandidate(Constructor, FoundDecl, 2890 From, CandidateSet, 2891 SuppressUserConversions); 2892 } 2893 } 2894 2895 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2896 2897 OverloadCandidateSet::iterator Best; 2898 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2899 case OR_Success: { 2900 // Record the standard conversion we used and the conversion function. 2901 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2902 S.MarkFunctionReferenced(From->getLocStart(), Constructor); 2903 2904 QualType ThisType = Constructor->getThisType(S.Context); 2905 // Initializer lists don't have conversions as such. 2906 User.Before.setAsIdentityConversion(); 2907 User.HadMultipleCandidates = HadMultipleCandidates; 2908 User.ConversionFunction = Constructor; 2909 User.FoundConversionFunction = Best->FoundDecl; 2910 User.After.setAsIdentityConversion(); 2911 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2912 User.After.setAllToTypes(ToType); 2913 return OR_Success; 2914 } 2915 2916 case OR_No_Viable_Function: 2917 return OR_No_Viable_Function; 2918 case OR_Deleted: 2919 return OR_Deleted; 2920 case OR_Ambiguous: 2921 return OR_Ambiguous; 2922 } 2923 2924 llvm_unreachable("Invalid OverloadResult!"); 2925 } 2926 2927 /// Determines whether there is a user-defined conversion sequence 2928 /// (C++ [over.ics.user]) that converts expression From to the type 2929 /// ToType. If such a conversion exists, User will contain the 2930 /// user-defined conversion sequence that performs such a conversion 2931 /// and this routine will return true. Otherwise, this routine returns 2932 /// false and User is unspecified. 2933 /// 2934 /// \param AllowExplicit true if the conversion should consider C++0x 2935 /// "explicit" conversion functions as well as non-explicit conversion 2936 /// functions (C++0x [class.conv.fct]p2). 2937 static OverloadingResult 2938 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 2939 UserDefinedConversionSequence &User, 2940 OverloadCandidateSet &CandidateSet, 2941 bool AllowExplicit) { 2942 // Whether we will only visit constructors. 2943 bool ConstructorsOnly = false; 2944 2945 // If the type we are conversion to is a class type, enumerate its 2946 // constructors. 2947 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 2948 // C++ [over.match.ctor]p1: 2949 // When objects of class type are direct-initialized (8.5), or 2950 // copy-initialized from an expression of the same or a 2951 // derived class type (8.5), overload resolution selects the 2952 // constructor. [...] For copy-initialization, the candidate 2953 // functions are all the converting constructors (12.3.1) of 2954 // that class. The argument list is the expression-list within 2955 // the parentheses of the initializer. 2956 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 2957 (From->getType()->getAs<RecordType>() && 2958 S.IsDerivedFrom(From->getType(), ToType))) 2959 ConstructorsOnly = true; 2960 2961 S.RequireCompleteType(From->getLocStart(), ToType, 0); 2962 // RequireCompleteType may have returned true due to some invalid decl 2963 // during template instantiation, but ToType may be complete enough now 2964 // to try to recover. 2965 if (ToType->isIncompleteType()) { 2966 // We're not going to find any constructors. 2967 } else if (CXXRecordDecl *ToRecordDecl 2968 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 2969 2970 Expr **Args = &From; 2971 unsigned NumArgs = 1; 2972 bool ListInitializing = false; 2973 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 2974 // But first, see if there is an init-list-contructor that will work. 2975 OverloadingResult Result = IsInitializerListConstructorConversion( 2976 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 2977 if (Result != OR_No_Viable_Function) 2978 return Result; 2979 // Never mind. 2980 CandidateSet.clear(); 2981 2982 // If we're list-initializing, we pass the individual elements as 2983 // arguments, not the entire list. 2984 Args = InitList->getInits(); 2985 NumArgs = InitList->getNumInits(); 2986 ListInitializing = true; 2987 } 2988 2989 DeclContext::lookup_iterator Con, ConEnd; 2990 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl); 2991 Con != ConEnd; ++Con) { 2992 NamedDecl *D = *Con; 2993 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2994 2995 // Find the constructor (which may be a template). 2996 CXXConstructorDecl *Constructor = 0; 2997 FunctionTemplateDecl *ConstructorTmpl 2998 = dyn_cast<FunctionTemplateDecl>(D); 2999 if (ConstructorTmpl) 3000 Constructor 3001 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3002 else 3003 Constructor = cast<CXXConstructorDecl>(D); 3004 3005 bool Usable = !Constructor->isInvalidDecl(); 3006 if (ListInitializing) 3007 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3008 else 3009 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3010 if (Usable) { 3011 bool SuppressUserConversions = !ConstructorsOnly; 3012 if (SuppressUserConversions && ListInitializing) { 3013 SuppressUserConversions = false; 3014 if (NumArgs == 1) { 3015 // If the first argument is (a reference to) the target type, 3016 // suppress conversions. 3017 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3018 S.Context, Constructor, ToType); 3019 } 3020 } 3021 if (ConstructorTmpl) 3022 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3023 /*ExplicitArgs*/ 0, 3024 llvm::makeArrayRef(Args, NumArgs), 3025 CandidateSet, SuppressUserConversions); 3026 else 3027 // Allow one user-defined conversion when user specifies a 3028 // From->ToType conversion via an static cast (c-style, etc). 3029 S.AddOverloadCandidate(Constructor, FoundDecl, 3030 llvm::makeArrayRef(Args, NumArgs), 3031 CandidateSet, SuppressUserConversions); 3032 } 3033 } 3034 } 3035 } 3036 3037 // Enumerate conversion functions, if we're allowed to. 3038 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3039 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3040 // No conversion functions from incomplete types. 3041 } else if (const RecordType *FromRecordType 3042 = From->getType()->getAs<RecordType>()) { 3043 if (CXXRecordDecl *FromRecordDecl 3044 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3045 // Add all of the conversion functions as candidates. 3046 const UnresolvedSetImpl *Conversions 3047 = FromRecordDecl->getVisibleConversionFunctions(); 3048 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 3049 E = Conversions->end(); I != E; ++I) { 3050 DeclAccessPair FoundDecl = I.getPair(); 3051 NamedDecl *D = FoundDecl.getDecl(); 3052 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3053 if (isa<UsingShadowDecl>(D)) 3054 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3055 3056 CXXConversionDecl *Conv; 3057 FunctionTemplateDecl *ConvTemplate; 3058 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3059 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3060 else 3061 Conv = cast<CXXConversionDecl>(D); 3062 3063 if (AllowExplicit || !Conv->isExplicit()) { 3064 if (ConvTemplate) 3065 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3066 ActingContext, From, ToType, 3067 CandidateSet); 3068 else 3069 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3070 From, ToType, CandidateSet); 3071 } 3072 } 3073 } 3074 } 3075 3076 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3077 3078 OverloadCandidateSet::iterator Best; 3079 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3080 case OR_Success: 3081 // Record the standard conversion we used and the conversion function. 3082 if (CXXConstructorDecl *Constructor 3083 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3084 S.MarkFunctionReferenced(From->getLocStart(), Constructor); 3085 3086 // C++ [over.ics.user]p1: 3087 // If the user-defined conversion is specified by a 3088 // constructor (12.3.1), the initial standard conversion 3089 // sequence converts the source type to the type required by 3090 // the argument of the constructor. 3091 // 3092 QualType ThisType = Constructor->getThisType(S.Context); 3093 if (isa<InitListExpr>(From)) { 3094 // Initializer lists don't have conversions as such. 3095 User.Before.setAsIdentityConversion(); 3096 } else { 3097 if (Best->Conversions[0].isEllipsis()) 3098 User.EllipsisConversion = true; 3099 else { 3100 User.Before = Best->Conversions[0].Standard; 3101 User.EllipsisConversion = false; 3102 } 3103 } 3104 User.HadMultipleCandidates = HadMultipleCandidates; 3105 User.ConversionFunction = Constructor; 3106 User.FoundConversionFunction = Best->FoundDecl; 3107 User.After.setAsIdentityConversion(); 3108 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3109 User.After.setAllToTypes(ToType); 3110 return OR_Success; 3111 } 3112 if (CXXConversionDecl *Conversion 3113 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3114 S.MarkFunctionReferenced(From->getLocStart(), Conversion); 3115 3116 // C++ [over.ics.user]p1: 3117 // 3118 // [...] If the user-defined conversion is specified by a 3119 // conversion function (12.3.2), the initial standard 3120 // conversion sequence converts the source type to the 3121 // implicit object parameter of the conversion function. 3122 User.Before = Best->Conversions[0].Standard; 3123 User.HadMultipleCandidates = HadMultipleCandidates; 3124 User.ConversionFunction = Conversion; 3125 User.FoundConversionFunction = Best->FoundDecl; 3126 User.EllipsisConversion = false; 3127 3128 // C++ [over.ics.user]p2: 3129 // The second standard conversion sequence converts the 3130 // result of the user-defined conversion to the target type 3131 // for the sequence. Since an implicit conversion sequence 3132 // is an initialization, the special rules for 3133 // initialization by user-defined conversion apply when 3134 // selecting the best user-defined conversion for a 3135 // user-defined conversion sequence (see 13.3.3 and 3136 // 13.3.3.1). 3137 User.After = Best->FinalConversion; 3138 return OR_Success; 3139 } 3140 llvm_unreachable("Not a constructor or conversion function?"); 3141 3142 case OR_No_Viable_Function: 3143 return OR_No_Viable_Function; 3144 case OR_Deleted: 3145 // No conversion here! We're done. 3146 return OR_Deleted; 3147 3148 case OR_Ambiguous: 3149 return OR_Ambiguous; 3150 } 3151 3152 llvm_unreachable("Invalid OverloadResult!"); 3153 } 3154 3155 bool 3156 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3157 ImplicitConversionSequence ICS; 3158 OverloadCandidateSet CandidateSet(From->getExprLoc()); 3159 OverloadingResult OvResult = 3160 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3161 CandidateSet, false); 3162 if (OvResult == OR_Ambiguous) 3163 Diag(From->getLocStart(), 3164 diag::err_typecheck_ambiguous_condition) 3165 << From->getType() << ToType << From->getSourceRange(); 3166 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) 3167 Diag(From->getLocStart(), 3168 diag::err_typecheck_nonviable_condition) 3169 << From->getType() << ToType << From->getSourceRange(); 3170 else 3171 return false; 3172 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3173 return true; 3174 } 3175 3176 /// \brief Compare the user-defined conversion functions or constructors 3177 /// of two user-defined conversion sequences to determine whether any ordering 3178 /// is possible. 3179 static ImplicitConversionSequence::CompareKind 3180 compareConversionFunctions(Sema &S, 3181 FunctionDecl *Function1, 3182 FunctionDecl *Function2) { 3183 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x) 3184 return ImplicitConversionSequence::Indistinguishable; 3185 3186 // Objective-C++: 3187 // If both conversion functions are implicitly-declared conversions from 3188 // a lambda closure type to a function pointer and a block pointer, 3189 // respectively, always prefer the conversion to a function pointer, 3190 // because the function pointer is more lightweight and is more likely 3191 // to keep code working. 3192 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1); 3193 if (!Conv1) 3194 return ImplicitConversionSequence::Indistinguishable; 3195 3196 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3197 if (!Conv2) 3198 return ImplicitConversionSequence::Indistinguishable; 3199 3200 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3201 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3202 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3203 if (Block1 != Block2) 3204 return Block1? ImplicitConversionSequence::Worse 3205 : ImplicitConversionSequence::Better; 3206 } 3207 3208 return ImplicitConversionSequence::Indistinguishable; 3209 } 3210 3211 /// CompareImplicitConversionSequences - Compare two implicit 3212 /// conversion sequences to determine whether one is better than the 3213 /// other or if they are indistinguishable (C++ 13.3.3.2). 3214 static ImplicitConversionSequence::CompareKind 3215 CompareImplicitConversionSequences(Sema &S, 3216 const ImplicitConversionSequence& ICS1, 3217 const ImplicitConversionSequence& ICS2) 3218 { 3219 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3220 // conversion sequences (as defined in 13.3.3.1) 3221 // -- a standard conversion sequence (13.3.3.1.1) is a better 3222 // conversion sequence than a user-defined conversion sequence or 3223 // an ellipsis conversion sequence, and 3224 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3225 // conversion sequence than an ellipsis conversion sequence 3226 // (13.3.3.1.3). 3227 // 3228 // C++0x [over.best.ics]p10: 3229 // For the purpose of ranking implicit conversion sequences as 3230 // described in 13.3.3.2, the ambiguous conversion sequence is 3231 // treated as a user-defined sequence that is indistinguishable 3232 // from any other user-defined conversion sequence. 3233 if (ICS1.getKindRank() < ICS2.getKindRank()) 3234 return ImplicitConversionSequence::Better; 3235 if (ICS2.getKindRank() < ICS1.getKindRank()) 3236 return ImplicitConversionSequence::Worse; 3237 3238 // The following checks require both conversion sequences to be of 3239 // the same kind. 3240 if (ICS1.getKind() != ICS2.getKind()) 3241 return ImplicitConversionSequence::Indistinguishable; 3242 3243 ImplicitConversionSequence::CompareKind Result = 3244 ImplicitConversionSequence::Indistinguishable; 3245 3246 // Two implicit conversion sequences of the same form are 3247 // indistinguishable conversion sequences unless one of the 3248 // following rules apply: (C++ 13.3.3.2p3): 3249 if (ICS1.isStandard()) 3250 Result = CompareStandardConversionSequences(S, 3251 ICS1.Standard, ICS2.Standard); 3252 else if (ICS1.isUserDefined()) { 3253 // User-defined conversion sequence U1 is a better conversion 3254 // sequence than another user-defined conversion sequence U2 if 3255 // they contain the same user-defined conversion function or 3256 // constructor and if the second standard conversion sequence of 3257 // U1 is better than the second standard conversion sequence of 3258 // U2 (C++ 13.3.3.2p3). 3259 if (ICS1.UserDefined.ConversionFunction == 3260 ICS2.UserDefined.ConversionFunction) 3261 Result = CompareStandardConversionSequences(S, 3262 ICS1.UserDefined.After, 3263 ICS2.UserDefined.After); 3264 else 3265 Result = compareConversionFunctions(S, 3266 ICS1.UserDefined.ConversionFunction, 3267 ICS2.UserDefined.ConversionFunction); 3268 } 3269 3270 // List-initialization sequence L1 is a better conversion sequence than 3271 // list-initialization sequence L2 if L1 converts to std::initializer_list<X> 3272 // for some X and L2 does not. 3273 if (Result == ImplicitConversionSequence::Indistinguishable && 3274 !ICS1.isBad() && 3275 ICS1.isListInitializationSequence() && 3276 ICS2.isListInitializationSequence()) { 3277 if (ICS1.isStdInitializerListElement() && 3278 !ICS2.isStdInitializerListElement()) 3279 return ImplicitConversionSequence::Better; 3280 if (!ICS1.isStdInitializerListElement() && 3281 ICS2.isStdInitializerListElement()) 3282 return ImplicitConversionSequence::Worse; 3283 } 3284 3285 return Result; 3286 } 3287 3288 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3289 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3290 Qualifiers Quals; 3291 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3292 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3293 } 3294 3295 return Context.hasSameUnqualifiedType(T1, T2); 3296 } 3297 3298 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3299 // determine if one is a proper subset of the other. 3300 static ImplicitConversionSequence::CompareKind 3301 compareStandardConversionSubsets(ASTContext &Context, 3302 const StandardConversionSequence& SCS1, 3303 const StandardConversionSequence& SCS2) { 3304 ImplicitConversionSequence::CompareKind Result 3305 = ImplicitConversionSequence::Indistinguishable; 3306 3307 // the identity conversion sequence is considered to be a subsequence of 3308 // any non-identity conversion sequence 3309 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3310 return ImplicitConversionSequence::Better; 3311 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3312 return ImplicitConversionSequence::Worse; 3313 3314 if (SCS1.Second != SCS2.Second) { 3315 if (SCS1.Second == ICK_Identity) 3316 Result = ImplicitConversionSequence::Better; 3317 else if (SCS2.Second == ICK_Identity) 3318 Result = ImplicitConversionSequence::Worse; 3319 else 3320 return ImplicitConversionSequence::Indistinguishable; 3321 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3322 return ImplicitConversionSequence::Indistinguishable; 3323 3324 if (SCS1.Third == SCS2.Third) { 3325 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3326 : ImplicitConversionSequence::Indistinguishable; 3327 } 3328 3329 if (SCS1.Third == ICK_Identity) 3330 return Result == ImplicitConversionSequence::Worse 3331 ? ImplicitConversionSequence::Indistinguishable 3332 : ImplicitConversionSequence::Better; 3333 3334 if (SCS2.Third == ICK_Identity) 3335 return Result == ImplicitConversionSequence::Better 3336 ? ImplicitConversionSequence::Indistinguishable 3337 : ImplicitConversionSequence::Worse; 3338 3339 return ImplicitConversionSequence::Indistinguishable; 3340 } 3341 3342 /// \brief Determine whether one of the given reference bindings is better 3343 /// than the other based on what kind of bindings they are. 3344 static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3345 const StandardConversionSequence &SCS2) { 3346 // C++0x [over.ics.rank]p3b4: 3347 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3348 // implicit object parameter of a non-static member function declared 3349 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3350 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3351 // lvalue reference to a function lvalue and S2 binds an rvalue 3352 // reference*. 3353 // 3354 // FIXME: Rvalue references. We're going rogue with the above edits, 3355 // because the semantics in the current C++0x working paper (N3225 at the 3356 // time of this writing) break the standard definition of std::forward 3357 // and std::reference_wrapper when dealing with references to functions. 3358 // Proposed wording changes submitted to CWG for consideration. 3359 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3360 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3361 return false; 3362 3363 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3364 SCS2.IsLvalueReference) || 3365 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3366 !SCS2.IsLvalueReference); 3367 } 3368 3369 /// CompareStandardConversionSequences - Compare two standard 3370 /// conversion sequences to determine whether one is better than the 3371 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3372 static ImplicitConversionSequence::CompareKind 3373 CompareStandardConversionSequences(Sema &S, 3374 const StandardConversionSequence& SCS1, 3375 const StandardConversionSequence& SCS2) 3376 { 3377 // Standard conversion sequence S1 is a better conversion sequence 3378 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3379 3380 // -- S1 is a proper subsequence of S2 (comparing the conversion 3381 // sequences in the canonical form defined by 13.3.3.1.1, 3382 // excluding any Lvalue Transformation; the identity conversion 3383 // sequence is considered to be a subsequence of any 3384 // non-identity conversion sequence) or, if not that, 3385 if (ImplicitConversionSequence::CompareKind CK 3386 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3387 return CK; 3388 3389 // -- the rank of S1 is better than the rank of S2 (by the rules 3390 // defined below), or, if not that, 3391 ImplicitConversionRank Rank1 = SCS1.getRank(); 3392 ImplicitConversionRank Rank2 = SCS2.getRank(); 3393 if (Rank1 < Rank2) 3394 return ImplicitConversionSequence::Better; 3395 else if (Rank2 < Rank1) 3396 return ImplicitConversionSequence::Worse; 3397 3398 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3399 // are indistinguishable unless one of the following rules 3400 // applies: 3401 3402 // A conversion that is not a conversion of a pointer, or 3403 // pointer to member, to bool is better than another conversion 3404 // that is such a conversion. 3405 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3406 return SCS2.isPointerConversionToBool() 3407 ? ImplicitConversionSequence::Better 3408 : ImplicitConversionSequence::Worse; 3409 3410 // C++ [over.ics.rank]p4b2: 3411 // 3412 // If class B is derived directly or indirectly from class A, 3413 // conversion of B* to A* is better than conversion of B* to 3414 // void*, and conversion of A* to void* is better than conversion 3415 // of B* to void*. 3416 bool SCS1ConvertsToVoid 3417 = SCS1.isPointerConversionToVoidPointer(S.Context); 3418 bool SCS2ConvertsToVoid 3419 = SCS2.isPointerConversionToVoidPointer(S.Context); 3420 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3421 // Exactly one of the conversion sequences is a conversion to 3422 // a void pointer; it's the worse conversion. 3423 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3424 : ImplicitConversionSequence::Worse; 3425 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3426 // Neither conversion sequence converts to a void pointer; compare 3427 // their derived-to-base conversions. 3428 if (ImplicitConversionSequence::CompareKind DerivedCK 3429 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3430 return DerivedCK; 3431 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3432 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3433 // Both conversion sequences are conversions to void 3434 // pointers. Compare the source types to determine if there's an 3435 // inheritance relationship in their sources. 3436 QualType FromType1 = SCS1.getFromType(); 3437 QualType FromType2 = SCS2.getFromType(); 3438 3439 // Adjust the types we're converting from via the array-to-pointer 3440 // conversion, if we need to. 3441 if (SCS1.First == ICK_Array_To_Pointer) 3442 FromType1 = S.Context.getArrayDecayedType(FromType1); 3443 if (SCS2.First == ICK_Array_To_Pointer) 3444 FromType2 = S.Context.getArrayDecayedType(FromType2); 3445 3446 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3447 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3448 3449 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3450 return ImplicitConversionSequence::Better; 3451 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3452 return ImplicitConversionSequence::Worse; 3453 3454 // Objective-C++: If one interface is more specific than the 3455 // other, it is the better one. 3456 const ObjCObjectPointerType* FromObjCPtr1 3457 = FromType1->getAs<ObjCObjectPointerType>(); 3458 const ObjCObjectPointerType* FromObjCPtr2 3459 = FromType2->getAs<ObjCObjectPointerType>(); 3460 if (FromObjCPtr1 && FromObjCPtr2) { 3461 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3462 FromObjCPtr2); 3463 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3464 FromObjCPtr1); 3465 if (AssignLeft != AssignRight) { 3466 return AssignLeft? ImplicitConversionSequence::Better 3467 : ImplicitConversionSequence::Worse; 3468 } 3469 } 3470 } 3471 3472 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3473 // bullet 3). 3474 if (ImplicitConversionSequence::CompareKind QualCK 3475 = CompareQualificationConversions(S, SCS1, SCS2)) 3476 return QualCK; 3477 3478 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3479 // Check for a better reference binding based on the kind of bindings. 3480 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3481 return ImplicitConversionSequence::Better; 3482 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3483 return ImplicitConversionSequence::Worse; 3484 3485 // C++ [over.ics.rank]p3b4: 3486 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3487 // which the references refer are the same type except for 3488 // top-level cv-qualifiers, and the type to which the reference 3489 // initialized by S2 refers is more cv-qualified than the type 3490 // to which the reference initialized by S1 refers. 3491 QualType T1 = SCS1.getToType(2); 3492 QualType T2 = SCS2.getToType(2); 3493 T1 = S.Context.getCanonicalType(T1); 3494 T2 = S.Context.getCanonicalType(T2); 3495 Qualifiers T1Quals, T2Quals; 3496 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3497 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3498 if (UnqualT1 == UnqualT2) { 3499 // Objective-C++ ARC: If the references refer to objects with different 3500 // lifetimes, prefer bindings that don't change lifetime. 3501 if (SCS1.ObjCLifetimeConversionBinding != 3502 SCS2.ObjCLifetimeConversionBinding) { 3503 return SCS1.ObjCLifetimeConversionBinding 3504 ? ImplicitConversionSequence::Worse 3505 : ImplicitConversionSequence::Better; 3506 } 3507 3508 // If the type is an array type, promote the element qualifiers to the 3509 // type for comparison. 3510 if (isa<ArrayType>(T1) && T1Quals) 3511 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3512 if (isa<ArrayType>(T2) && T2Quals) 3513 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3514 if (T2.isMoreQualifiedThan(T1)) 3515 return ImplicitConversionSequence::Better; 3516 else if (T1.isMoreQualifiedThan(T2)) 3517 return ImplicitConversionSequence::Worse; 3518 } 3519 } 3520 3521 // In Microsoft mode, prefer an integral conversion to a 3522 // floating-to-integral conversion if the integral conversion 3523 // is between types of the same size. 3524 // For example: 3525 // void f(float); 3526 // void f(int); 3527 // int main { 3528 // long a; 3529 // f(a); 3530 // } 3531 // Here, MSVC will call f(int) instead of generating a compile error 3532 // as clang will do in standard mode. 3533 if (S.getLangOpts().MicrosoftMode && 3534 SCS1.Second == ICK_Integral_Conversion && 3535 SCS2.Second == ICK_Floating_Integral && 3536 S.Context.getTypeSize(SCS1.getFromType()) == 3537 S.Context.getTypeSize(SCS1.getToType(2))) 3538 return ImplicitConversionSequence::Better; 3539 3540 return ImplicitConversionSequence::Indistinguishable; 3541 } 3542 3543 /// CompareQualificationConversions - Compares two standard conversion 3544 /// sequences to determine whether they can be ranked based on their 3545 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3546 ImplicitConversionSequence::CompareKind 3547 CompareQualificationConversions(Sema &S, 3548 const StandardConversionSequence& SCS1, 3549 const StandardConversionSequence& SCS2) { 3550 // C++ 13.3.3.2p3: 3551 // -- S1 and S2 differ only in their qualification conversion and 3552 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3553 // cv-qualification signature of type T1 is a proper subset of 3554 // the cv-qualification signature of type T2, and S1 is not the 3555 // deprecated string literal array-to-pointer conversion (4.2). 3556 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3557 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3558 return ImplicitConversionSequence::Indistinguishable; 3559 3560 // FIXME: the example in the standard doesn't use a qualification 3561 // conversion (!) 3562 QualType T1 = SCS1.getToType(2); 3563 QualType T2 = SCS2.getToType(2); 3564 T1 = S.Context.getCanonicalType(T1); 3565 T2 = S.Context.getCanonicalType(T2); 3566 Qualifiers T1Quals, T2Quals; 3567 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3568 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3569 3570 // If the types are the same, we won't learn anything by unwrapped 3571 // them. 3572 if (UnqualT1 == UnqualT2) 3573 return ImplicitConversionSequence::Indistinguishable; 3574 3575 // If the type is an array type, promote the element qualifiers to the type 3576 // for comparison. 3577 if (isa<ArrayType>(T1) && T1Quals) 3578 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3579 if (isa<ArrayType>(T2) && T2Quals) 3580 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3581 3582 ImplicitConversionSequence::CompareKind Result 3583 = ImplicitConversionSequence::Indistinguishable; 3584 3585 // Objective-C++ ARC: 3586 // Prefer qualification conversions not involving a change in lifetime 3587 // to qualification conversions that do not change lifetime. 3588 if (SCS1.QualificationIncludesObjCLifetime != 3589 SCS2.QualificationIncludesObjCLifetime) { 3590 Result = SCS1.QualificationIncludesObjCLifetime 3591 ? ImplicitConversionSequence::Worse 3592 : ImplicitConversionSequence::Better; 3593 } 3594 3595 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3596 // Within each iteration of the loop, we check the qualifiers to 3597 // determine if this still looks like a qualification 3598 // conversion. Then, if all is well, we unwrap one more level of 3599 // pointers or pointers-to-members and do it all again 3600 // until there are no more pointers or pointers-to-members left 3601 // to unwrap. This essentially mimics what 3602 // IsQualificationConversion does, but here we're checking for a 3603 // strict subset of qualifiers. 3604 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3605 // The qualifiers are the same, so this doesn't tell us anything 3606 // about how the sequences rank. 3607 ; 3608 else if (T2.isMoreQualifiedThan(T1)) { 3609 // T1 has fewer qualifiers, so it could be the better sequence. 3610 if (Result == ImplicitConversionSequence::Worse) 3611 // Neither has qualifiers that are a subset of the other's 3612 // qualifiers. 3613 return ImplicitConversionSequence::Indistinguishable; 3614 3615 Result = ImplicitConversionSequence::Better; 3616 } else if (T1.isMoreQualifiedThan(T2)) { 3617 // T2 has fewer qualifiers, so it could be the better sequence. 3618 if (Result == ImplicitConversionSequence::Better) 3619 // Neither has qualifiers that are a subset of the other's 3620 // qualifiers. 3621 return ImplicitConversionSequence::Indistinguishable; 3622 3623 Result = ImplicitConversionSequence::Worse; 3624 } else { 3625 // Qualifiers are disjoint. 3626 return ImplicitConversionSequence::Indistinguishable; 3627 } 3628 3629 // If the types after this point are equivalent, we're done. 3630 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3631 break; 3632 } 3633 3634 // Check that the winning standard conversion sequence isn't using 3635 // the deprecated string literal array to pointer conversion. 3636 switch (Result) { 3637 case ImplicitConversionSequence::Better: 3638 if (SCS1.DeprecatedStringLiteralToCharPtr) 3639 Result = ImplicitConversionSequence::Indistinguishable; 3640 break; 3641 3642 case ImplicitConversionSequence::Indistinguishable: 3643 break; 3644 3645 case ImplicitConversionSequence::Worse: 3646 if (SCS2.DeprecatedStringLiteralToCharPtr) 3647 Result = ImplicitConversionSequence::Indistinguishable; 3648 break; 3649 } 3650 3651 return Result; 3652 } 3653 3654 /// CompareDerivedToBaseConversions - Compares two standard conversion 3655 /// sequences to determine whether they can be ranked based on their 3656 /// various kinds of derived-to-base conversions (C++ 3657 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3658 /// conversions between Objective-C interface types. 3659 ImplicitConversionSequence::CompareKind 3660 CompareDerivedToBaseConversions(Sema &S, 3661 const StandardConversionSequence& SCS1, 3662 const StandardConversionSequence& SCS2) { 3663 QualType FromType1 = SCS1.getFromType(); 3664 QualType ToType1 = SCS1.getToType(1); 3665 QualType FromType2 = SCS2.getFromType(); 3666 QualType ToType2 = SCS2.getToType(1); 3667 3668 // Adjust the types we're converting from via the array-to-pointer 3669 // conversion, if we need to. 3670 if (SCS1.First == ICK_Array_To_Pointer) 3671 FromType1 = S.Context.getArrayDecayedType(FromType1); 3672 if (SCS2.First == ICK_Array_To_Pointer) 3673 FromType2 = S.Context.getArrayDecayedType(FromType2); 3674 3675 // Canonicalize all of the types. 3676 FromType1 = S.Context.getCanonicalType(FromType1); 3677 ToType1 = S.Context.getCanonicalType(ToType1); 3678 FromType2 = S.Context.getCanonicalType(FromType2); 3679 ToType2 = S.Context.getCanonicalType(ToType2); 3680 3681 // C++ [over.ics.rank]p4b3: 3682 // 3683 // If class B is derived directly or indirectly from class A and 3684 // class C is derived directly or indirectly from B, 3685 // 3686 // Compare based on pointer conversions. 3687 if (SCS1.Second == ICK_Pointer_Conversion && 3688 SCS2.Second == ICK_Pointer_Conversion && 3689 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3690 FromType1->isPointerType() && FromType2->isPointerType() && 3691 ToType1->isPointerType() && ToType2->isPointerType()) { 3692 QualType FromPointee1 3693 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3694 QualType ToPointee1 3695 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3696 QualType FromPointee2 3697 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3698 QualType ToPointee2 3699 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3700 3701 // -- conversion of C* to B* is better than conversion of C* to A*, 3702 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3703 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3704 return ImplicitConversionSequence::Better; 3705 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3706 return ImplicitConversionSequence::Worse; 3707 } 3708 3709 // -- conversion of B* to A* is better than conversion of C* to A*, 3710 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3711 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3712 return ImplicitConversionSequence::Better; 3713 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3714 return ImplicitConversionSequence::Worse; 3715 } 3716 } else if (SCS1.Second == ICK_Pointer_Conversion && 3717 SCS2.Second == ICK_Pointer_Conversion) { 3718 const ObjCObjectPointerType *FromPtr1 3719 = FromType1->getAs<ObjCObjectPointerType>(); 3720 const ObjCObjectPointerType *FromPtr2 3721 = FromType2->getAs<ObjCObjectPointerType>(); 3722 const ObjCObjectPointerType *ToPtr1 3723 = ToType1->getAs<ObjCObjectPointerType>(); 3724 const ObjCObjectPointerType *ToPtr2 3725 = ToType2->getAs<ObjCObjectPointerType>(); 3726 3727 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3728 // Apply the same conversion ranking rules for Objective-C pointer types 3729 // that we do for C++ pointers to class types. However, we employ the 3730 // Objective-C pseudo-subtyping relationship used for assignment of 3731 // Objective-C pointer types. 3732 bool FromAssignLeft 3733 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3734 bool FromAssignRight 3735 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3736 bool ToAssignLeft 3737 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3738 bool ToAssignRight 3739 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3740 3741 // A conversion to an a non-id object pointer type or qualified 'id' 3742 // type is better than a conversion to 'id'. 3743 if (ToPtr1->isObjCIdType() && 3744 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3745 return ImplicitConversionSequence::Worse; 3746 if (ToPtr2->isObjCIdType() && 3747 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3748 return ImplicitConversionSequence::Better; 3749 3750 // A conversion to a non-id object pointer type is better than a 3751 // conversion to a qualified 'id' type 3752 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3753 return ImplicitConversionSequence::Worse; 3754 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3755 return ImplicitConversionSequence::Better; 3756 3757 // A conversion to an a non-Class object pointer type or qualified 'Class' 3758 // type is better than a conversion to 'Class'. 3759 if (ToPtr1->isObjCClassType() && 3760 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3761 return ImplicitConversionSequence::Worse; 3762 if (ToPtr2->isObjCClassType() && 3763 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3764 return ImplicitConversionSequence::Better; 3765 3766 // A conversion to a non-Class object pointer type is better than a 3767 // conversion to a qualified 'Class' type. 3768 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3769 return ImplicitConversionSequence::Worse; 3770 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3771 return ImplicitConversionSequence::Better; 3772 3773 // -- "conversion of C* to B* is better than conversion of C* to A*," 3774 if (S.Context.hasSameType(FromType1, FromType2) && 3775 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3776 (ToAssignLeft != ToAssignRight)) 3777 return ToAssignLeft? ImplicitConversionSequence::Worse 3778 : ImplicitConversionSequence::Better; 3779 3780 // -- "conversion of B* to A* is better than conversion of C* to A*," 3781 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3782 (FromAssignLeft != FromAssignRight)) 3783 return FromAssignLeft? ImplicitConversionSequence::Better 3784 : ImplicitConversionSequence::Worse; 3785 } 3786 } 3787 3788 // Ranking of member-pointer types. 3789 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3790 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3791 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3792 const MemberPointerType * FromMemPointer1 = 3793 FromType1->getAs<MemberPointerType>(); 3794 const MemberPointerType * ToMemPointer1 = 3795 ToType1->getAs<MemberPointerType>(); 3796 const MemberPointerType * FromMemPointer2 = 3797 FromType2->getAs<MemberPointerType>(); 3798 const MemberPointerType * ToMemPointer2 = 3799 ToType2->getAs<MemberPointerType>(); 3800 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3801 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3802 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3803 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3804 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3805 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3806 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3807 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3808 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3809 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3810 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3811 return ImplicitConversionSequence::Worse; 3812 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3813 return ImplicitConversionSequence::Better; 3814 } 3815 // conversion of B::* to C::* is better than conversion of A::* to C::* 3816 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3817 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3818 return ImplicitConversionSequence::Better; 3819 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3820 return ImplicitConversionSequence::Worse; 3821 } 3822 } 3823 3824 if (SCS1.Second == ICK_Derived_To_Base) { 3825 // -- conversion of C to B is better than conversion of C to A, 3826 // -- binding of an expression of type C to a reference of type 3827 // B& is better than binding an expression of type C to a 3828 // reference of type A&, 3829 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3830 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3831 if (S.IsDerivedFrom(ToType1, ToType2)) 3832 return ImplicitConversionSequence::Better; 3833 else if (S.IsDerivedFrom(ToType2, ToType1)) 3834 return ImplicitConversionSequence::Worse; 3835 } 3836 3837 // -- conversion of B to A is better than conversion of C to A. 3838 // -- binding of an expression of type B to a reference of type 3839 // A& is better than binding an expression of type C to a 3840 // reference of type A&, 3841 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3842 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3843 if (S.IsDerivedFrom(FromType2, FromType1)) 3844 return ImplicitConversionSequence::Better; 3845 else if (S.IsDerivedFrom(FromType1, FromType2)) 3846 return ImplicitConversionSequence::Worse; 3847 } 3848 } 3849 3850 return ImplicitConversionSequence::Indistinguishable; 3851 } 3852 3853 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 3854 /// determine whether they are reference-related, 3855 /// reference-compatible, reference-compatible with added 3856 /// qualification, or incompatible, for use in C++ initialization by 3857 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3858 /// type, and the first type (T1) is the pointee type of the reference 3859 /// type being initialized. 3860 Sema::ReferenceCompareResult 3861 Sema::CompareReferenceRelationship(SourceLocation Loc, 3862 QualType OrigT1, QualType OrigT2, 3863 bool &DerivedToBase, 3864 bool &ObjCConversion, 3865 bool &ObjCLifetimeConversion) { 3866 assert(!OrigT1->isReferenceType() && 3867 "T1 must be the pointee type of the reference type"); 3868 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3869 3870 QualType T1 = Context.getCanonicalType(OrigT1); 3871 QualType T2 = Context.getCanonicalType(OrigT2); 3872 Qualifiers T1Quals, T2Quals; 3873 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3874 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3875 3876 // C++ [dcl.init.ref]p4: 3877 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3878 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3879 // T1 is a base class of T2. 3880 DerivedToBase = false; 3881 ObjCConversion = false; 3882 ObjCLifetimeConversion = false; 3883 if (UnqualT1 == UnqualT2) { 3884 // Nothing to do. 3885 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 3886 IsDerivedFrom(UnqualT2, UnqualT1)) 3887 DerivedToBase = true; 3888 else if (UnqualT1->isObjCObjectOrInterfaceType() && 3889 UnqualT2->isObjCObjectOrInterfaceType() && 3890 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 3891 ObjCConversion = true; 3892 else 3893 return Ref_Incompatible; 3894 3895 // At this point, we know that T1 and T2 are reference-related (at 3896 // least). 3897 3898 // If the type is an array type, promote the element qualifiers to the type 3899 // for comparison. 3900 if (isa<ArrayType>(T1) && T1Quals) 3901 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 3902 if (isa<ArrayType>(T2) && T2Quals) 3903 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 3904 3905 // C++ [dcl.init.ref]p4: 3906 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 3907 // reference-related to T2 and cv1 is the same cv-qualification 3908 // as, or greater cv-qualification than, cv2. For purposes of 3909 // overload resolution, cases for which cv1 is greater 3910 // cv-qualification than cv2 are identified as 3911 // reference-compatible with added qualification (see 13.3.3.2). 3912 // 3913 // Note that we also require equivalence of Objective-C GC and address-space 3914 // qualifiers when performing these computations, so that e.g., an int in 3915 // address space 1 is not reference-compatible with an int in address 3916 // space 2. 3917 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 3918 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 3919 T1Quals.removeObjCLifetime(); 3920 T2Quals.removeObjCLifetime(); 3921 ObjCLifetimeConversion = true; 3922 } 3923 3924 if (T1Quals == T2Quals) 3925 return Ref_Compatible; 3926 else if (T1Quals.compatiblyIncludes(T2Quals)) 3927 return Ref_Compatible_With_Added_Qualification; 3928 else 3929 return Ref_Related; 3930 } 3931 3932 /// \brief Look for a user-defined conversion to an value reference-compatible 3933 /// with DeclType. Return true if something definite is found. 3934 static bool 3935 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 3936 QualType DeclType, SourceLocation DeclLoc, 3937 Expr *Init, QualType T2, bool AllowRvalues, 3938 bool AllowExplicit) { 3939 assert(T2->isRecordType() && "Can only find conversions of record types."); 3940 CXXRecordDecl *T2RecordDecl 3941 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 3942 3943 OverloadCandidateSet CandidateSet(DeclLoc); 3944 const UnresolvedSetImpl *Conversions 3945 = T2RecordDecl->getVisibleConversionFunctions(); 3946 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 3947 E = Conversions->end(); I != E; ++I) { 3948 NamedDecl *D = *I; 3949 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 3950 if (isa<UsingShadowDecl>(D)) 3951 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3952 3953 FunctionTemplateDecl *ConvTemplate 3954 = dyn_cast<FunctionTemplateDecl>(D); 3955 CXXConversionDecl *Conv; 3956 if (ConvTemplate) 3957 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3958 else 3959 Conv = cast<CXXConversionDecl>(D); 3960 3961 // If this is an explicit conversion, and we're not allowed to consider 3962 // explicit conversions, skip it. 3963 if (!AllowExplicit && Conv->isExplicit()) 3964 continue; 3965 3966 if (AllowRvalues) { 3967 bool DerivedToBase = false; 3968 bool ObjCConversion = false; 3969 bool ObjCLifetimeConversion = false; 3970 3971 // If we are initializing an rvalue reference, don't permit conversion 3972 // functions that return lvalues. 3973 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 3974 const ReferenceType *RefType 3975 = Conv->getConversionType()->getAs<LValueReferenceType>(); 3976 if (RefType && !RefType->getPointeeType()->isFunctionType()) 3977 continue; 3978 } 3979 3980 if (!ConvTemplate && 3981 S.CompareReferenceRelationship( 3982 DeclLoc, 3983 Conv->getConversionType().getNonReferenceType() 3984 .getUnqualifiedType(), 3985 DeclType.getNonReferenceType().getUnqualifiedType(), 3986 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 3987 Sema::Ref_Incompatible) 3988 continue; 3989 } else { 3990 // If the conversion function doesn't return a reference type, 3991 // it can't be considered for this conversion. An rvalue reference 3992 // is only acceptable if its referencee is a function type. 3993 3994 const ReferenceType *RefType = 3995 Conv->getConversionType()->getAs<ReferenceType>(); 3996 if (!RefType || 3997 (!RefType->isLValueReferenceType() && 3998 !RefType->getPointeeType()->isFunctionType())) 3999 continue; 4000 } 4001 4002 if (ConvTemplate) 4003 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4004 Init, DeclType, CandidateSet); 4005 else 4006 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4007 DeclType, CandidateSet); 4008 } 4009 4010 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4011 4012 OverloadCandidateSet::iterator Best; 4013 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4014 case OR_Success: 4015 // C++ [over.ics.ref]p1: 4016 // 4017 // [...] If the parameter binds directly to the result of 4018 // applying a conversion function to the argument 4019 // expression, the implicit conversion sequence is a 4020 // user-defined conversion sequence (13.3.3.1.2), with the 4021 // second standard conversion sequence either an identity 4022 // conversion or, if the conversion function returns an 4023 // entity of a type that is a derived class of the parameter 4024 // type, a derived-to-base Conversion. 4025 if (!Best->FinalConversion.DirectBinding) 4026 return false; 4027 4028 if (Best->Function) 4029 S.MarkFunctionReferenced(DeclLoc, Best->Function); 4030 ICS.setUserDefined(); 4031 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4032 ICS.UserDefined.After = Best->FinalConversion; 4033 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4034 ICS.UserDefined.ConversionFunction = Best->Function; 4035 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4036 ICS.UserDefined.EllipsisConversion = false; 4037 assert(ICS.UserDefined.After.ReferenceBinding && 4038 ICS.UserDefined.After.DirectBinding && 4039 "Expected a direct reference binding!"); 4040 return true; 4041 4042 case OR_Ambiguous: 4043 ICS.setAmbiguous(); 4044 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4045 Cand != CandidateSet.end(); ++Cand) 4046 if (Cand->Viable) 4047 ICS.Ambiguous.addConversion(Cand->Function); 4048 return true; 4049 4050 case OR_No_Viable_Function: 4051 case OR_Deleted: 4052 // There was no suitable conversion, or we found a deleted 4053 // conversion; continue with other checks. 4054 return false; 4055 } 4056 4057 llvm_unreachable("Invalid OverloadResult!"); 4058 } 4059 4060 /// \brief Compute an implicit conversion sequence for reference 4061 /// initialization. 4062 static ImplicitConversionSequence 4063 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4064 SourceLocation DeclLoc, 4065 bool SuppressUserConversions, 4066 bool AllowExplicit) { 4067 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4068 4069 // Most paths end in a failed conversion. 4070 ImplicitConversionSequence ICS; 4071 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4072 4073 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4074 QualType T2 = Init->getType(); 4075 4076 // If the initializer is the address of an overloaded function, try 4077 // to resolve the overloaded function. If all goes well, T2 is the 4078 // type of the resulting function. 4079 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4080 DeclAccessPair Found; 4081 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4082 false, Found)) 4083 T2 = Fn->getType(); 4084 } 4085 4086 // Compute some basic properties of the types and the initializer. 4087 bool isRValRef = DeclType->isRValueReferenceType(); 4088 bool DerivedToBase = false; 4089 bool ObjCConversion = false; 4090 bool ObjCLifetimeConversion = false; 4091 Expr::Classification InitCategory = Init->Classify(S.Context); 4092 Sema::ReferenceCompareResult RefRelationship 4093 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4094 ObjCConversion, ObjCLifetimeConversion); 4095 4096 4097 // C++0x [dcl.init.ref]p5: 4098 // A reference to type "cv1 T1" is initialized by an expression 4099 // of type "cv2 T2" as follows: 4100 4101 // -- If reference is an lvalue reference and the initializer expression 4102 if (!isRValRef) { 4103 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4104 // reference-compatible with "cv2 T2," or 4105 // 4106 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4107 if (InitCategory.isLValue() && 4108 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4109 // C++ [over.ics.ref]p1: 4110 // When a parameter of reference type binds directly (8.5.3) 4111 // to an argument expression, the implicit conversion sequence 4112 // is the identity conversion, unless the argument expression 4113 // has a type that is a derived class of the parameter type, 4114 // in which case the implicit conversion sequence is a 4115 // derived-to-base Conversion (13.3.3.1). 4116 ICS.setStandard(); 4117 ICS.Standard.First = ICK_Identity; 4118 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4119 : ObjCConversion? ICK_Compatible_Conversion 4120 : ICK_Identity; 4121 ICS.Standard.Third = ICK_Identity; 4122 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4123 ICS.Standard.setToType(0, T2); 4124 ICS.Standard.setToType(1, T1); 4125 ICS.Standard.setToType(2, T1); 4126 ICS.Standard.ReferenceBinding = true; 4127 ICS.Standard.DirectBinding = true; 4128 ICS.Standard.IsLvalueReference = !isRValRef; 4129 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4130 ICS.Standard.BindsToRvalue = false; 4131 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4132 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4133 ICS.Standard.CopyConstructor = 0; 4134 4135 // Nothing more to do: the inaccessibility/ambiguity check for 4136 // derived-to-base conversions is suppressed when we're 4137 // computing the implicit conversion sequence (C++ 4138 // [over.best.ics]p2). 4139 return ICS; 4140 } 4141 4142 // -- has a class type (i.e., T2 is a class type), where T1 is 4143 // not reference-related to T2, and can be implicitly 4144 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4145 // is reference-compatible with "cv3 T3" 92) (this 4146 // conversion is selected by enumerating the applicable 4147 // conversion functions (13.3.1.6) and choosing the best 4148 // one through overload resolution (13.3)), 4149 if (!SuppressUserConversions && T2->isRecordType() && 4150 !S.RequireCompleteType(DeclLoc, T2, 0) && 4151 RefRelationship == Sema::Ref_Incompatible) { 4152 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4153 Init, T2, /*AllowRvalues=*/false, 4154 AllowExplicit)) 4155 return ICS; 4156 } 4157 } 4158 4159 // -- Otherwise, the reference shall be an lvalue reference to a 4160 // non-volatile const type (i.e., cv1 shall be const), or the reference 4161 // shall be an rvalue reference. 4162 // 4163 // We actually handle one oddity of C++ [over.ics.ref] at this 4164 // point, which is that, due to p2 (which short-circuits reference 4165 // binding by only attempting a simple conversion for non-direct 4166 // bindings) and p3's strange wording, we allow a const volatile 4167 // reference to bind to an rvalue. Hence the check for the presence 4168 // of "const" rather than checking for "const" being the only 4169 // qualifier. 4170 // This is also the point where rvalue references and lvalue inits no longer 4171 // go together. 4172 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4173 return ICS; 4174 4175 // -- If the initializer expression 4176 // 4177 // -- is an xvalue, class prvalue, array prvalue or function 4178 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4179 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4180 (InitCategory.isXValue() || 4181 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4182 (InitCategory.isLValue() && T2->isFunctionType()))) { 4183 ICS.setStandard(); 4184 ICS.Standard.First = ICK_Identity; 4185 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4186 : ObjCConversion? ICK_Compatible_Conversion 4187 : ICK_Identity; 4188 ICS.Standard.Third = ICK_Identity; 4189 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4190 ICS.Standard.setToType(0, T2); 4191 ICS.Standard.setToType(1, T1); 4192 ICS.Standard.setToType(2, T1); 4193 ICS.Standard.ReferenceBinding = true; 4194 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4195 // binding unless we're binding to a class prvalue. 4196 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4197 // allow the use of rvalue references in C++98/03 for the benefit of 4198 // standard library implementors; therefore, we need the xvalue check here. 4199 ICS.Standard.DirectBinding = 4200 S.getLangOpts().CPlusPlus0x || 4201 (InitCategory.isPRValue() && !T2->isRecordType()); 4202 ICS.Standard.IsLvalueReference = !isRValRef; 4203 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4204 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4205 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4206 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4207 ICS.Standard.CopyConstructor = 0; 4208 return ICS; 4209 } 4210 4211 // -- has a class type (i.e., T2 is a class type), where T1 is not 4212 // reference-related to T2, and can be implicitly converted to 4213 // an xvalue, class prvalue, or function lvalue of type 4214 // "cv3 T3", where "cv1 T1" is reference-compatible with 4215 // "cv3 T3", 4216 // 4217 // then the reference is bound to the value of the initializer 4218 // expression in the first case and to the result of the conversion 4219 // in the second case (or, in either case, to an appropriate base 4220 // class subobject). 4221 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4222 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4223 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4224 Init, T2, /*AllowRvalues=*/true, 4225 AllowExplicit)) { 4226 // In the second case, if the reference is an rvalue reference 4227 // and the second standard conversion sequence of the 4228 // user-defined conversion sequence includes an lvalue-to-rvalue 4229 // conversion, the program is ill-formed. 4230 if (ICS.isUserDefined() && isRValRef && 4231 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4232 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4233 4234 return ICS; 4235 } 4236 4237 // -- Otherwise, a temporary of type "cv1 T1" is created and 4238 // initialized from the initializer expression using the 4239 // rules for a non-reference copy initialization (8.5). The 4240 // reference is then bound to the temporary. If T1 is 4241 // reference-related to T2, cv1 must be the same 4242 // cv-qualification as, or greater cv-qualification than, 4243 // cv2; otherwise, the program is ill-formed. 4244 if (RefRelationship == Sema::Ref_Related) { 4245 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4246 // we would be reference-compatible or reference-compatible with 4247 // added qualification. But that wasn't the case, so the reference 4248 // initialization fails. 4249 // 4250 // Note that we only want to check address spaces and cvr-qualifiers here. 4251 // ObjC GC and lifetime qualifiers aren't important. 4252 Qualifiers T1Quals = T1.getQualifiers(); 4253 Qualifiers T2Quals = T2.getQualifiers(); 4254 T1Quals.removeObjCGCAttr(); 4255 T1Quals.removeObjCLifetime(); 4256 T2Quals.removeObjCGCAttr(); 4257 T2Quals.removeObjCLifetime(); 4258 if (!T1Quals.compatiblyIncludes(T2Quals)) 4259 return ICS; 4260 } 4261 4262 // If at least one of the types is a class type, the types are not 4263 // related, and we aren't allowed any user conversions, the 4264 // reference binding fails. This case is important for breaking 4265 // recursion, since TryImplicitConversion below will attempt to 4266 // create a temporary through the use of a copy constructor. 4267 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4268 (T1->isRecordType() || T2->isRecordType())) 4269 return ICS; 4270 4271 // If T1 is reference-related to T2 and the reference is an rvalue 4272 // reference, the initializer expression shall not be an lvalue. 4273 if (RefRelationship >= Sema::Ref_Related && 4274 isRValRef && Init->Classify(S.Context).isLValue()) 4275 return ICS; 4276 4277 // C++ [over.ics.ref]p2: 4278 // When a parameter of reference type is not bound directly to 4279 // an argument expression, the conversion sequence is the one 4280 // required to convert the argument expression to the 4281 // underlying type of the reference according to 4282 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4283 // to copy-initializing a temporary of the underlying type with 4284 // the argument expression. Any difference in top-level 4285 // cv-qualification is subsumed by the initialization itself 4286 // and does not constitute a conversion. 4287 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4288 /*AllowExplicit=*/false, 4289 /*InOverloadResolution=*/false, 4290 /*CStyle=*/false, 4291 /*AllowObjCWritebackConversion=*/false); 4292 4293 // Of course, that's still a reference binding. 4294 if (ICS.isStandard()) { 4295 ICS.Standard.ReferenceBinding = true; 4296 ICS.Standard.IsLvalueReference = !isRValRef; 4297 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4298 ICS.Standard.BindsToRvalue = true; 4299 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4300 ICS.Standard.ObjCLifetimeConversionBinding = false; 4301 } else if (ICS.isUserDefined()) { 4302 // Don't allow rvalue references to bind to lvalues. 4303 if (DeclType->isRValueReferenceType()) { 4304 if (const ReferenceType *RefType 4305 = ICS.UserDefined.ConversionFunction->getResultType() 4306 ->getAs<LValueReferenceType>()) { 4307 if (!RefType->getPointeeType()->isFunctionType()) { 4308 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, 4309 DeclType); 4310 return ICS; 4311 } 4312 } 4313 } 4314 4315 ICS.UserDefined.After.ReferenceBinding = true; 4316 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4317 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType(); 4318 ICS.UserDefined.After.BindsToRvalue = true; 4319 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4320 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4321 } 4322 4323 return ICS; 4324 } 4325 4326 static ImplicitConversionSequence 4327 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4328 bool SuppressUserConversions, 4329 bool InOverloadResolution, 4330 bool AllowObjCWritebackConversion, 4331 bool AllowExplicit = false); 4332 4333 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4334 /// initializer list From. 4335 static ImplicitConversionSequence 4336 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4337 bool SuppressUserConversions, 4338 bool InOverloadResolution, 4339 bool AllowObjCWritebackConversion) { 4340 // C++11 [over.ics.list]p1: 4341 // When an argument is an initializer list, it is not an expression and 4342 // special rules apply for converting it to a parameter type. 4343 4344 ImplicitConversionSequence Result; 4345 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4346 Result.setListInitializationSequence(); 4347 4348 // We need a complete type for what follows. Incomplete types can never be 4349 // initialized from init lists. 4350 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4351 return Result; 4352 4353 // C++11 [over.ics.list]p2: 4354 // If the parameter type is std::initializer_list<X> or "array of X" and 4355 // all the elements can be implicitly converted to X, the implicit 4356 // conversion sequence is the worst conversion necessary to convert an 4357 // element of the list to X. 4358 bool toStdInitializerList = false; 4359 QualType X; 4360 if (ToType->isArrayType()) 4361 X = S.Context.getBaseElementType(ToType); 4362 else 4363 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4364 if (!X.isNull()) { 4365 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4366 Expr *Init = From->getInit(i); 4367 ImplicitConversionSequence ICS = 4368 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4369 InOverloadResolution, 4370 AllowObjCWritebackConversion); 4371 // If a single element isn't convertible, fail. 4372 if (ICS.isBad()) { 4373 Result = ICS; 4374 break; 4375 } 4376 // Otherwise, look for the worst conversion. 4377 if (Result.isBad() || 4378 CompareImplicitConversionSequences(S, ICS, Result) == 4379 ImplicitConversionSequence::Worse) 4380 Result = ICS; 4381 } 4382 4383 // For an empty list, we won't have computed any conversion sequence. 4384 // Introduce the identity conversion sequence. 4385 if (From->getNumInits() == 0) { 4386 Result.setStandard(); 4387 Result.Standard.setAsIdentityConversion(); 4388 Result.Standard.setFromType(ToType); 4389 Result.Standard.setAllToTypes(ToType); 4390 } 4391 4392 Result.setListInitializationSequence(); 4393 Result.setStdInitializerListElement(toStdInitializerList); 4394 return Result; 4395 } 4396 4397 // C++11 [over.ics.list]p3: 4398 // Otherwise, if the parameter is a non-aggregate class X and overload 4399 // resolution chooses a single best constructor [...] the implicit 4400 // conversion sequence is a user-defined conversion sequence. If multiple 4401 // constructors are viable but none is better than the others, the 4402 // implicit conversion sequence is a user-defined conversion sequence. 4403 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4404 // This function can deal with initializer lists. 4405 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4406 /*AllowExplicit=*/false, 4407 InOverloadResolution, /*CStyle=*/false, 4408 AllowObjCWritebackConversion); 4409 Result.setListInitializationSequence(); 4410 return Result; 4411 } 4412 4413 // C++11 [over.ics.list]p4: 4414 // Otherwise, if the parameter has an aggregate type which can be 4415 // initialized from the initializer list [...] the implicit conversion 4416 // sequence is a user-defined conversion sequence. 4417 if (ToType->isAggregateType()) { 4418 // Type is an aggregate, argument is an init list. At this point it comes 4419 // down to checking whether the initialization works. 4420 // FIXME: Find out whether this parameter is consumed or not. 4421 InitializedEntity Entity = 4422 InitializedEntity::InitializeParameter(S.Context, ToType, 4423 /*Consumed=*/false); 4424 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) { 4425 Result.setUserDefined(); 4426 Result.UserDefined.Before.setAsIdentityConversion(); 4427 // Initializer lists don't have a type. 4428 Result.UserDefined.Before.setFromType(QualType()); 4429 Result.UserDefined.Before.setAllToTypes(QualType()); 4430 4431 Result.UserDefined.After.setAsIdentityConversion(); 4432 Result.UserDefined.After.setFromType(ToType); 4433 Result.UserDefined.After.setAllToTypes(ToType); 4434 Result.UserDefined.ConversionFunction = 0; 4435 } 4436 return Result; 4437 } 4438 4439 // C++11 [over.ics.list]p5: 4440 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4441 if (ToType->isReferenceType()) { 4442 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4443 // mention initializer lists in any way. So we go by what list- 4444 // initialization would do and try to extrapolate from that. 4445 4446 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4447 4448 // If the initializer list has a single element that is reference-related 4449 // to the parameter type, we initialize the reference from that. 4450 if (From->getNumInits() == 1) { 4451 Expr *Init = From->getInit(0); 4452 4453 QualType T2 = Init->getType(); 4454 4455 // If the initializer is the address of an overloaded function, try 4456 // to resolve the overloaded function. If all goes well, T2 is the 4457 // type of the resulting function. 4458 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4459 DeclAccessPair Found; 4460 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4461 Init, ToType, false, Found)) 4462 T2 = Fn->getType(); 4463 } 4464 4465 // Compute some basic properties of the types and the initializer. 4466 bool dummy1 = false; 4467 bool dummy2 = false; 4468 bool dummy3 = false; 4469 Sema::ReferenceCompareResult RefRelationship 4470 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4471 dummy2, dummy3); 4472 4473 if (RefRelationship >= Sema::Ref_Related) 4474 return TryReferenceInit(S, Init, ToType, 4475 /*FIXME:*/From->getLocStart(), 4476 SuppressUserConversions, 4477 /*AllowExplicit=*/false); 4478 } 4479 4480 // Otherwise, we bind the reference to a temporary created from the 4481 // initializer list. 4482 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4483 InOverloadResolution, 4484 AllowObjCWritebackConversion); 4485 if (Result.isFailure()) 4486 return Result; 4487 assert(!Result.isEllipsis() && 4488 "Sub-initialization cannot result in ellipsis conversion."); 4489 4490 // Can we even bind to a temporary? 4491 if (ToType->isRValueReferenceType() || 4492 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4493 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4494 Result.UserDefined.After; 4495 SCS.ReferenceBinding = true; 4496 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4497 SCS.BindsToRvalue = true; 4498 SCS.BindsToFunctionLvalue = false; 4499 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4500 SCS.ObjCLifetimeConversionBinding = false; 4501 } else 4502 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4503 From, ToType); 4504 return Result; 4505 } 4506 4507 // C++11 [over.ics.list]p6: 4508 // Otherwise, if the parameter type is not a class: 4509 if (!ToType->isRecordType()) { 4510 // - if the initializer list has one element, the implicit conversion 4511 // sequence is the one required to convert the element to the 4512 // parameter type. 4513 unsigned NumInits = From->getNumInits(); 4514 if (NumInits == 1) 4515 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4516 SuppressUserConversions, 4517 InOverloadResolution, 4518 AllowObjCWritebackConversion); 4519 // - if the initializer list has no elements, the implicit conversion 4520 // sequence is the identity conversion. 4521 else if (NumInits == 0) { 4522 Result.setStandard(); 4523 Result.Standard.setAsIdentityConversion(); 4524 Result.Standard.setFromType(ToType); 4525 Result.Standard.setAllToTypes(ToType); 4526 } 4527 Result.setListInitializationSequence(); 4528 return Result; 4529 } 4530 4531 // C++11 [over.ics.list]p7: 4532 // In all cases other than those enumerated above, no conversion is possible 4533 return Result; 4534 } 4535 4536 /// TryCopyInitialization - Try to copy-initialize a value of type 4537 /// ToType from the expression From. Return the implicit conversion 4538 /// sequence required to pass this argument, which may be a bad 4539 /// conversion sequence (meaning that the argument cannot be passed to 4540 /// a parameter of this type). If @p SuppressUserConversions, then we 4541 /// do not permit any user-defined conversion sequences. 4542 static ImplicitConversionSequence 4543 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4544 bool SuppressUserConversions, 4545 bool InOverloadResolution, 4546 bool AllowObjCWritebackConversion, 4547 bool AllowExplicit) { 4548 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4549 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4550 InOverloadResolution,AllowObjCWritebackConversion); 4551 4552 if (ToType->isReferenceType()) 4553 return TryReferenceInit(S, From, ToType, 4554 /*FIXME:*/From->getLocStart(), 4555 SuppressUserConversions, 4556 AllowExplicit); 4557 4558 return TryImplicitConversion(S, From, ToType, 4559 SuppressUserConversions, 4560 /*AllowExplicit=*/false, 4561 InOverloadResolution, 4562 /*CStyle=*/false, 4563 AllowObjCWritebackConversion); 4564 } 4565 4566 static bool TryCopyInitialization(const CanQualType FromQTy, 4567 const CanQualType ToQTy, 4568 Sema &S, 4569 SourceLocation Loc, 4570 ExprValueKind FromVK) { 4571 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4572 ImplicitConversionSequence ICS = 4573 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4574 4575 return !ICS.isBad(); 4576 } 4577 4578 /// TryObjectArgumentInitialization - Try to initialize the object 4579 /// parameter of the given member function (@c Method) from the 4580 /// expression @p From. 4581 static ImplicitConversionSequence 4582 TryObjectArgumentInitialization(Sema &S, QualType OrigFromType, 4583 Expr::Classification FromClassification, 4584 CXXMethodDecl *Method, 4585 CXXRecordDecl *ActingContext) { 4586 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4587 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4588 // const volatile object. 4589 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4590 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4591 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4592 4593 // Set up the conversion sequence as a "bad" conversion, to allow us 4594 // to exit early. 4595 ImplicitConversionSequence ICS; 4596 4597 // We need to have an object of class type. 4598 QualType FromType = OrigFromType; 4599 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4600 FromType = PT->getPointeeType(); 4601 4602 // When we had a pointer, it's implicitly dereferenced, so we 4603 // better have an lvalue. 4604 assert(FromClassification.isLValue()); 4605 } 4606 4607 assert(FromType->isRecordType()); 4608 4609 // C++0x [over.match.funcs]p4: 4610 // For non-static member functions, the type of the implicit object 4611 // parameter is 4612 // 4613 // - "lvalue reference to cv X" for functions declared without a 4614 // ref-qualifier or with the & ref-qualifier 4615 // - "rvalue reference to cv X" for functions declared with the && 4616 // ref-qualifier 4617 // 4618 // where X is the class of which the function is a member and cv is the 4619 // cv-qualification on the member function declaration. 4620 // 4621 // However, when finding an implicit conversion sequence for the argument, we 4622 // are not allowed to create temporaries or perform user-defined conversions 4623 // (C++ [over.match.funcs]p5). We perform a simplified version of 4624 // reference binding here, that allows class rvalues to bind to 4625 // non-constant references. 4626 4627 // First check the qualifiers. 4628 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4629 if (ImplicitParamType.getCVRQualifiers() 4630 != FromTypeCanon.getLocalCVRQualifiers() && 4631 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4632 ICS.setBad(BadConversionSequence::bad_qualifiers, 4633 OrigFromType, ImplicitParamType); 4634 return ICS; 4635 } 4636 4637 // Check that we have either the same type or a derived type. It 4638 // affects the conversion rank. 4639 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4640 ImplicitConversionKind SecondKind; 4641 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4642 SecondKind = ICK_Identity; 4643 } else if (S.IsDerivedFrom(FromType, ClassType)) 4644 SecondKind = ICK_Derived_To_Base; 4645 else { 4646 ICS.setBad(BadConversionSequence::unrelated_class, 4647 FromType, ImplicitParamType); 4648 return ICS; 4649 } 4650 4651 // Check the ref-qualifier. 4652 switch (Method->getRefQualifier()) { 4653 case RQ_None: 4654 // Do nothing; we don't care about lvalueness or rvalueness. 4655 break; 4656 4657 case RQ_LValue: 4658 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4659 // non-const lvalue reference cannot bind to an rvalue 4660 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4661 ImplicitParamType); 4662 return ICS; 4663 } 4664 break; 4665 4666 case RQ_RValue: 4667 if (!FromClassification.isRValue()) { 4668 // rvalue reference cannot bind to an lvalue 4669 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4670 ImplicitParamType); 4671 return ICS; 4672 } 4673 break; 4674 } 4675 4676 // Success. Mark this as a reference binding. 4677 ICS.setStandard(); 4678 ICS.Standard.setAsIdentityConversion(); 4679 ICS.Standard.Second = SecondKind; 4680 ICS.Standard.setFromType(FromType); 4681 ICS.Standard.setAllToTypes(ImplicitParamType); 4682 ICS.Standard.ReferenceBinding = true; 4683 ICS.Standard.DirectBinding = true; 4684 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4685 ICS.Standard.BindsToFunctionLvalue = false; 4686 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4687 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4688 = (Method->getRefQualifier() == RQ_None); 4689 return ICS; 4690 } 4691 4692 /// PerformObjectArgumentInitialization - Perform initialization of 4693 /// the implicit object parameter for the given Method with the given 4694 /// expression. 4695 ExprResult 4696 Sema::PerformObjectArgumentInitialization(Expr *From, 4697 NestedNameSpecifier *Qualifier, 4698 NamedDecl *FoundDecl, 4699 CXXMethodDecl *Method) { 4700 QualType FromRecordType, DestType; 4701 QualType ImplicitParamRecordType = 4702 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4703 4704 Expr::Classification FromClassification; 4705 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4706 FromRecordType = PT->getPointeeType(); 4707 DestType = Method->getThisType(Context); 4708 FromClassification = Expr::Classification::makeSimpleLValue(); 4709 } else { 4710 FromRecordType = From->getType(); 4711 DestType = ImplicitParamRecordType; 4712 FromClassification = From->Classify(Context); 4713 } 4714 4715 // Note that we always use the true parent context when performing 4716 // the actual argument initialization. 4717 ImplicitConversionSequence ICS 4718 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification, 4719 Method, Method->getParent()); 4720 if (ICS.isBad()) { 4721 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4722 Qualifiers FromQs = FromRecordType.getQualifiers(); 4723 Qualifiers ToQs = DestType.getQualifiers(); 4724 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4725 if (CVR) { 4726 Diag(From->getLocStart(), 4727 diag::err_member_function_call_bad_cvr) 4728 << Method->getDeclName() << FromRecordType << (CVR - 1) 4729 << From->getSourceRange(); 4730 Diag(Method->getLocation(), diag::note_previous_decl) 4731 << Method->getDeclName(); 4732 return ExprError(); 4733 } 4734 } 4735 4736 return Diag(From->getLocStart(), 4737 diag::err_implicit_object_parameter_init) 4738 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4739 } 4740 4741 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4742 ExprResult FromRes = 4743 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4744 if (FromRes.isInvalid()) 4745 return ExprError(); 4746 From = FromRes.take(); 4747 } 4748 4749 if (!Context.hasSameType(From->getType(), DestType)) 4750 From = ImpCastExprToType(From, DestType, CK_NoOp, 4751 From->getValueKind()).take(); 4752 return Owned(From); 4753 } 4754 4755 /// TryContextuallyConvertToBool - Attempt to contextually convert the 4756 /// expression From to bool (C++0x [conv]p3). 4757 static ImplicitConversionSequence 4758 TryContextuallyConvertToBool(Sema &S, Expr *From) { 4759 // FIXME: This is pretty broken. 4760 return TryImplicitConversion(S, From, S.Context.BoolTy, 4761 // FIXME: Are these flags correct? 4762 /*SuppressUserConversions=*/false, 4763 /*AllowExplicit=*/true, 4764 /*InOverloadResolution=*/false, 4765 /*CStyle=*/false, 4766 /*AllowObjCWritebackConversion=*/false); 4767 } 4768 4769 /// PerformContextuallyConvertToBool - Perform a contextual conversion 4770 /// of the expression From to bool (C++0x [conv]p3). 4771 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4772 if (checkPlaceholderForOverload(*this, From)) 4773 return ExprError(); 4774 4775 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4776 if (!ICS.isBad()) 4777 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4778 4779 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4780 return Diag(From->getLocStart(), 4781 diag::err_typecheck_bool_condition) 4782 << From->getType() << From->getSourceRange(); 4783 return ExprError(); 4784 } 4785 4786 /// Check that the specified conversion is permitted in a converted constant 4787 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 4788 /// is acceptable. 4789 static bool CheckConvertedConstantConversions(Sema &S, 4790 StandardConversionSequence &SCS) { 4791 // Since we know that the target type is an integral or unscoped enumeration 4792 // type, most conversion kinds are impossible. All possible First and Third 4793 // conversions are fine. 4794 switch (SCS.Second) { 4795 case ICK_Identity: 4796 case ICK_Integral_Promotion: 4797 case ICK_Integral_Conversion: 4798 return true; 4799 4800 case ICK_Boolean_Conversion: 4801 // Conversion from an integral or unscoped enumeration type to bool is 4802 // classified as ICK_Boolean_Conversion, but it's also an integral 4803 // conversion, so it's permitted in a converted constant expression. 4804 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4805 SCS.getToType(2)->isBooleanType(); 4806 4807 case ICK_Floating_Integral: 4808 case ICK_Complex_Real: 4809 return false; 4810 4811 case ICK_Lvalue_To_Rvalue: 4812 case ICK_Array_To_Pointer: 4813 case ICK_Function_To_Pointer: 4814 case ICK_NoReturn_Adjustment: 4815 case ICK_Qualification: 4816 case ICK_Compatible_Conversion: 4817 case ICK_Vector_Conversion: 4818 case ICK_Vector_Splat: 4819 case ICK_Derived_To_Base: 4820 case ICK_Pointer_Conversion: 4821 case ICK_Pointer_Member: 4822 case ICK_Block_Pointer_Conversion: 4823 case ICK_Writeback_Conversion: 4824 case ICK_Floating_Promotion: 4825 case ICK_Complex_Promotion: 4826 case ICK_Complex_Conversion: 4827 case ICK_Floating_Conversion: 4828 case ICK_TransparentUnionConversion: 4829 llvm_unreachable("unexpected second conversion kind"); 4830 4831 case ICK_Num_Conversion_Kinds: 4832 break; 4833 } 4834 4835 llvm_unreachable("unknown conversion kind"); 4836 } 4837 4838 /// CheckConvertedConstantExpression - Check that the expression From is a 4839 /// converted constant expression of type T, perform the conversion and produce 4840 /// the converted expression, per C++11 [expr.const]p3. 4841 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 4842 llvm::APSInt &Value, 4843 CCEKind CCE) { 4844 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11"); 4845 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 4846 4847 if (checkPlaceholderForOverload(*this, From)) 4848 return ExprError(); 4849 4850 // C++11 [expr.const]p3 with proposed wording fixes: 4851 // A converted constant expression of type T is a core constant expression, 4852 // implicitly converted to a prvalue of type T, where the converted 4853 // expression is a literal constant expression and the implicit conversion 4854 // sequence contains only user-defined conversions, lvalue-to-rvalue 4855 // conversions, integral promotions, and integral conversions other than 4856 // narrowing conversions. 4857 ImplicitConversionSequence ICS = 4858 TryImplicitConversion(From, T, 4859 /*SuppressUserConversions=*/false, 4860 /*AllowExplicit=*/false, 4861 /*InOverloadResolution=*/false, 4862 /*CStyle=*/false, 4863 /*AllowObjcWritebackConversion=*/false); 4864 StandardConversionSequence *SCS = 0; 4865 switch (ICS.getKind()) { 4866 case ImplicitConversionSequence::StandardConversion: 4867 if (!CheckConvertedConstantConversions(*this, ICS.Standard)) 4868 return Diag(From->getLocStart(), 4869 diag::err_typecheck_converted_constant_expression_disallowed) 4870 << From->getType() << From->getSourceRange() << T; 4871 SCS = &ICS.Standard; 4872 break; 4873 case ImplicitConversionSequence::UserDefinedConversion: 4874 // We are converting from class type to an integral or enumeration type, so 4875 // the Before sequence must be trivial. 4876 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After)) 4877 return Diag(From->getLocStart(), 4878 diag::err_typecheck_converted_constant_expression_disallowed) 4879 << From->getType() << From->getSourceRange() << T; 4880 SCS = &ICS.UserDefined.After; 4881 break; 4882 case ImplicitConversionSequence::AmbiguousConversion: 4883 case ImplicitConversionSequence::BadConversion: 4884 if (!DiagnoseMultipleUserDefinedConversion(From, T)) 4885 return Diag(From->getLocStart(), 4886 diag::err_typecheck_converted_constant_expression) 4887 << From->getType() << From->getSourceRange() << T; 4888 return ExprError(); 4889 4890 case ImplicitConversionSequence::EllipsisConversion: 4891 llvm_unreachable("ellipsis conversion in converted constant expression"); 4892 } 4893 4894 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting); 4895 if (Result.isInvalid()) 4896 return Result; 4897 4898 // Check for a narrowing implicit conversion. 4899 APValue PreNarrowingValue; 4900 QualType PreNarrowingType; 4901 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue, 4902 PreNarrowingType)) { 4903 case NK_Variable_Narrowing: 4904 // Implicit conversion to a narrower type, and the value is not a constant 4905 // expression. We'll diagnose this in a moment. 4906 case NK_Not_Narrowing: 4907 break; 4908 4909 case NK_Constant_Narrowing: 4910 Diag(From->getLocStart(), 4911 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4912 diag::err_cce_narrowing) 4913 << CCE << /*Constant*/1 4914 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T; 4915 break; 4916 4917 case NK_Type_Narrowing: 4918 Diag(From->getLocStart(), 4919 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4920 diag::err_cce_narrowing) 4921 << CCE << /*Constant*/0 << From->getType() << T; 4922 break; 4923 } 4924 4925 // Check the expression is a constant expression. 4926 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 4927 Expr::EvalResult Eval; 4928 Eval.Diag = &Notes; 4929 4930 if (!Result.get()->EvaluateAsRValue(Eval, Context)) { 4931 // The expression can't be folded, so we can't keep it at this position in 4932 // the AST. 4933 Result = ExprError(); 4934 } else { 4935 Value = Eval.Val.getInt(); 4936 4937 if (Notes.empty()) { 4938 // It's a constant expression. 4939 return Result; 4940 } 4941 } 4942 4943 // It's not a constant expression. Produce an appropriate diagnostic. 4944 if (Notes.size() == 1 && 4945 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 4946 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 4947 else { 4948 Diag(From->getLocStart(), diag::err_expr_not_cce) 4949 << CCE << From->getSourceRange(); 4950 for (unsigned I = 0; I < Notes.size(); ++I) 4951 Diag(Notes[I].first, Notes[I].second); 4952 } 4953 return Result; 4954 } 4955 4956 /// dropPointerConversions - If the given standard conversion sequence 4957 /// involves any pointer conversions, remove them. This may change 4958 /// the result type of the conversion sequence. 4959 static void dropPointerConversion(StandardConversionSequence &SCS) { 4960 if (SCS.Second == ICK_Pointer_Conversion) { 4961 SCS.Second = ICK_Identity; 4962 SCS.Third = ICK_Identity; 4963 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 4964 } 4965 } 4966 4967 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 4968 /// convert the expression From to an Objective-C pointer type. 4969 static ImplicitConversionSequence 4970 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 4971 // Do an implicit conversion to 'id'. 4972 QualType Ty = S.Context.getObjCIdType(); 4973 ImplicitConversionSequence ICS 4974 = TryImplicitConversion(S, From, Ty, 4975 // FIXME: Are these flags correct? 4976 /*SuppressUserConversions=*/false, 4977 /*AllowExplicit=*/true, 4978 /*InOverloadResolution=*/false, 4979 /*CStyle=*/false, 4980 /*AllowObjCWritebackConversion=*/false); 4981 4982 // Strip off any final conversions to 'id'. 4983 switch (ICS.getKind()) { 4984 case ImplicitConversionSequence::BadConversion: 4985 case ImplicitConversionSequence::AmbiguousConversion: 4986 case ImplicitConversionSequence::EllipsisConversion: 4987 break; 4988 4989 case ImplicitConversionSequence::UserDefinedConversion: 4990 dropPointerConversion(ICS.UserDefined.After); 4991 break; 4992 4993 case ImplicitConversionSequence::StandardConversion: 4994 dropPointerConversion(ICS.Standard); 4995 break; 4996 } 4997 4998 return ICS; 4999 } 5000 5001 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5002 /// conversion of the expression From to an Objective-C pointer type. 5003 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5004 if (checkPlaceholderForOverload(*this, From)) 5005 return ExprError(); 5006 5007 QualType Ty = Context.getObjCIdType(); 5008 ImplicitConversionSequence ICS = 5009 TryContextuallyConvertToObjCPointer(*this, From); 5010 if (!ICS.isBad()) 5011 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5012 return ExprError(); 5013 } 5014 5015 /// Determine whether the provided type is an integral type, or an enumeration 5016 /// type of a permitted flavor. 5017 static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) { 5018 return AllowScopedEnum ? T->isIntegralOrEnumerationType() 5019 : T->isIntegralOrUnscopedEnumerationType(); 5020 } 5021 5022 /// \brief Attempt to convert the given expression to an integral or 5023 /// enumeration type. 5024 /// 5025 /// This routine will attempt to convert an expression of class type to an 5026 /// integral or enumeration type, if that class type only has a single 5027 /// conversion to an integral or enumeration type. 5028 /// 5029 /// \param Loc The source location of the construct that requires the 5030 /// conversion. 5031 /// 5032 /// \param From The expression we're converting from. 5033 /// 5034 /// \param Diagnoser Used to output any diagnostics. 5035 /// 5036 /// \param AllowScopedEnumerations Specifies whether conversions to scoped 5037 /// enumerations should be considered. 5038 /// 5039 /// \returns The expression, converted to an integral or enumeration type if 5040 /// successful. 5041 ExprResult 5042 Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From, 5043 ICEConvertDiagnoser &Diagnoser, 5044 bool AllowScopedEnumerations) { 5045 // We can't perform any more checking for type-dependent expressions. 5046 if (From->isTypeDependent()) 5047 return Owned(From); 5048 5049 // Process placeholders immediately. 5050 if (From->hasPlaceholderType()) { 5051 ExprResult result = CheckPlaceholderExpr(From); 5052 if (result.isInvalid()) return result; 5053 From = result.take(); 5054 } 5055 5056 // If the expression already has integral or enumeration type, we're golden. 5057 QualType T = From->getType(); 5058 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations)) 5059 return DefaultLvalueConversion(From); 5060 5061 // FIXME: Check for missing '()' if T is a function type? 5062 5063 // If we don't have a class type in C++, there's no way we can get an 5064 // expression of integral or enumeration type. 5065 const RecordType *RecordTy = T->getAs<RecordType>(); 5066 if (!RecordTy || !getLangOpts().CPlusPlus) { 5067 if (!Diagnoser.Suppress) 5068 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange(); 5069 return Owned(From); 5070 } 5071 5072 // We must have a complete class type. 5073 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5074 ICEConvertDiagnoser &Diagnoser; 5075 Expr *From; 5076 5077 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From) 5078 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {} 5079 5080 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 5081 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5082 } 5083 } IncompleteDiagnoser(Diagnoser, From); 5084 5085 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5086 return Owned(From); 5087 5088 // Look for a conversion to an integral or enumeration type. 5089 UnresolvedSet<4> ViableConversions; 5090 UnresolvedSet<4> ExplicitConversions; 5091 const UnresolvedSetImpl *Conversions 5092 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5093 5094 bool HadMultipleCandidates = (Conversions->size() > 1); 5095 5096 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 5097 E = Conversions->end(); 5098 I != E; 5099 ++I) { 5100 if (CXXConversionDecl *Conversion 5101 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) { 5102 if (isIntegralOrEnumerationType( 5103 Conversion->getConversionType().getNonReferenceType(), 5104 AllowScopedEnumerations)) { 5105 if (Conversion->isExplicit()) 5106 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5107 else 5108 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5109 } 5110 } 5111 } 5112 5113 switch (ViableConversions.size()) { 5114 case 0: 5115 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) { 5116 DeclAccessPair Found = ExplicitConversions[0]; 5117 CXXConversionDecl *Conversion 5118 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5119 5120 // The user probably meant to invoke the given explicit 5121 // conversion; use it. 5122 QualType ConvTy 5123 = Conversion->getConversionType().getNonReferenceType(); 5124 std::string TypeStr; 5125 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy()); 5126 5127 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy) 5128 << FixItHint::CreateInsertion(From->getLocStart(), 5129 "static_cast<" + TypeStr + ">(") 5130 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()), 5131 ")"); 5132 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy); 5133 5134 // If we aren't in a SFINAE context, build a call to the 5135 // explicit conversion function. 5136 if (isSFINAEContext()) 5137 return ExprError(); 5138 5139 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5140 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion, 5141 HadMultipleCandidates); 5142 if (Result.isInvalid()) 5143 return ExprError(); 5144 // Record usage of conversion in an implicit cast. 5145 From = ImplicitCastExpr::Create(Context, Result.get()->getType(), 5146 CK_UserDefinedConversion, 5147 Result.get(), 0, 5148 Result.get()->getValueKind()); 5149 } 5150 5151 // We'll complain below about a non-integral condition type. 5152 break; 5153 5154 case 1: { 5155 // Apply this conversion. 5156 DeclAccessPair Found = ViableConversions[0]; 5157 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5158 5159 CXXConversionDecl *Conversion 5160 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5161 QualType ConvTy 5162 = Conversion->getConversionType().getNonReferenceType(); 5163 if (!Diagnoser.SuppressConversion) { 5164 if (isSFINAEContext()) 5165 return ExprError(); 5166 5167 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy) 5168 << From->getSourceRange(); 5169 } 5170 5171 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion, 5172 HadMultipleCandidates); 5173 if (Result.isInvalid()) 5174 return ExprError(); 5175 // Record usage of conversion in an implicit cast. 5176 From = ImplicitCastExpr::Create(Context, Result.get()->getType(), 5177 CK_UserDefinedConversion, 5178 Result.get(), 0, 5179 Result.get()->getValueKind()); 5180 break; 5181 } 5182 5183 default: 5184 if (Diagnoser.Suppress) 5185 return ExprError(); 5186 5187 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange(); 5188 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5189 CXXConversionDecl *Conv 5190 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5191 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5192 Diagnoser.noteAmbiguous(*this, Conv, ConvTy); 5193 } 5194 return Owned(From); 5195 } 5196 5197 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) && 5198 !Diagnoser.Suppress) { 5199 Diagnoser.diagnoseNotInt(*this, Loc, From->getType()) 5200 << From->getSourceRange(); 5201 } 5202 5203 return DefaultLvalueConversion(From); 5204 } 5205 5206 /// AddOverloadCandidate - Adds the given function to the set of 5207 /// candidate functions, using the given function call arguments. If 5208 /// @p SuppressUserConversions, then don't allow user-defined 5209 /// conversions via constructors or conversion operators. 5210 /// 5211 /// \param PartialOverloading true if we are performing "partial" overloading 5212 /// based on an incomplete set of function arguments. This feature is used by 5213 /// code completion. 5214 void 5215 Sema::AddOverloadCandidate(FunctionDecl *Function, 5216 DeclAccessPair FoundDecl, 5217 llvm::ArrayRef<Expr *> Args, 5218 OverloadCandidateSet& CandidateSet, 5219 bool SuppressUserConversions, 5220 bool PartialOverloading, 5221 bool AllowExplicit) { 5222 const FunctionProtoType* Proto 5223 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5224 assert(Proto && "Functions without a prototype cannot be overloaded"); 5225 assert(!Function->getDescribedFunctionTemplate() && 5226 "Use AddTemplateOverloadCandidate for function templates"); 5227 5228 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5229 if (!isa<CXXConstructorDecl>(Method)) { 5230 // If we get here, it's because we're calling a member function 5231 // that is named without a member access expression (e.g., 5232 // "this->f") that was either written explicitly or created 5233 // implicitly. This can happen with a qualified call to a member 5234 // function, e.g., X::f(). We use an empty type for the implied 5235 // object argument (C++ [over.call.func]p3), and the acting context 5236 // is irrelevant. 5237 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5238 QualType(), Expr::Classification::makeSimpleLValue(), 5239 Args, CandidateSet, SuppressUserConversions); 5240 return; 5241 } 5242 // We treat a constructor like a non-member function, since its object 5243 // argument doesn't participate in overload resolution. 5244 } 5245 5246 if (!CandidateSet.isNewCandidate(Function)) 5247 return; 5248 5249 // Overload resolution is always an unevaluated context. 5250 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5251 5252 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){ 5253 // C++ [class.copy]p3: 5254 // A member function template is never instantiated to perform the copy 5255 // of a class object to an object of its class type. 5256 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5257 if (Args.size() == 1 && 5258 Constructor->isSpecializationCopyingObject() && 5259 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5260 IsDerivedFrom(Args[0]->getType(), ClassType))) 5261 return; 5262 } 5263 5264 // Add this candidate 5265 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5266 Candidate.FoundDecl = FoundDecl; 5267 Candidate.Function = Function; 5268 Candidate.Viable = true; 5269 Candidate.IsSurrogate = false; 5270 Candidate.IgnoreObjectArgument = false; 5271 Candidate.ExplicitCallArguments = Args.size(); 5272 5273 unsigned NumArgsInProto = Proto->getNumArgs(); 5274 5275 // (C++ 13.3.2p2): A candidate function having fewer than m 5276 // parameters is viable only if it has an ellipsis in its parameter 5277 // list (8.3.5). 5278 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto && 5279 !Proto->isVariadic()) { 5280 Candidate.Viable = false; 5281 Candidate.FailureKind = ovl_fail_too_many_arguments; 5282 return; 5283 } 5284 5285 // (C++ 13.3.2p2): A candidate function having more than m parameters 5286 // is viable only if the (m+1)st parameter has a default argument 5287 // (8.3.6). For the purposes of overload resolution, the 5288 // parameter list is truncated on the right, so that there are 5289 // exactly m parameters. 5290 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5291 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5292 // Not enough arguments. 5293 Candidate.Viable = false; 5294 Candidate.FailureKind = ovl_fail_too_few_arguments; 5295 return; 5296 } 5297 5298 // (CUDA B.1): Check for invalid calls between targets. 5299 if (getLangOpts().CUDA) 5300 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5301 if (CheckCUDATarget(Caller, Function)) { 5302 Candidate.Viable = false; 5303 Candidate.FailureKind = ovl_fail_bad_target; 5304 return; 5305 } 5306 5307 // Determine the implicit conversion sequences for each of the 5308 // arguments. 5309 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5310 if (ArgIdx < NumArgsInProto) { 5311 // (C++ 13.3.2p3): for F to be a viable function, there shall 5312 // exist for each argument an implicit conversion sequence 5313 // (13.3.3.1) that converts that argument to the corresponding 5314 // parameter of F. 5315 QualType ParamType = Proto->getArgType(ArgIdx); 5316 Candidate.Conversions[ArgIdx] 5317 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5318 SuppressUserConversions, 5319 /*InOverloadResolution=*/true, 5320 /*AllowObjCWritebackConversion=*/ 5321 getLangOpts().ObjCAutoRefCount, 5322 AllowExplicit); 5323 if (Candidate.Conversions[ArgIdx].isBad()) { 5324 Candidate.Viable = false; 5325 Candidate.FailureKind = ovl_fail_bad_conversion; 5326 break; 5327 } 5328 } else { 5329 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5330 // argument for which there is no corresponding parameter is 5331 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5332 Candidate.Conversions[ArgIdx].setEllipsis(); 5333 } 5334 } 5335 } 5336 5337 /// \brief Add all of the function declarations in the given function set to 5338 /// the overload canddiate set. 5339 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5340 llvm::ArrayRef<Expr *> Args, 5341 OverloadCandidateSet& CandidateSet, 5342 bool SuppressUserConversions, 5343 TemplateArgumentListInfo *ExplicitTemplateArgs) { 5344 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5345 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5346 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5347 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5348 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5349 cast<CXXMethodDecl>(FD)->getParent(), 5350 Args[0]->getType(), Args[0]->Classify(Context), 5351 Args.slice(1), CandidateSet, 5352 SuppressUserConversions); 5353 else 5354 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5355 SuppressUserConversions); 5356 } else { 5357 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5358 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5359 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5360 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5361 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5362 ExplicitTemplateArgs, 5363 Args[0]->getType(), 5364 Args[0]->Classify(Context), Args.slice(1), 5365 CandidateSet, SuppressUserConversions); 5366 else 5367 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5368 ExplicitTemplateArgs, Args, 5369 CandidateSet, SuppressUserConversions); 5370 } 5371 } 5372 } 5373 5374 /// AddMethodCandidate - Adds a named decl (which is some kind of 5375 /// method) as a method candidate to the given overload set. 5376 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5377 QualType ObjectType, 5378 Expr::Classification ObjectClassification, 5379 Expr **Args, unsigned NumArgs, 5380 OverloadCandidateSet& CandidateSet, 5381 bool SuppressUserConversions) { 5382 NamedDecl *Decl = FoundDecl.getDecl(); 5383 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5384 5385 if (isa<UsingShadowDecl>(Decl)) 5386 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5387 5388 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5389 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5390 "Expected a member function template"); 5391 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5392 /*ExplicitArgs*/ 0, 5393 ObjectType, ObjectClassification, 5394 llvm::makeArrayRef(Args, NumArgs), CandidateSet, 5395 SuppressUserConversions); 5396 } else { 5397 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5398 ObjectType, ObjectClassification, 5399 llvm::makeArrayRef(Args, NumArgs), 5400 CandidateSet, SuppressUserConversions); 5401 } 5402 } 5403 5404 /// AddMethodCandidate - Adds the given C++ member function to the set 5405 /// of candidate functions, using the given function call arguments 5406 /// and the object argument (@c Object). For example, in a call 5407 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5408 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5409 /// allow user-defined conversions via constructors or conversion 5410 /// operators. 5411 void 5412 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5413 CXXRecordDecl *ActingContext, QualType ObjectType, 5414 Expr::Classification ObjectClassification, 5415 llvm::ArrayRef<Expr *> Args, 5416 OverloadCandidateSet& CandidateSet, 5417 bool SuppressUserConversions) { 5418 const FunctionProtoType* Proto 5419 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5420 assert(Proto && "Methods without a prototype cannot be overloaded"); 5421 assert(!isa<CXXConstructorDecl>(Method) && 5422 "Use AddOverloadCandidate for constructors"); 5423 5424 if (!CandidateSet.isNewCandidate(Method)) 5425 return; 5426 5427 // Overload resolution is always an unevaluated context. 5428 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5429 5430 // Add this candidate 5431 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5432 Candidate.FoundDecl = FoundDecl; 5433 Candidate.Function = Method; 5434 Candidate.IsSurrogate = false; 5435 Candidate.IgnoreObjectArgument = false; 5436 Candidate.ExplicitCallArguments = Args.size(); 5437 5438 unsigned NumArgsInProto = Proto->getNumArgs(); 5439 5440 // (C++ 13.3.2p2): A candidate function having fewer than m 5441 // parameters is viable only if it has an ellipsis in its parameter 5442 // list (8.3.5). 5443 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5444 Candidate.Viable = false; 5445 Candidate.FailureKind = ovl_fail_too_many_arguments; 5446 return; 5447 } 5448 5449 // (C++ 13.3.2p2): A candidate function having more than m parameters 5450 // is viable only if the (m+1)st parameter has a default argument 5451 // (8.3.6). For the purposes of overload resolution, the 5452 // parameter list is truncated on the right, so that there are 5453 // exactly m parameters. 5454 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 5455 if (Args.size() < MinRequiredArgs) { 5456 // Not enough arguments. 5457 Candidate.Viable = false; 5458 Candidate.FailureKind = ovl_fail_too_few_arguments; 5459 return; 5460 } 5461 5462 Candidate.Viable = true; 5463 5464 if (Method->isStatic() || ObjectType.isNull()) 5465 // The implicit object argument is ignored. 5466 Candidate.IgnoreObjectArgument = true; 5467 else { 5468 // Determine the implicit conversion sequence for the object 5469 // parameter. 5470 Candidate.Conversions[0] 5471 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 5472 Method, ActingContext); 5473 if (Candidate.Conversions[0].isBad()) { 5474 Candidate.Viable = false; 5475 Candidate.FailureKind = ovl_fail_bad_conversion; 5476 return; 5477 } 5478 } 5479 5480 // Determine the implicit conversion sequences for each of the 5481 // arguments. 5482 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5483 if (ArgIdx < NumArgsInProto) { 5484 // (C++ 13.3.2p3): for F to be a viable function, there shall 5485 // exist for each argument an implicit conversion sequence 5486 // (13.3.3.1) that converts that argument to the corresponding 5487 // parameter of F. 5488 QualType ParamType = Proto->getArgType(ArgIdx); 5489 Candidate.Conversions[ArgIdx + 1] 5490 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5491 SuppressUserConversions, 5492 /*InOverloadResolution=*/true, 5493 /*AllowObjCWritebackConversion=*/ 5494 getLangOpts().ObjCAutoRefCount); 5495 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5496 Candidate.Viable = false; 5497 Candidate.FailureKind = ovl_fail_bad_conversion; 5498 break; 5499 } 5500 } else { 5501 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5502 // argument for which there is no corresponding parameter is 5503 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5504 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5505 } 5506 } 5507 } 5508 5509 /// \brief Add a C++ member function template as a candidate to the candidate 5510 /// set, using template argument deduction to produce an appropriate member 5511 /// function template specialization. 5512 void 5513 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 5514 DeclAccessPair FoundDecl, 5515 CXXRecordDecl *ActingContext, 5516 TemplateArgumentListInfo *ExplicitTemplateArgs, 5517 QualType ObjectType, 5518 Expr::Classification ObjectClassification, 5519 llvm::ArrayRef<Expr *> Args, 5520 OverloadCandidateSet& CandidateSet, 5521 bool SuppressUserConversions) { 5522 if (!CandidateSet.isNewCandidate(MethodTmpl)) 5523 return; 5524 5525 // C++ [over.match.funcs]p7: 5526 // In each case where a candidate is a function template, candidate 5527 // function template specializations are generated using template argument 5528 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5529 // candidate functions in the usual way.113) A given name can refer to one 5530 // or more function templates and also to a set of overloaded non-template 5531 // functions. In such a case, the candidate functions generated from each 5532 // function template are combined with the set of non-template candidate 5533 // functions. 5534 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 5535 FunctionDecl *Specialization = 0; 5536 if (TemplateDeductionResult Result 5537 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 5538 Specialization, Info)) { 5539 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5540 Candidate.FoundDecl = FoundDecl; 5541 Candidate.Function = MethodTmpl->getTemplatedDecl(); 5542 Candidate.Viable = false; 5543 Candidate.FailureKind = ovl_fail_bad_deduction; 5544 Candidate.IsSurrogate = false; 5545 Candidate.IgnoreObjectArgument = false; 5546 Candidate.ExplicitCallArguments = Args.size(); 5547 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5548 Info); 5549 return; 5550 } 5551 5552 // Add the function template specialization produced by template argument 5553 // deduction as a candidate. 5554 assert(Specialization && "Missing member function template specialization?"); 5555 assert(isa<CXXMethodDecl>(Specialization) && 5556 "Specialization is not a member function?"); 5557 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 5558 ActingContext, ObjectType, ObjectClassification, Args, 5559 CandidateSet, SuppressUserConversions); 5560 } 5561 5562 /// \brief Add a C++ function template specialization as a candidate 5563 /// in the candidate set, using template argument deduction to produce 5564 /// an appropriate function template specialization. 5565 void 5566 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 5567 DeclAccessPair FoundDecl, 5568 TemplateArgumentListInfo *ExplicitTemplateArgs, 5569 llvm::ArrayRef<Expr *> Args, 5570 OverloadCandidateSet& CandidateSet, 5571 bool SuppressUserConversions) { 5572 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5573 return; 5574 5575 // C++ [over.match.funcs]p7: 5576 // In each case where a candidate is a function template, candidate 5577 // function template specializations are generated using template argument 5578 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5579 // candidate functions in the usual way.113) A given name can refer to one 5580 // or more function templates and also to a set of overloaded non-template 5581 // functions. In such a case, the candidate functions generated from each 5582 // function template are combined with the set of non-template candidate 5583 // functions. 5584 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 5585 FunctionDecl *Specialization = 0; 5586 if (TemplateDeductionResult Result 5587 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 5588 Specialization, Info)) { 5589 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5590 Candidate.FoundDecl = FoundDecl; 5591 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5592 Candidate.Viable = false; 5593 Candidate.FailureKind = ovl_fail_bad_deduction; 5594 Candidate.IsSurrogate = false; 5595 Candidate.IgnoreObjectArgument = false; 5596 Candidate.ExplicitCallArguments = Args.size(); 5597 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5598 Info); 5599 return; 5600 } 5601 5602 // Add the function template specialization produced by template argument 5603 // deduction as a candidate. 5604 assert(Specialization && "Missing function template specialization?"); 5605 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 5606 SuppressUserConversions); 5607 } 5608 5609 /// AddConversionCandidate - Add a C++ conversion function as a 5610 /// candidate in the candidate set (C++ [over.match.conv], 5611 /// C++ [over.match.copy]). From is the expression we're converting from, 5612 /// and ToType is the type that we're eventually trying to convert to 5613 /// (which may or may not be the same type as the type that the 5614 /// conversion function produces). 5615 void 5616 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 5617 DeclAccessPair FoundDecl, 5618 CXXRecordDecl *ActingContext, 5619 Expr *From, QualType ToType, 5620 OverloadCandidateSet& CandidateSet) { 5621 assert(!Conversion->getDescribedFunctionTemplate() && 5622 "Conversion function templates use AddTemplateConversionCandidate"); 5623 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 5624 if (!CandidateSet.isNewCandidate(Conversion)) 5625 return; 5626 5627 // Overload resolution is always an unevaluated context. 5628 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5629 5630 // Add this candidate 5631 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 5632 Candidate.FoundDecl = FoundDecl; 5633 Candidate.Function = Conversion; 5634 Candidate.IsSurrogate = false; 5635 Candidate.IgnoreObjectArgument = false; 5636 Candidate.FinalConversion.setAsIdentityConversion(); 5637 Candidate.FinalConversion.setFromType(ConvType); 5638 Candidate.FinalConversion.setAllToTypes(ToType); 5639 Candidate.Viable = true; 5640 Candidate.ExplicitCallArguments = 1; 5641 5642 // C++ [over.match.funcs]p4: 5643 // For conversion functions, the function is considered to be a member of 5644 // the class of the implicit implied object argument for the purpose of 5645 // defining the type of the implicit object parameter. 5646 // 5647 // Determine the implicit conversion sequence for the implicit 5648 // object parameter. 5649 QualType ImplicitParamType = From->getType(); 5650 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 5651 ImplicitParamType = FromPtrType->getPointeeType(); 5652 CXXRecordDecl *ConversionContext 5653 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 5654 5655 Candidate.Conversions[0] 5656 = TryObjectArgumentInitialization(*this, From->getType(), 5657 From->Classify(Context), 5658 Conversion, ConversionContext); 5659 5660 if (Candidate.Conversions[0].isBad()) { 5661 Candidate.Viable = false; 5662 Candidate.FailureKind = ovl_fail_bad_conversion; 5663 return; 5664 } 5665 5666 // We won't go through a user-define type conversion function to convert a 5667 // derived to base as such conversions are given Conversion Rank. They only 5668 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 5669 QualType FromCanon 5670 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 5671 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 5672 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 5673 Candidate.Viable = false; 5674 Candidate.FailureKind = ovl_fail_trivial_conversion; 5675 return; 5676 } 5677 5678 // To determine what the conversion from the result of calling the 5679 // conversion function to the type we're eventually trying to 5680 // convert to (ToType), we need to synthesize a call to the 5681 // conversion function and attempt copy initialization from it. This 5682 // makes sure that we get the right semantics with respect to 5683 // lvalues/rvalues and the type. Fortunately, we can allocate this 5684 // call on the stack and we don't need its arguments to be 5685 // well-formed. 5686 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 5687 VK_LValue, From->getLocStart()); 5688 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 5689 Context.getPointerType(Conversion->getType()), 5690 CK_FunctionToPointerDecay, 5691 &ConversionRef, VK_RValue); 5692 5693 QualType ConversionType = Conversion->getConversionType(); 5694 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 5695 Candidate.Viable = false; 5696 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5697 return; 5698 } 5699 5700 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 5701 5702 // Note that it is safe to allocate CallExpr on the stack here because 5703 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 5704 // allocator). 5705 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 5706 CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK, 5707 From->getLocStart()); 5708 ImplicitConversionSequence ICS = 5709 TryCopyInitialization(*this, &Call, ToType, 5710 /*SuppressUserConversions=*/true, 5711 /*InOverloadResolution=*/false, 5712 /*AllowObjCWritebackConversion=*/false); 5713 5714 switch (ICS.getKind()) { 5715 case ImplicitConversionSequence::StandardConversion: 5716 Candidate.FinalConversion = ICS.Standard; 5717 5718 // C++ [over.ics.user]p3: 5719 // If the user-defined conversion is specified by a specialization of a 5720 // conversion function template, the second standard conversion sequence 5721 // shall have exact match rank. 5722 if (Conversion->getPrimaryTemplate() && 5723 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 5724 Candidate.Viable = false; 5725 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 5726 } 5727 5728 // C++0x [dcl.init.ref]p5: 5729 // In the second case, if the reference is an rvalue reference and 5730 // the second standard conversion sequence of the user-defined 5731 // conversion sequence includes an lvalue-to-rvalue conversion, the 5732 // program is ill-formed. 5733 if (ToType->isRValueReferenceType() && 5734 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 5735 Candidate.Viable = false; 5736 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5737 } 5738 break; 5739 5740 case ImplicitConversionSequence::BadConversion: 5741 Candidate.Viable = false; 5742 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5743 break; 5744 5745 default: 5746 llvm_unreachable( 5747 "Can only end up with a standard conversion sequence or failure"); 5748 } 5749 } 5750 5751 /// \brief Adds a conversion function template specialization 5752 /// candidate to the overload set, using template argument deduction 5753 /// to deduce the template arguments of the conversion function 5754 /// template from the type that we are converting to (C++ 5755 /// [temp.deduct.conv]). 5756 void 5757 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 5758 DeclAccessPair FoundDecl, 5759 CXXRecordDecl *ActingDC, 5760 Expr *From, QualType ToType, 5761 OverloadCandidateSet &CandidateSet) { 5762 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 5763 "Only conversion function templates permitted here"); 5764 5765 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5766 return; 5767 5768 TemplateDeductionInfo Info(Context, CandidateSet.getLocation()); 5769 CXXConversionDecl *Specialization = 0; 5770 if (TemplateDeductionResult Result 5771 = DeduceTemplateArguments(FunctionTemplate, ToType, 5772 Specialization, Info)) { 5773 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5774 Candidate.FoundDecl = FoundDecl; 5775 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5776 Candidate.Viable = false; 5777 Candidate.FailureKind = ovl_fail_bad_deduction; 5778 Candidate.IsSurrogate = false; 5779 Candidate.IgnoreObjectArgument = false; 5780 Candidate.ExplicitCallArguments = 1; 5781 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5782 Info); 5783 return; 5784 } 5785 5786 // Add the conversion function template specialization produced by 5787 // template argument deduction as a candidate. 5788 assert(Specialization && "Missing function template specialization?"); 5789 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 5790 CandidateSet); 5791 } 5792 5793 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 5794 /// converts the given @c Object to a function pointer via the 5795 /// conversion function @c Conversion, and then attempts to call it 5796 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 5797 /// the type of function that we'll eventually be calling. 5798 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 5799 DeclAccessPair FoundDecl, 5800 CXXRecordDecl *ActingContext, 5801 const FunctionProtoType *Proto, 5802 Expr *Object, 5803 llvm::ArrayRef<Expr *> Args, 5804 OverloadCandidateSet& CandidateSet) { 5805 if (!CandidateSet.isNewCandidate(Conversion)) 5806 return; 5807 5808 // Overload resolution is always an unevaluated context. 5809 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5810 5811 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5812 Candidate.FoundDecl = FoundDecl; 5813 Candidate.Function = 0; 5814 Candidate.Surrogate = Conversion; 5815 Candidate.Viable = true; 5816 Candidate.IsSurrogate = true; 5817 Candidate.IgnoreObjectArgument = false; 5818 Candidate.ExplicitCallArguments = Args.size(); 5819 5820 // Determine the implicit conversion sequence for the implicit 5821 // object parameter. 5822 ImplicitConversionSequence ObjectInit 5823 = TryObjectArgumentInitialization(*this, Object->getType(), 5824 Object->Classify(Context), 5825 Conversion, ActingContext); 5826 if (ObjectInit.isBad()) { 5827 Candidate.Viable = false; 5828 Candidate.FailureKind = ovl_fail_bad_conversion; 5829 Candidate.Conversions[0] = ObjectInit; 5830 return; 5831 } 5832 5833 // The first conversion is actually a user-defined conversion whose 5834 // first conversion is ObjectInit's standard conversion (which is 5835 // effectively a reference binding). Record it as such. 5836 Candidate.Conversions[0].setUserDefined(); 5837 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 5838 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 5839 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 5840 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 5841 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 5842 Candidate.Conversions[0].UserDefined.After 5843 = Candidate.Conversions[0].UserDefined.Before; 5844 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 5845 5846 // Find the 5847 unsigned NumArgsInProto = Proto->getNumArgs(); 5848 5849 // (C++ 13.3.2p2): A candidate function having fewer than m 5850 // parameters is viable only if it has an ellipsis in its parameter 5851 // list (8.3.5). 5852 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5853 Candidate.Viable = false; 5854 Candidate.FailureKind = ovl_fail_too_many_arguments; 5855 return; 5856 } 5857 5858 // Function types don't have any default arguments, so just check if 5859 // we have enough arguments. 5860 if (Args.size() < NumArgsInProto) { 5861 // Not enough arguments. 5862 Candidate.Viable = false; 5863 Candidate.FailureKind = ovl_fail_too_few_arguments; 5864 return; 5865 } 5866 5867 // Determine the implicit conversion sequences for each of the 5868 // arguments. 5869 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5870 if (ArgIdx < NumArgsInProto) { 5871 // (C++ 13.3.2p3): for F to be a viable function, there shall 5872 // exist for each argument an implicit conversion sequence 5873 // (13.3.3.1) that converts that argument to the corresponding 5874 // parameter of F. 5875 QualType ParamType = Proto->getArgType(ArgIdx); 5876 Candidate.Conversions[ArgIdx + 1] 5877 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5878 /*SuppressUserConversions=*/false, 5879 /*InOverloadResolution=*/false, 5880 /*AllowObjCWritebackConversion=*/ 5881 getLangOpts().ObjCAutoRefCount); 5882 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5883 Candidate.Viable = false; 5884 Candidate.FailureKind = ovl_fail_bad_conversion; 5885 break; 5886 } 5887 } else { 5888 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5889 // argument for which there is no corresponding parameter is 5890 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5891 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5892 } 5893 } 5894 } 5895 5896 /// \brief Add overload candidates for overloaded operators that are 5897 /// member functions. 5898 /// 5899 /// Add the overloaded operator candidates that are member functions 5900 /// for the operator Op that was used in an operator expression such 5901 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 5902 /// CandidateSet will store the added overload candidates. (C++ 5903 /// [over.match.oper]). 5904 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 5905 SourceLocation OpLoc, 5906 Expr **Args, unsigned NumArgs, 5907 OverloadCandidateSet& CandidateSet, 5908 SourceRange OpRange) { 5909 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 5910 5911 // C++ [over.match.oper]p3: 5912 // For a unary operator @ with an operand of a type whose 5913 // cv-unqualified version is T1, and for a binary operator @ with 5914 // a left operand of a type whose cv-unqualified version is T1 and 5915 // a right operand of a type whose cv-unqualified version is T2, 5916 // three sets of candidate functions, designated member 5917 // candidates, non-member candidates and built-in candidates, are 5918 // constructed as follows: 5919 QualType T1 = Args[0]->getType(); 5920 5921 // -- If T1 is a class type, the set of member candidates is the 5922 // result of the qualified lookup of T1::operator@ 5923 // (13.3.1.1.1); otherwise, the set of member candidates is 5924 // empty. 5925 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 5926 // Complete the type if it can be completed. Otherwise, we're done. 5927 if (RequireCompleteType(OpLoc, T1, 0)) 5928 return; 5929 5930 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 5931 LookupQualifiedName(Operators, T1Rec->getDecl()); 5932 Operators.suppressDiagnostics(); 5933 5934 for (LookupResult::iterator Oper = Operators.begin(), 5935 OperEnd = Operators.end(); 5936 Oper != OperEnd; 5937 ++Oper) 5938 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 5939 Args[0]->Classify(Context), Args + 1, NumArgs - 1, 5940 CandidateSet, 5941 /* SuppressUserConversions = */ false); 5942 } 5943 } 5944 5945 /// AddBuiltinCandidate - Add a candidate for a built-in 5946 /// operator. ResultTy and ParamTys are the result and parameter types 5947 /// of the built-in candidate, respectively. Args and NumArgs are the 5948 /// arguments being passed to the candidate. IsAssignmentOperator 5949 /// should be true when this built-in candidate is an assignment 5950 /// operator. NumContextualBoolArguments is the number of arguments 5951 /// (at the beginning of the argument list) that will be contextually 5952 /// converted to bool. 5953 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 5954 Expr **Args, unsigned NumArgs, 5955 OverloadCandidateSet& CandidateSet, 5956 bool IsAssignmentOperator, 5957 unsigned NumContextualBoolArguments) { 5958 // Overload resolution is always an unevaluated context. 5959 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5960 5961 // Add this candidate 5962 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs); 5963 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 5964 Candidate.Function = 0; 5965 Candidate.IsSurrogate = false; 5966 Candidate.IgnoreObjectArgument = false; 5967 Candidate.BuiltinTypes.ResultTy = ResultTy; 5968 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 5969 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 5970 5971 // Determine the implicit conversion sequences for each of the 5972 // arguments. 5973 Candidate.Viable = true; 5974 Candidate.ExplicitCallArguments = NumArgs; 5975 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 5976 // C++ [over.match.oper]p4: 5977 // For the built-in assignment operators, conversions of the 5978 // left operand are restricted as follows: 5979 // -- no temporaries are introduced to hold the left operand, and 5980 // -- no user-defined conversions are applied to the left 5981 // operand to achieve a type match with the left-most 5982 // parameter of a built-in candidate. 5983 // 5984 // We block these conversions by turning off user-defined 5985 // conversions, since that is the only way that initialization of 5986 // a reference to a non-class type can occur from something that 5987 // is not of the same type. 5988 if (ArgIdx < NumContextualBoolArguments) { 5989 assert(ParamTys[ArgIdx] == Context.BoolTy && 5990 "Contextual conversion to bool requires bool type"); 5991 Candidate.Conversions[ArgIdx] 5992 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 5993 } else { 5994 Candidate.Conversions[ArgIdx] 5995 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 5996 ArgIdx == 0 && IsAssignmentOperator, 5997 /*InOverloadResolution=*/false, 5998 /*AllowObjCWritebackConversion=*/ 5999 getLangOpts().ObjCAutoRefCount); 6000 } 6001 if (Candidate.Conversions[ArgIdx].isBad()) { 6002 Candidate.Viable = false; 6003 Candidate.FailureKind = ovl_fail_bad_conversion; 6004 break; 6005 } 6006 } 6007 } 6008 6009 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6010 /// candidate operator functions for built-in operators (C++ 6011 /// [over.built]). The types are separated into pointer types and 6012 /// enumeration types. 6013 class BuiltinCandidateTypeSet { 6014 /// TypeSet - A set of types. 6015 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6016 6017 /// PointerTypes - The set of pointer types that will be used in the 6018 /// built-in candidates. 6019 TypeSet PointerTypes; 6020 6021 /// MemberPointerTypes - The set of member pointer types that will be 6022 /// used in the built-in candidates. 6023 TypeSet MemberPointerTypes; 6024 6025 /// EnumerationTypes - The set of enumeration types that will be 6026 /// used in the built-in candidates. 6027 TypeSet EnumerationTypes; 6028 6029 /// \brief The set of vector types that will be used in the built-in 6030 /// candidates. 6031 TypeSet VectorTypes; 6032 6033 /// \brief A flag indicating non-record types are viable candidates 6034 bool HasNonRecordTypes; 6035 6036 /// \brief A flag indicating whether either arithmetic or enumeration types 6037 /// were present in the candidate set. 6038 bool HasArithmeticOrEnumeralTypes; 6039 6040 /// \brief A flag indicating whether the nullptr type was present in the 6041 /// candidate set. 6042 bool HasNullPtrType; 6043 6044 /// Sema - The semantic analysis instance where we are building the 6045 /// candidate type set. 6046 Sema &SemaRef; 6047 6048 /// Context - The AST context in which we will build the type sets. 6049 ASTContext &Context; 6050 6051 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6052 const Qualifiers &VisibleQuals); 6053 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6054 6055 public: 6056 /// iterator - Iterates through the types that are part of the set. 6057 typedef TypeSet::iterator iterator; 6058 6059 BuiltinCandidateTypeSet(Sema &SemaRef) 6060 : HasNonRecordTypes(false), 6061 HasArithmeticOrEnumeralTypes(false), 6062 HasNullPtrType(false), 6063 SemaRef(SemaRef), 6064 Context(SemaRef.Context) { } 6065 6066 void AddTypesConvertedFrom(QualType Ty, 6067 SourceLocation Loc, 6068 bool AllowUserConversions, 6069 bool AllowExplicitConversions, 6070 const Qualifiers &VisibleTypeConversionsQuals); 6071 6072 /// pointer_begin - First pointer type found; 6073 iterator pointer_begin() { return PointerTypes.begin(); } 6074 6075 /// pointer_end - Past the last pointer type found; 6076 iterator pointer_end() { return PointerTypes.end(); } 6077 6078 /// member_pointer_begin - First member pointer type found; 6079 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6080 6081 /// member_pointer_end - Past the last member pointer type found; 6082 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6083 6084 /// enumeration_begin - First enumeration type found; 6085 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6086 6087 /// enumeration_end - Past the last enumeration type found; 6088 iterator enumeration_end() { return EnumerationTypes.end(); } 6089 6090 iterator vector_begin() { return VectorTypes.begin(); } 6091 iterator vector_end() { return VectorTypes.end(); } 6092 6093 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6094 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6095 bool hasNullPtrType() const { return HasNullPtrType; } 6096 }; 6097 6098 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6099 /// the set of pointer types along with any more-qualified variants of 6100 /// that type. For example, if @p Ty is "int const *", this routine 6101 /// will add "int const *", "int const volatile *", "int const 6102 /// restrict *", and "int const volatile restrict *" to the set of 6103 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6104 /// false otherwise. 6105 /// 6106 /// FIXME: what to do about extended qualifiers? 6107 bool 6108 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6109 const Qualifiers &VisibleQuals) { 6110 6111 // Insert this type. 6112 if (!PointerTypes.insert(Ty)) 6113 return false; 6114 6115 QualType PointeeTy; 6116 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6117 bool buildObjCPtr = false; 6118 if (!PointerTy) { 6119 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6120 PointeeTy = PTy->getPointeeType(); 6121 buildObjCPtr = true; 6122 } else { 6123 PointeeTy = PointerTy->getPointeeType(); 6124 } 6125 6126 // Don't add qualified variants of arrays. For one, they're not allowed 6127 // (the qualifier would sink to the element type), and for another, the 6128 // only overload situation where it matters is subscript or pointer +- int, 6129 // and those shouldn't have qualifier variants anyway. 6130 if (PointeeTy->isArrayType()) 6131 return true; 6132 6133 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6134 bool hasVolatile = VisibleQuals.hasVolatile(); 6135 bool hasRestrict = VisibleQuals.hasRestrict(); 6136 6137 // Iterate through all strict supersets of BaseCVR. 6138 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6139 if ((CVR | BaseCVR) != CVR) continue; 6140 // Skip over volatile if no volatile found anywhere in the types. 6141 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6142 6143 // Skip over restrict if no restrict found anywhere in the types, or if 6144 // the type cannot be restrict-qualified. 6145 if ((CVR & Qualifiers::Restrict) && 6146 (!hasRestrict || 6147 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6148 continue; 6149 6150 // Build qualified pointee type. 6151 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6152 6153 // Build qualified pointer type. 6154 QualType QPointerTy; 6155 if (!buildObjCPtr) 6156 QPointerTy = Context.getPointerType(QPointeeTy); 6157 else 6158 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6159 6160 // Insert qualified pointer type. 6161 PointerTypes.insert(QPointerTy); 6162 } 6163 6164 return true; 6165 } 6166 6167 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6168 /// to the set of pointer types along with any more-qualified variants of 6169 /// that type. For example, if @p Ty is "int const *", this routine 6170 /// will add "int const *", "int const volatile *", "int const 6171 /// restrict *", and "int const volatile restrict *" to the set of 6172 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6173 /// false otherwise. 6174 /// 6175 /// FIXME: what to do about extended qualifiers? 6176 bool 6177 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6178 QualType Ty) { 6179 // Insert this type. 6180 if (!MemberPointerTypes.insert(Ty)) 6181 return false; 6182 6183 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6184 assert(PointerTy && "type was not a member pointer type!"); 6185 6186 QualType PointeeTy = PointerTy->getPointeeType(); 6187 // Don't add qualified variants of arrays. For one, they're not allowed 6188 // (the qualifier would sink to the element type), and for another, the 6189 // only overload situation where it matters is subscript or pointer +- int, 6190 // and those shouldn't have qualifier variants anyway. 6191 if (PointeeTy->isArrayType()) 6192 return true; 6193 const Type *ClassTy = PointerTy->getClass(); 6194 6195 // Iterate through all strict supersets of the pointee type's CVR 6196 // qualifiers. 6197 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6198 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6199 if ((CVR | BaseCVR) != CVR) continue; 6200 6201 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6202 MemberPointerTypes.insert( 6203 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6204 } 6205 6206 return true; 6207 } 6208 6209 /// AddTypesConvertedFrom - Add each of the types to which the type @p 6210 /// Ty can be implicit converted to the given set of @p Types. We're 6211 /// primarily interested in pointer types and enumeration types. We also 6212 /// take member pointer types, for the conditional operator. 6213 /// AllowUserConversions is true if we should look at the conversion 6214 /// functions of a class type, and AllowExplicitConversions if we 6215 /// should also include the explicit conversion functions of a class 6216 /// type. 6217 void 6218 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6219 SourceLocation Loc, 6220 bool AllowUserConversions, 6221 bool AllowExplicitConversions, 6222 const Qualifiers &VisibleQuals) { 6223 // Only deal with canonical types. 6224 Ty = Context.getCanonicalType(Ty); 6225 6226 // Look through reference types; they aren't part of the type of an 6227 // expression for the purposes of conversions. 6228 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6229 Ty = RefTy->getPointeeType(); 6230 6231 // If we're dealing with an array type, decay to the pointer. 6232 if (Ty->isArrayType()) 6233 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6234 6235 // Otherwise, we don't care about qualifiers on the type. 6236 Ty = Ty.getLocalUnqualifiedType(); 6237 6238 // Flag if we ever add a non-record type. 6239 const RecordType *TyRec = Ty->getAs<RecordType>(); 6240 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6241 6242 // Flag if we encounter an arithmetic type. 6243 HasArithmeticOrEnumeralTypes = 6244 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6245 6246 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6247 PointerTypes.insert(Ty); 6248 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6249 // Insert our type, and its more-qualified variants, into the set 6250 // of types. 6251 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6252 return; 6253 } else if (Ty->isMemberPointerType()) { 6254 // Member pointers are far easier, since the pointee can't be converted. 6255 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6256 return; 6257 } else if (Ty->isEnumeralType()) { 6258 HasArithmeticOrEnumeralTypes = true; 6259 EnumerationTypes.insert(Ty); 6260 } else if (Ty->isVectorType()) { 6261 // We treat vector types as arithmetic types in many contexts as an 6262 // extension. 6263 HasArithmeticOrEnumeralTypes = true; 6264 VectorTypes.insert(Ty); 6265 } else if (Ty->isNullPtrType()) { 6266 HasNullPtrType = true; 6267 } else if (AllowUserConversions && TyRec) { 6268 // No conversion functions in incomplete types. 6269 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6270 return; 6271 6272 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6273 const UnresolvedSetImpl *Conversions 6274 = ClassDecl->getVisibleConversionFunctions(); 6275 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 6276 E = Conversions->end(); I != E; ++I) { 6277 NamedDecl *D = I.getDecl(); 6278 if (isa<UsingShadowDecl>(D)) 6279 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6280 6281 // Skip conversion function templates; they don't tell us anything 6282 // about which builtin types we can convert to. 6283 if (isa<FunctionTemplateDecl>(D)) 6284 continue; 6285 6286 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6287 if (AllowExplicitConversions || !Conv->isExplicit()) { 6288 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6289 VisibleQuals); 6290 } 6291 } 6292 } 6293 } 6294 6295 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6296 /// the volatile- and non-volatile-qualified assignment operators for the 6297 /// given type to the candidate set. 6298 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6299 QualType T, 6300 Expr **Args, 6301 unsigned NumArgs, 6302 OverloadCandidateSet &CandidateSet) { 6303 QualType ParamTypes[2]; 6304 6305 // T& operator=(T&, T) 6306 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6307 ParamTypes[1] = T; 6308 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 6309 /*IsAssignmentOperator=*/true); 6310 6311 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6312 // volatile T& operator=(volatile T&, T) 6313 ParamTypes[0] 6314 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6315 ParamTypes[1] = T; 6316 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 6317 /*IsAssignmentOperator=*/true); 6318 } 6319 } 6320 6321 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6322 /// if any, found in visible type conversion functions found in ArgExpr's type. 6323 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6324 Qualifiers VRQuals; 6325 const RecordType *TyRec; 6326 if (const MemberPointerType *RHSMPType = 6327 ArgExpr->getType()->getAs<MemberPointerType>()) 6328 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6329 else 6330 TyRec = ArgExpr->getType()->getAs<RecordType>(); 6331 if (!TyRec) { 6332 // Just to be safe, assume the worst case. 6333 VRQuals.addVolatile(); 6334 VRQuals.addRestrict(); 6335 return VRQuals; 6336 } 6337 6338 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6339 if (!ClassDecl->hasDefinition()) 6340 return VRQuals; 6341 6342 const UnresolvedSetImpl *Conversions = 6343 ClassDecl->getVisibleConversionFunctions(); 6344 6345 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 6346 E = Conversions->end(); I != E; ++I) { 6347 NamedDecl *D = I.getDecl(); 6348 if (isa<UsingShadowDecl>(D)) 6349 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6350 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6351 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 6352 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 6353 CanTy = ResTypeRef->getPointeeType(); 6354 // Need to go down the pointer/mempointer chain and add qualifiers 6355 // as see them. 6356 bool done = false; 6357 while (!done) { 6358 if (CanTy.isRestrictQualified()) 6359 VRQuals.addRestrict(); 6360 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 6361 CanTy = ResTypePtr->getPointeeType(); 6362 else if (const MemberPointerType *ResTypeMPtr = 6363 CanTy->getAs<MemberPointerType>()) 6364 CanTy = ResTypeMPtr->getPointeeType(); 6365 else 6366 done = true; 6367 if (CanTy.isVolatileQualified()) 6368 VRQuals.addVolatile(); 6369 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 6370 return VRQuals; 6371 } 6372 } 6373 } 6374 return VRQuals; 6375 } 6376 6377 namespace { 6378 6379 /// \brief Helper class to manage the addition of builtin operator overload 6380 /// candidates. It provides shared state and utility methods used throughout 6381 /// the process, as well as a helper method to add each group of builtin 6382 /// operator overloads from the standard to a candidate set. 6383 class BuiltinOperatorOverloadBuilder { 6384 // Common instance state available to all overload candidate addition methods. 6385 Sema &S; 6386 Expr **Args; 6387 unsigned NumArgs; 6388 Qualifiers VisibleTypeConversionsQuals; 6389 bool HasArithmeticOrEnumeralCandidateType; 6390 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 6391 OverloadCandidateSet &CandidateSet; 6392 6393 // Define some constants used to index and iterate over the arithemetic types 6394 // provided via the getArithmeticType() method below. 6395 // The "promoted arithmetic types" are the arithmetic 6396 // types are that preserved by promotion (C++ [over.built]p2). 6397 static const unsigned FirstIntegralType = 3; 6398 static const unsigned LastIntegralType = 20; 6399 static const unsigned FirstPromotedIntegralType = 3, 6400 LastPromotedIntegralType = 11; 6401 static const unsigned FirstPromotedArithmeticType = 0, 6402 LastPromotedArithmeticType = 11; 6403 static const unsigned NumArithmeticTypes = 20; 6404 6405 /// \brief Get the canonical type for a given arithmetic type index. 6406 CanQualType getArithmeticType(unsigned index) { 6407 assert(index < NumArithmeticTypes); 6408 static CanQualType ASTContext::* const 6409 ArithmeticTypes[NumArithmeticTypes] = { 6410 // Start of promoted types. 6411 &ASTContext::FloatTy, 6412 &ASTContext::DoubleTy, 6413 &ASTContext::LongDoubleTy, 6414 6415 // Start of integral types. 6416 &ASTContext::IntTy, 6417 &ASTContext::LongTy, 6418 &ASTContext::LongLongTy, 6419 &ASTContext::Int128Ty, 6420 &ASTContext::UnsignedIntTy, 6421 &ASTContext::UnsignedLongTy, 6422 &ASTContext::UnsignedLongLongTy, 6423 &ASTContext::UnsignedInt128Ty, 6424 // End of promoted types. 6425 6426 &ASTContext::BoolTy, 6427 &ASTContext::CharTy, 6428 &ASTContext::WCharTy, 6429 &ASTContext::Char16Ty, 6430 &ASTContext::Char32Ty, 6431 &ASTContext::SignedCharTy, 6432 &ASTContext::ShortTy, 6433 &ASTContext::UnsignedCharTy, 6434 &ASTContext::UnsignedShortTy, 6435 // End of integral types. 6436 // FIXME: What about complex? What about half? 6437 }; 6438 return S.Context.*ArithmeticTypes[index]; 6439 } 6440 6441 /// \brief Gets the canonical type resulting from the usual arithemetic 6442 /// converions for the given arithmetic types. 6443 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 6444 // Accelerator table for performing the usual arithmetic conversions. 6445 // The rules are basically: 6446 // - if either is floating-point, use the wider floating-point 6447 // - if same signedness, use the higher rank 6448 // - if same size, use unsigned of the higher rank 6449 // - use the larger type 6450 // These rules, together with the axiom that higher ranks are 6451 // never smaller, are sufficient to precompute all of these results 6452 // *except* when dealing with signed types of higher rank. 6453 // (we could precompute SLL x UI for all known platforms, but it's 6454 // better not to make any assumptions). 6455 // We assume that int128 has a higher rank than long long on all platforms. 6456 enum PromotedType { 6457 Dep=-1, 6458 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 6459 }; 6460 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 6461 [LastPromotedArithmeticType] = { 6462 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 6463 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 6464 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 6465 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 6466 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 6467 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 6468 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 6469 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 6470 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 6471 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 6472 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 6473 }; 6474 6475 assert(L < LastPromotedArithmeticType); 6476 assert(R < LastPromotedArithmeticType); 6477 int Idx = ConversionsTable[L][R]; 6478 6479 // Fast path: the table gives us a concrete answer. 6480 if (Idx != Dep) return getArithmeticType(Idx); 6481 6482 // Slow path: we need to compare widths. 6483 // An invariant is that the signed type has higher rank. 6484 CanQualType LT = getArithmeticType(L), 6485 RT = getArithmeticType(R); 6486 unsigned LW = S.Context.getIntWidth(LT), 6487 RW = S.Context.getIntWidth(RT); 6488 6489 // If they're different widths, use the signed type. 6490 if (LW > RW) return LT; 6491 else if (LW < RW) return RT; 6492 6493 // Otherwise, use the unsigned type of the signed type's rank. 6494 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 6495 assert(L == SLL || R == SLL); 6496 return S.Context.UnsignedLongLongTy; 6497 } 6498 6499 /// \brief Helper method to factor out the common pattern of adding overloads 6500 /// for '++' and '--' builtin operators. 6501 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 6502 bool HasVolatile, 6503 bool HasRestrict) { 6504 QualType ParamTypes[2] = { 6505 S.Context.getLValueReferenceType(CandidateTy), 6506 S.Context.IntTy 6507 }; 6508 6509 // Non-volatile version. 6510 if (NumArgs == 1) 6511 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6512 else 6513 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6514 6515 // Use a heuristic to reduce number of builtin candidates in the set: 6516 // add volatile version only if there are conversions to a volatile type. 6517 if (HasVolatile) { 6518 ParamTypes[0] = 6519 S.Context.getLValueReferenceType( 6520 S.Context.getVolatileType(CandidateTy)); 6521 if (NumArgs == 1) 6522 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6523 else 6524 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6525 } 6526 6527 // Add restrict version only if there are conversions to a restrict type 6528 // and our candidate type is a non-restrict-qualified pointer. 6529 if (HasRestrict && CandidateTy->isAnyPointerType() && 6530 !CandidateTy.isRestrictQualified()) { 6531 ParamTypes[0] 6532 = S.Context.getLValueReferenceType( 6533 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 6534 if (NumArgs == 1) 6535 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6536 else 6537 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6538 6539 if (HasVolatile) { 6540 ParamTypes[0] 6541 = S.Context.getLValueReferenceType( 6542 S.Context.getCVRQualifiedType(CandidateTy, 6543 (Qualifiers::Volatile | 6544 Qualifiers::Restrict))); 6545 if (NumArgs == 1) 6546 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, 6547 CandidateSet); 6548 else 6549 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6550 } 6551 } 6552 6553 } 6554 6555 public: 6556 BuiltinOperatorOverloadBuilder( 6557 Sema &S, Expr **Args, unsigned NumArgs, 6558 Qualifiers VisibleTypeConversionsQuals, 6559 bool HasArithmeticOrEnumeralCandidateType, 6560 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 6561 OverloadCandidateSet &CandidateSet) 6562 : S(S), Args(Args), NumArgs(NumArgs), 6563 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 6564 HasArithmeticOrEnumeralCandidateType( 6565 HasArithmeticOrEnumeralCandidateType), 6566 CandidateTypes(CandidateTypes), 6567 CandidateSet(CandidateSet) { 6568 // Validate some of our static helper constants in debug builds. 6569 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 6570 "Invalid first promoted integral type"); 6571 assert(getArithmeticType(LastPromotedIntegralType - 1) 6572 == S.Context.UnsignedInt128Ty && 6573 "Invalid last promoted integral type"); 6574 assert(getArithmeticType(FirstPromotedArithmeticType) 6575 == S.Context.FloatTy && 6576 "Invalid first promoted arithmetic type"); 6577 assert(getArithmeticType(LastPromotedArithmeticType - 1) 6578 == S.Context.UnsignedInt128Ty && 6579 "Invalid last promoted arithmetic type"); 6580 } 6581 6582 // C++ [over.built]p3: 6583 // 6584 // For every pair (T, VQ), where T is an arithmetic type, and VQ 6585 // is either volatile or empty, there exist candidate operator 6586 // functions of the form 6587 // 6588 // VQ T& operator++(VQ T&); 6589 // T operator++(VQ T&, int); 6590 // 6591 // C++ [over.built]p4: 6592 // 6593 // For every pair (T, VQ), where T is an arithmetic type other 6594 // than bool, and VQ is either volatile or empty, there exist 6595 // candidate operator functions of the form 6596 // 6597 // VQ T& operator--(VQ T&); 6598 // T operator--(VQ T&, int); 6599 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 6600 if (!HasArithmeticOrEnumeralCandidateType) 6601 return; 6602 6603 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 6604 Arith < NumArithmeticTypes; ++Arith) { 6605 addPlusPlusMinusMinusStyleOverloads( 6606 getArithmeticType(Arith), 6607 VisibleTypeConversionsQuals.hasVolatile(), 6608 VisibleTypeConversionsQuals.hasRestrict()); 6609 } 6610 } 6611 6612 // C++ [over.built]p5: 6613 // 6614 // For every pair (T, VQ), where T is a cv-qualified or 6615 // cv-unqualified object type, and VQ is either volatile or 6616 // empty, there exist candidate operator functions of the form 6617 // 6618 // T*VQ& operator++(T*VQ&); 6619 // T*VQ& operator--(T*VQ&); 6620 // T* operator++(T*VQ&, int); 6621 // T* operator--(T*VQ&, int); 6622 void addPlusPlusMinusMinusPointerOverloads() { 6623 for (BuiltinCandidateTypeSet::iterator 6624 Ptr = CandidateTypes[0].pointer_begin(), 6625 PtrEnd = CandidateTypes[0].pointer_end(); 6626 Ptr != PtrEnd; ++Ptr) { 6627 // Skip pointer types that aren't pointers to object types. 6628 if (!(*Ptr)->getPointeeType()->isObjectType()) 6629 continue; 6630 6631 addPlusPlusMinusMinusStyleOverloads(*Ptr, 6632 (!(*Ptr).isVolatileQualified() && 6633 VisibleTypeConversionsQuals.hasVolatile()), 6634 (!(*Ptr).isRestrictQualified() && 6635 VisibleTypeConversionsQuals.hasRestrict())); 6636 } 6637 } 6638 6639 // C++ [over.built]p6: 6640 // For every cv-qualified or cv-unqualified object type T, there 6641 // exist candidate operator functions of the form 6642 // 6643 // T& operator*(T*); 6644 // 6645 // C++ [over.built]p7: 6646 // For every function type T that does not have cv-qualifiers or a 6647 // ref-qualifier, there exist candidate operator functions of the form 6648 // T& operator*(T*); 6649 void addUnaryStarPointerOverloads() { 6650 for (BuiltinCandidateTypeSet::iterator 6651 Ptr = CandidateTypes[0].pointer_begin(), 6652 PtrEnd = CandidateTypes[0].pointer_end(); 6653 Ptr != PtrEnd; ++Ptr) { 6654 QualType ParamTy = *Ptr; 6655 QualType PointeeTy = ParamTy->getPointeeType(); 6656 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 6657 continue; 6658 6659 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 6660 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 6661 continue; 6662 6663 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 6664 &ParamTy, Args, 1, CandidateSet); 6665 } 6666 } 6667 6668 // C++ [over.built]p9: 6669 // For every promoted arithmetic type T, there exist candidate 6670 // operator functions of the form 6671 // 6672 // T operator+(T); 6673 // T operator-(T); 6674 void addUnaryPlusOrMinusArithmeticOverloads() { 6675 if (!HasArithmeticOrEnumeralCandidateType) 6676 return; 6677 6678 for (unsigned Arith = FirstPromotedArithmeticType; 6679 Arith < LastPromotedArithmeticType; ++Arith) { 6680 QualType ArithTy = getArithmeticType(Arith); 6681 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet); 6682 } 6683 6684 // Extension: We also add these operators for vector types. 6685 for (BuiltinCandidateTypeSet::iterator 6686 Vec = CandidateTypes[0].vector_begin(), 6687 VecEnd = CandidateTypes[0].vector_end(); 6688 Vec != VecEnd; ++Vec) { 6689 QualType VecTy = *Vec; 6690 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 6691 } 6692 } 6693 6694 // C++ [over.built]p8: 6695 // For every type T, there exist candidate operator functions of 6696 // the form 6697 // 6698 // T* operator+(T*); 6699 void addUnaryPlusPointerOverloads() { 6700 for (BuiltinCandidateTypeSet::iterator 6701 Ptr = CandidateTypes[0].pointer_begin(), 6702 PtrEnd = CandidateTypes[0].pointer_end(); 6703 Ptr != PtrEnd; ++Ptr) { 6704 QualType ParamTy = *Ptr; 6705 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 6706 } 6707 } 6708 6709 // C++ [over.built]p10: 6710 // For every promoted integral type T, there exist candidate 6711 // operator functions of the form 6712 // 6713 // T operator~(T); 6714 void addUnaryTildePromotedIntegralOverloads() { 6715 if (!HasArithmeticOrEnumeralCandidateType) 6716 return; 6717 6718 for (unsigned Int = FirstPromotedIntegralType; 6719 Int < LastPromotedIntegralType; ++Int) { 6720 QualType IntTy = getArithmeticType(Int); 6721 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet); 6722 } 6723 6724 // Extension: We also add this operator for vector types. 6725 for (BuiltinCandidateTypeSet::iterator 6726 Vec = CandidateTypes[0].vector_begin(), 6727 VecEnd = CandidateTypes[0].vector_end(); 6728 Vec != VecEnd; ++Vec) { 6729 QualType VecTy = *Vec; 6730 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 6731 } 6732 } 6733 6734 // C++ [over.match.oper]p16: 6735 // For every pointer to member type T, there exist candidate operator 6736 // functions of the form 6737 // 6738 // bool operator==(T,T); 6739 // bool operator!=(T,T); 6740 void addEqualEqualOrNotEqualMemberPointerOverloads() { 6741 /// Set of (canonical) types that we've already handled. 6742 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6743 6744 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6745 for (BuiltinCandidateTypeSet::iterator 6746 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 6747 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 6748 MemPtr != MemPtrEnd; 6749 ++MemPtr) { 6750 // Don't add the same builtin candidate twice. 6751 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 6752 continue; 6753 6754 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 6755 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6756 CandidateSet); 6757 } 6758 } 6759 } 6760 6761 // C++ [over.built]p15: 6762 // 6763 // For every T, where T is an enumeration type, a pointer type, or 6764 // std::nullptr_t, there exist candidate operator functions of the form 6765 // 6766 // bool operator<(T, T); 6767 // bool operator>(T, T); 6768 // bool operator<=(T, T); 6769 // bool operator>=(T, T); 6770 // bool operator==(T, T); 6771 // bool operator!=(T, T); 6772 void addRelationalPointerOrEnumeralOverloads() { 6773 // C++ [over.built]p1: 6774 // If there is a user-written candidate with the same name and parameter 6775 // types as a built-in candidate operator function, the built-in operator 6776 // function is hidden and is not included in the set of candidate 6777 // functions. 6778 // 6779 // The text is actually in a note, but if we don't implement it then we end 6780 // up with ambiguities when the user provides an overloaded operator for 6781 // an enumeration type. Note that only enumeration types have this problem, 6782 // so we track which enumeration types we've seen operators for. Also, the 6783 // only other overloaded operator with enumeration argumenst, operator=, 6784 // cannot be overloaded for enumeration types, so this is the only place 6785 // where we must suppress candidates like this. 6786 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 6787 UserDefinedBinaryOperators; 6788 6789 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6790 if (CandidateTypes[ArgIdx].enumeration_begin() != 6791 CandidateTypes[ArgIdx].enumeration_end()) { 6792 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 6793 CEnd = CandidateSet.end(); 6794 C != CEnd; ++C) { 6795 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 6796 continue; 6797 6798 QualType FirstParamType = 6799 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 6800 QualType SecondParamType = 6801 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 6802 6803 // Skip if either parameter isn't of enumeral type. 6804 if (!FirstParamType->isEnumeralType() || 6805 !SecondParamType->isEnumeralType()) 6806 continue; 6807 6808 // Add this operator to the set of known user-defined operators. 6809 UserDefinedBinaryOperators.insert( 6810 std::make_pair(S.Context.getCanonicalType(FirstParamType), 6811 S.Context.getCanonicalType(SecondParamType))); 6812 } 6813 } 6814 } 6815 6816 /// Set of (canonical) types that we've already handled. 6817 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6818 6819 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6820 for (BuiltinCandidateTypeSet::iterator 6821 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 6822 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 6823 Ptr != PtrEnd; ++Ptr) { 6824 // Don't add the same builtin candidate twice. 6825 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 6826 continue; 6827 6828 QualType ParamTypes[2] = { *Ptr, *Ptr }; 6829 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6830 CandidateSet); 6831 } 6832 for (BuiltinCandidateTypeSet::iterator 6833 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 6834 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 6835 Enum != EnumEnd; ++Enum) { 6836 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 6837 6838 // Don't add the same builtin candidate twice, or if a user defined 6839 // candidate exists. 6840 if (!AddedTypes.insert(CanonType) || 6841 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 6842 CanonType))) 6843 continue; 6844 6845 QualType ParamTypes[2] = { *Enum, *Enum }; 6846 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6847 CandidateSet); 6848 } 6849 6850 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 6851 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 6852 if (AddedTypes.insert(NullPtrTy) && 6853 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 6854 NullPtrTy))) { 6855 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 6856 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6857 CandidateSet); 6858 } 6859 } 6860 } 6861 } 6862 6863 // C++ [over.built]p13: 6864 // 6865 // For every cv-qualified or cv-unqualified object type T 6866 // there exist candidate operator functions of the form 6867 // 6868 // T* operator+(T*, ptrdiff_t); 6869 // T& operator[](T*, ptrdiff_t); [BELOW] 6870 // T* operator-(T*, ptrdiff_t); 6871 // T* operator+(ptrdiff_t, T*); 6872 // T& operator[](ptrdiff_t, T*); [BELOW] 6873 // 6874 // C++ [over.built]p14: 6875 // 6876 // For every T, where T is a pointer to object type, there 6877 // exist candidate operator functions of the form 6878 // 6879 // ptrdiff_t operator-(T, T); 6880 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 6881 /// Set of (canonical) types that we've already handled. 6882 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6883 6884 for (int Arg = 0; Arg < 2; ++Arg) { 6885 QualType AsymetricParamTypes[2] = { 6886 S.Context.getPointerDiffType(), 6887 S.Context.getPointerDiffType(), 6888 }; 6889 for (BuiltinCandidateTypeSet::iterator 6890 Ptr = CandidateTypes[Arg].pointer_begin(), 6891 PtrEnd = CandidateTypes[Arg].pointer_end(); 6892 Ptr != PtrEnd; ++Ptr) { 6893 QualType PointeeTy = (*Ptr)->getPointeeType(); 6894 if (!PointeeTy->isObjectType()) 6895 continue; 6896 6897 AsymetricParamTypes[Arg] = *Ptr; 6898 if (Arg == 0 || Op == OO_Plus) { 6899 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 6900 // T* operator+(ptrdiff_t, T*); 6901 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2, 6902 CandidateSet); 6903 } 6904 if (Op == OO_Minus) { 6905 // ptrdiff_t operator-(T, T); 6906 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 6907 continue; 6908 6909 QualType ParamTypes[2] = { *Ptr, *Ptr }; 6910 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 6911 Args, 2, CandidateSet); 6912 } 6913 } 6914 } 6915 } 6916 6917 // C++ [over.built]p12: 6918 // 6919 // For every pair of promoted arithmetic types L and R, there 6920 // exist candidate operator functions of the form 6921 // 6922 // LR operator*(L, R); 6923 // LR operator/(L, R); 6924 // LR operator+(L, R); 6925 // LR operator-(L, R); 6926 // bool operator<(L, R); 6927 // bool operator>(L, R); 6928 // bool operator<=(L, R); 6929 // bool operator>=(L, R); 6930 // bool operator==(L, R); 6931 // bool operator!=(L, R); 6932 // 6933 // where LR is the result of the usual arithmetic conversions 6934 // between types L and R. 6935 // 6936 // C++ [over.built]p24: 6937 // 6938 // For every pair of promoted arithmetic types L and R, there exist 6939 // candidate operator functions of the form 6940 // 6941 // LR operator?(bool, L, R); 6942 // 6943 // where LR is the result of the usual arithmetic conversions 6944 // between types L and R. 6945 // Our candidates ignore the first parameter. 6946 void addGenericBinaryArithmeticOverloads(bool isComparison) { 6947 if (!HasArithmeticOrEnumeralCandidateType) 6948 return; 6949 6950 for (unsigned Left = FirstPromotedArithmeticType; 6951 Left < LastPromotedArithmeticType; ++Left) { 6952 for (unsigned Right = FirstPromotedArithmeticType; 6953 Right < LastPromotedArithmeticType; ++Right) { 6954 QualType LandR[2] = { getArithmeticType(Left), 6955 getArithmeticType(Right) }; 6956 QualType Result = 6957 isComparison ? S.Context.BoolTy 6958 : getUsualArithmeticConversions(Left, Right); 6959 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 6960 } 6961 } 6962 6963 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 6964 // conditional operator for vector types. 6965 for (BuiltinCandidateTypeSet::iterator 6966 Vec1 = CandidateTypes[0].vector_begin(), 6967 Vec1End = CandidateTypes[0].vector_end(); 6968 Vec1 != Vec1End; ++Vec1) { 6969 for (BuiltinCandidateTypeSet::iterator 6970 Vec2 = CandidateTypes[1].vector_begin(), 6971 Vec2End = CandidateTypes[1].vector_end(); 6972 Vec2 != Vec2End; ++Vec2) { 6973 QualType LandR[2] = { *Vec1, *Vec2 }; 6974 QualType Result = S.Context.BoolTy; 6975 if (!isComparison) { 6976 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 6977 Result = *Vec1; 6978 else 6979 Result = *Vec2; 6980 } 6981 6982 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 6983 } 6984 } 6985 } 6986 6987 // C++ [over.built]p17: 6988 // 6989 // For every pair of promoted integral types L and R, there 6990 // exist candidate operator functions of the form 6991 // 6992 // LR operator%(L, R); 6993 // LR operator&(L, R); 6994 // LR operator^(L, R); 6995 // LR operator|(L, R); 6996 // L operator<<(L, R); 6997 // L operator>>(L, R); 6998 // 6999 // where LR is the result of the usual arithmetic conversions 7000 // between types L and R. 7001 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7002 if (!HasArithmeticOrEnumeralCandidateType) 7003 return; 7004 7005 for (unsigned Left = FirstPromotedIntegralType; 7006 Left < LastPromotedIntegralType; ++Left) { 7007 for (unsigned Right = FirstPromotedIntegralType; 7008 Right < LastPromotedIntegralType; ++Right) { 7009 QualType LandR[2] = { getArithmeticType(Left), 7010 getArithmeticType(Right) }; 7011 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7012 ? LandR[0] 7013 : getUsualArithmeticConversions(Left, Right); 7014 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 7015 } 7016 } 7017 } 7018 7019 // C++ [over.built]p20: 7020 // 7021 // For every pair (T, VQ), where T is an enumeration or 7022 // pointer to member type and VQ is either volatile or 7023 // empty, there exist candidate operator functions of the form 7024 // 7025 // VQ T& operator=(VQ T&, T); 7026 void addAssignmentMemberPointerOrEnumeralOverloads() { 7027 /// Set of (canonical) types that we've already handled. 7028 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7029 7030 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7031 for (BuiltinCandidateTypeSet::iterator 7032 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7033 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7034 Enum != EnumEnd; ++Enum) { 7035 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7036 continue; 7037 7038 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2, 7039 CandidateSet); 7040 } 7041 7042 for (BuiltinCandidateTypeSet::iterator 7043 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7044 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7045 MemPtr != MemPtrEnd; ++MemPtr) { 7046 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7047 continue; 7048 7049 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2, 7050 CandidateSet); 7051 } 7052 } 7053 } 7054 7055 // C++ [over.built]p19: 7056 // 7057 // For every pair (T, VQ), where T is any type and VQ is either 7058 // volatile or empty, there exist candidate operator functions 7059 // of the form 7060 // 7061 // T*VQ& operator=(T*VQ&, T*); 7062 // 7063 // C++ [over.built]p21: 7064 // 7065 // For every pair (T, VQ), where T is a cv-qualified or 7066 // cv-unqualified object type and VQ is either volatile or 7067 // empty, there exist candidate operator functions of the form 7068 // 7069 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7070 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7071 void addAssignmentPointerOverloads(bool isEqualOp) { 7072 /// Set of (canonical) types that we've already handled. 7073 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7074 7075 for (BuiltinCandidateTypeSet::iterator 7076 Ptr = CandidateTypes[0].pointer_begin(), 7077 PtrEnd = CandidateTypes[0].pointer_end(); 7078 Ptr != PtrEnd; ++Ptr) { 7079 // If this is operator=, keep track of the builtin candidates we added. 7080 if (isEqualOp) 7081 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7082 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7083 continue; 7084 7085 // non-volatile version 7086 QualType ParamTypes[2] = { 7087 S.Context.getLValueReferenceType(*Ptr), 7088 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7089 }; 7090 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7091 /*IsAssigmentOperator=*/ isEqualOp); 7092 7093 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7094 VisibleTypeConversionsQuals.hasVolatile(); 7095 if (NeedVolatile) { 7096 // volatile version 7097 ParamTypes[0] = 7098 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7099 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7100 /*IsAssigmentOperator=*/isEqualOp); 7101 } 7102 7103 if (!(*Ptr).isRestrictQualified() && 7104 VisibleTypeConversionsQuals.hasRestrict()) { 7105 // restrict version 7106 ParamTypes[0] 7107 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7108 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7109 /*IsAssigmentOperator=*/isEqualOp); 7110 7111 if (NeedVolatile) { 7112 // volatile restrict version 7113 ParamTypes[0] 7114 = S.Context.getLValueReferenceType( 7115 S.Context.getCVRQualifiedType(*Ptr, 7116 (Qualifiers::Volatile | 7117 Qualifiers::Restrict))); 7118 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7119 CandidateSet, 7120 /*IsAssigmentOperator=*/isEqualOp); 7121 } 7122 } 7123 } 7124 7125 if (isEqualOp) { 7126 for (BuiltinCandidateTypeSet::iterator 7127 Ptr = CandidateTypes[1].pointer_begin(), 7128 PtrEnd = CandidateTypes[1].pointer_end(); 7129 Ptr != PtrEnd; ++Ptr) { 7130 // Make sure we don't add the same candidate twice. 7131 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7132 continue; 7133 7134 QualType ParamTypes[2] = { 7135 S.Context.getLValueReferenceType(*Ptr), 7136 *Ptr, 7137 }; 7138 7139 // non-volatile version 7140 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7141 /*IsAssigmentOperator=*/true); 7142 7143 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7144 VisibleTypeConversionsQuals.hasVolatile(); 7145 if (NeedVolatile) { 7146 // volatile version 7147 ParamTypes[0] = 7148 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7149 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7150 CandidateSet, /*IsAssigmentOperator=*/true); 7151 } 7152 7153 if (!(*Ptr).isRestrictQualified() && 7154 VisibleTypeConversionsQuals.hasRestrict()) { 7155 // restrict version 7156 ParamTypes[0] 7157 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7158 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7159 CandidateSet, /*IsAssigmentOperator=*/true); 7160 7161 if (NeedVolatile) { 7162 // volatile restrict version 7163 ParamTypes[0] 7164 = S.Context.getLValueReferenceType( 7165 S.Context.getCVRQualifiedType(*Ptr, 7166 (Qualifiers::Volatile | 7167 Qualifiers::Restrict))); 7168 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7169 CandidateSet, /*IsAssigmentOperator=*/true); 7170 7171 } 7172 } 7173 } 7174 } 7175 } 7176 7177 // C++ [over.built]p18: 7178 // 7179 // For every triple (L, VQ, R), where L is an arithmetic type, 7180 // VQ is either volatile or empty, and R is a promoted 7181 // arithmetic type, there exist candidate operator functions of 7182 // the form 7183 // 7184 // VQ L& operator=(VQ L&, R); 7185 // VQ L& operator*=(VQ L&, R); 7186 // VQ L& operator/=(VQ L&, R); 7187 // VQ L& operator+=(VQ L&, R); 7188 // VQ L& operator-=(VQ L&, R); 7189 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7190 if (!HasArithmeticOrEnumeralCandidateType) 7191 return; 7192 7193 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7194 for (unsigned Right = FirstPromotedArithmeticType; 7195 Right < LastPromotedArithmeticType; ++Right) { 7196 QualType ParamTypes[2]; 7197 ParamTypes[1] = getArithmeticType(Right); 7198 7199 // Add this built-in operator as a candidate (VQ is empty). 7200 ParamTypes[0] = 7201 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7202 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7203 /*IsAssigmentOperator=*/isEqualOp); 7204 7205 // Add this built-in operator as a candidate (VQ is 'volatile'). 7206 if (VisibleTypeConversionsQuals.hasVolatile()) { 7207 ParamTypes[0] = 7208 S.Context.getVolatileType(getArithmeticType(Left)); 7209 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7210 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7211 CandidateSet, 7212 /*IsAssigmentOperator=*/isEqualOp); 7213 } 7214 } 7215 } 7216 7217 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7218 for (BuiltinCandidateTypeSet::iterator 7219 Vec1 = CandidateTypes[0].vector_begin(), 7220 Vec1End = CandidateTypes[0].vector_end(); 7221 Vec1 != Vec1End; ++Vec1) { 7222 for (BuiltinCandidateTypeSet::iterator 7223 Vec2 = CandidateTypes[1].vector_begin(), 7224 Vec2End = CandidateTypes[1].vector_end(); 7225 Vec2 != Vec2End; ++Vec2) { 7226 QualType ParamTypes[2]; 7227 ParamTypes[1] = *Vec2; 7228 // Add this built-in operator as a candidate (VQ is empty). 7229 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7230 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7231 /*IsAssigmentOperator=*/isEqualOp); 7232 7233 // Add this built-in operator as a candidate (VQ is 'volatile'). 7234 if (VisibleTypeConversionsQuals.hasVolatile()) { 7235 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7236 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7237 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7238 CandidateSet, 7239 /*IsAssigmentOperator=*/isEqualOp); 7240 } 7241 } 7242 } 7243 } 7244 7245 // C++ [over.built]p22: 7246 // 7247 // For every triple (L, VQ, R), where L is an integral type, VQ 7248 // is either volatile or empty, and R is a promoted integral 7249 // type, there exist candidate operator functions of the form 7250 // 7251 // VQ L& operator%=(VQ L&, R); 7252 // VQ L& operator<<=(VQ L&, R); 7253 // VQ L& operator>>=(VQ L&, R); 7254 // VQ L& operator&=(VQ L&, R); 7255 // VQ L& operator^=(VQ L&, R); 7256 // VQ L& operator|=(VQ L&, R); 7257 void addAssignmentIntegralOverloads() { 7258 if (!HasArithmeticOrEnumeralCandidateType) 7259 return; 7260 7261 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7262 for (unsigned Right = FirstPromotedIntegralType; 7263 Right < LastPromotedIntegralType; ++Right) { 7264 QualType ParamTypes[2]; 7265 ParamTypes[1] = getArithmeticType(Right); 7266 7267 // Add this built-in operator as a candidate (VQ is empty). 7268 ParamTypes[0] = 7269 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7270 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 7271 if (VisibleTypeConversionsQuals.hasVolatile()) { 7272 // Add this built-in operator as a candidate (VQ is 'volatile'). 7273 ParamTypes[0] = getArithmeticType(Left); 7274 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7275 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7276 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7277 CandidateSet); 7278 } 7279 } 7280 } 7281 } 7282 7283 // C++ [over.operator]p23: 7284 // 7285 // There also exist candidate operator functions of the form 7286 // 7287 // bool operator!(bool); 7288 // bool operator&&(bool, bool); 7289 // bool operator||(bool, bool); 7290 void addExclaimOverload() { 7291 QualType ParamTy = S.Context.BoolTy; 7292 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet, 7293 /*IsAssignmentOperator=*/false, 7294 /*NumContextualBoolArguments=*/1); 7295 } 7296 void addAmpAmpOrPipePipeOverload() { 7297 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7298 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet, 7299 /*IsAssignmentOperator=*/false, 7300 /*NumContextualBoolArguments=*/2); 7301 } 7302 7303 // C++ [over.built]p13: 7304 // 7305 // For every cv-qualified or cv-unqualified object type T there 7306 // exist candidate operator functions of the form 7307 // 7308 // T* operator+(T*, ptrdiff_t); [ABOVE] 7309 // T& operator[](T*, ptrdiff_t); 7310 // T* operator-(T*, ptrdiff_t); [ABOVE] 7311 // T* operator+(ptrdiff_t, T*); [ABOVE] 7312 // T& operator[](ptrdiff_t, T*); 7313 void addSubscriptOverloads() { 7314 for (BuiltinCandidateTypeSet::iterator 7315 Ptr = CandidateTypes[0].pointer_begin(), 7316 PtrEnd = CandidateTypes[0].pointer_end(); 7317 Ptr != PtrEnd; ++Ptr) { 7318 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7319 QualType PointeeType = (*Ptr)->getPointeeType(); 7320 if (!PointeeType->isObjectType()) 7321 continue; 7322 7323 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7324 7325 // T& operator[](T*, ptrdiff_t) 7326 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7327 } 7328 7329 for (BuiltinCandidateTypeSet::iterator 7330 Ptr = CandidateTypes[1].pointer_begin(), 7331 PtrEnd = CandidateTypes[1].pointer_end(); 7332 Ptr != PtrEnd; ++Ptr) { 7333 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7334 QualType PointeeType = (*Ptr)->getPointeeType(); 7335 if (!PointeeType->isObjectType()) 7336 continue; 7337 7338 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7339 7340 // T& operator[](ptrdiff_t, T*) 7341 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7342 } 7343 } 7344 7345 // C++ [over.built]p11: 7346 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7347 // C1 is the same type as C2 or is a derived class of C2, T is an object 7348 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7349 // there exist candidate operator functions of the form 7350 // 7351 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7352 // 7353 // where CV12 is the union of CV1 and CV2. 7354 void addArrowStarOverloads() { 7355 for (BuiltinCandidateTypeSet::iterator 7356 Ptr = CandidateTypes[0].pointer_begin(), 7357 PtrEnd = CandidateTypes[0].pointer_end(); 7358 Ptr != PtrEnd; ++Ptr) { 7359 QualType C1Ty = (*Ptr); 7360 QualType C1; 7361 QualifierCollector Q1; 7362 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 7363 if (!isa<RecordType>(C1)) 7364 continue; 7365 // heuristic to reduce number of builtin candidates in the set. 7366 // Add volatile/restrict version only if there are conversions to a 7367 // volatile/restrict type. 7368 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 7369 continue; 7370 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 7371 continue; 7372 for (BuiltinCandidateTypeSet::iterator 7373 MemPtr = CandidateTypes[1].member_pointer_begin(), 7374 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 7375 MemPtr != MemPtrEnd; ++MemPtr) { 7376 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 7377 QualType C2 = QualType(mptr->getClass(), 0); 7378 C2 = C2.getUnqualifiedType(); 7379 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 7380 break; 7381 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 7382 // build CV12 T& 7383 QualType T = mptr->getPointeeType(); 7384 if (!VisibleTypeConversionsQuals.hasVolatile() && 7385 T.isVolatileQualified()) 7386 continue; 7387 if (!VisibleTypeConversionsQuals.hasRestrict() && 7388 T.isRestrictQualified()) 7389 continue; 7390 T = Q1.apply(S.Context, T); 7391 QualType ResultTy = S.Context.getLValueReferenceType(T); 7392 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7393 } 7394 } 7395 } 7396 7397 // Note that we don't consider the first argument, since it has been 7398 // contextually converted to bool long ago. The candidates below are 7399 // therefore added as binary. 7400 // 7401 // C++ [over.built]p25: 7402 // For every type T, where T is a pointer, pointer-to-member, or scoped 7403 // enumeration type, there exist candidate operator functions of the form 7404 // 7405 // T operator?(bool, T, T); 7406 // 7407 void addConditionalOperatorOverloads() { 7408 /// Set of (canonical) types that we've already handled. 7409 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7410 7411 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7412 for (BuiltinCandidateTypeSet::iterator 7413 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7414 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7415 Ptr != PtrEnd; ++Ptr) { 7416 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7417 continue; 7418 7419 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7420 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 7421 } 7422 7423 for (BuiltinCandidateTypeSet::iterator 7424 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7425 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7426 MemPtr != MemPtrEnd; ++MemPtr) { 7427 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7428 continue; 7429 7430 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7431 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet); 7432 } 7433 7434 if (S.getLangOpts().CPlusPlus0x) { 7435 for (BuiltinCandidateTypeSet::iterator 7436 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7437 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7438 Enum != EnumEnd; ++Enum) { 7439 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 7440 continue; 7441 7442 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7443 continue; 7444 7445 QualType ParamTypes[2] = { *Enum, *Enum }; 7446 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet); 7447 } 7448 } 7449 } 7450 } 7451 }; 7452 7453 } // end anonymous namespace 7454 7455 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 7456 /// operator overloads to the candidate set (C++ [over.built]), based 7457 /// on the operator @p Op and the arguments given. For example, if the 7458 /// operator is a binary '+', this routine might add "int 7459 /// operator+(int, int)" to cover integer addition. 7460 void 7461 Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 7462 SourceLocation OpLoc, 7463 Expr **Args, unsigned NumArgs, 7464 OverloadCandidateSet& CandidateSet) { 7465 // Find all of the types that the arguments can convert to, but only 7466 // if the operator we're looking at has built-in operator candidates 7467 // that make use of these types. Also record whether we encounter non-record 7468 // candidate types or either arithmetic or enumeral candidate types. 7469 Qualifiers VisibleTypeConversionsQuals; 7470 VisibleTypeConversionsQuals.addConst(); 7471 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 7472 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 7473 7474 bool HasNonRecordCandidateType = false; 7475 bool HasArithmeticOrEnumeralCandidateType = false; 7476 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 7477 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 7478 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 7479 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 7480 OpLoc, 7481 true, 7482 (Op == OO_Exclaim || 7483 Op == OO_AmpAmp || 7484 Op == OO_PipePipe), 7485 VisibleTypeConversionsQuals); 7486 HasNonRecordCandidateType = HasNonRecordCandidateType || 7487 CandidateTypes[ArgIdx].hasNonRecordTypes(); 7488 HasArithmeticOrEnumeralCandidateType = 7489 HasArithmeticOrEnumeralCandidateType || 7490 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 7491 } 7492 7493 // Exit early when no non-record types have been added to the candidate set 7494 // for any of the arguments to the operator. 7495 // 7496 // We can't exit early for !, ||, or &&, since there we have always have 7497 // 'bool' overloads. 7498 if (!HasNonRecordCandidateType && 7499 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 7500 return; 7501 7502 // Setup an object to manage the common state for building overloads. 7503 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs, 7504 VisibleTypeConversionsQuals, 7505 HasArithmeticOrEnumeralCandidateType, 7506 CandidateTypes, CandidateSet); 7507 7508 // Dispatch over the operation to add in only those overloads which apply. 7509 switch (Op) { 7510 case OO_None: 7511 case NUM_OVERLOADED_OPERATORS: 7512 llvm_unreachable("Expected an overloaded operator"); 7513 7514 case OO_New: 7515 case OO_Delete: 7516 case OO_Array_New: 7517 case OO_Array_Delete: 7518 case OO_Call: 7519 llvm_unreachable( 7520 "Special operators don't use AddBuiltinOperatorCandidates"); 7521 7522 case OO_Comma: 7523 case OO_Arrow: 7524 // C++ [over.match.oper]p3: 7525 // -- For the operator ',', the unary operator '&', or the 7526 // operator '->', the built-in candidates set is empty. 7527 break; 7528 7529 case OO_Plus: // '+' is either unary or binary 7530 if (NumArgs == 1) 7531 OpBuilder.addUnaryPlusPointerOverloads(); 7532 // Fall through. 7533 7534 case OO_Minus: // '-' is either unary or binary 7535 if (NumArgs == 1) { 7536 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 7537 } else { 7538 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 7539 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7540 } 7541 break; 7542 7543 case OO_Star: // '*' is either unary or binary 7544 if (NumArgs == 1) 7545 OpBuilder.addUnaryStarPointerOverloads(); 7546 else 7547 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7548 break; 7549 7550 case OO_Slash: 7551 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7552 break; 7553 7554 case OO_PlusPlus: 7555 case OO_MinusMinus: 7556 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 7557 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 7558 break; 7559 7560 case OO_EqualEqual: 7561 case OO_ExclaimEqual: 7562 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 7563 // Fall through. 7564 7565 case OO_Less: 7566 case OO_Greater: 7567 case OO_LessEqual: 7568 case OO_GreaterEqual: 7569 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 7570 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 7571 break; 7572 7573 case OO_Percent: 7574 case OO_Caret: 7575 case OO_Pipe: 7576 case OO_LessLess: 7577 case OO_GreaterGreater: 7578 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7579 break; 7580 7581 case OO_Amp: // '&' is either unary or binary 7582 if (NumArgs == 1) 7583 // C++ [over.match.oper]p3: 7584 // -- For the operator ',', the unary operator '&', or the 7585 // operator '->', the built-in candidates set is empty. 7586 break; 7587 7588 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7589 break; 7590 7591 case OO_Tilde: 7592 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 7593 break; 7594 7595 case OO_Equal: 7596 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 7597 // Fall through. 7598 7599 case OO_PlusEqual: 7600 case OO_MinusEqual: 7601 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 7602 // Fall through. 7603 7604 case OO_StarEqual: 7605 case OO_SlashEqual: 7606 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 7607 break; 7608 7609 case OO_PercentEqual: 7610 case OO_LessLessEqual: 7611 case OO_GreaterGreaterEqual: 7612 case OO_AmpEqual: 7613 case OO_CaretEqual: 7614 case OO_PipeEqual: 7615 OpBuilder.addAssignmentIntegralOverloads(); 7616 break; 7617 7618 case OO_Exclaim: 7619 OpBuilder.addExclaimOverload(); 7620 break; 7621 7622 case OO_AmpAmp: 7623 case OO_PipePipe: 7624 OpBuilder.addAmpAmpOrPipePipeOverload(); 7625 break; 7626 7627 case OO_Subscript: 7628 OpBuilder.addSubscriptOverloads(); 7629 break; 7630 7631 case OO_ArrowStar: 7632 OpBuilder.addArrowStarOverloads(); 7633 break; 7634 7635 case OO_Conditional: 7636 OpBuilder.addConditionalOperatorOverloads(); 7637 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7638 break; 7639 } 7640 } 7641 7642 /// \brief Add function candidates found via argument-dependent lookup 7643 /// to the set of overloading candidates. 7644 /// 7645 /// This routine performs argument-dependent name lookup based on the 7646 /// given function name (which may also be an operator name) and adds 7647 /// all of the overload candidates found by ADL to the overload 7648 /// candidate set (C++ [basic.lookup.argdep]). 7649 void 7650 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 7651 bool Operator, SourceLocation Loc, 7652 llvm::ArrayRef<Expr *> Args, 7653 TemplateArgumentListInfo *ExplicitTemplateArgs, 7654 OverloadCandidateSet& CandidateSet, 7655 bool PartialOverloading, 7656 bool StdNamespaceIsAssociated) { 7657 ADLResult Fns; 7658 7659 // FIXME: This approach for uniquing ADL results (and removing 7660 // redundant candidates from the set) relies on pointer-equality, 7661 // which means we need to key off the canonical decl. However, 7662 // always going back to the canonical decl might not get us the 7663 // right set of default arguments. What default arguments are 7664 // we supposed to consider on ADL candidates, anyway? 7665 7666 // FIXME: Pass in the explicit template arguments? 7667 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns, 7668 StdNamespaceIsAssociated); 7669 7670 // Erase all of the candidates we already knew about. 7671 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 7672 CandEnd = CandidateSet.end(); 7673 Cand != CandEnd; ++Cand) 7674 if (Cand->Function) { 7675 Fns.erase(Cand->Function); 7676 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 7677 Fns.erase(FunTmpl); 7678 } 7679 7680 // For each of the ADL candidates we found, add it to the overload 7681 // set. 7682 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 7683 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 7684 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 7685 if (ExplicitTemplateArgs) 7686 continue; 7687 7688 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 7689 PartialOverloading); 7690 } else 7691 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 7692 FoundDecl, ExplicitTemplateArgs, 7693 Args, CandidateSet); 7694 } 7695 } 7696 7697 /// isBetterOverloadCandidate - Determines whether the first overload 7698 /// candidate is a better candidate than the second (C++ 13.3.3p1). 7699 bool 7700 isBetterOverloadCandidate(Sema &S, 7701 const OverloadCandidate &Cand1, 7702 const OverloadCandidate &Cand2, 7703 SourceLocation Loc, 7704 bool UserDefinedConversion) { 7705 // Define viable functions to be better candidates than non-viable 7706 // functions. 7707 if (!Cand2.Viable) 7708 return Cand1.Viable; 7709 else if (!Cand1.Viable) 7710 return false; 7711 7712 // C++ [over.match.best]p1: 7713 // 7714 // -- if F is a static member function, ICS1(F) is defined such 7715 // that ICS1(F) is neither better nor worse than ICS1(G) for 7716 // any function G, and, symmetrically, ICS1(G) is neither 7717 // better nor worse than ICS1(F). 7718 unsigned StartArg = 0; 7719 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 7720 StartArg = 1; 7721 7722 // C++ [over.match.best]p1: 7723 // A viable function F1 is defined to be a better function than another 7724 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 7725 // conversion sequence than ICSi(F2), and then... 7726 unsigned NumArgs = Cand1.NumConversions; 7727 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 7728 bool HasBetterConversion = false; 7729 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 7730 switch (CompareImplicitConversionSequences(S, 7731 Cand1.Conversions[ArgIdx], 7732 Cand2.Conversions[ArgIdx])) { 7733 case ImplicitConversionSequence::Better: 7734 // Cand1 has a better conversion sequence. 7735 HasBetterConversion = true; 7736 break; 7737 7738 case ImplicitConversionSequence::Worse: 7739 // Cand1 can't be better than Cand2. 7740 return false; 7741 7742 case ImplicitConversionSequence::Indistinguishable: 7743 // Do nothing. 7744 break; 7745 } 7746 } 7747 7748 // -- for some argument j, ICSj(F1) is a better conversion sequence than 7749 // ICSj(F2), or, if not that, 7750 if (HasBetterConversion) 7751 return true; 7752 7753 // - F1 is a non-template function and F2 is a function template 7754 // specialization, or, if not that, 7755 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 7756 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 7757 return true; 7758 7759 // -- F1 and F2 are function template specializations, and the function 7760 // template for F1 is more specialized than the template for F2 7761 // according to the partial ordering rules described in 14.5.5.2, or, 7762 // if not that, 7763 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 7764 Cand2.Function && Cand2.Function->getPrimaryTemplate()) { 7765 if (FunctionTemplateDecl *BetterTemplate 7766 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 7767 Cand2.Function->getPrimaryTemplate(), 7768 Loc, 7769 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 7770 : TPOC_Call, 7771 Cand1.ExplicitCallArguments)) 7772 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 7773 } 7774 7775 // -- the context is an initialization by user-defined conversion 7776 // (see 8.5, 13.3.1.5) and the standard conversion sequence 7777 // from the return type of F1 to the destination type (i.e., 7778 // the type of the entity being initialized) is a better 7779 // conversion sequence than the standard conversion sequence 7780 // from the return type of F2 to the destination type. 7781 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 7782 isa<CXXConversionDecl>(Cand1.Function) && 7783 isa<CXXConversionDecl>(Cand2.Function)) { 7784 // First check whether we prefer one of the conversion functions over the 7785 // other. This only distinguishes the results in non-standard, extension 7786 // cases such as the conversion from a lambda closure type to a function 7787 // pointer or block. 7788 ImplicitConversionSequence::CompareKind FuncResult 7789 = compareConversionFunctions(S, Cand1.Function, Cand2.Function); 7790 if (FuncResult != ImplicitConversionSequence::Indistinguishable) 7791 return FuncResult; 7792 7793 switch (CompareStandardConversionSequences(S, 7794 Cand1.FinalConversion, 7795 Cand2.FinalConversion)) { 7796 case ImplicitConversionSequence::Better: 7797 // Cand1 has a better conversion sequence. 7798 return true; 7799 7800 case ImplicitConversionSequence::Worse: 7801 // Cand1 can't be better than Cand2. 7802 return false; 7803 7804 case ImplicitConversionSequence::Indistinguishable: 7805 // Do nothing 7806 break; 7807 } 7808 } 7809 7810 return false; 7811 } 7812 7813 /// \brief Computes the best viable function (C++ 13.3.3) 7814 /// within an overload candidate set. 7815 /// 7816 /// \param Loc The location of the function name (or operator symbol) for 7817 /// which overload resolution occurs. 7818 /// 7819 /// \param Best If overload resolution was successful or found a deleted 7820 /// function, \p Best points to the candidate function found. 7821 /// 7822 /// \returns The result of overload resolution. 7823 OverloadingResult 7824 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 7825 iterator &Best, 7826 bool UserDefinedConversion) { 7827 // Find the best viable function. 7828 Best = end(); 7829 for (iterator Cand = begin(); Cand != end(); ++Cand) { 7830 if (Cand->Viable) 7831 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 7832 UserDefinedConversion)) 7833 Best = Cand; 7834 } 7835 7836 // If we didn't find any viable functions, abort. 7837 if (Best == end()) 7838 return OR_No_Viable_Function; 7839 7840 // Make sure that this function is better than every other viable 7841 // function. If not, we have an ambiguity. 7842 for (iterator Cand = begin(); Cand != end(); ++Cand) { 7843 if (Cand->Viable && 7844 Cand != Best && 7845 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 7846 UserDefinedConversion)) { 7847 Best = end(); 7848 return OR_Ambiguous; 7849 } 7850 } 7851 7852 // Best is the best viable function. 7853 if (Best->Function && 7854 (Best->Function->isDeleted() || 7855 S.isFunctionConsideredUnavailable(Best->Function))) 7856 return OR_Deleted; 7857 7858 return OR_Success; 7859 } 7860 7861 namespace { 7862 7863 enum OverloadCandidateKind { 7864 oc_function, 7865 oc_method, 7866 oc_constructor, 7867 oc_function_template, 7868 oc_method_template, 7869 oc_constructor_template, 7870 oc_implicit_default_constructor, 7871 oc_implicit_copy_constructor, 7872 oc_implicit_move_constructor, 7873 oc_implicit_copy_assignment, 7874 oc_implicit_move_assignment, 7875 oc_implicit_inherited_constructor 7876 }; 7877 7878 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 7879 FunctionDecl *Fn, 7880 std::string &Description) { 7881 bool isTemplate = false; 7882 7883 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 7884 isTemplate = true; 7885 Description = S.getTemplateArgumentBindingsText( 7886 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 7887 } 7888 7889 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 7890 if (!Ctor->isImplicit()) 7891 return isTemplate ? oc_constructor_template : oc_constructor; 7892 7893 if (Ctor->getInheritedConstructor()) 7894 return oc_implicit_inherited_constructor; 7895 7896 if (Ctor->isDefaultConstructor()) 7897 return oc_implicit_default_constructor; 7898 7899 if (Ctor->isMoveConstructor()) 7900 return oc_implicit_move_constructor; 7901 7902 assert(Ctor->isCopyConstructor() && 7903 "unexpected sort of implicit constructor"); 7904 return oc_implicit_copy_constructor; 7905 } 7906 7907 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 7908 // This actually gets spelled 'candidate function' for now, but 7909 // it doesn't hurt to split it out. 7910 if (!Meth->isImplicit()) 7911 return isTemplate ? oc_method_template : oc_method; 7912 7913 if (Meth->isMoveAssignmentOperator()) 7914 return oc_implicit_move_assignment; 7915 7916 if (Meth->isCopyAssignmentOperator()) 7917 return oc_implicit_copy_assignment; 7918 7919 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 7920 return oc_method; 7921 } 7922 7923 return isTemplate ? oc_function_template : oc_function; 7924 } 7925 7926 void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) { 7927 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 7928 if (!Ctor) return; 7929 7930 Ctor = Ctor->getInheritedConstructor(); 7931 if (!Ctor) return; 7932 7933 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 7934 } 7935 7936 } // end anonymous namespace 7937 7938 // Notes the location of an overload candidate. 7939 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 7940 std::string FnDesc; 7941 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 7942 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 7943 << (unsigned) K << FnDesc; 7944 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 7945 Diag(Fn->getLocation(), PD); 7946 MaybeEmitInheritedConstructorNote(*this, Fn); 7947 } 7948 7949 //Notes the location of all overload candidates designated through 7950 // OverloadedExpr 7951 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 7952 assert(OverloadedExpr->getType() == Context.OverloadTy); 7953 7954 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 7955 OverloadExpr *OvlExpr = Ovl.Expression; 7956 7957 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 7958 IEnd = OvlExpr->decls_end(); 7959 I != IEnd; ++I) { 7960 if (FunctionTemplateDecl *FunTmpl = 7961 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 7962 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 7963 } else if (FunctionDecl *Fun 7964 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 7965 NoteOverloadCandidate(Fun, DestType); 7966 } 7967 } 7968 } 7969 7970 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 7971 /// "lead" diagnostic; it will be given two arguments, the source and 7972 /// target types of the conversion. 7973 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 7974 Sema &S, 7975 SourceLocation CaretLoc, 7976 const PartialDiagnostic &PDiag) const { 7977 S.Diag(CaretLoc, PDiag) 7978 << Ambiguous.getFromType() << Ambiguous.getToType(); 7979 for (AmbiguousConversionSequence::const_iterator 7980 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 7981 S.NoteOverloadCandidate(*I); 7982 } 7983 } 7984 7985 namespace { 7986 7987 void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 7988 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 7989 assert(Conv.isBad()); 7990 assert(Cand->Function && "for now, candidate must be a function"); 7991 FunctionDecl *Fn = Cand->Function; 7992 7993 // There's a conversion slot for the object argument if this is a 7994 // non-constructor method. Note that 'I' corresponds the 7995 // conversion-slot index. 7996 bool isObjectArgument = false; 7997 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 7998 if (I == 0) 7999 isObjectArgument = true; 8000 else 8001 I--; 8002 } 8003 8004 std::string FnDesc; 8005 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8006 8007 Expr *FromExpr = Conv.Bad.FromExpr; 8008 QualType FromTy = Conv.Bad.getFromType(); 8009 QualType ToTy = Conv.Bad.getToType(); 8010 8011 if (FromTy == S.Context.OverloadTy) { 8012 assert(FromExpr && "overload set argument came from implicit argument?"); 8013 Expr *E = FromExpr->IgnoreParens(); 8014 if (isa<UnaryOperator>(E)) 8015 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8016 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8017 8018 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8019 << (unsigned) FnKind << FnDesc 8020 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8021 << ToTy << Name << I+1; 8022 MaybeEmitInheritedConstructorNote(S, Fn); 8023 return; 8024 } 8025 8026 // Do some hand-waving analysis to see if the non-viability is due 8027 // to a qualifier mismatch. 8028 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8029 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8030 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8031 CToTy = RT->getPointeeType(); 8032 else { 8033 // TODO: detect and diagnose the full richness of const mismatches. 8034 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8035 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8036 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8037 } 8038 8039 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8040 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8041 Qualifiers FromQs = CFromTy.getQualifiers(); 8042 Qualifiers ToQs = CToTy.getQualifiers(); 8043 8044 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8045 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8046 << (unsigned) FnKind << FnDesc 8047 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8048 << FromTy 8049 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8050 << (unsigned) isObjectArgument << I+1; 8051 MaybeEmitInheritedConstructorNote(S, Fn); 8052 return; 8053 } 8054 8055 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8056 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8057 << (unsigned) FnKind << FnDesc 8058 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8059 << FromTy 8060 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8061 << (unsigned) isObjectArgument << I+1; 8062 MaybeEmitInheritedConstructorNote(S, Fn); 8063 return; 8064 } 8065 8066 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8067 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8068 << (unsigned) FnKind << FnDesc 8069 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8070 << FromTy 8071 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8072 << (unsigned) isObjectArgument << I+1; 8073 MaybeEmitInheritedConstructorNote(S, Fn); 8074 return; 8075 } 8076 8077 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8078 assert(CVR && "unexpected qualifiers mismatch"); 8079 8080 if (isObjectArgument) { 8081 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8082 << (unsigned) FnKind << FnDesc 8083 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8084 << FromTy << (CVR - 1); 8085 } else { 8086 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8087 << (unsigned) FnKind << FnDesc 8088 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8089 << FromTy << (CVR - 1) << I+1; 8090 } 8091 MaybeEmitInheritedConstructorNote(S, Fn); 8092 return; 8093 } 8094 8095 // Special diagnostic for failure to convert an initializer list, since 8096 // telling the user that it has type void is not useful. 8097 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8098 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8099 << (unsigned) FnKind << FnDesc 8100 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8101 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8102 MaybeEmitInheritedConstructorNote(S, Fn); 8103 return; 8104 } 8105 8106 // Diagnose references or pointers to incomplete types differently, 8107 // since it's far from impossible that the incompleteness triggered 8108 // the failure. 8109 QualType TempFromTy = FromTy.getNonReferenceType(); 8110 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8111 TempFromTy = PTy->getPointeeType(); 8112 if (TempFromTy->isIncompleteType()) { 8113 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8114 << (unsigned) FnKind << FnDesc 8115 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8116 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8117 MaybeEmitInheritedConstructorNote(S, Fn); 8118 return; 8119 } 8120 8121 // Diagnose base -> derived pointer conversions. 8122 unsigned BaseToDerivedConversion = 0; 8123 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8124 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8125 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8126 FromPtrTy->getPointeeType()) && 8127 !FromPtrTy->getPointeeType()->isIncompleteType() && 8128 !ToPtrTy->getPointeeType()->isIncompleteType() && 8129 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8130 FromPtrTy->getPointeeType())) 8131 BaseToDerivedConversion = 1; 8132 } 8133 } else if (const ObjCObjectPointerType *FromPtrTy 8134 = FromTy->getAs<ObjCObjectPointerType>()) { 8135 if (const ObjCObjectPointerType *ToPtrTy 8136 = ToTy->getAs<ObjCObjectPointerType>()) 8137 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8138 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8139 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8140 FromPtrTy->getPointeeType()) && 8141 FromIface->isSuperClassOf(ToIface)) 8142 BaseToDerivedConversion = 2; 8143 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8144 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8145 !FromTy->isIncompleteType() && 8146 !ToRefTy->getPointeeType()->isIncompleteType() && 8147 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8148 BaseToDerivedConversion = 3; 8149 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8150 ToTy.getNonReferenceType().getCanonicalType() == 8151 FromTy.getNonReferenceType().getCanonicalType()) { 8152 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8153 << (unsigned) FnKind << FnDesc 8154 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8155 << (unsigned) isObjectArgument << I + 1; 8156 MaybeEmitInheritedConstructorNote(S, Fn); 8157 return; 8158 } 8159 } 8160 8161 if (BaseToDerivedConversion) { 8162 S.Diag(Fn->getLocation(), 8163 diag::note_ovl_candidate_bad_base_to_derived_conv) 8164 << (unsigned) FnKind << FnDesc 8165 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8166 << (BaseToDerivedConversion - 1) 8167 << FromTy << ToTy << I+1; 8168 MaybeEmitInheritedConstructorNote(S, Fn); 8169 return; 8170 } 8171 8172 if (isa<ObjCObjectPointerType>(CFromTy) && 8173 isa<PointerType>(CToTy)) { 8174 Qualifiers FromQs = CFromTy.getQualifiers(); 8175 Qualifiers ToQs = CToTy.getQualifiers(); 8176 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8177 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8178 << (unsigned) FnKind << FnDesc 8179 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8180 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8181 MaybeEmitInheritedConstructorNote(S, Fn); 8182 return; 8183 } 8184 } 8185 8186 // Emit the generic diagnostic and, optionally, add the hints to it. 8187 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8188 FDiag << (unsigned) FnKind << FnDesc 8189 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8190 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8191 << (unsigned) (Cand->Fix.Kind); 8192 8193 // If we can fix the conversion, suggest the FixIts. 8194 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8195 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8196 FDiag << *HI; 8197 S.Diag(Fn->getLocation(), FDiag); 8198 8199 MaybeEmitInheritedConstructorNote(S, Fn); 8200 } 8201 8202 void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8203 unsigned NumFormalArgs) { 8204 // TODO: treat calls to a missing default constructor as a special case 8205 8206 FunctionDecl *Fn = Cand->Function; 8207 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8208 8209 unsigned MinParams = Fn->getMinRequiredArguments(); 8210 8211 // With invalid overloaded operators, it's possible that we think we 8212 // have an arity mismatch when it fact it looks like we have the 8213 // right number of arguments, because only overloaded operators have 8214 // the weird behavior of overloading member and non-member functions. 8215 // Just don't report anything. 8216 if (Fn->isInvalidDecl() && 8217 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8218 return; 8219 8220 // at least / at most / exactly 8221 unsigned mode, modeCount; 8222 if (NumFormalArgs < MinParams) { 8223 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8224 (Cand->FailureKind == ovl_fail_bad_deduction && 8225 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8226 if (MinParams != FnTy->getNumArgs() || 8227 FnTy->isVariadic() || FnTy->isTemplateVariadic()) 8228 mode = 0; // "at least" 8229 else 8230 mode = 2; // "exactly" 8231 modeCount = MinParams; 8232 } else { 8233 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8234 (Cand->FailureKind == ovl_fail_bad_deduction && 8235 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8236 if (MinParams != FnTy->getNumArgs()) 8237 mode = 1; // "at most" 8238 else 8239 mode = 2; // "exactly" 8240 modeCount = FnTy->getNumArgs(); 8241 } 8242 8243 std::string Description; 8244 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8245 8246 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8247 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8248 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8249 << Fn->getParamDecl(0) << NumFormalArgs; 8250 else 8251 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8252 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8253 << modeCount << NumFormalArgs; 8254 MaybeEmitInheritedConstructorNote(S, Fn); 8255 } 8256 8257 /// Diagnose a failed template-argument deduction. 8258 void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 8259 unsigned NumArgs) { 8260 FunctionDecl *Fn = Cand->Function; // pattern 8261 8262 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter(); 8263 NamedDecl *ParamD; 8264 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8265 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8266 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8267 switch (Cand->DeductionFailure.Result) { 8268 case Sema::TDK_Success: 8269 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8270 8271 case Sema::TDK_Incomplete: { 8272 assert(ParamD && "no parameter found for incomplete deduction result"); 8273 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction) 8274 << ParamD->getDeclName(); 8275 MaybeEmitInheritedConstructorNote(S, Fn); 8276 return; 8277 } 8278 8279 case Sema::TDK_Underqualified: { 8280 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8281 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 8282 8283 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType(); 8284 8285 // Param will have been canonicalized, but it should just be a 8286 // qualified version of ParamD, so move the qualifiers to that. 8287 QualifierCollector Qs; 8288 Qs.strip(Param); 8289 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 8290 assert(S.Context.hasSameType(Param, NonCanonParam)); 8291 8292 // Arg has also been canonicalized, but there's nothing we can do 8293 // about that. It also doesn't matter as much, because it won't 8294 // have any template parameters in it (because deduction isn't 8295 // done on dependent types). 8296 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType(); 8297 8298 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified) 8299 << ParamD->getDeclName() << Arg << NonCanonParam; 8300 MaybeEmitInheritedConstructorNote(S, Fn); 8301 return; 8302 } 8303 8304 case Sema::TDK_Inconsistent: { 8305 assert(ParamD && "no parameter found for inconsistent deduction result"); 8306 int which = 0; 8307 if (isa<TemplateTypeParmDecl>(ParamD)) 8308 which = 0; 8309 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 8310 which = 1; 8311 else { 8312 which = 2; 8313 } 8314 8315 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction) 8316 << which << ParamD->getDeclName() 8317 << *Cand->DeductionFailure.getFirstArg() 8318 << *Cand->DeductionFailure.getSecondArg(); 8319 MaybeEmitInheritedConstructorNote(S, Fn); 8320 return; 8321 } 8322 8323 case Sema::TDK_InvalidExplicitArguments: 8324 assert(ParamD && "no parameter found for invalid explicit arguments"); 8325 if (ParamD->getDeclName()) 8326 S.Diag(Fn->getLocation(), 8327 diag::note_ovl_candidate_explicit_arg_mismatch_named) 8328 << ParamD->getDeclName(); 8329 else { 8330 int index = 0; 8331 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 8332 index = TTP->getIndex(); 8333 else if (NonTypeTemplateParmDecl *NTTP 8334 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 8335 index = NTTP->getIndex(); 8336 else 8337 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 8338 S.Diag(Fn->getLocation(), 8339 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 8340 << (index + 1); 8341 } 8342 MaybeEmitInheritedConstructorNote(S, Fn); 8343 return; 8344 8345 case Sema::TDK_TooManyArguments: 8346 case Sema::TDK_TooFewArguments: 8347 DiagnoseArityMismatch(S, Cand, NumArgs); 8348 return; 8349 8350 case Sema::TDK_InstantiationDepth: 8351 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth); 8352 MaybeEmitInheritedConstructorNote(S, Fn); 8353 return; 8354 8355 case Sema::TDK_SubstitutionFailure: { 8356 // Format the template argument list into the argument string. 8357 llvm::SmallString<128> TemplateArgString; 8358 if (TemplateArgumentList *Args = 8359 Cand->DeductionFailure.getTemplateArgumentList()) { 8360 TemplateArgString = " "; 8361 TemplateArgString += S.getTemplateArgumentBindingsText( 8362 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args); 8363 } 8364 8365 // If this candidate was disabled by enable_if, say so. 8366 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic(); 8367 if (PDiag && PDiag->second.getDiagID() == 8368 diag::err_typename_nested_not_found_enable_if) { 8369 // FIXME: Use the source range of the condition, and the fully-qualified 8370 // name of the enable_if template. These are both present in PDiag. 8371 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 8372 << "'enable_if'" << TemplateArgString; 8373 return; 8374 } 8375 8376 // Format the SFINAE diagnostic into the argument string. 8377 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 8378 // formatted message in another diagnostic. 8379 llvm::SmallString<128> SFINAEArgString; 8380 SourceRange R; 8381 if (PDiag) { 8382 SFINAEArgString = ": "; 8383 R = SourceRange(PDiag->first, PDiag->first); 8384 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 8385 } 8386 8387 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure) 8388 << TemplateArgString << SFINAEArgString << R; 8389 MaybeEmitInheritedConstructorNote(S, Fn); 8390 return; 8391 } 8392 8393 // TODO: diagnose these individually, then kill off 8394 // note_ovl_candidate_bad_deduction, which is uselessly vague. 8395 case Sema::TDK_NonDeducedMismatch: 8396 case Sema::TDK_FailedOverloadResolution: 8397 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction); 8398 MaybeEmitInheritedConstructorNote(S, Fn); 8399 return; 8400 } 8401 } 8402 8403 /// CUDA: diagnose an invalid call across targets. 8404 void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 8405 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 8406 FunctionDecl *Callee = Cand->Function; 8407 8408 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 8409 CalleeTarget = S.IdentifyCUDATarget(Callee); 8410 8411 std::string FnDesc; 8412 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 8413 8414 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 8415 << (unsigned) FnKind << CalleeTarget << CallerTarget; 8416 } 8417 8418 /// Generates a 'note' diagnostic for an overload candidate. We've 8419 /// already generated a primary error at the call site. 8420 /// 8421 /// It really does need to be a single diagnostic with its caret 8422 /// pointed at the candidate declaration. Yes, this creates some 8423 /// major challenges of technical writing. Yes, this makes pointing 8424 /// out problems with specific arguments quite awkward. It's still 8425 /// better than generating twenty screens of text for every failed 8426 /// overload. 8427 /// 8428 /// It would be great to be able to express per-candidate problems 8429 /// more richly for those diagnostic clients that cared, but we'd 8430 /// still have to be just as careful with the default diagnostics. 8431 void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 8432 unsigned NumArgs) { 8433 FunctionDecl *Fn = Cand->Function; 8434 8435 // Note deleted candidates, but only if they're viable. 8436 if (Cand->Viable && (Fn->isDeleted() || 8437 S.isFunctionConsideredUnavailable(Fn))) { 8438 std::string FnDesc; 8439 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8440 8441 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 8442 << FnKind << FnDesc 8443 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 8444 MaybeEmitInheritedConstructorNote(S, Fn); 8445 return; 8446 } 8447 8448 // We don't really have anything else to say about viable candidates. 8449 if (Cand->Viable) { 8450 S.NoteOverloadCandidate(Fn); 8451 return; 8452 } 8453 8454 switch (Cand->FailureKind) { 8455 case ovl_fail_too_many_arguments: 8456 case ovl_fail_too_few_arguments: 8457 return DiagnoseArityMismatch(S, Cand, NumArgs); 8458 8459 case ovl_fail_bad_deduction: 8460 return DiagnoseBadDeduction(S, Cand, NumArgs); 8461 8462 case ovl_fail_trivial_conversion: 8463 case ovl_fail_bad_final_conversion: 8464 case ovl_fail_final_conversion_not_exact: 8465 return S.NoteOverloadCandidate(Fn); 8466 8467 case ovl_fail_bad_conversion: { 8468 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 8469 for (unsigned N = Cand->NumConversions; I != N; ++I) 8470 if (Cand->Conversions[I].isBad()) 8471 return DiagnoseBadConversion(S, Cand, I); 8472 8473 // FIXME: this currently happens when we're called from SemaInit 8474 // when user-conversion overload fails. Figure out how to handle 8475 // those conditions and diagnose them well. 8476 return S.NoteOverloadCandidate(Fn); 8477 } 8478 8479 case ovl_fail_bad_target: 8480 return DiagnoseBadTarget(S, Cand); 8481 } 8482 } 8483 8484 void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 8485 // Desugar the type of the surrogate down to a function type, 8486 // retaining as many typedefs as possible while still showing 8487 // the function type (and, therefore, its parameter types). 8488 QualType FnType = Cand->Surrogate->getConversionType(); 8489 bool isLValueReference = false; 8490 bool isRValueReference = false; 8491 bool isPointer = false; 8492 if (const LValueReferenceType *FnTypeRef = 8493 FnType->getAs<LValueReferenceType>()) { 8494 FnType = FnTypeRef->getPointeeType(); 8495 isLValueReference = true; 8496 } else if (const RValueReferenceType *FnTypeRef = 8497 FnType->getAs<RValueReferenceType>()) { 8498 FnType = FnTypeRef->getPointeeType(); 8499 isRValueReference = true; 8500 } 8501 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 8502 FnType = FnTypePtr->getPointeeType(); 8503 isPointer = true; 8504 } 8505 // Desugar down to a function type. 8506 FnType = QualType(FnType->getAs<FunctionType>(), 0); 8507 // Reconstruct the pointer/reference as appropriate. 8508 if (isPointer) FnType = S.Context.getPointerType(FnType); 8509 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 8510 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 8511 8512 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 8513 << FnType; 8514 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 8515 } 8516 8517 void NoteBuiltinOperatorCandidate(Sema &S, 8518 const char *Opc, 8519 SourceLocation OpLoc, 8520 OverloadCandidate *Cand) { 8521 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 8522 std::string TypeStr("operator"); 8523 TypeStr += Opc; 8524 TypeStr += "("; 8525 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 8526 if (Cand->NumConversions == 1) { 8527 TypeStr += ")"; 8528 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 8529 } else { 8530 TypeStr += ", "; 8531 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 8532 TypeStr += ")"; 8533 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 8534 } 8535 } 8536 8537 void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 8538 OverloadCandidate *Cand) { 8539 unsigned NoOperands = Cand->NumConversions; 8540 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 8541 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 8542 if (ICS.isBad()) break; // all meaningless after first invalid 8543 if (!ICS.isAmbiguous()) continue; 8544 8545 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 8546 S.PDiag(diag::note_ambiguous_type_conversion)); 8547 } 8548 } 8549 8550 SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 8551 if (Cand->Function) 8552 return Cand->Function->getLocation(); 8553 if (Cand->IsSurrogate) 8554 return Cand->Surrogate->getLocation(); 8555 return SourceLocation(); 8556 } 8557 8558 static unsigned 8559 RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) { 8560 switch ((Sema::TemplateDeductionResult)DFI.Result) { 8561 case Sema::TDK_Success: 8562 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8563 8564 case Sema::TDK_Incomplete: 8565 return 1; 8566 8567 case Sema::TDK_Underqualified: 8568 case Sema::TDK_Inconsistent: 8569 return 2; 8570 8571 case Sema::TDK_SubstitutionFailure: 8572 case Sema::TDK_NonDeducedMismatch: 8573 return 3; 8574 8575 case Sema::TDK_InstantiationDepth: 8576 case Sema::TDK_FailedOverloadResolution: 8577 return 4; 8578 8579 case Sema::TDK_InvalidExplicitArguments: 8580 return 5; 8581 8582 case Sema::TDK_TooManyArguments: 8583 case Sema::TDK_TooFewArguments: 8584 return 6; 8585 } 8586 llvm_unreachable("Unhandled deduction result"); 8587 } 8588 8589 struct CompareOverloadCandidatesForDisplay { 8590 Sema &S; 8591 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 8592 8593 bool operator()(const OverloadCandidate *L, 8594 const OverloadCandidate *R) { 8595 // Fast-path this check. 8596 if (L == R) return false; 8597 8598 // Order first by viability. 8599 if (L->Viable) { 8600 if (!R->Viable) return true; 8601 8602 // TODO: introduce a tri-valued comparison for overload 8603 // candidates. Would be more worthwhile if we had a sort 8604 // that could exploit it. 8605 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 8606 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 8607 } else if (R->Viable) 8608 return false; 8609 8610 assert(L->Viable == R->Viable); 8611 8612 // Criteria by which we can sort non-viable candidates: 8613 if (!L->Viable) { 8614 // 1. Arity mismatches come after other candidates. 8615 if (L->FailureKind == ovl_fail_too_many_arguments || 8616 L->FailureKind == ovl_fail_too_few_arguments) 8617 return false; 8618 if (R->FailureKind == ovl_fail_too_many_arguments || 8619 R->FailureKind == ovl_fail_too_few_arguments) 8620 return true; 8621 8622 // 2. Bad conversions come first and are ordered by the number 8623 // of bad conversions and quality of good conversions. 8624 if (L->FailureKind == ovl_fail_bad_conversion) { 8625 if (R->FailureKind != ovl_fail_bad_conversion) 8626 return true; 8627 8628 // The conversion that can be fixed with a smaller number of changes, 8629 // comes first. 8630 unsigned numLFixes = L->Fix.NumConversionsFixed; 8631 unsigned numRFixes = R->Fix.NumConversionsFixed; 8632 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 8633 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 8634 if (numLFixes != numRFixes) { 8635 if (numLFixes < numRFixes) 8636 return true; 8637 else 8638 return false; 8639 } 8640 8641 // If there's any ordering between the defined conversions... 8642 // FIXME: this might not be transitive. 8643 assert(L->NumConversions == R->NumConversions); 8644 8645 int leftBetter = 0; 8646 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 8647 for (unsigned E = L->NumConversions; I != E; ++I) { 8648 switch (CompareImplicitConversionSequences(S, 8649 L->Conversions[I], 8650 R->Conversions[I])) { 8651 case ImplicitConversionSequence::Better: 8652 leftBetter++; 8653 break; 8654 8655 case ImplicitConversionSequence::Worse: 8656 leftBetter--; 8657 break; 8658 8659 case ImplicitConversionSequence::Indistinguishable: 8660 break; 8661 } 8662 } 8663 if (leftBetter > 0) return true; 8664 if (leftBetter < 0) return false; 8665 8666 } else if (R->FailureKind == ovl_fail_bad_conversion) 8667 return false; 8668 8669 if (L->FailureKind == ovl_fail_bad_deduction) { 8670 if (R->FailureKind != ovl_fail_bad_deduction) 8671 return true; 8672 8673 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 8674 return RankDeductionFailure(L->DeductionFailure) 8675 < RankDeductionFailure(R->DeductionFailure); 8676 } else if (R->FailureKind == ovl_fail_bad_deduction) 8677 return false; 8678 8679 // TODO: others? 8680 } 8681 8682 // Sort everything else by location. 8683 SourceLocation LLoc = GetLocationForCandidate(L); 8684 SourceLocation RLoc = GetLocationForCandidate(R); 8685 8686 // Put candidates without locations (e.g. builtins) at the end. 8687 if (LLoc.isInvalid()) return false; 8688 if (RLoc.isInvalid()) return true; 8689 8690 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 8691 } 8692 }; 8693 8694 /// CompleteNonViableCandidate - Normally, overload resolution only 8695 /// computes up to the first. Produces the FixIt set if possible. 8696 void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 8697 llvm::ArrayRef<Expr *> Args) { 8698 assert(!Cand->Viable); 8699 8700 // Don't do anything on failures other than bad conversion. 8701 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 8702 8703 // We only want the FixIts if all the arguments can be corrected. 8704 bool Unfixable = false; 8705 // Use a implicit copy initialization to check conversion fixes. 8706 Cand->Fix.setConversionChecker(TryCopyInitialization); 8707 8708 // Skip forward to the first bad conversion. 8709 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 8710 unsigned ConvCount = Cand->NumConversions; 8711 while (true) { 8712 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 8713 ConvIdx++; 8714 if (Cand->Conversions[ConvIdx - 1].isBad()) { 8715 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 8716 break; 8717 } 8718 } 8719 8720 if (ConvIdx == ConvCount) 8721 return; 8722 8723 assert(!Cand->Conversions[ConvIdx].isInitialized() && 8724 "remaining conversion is initialized?"); 8725 8726 // FIXME: this should probably be preserved from the overload 8727 // operation somehow. 8728 bool SuppressUserConversions = false; 8729 8730 const FunctionProtoType* Proto; 8731 unsigned ArgIdx = ConvIdx; 8732 8733 if (Cand->IsSurrogate) { 8734 QualType ConvType 8735 = Cand->Surrogate->getConversionType().getNonReferenceType(); 8736 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 8737 ConvType = ConvPtrType->getPointeeType(); 8738 Proto = ConvType->getAs<FunctionProtoType>(); 8739 ArgIdx--; 8740 } else if (Cand->Function) { 8741 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 8742 if (isa<CXXMethodDecl>(Cand->Function) && 8743 !isa<CXXConstructorDecl>(Cand->Function)) 8744 ArgIdx--; 8745 } else { 8746 // Builtin binary operator with a bad first conversion. 8747 assert(ConvCount <= 3); 8748 for (; ConvIdx != ConvCount; ++ConvIdx) 8749 Cand->Conversions[ConvIdx] 8750 = TryCopyInitialization(S, Args[ConvIdx], 8751 Cand->BuiltinTypes.ParamTypes[ConvIdx], 8752 SuppressUserConversions, 8753 /*InOverloadResolution*/ true, 8754 /*AllowObjCWritebackConversion=*/ 8755 S.getLangOpts().ObjCAutoRefCount); 8756 return; 8757 } 8758 8759 // Fill in the rest of the conversions. 8760 unsigned NumArgsInProto = Proto->getNumArgs(); 8761 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 8762 if (ArgIdx < NumArgsInProto) { 8763 Cand->Conversions[ConvIdx] 8764 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx), 8765 SuppressUserConversions, 8766 /*InOverloadResolution=*/true, 8767 /*AllowObjCWritebackConversion=*/ 8768 S.getLangOpts().ObjCAutoRefCount); 8769 // Store the FixIt in the candidate if it exists. 8770 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 8771 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 8772 } 8773 else 8774 Cand->Conversions[ConvIdx].setEllipsis(); 8775 } 8776 } 8777 8778 } // end anonymous namespace 8779 8780 /// PrintOverloadCandidates - When overload resolution fails, prints 8781 /// diagnostic messages containing the candidates in the candidate 8782 /// set. 8783 void OverloadCandidateSet::NoteCandidates(Sema &S, 8784 OverloadCandidateDisplayKind OCD, 8785 llvm::ArrayRef<Expr *> Args, 8786 const char *Opc, 8787 SourceLocation OpLoc) { 8788 // Sort the candidates by viability and position. Sorting directly would 8789 // be prohibitive, so we make a set of pointers and sort those. 8790 SmallVector<OverloadCandidate*, 32> Cands; 8791 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 8792 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 8793 if (Cand->Viable) 8794 Cands.push_back(Cand); 8795 else if (OCD == OCD_AllCandidates) { 8796 CompleteNonViableCandidate(S, Cand, Args); 8797 if (Cand->Function || Cand->IsSurrogate) 8798 Cands.push_back(Cand); 8799 // Otherwise, this a non-viable builtin candidate. We do not, in general, 8800 // want to list every possible builtin candidate. 8801 } 8802 } 8803 8804 std::sort(Cands.begin(), Cands.end(), 8805 CompareOverloadCandidatesForDisplay(S)); 8806 8807 bool ReportedAmbiguousConversions = false; 8808 8809 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 8810 const DiagnosticsEngine::OverloadsShown ShowOverloads = 8811 S.Diags.getShowOverloads(); 8812 unsigned CandsShown = 0; 8813 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 8814 OverloadCandidate *Cand = *I; 8815 8816 // Set an arbitrary limit on the number of candidate functions we'll spam 8817 // the user with. FIXME: This limit should depend on details of the 8818 // candidate list. 8819 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) { 8820 break; 8821 } 8822 ++CandsShown; 8823 8824 if (Cand->Function) 8825 NoteFunctionCandidate(S, Cand, Args.size()); 8826 else if (Cand->IsSurrogate) 8827 NoteSurrogateCandidate(S, Cand); 8828 else { 8829 assert(Cand->Viable && 8830 "Non-viable built-in candidates are not added to Cands."); 8831 // Generally we only see ambiguities including viable builtin 8832 // operators if overload resolution got screwed up by an 8833 // ambiguous user-defined conversion. 8834 // 8835 // FIXME: It's quite possible for different conversions to see 8836 // different ambiguities, though. 8837 if (!ReportedAmbiguousConversions) { 8838 NoteAmbiguousUserConversions(S, OpLoc, Cand); 8839 ReportedAmbiguousConversions = true; 8840 } 8841 8842 // If this is a viable builtin, print it. 8843 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 8844 } 8845 } 8846 8847 if (I != E) 8848 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 8849 } 8850 8851 // [PossiblyAFunctionType] --> [Return] 8852 // NonFunctionType --> NonFunctionType 8853 // R (A) --> R(A) 8854 // R (*)(A) --> R (A) 8855 // R (&)(A) --> R (A) 8856 // R (S::*)(A) --> R (A) 8857 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 8858 QualType Ret = PossiblyAFunctionType; 8859 if (const PointerType *ToTypePtr = 8860 PossiblyAFunctionType->getAs<PointerType>()) 8861 Ret = ToTypePtr->getPointeeType(); 8862 else if (const ReferenceType *ToTypeRef = 8863 PossiblyAFunctionType->getAs<ReferenceType>()) 8864 Ret = ToTypeRef->getPointeeType(); 8865 else if (const MemberPointerType *MemTypePtr = 8866 PossiblyAFunctionType->getAs<MemberPointerType>()) 8867 Ret = MemTypePtr->getPointeeType(); 8868 Ret = 8869 Context.getCanonicalType(Ret).getUnqualifiedType(); 8870 return Ret; 8871 } 8872 8873 // A helper class to help with address of function resolution 8874 // - allows us to avoid passing around all those ugly parameters 8875 class AddressOfFunctionResolver 8876 { 8877 Sema& S; 8878 Expr* SourceExpr; 8879 const QualType& TargetType; 8880 QualType TargetFunctionType; // Extracted function type from target type 8881 8882 bool Complain; 8883 //DeclAccessPair& ResultFunctionAccessPair; 8884 ASTContext& Context; 8885 8886 bool TargetTypeIsNonStaticMemberFunction; 8887 bool FoundNonTemplateFunction; 8888 8889 OverloadExpr::FindResult OvlExprInfo; 8890 OverloadExpr *OvlExpr; 8891 TemplateArgumentListInfo OvlExplicitTemplateArgs; 8892 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 8893 8894 public: 8895 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr, 8896 const QualType& TargetType, bool Complain) 8897 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 8898 Complain(Complain), Context(S.getASTContext()), 8899 TargetTypeIsNonStaticMemberFunction( 8900 !!TargetType->getAs<MemberPointerType>()), 8901 FoundNonTemplateFunction(false), 8902 OvlExprInfo(OverloadExpr::find(SourceExpr)), 8903 OvlExpr(OvlExprInfo.Expression) 8904 { 8905 ExtractUnqualifiedFunctionTypeFromTargetType(); 8906 8907 if (!TargetFunctionType->isFunctionType()) { 8908 if (OvlExpr->hasExplicitTemplateArgs()) { 8909 DeclAccessPair dap; 8910 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization( 8911 OvlExpr, false, &dap) ) { 8912 8913 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 8914 if (!Method->isStatic()) { 8915 // If the target type is a non-function type and the function 8916 // found is a non-static member function, pretend as if that was 8917 // the target, it's the only possible type to end up with. 8918 TargetTypeIsNonStaticMemberFunction = true; 8919 8920 // And skip adding the function if its not in the proper form. 8921 // We'll diagnose this due to an empty set of functions. 8922 if (!OvlExprInfo.HasFormOfMemberPointer) 8923 return; 8924 } 8925 } 8926 8927 Matches.push_back(std::make_pair(dap,Fn)); 8928 } 8929 } 8930 return; 8931 } 8932 8933 if (OvlExpr->hasExplicitTemplateArgs()) 8934 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 8935 8936 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 8937 // C++ [over.over]p4: 8938 // If more than one function is selected, [...] 8939 if (Matches.size() > 1) { 8940 if (FoundNonTemplateFunction) 8941 EliminateAllTemplateMatches(); 8942 else 8943 EliminateAllExceptMostSpecializedTemplate(); 8944 } 8945 } 8946 } 8947 8948 private: 8949 bool isTargetTypeAFunction() const { 8950 return TargetFunctionType->isFunctionType(); 8951 } 8952 8953 // [ToType] [Return] 8954 8955 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 8956 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 8957 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 8958 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 8959 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 8960 } 8961 8962 // return true if any matching specializations were found 8963 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 8964 const DeclAccessPair& CurAccessFunPair) { 8965 if (CXXMethodDecl *Method 8966 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 8967 // Skip non-static function templates when converting to pointer, and 8968 // static when converting to member pointer. 8969 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 8970 return false; 8971 } 8972 else if (TargetTypeIsNonStaticMemberFunction) 8973 return false; 8974 8975 // C++ [over.over]p2: 8976 // If the name is a function template, template argument deduction is 8977 // done (14.8.2.2), and if the argument deduction succeeds, the 8978 // resulting template argument list is used to generate a single 8979 // function template specialization, which is added to the set of 8980 // overloaded functions considered. 8981 FunctionDecl *Specialization = 0; 8982 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc()); 8983 if (Sema::TemplateDeductionResult Result 8984 = S.DeduceTemplateArguments(FunctionTemplate, 8985 &OvlExplicitTemplateArgs, 8986 TargetFunctionType, Specialization, 8987 Info)) { 8988 // FIXME: make a note of the failed deduction for diagnostics. 8989 (void)Result; 8990 return false; 8991 } 8992 8993 // Template argument deduction ensures that we have an exact match. 8994 // This function template specicalization works. 8995 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 8996 assert(TargetFunctionType 8997 == Context.getCanonicalType(Specialization->getType())); 8998 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 8999 return true; 9000 } 9001 9002 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9003 const DeclAccessPair& CurAccessFunPair) { 9004 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9005 // Skip non-static functions when converting to pointer, and static 9006 // when converting to member pointer. 9007 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9008 return false; 9009 } 9010 else if (TargetTypeIsNonStaticMemberFunction) 9011 return false; 9012 9013 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9014 if (S.getLangOpts().CUDA) 9015 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9016 if (S.CheckCUDATarget(Caller, FunDecl)) 9017 return false; 9018 9019 QualType ResultTy; 9020 if (Context.hasSameUnqualifiedType(TargetFunctionType, 9021 FunDecl->getType()) || 9022 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9023 ResultTy)) { 9024 Matches.push_back(std::make_pair(CurAccessFunPair, 9025 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9026 FoundNonTemplateFunction = true; 9027 return true; 9028 } 9029 } 9030 9031 return false; 9032 } 9033 9034 bool FindAllFunctionsThatMatchTargetTypeExactly() { 9035 bool Ret = false; 9036 9037 // If the overload expression doesn't have the form of a pointer to 9038 // member, don't try to convert it to a pointer-to-member type. 9039 if (IsInvalidFormOfPointerToMemberFunction()) 9040 return false; 9041 9042 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9043 E = OvlExpr->decls_end(); 9044 I != E; ++I) { 9045 // Look through any using declarations to find the underlying function. 9046 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 9047 9048 // C++ [over.over]p3: 9049 // Non-member functions and static member functions match 9050 // targets of type "pointer-to-function" or "reference-to-function." 9051 // Nonstatic member functions match targets of 9052 // type "pointer-to-member-function." 9053 // Note that according to DR 247, the containing class does not matter. 9054 if (FunctionTemplateDecl *FunctionTemplate 9055 = dyn_cast<FunctionTemplateDecl>(Fn)) { 9056 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 9057 Ret = true; 9058 } 9059 // If we have explicit template arguments supplied, skip non-templates. 9060 else if (!OvlExpr->hasExplicitTemplateArgs() && 9061 AddMatchingNonTemplateFunction(Fn, I.getPair())) 9062 Ret = true; 9063 } 9064 assert(Ret || Matches.empty()); 9065 return Ret; 9066 } 9067 9068 void EliminateAllExceptMostSpecializedTemplate() { 9069 // [...] and any given function template specialization F1 is 9070 // eliminated if the set contains a second function template 9071 // specialization whose function template is more specialized 9072 // than the function template of F1 according to the partial 9073 // ordering rules of 14.5.5.2. 9074 9075 // The algorithm specified above is quadratic. We instead use a 9076 // two-pass algorithm (similar to the one used to identify the 9077 // best viable function in an overload set) that identifies the 9078 // best function template (if it exists). 9079 9080 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 9081 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 9082 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 9083 9084 UnresolvedSetIterator Result = 9085 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(), 9086 TPOC_Other, 0, SourceExpr->getLocStart(), 9087 S.PDiag(), 9088 S.PDiag(diag::err_addr_ovl_ambiguous) 9089 << Matches[0].second->getDeclName(), 9090 S.PDiag(diag::note_ovl_candidate) 9091 << (unsigned) oc_function_template, 9092 Complain, TargetFunctionType); 9093 9094 if (Result != MatchesCopy.end()) { 9095 // Make it the first and only element 9096 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 9097 Matches[0].second = cast<FunctionDecl>(*Result); 9098 Matches.resize(1); 9099 } 9100 } 9101 9102 void EliminateAllTemplateMatches() { 9103 // [...] any function template specializations in the set are 9104 // eliminated if the set also contains a non-template function, [...] 9105 for (unsigned I = 0, N = Matches.size(); I != N; ) { 9106 if (Matches[I].second->getPrimaryTemplate() == 0) 9107 ++I; 9108 else { 9109 Matches[I] = Matches[--N]; 9110 Matches.set_size(N); 9111 } 9112 } 9113 } 9114 9115 public: 9116 void ComplainNoMatchesFound() const { 9117 assert(Matches.empty()); 9118 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 9119 << OvlExpr->getName() << TargetFunctionType 9120 << OvlExpr->getSourceRange(); 9121 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9122 } 9123 9124 bool IsInvalidFormOfPointerToMemberFunction() const { 9125 return TargetTypeIsNonStaticMemberFunction && 9126 !OvlExprInfo.HasFormOfMemberPointer; 9127 } 9128 9129 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 9130 // TODO: Should we condition this on whether any functions might 9131 // have matched, or is it more appropriate to do that in callers? 9132 // TODO: a fixit wouldn't hurt. 9133 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 9134 << TargetType << OvlExpr->getSourceRange(); 9135 } 9136 9137 void ComplainOfInvalidConversion() const { 9138 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 9139 << OvlExpr->getName() << TargetType; 9140 } 9141 9142 void ComplainMultipleMatchesFound() const { 9143 assert(Matches.size() > 1); 9144 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 9145 << OvlExpr->getName() 9146 << OvlExpr->getSourceRange(); 9147 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9148 } 9149 9150 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 9151 9152 int getNumMatches() const { return Matches.size(); } 9153 9154 FunctionDecl* getMatchingFunctionDecl() const { 9155 if (Matches.size() != 1) return 0; 9156 return Matches[0].second; 9157 } 9158 9159 const DeclAccessPair* getMatchingFunctionAccessPair() const { 9160 if (Matches.size() != 1) return 0; 9161 return &Matches[0].first; 9162 } 9163 }; 9164 9165 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 9166 /// an overloaded function (C++ [over.over]), where @p From is an 9167 /// expression with overloaded function type and @p ToType is the type 9168 /// we're trying to resolve to. For example: 9169 /// 9170 /// @code 9171 /// int f(double); 9172 /// int f(int); 9173 /// 9174 /// int (*pfd)(double) = f; // selects f(double) 9175 /// @endcode 9176 /// 9177 /// This routine returns the resulting FunctionDecl if it could be 9178 /// resolved, and NULL otherwise. When @p Complain is true, this 9179 /// routine will emit diagnostics if there is an error. 9180 FunctionDecl * 9181 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 9182 QualType TargetType, 9183 bool Complain, 9184 DeclAccessPair &FoundResult, 9185 bool *pHadMultipleCandidates) { 9186 assert(AddressOfExpr->getType() == Context.OverloadTy); 9187 9188 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 9189 Complain); 9190 int NumMatches = Resolver.getNumMatches(); 9191 FunctionDecl* Fn = 0; 9192 if (NumMatches == 0 && Complain) { 9193 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 9194 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 9195 else 9196 Resolver.ComplainNoMatchesFound(); 9197 } 9198 else if (NumMatches > 1 && Complain) 9199 Resolver.ComplainMultipleMatchesFound(); 9200 else if (NumMatches == 1) { 9201 Fn = Resolver.getMatchingFunctionDecl(); 9202 assert(Fn); 9203 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 9204 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn); 9205 if (Complain) 9206 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 9207 } 9208 9209 if (pHadMultipleCandidates) 9210 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 9211 return Fn; 9212 } 9213 9214 /// \brief Given an expression that refers to an overloaded function, try to 9215 /// resolve that overloaded function expression down to a single function. 9216 /// 9217 /// This routine can only resolve template-ids that refer to a single function 9218 /// template, where that template-id refers to a single template whose template 9219 /// arguments are either provided by the template-id or have defaults, 9220 /// as described in C++0x [temp.arg.explicit]p3. 9221 FunctionDecl * 9222 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 9223 bool Complain, 9224 DeclAccessPair *FoundResult) { 9225 // C++ [over.over]p1: 9226 // [...] [Note: any redundant set of parentheses surrounding the 9227 // overloaded function name is ignored (5.1). ] 9228 // C++ [over.over]p1: 9229 // [...] The overloaded function name can be preceded by the & 9230 // operator. 9231 9232 // If we didn't actually find any template-ids, we're done. 9233 if (!ovl->hasExplicitTemplateArgs()) 9234 return 0; 9235 9236 TemplateArgumentListInfo ExplicitTemplateArgs; 9237 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 9238 9239 // Look through all of the overloaded functions, searching for one 9240 // whose type matches exactly. 9241 FunctionDecl *Matched = 0; 9242 for (UnresolvedSetIterator I = ovl->decls_begin(), 9243 E = ovl->decls_end(); I != E; ++I) { 9244 // C++0x [temp.arg.explicit]p3: 9245 // [...] In contexts where deduction is done and fails, or in contexts 9246 // where deduction is not done, if a template argument list is 9247 // specified and it, along with any default template arguments, 9248 // identifies a single function template specialization, then the 9249 // template-id is an lvalue for the function template specialization. 9250 FunctionTemplateDecl *FunctionTemplate 9251 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 9252 9253 // C++ [over.over]p2: 9254 // If the name is a function template, template argument deduction is 9255 // done (14.8.2.2), and if the argument deduction succeeds, the 9256 // resulting template argument list is used to generate a single 9257 // function template specialization, which is added to the set of 9258 // overloaded functions considered. 9259 FunctionDecl *Specialization = 0; 9260 TemplateDeductionInfo Info(Context, ovl->getNameLoc()); 9261 if (TemplateDeductionResult Result 9262 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 9263 Specialization, Info)) { 9264 // FIXME: make a note of the failed deduction for diagnostics. 9265 (void)Result; 9266 continue; 9267 } 9268 9269 assert(Specialization && "no specialization and no error?"); 9270 9271 // Multiple matches; we can't resolve to a single declaration. 9272 if (Matched) { 9273 if (Complain) { 9274 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 9275 << ovl->getName(); 9276 NoteAllOverloadCandidates(ovl); 9277 } 9278 return 0; 9279 } 9280 9281 Matched = Specialization; 9282 if (FoundResult) *FoundResult = I.getPair(); 9283 } 9284 9285 return Matched; 9286 } 9287 9288 9289 9290 9291 // Resolve and fix an overloaded expression that can be resolved 9292 // because it identifies a single function template specialization. 9293 // 9294 // Last three arguments should only be supplied if Complain = true 9295 // 9296 // Return true if it was logically possible to so resolve the 9297 // expression, regardless of whether or not it succeeded. Always 9298 // returns true if 'complain' is set. 9299 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 9300 ExprResult &SrcExpr, bool doFunctionPointerConverion, 9301 bool complain, const SourceRange& OpRangeForComplaining, 9302 QualType DestTypeForComplaining, 9303 unsigned DiagIDForComplaining) { 9304 assert(SrcExpr.get()->getType() == Context.OverloadTy); 9305 9306 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 9307 9308 DeclAccessPair found; 9309 ExprResult SingleFunctionExpression; 9310 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 9311 ovl.Expression, /*complain*/ false, &found)) { 9312 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 9313 SrcExpr = ExprError(); 9314 return true; 9315 } 9316 9317 // It is only correct to resolve to an instance method if we're 9318 // resolving a form that's permitted to be a pointer to member. 9319 // Otherwise we'll end up making a bound member expression, which 9320 // is illegal in all the contexts we resolve like this. 9321 if (!ovl.HasFormOfMemberPointer && 9322 isa<CXXMethodDecl>(fn) && 9323 cast<CXXMethodDecl>(fn)->isInstance()) { 9324 if (!complain) return false; 9325 9326 Diag(ovl.Expression->getExprLoc(), 9327 diag::err_bound_member_function) 9328 << 0 << ovl.Expression->getSourceRange(); 9329 9330 // TODO: I believe we only end up here if there's a mix of 9331 // static and non-static candidates (otherwise the expression 9332 // would have 'bound member' type, not 'overload' type). 9333 // Ideally we would note which candidate was chosen and why 9334 // the static candidates were rejected. 9335 SrcExpr = ExprError(); 9336 return true; 9337 } 9338 9339 // Fix the expression to refer to 'fn'. 9340 SingleFunctionExpression = 9341 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn)); 9342 9343 // If desired, do function-to-pointer decay. 9344 if (doFunctionPointerConverion) { 9345 SingleFunctionExpression = 9346 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take()); 9347 if (SingleFunctionExpression.isInvalid()) { 9348 SrcExpr = ExprError(); 9349 return true; 9350 } 9351 } 9352 } 9353 9354 if (!SingleFunctionExpression.isUsable()) { 9355 if (complain) { 9356 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 9357 << ovl.Expression->getName() 9358 << DestTypeForComplaining 9359 << OpRangeForComplaining 9360 << ovl.Expression->getQualifierLoc().getSourceRange(); 9361 NoteAllOverloadCandidates(SrcExpr.get()); 9362 9363 SrcExpr = ExprError(); 9364 return true; 9365 } 9366 9367 return false; 9368 } 9369 9370 SrcExpr = SingleFunctionExpression; 9371 return true; 9372 } 9373 9374 /// \brief Add a single candidate to the overload set. 9375 static void AddOverloadedCallCandidate(Sema &S, 9376 DeclAccessPair FoundDecl, 9377 TemplateArgumentListInfo *ExplicitTemplateArgs, 9378 llvm::ArrayRef<Expr *> Args, 9379 OverloadCandidateSet &CandidateSet, 9380 bool PartialOverloading, 9381 bool KnownValid) { 9382 NamedDecl *Callee = FoundDecl.getDecl(); 9383 if (isa<UsingShadowDecl>(Callee)) 9384 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 9385 9386 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 9387 if (ExplicitTemplateArgs) { 9388 assert(!KnownValid && "Explicit template arguments?"); 9389 return; 9390 } 9391 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false, 9392 PartialOverloading); 9393 return; 9394 } 9395 9396 if (FunctionTemplateDecl *FuncTemplate 9397 = dyn_cast<FunctionTemplateDecl>(Callee)) { 9398 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 9399 ExplicitTemplateArgs, Args, CandidateSet); 9400 return; 9401 } 9402 9403 assert(!KnownValid && "unhandled case in overloaded call candidate"); 9404 } 9405 9406 /// \brief Add the overload candidates named by callee and/or found by argument 9407 /// dependent lookup to the given overload set. 9408 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 9409 llvm::ArrayRef<Expr *> Args, 9410 OverloadCandidateSet &CandidateSet, 9411 bool PartialOverloading) { 9412 9413 #ifndef NDEBUG 9414 // Verify that ArgumentDependentLookup is consistent with the rules 9415 // in C++0x [basic.lookup.argdep]p3: 9416 // 9417 // Let X be the lookup set produced by unqualified lookup (3.4.1) 9418 // and let Y be the lookup set produced by argument dependent 9419 // lookup (defined as follows). If X contains 9420 // 9421 // -- a declaration of a class member, or 9422 // 9423 // -- a block-scope function declaration that is not a 9424 // using-declaration, or 9425 // 9426 // -- a declaration that is neither a function or a function 9427 // template 9428 // 9429 // then Y is empty. 9430 9431 if (ULE->requiresADL()) { 9432 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9433 E = ULE->decls_end(); I != E; ++I) { 9434 assert(!(*I)->getDeclContext()->isRecord()); 9435 assert(isa<UsingShadowDecl>(*I) || 9436 !(*I)->getDeclContext()->isFunctionOrMethod()); 9437 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 9438 } 9439 } 9440 #endif 9441 9442 // It would be nice to avoid this copy. 9443 TemplateArgumentListInfo TABuffer; 9444 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9445 if (ULE->hasExplicitTemplateArgs()) { 9446 ULE->copyTemplateArgumentsInto(TABuffer); 9447 ExplicitTemplateArgs = &TABuffer; 9448 } 9449 9450 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9451 E = ULE->decls_end(); I != E; ++I) 9452 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 9453 CandidateSet, PartialOverloading, 9454 /*KnownValid*/ true); 9455 9456 if (ULE->requiresADL()) 9457 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 9458 ULE->getExprLoc(), 9459 Args, ExplicitTemplateArgs, 9460 CandidateSet, PartialOverloading, 9461 ULE->isStdAssociatedNamespace()); 9462 } 9463 9464 /// Attempt to recover from an ill-formed use of a non-dependent name in a 9465 /// template, where the non-dependent name was declared after the template 9466 /// was defined. This is common in code written for a compilers which do not 9467 /// correctly implement two-stage name lookup. 9468 /// 9469 /// Returns true if a viable candidate was found and a diagnostic was issued. 9470 static bool 9471 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 9472 const CXXScopeSpec &SS, LookupResult &R, 9473 TemplateArgumentListInfo *ExplicitTemplateArgs, 9474 llvm::ArrayRef<Expr *> Args) { 9475 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 9476 return false; 9477 9478 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 9479 if (DC->isTransparentContext()) 9480 continue; 9481 9482 SemaRef.LookupQualifiedName(R, DC); 9483 9484 if (!R.empty()) { 9485 R.suppressDiagnostics(); 9486 9487 if (isa<CXXRecordDecl>(DC)) { 9488 // Don't diagnose names we find in classes; we get much better 9489 // diagnostics for these from DiagnoseEmptyLookup. 9490 R.clear(); 9491 return false; 9492 } 9493 9494 OverloadCandidateSet Candidates(FnLoc); 9495 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9496 AddOverloadedCallCandidate(SemaRef, I.getPair(), 9497 ExplicitTemplateArgs, Args, 9498 Candidates, false, /*KnownValid*/ false); 9499 9500 OverloadCandidateSet::iterator Best; 9501 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 9502 // No viable functions. Don't bother the user with notes for functions 9503 // which don't work and shouldn't be found anyway. 9504 R.clear(); 9505 return false; 9506 } 9507 9508 // Find the namespaces where ADL would have looked, and suggest 9509 // declaring the function there instead. 9510 Sema::AssociatedNamespaceSet AssociatedNamespaces; 9511 Sema::AssociatedClassSet AssociatedClasses; 9512 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 9513 AssociatedNamespaces, 9514 AssociatedClasses); 9515 // Never suggest declaring a function within namespace 'std'. 9516 Sema::AssociatedNamespaceSet SuggestedNamespaces; 9517 if (DeclContext *Std = SemaRef.getStdNamespace()) { 9518 for (Sema::AssociatedNamespaceSet::iterator 9519 it = AssociatedNamespaces.begin(), 9520 end = AssociatedNamespaces.end(); it != end; ++it) { 9521 if (!Std->Encloses(*it)) 9522 SuggestedNamespaces.insert(*it); 9523 } 9524 } else { 9525 // Lacking the 'std::' namespace, use all of the associated namespaces. 9526 SuggestedNamespaces = AssociatedNamespaces; 9527 } 9528 9529 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 9530 << R.getLookupName(); 9531 if (SuggestedNamespaces.empty()) { 9532 SemaRef.Diag(Best->Function->getLocation(), 9533 diag::note_not_found_by_two_phase_lookup) 9534 << R.getLookupName() << 0; 9535 } else if (SuggestedNamespaces.size() == 1) { 9536 SemaRef.Diag(Best->Function->getLocation(), 9537 diag::note_not_found_by_two_phase_lookup) 9538 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 9539 } else { 9540 // FIXME: It would be useful to list the associated namespaces here, 9541 // but the diagnostics infrastructure doesn't provide a way to produce 9542 // a localized representation of a list of items. 9543 SemaRef.Diag(Best->Function->getLocation(), 9544 diag::note_not_found_by_two_phase_lookup) 9545 << R.getLookupName() << 2; 9546 } 9547 9548 // Try to recover by calling this function. 9549 return true; 9550 } 9551 9552 R.clear(); 9553 } 9554 9555 return false; 9556 } 9557 9558 /// Attempt to recover from ill-formed use of a non-dependent operator in a 9559 /// template, where the non-dependent operator was declared after the template 9560 /// was defined. 9561 /// 9562 /// Returns true if a viable candidate was found and a diagnostic was issued. 9563 static bool 9564 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 9565 SourceLocation OpLoc, 9566 llvm::ArrayRef<Expr *> Args) { 9567 DeclarationName OpName = 9568 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 9569 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 9570 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 9571 /*ExplicitTemplateArgs=*/0, Args); 9572 } 9573 9574 namespace { 9575 // Callback to limit the allowed keywords and to only accept typo corrections 9576 // that are keywords or whose decls refer to functions (or template functions) 9577 // that accept the given number of arguments. 9578 class RecoveryCallCCC : public CorrectionCandidateCallback { 9579 public: 9580 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs) 9581 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) { 9582 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus; 9583 WantRemainingKeywords = false; 9584 } 9585 9586 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9587 if (!candidate.getCorrectionDecl()) 9588 return candidate.isKeyword(); 9589 9590 for (TypoCorrection::const_decl_iterator DI = candidate.begin(), 9591 DIEnd = candidate.end(); DI != DIEnd; ++DI) { 9592 FunctionDecl *FD = 0; 9593 NamedDecl *ND = (*DI)->getUnderlyingDecl(); 9594 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 9595 FD = FTD->getTemplatedDecl(); 9596 if (!HasExplicitTemplateArgs && !FD) { 9597 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) { 9598 // If the Decl is neither a function nor a template function, 9599 // determine if it is a pointer or reference to a function. If so, 9600 // check against the number of arguments expected for the pointee. 9601 QualType ValType = cast<ValueDecl>(ND)->getType(); 9602 if (ValType->isAnyPointerType() || ValType->isReferenceType()) 9603 ValType = ValType->getPointeeType(); 9604 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>()) 9605 if (FPT->getNumArgs() == NumArgs) 9606 return true; 9607 } 9608 } 9609 if (FD && FD->getNumParams() >= NumArgs && 9610 FD->getMinRequiredArguments() <= NumArgs) 9611 return true; 9612 } 9613 return false; 9614 } 9615 9616 private: 9617 unsigned NumArgs; 9618 bool HasExplicitTemplateArgs; 9619 }; 9620 9621 // Callback that effectively disabled typo correction 9622 class NoTypoCorrectionCCC : public CorrectionCandidateCallback { 9623 public: 9624 NoTypoCorrectionCCC() { 9625 WantTypeSpecifiers = false; 9626 WantExpressionKeywords = false; 9627 WantCXXNamedCasts = false; 9628 WantRemainingKeywords = false; 9629 } 9630 9631 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9632 return false; 9633 } 9634 }; 9635 } 9636 9637 /// Attempts to recover from a call where no functions were found. 9638 /// 9639 /// Returns true if new candidates were found. 9640 static ExprResult 9641 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9642 UnresolvedLookupExpr *ULE, 9643 SourceLocation LParenLoc, 9644 llvm::MutableArrayRef<Expr *> Args, 9645 SourceLocation RParenLoc, 9646 bool EmptyLookup, bool AllowTypoCorrection) { 9647 9648 CXXScopeSpec SS; 9649 SS.Adopt(ULE->getQualifierLoc()); 9650 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 9651 9652 TemplateArgumentListInfo TABuffer; 9653 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9654 if (ULE->hasExplicitTemplateArgs()) { 9655 ULE->copyTemplateArgumentsInto(TABuffer); 9656 ExplicitTemplateArgs = &TABuffer; 9657 } 9658 9659 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 9660 Sema::LookupOrdinaryName); 9661 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0); 9662 NoTypoCorrectionCCC RejectAll; 9663 CorrectionCandidateCallback *CCC = AllowTypoCorrection ? 9664 (CorrectionCandidateCallback*)&Validator : 9665 (CorrectionCandidateCallback*)&RejectAll; 9666 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 9667 ExplicitTemplateArgs, Args) && 9668 (!EmptyLookup || 9669 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC, 9670 ExplicitTemplateArgs, Args))) 9671 return ExprError(); 9672 9673 assert(!R.empty() && "lookup results empty despite recovery"); 9674 9675 // Build an implicit member call if appropriate. Just drop the 9676 // casts and such from the call, we don't really care. 9677 ExprResult NewFn = ExprError(); 9678 if ((*R.begin())->isCXXClassMember()) 9679 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 9680 R, ExplicitTemplateArgs); 9681 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 9682 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 9683 ExplicitTemplateArgs); 9684 else 9685 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 9686 9687 if (NewFn.isInvalid()) 9688 return ExprError(); 9689 9690 // This shouldn't cause an infinite loop because we're giving it 9691 // an expression with viable lookup results, which should never 9692 // end up here. 9693 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 9694 MultiExprArg(Args.data(), Args.size()), 9695 RParenLoc); 9696 } 9697 9698 /// \brief Constructs and populates an OverloadedCandidateSet from 9699 /// the given function. 9700 /// \returns true when an the ExprResult output parameter has been set. 9701 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 9702 UnresolvedLookupExpr *ULE, 9703 Expr **Args, unsigned NumArgs, 9704 SourceLocation RParenLoc, 9705 OverloadCandidateSet *CandidateSet, 9706 ExprResult *Result) { 9707 #ifndef NDEBUG 9708 if (ULE->requiresADL()) { 9709 // To do ADL, we must have found an unqualified name. 9710 assert(!ULE->getQualifier() && "qualified name with ADL"); 9711 9712 // We don't perform ADL for implicit declarations of builtins. 9713 // Verify that this was correctly set up. 9714 FunctionDecl *F; 9715 if (ULE->decls_begin() + 1 == ULE->decls_end() && 9716 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 9717 F->getBuiltinID() && F->isImplicit()) 9718 llvm_unreachable("performing ADL for builtin"); 9719 9720 // We don't perform ADL in C. 9721 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 9722 } else 9723 assert(!ULE->isStdAssociatedNamespace() && 9724 "std is associated namespace but not doing ADL"); 9725 #endif 9726 9727 UnbridgedCastsSet UnbridgedCasts; 9728 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) { 9729 *Result = ExprError(); 9730 return true; 9731 } 9732 9733 // Add the functions denoted by the callee to the set of candidate 9734 // functions, including those from argument-dependent lookup. 9735 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs), 9736 *CandidateSet); 9737 9738 // If we found nothing, try to recover. 9739 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 9740 // out if it fails. 9741 if (CandidateSet->empty()) { 9742 // In Microsoft mode, if we are inside a template class member function then 9743 // create a type dependent CallExpr. The goal is to postpone name lookup 9744 // to instantiation time to be able to search into type dependent base 9745 // classes. 9746 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() && 9747 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 9748 CallExpr *CE = new (Context) CallExpr(Context, Fn, 9749 llvm::makeArrayRef(Args, NumArgs), 9750 Context.DependentTy, VK_RValue, 9751 RParenLoc); 9752 CE->setTypeDependent(true); 9753 *Result = Owned(CE); 9754 return true; 9755 } 9756 return false; 9757 } 9758 9759 UnbridgedCasts.restore(); 9760 return false; 9761 } 9762 9763 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 9764 /// the completed call expression. If overload resolution fails, emits 9765 /// diagnostics and returns ExprError() 9766 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9767 UnresolvedLookupExpr *ULE, 9768 SourceLocation LParenLoc, 9769 Expr **Args, unsigned NumArgs, 9770 SourceLocation RParenLoc, 9771 Expr *ExecConfig, 9772 OverloadCandidateSet *CandidateSet, 9773 OverloadCandidateSet::iterator *Best, 9774 OverloadingResult OverloadResult, 9775 bool AllowTypoCorrection) { 9776 if (CandidateSet->empty()) 9777 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 9778 llvm::MutableArrayRef<Expr *>(Args, NumArgs), 9779 RParenLoc, /*EmptyLookup=*/true, 9780 AllowTypoCorrection); 9781 9782 switch (OverloadResult) { 9783 case OR_Success: { 9784 FunctionDecl *FDecl = (*Best)->Function; 9785 SemaRef.MarkFunctionReferenced(Fn->getExprLoc(), FDecl); 9786 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 9787 SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()); 9788 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 9789 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, 9790 RParenLoc, ExecConfig); 9791 } 9792 9793 case OR_No_Viable_Function: { 9794 // Try to recover by looking for viable functions which the user might 9795 // have meant to call. 9796 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 9797 llvm::MutableArrayRef<Expr *>(Args, NumArgs), 9798 RParenLoc, 9799 /*EmptyLookup=*/false, 9800 AllowTypoCorrection); 9801 if (!Recovery.isInvalid()) 9802 return Recovery; 9803 9804 SemaRef.Diag(Fn->getLocStart(), 9805 diag::err_ovl_no_viable_function_in_call) 9806 << ULE->getName() << Fn->getSourceRange(); 9807 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, 9808 llvm::makeArrayRef(Args, NumArgs)); 9809 break; 9810 } 9811 9812 case OR_Ambiguous: 9813 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 9814 << ULE->getName() << Fn->getSourceRange(); 9815 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, 9816 llvm::makeArrayRef(Args, NumArgs)); 9817 break; 9818 9819 case OR_Deleted: { 9820 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 9821 << (*Best)->Function->isDeleted() 9822 << ULE->getName() 9823 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 9824 << Fn->getSourceRange(); 9825 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, 9826 llvm::makeArrayRef(Args, NumArgs)); 9827 9828 // We emitted an error for the unvailable/deleted function call but keep 9829 // the call in the AST. 9830 FunctionDecl *FDecl = (*Best)->Function; 9831 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 9832 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, 9833 RParenLoc, ExecConfig); 9834 } 9835 } 9836 9837 // Overload resolution failed. 9838 return ExprError(); 9839 } 9840 9841 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 9842 /// (which eventually refers to the declaration Func) and the call 9843 /// arguments Args/NumArgs, attempt to resolve the function call down 9844 /// to a specific function. If overload resolution succeeds, returns 9845 /// the call expression produced by overload resolution. 9846 /// Otherwise, emits diagnostics and returns ExprError. 9847 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 9848 UnresolvedLookupExpr *ULE, 9849 SourceLocation LParenLoc, 9850 Expr **Args, unsigned NumArgs, 9851 SourceLocation RParenLoc, 9852 Expr *ExecConfig, 9853 bool AllowTypoCorrection) { 9854 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 9855 ExprResult result; 9856 9857 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc, 9858 &CandidateSet, &result)) 9859 return result; 9860 9861 OverloadCandidateSet::iterator Best; 9862 OverloadingResult OverloadResult = 9863 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 9864 9865 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs, 9866 RParenLoc, ExecConfig, &CandidateSet, 9867 &Best, OverloadResult, 9868 AllowTypoCorrection); 9869 } 9870 9871 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 9872 return Functions.size() > 1 || 9873 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 9874 } 9875 9876 /// \brief Create a unary operation that may resolve to an overloaded 9877 /// operator. 9878 /// 9879 /// \param OpLoc The location of the operator itself (e.g., '*'). 9880 /// 9881 /// \param OpcIn The UnaryOperator::Opcode that describes this 9882 /// operator. 9883 /// 9884 /// \param Fns The set of non-member functions that will be 9885 /// considered by overload resolution. The caller needs to build this 9886 /// set based on the context using, e.g., 9887 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 9888 /// set should not contain any member functions; those will be added 9889 /// by CreateOverloadedUnaryOp(). 9890 /// 9891 /// \param Input The input argument. 9892 ExprResult 9893 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 9894 const UnresolvedSetImpl &Fns, 9895 Expr *Input) { 9896 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 9897 9898 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 9899 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 9900 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 9901 // TODO: provide better source location info. 9902 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 9903 9904 if (checkPlaceholderForOverload(*this, Input)) 9905 return ExprError(); 9906 9907 Expr *Args[2] = { Input, 0 }; 9908 unsigned NumArgs = 1; 9909 9910 // For post-increment and post-decrement, add the implicit '0' as 9911 // the second argument, so that we know this is a post-increment or 9912 // post-decrement. 9913 if (Opc == UO_PostInc || Opc == UO_PostDec) { 9914 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 9915 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 9916 SourceLocation()); 9917 NumArgs = 2; 9918 } 9919 9920 if (Input->isTypeDependent()) { 9921 if (Fns.empty()) 9922 return Owned(new (Context) UnaryOperator(Input, 9923 Opc, 9924 Context.DependentTy, 9925 VK_RValue, OK_Ordinary, 9926 OpLoc)); 9927 9928 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 9929 UnresolvedLookupExpr *Fn 9930 = UnresolvedLookupExpr::Create(Context, NamingClass, 9931 NestedNameSpecifierLoc(), OpNameInfo, 9932 /*ADL*/ true, IsOverloaded(Fns), 9933 Fns.begin(), Fns.end()); 9934 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 9935 llvm::makeArrayRef(Args, NumArgs), 9936 Context.DependentTy, 9937 VK_RValue, 9938 OpLoc)); 9939 } 9940 9941 // Build an empty overload set. 9942 OverloadCandidateSet CandidateSet(OpLoc); 9943 9944 // Add the candidates from the given function set. 9945 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet, 9946 false); 9947 9948 // Add operator candidates that are member functions. 9949 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 9950 9951 // Add candidates from ADL. 9952 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 9953 OpLoc, llvm::makeArrayRef(Args, NumArgs), 9954 /*ExplicitTemplateArgs*/ 0, 9955 CandidateSet); 9956 9957 // Add builtin operator candidates. 9958 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 9959 9960 bool HadMultipleCandidates = (CandidateSet.size() > 1); 9961 9962 // Perform overload resolution. 9963 OverloadCandidateSet::iterator Best; 9964 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 9965 case OR_Success: { 9966 // We found a built-in operator or an overloaded operator. 9967 FunctionDecl *FnDecl = Best->Function; 9968 9969 if (FnDecl) { 9970 // We matched an overloaded operator. Build a call to that 9971 // operator. 9972 9973 MarkFunctionReferenced(OpLoc, FnDecl); 9974 9975 // Convert the arguments. 9976 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 9977 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 9978 9979 ExprResult InputRes = 9980 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 9981 Best->FoundDecl, Method); 9982 if (InputRes.isInvalid()) 9983 return ExprError(); 9984 Input = InputRes.take(); 9985 } else { 9986 // Convert the arguments. 9987 ExprResult InputInit 9988 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 9989 Context, 9990 FnDecl->getParamDecl(0)), 9991 SourceLocation(), 9992 Input); 9993 if (InputInit.isInvalid()) 9994 return ExprError(); 9995 Input = InputInit.take(); 9996 } 9997 9998 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 9999 10000 // Determine the result type. 10001 QualType ResultTy = FnDecl->getResultType(); 10002 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10003 ResultTy = ResultTy.getNonLValueExprType(Context); 10004 10005 // Build the actual expression node. 10006 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10007 HadMultipleCandidates, OpLoc); 10008 if (FnExpr.isInvalid()) 10009 return ExprError(); 10010 10011 Args[0] = Input; 10012 CallExpr *TheCall = 10013 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10014 llvm::makeArrayRef(Args, NumArgs), 10015 ResultTy, VK, OpLoc); 10016 10017 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10018 FnDecl)) 10019 return ExprError(); 10020 10021 return MaybeBindToTemporary(TheCall); 10022 } else { 10023 // We matched a built-in operator. Convert the arguments, then 10024 // break out so that we will build the appropriate built-in 10025 // operator node. 10026 ExprResult InputRes = 10027 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 10028 Best->Conversions[0], AA_Passing); 10029 if (InputRes.isInvalid()) 10030 return ExprError(); 10031 Input = InputRes.take(); 10032 break; 10033 } 10034 } 10035 10036 case OR_No_Viable_Function: 10037 // This is an erroneous use of an operator which can be overloaded by 10038 // a non-member function. Check for non-member operators which were 10039 // defined too late to be candidates. 10040 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, 10041 llvm::makeArrayRef(Args, NumArgs))) 10042 // FIXME: Recover by calling the found function. 10043 return ExprError(); 10044 10045 // No viable function; fall through to handling this as a 10046 // built-in operator, which will produce an error message for us. 10047 break; 10048 10049 case OR_Ambiguous: 10050 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 10051 << UnaryOperator::getOpcodeStr(Opc) 10052 << Input->getType() 10053 << Input->getSourceRange(); 10054 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 10055 llvm::makeArrayRef(Args, NumArgs), 10056 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10057 return ExprError(); 10058 10059 case OR_Deleted: 10060 Diag(OpLoc, diag::err_ovl_deleted_oper) 10061 << Best->Function->isDeleted() 10062 << UnaryOperator::getOpcodeStr(Opc) 10063 << getDeletedOrUnavailableSuffix(Best->Function) 10064 << Input->getSourceRange(); 10065 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10066 llvm::makeArrayRef(Args, NumArgs), 10067 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10068 return ExprError(); 10069 } 10070 10071 // Either we found no viable overloaded operator or we matched a 10072 // built-in operator. In either case, fall through to trying to 10073 // build a built-in operation. 10074 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10075 } 10076 10077 /// \brief Create a binary operation that may resolve to an overloaded 10078 /// operator. 10079 /// 10080 /// \param OpLoc The location of the operator itself (e.g., '+'). 10081 /// 10082 /// \param OpcIn The BinaryOperator::Opcode that describes this 10083 /// operator. 10084 /// 10085 /// \param Fns The set of non-member functions that will be 10086 /// considered by overload resolution. The caller needs to build this 10087 /// set based on the context using, e.g., 10088 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10089 /// set should not contain any member functions; those will be added 10090 /// by CreateOverloadedBinOp(). 10091 /// 10092 /// \param LHS Left-hand argument. 10093 /// \param RHS Right-hand argument. 10094 ExprResult 10095 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 10096 unsigned OpcIn, 10097 const UnresolvedSetImpl &Fns, 10098 Expr *LHS, Expr *RHS) { 10099 Expr *Args[2] = { LHS, RHS }; 10100 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 10101 10102 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 10103 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 10104 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10105 10106 // If either side is type-dependent, create an appropriate dependent 10107 // expression. 10108 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10109 if (Fns.empty()) { 10110 // If there are no functions to store, just build a dependent 10111 // BinaryOperator or CompoundAssignment. 10112 if (Opc <= BO_Assign || Opc > BO_OrAssign) 10113 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 10114 Context.DependentTy, 10115 VK_RValue, OK_Ordinary, 10116 OpLoc)); 10117 10118 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 10119 Context.DependentTy, 10120 VK_LValue, 10121 OK_Ordinary, 10122 Context.DependentTy, 10123 Context.DependentTy, 10124 OpLoc)); 10125 } 10126 10127 // FIXME: save results of ADL from here? 10128 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10129 // TODO: provide better source location info in DNLoc component. 10130 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10131 UnresolvedLookupExpr *Fn 10132 = UnresolvedLookupExpr::Create(Context, NamingClass, 10133 NestedNameSpecifierLoc(), OpNameInfo, 10134 /*ADL*/ true, IsOverloaded(Fns), 10135 Fns.begin(), Fns.end()); 10136 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 10137 Args, 10138 Context.DependentTy, 10139 VK_RValue, 10140 OpLoc)); 10141 } 10142 10143 // Always do placeholder-like conversions on the RHS. 10144 if (checkPlaceholderForOverload(*this, Args[1])) 10145 return ExprError(); 10146 10147 // Do placeholder-like conversion on the LHS; note that we should 10148 // not get here with a PseudoObject LHS. 10149 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 10150 if (checkPlaceholderForOverload(*this, Args[0])) 10151 return ExprError(); 10152 10153 // If this is the assignment operator, we only perform overload resolution 10154 // if the left-hand side is a class or enumeration type. This is actually 10155 // a hack. The standard requires that we do overload resolution between the 10156 // various built-in candidates, but as DR507 points out, this can lead to 10157 // problems. So we do it this way, which pretty much follows what GCC does. 10158 // Note that we go the traditional code path for compound assignment forms. 10159 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 10160 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10161 10162 // If this is the .* operator, which is not overloadable, just 10163 // create a built-in binary operator. 10164 if (Opc == BO_PtrMemD) 10165 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10166 10167 // Build an empty overload set. 10168 OverloadCandidateSet CandidateSet(OpLoc); 10169 10170 // Add the candidates from the given function set. 10171 AddFunctionCandidates(Fns, Args, CandidateSet, false); 10172 10173 // Add operator candidates that are member functions. 10174 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 10175 10176 // Add candidates from ADL. 10177 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10178 OpLoc, Args, 10179 /*ExplicitTemplateArgs*/ 0, 10180 CandidateSet); 10181 10182 // Add builtin operator candidates. 10183 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 10184 10185 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10186 10187 // Perform overload resolution. 10188 OverloadCandidateSet::iterator Best; 10189 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10190 case OR_Success: { 10191 // We found a built-in operator or an overloaded operator. 10192 FunctionDecl *FnDecl = Best->Function; 10193 10194 if (FnDecl) { 10195 // We matched an overloaded operator. Build a call to that 10196 // operator. 10197 10198 MarkFunctionReferenced(OpLoc, FnDecl); 10199 10200 // Convert the arguments. 10201 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10202 // Best->Access is only meaningful for class members. 10203 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 10204 10205 ExprResult Arg1 = 10206 PerformCopyInitialization( 10207 InitializedEntity::InitializeParameter(Context, 10208 FnDecl->getParamDecl(0)), 10209 SourceLocation(), Owned(Args[1])); 10210 if (Arg1.isInvalid()) 10211 return ExprError(); 10212 10213 ExprResult Arg0 = 10214 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10215 Best->FoundDecl, Method); 10216 if (Arg0.isInvalid()) 10217 return ExprError(); 10218 Args[0] = Arg0.takeAs<Expr>(); 10219 Args[1] = RHS = Arg1.takeAs<Expr>(); 10220 } else { 10221 // Convert the arguments. 10222 ExprResult Arg0 = PerformCopyInitialization( 10223 InitializedEntity::InitializeParameter(Context, 10224 FnDecl->getParamDecl(0)), 10225 SourceLocation(), Owned(Args[0])); 10226 if (Arg0.isInvalid()) 10227 return ExprError(); 10228 10229 ExprResult Arg1 = 10230 PerformCopyInitialization( 10231 InitializedEntity::InitializeParameter(Context, 10232 FnDecl->getParamDecl(1)), 10233 SourceLocation(), Owned(Args[1])); 10234 if (Arg1.isInvalid()) 10235 return ExprError(); 10236 Args[0] = LHS = Arg0.takeAs<Expr>(); 10237 Args[1] = RHS = Arg1.takeAs<Expr>(); 10238 } 10239 10240 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 10241 10242 // Determine the result type. 10243 QualType ResultTy = FnDecl->getResultType(); 10244 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10245 ResultTy = ResultTy.getNonLValueExprType(Context); 10246 10247 // Build the actual expression node. 10248 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10249 HadMultipleCandidates, OpLoc); 10250 if (FnExpr.isInvalid()) 10251 return ExprError(); 10252 10253 CXXOperatorCallExpr *TheCall = 10254 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10255 Args, ResultTy, VK, OpLoc); 10256 10257 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10258 FnDecl)) 10259 return ExprError(); 10260 10261 return MaybeBindToTemporary(TheCall); 10262 } else { 10263 // We matched a built-in operator. Convert the arguments, then 10264 // break out so that we will build the appropriate built-in 10265 // operator node. 10266 ExprResult ArgsRes0 = 10267 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10268 Best->Conversions[0], AA_Passing); 10269 if (ArgsRes0.isInvalid()) 10270 return ExprError(); 10271 Args[0] = ArgsRes0.take(); 10272 10273 ExprResult ArgsRes1 = 10274 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10275 Best->Conversions[1], AA_Passing); 10276 if (ArgsRes1.isInvalid()) 10277 return ExprError(); 10278 Args[1] = ArgsRes1.take(); 10279 break; 10280 } 10281 } 10282 10283 case OR_No_Viable_Function: { 10284 // C++ [over.match.oper]p9: 10285 // If the operator is the operator , [...] and there are no 10286 // viable functions, then the operator is assumed to be the 10287 // built-in operator and interpreted according to clause 5. 10288 if (Opc == BO_Comma) 10289 break; 10290 10291 // For class as left operand for assignment or compound assigment 10292 // operator do not fall through to handling in built-in, but report that 10293 // no overloaded assignment operator found 10294 ExprResult Result = ExprError(); 10295 if (Args[0]->getType()->isRecordType() && 10296 Opc >= BO_Assign && Opc <= BO_OrAssign) { 10297 Diag(OpLoc, diag::err_ovl_no_viable_oper) 10298 << BinaryOperator::getOpcodeStr(Opc) 10299 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10300 } else { 10301 // This is an erroneous use of an operator which can be overloaded by 10302 // a non-member function. Check for non-member operators which were 10303 // defined too late to be candidates. 10304 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 10305 // FIXME: Recover by calling the found function. 10306 return ExprError(); 10307 10308 // No viable function; try to create a built-in operation, which will 10309 // produce an error. Then, show the non-viable candidates. 10310 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10311 } 10312 assert(Result.isInvalid() && 10313 "C++ binary operator overloading is missing candidates!"); 10314 if (Result.isInvalid()) 10315 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10316 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10317 return Result; 10318 } 10319 10320 case OR_Ambiguous: 10321 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 10322 << BinaryOperator::getOpcodeStr(Opc) 10323 << Args[0]->getType() << Args[1]->getType() 10324 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10325 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10326 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10327 return ExprError(); 10328 10329 case OR_Deleted: 10330 if (isImplicitlyDeleted(Best->Function)) { 10331 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 10332 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 10333 << getSpecialMember(Method) 10334 << BinaryOperator::getOpcodeStr(Opc) 10335 << getDeletedOrUnavailableSuffix(Best->Function); 10336 10337 if (getSpecialMember(Method) != CXXInvalid) { 10338 // The user probably meant to call this special member. Just 10339 // explain why it's deleted. 10340 NoteDeletedFunction(Method); 10341 return ExprError(); 10342 } 10343 } else { 10344 Diag(OpLoc, diag::err_ovl_deleted_oper) 10345 << Best->Function->isDeleted() 10346 << BinaryOperator::getOpcodeStr(Opc) 10347 << getDeletedOrUnavailableSuffix(Best->Function) 10348 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10349 } 10350 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10351 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10352 return ExprError(); 10353 } 10354 10355 // We matched a built-in operator; build it. 10356 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10357 } 10358 10359 ExprResult 10360 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 10361 SourceLocation RLoc, 10362 Expr *Base, Expr *Idx) { 10363 Expr *Args[2] = { Base, Idx }; 10364 DeclarationName OpName = 10365 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 10366 10367 // If either side is type-dependent, create an appropriate dependent 10368 // expression. 10369 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10370 10371 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10372 // CHECKME: no 'operator' keyword? 10373 DeclarationNameInfo OpNameInfo(OpName, LLoc); 10374 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10375 UnresolvedLookupExpr *Fn 10376 = UnresolvedLookupExpr::Create(Context, NamingClass, 10377 NestedNameSpecifierLoc(), OpNameInfo, 10378 /*ADL*/ true, /*Overloaded*/ false, 10379 UnresolvedSetIterator(), 10380 UnresolvedSetIterator()); 10381 // Can't add any actual overloads yet 10382 10383 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 10384 Args, 10385 Context.DependentTy, 10386 VK_RValue, 10387 RLoc)); 10388 } 10389 10390 // Handle placeholders on both operands. 10391 if (checkPlaceholderForOverload(*this, Args[0])) 10392 return ExprError(); 10393 if (checkPlaceholderForOverload(*this, Args[1])) 10394 return ExprError(); 10395 10396 // Build an empty overload set. 10397 OverloadCandidateSet CandidateSet(LLoc); 10398 10399 // Subscript can only be overloaded as a member function. 10400 10401 // Add operator candidates that are member functions. 10402 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 10403 10404 // Add builtin operator candidates. 10405 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 10406 10407 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10408 10409 // Perform overload resolution. 10410 OverloadCandidateSet::iterator Best; 10411 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 10412 case OR_Success: { 10413 // We found a built-in operator or an overloaded operator. 10414 FunctionDecl *FnDecl = Best->Function; 10415 10416 if (FnDecl) { 10417 // We matched an overloaded operator. Build a call to that 10418 // operator. 10419 10420 MarkFunctionReferenced(LLoc, FnDecl); 10421 10422 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 10423 DiagnoseUseOfDecl(Best->FoundDecl, LLoc); 10424 10425 // Convert the arguments. 10426 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 10427 ExprResult Arg0 = 10428 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10429 Best->FoundDecl, Method); 10430 if (Arg0.isInvalid()) 10431 return ExprError(); 10432 Args[0] = Arg0.take(); 10433 10434 // Convert the arguments. 10435 ExprResult InputInit 10436 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10437 Context, 10438 FnDecl->getParamDecl(0)), 10439 SourceLocation(), 10440 Owned(Args[1])); 10441 if (InputInit.isInvalid()) 10442 return ExprError(); 10443 10444 Args[1] = InputInit.takeAs<Expr>(); 10445 10446 // Determine the result type 10447 QualType ResultTy = FnDecl->getResultType(); 10448 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10449 ResultTy = ResultTy.getNonLValueExprType(Context); 10450 10451 // Build the actual expression node. 10452 DeclarationNameInfo OpLocInfo(OpName, LLoc); 10453 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10454 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10455 HadMultipleCandidates, 10456 OpLocInfo.getLoc(), 10457 OpLocInfo.getInfo()); 10458 if (FnExpr.isInvalid()) 10459 return ExprError(); 10460 10461 CXXOperatorCallExpr *TheCall = 10462 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 10463 FnExpr.take(), Args, 10464 ResultTy, VK, RLoc); 10465 10466 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall, 10467 FnDecl)) 10468 return ExprError(); 10469 10470 return MaybeBindToTemporary(TheCall); 10471 } else { 10472 // We matched a built-in operator. Convert the arguments, then 10473 // break out so that we will build the appropriate built-in 10474 // operator node. 10475 ExprResult ArgsRes0 = 10476 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10477 Best->Conversions[0], AA_Passing); 10478 if (ArgsRes0.isInvalid()) 10479 return ExprError(); 10480 Args[0] = ArgsRes0.take(); 10481 10482 ExprResult ArgsRes1 = 10483 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10484 Best->Conversions[1], AA_Passing); 10485 if (ArgsRes1.isInvalid()) 10486 return ExprError(); 10487 Args[1] = ArgsRes1.take(); 10488 10489 break; 10490 } 10491 } 10492 10493 case OR_No_Viable_Function: { 10494 if (CandidateSet.empty()) 10495 Diag(LLoc, diag::err_ovl_no_oper) 10496 << Args[0]->getType() << /*subscript*/ 0 10497 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10498 else 10499 Diag(LLoc, diag::err_ovl_no_viable_subscript) 10500 << Args[0]->getType() 10501 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10502 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10503 "[]", LLoc); 10504 return ExprError(); 10505 } 10506 10507 case OR_Ambiguous: 10508 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 10509 << "[]" 10510 << Args[0]->getType() << Args[1]->getType() 10511 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10512 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10513 "[]", LLoc); 10514 return ExprError(); 10515 10516 case OR_Deleted: 10517 Diag(LLoc, diag::err_ovl_deleted_oper) 10518 << Best->Function->isDeleted() << "[]" 10519 << getDeletedOrUnavailableSuffix(Best->Function) 10520 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10521 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10522 "[]", LLoc); 10523 return ExprError(); 10524 } 10525 10526 // We matched a built-in operator; build it. 10527 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 10528 } 10529 10530 /// BuildCallToMemberFunction - Build a call to a member 10531 /// function. MemExpr is the expression that refers to the member 10532 /// function (and includes the object parameter), Args/NumArgs are the 10533 /// arguments to the function call (not including the object 10534 /// parameter). The caller needs to validate that the member 10535 /// expression refers to a non-static member function or an overloaded 10536 /// member function. 10537 ExprResult 10538 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 10539 SourceLocation LParenLoc, Expr **Args, 10540 unsigned NumArgs, SourceLocation RParenLoc) { 10541 assert(MemExprE->getType() == Context.BoundMemberTy || 10542 MemExprE->getType() == Context.OverloadTy); 10543 10544 // Dig out the member expression. This holds both the object 10545 // argument and the member function we're referring to. 10546 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 10547 10548 // Determine whether this is a call to a pointer-to-member function. 10549 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 10550 assert(op->getType() == Context.BoundMemberTy); 10551 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 10552 10553 QualType fnType = 10554 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 10555 10556 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 10557 QualType resultType = proto->getCallResultType(Context); 10558 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType()); 10559 10560 // Check that the object type isn't more qualified than the 10561 // member function we're calling. 10562 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 10563 10564 QualType objectType = op->getLHS()->getType(); 10565 if (op->getOpcode() == BO_PtrMemI) 10566 objectType = objectType->castAs<PointerType>()->getPointeeType(); 10567 Qualifiers objectQuals = objectType.getQualifiers(); 10568 10569 Qualifiers difference = objectQuals - funcQuals; 10570 difference.removeObjCGCAttr(); 10571 difference.removeAddressSpace(); 10572 if (difference) { 10573 std::string qualsString = difference.getAsString(); 10574 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 10575 << fnType.getUnqualifiedType() 10576 << qualsString 10577 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 10578 } 10579 10580 CXXMemberCallExpr *call 10581 = new (Context) CXXMemberCallExpr(Context, MemExprE, 10582 llvm::makeArrayRef(Args, NumArgs), 10583 resultType, valueKind, RParenLoc); 10584 10585 if (CheckCallReturnType(proto->getResultType(), 10586 op->getRHS()->getLocStart(), 10587 call, 0)) 10588 return ExprError(); 10589 10590 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc)) 10591 return ExprError(); 10592 10593 return MaybeBindToTemporary(call); 10594 } 10595 10596 UnbridgedCastsSet UnbridgedCasts; 10597 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 10598 return ExprError(); 10599 10600 MemberExpr *MemExpr; 10601 CXXMethodDecl *Method = 0; 10602 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 10603 NestedNameSpecifier *Qualifier = 0; 10604 if (isa<MemberExpr>(NakedMemExpr)) { 10605 MemExpr = cast<MemberExpr>(NakedMemExpr); 10606 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 10607 FoundDecl = MemExpr->getFoundDecl(); 10608 Qualifier = MemExpr->getQualifier(); 10609 UnbridgedCasts.restore(); 10610 } else { 10611 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 10612 Qualifier = UnresExpr->getQualifier(); 10613 10614 QualType ObjectType = UnresExpr->getBaseType(); 10615 Expr::Classification ObjectClassification 10616 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 10617 : UnresExpr->getBase()->Classify(Context); 10618 10619 // Add overload candidates 10620 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 10621 10622 // FIXME: avoid copy. 10623 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 10624 if (UnresExpr->hasExplicitTemplateArgs()) { 10625 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 10626 TemplateArgs = &TemplateArgsBuffer; 10627 } 10628 10629 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 10630 E = UnresExpr->decls_end(); I != E; ++I) { 10631 10632 NamedDecl *Func = *I; 10633 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 10634 if (isa<UsingShadowDecl>(Func)) 10635 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 10636 10637 10638 // Microsoft supports direct constructor calls. 10639 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 10640 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 10641 llvm::makeArrayRef(Args, NumArgs), CandidateSet); 10642 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 10643 // If explicit template arguments were provided, we can't call a 10644 // non-template member function. 10645 if (TemplateArgs) 10646 continue; 10647 10648 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 10649 ObjectClassification, 10650 llvm::makeArrayRef(Args, NumArgs), CandidateSet, 10651 /*SuppressUserConversions=*/false); 10652 } else { 10653 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 10654 I.getPair(), ActingDC, TemplateArgs, 10655 ObjectType, ObjectClassification, 10656 llvm::makeArrayRef(Args, NumArgs), 10657 CandidateSet, 10658 /*SuppressUsedConversions=*/false); 10659 } 10660 } 10661 10662 DeclarationName DeclName = UnresExpr->getMemberName(); 10663 10664 UnbridgedCasts.restore(); 10665 10666 OverloadCandidateSet::iterator Best; 10667 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 10668 Best)) { 10669 case OR_Success: 10670 Method = cast<CXXMethodDecl>(Best->Function); 10671 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method); 10672 FoundDecl = Best->FoundDecl; 10673 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 10674 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()); 10675 break; 10676 10677 case OR_No_Viable_Function: 10678 Diag(UnresExpr->getMemberLoc(), 10679 diag::err_ovl_no_viable_member_function_in_call) 10680 << DeclName << MemExprE->getSourceRange(); 10681 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10682 llvm::makeArrayRef(Args, NumArgs)); 10683 // FIXME: Leaking incoming expressions! 10684 return ExprError(); 10685 10686 case OR_Ambiguous: 10687 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 10688 << DeclName << MemExprE->getSourceRange(); 10689 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10690 llvm::makeArrayRef(Args, NumArgs)); 10691 // FIXME: Leaking incoming expressions! 10692 return ExprError(); 10693 10694 case OR_Deleted: 10695 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 10696 << Best->Function->isDeleted() 10697 << DeclName 10698 << getDeletedOrUnavailableSuffix(Best->Function) 10699 << MemExprE->getSourceRange(); 10700 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10701 llvm::makeArrayRef(Args, NumArgs)); 10702 // FIXME: Leaking incoming expressions! 10703 return ExprError(); 10704 } 10705 10706 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 10707 10708 // If overload resolution picked a static member, build a 10709 // non-member call based on that function. 10710 if (Method->isStatic()) { 10711 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, 10712 Args, NumArgs, RParenLoc); 10713 } 10714 10715 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 10716 } 10717 10718 QualType ResultType = Method->getResultType(); 10719 ExprValueKind VK = Expr::getValueKindForType(ResultType); 10720 ResultType = ResultType.getNonLValueExprType(Context); 10721 10722 assert(Method && "Member call to something that isn't a method?"); 10723 CXXMemberCallExpr *TheCall = 10724 new (Context) CXXMemberCallExpr(Context, MemExprE, 10725 llvm::makeArrayRef(Args, NumArgs), 10726 ResultType, VK, RParenLoc); 10727 10728 // Check for a valid return type. 10729 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 10730 TheCall, Method)) 10731 return ExprError(); 10732 10733 // Convert the object argument (for a non-static member function call). 10734 // We only need to do this if there was actually an overload; otherwise 10735 // it was done at lookup. 10736 if (!Method->isStatic()) { 10737 ExprResult ObjectArg = 10738 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 10739 FoundDecl, Method); 10740 if (ObjectArg.isInvalid()) 10741 return ExprError(); 10742 MemExpr->setBase(ObjectArg.take()); 10743 } 10744 10745 // Convert the rest of the arguments 10746 const FunctionProtoType *Proto = 10747 Method->getType()->getAs<FunctionProtoType>(); 10748 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs, 10749 RParenLoc)) 10750 return ExprError(); 10751 10752 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs); 10753 10754 if (CheckFunctionCall(Method, TheCall, Proto)) 10755 return ExprError(); 10756 10757 if ((isa<CXXConstructorDecl>(CurContext) || 10758 isa<CXXDestructorDecl>(CurContext)) && 10759 TheCall->getMethodDecl()->isPure()) { 10760 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 10761 10762 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 10763 Diag(MemExpr->getLocStart(), 10764 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 10765 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 10766 << MD->getParent()->getDeclName(); 10767 10768 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 10769 } 10770 } 10771 return MaybeBindToTemporary(TheCall); 10772 } 10773 10774 /// BuildCallToObjectOfClassType - Build a call to an object of class 10775 /// type (C++ [over.call.object]), which can end up invoking an 10776 /// overloaded function call operator (@c operator()) or performing a 10777 /// user-defined conversion on the object argument. 10778 ExprResult 10779 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 10780 SourceLocation LParenLoc, 10781 Expr **Args, unsigned NumArgs, 10782 SourceLocation RParenLoc) { 10783 if (checkPlaceholderForOverload(*this, Obj)) 10784 return ExprError(); 10785 ExprResult Object = Owned(Obj); 10786 10787 UnbridgedCastsSet UnbridgedCasts; 10788 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 10789 return ExprError(); 10790 10791 assert(Object.get()->getType()->isRecordType() && "Requires object type argument"); 10792 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 10793 10794 // C++ [over.call.object]p1: 10795 // If the primary-expression E in the function call syntax 10796 // evaluates to a class object of type "cv T", then the set of 10797 // candidate functions includes at least the function call 10798 // operators of T. The function call operators of T are obtained by 10799 // ordinary lookup of the name operator() in the context of 10800 // (E).operator(). 10801 OverloadCandidateSet CandidateSet(LParenLoc); 10802 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 10803 10804 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 10805 diag::err_incomplete_object_call, Object.get())) 10806 return true; 10807 10808 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 10809 LookupQualifiedName(R, Record->getDecl()); 10810 R.suppressDiagnostics(); 10811 10812 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 10813 Oper != OperEnd; ++Oper) { 10814 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 10815 Object.get()->Classify(Context), Args, NumArgs, CandidateSet, 10816 /*SuppressUserConversions=*/ false); 10817 } 10818 10819 // C++ [over.call.object]p2: 10820 // In addition, for each (non-explicit in C++0x) conversion function 10821 // declared in T of the form 10822 // 10823 // operator conversion-type-id () cv-qualifier; 10824 // 10825 // where cv-qualifier is the same cv-qualification as, or a 10826 // greater cv-qualification than, cv, and where conversion-type-id 10827 // denotes the type "pointer to function of (P1,...,Pn) returning 10828 // R", or the type "reference to pointer to function of 10829 // (P1,...,Pn) returning R", or the type "reference to function 10830 // of (P1,...,Pn) returning R", a surrogate call function [...] 10831 // is also considered as a candidate function. Similarly, 10832 // surrogate call functions are added to the set of candidate 10833 // functions for each conversion function declared in an 10834 // accessible base class provided the function is not hidden 10835 // within T by another intervening declaration. 10836 const UnresolvedSetImpl *Conversions 10837 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 10838 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 10839 E = Conversions->end(); I != E; ++I) { 10840 NamedDecl *D = *I; 10841 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 10842 if (isa<UsingShadowDecl>(D)) 10843 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 10844 10845 // Skip over templated conversion functions; they aren't 10846 // surrogates. 10847 if (isa<FunctionTemplateDecl>(D)) 10848 continue; 10849 10850 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 10851 if (!Conv->isExplicit()) { 10852 // Strip the reference type (if any) and then the pointer type (if 10853 // any) to get down to what might be a function type. 10854 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 10855 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10856 ConvType = ConvPtrType->getPointeeType(); 10857 10858 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 10859 { 10860 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 10861 Object.get(), llvm::makeArrayRef(Args, NumArgs), 10862 CandidateSet); 10863 } 10864 } 10865 } 10866 10867 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10868 10869 // Perform overload resolution. 10870 OverloadCandidateSet::iterator Best; 10871 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 10872 Best)) { 10873 case OR_Success: 10874 // Overload resolution succeeded; we'll build the appropriate call 10875 // below. 10876 break; 10877 10878 case OR_No_Viable_Function: 10879 if (CandidateSet.empty()) 10880 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 10881 << Object.get()->getType() << /*call*/ 1 10882 << Object.get()->getSourceRange(); 10883 else 10884 Diag(Object.get()->getLocStart(), 10885 diag::err_ovl_no_viable_object_call) 10886 << Object.get()->getType() << Object.get()->getSourceRange(); 10887 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10888 llvm::makeArrayRef(Args, NumArgs)); 10889 break; 10890 10891 case OR_Ambiguous: 10892 Diag(Object.get()->getLocStart(), 10893 diag::err_ovl_ambiguous_object_call) 10894 << Object.get()->getType() << Object.get()->getSourceRange(); 10895 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 10896 llvm::makeArrayRef(Args, NumArgs)); 10897 break; 10898 10899 case OR_Deleted: 10900 Diag(Object.get()->getLocStart(), 10901 diag::err_ovl_deleted_object_call) 10902 << Best->Function->isDeleted() 10903 << Object.get()->getType() 10904 << getDeletedOrUnavailableSuffix(Best->Function) 10905 << Object.get()->getSourceRange(); 10906 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10907 llvm::makeArrayRef(Args, NumArgs)); 10908 break; 10909 } 10910 10911 if (Best == CandidateSet.end()) 10912 return true; 10913 10914 UnbridgedCasts.restore(); 10915 10916 if (Best->Function == 0) { 10917 // Since there is no function declaration, this is one of the 10918 // surrogate candidates. Dig out the conversion function. 10919 CXXConversionDecl *Conv 10920 = cast<CXXConversionDecl>( 10921 Best->Conversions[0].UserDefined.ConversionFunction); 10922 10923 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 10924 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 10925 10926 // We selected one of the surrogate functions that converts the 10927 // object parameter to a function pointer. Perform the conversion 10928 // on the object argument, then let ActOnCallExpr finish the job. 10929 10930 // Create an implicit member expr to refer to the conversion operator. 10931 // and then call it. 10932 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 10933 Conv, HadMultipleCandidates); 10934 if (Call.isInvalid()) 10935 return ExprError(); 10936 // Record usage of conversion in an implicit cast. 10937 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(), 10938 CK_UserDefinedConversion, 10939 Call.get(), 0, VK_RValue)); 10940 10941 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs), 10942 RParenLoc); 10943 } 10944 10945 MarkFunctionReferenced(LParenLoc, Best->Function); 10946 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 10947 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 10948 10949 // We found an overloaded operator(). Build a CXXOperatorCallExpr 10950 // that calls this method, using Object for the implicit object 10951 // parameter and passing along the remaining arguments. 10952 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 10953 const FunctionProtoType *Proto = 10954 Method->getType()->getAs<FunctionProtoType>(); 10955 10956 unsigned NumArgsInProto = Proto->getNumArgs(); 10957 unsigned NumArgsToCheck = NumArgs; 10958 10959 // Build the full argument list for the method call (the 10960 // implicit object parameter is placed at the beginning of the 10961 // list). 10962 Expr **MethodArgs; 10963 if (NumArgs < NumArgsInProto) { 10964 NumArgsToCheck = NumArgsInProto; 10965 MethodArgs = new Expr*[NumArgsInProto + 1]; 10966 } else { 10967 MethodArgs = new Expr*[NumArgs + 1]; 10968 } 10969 MethodArgs[0] = Object.get(); 10970 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 10971 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 10972 10973 DeclarationNameInfo OpLocInfo( 10974 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 10975 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 10976 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, 10977 HadMultipleCandidates, 10978 OpLocInfo.getLoc(), 10979 OpLocInfo.getInfo()); 10980 if (NewFn.isInvalid()) 10981 return true; 10982 10983 // Once we've built TheCall, all of the expressions are properly 10984 // owned. 10985 QualType ResultTy = Method->getResultType(); 10986 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10987 ResultTy = ResultTy.getNonLValueExprType(Context); 10988 10989 CXXOperatorCallExpr *TheCall = 10990 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(), 10991 llvm::makeArrayRef(MethodArgs, NumArgs+1), 10992 ResultTy, VK, RParenLoc); 10993 delete [] MethodArgs; 10994 10995 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall, 10996 Method)) 10997 return true; 10998 10999 // We may have default arguments. If so, we need to allocate more 11000 // slots in the call for them. 11001 if (NumArgs < NumArgsInProto) 11002 TheCall->setNumArgs(Context, NumArgsInProto + 1); 11003 else if (NumArgs > NumArgsInProto) 11004 NumArgsToCheck = NumArgsInProto; 11005 11006 bool IsError = false; 11007 11008 // Initialize the implicit object parameter. 11009 ExprResult ObjRes = 11010 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0, 11011 Best->FoundDecl, Method); 11012 if (ObjRes.isInvalid()) 11013 IsError = true; 11014 else 11015 Object = ObjRes; 11016 TheCall->setArg(0, Object.take()); 11017 11018 // Check the argument types. 11019 for (unsigned i = 0; i != NumArgsToCheck; i++) { 11020 Expr *Arg; 11021 if (i < NumArgs) { 11022 Arg = Args[i]; 11023 11024 // Pass the argument. 11025 11026 ExprResult InputInit 11027 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11028 Context, 11029 Method->getParamDecl(i)), 11030 SourceLocation(), Arg); 11031 11032 IsError |= InputInit.isInvalid(); 11033 Arg = InputInit.takeAs<Expr>(); 11034 } else { 11035 ExprResult DefArg 11036 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 11037 if (DefArg.isInvalid()) { 11038 IsError = true; 11039 break; 11040 } 11041 11042 Arg = DefArg.takeAs<Expr>(); 11043 } 11044 11045 TheCall->setArg(i + 1, Arg); 11046 } 11047 11048 // If this is a variadic call, handle args passed through "...". 11049 if (Proto->isVariadic()) { 11050 // Promote the arguments (C99 6.5.2.2p7). 11051 for (unsigned i = NumArgsInProto; i < NumArgs; i++) { 11052 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); 11053 IsError |= Arg.isInvalid(); 11054 TheCall->setArg(i + 1, Arg.take()); 11055 } 11056 } 11057 11058 if (IsError) return true; 11059 11060 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs); 11061 11062 if (CheckFunctionCall(Method, TheCall, Proto)) 11063 return true; 11064 11065 return MaybeBindToTemporary(TheCall); 11066 } 11067 11068 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 11069 /// (if one exists), where @c Base is an expression of class type and 11070 /// @c Member is the name of the member we're trying to find. 11071 ExprResult 11072 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) { 11073 assert(Base->getType()->isRecordType() && 11074 "left-hand side must have class type"); 11075 11076 if (checkPlaceholderForOverload(*this, Base)) 11077 return ExprError(); 11078 11079 SourceLocation Loc = Base->getExprLoc(); 11080 11081 // C++ [over.ref]p1: 11082 // 11083 // [...] An expression x->m is interpreted as (x.operator->())->m 11084 // for a class object x of type T if T::operator->() exists and if 11085 // the operator is selected as the best match function by the 11086 // overload resolution mechanism (13.3). 11087 DeclarationName OpName = 11088 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 11089 OverloadCandidateSet CandidateSet(Loc); 11090 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 11091 11092 if (RequireCompleteType(Loc, Base->getType(), 11093 diag::err_typecheck_incomplete_tag, Base)) 11094 return ExprError(); 11095 11096 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 11097 LookupQualifiedName(R, BaseRecord->getDecl()); 11098 R.suppressDiagnostics(); 11099 11100 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11101 Oper != OperEnd; ++Oper) { 11102 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 11103 0, 0, CandidateSet, /*SuppressUserConversions=*/false); 11104 } 11105 11106 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11107 11108 // Perform overload resolution. 11109 OverloadCandidateSet::iterator Best; 11110 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11111 case OR_Success: 11112 // Overload resolution succeeded; we'll build the call below. 11113 break; 11114 11115 case OR_No_Viable_Function: 11116 if (CandidateSet.empty()) 11117 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 11118 << Base->getType() << Base->getSourceRange(); 11119 else 11120 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11121 << "operator->" << Base->getSourceRange(); 11122 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11123 return ExprError(); 11124 11125 case OR_Ambiguous: 11126 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11127 << "->" << Base->getType() << Base->getSourceRange(); 11128 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 11129 return ExprError(); 11130 11131 case OR_Deleted: 11132 Diag(OpLoc, diag::err_ovl_deleted_oper) 11133 << Best->Function->isDeleted() 11134 << "->" 11135 << getDeletedOrUnavailableSuffix(Best->Function) 11136 << Base->getSourceRange(); 11137 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11138 return ExprError(); 11139 } 11140 11141 MarkFunctionReferenced(OpLoc, Best->Function); 11142 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 11143 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 11144 11145 // Convert the object parameter. 11146 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11147 ExprResult BaseResult = 11148 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 11149 Best->FoundDecl, Method); 11150 if (BaseResult.isInvalid()) 11151 return ExprError(); 11152 Base = BaseResult.take(); 11153 11154 // Build the operator call. 11155 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, 11156 HadMultipleCandidates, OpLoc); 11157 if (FnExpr.isInvalid()) 11158 return ExprError(); 11159 11160 QualType ResultTy = Method->getResultType(); 11161 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11162 ResultTy = ResultTy.getNonLValueExprType(Context); 11163 CXXOperatorCallExpr *TheCall = 11164 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(), 11165 Base, ResultTy, VK, OpLoc); 11166 11167 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall, 11168 Method)) 11169 return ExprError(); 11170 11171 return MaybeBindToTemporary(TheCall); 11172 } 11173 11174 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 11175 /// a literal operator described by the provided lookup results. 11176 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 11177 DeclarationNameInfo &SuffixInfo, 11178 ArrayRef<Expr*> Args, 11179 SourceLocation LitEndLoc, 11180 TemplateArgumentListInfo *TemplateArgs) { 11181 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 11182 11183 OverloadCandidateSet CandidateSet(UDSuffixLoc); 11184 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true, 11185 TemplateArgs); 11186 11187 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11188 11189 // Perform overload resolution. This will usually be trivial, but might need 11190 // to perform substitutions for a literal operator template. 11191 OverloadCandidateSet::iterator Best; 11192 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 11193 case OR_Success: 11194 case OR_Deleted: 11195 break; 11196 11197 case OR_No_Viable_Function: 11198 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 11199 << R.getLookupName(); 11200 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11201 return ExprError(); 11202 11203 case OR_Ambiguous: 11204 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 11205 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11206 return ExprError(); 11207 } 11208 11209 FunctionDecl *FD = Best->Function; 11210 MarkFunctionReferenced(UDSuffixLoc, FD); 11211 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc); 11212 11213 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates, 11214 SuffixInfo.getLoc(), 11215 SuffixInfo.getInfo()); 11216 if (Fn.isInvalid()) 11217 return true; 11218 11219 // Check the argument types. This should almost always be a no-op, except 11220 // that array-to-pointer decay is applied to string literals. 11221 Expr *ConvArgs[2]; 11222 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 11223 ExprResult InputInit = PerformCopyInitialization( 11224 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 11225 SourceLocation(), Args[ArgIdx]); 11226 if (InputInit.isInvalid()) 11227 return true; 11228 ConvArgs[ArgIdx] = InputInit.take(); 11229 } 11230 11231 QualType ResultTy = FD->getResultType(); 11232 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11233 ResultTy = ResultTy.getNonLValueExprType(Context); 11234 11235 UserDefinedLiteral *UDL = 11236 new (Context) UserDefinedLiteral(Context, Fn.take(), 11237 llvm::makeArrayRef(ConvArgs, Args.size()), 11238 ResultTy, VK, LitEndLoc, UDSuffixLoc); 11239 11240 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD)) 11241 return ExprError(); 11242 11243 if (CheckFunctionCall(FD, UDL, NULL)) 11244 return ExprError(); 11245 11246 return MaybeBindToTemporary(UDL); 11247 } 11248 11249 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 11250 /// given LookupResult is non-empty, it is assumed to describe a member which 11251 /// will be invoked. Otherwise, the function will be found via argument 11252 /// dependent lookup. 11253 /// CallExpr is set to a valid expression and FRS_Success returned on success, 11254 /// otherwise CallExpr is set to ExprError() and some non-success value 11255 /// is returned. 11256 Sema::ForRangeStatus 11257 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 11258 SourceLocation RangeLoc, VarDecl *Decl, 11259 BeginEndFunction BEF, 11260 const DeclarationNameInfo &NameInfo, 11261 LookupResult &MemberLookup, 11262 OverloadCandidateSet *CandidateSet, 11263 Expr *Range, ExprResult *CallExpr) { 11264 CandidateSet->clear(); 11265 if (!MemberLookup.empty()) { 11266 ExprResult MemberRef = 11267 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 11268 /*IsPtr=*/false, CXXScopeSpec(), 11269 /*TemplateKWLoc=*/SourceLocation(), 11270 /*FirstQualifierInScope=*/0, 11271 MemberLookup, 11272 /*TemplateArgs=*/0); 11273 if (MemberRef.isInvalid()) { 11274 *CallExpr = ExprError(); 11275 Diag(Range->getLocStart(), diag::note_in_for_range) 11276 << RangeLoc << BEF << Range->getType(); 11277 return FRS_DiagnosticIssued; 11278 } 11279 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0); 11280 if (CallExpr->isInvalid()) { 11281 *CallExpr = ExprError(); 11282 Diag(Range->getLocStart(), diag::note_in_for_range) 11283 << RangeLoc << BEF << Range->getType(); 11284 return FRS_DiagnosticIssued; 11285 } 11286 } else { 11287 UnresolvedSet<0> FoundNames; 11288 // C++11 [stmt.ranged]p1: For the purposes of this name lookup, namespace 11289 // std is an associated namespace. 11290 UnresolvedLookupExpr *Fn = 11291 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0, 11292 NestedNameSpecifierLoc(), NameInfo, 11293 /*NeedsADL=*/true, /*Overloaded=*/false, 11294 FoundNames.begin(), FoundNames.end(), 11295 /*LookInStdNamespace=*/true); 11296 11297 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc, 11298 CandidateSet, CallExpr); 11299 if (CandidateSet->empty() || CandidateSetError) { 11300 *CallExpr = ExprError(); 11301 return FRS_NoViableFunction; 11302 } 11303 OverloadCandidateSet::iterator Best; 11304 OverloadingResult OverloadResult = 11305 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 11306 11307 if (OverloadResult == OR_No_Viable_Function) { 11308 *CallExpr = ExprError(); 11309 return FRS_NoViableFunction; 11310 } 11311 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1, 11312 Loc, 0, CandidateSet, &Best, 11313 OverloadResult, 11314 /*AllowTypoCorrection=*/false); 11315 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 11316 *CallExpr = ExprError(); 11317 Diag(Range->getLocStart(), diag::note_in_for_range) 11318 << RangeLoc << BEF << Range->getType(); 11319 return FRS_DiagnosticIssued; 11320 } 11321 } 11322 return FRS_Success; 11323 } 11324 11325 11326 /// FixOverloadedFunctionReference - E is an expression that refers to 11327 /// a C++ overloaded function (possibly with some parentheses and 11328 /// perhaps a '&' around it). We have resolved the overloaded function 11329 /// to the function declaration Fn, so patch up the expression E to 11330 /// refer (possibly indirectly) to Fn. Returns the new expr. 11331 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 11332 FunctionDecl *Fn) { 11333 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 11334 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 11335 Found, Fn); 11336 if (SubExpr == PE->getSubExpr()) 11337 return PE; 11338 11339 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 11340 } 11341 11342 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11343 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 11344 Found, Fn); 11345 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 11346 SubExpr->getType()) && 11347 "Implicit cast type cannot be determined from overload"); 11348 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 11349 if (SubExpr == ICE->getSubExpr()) 11350 return ICE; 11351 11352 return ImplicitCastExpr::Create(Context, ICE->getType(), 11353 ICE->getCastKind(), 11354 SubExpr, 0, 11355 ICE->getValueKind()); 11356 } 11357 11358 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 11359 assert(UnOp->getOpcode() == UO_AddrOf && 11360 "Can only take the address of an overloaded function"); 11361 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11362 if (Method->isStatic()) { 11363 // Do nothing: static member functions aren't any different 11364 // from non-member functions. 11365 } else { 11366 // Fix the sub expression, which really has to be an 11367 // UnresolvedLookupExpr holding an overloaded member function 11368 // or template. 11369 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11370 Found, Fn); 11371 if (SubExpr == UnOp->getSubExpr()) 11372 return UnOp; 11373 11374 assert(isa<DeclRefExpr>(SubExpr) 11375 && "fixed to something other than a decl ref"); 11376 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 11377 && "fixed to a member ref with no nested name qualifier"); 11378 11379 // We have taken the address of a pointer to member 11380 // function. Perform the computation here so that we get the 11381 // appropriate pointer to member type. 11382 QualType ClassType 11383 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 11384 QualType MemPtrType 11385 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 11386 11387 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 11388 VK_RValue, OK_Ordinary, 11389 UnOp->getOperatorLoc()); 11390 } 11391 } 11392 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11393 Found, Fn); 11394 if (SubExpr == UnOp->getSubExpr()) 11395 return UnOp; 11396 11397 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 11398 Context.getPointerType(SubExpr->getType()), 11399 VK_RValue, OK_Ordinary, 11400 UnOp->getOperatorLoc()); 11401 } 11402 11403 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11404 // FIXME: avoid copy. 11405 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11406 if (ULE->hasExplicitTemplateArgs()) { 11407 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 11408 TemplateArgs = &TemplateArgsBuffer; 11409 } 11410 11411 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11412 ULE->getQualifierLoc(), 11413 ULE->getTemplateKeywordLoc(), 11414 Fn, 11415 /*enclosing*/ false, // FIXME? 11416 ULE->getNameLoc(), 11417 Fn->getType(), 11418 VK_LValue, 11419 Found.getDecl(), 11420 TemplateArgs); 11421 MarkDeclRefReferenced(DRE); 11422 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 11423 return DRE; 11424 } 11425 11426 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 11427 // FIXME: avoid copy. 11428 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11429 if (MemExpr->hasExplicitTemplateArgs()) { 11430 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11431 TemplateArgs = &TemplateArgsBuffer; 11432 } 11433 11434 Expr *Base; 11435 11436 // If we're filling in a static method where we used to have an 11437 // implicit member access, rewrite to a simple decl ref. 11438 if (MemExpr->isImplicitAccess()) { 11439 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11440 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11441 MemExpr->getQualifierLoc(), 11442 MemExpr->getTemplateKeywordLoc(), 11443 Fn, 11444 /*enclosing*/ false, 11445 MemExpr->getMemberLoc(), 11446 Fn->getType(), 11447 VK_LValue, 11448 Found.getDecl(), 11449 TemplateArgs); 11450 MarkDeclRefReferenced(DRE); 11451 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 11452 return DRE; 11453 } else { 11454 SourceLocation Loc = MemExpr->getMemberLoc(); 11455 if (MemExpr->getQualifier()) 11456 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 11457 CheckCXXThisCapture(Loc); 11458 Base = new (Context) CXXThisExpr(Loc, 11459 MemExpr->getBaseType(), 11460 /*isImplicit=*/true); 11461 } 11462 } else 11463 Base = MemExpr->getBase(); 11464 11465 ExprValueKind valueKind; 11466 QualType type; 11467 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11468 valueKind = VK_LValue; 11469 type = Fn->getType(); 11470 } else { 11471 valueKind = VK_RValue; 11472 type = Context.BoundMemberTy; 11473 } 11474 11475 MemberExpr *ME = MemberExpr::Create(Context, Base, 11476 MemExpr->isArrow(), 11477 MemExpr->getQualifierLoc(), 11478 MemExpr->getTemplateKeywordLoc(), 11479 Fn, 11480 Found, 11481 MemExpr->getMemberNameInfo(), 11482 TemplateArgs, 11483 type, valueKind, OK_Ordinary); 11484 ME->setHadMultipleCandidates(true); 11485 return ME; 11486 } 11487 11488 llvm_unreachable("Invalid reference to overloaded function"); 11489 } 11490 11491 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 11492 DeclAccessPair Found, 11493 FunctionDecl *Fn) { 11494 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 11495 } 11496 11497 } // end namespace clang 11498