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/Overload.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/CXXInheritance.h" 17 #include "clang/AST/DeclObjC.h" 18 #include "clang/AST/Expr.h" 19 #include "clang/AST/ExprCXX.h" 20 #include "clang/AST/ExprObjC.h" 21 #include "clang/AST/TypeOrdering.h" 22 #include "clang/Basic/Diagnostic.h" 23 #include "clang/Basic/PartialDiagnostic.h" 24 #include "clang/Lex/Preprocessor.h" 25 #include "clang/Sema/Initialization.h" 26 #include "clang/Sema/Lookup.h" 27 #include "clang/Sema/SemaInternal.h" 28 #include "clang/Sema/Template.h" 29 #include "clang/Sema/TemplateDeduction.h" 30 #include "llvm/ADT/DenseSet.h" 31 #include "llvm/ADT/STLExtras.h" 32 #include "llvm/ADT/SmallPtrSet.h" 33 #include "llvm/ADT/SmallString.h" 34 #include <algorithm> 35 36 namespace clang { 37 using namespace sema; 38 39 /// A convenience routine for creating a decayed reference to a 40 /// function. 41 static ExprResult 42 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates, 43 SourceLocation Loc = SourceLocation(), 44 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 45 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 46 VK_LValue, Loc, LocInfo); 47 if (HadMultipleCandidates) 48 DRE->setHadMultipleCandidates(true); 49 ExprResult E = S.Owned(DRE); 50 E = S.DefaultFunctionArrayConversion(E.take()); 51 if (E.isInvalid()) 52 return ExprError(); 53 return E; 54 } 55 56 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 57 bool InOverloadResolution, 58 StandardConversionSequence &SCS, 59 bool CStyle, 60 bool AllowObjCWritebackConversion); 61 62 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 63 QualType &ToType, 64 bool InOverloadResolution, 65 StandardConversionSequence &SCS, 66 bool CStyle); 67 static OverloadingResult 68 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 69 UserDefinedConversionSequence& User, 70 OverloadCandidateSet& Conversions, 71 bool AllowExplicit); 72 73 74 static ImplicitConversionSequence::CompareKind 75 CompareStandardConversionSequences(Sema &S, 76 const StandardConversionSequence& SCS1, 77 const StandardConversionSequence& SCS2); 78 79 static ImplicitConversionSequence::CompareKind 80 CompareQualificationConversions(Sema &S, 81 const StandardConversionSequence& SCS1, 82 const StandardConversionSequence& SCS2); 83 84 static ImplicitConversionSequence::CompareKind 85 CompareDerivedToBaseConversions(Sema &S, 86 const StandardConversionSequence& SCS1, 87 const StandardConversionSequence& SCS2); 88 89 90 91 /// GetConversionCategory - Retrieve the implicit conversion 92 /// category corresponding to the given implicit conversion kind. 93 ImplicitConversionCategory 94 GetConversionCategory(ImplicitConversionKind Kind) { 95 static const ImplicitConversionCategory 96 Category[(int)ICK_Num_Conversion_Kinds] = { 97 ICC_Identity, 98 ICC_Lvalue_Transformation, 99 ICC_Lvalue_Transformation, 100 ICC_Lvalue_Transformation, 101 ICC_Identity, 102 ICC_Qualification_Adjustment, 103 ICC_Promotion, 104 ICC_Promotion, 105 ICC_Promotion, 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 ICC_Conversion 119 }; 120 return Category[(int)Kind]; 121 } 122 123 /// GetConversionRank - Retrieve the implicit conversion rank 124 /// corresponding to the given implicit conversion kind. 125 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 126 static const ImplicitConversionRank 127 Rank[(int)ICK_Num_Conversion_Kinds] = { 128 ICR_Exact_Match, 129 ICR_Exact_Match, 130 ICR_Exact_Match, 131 ICR_Exact_Match, 132 ICR_Exact_Match, 133 ICR_Exact_Match, 134 ICR_Promotion, 135 ICR_Promotion, 136 ICR_Promotion, 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_Conversion, 148 ICR_Complex_Real_Conversion, 149 ICR_Conversion, 150 ICR_Conversion, 151 ICR_Writeback_Conversion 152 }; 153 return Rank[(int)Kind]; 154 } 155 156 /// GetImplicitConversionName - Return the name of this kind of 157 /// implicit conversion. 158 const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 159 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 160 "No conversion", 161 "Lvalue-to-rvalue", 162 "Array-to-pointer", 163 "Function-to-pointer", 164 "Noreturn adjustment", 165 "Qualification", 166 "Integral promotion", 167 "Floating point promotion", 168 "Complex promotion", 169 "Integral conversion", 170 "Floating conversion", 171 "Complex conversion", 172 "Floating-integral conversion", 173 "Pointer conversion", 174 "Pointer-to-member conversion", 175 "Boolean conversion", 176 "Compatible-types conversion", 177 "Derived-to-base conversion", 178 "Vector conversion", 179 "Vector splat", 180 "Complex-real conversion", 181 "Block Pointer conversion", 182 "Transparent Union Conversion" 183 "Writeback conversion" 184 }; 185 return Name[Kind]; 186 } 187 188 /// StandardConversionSequence - Set the standard conversion 189 /// sequence to the identity conversion. 190 void StandardConversionSequence::setAsIdentityConversion() { 191 First = ICK_Identity; 192 Second = ICK_Identity; 193 Third = ICK_Identity; 194 DeprecatedStringLiteralToCharPtr = false; 195 QualificationIncludesObjCLifetime = false; 196 ReferenceBinding = false; 197 DirectBinding = false; 198 IsLvalueReference = true; 199 BindsToFunctionLvalue = false; 200 BindsToRvalue = false; 201 BindsImplicitObjectArgumentWithoutRefQualifier = false; 202 ObjCLifetimeConversionBinding = false; 203 CopyConstructor = 0; 204 } 205 206 /// getRank - Retrieve the rank of this standard conversion sequence 207 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 208 /// implicit conversions. 209 ImplicitConversionRank StandardConversionSequence::getRank() const { 210 ImplicitConversionRank Rank = ICR_Exact_Match; 211 if (GetConversionRank(First) > Rank) 212 Rank = GetConversionRank(First); 213 if (GetConversionRank(Second) > Rank) 214 Rank = GetConversionRank(Second); 215 if (GetConversionRank(Third) > Rank) 216 Rank = GetConversionRank(Third); 217 return Rank; 218 } 219 220 /// isPointerConversionToBool - Determines whether this conversion is 221 /// a conversion of a pointer or pointer-to-member to bool. This is 222 /// used as part of the ranking of standard conversion sequences 223 /// (C++ 13.3.3.2p4). 224 bool StandardConversionSequence::isPointerConversionToBool() const { 225 // Note that FromType has not necessarily been transformed by the 226 // array-to-pointer or function-to-pointer implicit conversions, so 227 // check for their presence as well as checking whether FromType is 228 // a pointer. 229 if (getToType(1)->isBooleanType() && 230 (getFromType()->isPointerType() || 231 getFromType()->isObjCObjectPointerType() || 232 getFromType()->isBlockPointerType() || 233 getFromType()->isNullPtrType() || 234 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 235 return true; 236 237 return false; 238 } 239 240 /// isPointerConversionToVoidPointer - Determines whether this 241 /// conversion is a conversion of a pointer to a void pointer. This is 242 /// used as part of the ranking of standard conversion sequences (C++ 243 /// 13.3.3.2p4). 244 bool 245 StandardConversionSequence:: 246 isPointerConversionToVoidPointer(ASTContext& Context) const { 247 QualType FromType = getFromType(); 248 QualType ToType = getToType(1); 249 250 // Note that FromType has not necessarily been transformed by the 251 // array-to-pointer implicit conversion, so check for its presence 252 // and redo the conversion to get a pointer. 253 if (First == ICK_Array_To_Pointer) 254 FromType = Context.getArrayDecayedType(FromType); 255 256 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 257 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 258 return ToPtrType->getPointeeType()->isVoidType(); 259 260 return false; 261 } 262 263 /// Skip any implicit casts which could be either part of a narrowing conversion 264 /// or after one in an implicit conversion. 265 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 266 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 267 switch (ICE->getCastKind()) { 268 case CK_NoOp: 269 case CK_IntegralCast: 270 case CK_IntegralToBoolean: 271 case CK_IntegralToFloating: 272 case CK_FloatingToIntegral: 273 case CK_FloatingToBoolean: 274 case CK_FloatingCast: 275 Converted = ICE->getSubExpr(); 276 continue; 277 278 default: 279 return Converted; 280 } 281 } 282 283 return Converted; 284 } 285 286 /// Check if this standard conversion sequence represents a narrowing 287 /// conversion, according to C++11 [dcl.init.list]p7. 288 /// 289 /// \param Ctx The AST context. 290 /// \param Converted The result of applying this standard conversion sequence. 291 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 292 /// value of the expression prior to the narrowing conversion. 293 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 294 /// type of the expression prior to the narrowing conversion. 295 NarrowingKind 296 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 297 const Expr *Converted, 298 APValue &ConstantValue, 299 QualType &ConstantType) const { 300 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 301 302 // C++11 [dcl.init.list]p7: 303 // A narrowing conversion is an implicit conversion ... 304 QualType FromType = getToType(0); 305 QualType ToType = getToType(1); 306 switch (Second) { 307 // -- from a floating-point type to an integer type, or 308 // 309 // -- from an integer type or unscoped enumeration type to a floating-point 310 // type, except where the source is a constant expression and the actual 311 // value after conversion will fit into the target type and will produce 312 // the original value when converted back to the original type, or 313 case ICK_Floating_Integral: 314 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 315 return NK_Type_Narrowing; 316 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 317 llvm::APSInt IntConstantValue; 318 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 319 if (Initializer && 320 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 321 // Convert the integer to the floating type. 322 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 323 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 324 llvm::APFloat::rmNearestTiesToEven); 325 // And back. 326 llvm::APSInt ConvertedValue = IntConstantValue; 327 bool ignored; 328 Result.convertToInteger(ConvertedValue, 329 llvm::APFloat::rmTowardZero, &ignored); 330 // If the resulting value is different, this was a narrowing conversion. 331 if (IntConstantValue != ConvertedValue) { 332 ConstantValue = APValue(IntConstantValue); 333 ConstantType = Initializer->getType(); 334 return NK_Constant_Narrowing; 335 } 336 } else { 337 // Variables are always narrowings. 338 return NK_Variable_Narrowing; 339 } 340 } 341 return NK_Not_Narrowing; 342 343 // -- from long double to double or float, or from double to float, except 344 // where the source is a constant expression and the actual value after 345 // conversion is within the range of values that can be represented (even 346 // if it cannot be represented exactly), or 347 case ICK_Floating_Conversion: 348 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 349 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 350 // FromType is larger than ToType. 351 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 352 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 353 // Constant! 354 assert(ConstantValue.isFloat()); 355 llvm::APFloat FloatVal = ConstantValue.getFloat(); 356 // Convert the source value into the target type. 357 bool ignored; 358 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 359 Ctx.getFloatTypeSemantics(ToType), 360 llvm::APFloat::rmNearestTiesToEven, &ignored); 361 // If there was no overflow, the source value is within the range of 362 // values that can be represented. 363 if (ConvertStatus & llvm::APFloat::opOverflow) { 364 ConstantType = Initializer->getType(); 365 return NK_Constant_Narrowing; 366 } 367 } else { 368 return NK_Variable_Narrowing; 369 } 370 } 371 return NK_Not_Narrowing; 372 373 // -- from an integer type or unscoped enumeration type to an integer type 374 // that cannot represent all the values of the original type, except where 375 // the source is a constant expression and the actual value after 376 // conversion will fit into the target type and will produce the original 377 // value when converted back to the original type. 378 case ICK_Boolean_Conversion: // Bools are integers too. 379 if (!FromType->isIntegralOrUnscopedEnumerationType()) { 380 // Boolean conversions can be from pointers and pointers to members 381 // [conv.bool], and those aren't considered narrowing conversions. 382 return NK_Not_Narrowing; 383 } // Otherwise, fall through to the integral case. 384 case ICK_Integral_Conversion: { 385 assert(FromType->isIntegralOrUnscopedEnumerationType()); 386 assert(ToType->isIntegralOrUnscopedEnumerationType()); 387 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 388 const unsigned FromWidth = Ctx.getIntWidth(FromType); 389 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 390 const unsigned ToWidth = Ctx.getIntWidth(ToType); 391 392 if (FromWidth > ToWidth || 393 (FromWidth == ToWidth && FromSigned != ToSigned) || 394 (FromSigned && !ToSigned)) { 395 // Not all values of FromType can be represented in ToType. 396 llvm::APSInt InitializerValue; 397 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 398 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 399 // Such conversions on variables are always narrowing. 400 return NK_Variable_Narrowing; 401 } 402 bool Narrowing = false; 403 if (FromWidth < ToWidth) { 404 // Negative -> unsigned is narrowing. Otherwise, more bits is never 405 // narrowing. 406 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 407 Narrowing = true; 408 } else { 409 // Add a bit to the InitializerValue so we don't have to worry about 410 // signed vs. unsigned comparisons. 411 InitializerValue = InitializerValue.extend( 412 InitializerValue.getBitWidth() + 1); 413 // Convert the initializer to and from the target width and signed-ness. 414 llvm::APSInt ConvertedValue = InitializerValue; 415 ConvertedValue = ConvertedValue.trunc(ToWidth); 416 ConvertedValue.setIsSigned(ToSigned); 417 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 418 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 419 // If the result is different, this was a narrowing conversion. 420 if (ConvertedValue != InitializerValue) 421 Narrowing = true; 422 } 423 if (Narrowing) { 424 ConstantType = Initializer->getType(); 425 ConstantValue = APValue(InitializerValue); 426 return NK_Constant_Narrowing; 427 } 428 } 429 return NK_Not_Narrowing; 430 } 431 432 default: 433 // Other kinds of conversions are not narrowings. 434 return NK_Not_Narrowing; 435 } 436 } 437 438 /// DebugPrint - Print this standard conversion sequence to standard 439 /// error. Useful for debugging overloading issues. 440 void StandardConversionSequence::DebugPrint() const { 441 raw_ostream &OS = llvm::errs(); 442 bool PrintedSomething = false; 443 if (First != ICK_Identity) { 444 OS << GetImplicitConversionName(First); 445 PrintedSomething = true; 446 } 447 448 if (Second != ICK_Identity) { 449 if (PrintedSomething) { 450 OS << " -> "; 451 } 452 OS << GetImplicitConversionName(Second); 453 454 if (CopyConstructor) { 455 OS << " (by copy constructor)"; 456 } else if (DirectBinding) { 457 OS << " (direct reference binding)"; 458 } else if (ReferenceBinding) { 459 OS << " (reference binding)"; 460 } 461 PrintedSomething = true; 462 } 463 464 if (Third != ICK_Identity) { 465 if (PrintedSomething) { 466 OS << " -> "; 467 } 468 OS << GetImplicitConversionName(Third); 469 PrintedSomething = true; 470 } 471 472 if (!PrintedSomething) { 473 OS << "No conversions required"; 474 } 475 } 476 477 /// DebugPrint - Print this user-defined conversion sequence to standard 478 /// error. Useful for debugging overloading issues. 479 void UserDefinedConversionSequence::DebugPrint() const { 480 raw_ostream &OS = llvm::errs(); 481 if (Before.First || Before.Second || Before.Third) { 482 Before.DebugPrint(); 483 OS << " -> "; 484 } 485 if (ConversionFunction) 486 OS << '\'' << *ConversionFunction << '\''; 487 else 488 OS << "aggregate initialization"; 489 if (After.First || After.Second || After.Third) { 490 OS << " -> "; 491 After.DebugPrint(); 492 } 493 } 494 495 /// DebugPrint - Print this implicit conversion sequence to standard 496 /// error. Useful for debugging overloading issues. 497 void ImplicitConversionSequence::DebugPrint() const { 498 raw_ostream &OS = llvm::errs(); 499 switch (ConversionKind) { 500 case StandardConversion: 501 OS << "Standard conversion: "; 502 Standard.DebugPrint(); 503 break; 504 case UserDefinedConversion: 505 OS << "User-defined conversion: "; 506 UserDefined.DebugPrint(); 507 break; 508 case EllipsisConversion: 509 OS << "Ellipsis conversion"; 510 break; 511 case AmbiguousConversion: 512 OS << "Ambiguous conversion"; 513 break; 514 case BadConversion: 515 OS << "Bad conversion"; 516 break; 517 } 518 519 OS << "\n"; 520 } 521 522 void AmbiguousConversionSequence::construct() { 523 new (&conversions()) ConversionSet(); 524 } 525 526 void AmbiguousConversionSequence::destruct() { 527 conversions().~ConversionSet(); 528 } 529 530 void 531 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 532 FromTypePtr = O.FromTypePtr; 533 ToTypePtr = O.ToTypePtr; 534 new (&conversions()) ConversionSet(O.conversions()); 535 } 536 537 namespace { 538 // Structure used by OverloadCandidate::DeductionFailureInfo to store 539 // template parameter and template argument information. 540 struct DFIParamWithArguments { 541 TemplateParameter Param; 542 TemplateArgument FirstArg; 543 TemplateArgument SecondArg; 544 }; 545 } 546 547 /// \brief Convert from Sema's representation of template deduction information 548 /// to the form used in overload-candidate information. 549 OverloadCandidate::DeductionFailureInfo 550 static MakeDeductionFailureInfo(ASTContext &Context, 551 Sema::TemplateDeductionResult TDK, 552 TemplateDeductionInfo &Info) { 553 OverloadCandidate::DeductionFailureInfo Result; 554 Result.Result = static_cast<unsigned>(TDK); 555 Result.HasDiagnostic = false; 556 Result.Data = 0; 557 switch (TDK) { 558 case Sema::TDK_Success: 559 case Sema::TDK_Invalid: 560 case Sema::TDK_InstantiationDepth: 561 case Sema::TDK_TooManyArguments: 562 case Sema::TDK_TooFewArguments: 563 break; 564 565 case Sema::TDK_Incomplete: 566 case Sema::TDK_InvalidExplicitArguments: 567 Result.Data = Info.Param.getOpaqueValue(); 568 break; 569 570 case Sema::TDK_Inconsistent: 571 case Sema::TDK_Underqualified: { 572 // FIXME: Should allocate from normal heap so that we can free this later. 573 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 574 Saved->Param = Info.Param; 575 Saved->FirstArg = Info.FirstArg; 576 Saved->SecondArg = Info.SecondArg; 577 Result.Data = Saved; 578 break; 579 } 580 581 case Sema::TDK_SubstitutionFailure: 582 Result.Data = Info.take(); 583 if (Info.hasSFINAEDiagnostic()) { 584 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 585 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 586 Info.takeSFINAEDiagnostic(*Diag); 587 Result.HasDiagnostic = true; 588 } 589 break; 590 591 case Sema::TDK_NonDeducedMismatch: 592 case Sema::TDK_FailedOverloadResolution: 593 break; 594 } 595 596 return Result; 597 } 598 599 void OverloadCandidate::DeductionFailureInfo::Destroy() { 600 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 601 case Sema::TDK_Success: 602 case Sema::TDK_Invalid: 603 case Sema::TDK_InstantiationDepth: 604 case Sema::TDK_Incomplete: 605 case Sema::TDK_TooManyArguments: 606 case Sema::TDK_TooFewArguments: 607 case Sema::TDK_InvalidExplicitArguments: 608 break; 609 610 case Sema::TDK_Inconsistent: 611 case Sema::TDK_Underqualified: 612 // FIXME: Destroy the data? 613 Data = 0; 614 break; 615 616 case Sema::TDK_SubstitutionFailure: 617 // FIXME: Destroy the template argument list? 618 Data = 0; 619 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 620 Diag->~PartialDiagnosticAt(); 621 HasDiagnostic = false; 622 } 623 break; 624 625 // Unhandled 626 case Sema::TDK_NonDeducedMismatch: 627 case Sema::TDK_FailedOverloadResolution: 628 break; 629 } 630 } 631 632 PartialDiagnosticAt * 633 OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() { 634 if (HasDiagnostic) 635 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 636 return 0; 637 } 638 639 TemplateParameter 640 OverloadCandidate::DeductionFailureInfo::getTemplateParameter() { 641 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 642 case Sema::TDK_Success: 643 case Sema::TDK_Invalid: 644 case Sema::TDK_InstantiationDepth: 645 case Sema::TDK_TooManyArguments: 646 case Sema::TDK_TooFewArguments: 647 case Sema::TDK_SubstitutionFailure: 648 return TemplateParameter(); 649 650 case Sema::TDK_Incomplete: 651 case Sema::TDK_InvalidExplicitArguments: 652 return TemplateParameter::getFromOpaqueValue(Data); 653 654 case Sema::TDK_Inconsistent: 655 case Sema::TDK_Underqualified: 656 return static_cast<DFIParamWithArguments*>(Data)->Param; 657 658 // Unhandled 659 case Sema::TDK_NonDeducedMismatch: 660 case Sema::TDK_FailedOverloadResolution: 661 break; 662 } 663 664 return TemplateParameter(); 665 } 666 667 TemplateArgumentList * 668 OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() { 669 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 670 case Sema::TDK_Success: 671 case Sema::TDK_Invalid: 672 case Sema::TDK_InstantiationDepth: 673 case Sema::TDK_TooManyArguments: 674 case Sema::TDK_TooFewArguments: 675 case Sema::TDK_Incomplete: 676 case Sema::TDK_InvalidExplicitArguments: 677 case Sema::TDK_Inconsistent: 678 case Sema::TDK_Underqualified: 679 return 0; 680 681 case Sema::TDK_SubstitutionFailure: 682 return static_cast<TemplateArgumentList*>(Data); 683 684 // Unhandled 685 case Sema::TDK_NonDeducedMismatch: 686 case Sema::TDK_FailedOverloadResolution: 687 break; 688 } 689 690 return 0; 691 } 692 693 const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() { 694 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 695 case Sema::TDK_Success: 696 case Sema::TDK_Invalid: 697 case Sema::TDK_InstantiationDepth: 698 case Sema::TDK_Incomplete: 699 case Sema::TDK_TooManyArguments: 700 case Sema::TDK_TooFewArguments: 701 case Sema::TDK_InvalidExplicitArguments: 702 case Sema::TDK_SubstitutionFailure: 703 return 0; 704 705 case Sema::TDK_Inconsistent: 706 case Sema::TDK_Underqualified: 707 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg; 708 709 // Unhandled 710 case Sema::TDK_NonDeducedMismatch: 711 case Sema::TDK_FailedOverloadResolution: 712 break; 713 } 714 715 return 0; 716 } 717 718 const TemplateArgument * 719 OverloadCandidate::DeductionFailureInfo::getSecondArg() { 720 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 721 case Sema::TDK_Success: 722 case Sema::TDK_Invalid: 723 case Sema::TDK_InstantiationDepth: 724 case Sema::TDK_Incomplete: 725 case Sema::TDK_TooManyArguments: 726 case Sema::TDK_TooFewArguments: 727 case Sema::TDK_InvalidExplicitArguments: 728 case Sema::TDK_SubstitutionFailure: 729 return 0; 730 731 case Sema::TDK_Inconsistent: 732 case Sema::TDK_Underqualified: 733 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg; 734 735 // Unhandled 736 case Sema::TDK_NonDeducedMismatch: 737 case Sema::TDK_FailedOverloadResolution: 738 break; 739 } 740 741 return 0; 742 } 743 744 void OverloadCandidateSet::destroyCandidates() { 745 for (iterator i = begin(), e = end(); i != e; ++i) { 746 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 747 i->Conversions[ii].~ImplicitConversionSequence(); 748 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 749 i->DeductionFailure.Destroy(); 750 } 751 } 752 753 void OverloadCandidateSet::clear() { 754 destroyCandidates(); 755 NumInlineSequences = 0; 756 Candidates.clear(); 757 Functions.clear(); 758 } 759 760 namespace { 761 class UnbridgedCastsSet { 762 struct Entry { 763 Expr **Addr; 764 Expr *Saved; 765 }; 766 SmallVector<Entry, 2> Entries; 767 768 public: 769 void save(Sema &S, Expr *&E) { 770 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 771 Entry entry = { &E, E }; 772 Entries.push_back(entry); 773 E = S.stripARCUnbridgedCast(E); 774 } 775 776 void restore() { 777 for (SmallVectorImpl<Entry>::iterator 778 i = Entries.begin(), e = Entries.end(); i != e; ++i) 779 *i->Addr = i->Saved; 780 } 781 }; 782 } 783 784 /// checkPlaceholderForOverload - Do any interesting placeholder-like 785 /// preprocessing on the given expression. 786 /// 787 /// \param unbridgedCasts a collection to which to add unbridged casts; 788 /// without this, they will be immediately diagnosed as errors 789 /// 790 /// Return true on unrecoverable error. 791 static bool checkPlaceholderForOverload(Sema &S, Expr *&E, 792 UnbridgedCastsSet *unbridgedCasts = 0) { 793 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 794 // We can't handle overloaded expressions here because overload 795 // resolution might reasonably tweak them. 796 if (placeholder->getKind() == BuiltinType::Overload) return false; 797 798 // If the context potentially accepts unbridged ARC casts, strip 799 // the unbridged cast and add it to the collection for later restoration. 800 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 801 unbridgedCasts) { 802 unbridgedCasts->save(S, E); 803 return false; 804 } 805 806 // Go ahead and check everything else. 807 ExprResult result = S.CheckPlaceholderExpr(E); 808 if (result.isInvalid()) 809 return true; 810 811 E = result.take(); 812 return false; 813 } 814 815 // Nothing to do. 816 return false; 817 } 818 819 /// checkArgPlaceholdersForOverload - Check a set of call operands for 820 /// placeholders. 821 static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args, 822 unsigned numArgs, 823 UnbridgedCastsSet &unbridged) { 824 for (unsigned i = 0; i != numArgs; ++i) 825 if (checkPlaceholderForOverload(S, args[i], &unbridged)) 826 return true; 827 828 return false; 829 } 830 831 // IsOverload - Determine whether the given New declaration is an 832 // overload of the declarations in Old. This routine returns false if 833 // New and Old cannot be overloaded, e.g., if New has the same 834 // signature as some function in Old (C++ 1.3.10) or if the Old 835 // declarations aren't functions (or function templates) at all. When 836 // it does return false, MatchedDecl will point to the decl that New 837 // cannot be overloaded with. This decl may be a UsingShadowDecl on 838 // top of the underlying declaration. 839 // 840 // Example: Given the following input: 841 // 842 // void f(int, float); // #1 843 // void f(int, int); // #2 844 // int f(int, int); // #3 845 // 846 // When we process #1, there is no previous declaration of "f", 847 // so IsOverload will not be used. 848 // 849 // When we process #2, Old contains only the FunctionDecl for #1. By 850 // comparing the parameter types, we see that #1 and #2 are overloaded 851 // (since they have different signatures), so this routine returns 852 // false; MatchedDecl is unchanged. 853 // 854 // When we process #3, Old is an overload set containing #1 and #2. We 855 // compare the signatures of #3 to #1 (they're overloaded, so we do 856 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 857 // identical (return types of functions are not part of the 858 // signature), IsOverload returns false and MatchedDecl will be set to 859 // point to the FunctionDecl for #2. 860 // 861 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 862 // into a class by a using declaration. The rules for whether to hide 863 // shadow declarations ignore some properties which otherwise figure 864 // into a function template's signature. 865 Sema::OverloadKind 866 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 867 NamedDecl *&Match, bool NewIsUsingDecl) { 868 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 869 I != E; ++I) { 870 NamedDecl *OldD = *I; 871 872 bool OldIsUsingDecl = false; 873 if (isa<UsingShadowDecl>(OldD)) { 874 OldIsUsingDecl = true; 875 876 // We can always introduce two using declarations into the same 877 // context, even if they have identical signatures. 878 if (NewIsUsingDecl) continue; 879 880 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 881 } 882 883 // If either declaration was introduced by a using declaration, 884 // we'll need to use slightly different rules for matching. 885 // Essentially, these rules are the normal rules, except that 886 // function templates hide function templates with different 887 // return types or template parameter lists. 888 bool UseMemberUsingDeclRules = 889 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord(); 890 891 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) { 892 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) { 893 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 894 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 895 continue; 896 } 897 898 Match = *I; 899 return Ovl_Match; 900 } 901 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) { 902 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 903 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 904 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 905 continue; 906 } 907 908 Match = *I; 909 return Ovl_Match; 910 } 911 } else if (isa<UsingDecl>(OldD)) { 912 // We can overload with these, which can show up when doing 913 // redeclaration checks for UsingDecls. 914 assert(Old.getLookupKind() == LookupUsingDeclName); 915 } else if (isa<TagDecl>(OldD)) { 916 // We can always overload with tags by hiding them. 917 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 918 // Optimistically assume that an unresolved using decl will 919 // overload; if it doesn't, we'll have to diagnose during 920 // template instantiation. 921 } else { 922 // (C++ 13p1): 923 // Only function declarations can be overloaded; object and type 924 // declarations cannot be overloaded. 925 Match = *I; 926 return Ovl_NonFunction; 927 } 928 } 929 930 return Ovl_Overload; 931 } 932 933 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 934 bool UseUsingDeclRules) { 935 // If both of the functions are extern "C", then they are not 936 // overloads. 937 if (Old->isExternC() && New->isExternC()) 938 return false; 939 940 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 941 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 942 943 // C++ [temp.fct]p2: 944 // A function template can be overloaded with other function templates 945 // and with normal (non-template) functions. 946 if ((OldTemplate == 0) != (NewTemplate == 0)) 947 return true; 948 949 // Is the function New an overload of the function Old? 950 QualType OldQType = Context.getCanonicalType(Old->getType()); 951 QualType NewQType = Context.getCanonicalType(New->getType()); 952 953 // Compare the signatures (C++ 1.3.10) of the two functions to 954 // determine whether they are overloads. If we find any mismatch 955 // in the signature, they are overloads. 956 957 // If either of these functions is a K&R-style function (no 958 // prototype), then we consider them to have matching signatures. 959 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 960 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 961 return false; 962 963 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType); 964 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType); 965 966 // The signature of a function includes the types of its 967 // parameters (C++ 1.3.10), which includes the presence or absence 968 // of the ellipsis; see C++ DR 357). 969 if (OldQType != NewQType && 970 (OldType->getNumArgs() != NewType->getNumArgs() || 971 OldType->isVariadic() != NewType->isVariadic() || 972 !FunctionArgTypesAreEqual(OldType, NewType))) 973 return true; 974 975 // C++ [temp.over.link]p4: 976 // The signature of a function template consists of its function 977 // signature, its return type and its template parameter list. The names 978 // of the template parameters are significant only for establishing the 979 // relationship between the template parameters and the rest of the 980 // signature. 981 // 982 // We check the return type and template parameter lists for function 983 // templates first; the remaining checks follow. 984 // 985 // However, we don't consider either of these when deciding whether 986 // a member introduced by a shadow declaration is hidden. 987 if (!UseUsingDeclRules && NewTemplate && 988 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 989 OldTemplate->getTemplateParameters(), 990 false, TPL_TemplateMatch) || 991 OldType->getResultType() != NewType->getResultType())) 992 return true; 993 994 // If the function is a class member, its signature includes the 995 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 996 // 997 // As part of this, also check whether one of the member functions 998 // is static, in which case they are not overloads (C++ 999 // 13.1p2). While not part of the definition of the signature, 1000 // this check is important to determine whether these functions 1001 // can be overloaded. 1002 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 1003 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 1004 if (OldMethod && NewMethod && 1005 !OldMethod->isStatic() && !NewMethod->isStatic() && 1006 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() || 1007 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) { 1008 if (!UseUsingDeclRules && 1009 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() && 1010 (OldMethod->getRefQualifier() == RQ_None || 1011 NewMethod->getRefQualifier() == RQ_None)) { 1012 // C++0x [over.load]p2: 1013 // - Member function declarations with the same name and the same 1014 // parameter-type-list as well as member function template 1015 // declarations with the same name, the same parameter-type-list, and 1016 // the same template parameter lists cannot be overloaded if any of 1017 // them, but not all, have a ref-qualifier (8.3.5). 1018 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1019 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1020 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1021 } 1022 1023 return true; 1024 } 1025 1026 // The signatures match; this is not an overload. 1027 return false; 1028 } 1029 1030 /// \brief Checks availability of the function depending on the current 1031 /// function context. Inside an unavailable function, unavailability is ignored. 1032 /// 1033 /// \returns true if \arg FD is unavailable and current context is inside 1034 /// an available function, false otherwise. 1035 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1036 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1037 } 1038 1039 /// \brief Tries a user-defined conversion from From to ToType. 1040 /// 1041 /// Produces an implicit conversion sequence for when a standard conversion 1042 /// is not an option. See TryImplicitConversion for more information. 1043 static ImplicitConversionSequence 1044 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1045 bool SuppressUserConversions, 1046 bool AllowExplicit, 1047 bool InOverloadResolution, 1048 bool CStyle, 1049 bool AllowObjCWritebackConversion) { 1050 ImplicitConversionSequence ICS; 1051 1052 if (SuppressUserConversions) { 1053 // We're not in the case above, so there is no conversion that 1054 // we can perform. 1055 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1056 return ICS; 1057 } 1058 1059 // Attempt user-defined conversion. 1060 OverloadCandidateSet Conversions(From->getExprLoc()); 1061 OverloadingResult UserDefResult 1062 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 1063 AllowExplicit); 1064 1065 if (UserDefResult == OR_Success) { 1066 ICS.setUserDefined(); 1067 // C++ [over.ics.user]p4: 1068 // A conversion of an expression of class type to the same class 1069 // type is given Exact Match rank, and a conversion of an 1070 // expression of class type to a base class of that type is 1071 // given Conversion rank, in spite of the fact that a copy 1072 // constructor (i.e., a user-defined conversion function) is 1073 // called for those cases. 1074 if (CXXConstructorDecl *Constructor 1075 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1076 QualType FromCanon 1077 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1078 QualType ToCanon 1079 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1080 if (Constructor->isCopyConstructor() && 1081 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1082 // Turn this into a "standard" conversion sequence, so that it 1083 // gets ranked with standard conversion sequences. 1084 ICS.setStandard(); 1085 ICS.Standard.setAsIdentityConversion(); 1086 ICS.Standard.setFromType(From->getType()); 1087 ICS.Standard.setAllToTypes(ToType); 1088 ICS.Standard.CopyConstructor = Constructor; 1089 if (ToCanon != FromCanon) 1090 ICS.Standard.Second = ICK_Derived_To_Base; 1091 } 1092 } 1093 1094 // C++ [over.best.ics]p4: 1095 // However, when considering the argument of a user-defined 1096 // conversion function that is a candidate by 13.3.1.3 when 1097 // invoked for the copying of the temporary in the second step 1098 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 1099 // 13.3.1.6 in all cases, only standard conversion sequences and 1100 // ellipsis conversion sequences are allowed. 1101 if (SuppressUserConversions && ICS.isUserDefined()) { 1102 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 1103 } 1104 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 1105 ICS.setAmbiguous(); 1106 ICS.Ambiguous.setFromType(From->getType()); 1107 ICS.Ambiguous.setToType(ToType); 1108 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1109 Cand != Conversions.end(); ++Cand) 1110 if (Cand->Viable) 1111 ICS.Ambiguous.addConversion(Cand->Function); 1112 } else { 1113 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1114 } 1115 1116 return ICS; 1117 } 1118 1119 /// TryImplicitConversion - Attempt to perform an implicit conversion 1120 /// from the given expression (Expr) to the given type (ToType). This 1121 /// function returns an implicit conversion sequence that can be used 1122 /// to perform the initialization. Given 1123 /// 1124 /// void f(float f); 1125 /// void g(int i) { f(i); } 1126 /// 1127 /// this routine would produce an implicit conversion sequence to 1128 /// describe the initialization of f from i, which will be a standard 1129 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1130 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1131 // 1132 /// Note that this routine only determines how the conversion can be 1133 /// performed; it does not actually perform the conversion. As such, 1134 /// it will not produce any diagnostics if no conversion is available, 1135 /// but will instead return an implicit conversion sequence of kind 1136 /// "BadConversion". 1137 /// 1138 /// If @p SuppressUserConversions, then user-defined conversions are 1139 /// not permitted. 1140 /// If @p AllowExplicit, then explicit user-defined conversions are 1141 /// permitted. 1142 /// 1143 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1144 /// writeback conversion, which allows __autoreleasing id* parameters to 1145 /// be initialized with __strong id* or __weak id* arguments. 1146 static ImplicitConversionSequence 1147 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1148 bool SuppressUserConversions, 1149 bool AllowExplicit, 1150 bool InOverloadResolution, 1151 bool CStyle, 1152 bool AllowObjCWritebackConversion) { 1153 ImplicitConversionSequence ICS; 1154 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1155 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1156 ICS.setStandard(); 1157 return ICS; 1158 } 1159 1160 if (!S.getLangOpts().CPlusPlus) { 1161 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1162 return ICS; 1163 } 1164 1165 // C++ [over.ics.user]p4: 1166 // A conversion of an expression of class type to the same class 1167 // type is given Exact Match rank, and a conversion of an 1168 // expression of class type to a base class of that type is 1169 // given Conversion rank, in spite of the fact that a copy/move 1170 // constructor (i.e., a user-defined conversion function) is 1171 // called for those cases. 1172 QualType FromType = From->getType(); 1173 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1174 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1175 S.IsDerivedFrom(FromType, ToType))) { 1176 ICS.setStandard(); 1177 ICS.Standard.setAsIdentityConversion(); 1178 ICS.Standard.setFromType(FromType); 1179 ICS.Standard.setAllToTypes(ToType); 1180 1181 // We don't actually check at this point whether there is a valid 1182 // copy/move constructor, since overloading just assumes that it 1183 // exists. When we actually perform initialization, we'll find the 1184 // appropriate constructor to copy the returned object, if needed. 1185 ICS.Standard.CopyConstructor = 0; 1186 1187 // Determine whether this is considered a derived-to-base conversion. 1188 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1189 ICS.Standard.Second = ICK_Derived_To_Base; 1190 1191 return ICS; 1192 } 1193 1194 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1195 AllowExplicit, InOverloadResolution, CStyle, 1196 AllowObjCWritebackConversion); 1197 } 1198 1199 ImplicitConversionSequence 1200 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1201 bool SuppressUserConversions, 1202 bool AllowExplicit, 1203 bool InOverloadResolution, 1204 bool CStyle, 1205 bool AllowObjCWritebackConversion) { 1206 return clang::TryImplicitConversion(*this, From, ToType, 1207 SuppressUserConversions, AllowExplicit, 1208 InOverloadResolution, CStyle, 1209 AllowObjCWritebackConversion); 1210 } 1211 1212 /// PerformImplicitConversion - Perform an implicit conversion of the 1213 /// expression From to the type ToType. Returns the 1214 /// converted expression. Flavor is the kind of conversion we're 1215 /// performing, used in the error message. If @p AllowExplicit, 1216 /// explicit user-defined conversions are permitted. 1217 ExprResult 1218 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1219 AssignmentAction Action, bool AllowExplicit) { 1220 ImplicitConversionSequence ICS; 1221 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1222 } 1223 1224 ExprResult 1225 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1226 AssignmentAction Action, bool AllowExplicit, 1227 ImplicitConversionSequence& ICS) { 1228 if (checkPlaceholderForOverload(*this, From)) 1229 return ExprError(); 1230 1231 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1232 bool AllowObjCWritebackConversion 1233 = getLangOpts().ObjCAutoRefCount && 1234 (Action == AA_Passing || Action == AA_Sending); 1235 1236 ICS = clang::TryImplicitConversion(*this, From, ToType, 1237 /*SuppressUserConversions=*/false, 1238 AllowExplicit, 1239 /*InOverloadResolution=*/false, 1240 /*CStyle=*/false, 1241 AllowObjCWritebackConversion); 1242 return PerformImplicitConversion(From, ToType, ICS, Action); 1243 } 1244 1245 /// \brief Determine whether the conversion from FromType to ToType is a valid 1246 /// conversion that strips "noreturn" off the nested function type. 1247 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1248 QualType &ResultTy) { 1249 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1250 return false; 1251 1252 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1253 // where F adds one of the following at most once: 1254 // - a pointer 1255 // - a member pointer 1256 // - a block pointer 1257 CanQualType CanTo = Context.getCanonicalType(ToType); 1258 CanQualType CanFrom = Context.getCanonicalType(FromType); 1259 Type::TypeClass TyClass = CanTo->getTypeClass(); 1260 if (TyClass != CanFrom->getTypeClass()) return false; 1261 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1262 if (TyClass == Type::Pointer) { 1263 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1264 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1265 } else if (TyClass == Type::BlockPointer) { 1266 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1267 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1268 } else if (TyClass == Type::MemberPointer) { 1269 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1270 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1271 } else { 1272 return false; 1273 } 1274 1275 TyClass = CanTo->getTypeClass(); 1276 if (TyClass != CanFrom->getTypeClass()) return false; 1277 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1278 return false; 1279 } 1280 1281 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1282 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1283 if (!EInfo.getNoReturn()) return false; 1284 1285 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1286 assert(QualType(FromFn, 0).isCanonical()); 1287 if (QualType(FromFn, 0) != CanTo) return false; 1288 1289 ResultTy = ToType; 1290 return true; 1291 } 1292 1293 /// \brief Determine whether the conversion from FromType to ToType is a valid 1294 /// vector conversion. 1295 /// 1296 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1297 /// conversion. 1298 static bool IsVectorConversion(ASTContext &Context, QualType FromType, 1299 QualType ToType, ImplicitConversionKind &ICK) { 1300 // We need at least one of these types to be a vector type to have a vector 1301 // conversion. 1302 if (!ToType->isVectorType() && !FromType->isVectorType()) 1303 return false; 1304 1305 // Identical types require no conversions. 1306 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1307 return false; 1308 1309 // There are no conversions between extended vector types, only identity. 1310 if (ToType->isExtVectorType()) { 1311 // There are no conversions between extended vector types other than the 1312 // identity conversion. 1313 if (FromType->isExtVectorType()) 1314 return false; 1315 1316 // Vector splat from any arithmetic type to a vector. 1317 if (FromType->isArithmeticType()) { 1318 ICK = ICK_Vector_Splat; 1319 return true; 1320 } 1321 } 1322 1323 // We can perform the conversion between vector types in the following cases: 1324 // 1)vector types are equivalent AltiVec and GCC vector types 1325 // 2)lax vector conversions are permitted and the vector types are of the 1326 // same size 1327 if (ToType->isVectorType() && FromType->isVectorType()) { 1328 if (Context.areCompatibleVectorTypes(FromType, ToType) || 1329 (Context.getLangOpts().LaxVectorConversions && 1330 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) { 1331 ICK = ICK_Vector_Conversion; 1332 return true; 1333 } 1334 } 1335 1336 return false; 1337 } 1338 1339 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1340 bool InOverloadResolution, 1341 StandardConversionSequence &SCS, 1342 bool CStyle); 1343 1344 /// IsStandardConversion - Determines whether there is a standard 1345 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1346 /// expression From to the type ToType. Standard conversion sequences 1347 /// only consider non-class types; for conversions that involve class 1348 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1349 /// contain the standard conversion sequence required to perform this 1350 /// conversion and this routine will return true. Otherwise, this 1351 /// routine will return false and the value of SCS is unspecified. 1352 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1353 bool InOverloadResolution, 1354 StandardConversionSequence &SCS, 1355 bool CStyle, 1356 bool AllowObjCWritebackConversion) { 1357 QualType FromType = From->getType(); 1358 1359 // Standard conversions (C++ [conv]) 1360 SCS.setAsIdentityConversion(); 1361 SCS.DeprecatedStringLiteralToCharPtr = false; 1362 SCS.IncompatibleObjC = false; 1363 SCS.setFromType(FromType); 1364 SCS.CopyConstructor = 0; 1365 1366 // There are no standard conversions for class types in C++, so 1367 // abort early. When overloading in C, however, we do permit 1368 if (FromType->isRecordType() || ToType->isRecordType()) { 1369 if (S.getLangOpts().CPlusPlus) 1370 return false; 1371 1372 // When we're overloading in C, we allow, as standard conversions, 1373 } 1374 1375 // The first conversion can be an lvalue-to-rvalue conversion, 1376 // array-to-pointer conversion, or function-to-pointer conversion 1377 // (C++ 4p1). 1378 1379 if (FromType == S.Context.OverloadTy) { 1380 DeclAccessPair AccessPair; 1381 if (FunctionDecl *Fn 1382 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1383 AccessPair)) { 1384 // We were able to resolve the address of the overloaded function, 1385 // so we can convert to the type of that function. 1386 FromType = Fn->getType(); 1387 1388 // we can sometimes resolve &foo<int> regardless of ToType, so check 1389 // if the type matches (identity) or we are converting to bool 1390 if (!S.Context.hasSameUnqualifiedType( 1391 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1392 QualType resultTy; 1393 // if the function type matches except for [[noreturn]], it's ok 1394 if (!S.IsNoReturnConversion(FromType, 1395 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1396 // otherwise, only a boolean conversion is standard 1397 if (!ToType->isBooleanType()) 1398 return false; 1399 } 1400 1401 // Check if the "from" expression is taking the address of an overloaded 1402 // function and recompute the FromType accordingly. Take advantage of the 1403 // fact that non-static member functions *must* have such an address-of 1404 // expression. 1405 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1406 if (Method && !Method->isStatic()) { 1407 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1408 "Non-unary operator on non-static member address"); 1409 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1410 == UO_AddrOf && 1411 "Non-address-of operator on non-static member address"); 1412 const Type *ClassType 1413 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1414 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1415 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1416 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1417 UO_AddrOf && 1418 "Non-address-of operator for overloaded function expression"); 1419 FromType = S.Context.getPointerType(FromType); 1420 } 1421 1422 // Check that we've computed the proper type after overload resolution. 1423 assert(S.Context.hasSameType( 1424 FromType, 1425 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1426 } else { 1427 return false; 1428 } 1429 } 1430 // Lvalue-to-rvalue conversion (C++11 4.1): 1431 // A glvalue (3.10) of a non-function, non-array type T can 1432 // be converted to a prvalue. 1433 bool argIsLValue = From->isGLValue(); 1434 if (argIsLValue && 1435 !FromType->isFunctionType() && !FromType->isArrayType() && 1436 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1437 SCS.First = ICK_Lvalue_To_Rvalue; 1438 1439 // C11 6.3.2.1p2: 1440 // ... if the lvalue has atomic type, the value has the non-atomic version 1441 // of the type of the lvalue ... 1442 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1443 FromType = Atomic->getValueType(); 1444 1445 // If T is a non-class type, the type of the rvalue is the 1446 // cv-unqualified version of T. Otherwise, the type of the rvalue 1447 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1448 // just strip the qualifiers because they don't matter. 1449 FromType = FromType.getUnqualifiedType(); 1450 } else if (FromType->isArrayType()) { 1451 // Array-to-pointer conversion (C++ 4.2) 1452 SCS.First = ICK_Array_To_Pointer; 1453 1454 // An lvalue or rvalue of type "array of N T" or "array of unknown 1455 // bound of T" can be converted to an rvalue of type "pointer to 1456 // T" (C++ 4.2p1). 1457 FromType = S.Context.getArrayDecayedType(FromType); 1458 1459 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1460 // This conversion is deprecated. (C++ D.4). 1461 SCS.DeprecatedStringLiteralToCharPtr = true; 1462 1463 // For the purpose of ranking in overload resolution 1464 // (13.3.3.1.1), this conversion is considered an 1465 // array-to-pointer conversion followed by a qualification 1466 // conversion (4.4). (C++ 4.2p2) 1467 SCS.Second = ICK_Identity; 1468 SCS.Third = ICK_Qualification; 1469 SCS.QualificationIncludesObjCLifetime = false; 1470 SCS.setAllToTypes(FromType); 1471 return true; 1472 } 1473 } else if (FromType->isFunctionType() && argIsLValue) { 1474 // Function-to-pointer conversion (C++ 4.3). 1475 SCS.First = ICK_Function_To_Pointer; 1476 1477 // An lvalue of function type T can be converted to an rvalue of 1478 // type "pointer to T." The result is a pointer to the 1479 // function. (C++ 4.3p1). 1480 FromType = S.Context.getPointerType(FromType); 1481 } else { 1482 // We don't require any conversions for the first step. 1483 SCS.First = ICK_Identity; 1484 } 1485 SCS.setToType(0, FromType); 1486 1487 // The second conversion can be an integral promotion, floating 1488 // point promotion, integral conversion, floating point conversion, 1489 // floating-integral conversion, pointer conversion, 1490 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1491 // For overloading in C, this can also be a "compatible-type" 1492 // conversion. 1493 bool IncompatibleObjC = false; 1494 ImplicitConversionKind SecondICK = ICK_Identity; 1495 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1496 // The unqualified versions of the types are the same: there's no 1497 // conversion to do. 1498 SCS.Second = ICK_Identity; 1499 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1500 // Integral promotion (C++ 4.5). 1501 SCS.Second = ICK_Integral_Promotion; 1502 FromType = ToType.getUnqualifiedType(); 1503 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1504 // Floating point promotion (C++ 4.6). 1505 SCS.Second = ICK_Floating_Promotion; 1506 FromType = ToType.getUnqualifiedType(); 1507 } else if (S.IsComplexPromotion(FromType, ToType)) { 1508 // Complex promotion (Clang extension) 1509 SCS.Second = ICK_Complex_Promotion; 1510 FromType = ToType.getUnqualifiedType(); 1511 } else if (ToType->isBooleanType() && 1512 (FromType->isArithmeticType() || 1513 FromType->isAnyPointerType() || 1514 FromType->isBlockPointerType() || 1515 FromType->isMemberPointerType() || 1516 FromType->isNullPtrType())) { 1517 // Boolean conversions (C++ 4.12). 1518 SCS.Second = ICK_Boolean_Conversion; 1519 FromType = S.Context.BoolTy; 1520 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1521 ToType->isIntegralType(S.Context)) { 1522 // Integral conversions (C++ 4.7). 1523 SCS.Second = ICK_Integral_Conversion; 1524 FromType = ToType.getUnqualifiedType(); 1525 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) { 1526 // Complex conversions (C99 6.3.1.6) 1527 SCS.Second = ICK_Complex_Conversion; 1528 FromType = ToType.getUnqualifiedType(); 1529 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1530 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1531 // Complex-real conversions (C99 6.3.1.7) 1532 SCS.Second = ICK_Complex_Real; 1533 FromType = ToType.getUnqualifiedType(); 1534 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1535 // Floating point conversions (C++ 4.8). 1536 SCS.Second = ICK_Floating_Conversion; 1537 FromType = ToType.getUnqualifiedType(); 1538 } else if ((FromType->isRealFloatingType() && 1539 ToType->isIntegralType(S.Context)) || 1540 (FromType->isIntegralOrUnscopedEnumerationType() && 1541 ToType->isRealFloatingType())) { 1542 // Floating-integral conversions (C++ 4.9). 1543 SCS.Second = ICK_Floating_Integral; 1544 FromType = ToType.getUnqualifiedType(); 1545 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1546 SCS.Second = ICK_Block_Pointer_Conversion; 1547 } else if (AllowObjCWritebackConversion && 1548 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1549 SCS.Second = ICK_Writeback_Conversion; 1550 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1551 FromType, IncompatibleObjC)) { 1552 // Pointer conversions (C++ 4.10). 1553 SCS.Second = ICK_Pointer_Conversion; 1554 SCS.IncompatibleObjC = IncompatibleObjC; 1555 FromType = FromType.getUnqualifiedType(); 1556 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1557 InOverloadResolution, FromType)) { 1558 // Pointer to member conversions (4.11). 1559 SCS.Second = ICK_Pointer_Member; 1560 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) { 1561 SCS.Second = SecondICK; 1562 FromType = ToType.getUnqualifiedType(); 1563 } else if (!S.getLangOpts().CPlusPlus && 1564 S.Context.typesAreCompatible(ToType, FromType)) { 1565 // Compatible conversions (Clang extension for C function overloading) 1566 SCS.Second = ICK_Compatible_Conversion; 1567 FromType = ToType.getUnqualifiedType(); 1568 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1569 // Treat a conversion that strips "noreturn" as an identity conversion. 1570 SCS.Second = ICK_NoReturn_Adjustment; 1571 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1572 InOverloadResolution, 1573 SCS, CStyle)) { 1574 SCS.Second = ICK_TransparentUnionConversion; 1575 FromType = ToType; 1576 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1577 CStyle)) { 1578 // tryAtomicConversion has updated the standard conversion sequence 1579 // appropriately. 1580 return true; 1581 } else { 1582 // No second conversion required. 1583 SCS.Second = ICK_Identity; 1584 } 1585 SCS.setToType(1, FromType); 1586 1587 QualType CanonFrom; 1588 QualType CanonTo; 1589 // The third conversion can be a qualification conversion (C++ 4p1). 1590 bool ObjCLifetimeConversion; 1591 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1592 ObjCLifetimeConversion)) { 1593 SCS.Third = ICK_Qualification; 1594 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1595 FromType = ToType; 1596 CanonFrom = S.Context.getCanonicalType(FromType); 1597 CanonTo = S.Context.getCanonicalType(ToType); 1598 } else { 1599 // No conversion required 1600 SCS.Third = ICK_Identity; 1601 1602 // C++ [over.best.ics]p6: 1603 // [...] Any difference in top-level cv-qualification is 1604 // subsumed by the initialization itself and does not constitute 1605 // a conversion. [...] 1606 CanonFrom = S.Context.getCanonicalType(FromType); 1607 CanonTo = S.Context.getCanonicalType(ToType); 1608 if (CanonFrom.getLocalUnqualifiedType() 1609 == CanonTo.getLocalUnqualifiedType() && 1610 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers() 1611 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr() 1612 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) { 1613 FromType = ToType; 1614 CanonFrom = CanonTo; 1615 } 1616 } 1617 SCS.setToType(2, FromType); 1618 1619 // If we have not converted the argument type to the parameter type, 1620 // this is a bad conversion sequence. 1621 if (CanonFrom != CanonTo) 1622 return false; 1623 1624 return true; 1625 } 1626 1627 static bool 1628 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1629 QualType &ToType, 1630 bool InOverloadResolution, 1631 StandardConversionSequence &SCS, 1632 bool CStyle) { 1633 1634 const RecordType *UT = ToType->getAsUnionType(); 1635 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1636 return false; 1637 // The field to initialize within the transparent union. 1638 RecordDecl *UD = UT->getDecl(); 1639 // It's compatible if the expression matches any of the fields. 1640 for (RecordDecl::field_iterator it = UD->field_begin(), 1641 itend = UD->field_end(); 1642 it != itend; ++it) { 1643 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1644 CStyle, /*ObjCWritebackConversion=*/false)) { 1645 ToType = it->getType(); 1646 return true; 1647 } 1648 } 1649 return false; 1650 } 1651 1652 /// IsIntegralPromotion - Determines whether the conversion from the 1653 /// expression From (whose potentially-adjusted type is FromType) to 1654 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1655 /// sets PromotedType to the promoted type. 1656 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1657 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1658 // All integers are built-in. 1659 if (!To) { 1660 return false; 1661 } 1662 1663 // An rvalue of type char, signed char, unsigned char, short int, or 1664 // unsigned short int can be converted to an rvalue of type int if 1665 // int can represent all the values of the source type; otherwise, 1666 // the source rvalue can be converted to an rvalue of type unsigned 1667 // int (C++ 4.5p1). 1668 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1669 !FromType->isEnumeralType()) { 1670 if (// We can promote any signed, promotable integer type to an int 1671 (FromType->isSignedIntegerType() || 1672 // We can promote any unsigned integer type whose size is 1673 // less than int to an int. 1674 (!FromType->isSignedIntegerType() && 1675 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1676 return To->getKind() == BuiltinType::Int; 1677 } 1678 1679 return To->getKind() == BuiltinType::UInt; 1680 } 1681 1682 // C++11 [conv.prom]p3: 1683 // A prvalue of an unscoped enumeration type whose underlying type is not 1684 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1685 // following types that can represent all the values of the enumeration 1686 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1687 // unsigned int, long int, unsigned long int, long long int, or unsigned 1688 // long long int. If none of the types in that list can represent all the 1689 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1690 // type can be converted to an rvalue a prvalue of the extended integer type 1691 // with lowest integer conversion rank (4.13) greater than the rank of long 1692 // long in which all the values of the enumeration can be represented. If 1693 // there are two such extended types, the signed one is chosen. 1694 // C++11 [conv.prom]p4: 1695 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1696 // can be converted to a prvalue of its underlying type. Moreover, if 1697 // integral promotion can be applied to its underlying type, a prvalue of an 1698 // unscoped enumeration type whose underlying type is fixed can also be 1699 // converted to a prvalue of the promoted underlying type. 1700 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1701 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1702 // provided for a scoped enumeration. 1703 if (FromEnumType->getDecl()->isScoped()) 1704 return false; 1705 1706 // We can perform an integral promotion to the underlying type of the enum, 1707 // even if that's not the promoted type. 1708 if (FromEnumType->getDecl()->isFixed()) { 1709 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1710 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1711 IsIntegralPromotion(From, Underlying, ToType); 1712 } 1713 1714 // We have already pre-calculated the promotion type, so this is trivial. 1715 if (ToType->isIntegerType() && 1716 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1717 return Context.hasSameUnqualifiedType(ToType, 1718 FromEnumType->getDecl()->getPromotionType()); 1719 } 1720 1721 // C++0x [conv.prom]p2: 1722 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1723 // to an rvalue a prvalue of the first of the following types that can 1724 // represent all the values of its underlying type: int, unsigned int, 1725 // long int, unsigned long int, long long int, or unsigned long long int. 1726 // If none of the types in that list can represent all the values of its 1727 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1728 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1729 // type. 1730 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1731 ToType->isIntegerType()) { 1732 // Determine whether the type we're converting from is signed or 1733 // unsigned. 1734 bool FromIsSigned = FromType->isSignedIntegerType(); 1735 uint64_t FromSize = Context.getTypeSize(FromType); 1736 1737 // The types we'll try to promote to, in the appropriate 1738 // order. Try each of these types. 1739 QualType PromoteTypes[6] = { 1740 Context.IntTy, Context.UnsignedIntTy, 1741 Context.LongTy, Context.UnsignedLongTy , 1742 Context.LongLongTy, Context.UnsignedLongLongTy 1743 }; 1744 for (int Idx = 0; Idx < 6; ++Idx) { 1745 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1746 if (FromSize < ToSize || 1747 (FromSize == ToSize && 1748 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1749 // We found the type that we can promote to. If this is the 1750 // type we wanted, we have a promotion. Otherwise, no 1751 // promotion. 1752 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1753 } 1754 } 1755 } 1756 1757 // An rvalue for an integral bit-field (9.6) can be converted to an 1758 // rvalue of type int if int can represent all the values of the 1759 // bit-field; otherwise, it can be converted to unsigned int if 1760 // unsigned int can represent all the values of the bit-field. If 1761 // the bit-field is larger yet, no integral promotion applies to 1762 // it. If the bit-field has an enumerated type, it is treated as any 1763 // other value of that type for promotion purposes (C++ 4.5p3). 1764 // FIXME: We should delay checking of bit-fields until we actually perform the 1765 // conversion. 1766 using llvm::APSInt; 1767 if (From) 1768 if (FieldDecl *MemberDecl = From->getBitField()) { 1769 APSInt BitWidth; 1770 if (FromType->isIntegralType(Context) && 1771 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1772 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1773 ToSize = Context.getTypeSize(ToType); 1774 1775 // Are we promoting to an int from a bitfield that fits in an int? 1776 if (BitWidth < ToSize || 1777 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1778 return To->getKind() == BuiltinType::Int; 1779 } 1780 1781 // Are we promoting to an unsigned int from an unsigned bitfield 1782 // that fits into an unsigned int? 1783 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1784 return To->getKind() == BuiltinType::UInt; 1785 } 1786 1787 return false; 1788 } 1789 } 1790 1791 // An rvalue of type bool can be converted to an rvalue of type int, 1792 // with false becoming zero and true becoming one (C++ 4.5p4). 1793 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1794 return true; 1795 } 1796 1797 return false; 1798 } 1799 1800 /// IsFloatingPointPromotion - Determines whether the conversion from 1801 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1802 /// returns true and sets PromotedType to the promoted type. 1803 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1804 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1805 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1806 /// An rvalue of type float can be converted to an rvalue of type 1807 /// double. (C++ 4.6p1). 1808 if (FromBuiltin->getKind() == BuiltinType::Float && 1809 ToBuiltin->getKind() == BuiltinType::Double) 1810 return true; 1811 1812 // C99 6.3.1.5p1: 1813 // When a float is promoted to double or long double, or a 1814 // double is promoted to long double [...]. 1815 if (!getLangOpts().CPlusPlus && 1816 (FromBuiltin->getKind() == BuiltinType::Float || 1817 FromBuiltin->getKind() == BuiltinType::Double) && 1818 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1819 return true; 1820 1821 // Half can be promoted to float. 1822 if (FromBuiltin->getKind() == BuiltinType::Half && 1823 ToBuiltin->getKind() == BuiltinType::Float) 1824 return true; 1825 } 1826 1827 return false; 1828 } 1829 1830 /// \brief Determine if a conversion is a complex promotion. 1831 /// 1832 /// A complex promotion is defined as a complex -> complex conversion 1833 /// where the conversion between the underlying real types is a 1834 /// floating-point or integral promotion. 1835 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1836 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1837 if (!FromComplex) 1838 return false; 1839 1840 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1841 if (!ToComplex) 1842 return false; 1843 1844 return IsFloatingPointPromotion(FromComplex->getElementType(), 1845 ToComplex->getElementType()) || 1846 IsIntegralPromotion(0, FromComplex->getElementType(), 1847 ToComplex->getElementType()); 1848 } 1849 1850 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1851 /// the pointer type FromPtr to a pointer to type ToPointee, with the 1852 /// same type qualifiers as FromPtr has on its pointee type. ToType, 1853 /// if non-empty, will be a pointer to ToType that may or may not have 1854 /// the right set of qualifiers on its pointee. 1855 /// 1856 static QualType 1857 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1858 QualType ToPointee, QualType ToType, 1859 ASTContext &Context, 1860 bool StripObjCLifetime = false) { 1861 assert((FromPtr->getTypeClass() == Type::Pointer || 1862 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1863 "Invalid similarly-qualified pointer type"); 1864 1865 /// Conversions to 'id' subsume cv-qualifier conversions. 1866 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1867 return ToType.getUnqualifiedType(); 1868 1869 QualType CanonFromPointee 1870 = Context.getCanonicalType(FromPtr->getPointeeType()); 1871 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1872 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1873 1874 if (StripObjCLifetime) 1875 Quals.removeObjCLifetime(); 1876 1877 // Exact qualifier match -> return the pointer type we're converting to. 1878 if (CanonToPointee.getLocalQualifiers() == Quals) { 1879 // ToType is exactly what we need. Return it. 1880 if (!ToType.isNull()) 1881 return ToType.getUnqualifiedType(); 1882 1883 // Build a pointer to ToPointee. It has the right qualifiers 1884 // already. 1885 if (isa<ObjCObjectPointerType>(ToType)) 1886 return Context.getObjCObjectPointerType(ToPointee); 1887 return Context.getPointerType(ToPointee); 1888 } 1889 1890 // Just build a canonical type that has the right qualifiers. 1891 QualType QualifiedCanonToPointee 1892 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1893 1894 if (isa<ObjCObjectPointerType>(ToType)) 1895 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1896 return Context.getPointerType(QualifiedCanonToPointee); 1897 } 1898 1899 static bool isNullPointerConstantForConversion(Expr *Expr, 1900 bool InOverloadResolution, 1901 ASTContext &Context) { 1902 // Handle value-dependent integral null pointer constants correctly. 1903 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1904 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1905 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1906 return !InOverloadResolution; 1907 1908 return Expr->isNullPointerConstant(Context, 1909 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1910 : Expr::NPC_ValueDependentIsNull); 1911 } 1912 1913 /// IsPointerConversion - Determines whether the conversion of the 1914 /// expression From, which has the (possibly adjusted) type FromType, 1915 /// can be converted to the type ToType via a pointer conversion (C++ 1916 /// 4.10). If so, returns true and places the converted type (that 1917 /// might differ from ToType in its cv-qualifiers at some level) into 1918 /// ConvertedType. 1919 /// 1920 /// This routine also supports conversions to and from block pointers 1921 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 1922 /// pointers to interfaces. FIXME: Once we've determined the 1923 /// appropriate overloading rules for Objective-C, we may want to 1924 /// split the Objective-C checks into a different routine; however, 1925 /// GCC seems to consider all of these conversions to be pointer 1926 /// conversions, so for now they live here. IncompatibleObjC will be 1927 /// set if the conversion is an allowed Objective-C conversion that 1928 /// should result in a warning. 1929 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1930 bool InOverloadResolution, 1931 QualType& ConvertedType, 1932 bool &IncompatibleObjC) { 1933 IncompatibleObjC = false; 1934 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 1935 IncompatibleObjC)) 1936 return true; 1937 1938 // Conversion from a null pointer constant to any Objective-C pointer type. 1939 if (ToType->isObjCObjectPointerType() && 1940 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1941 ConvertedType = ToType; 1942 return true; 1943 } 1944 1945 // Blocks: Block pointers can be converted to void*. 1946 if (FromType->isBlockPointerType() && ToType->isPointerType() && 1947 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 1948 ConvertedType = ToType; 1949 return true; 1950 } 1951 // Blocks: A null pointer constant can be converted to a block 1952 // pointer type. 1953 if (ToType->isBlockPointerType() && 1954 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1955 ConvertedType = ToType; 1956 return true; 1957 } 1958 1959 // If the left-hand-side is nullptr_t, the right side can be a null 1960 // pointer constant. 1961 if (ToType->isNullPtrType() && 1962 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1963 ConvertedType = ToType; 1964 return true; 1965 } 1966 1967 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 1968 if (!ToTypePtr) 1969 return false; 1970 1971 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 1972 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1973 ConvertedType = ToType; 1974 return true; 1975 } 1976 1977 // Beyond this point, both types need to be pointers 1978 // , including objective-c pointers. 1979 QualType ToPointeeType = ToTypePtr->getPointeeType(); 1980 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 1981 !getLangOpts().ObjCAutoRefCount) { 1982 ConvertedType = BuildSimilarlyQualifiedPointerType( 1983 FromType->getAs<ObjCObjectPointerType>(), 1984 ToPointeeType, 1985 ToType, Context); 1986 return true; 1987 } 1988 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 1989 if (!FromTypePtr) 1990 return false; 1991 1992 QualType FromPointeeType = FromTypePtr->getPointeeType(); 1993 1994 // If the unqualified pointee types are the same, this can't be a 1995 // pointer conversion, so don't do all of the work below. 1996 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 1997 return false; 1998 1999 // An rvalue of type "pointer to cv T," where T is an object type, 2000 // can be converted to an rvalue of type "pointer to cv void" (C++ 2001 // 4.10p2). 2002 if (FromPointeeType->isIncompleteOrObjectType() && 2003 ToPointeeType->isVoidType()) { 2004 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2005 ToPointeeType, 2006 ToType, Context, 2007 /*StripObjCLifetime=*/true); 2008 return true; 2009 } 2010 2011 // MSVC allows implicit function to void* type conversion. 2012 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 2013 ToPointeeType->isVoidType()) { 2014 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2015 ToPointeeType, 2016 ToType, Context); 2017 return true; 2018 } 2019 2020 // When we're overloading in C, we allow a special kind of pointer 2021 // conversion for compatible-but-not-identical pointee types. 2022 if (!getLangOpts().CPlusPlus && 2023 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2024 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2025 ToPointeeType, 2026 ToType, Context); 2027 return true; 2028 } 2029 2030 // C++ [conv.ptr]p3: 2031 // 2032 // An rvalue of type "pointer to cv D," where D is a class type, 2033 // can be converted to an rvalue of type "pointer to cv B," where 2034 // B is a base class (clause 10) of D. If B is an inaccessible 2035 // (clause 11) or ambiguous (10.2) base class of D, a program that 2036 // necessitates this conversion is ill-formed. The result of the 2037 // conversion is a pointer to the base class sub-object of the 2038 // derived class object. The null pointer value is converted to 2039 // the null pointer value of the destination type. 2040 // 2041 // Note that we do not check for ambiguity or inaccessibility 2042 // here. That is handled by CheckPointerConversion. 2043 if (getLangOpts().CPlusPlus && 2044 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2045 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2046 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2047 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2048 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2049 ToPointeeType, 2050 ToType, Context); 2051 return true; 2052 } 2053 2054 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2055 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2056 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2057 ToPointeeType, 2058 ToType, Context); 2059 return true; 2060 } 2061 2062 return false; 2063 } 2064 2065 /// \brief Adopt the given qualifiers for the given type. 2066 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2067 Qualifiers TQs = T.getQualifiers(); 2068 2069 // Check whether qualifiers already match. 2070 if (TQs == Qs) 2071 return T; 2072 2073 if (Qs.compatiblyIncludes(TQs)) 2074 return Context.getQualifiedType(T, Qs); 2075 2076 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2077 } 2078 2079 /// isObjCPointerConversion - Determines whether this is an 2080 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2081 /// with the same arguments and return values. 2082 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2083 QualType& ConvertedType, 2084 bool &IncompatibleObjC) { 2085 if (!getLangOpts().ObjC1) 2086 return false; 2087 2088 // The set of qualifiers on the type we're converting from. 2089 Qualifiers FromQualifiers = FromType.getQualifiers(); 2090 2091 // First, we handle all conversions on ObjC object pointer types. 2092 const ObjCObjectPointerType* ToObjCPtr = 2093 ToType->getAs<ObjCObjectPointerType>(); 2094 const ObjCObjectPointerType *FromObjCPtr = 2095 FromType->getAs<ObjCObjectPointerType>(); 2096 2097 if (ToObjCPtr && FromObjCPtr) { 2098 // If the pointee types are the same (ignoring qualifications), 2099 // then this is not a pointer conversion. 2100 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2101 FromObjCPtr->getPointeeType())) 2102 return false; 2103 2104 // Check for compatible 2105 // Objective C++: We're able to convert between "id" or "Class" and a 2106 // pointer to any interface (in both directions). 2107 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2108 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2109 return true; 2110 } 2111 // Conversions with Objective-C's id<...>. 2112 if ((FromObjCPtr->isObjCQualifiedIdType() || 2113 ToObjCPtr->isObjCQualifiedIdType()) && 2114 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2115 /*compare=*/false)) { 2116 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2117 return true; 2118 } 2119 // Objective C++: We're able to convert from a pointer to an 2120 // interface to a pointer to a different interface. 2121 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2122 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2123 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2124 if (getLangOpts().CPlusPlus && LHS && RHS && 2125 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2126 FromObjCPtr->getPointeeType())) 2127 return false; 2128 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2129 ToObjCPtr->getPointeeType(), 2130 ToType, Context); 2131 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2132 return true; 2133 } 2134 2135 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2136 // Okay: this is some kind of implicit downcast of Objective-C 2137 // interfaces, which is permitted. However, we're going to 2138 // complain about it. 2139 IncompatibleObjC = true; 2140 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2141 ToObjCPtr->getPointeeType(), 2142 ToType, Context); 2143 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2144 return true; 2145 } 2146 } 2147 // Beyond this point, both types need to be C pointers or block pointers. 2148 QualType ToPointeeType; 2149 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2150 ToPointeeType = ToCPtr->getPointeeType(); 2151 else if (const BlockPointerType *ToBlockPtr = 2152 ToType->getAs<BlockPointerType>()) { 2153 // Objective C++: We're able to convert from a pointer to any object 2154 // to a block pointer type. 2155 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2156 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2157 return true; 2158 } 2159 ToPointeeType = ToBlockPtr->getPointeeType(); 2160 } 2161 else if (FromType->getAs<BlockPointerType>() && 2162 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2163 // Objective C++: We're able to convert from a block pointer type to a 2164 // pointer to any object. 2165 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2166 return true; 2167 } 2168 else 2169 return false; 2170 2171 QualType FromPointeeType; 2172 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2173 FromPointeeType = FromCPtr->getPointeeType(); 2174 else if (const BlockPointerType *FromBlockPtr = 2175 FromType->getAs<BlockPointerType>()) 2176 FromPointeeType = FromBlockPtr->getPointeeType(); 2177 else 2178 return false; 2179 2180 // If we have pointers to pointers, recursively check whether this 2181 // is an Objective-C conversion. 2182 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2183 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2184 IncompatibleObjC)) { 2185 // We always complain about this conversion. 2186 IncompatibleObjC = true; 2187 ConvertedType = Context.getPointerType(ConvertedType); 2188 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2189 return true; 2190 } 2191 // Allow conversion of pointee being objective-c pointer to another one; 2192 // as in I* to id. 2193 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2194 ToPointeeType->getAs<ObjCObjectPointerType>() && 2195 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2196 IncompatibleObjC)) { 2197 2198 ConvertedType = Context.getPointerType(ConvertedType); 2199 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2200 return true; 2201 } 2202 2203 // If we have pointers to functions or blocks, check whether the only 2204 // differences in the argument and result types are in Objective-C 2205 // pointer conversions. If so, we permit the conversion (but 2206 // complain about it). 2207 const FunctionProtoType *FromFunctionType 2208 = FromPointeeType->getAs<FunctionProtoType>(); 2209 const FunctionProtoType *ToFunctionType 2210 = ToPointeeType->getAs<FunctionProtoType>(); 2211 if (FromFunctionType && ToFunctionType) { 2212 // If the function types are exactly the same, this isn't an 2213 // Objective-C pointer conversion. 2214 if (Context.getCanonicalType(FromPointeeType) 2215 == Context.getCanonicalType(ToPointeeType)) 2216 return false; 2217 2218 // Perform the quick checks that will tell us whether these 2219 // function types are obviously different. 2220 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2221 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2222 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2223 return false; 2224 2225 bool HasObjCConversion = false; 2226 if (Context.getCanonicalType(FromFunctionType->getResultType()) 2227 == Context.getCanonicalType(ToFunctionType->getResultType())) { 2228 // Okay, the types match exactly. Nothing to do. 2229 } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 2230 ToFunctionType->getResultType(), 2231 ConvertedType, IncompatibleObjC)) { 2232 // Okay, we have an Objective-C pointer conversion. 2233 HasObjCConversion = true; 2234 } else { 2235 // Function types are too different. Abort. 2236 return false; 2237 } 2238 2239 // Check argument types. 2240 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2241 ArgIdx != NumArgs; ++ArgIdx) { 2242 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2243 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2244 if (Context.getCanonicalType(FromArgType) 2245 == Context.getCanonicalType(ToArgType)) { 2246 // Okay, the types match exactly. Nothing to do. 2247 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2248 ConvertedType, IncompatibleObjC)) { 2249 // Okay, we have an Objective-C pointer conversion. 2250 HasObjCConversion = true; 2251 } else { 2252 // Argument types are too different. Abort. 2253 return false; 2254 } 2255 } 2256 2257 if (HasObjCConversion) { 2258 // We had an Objective-C conversion. Allow this pointer 2259 // conversion, but complain about it. 2260 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2261 IncompatibleObjC = true; 2262 return true; 2263 } 2264 } 2265 2266 return false; 2267 } 2268 2269 /// \brief Determine whether this is an Objective-C writeback conversion, 2270 /// used for parameter passing when performing automatic reference counting. 2271 /// 2272 /// \param FromType The type we're converting form. 2273 /// 2274 /// \param ToType The type we're converting to. 2275 /// 2276 /// \param ConvertedType The type that will be produced after applying 2277 /// this conversion. 2278 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2279 QualType &ConvertedType) { 2280 if (!getLangOpts().ObjCAutoRefCount || 2281 Context.hasSameUnqualifiedType(FromType, ToType)) 2282 return false; 2283 2284 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2285 QualType ToPointee; 2286 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2287 ToPointee = ToPointer->getPointeeType(); 2288 else 2289 return false; 2290 2291 Qualifiers ToQuals = ToPointee.getQualifiers(); 2292 if (!ToPointee->isObjCLifetimeType() || 2293 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2294 !ToQuals.withoutObjCLifetime().empty()) 2295 return false; 2296 2297 // Argument must be a pointer to __strong to __weak. 2298 QualType FromPointee; 2299 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2300 FromPointee = FromPointer->getPointeeType(); 2301 else 2302 return false; 2303 2304 Qualifiers FromQuals = FromPointee.getQualifiers(); 2305 if (!FromPointee->isObjCLifetimeType() || 2306 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2307 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2308 return false; 2309 2310 // Make sure that we have compatible qualifiers. 2311 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2312 if (!ToQuals.compatiblyIncludes(FromQuals)) 2313 return false; 2314 2315 // Remove qualifiers from the pointee type we're converting from; they 2316 // aren't used in the compatibility check belong, and we'll be adding back 2317 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2318 FromPointee = FromPointee.getUnqualifiedType(); 2319 2320 // The unqualified form of the pointee types must be compatible. 2321 ToPointee = ToPointee.getUnqualifiedType(); 2322 bool IncompatibleObjC; 2323 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2324 FromPointee = ToPointee; 2325 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2326 IncompatibleObjC)) 2327 return false; 2328 2329 /// \brief Construct the type we're converting to, which is a pointer to 2330 /// __autoreleasing pointee. 2331 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2332 ConvertedType = Context.getPointerType(FromPointee); 2333 return true; 2334 } 2335 2336 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2337 QualType& ConvertedType) { 2338 QualType ToPointeeType; 2339 if (const BlockPointerType *ToBlockPtr = 2340 ToType->getAs<BlockPointerType>()) 2341 ToPointeeType = ToBlockPtr->getPointeeType(); 2342 else 2343 return false; 2344 2345 QualType FromPointeeType; 2346 if (const BlockPointerType *FromBlockPtr = 2347 FromType->getAs<BlockPointerType>()) 2348 FromPointeeType = FromBlockPtr->getPointeeType(); 2349 else 2350 return false; 2351 // We have pointer to blocks, check whether the only 2352 // differences in the argument and result types are in Objective-C 2353 // pointer conversions. If so, we permit the conversion. 2354 2355 const FunctionProtoType *FromFunctionType 2356 = FromPointeeType->getAs<FunctionProtoType>(); 2357 const FunctionProtoType *ToFunctionType 2358 = ToPointeeType->getAs<FunctionProtoType>(); 2359 2360 if (!FromFunctionType || !ToFunctionType) 2361 return false; 2362 2363 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2364 return true; 2365 2366 // Perform the quick checks that will tell us whether these 2367 // function types are obviously different. 2368 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2369 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2370 return false; 2371 2372 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2373 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2374 if (FromEInfo != ToEInfo) 2375 return false; 2376 2377 bool IncompatibleObjC = false; 2378 if (Context.hasSameType(FromFunctionType->getResultType(), 2379 ToFunctionType->getResultType())) { 2380 // Okay, the types match exactly. Nothing to do. 2381 } else { 2382 QualType RHS = FromFunctionType->getResultType(); 2383 QualType LHS = ToFunctionType->getResultType(); 2384 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2385 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2386 LHS = LHS.getUnqualifiedType(); 2387 2388 if (Context.hasSameType(RHS,LHS)) { 2389 // OK exact match. 2390 } else if (isObjCPointerConversion(RHS, LHS, 2391 ConvertedType, IncompatibleObjC)) { 2392 if (IncompatibleObjC) 2393 return false; 2394 // Okay, we have an Objective-C pointer conversion. 2395 } 2396 else 2397 return false; 2398 } 2399 2400 // Check argument types. 2401 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2402 ArgIdx != NumArgs; ++ArgIdx) { 2403 IncompatibleObjC = false; 2404 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2405 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2406 if (Context.hasSameType(FromArgType, ToArgType)) { 2407 // Okay, the types match exactly. Nothing to do. 2408 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2409 ConvertedType, IncompatibleObjC)) { 2410 if (IncompatibleObjC) 2411 return false; 2412 // Okay, we have an Objective-C pointer conversion. 2413 } else 2414 // Argument types are too different. Abort. 2415 return false; 2416 } 2417 if (LangOpts.ObjCAutoRefCount && 2418 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2419 ToFunctionType)) 2420 return false; 2421 2422 ConvertedType = ToType; 2423 return true; 2424 } 2425 2426 enum { 2427 ft_default, 2428 ft_different_class, 2429 ft_parameter_arity, 2430 ft_parameter_mismatch, 2431 ft_return_type, 2432 ft_qualifer_mismatch 2433 }; 2434 2435 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2436 /// function types. Catches different number of parameter, mismatch in 2437 /// parameter types, and different return types. 2438 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2439 QualType FromType, QualType ToType) { 2440 // If either type is not valid, include no extra info. 2441 if (FromType.isNull() || ToType.isNull()) { 2442 PDiag << ft_default; 2443 return; 2444 } 2445 2446 // Get the function type from the pointers. 2447 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2448 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2449 *ToMember = ToType->getAs<MemberPointerType>(); 2450 if (FromMember->getClass() != ToMember->getClass()) { 2451 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2452 << QualType(FromMember->getClass(), 0); 2453 return; 2454 } 2455 FromType = FromMember->getPointeeType(); 2456 ToType = ToMember->getPointeeType(); 2457 } 2458 2459 if (FromType->isPointerType()) 2460 FromType = FromType->getPointeeType(); 2461 if (ToType->isPointerType()) 2462 ToType = ToType->getPointeeType(); 2463 2464 // Remove references. 2465 FromType = FromType.getNonReferenceType(); 2466 ToType = ToType.getNonReferenceType(); 2467 2468 // Don't print extra info for non-specialized template functions. 2469 if (FromType->isInstantiationDependentType() && 2470 !FromType->getAs<TemplateSpecializationType>()) { 2471 PDiag << ft_default; 2472 return; 2473 } 2474 2475 // No extra info for same types. 2476 if (Context.hasSameType(FromType, ToType)) { 2477 PDiag << ft_default; 2478 return; 2479 } 2480 2481 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2482 *ToFunction = ToType->getAs<FunctionProtoType>(); 2483 2484 // Both types need to be function types. 2485 if (!FromFunction || !ToFunction) { 2486 PDiag << ft_default; 2487 return; 2488 } 2489 2490 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) { 2491 PDiag << ft_parameter_arity << ToFunction->getNumArgs() 2492 << FromFunction->getNumArgs(); 2493 return; 2494 } 2495 2496 // Handle different parameter types. 2497 unsigned ArgPos; 2498 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2499 PDiag << ft_parameter_mismatch << ArgPos + 1 2500 << ToFunction->getArgType(ArgPos) 2501 << FromFunction->getArgType(ArgPos); 2502 return; 2503 } 2504 2505 // Handle different return type. 2506 if (!Context.hasSameType(FromFunction->getResultType(), 2507 ToFunction->getResultType())) { 2508 PDiag << ft_return_type << ToFunction->getResultType() 2509 << FromFunction->getResultType(); 2510 return; 2511 } 2512 2513 unsigned FromQuals = FromFunction->getTypeQuals(), 2514 ToQuals = ToFunction->getTypeQuals(); 2515 if (FromQuals != ToQuals) { 2516 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2517 return; 2518 } 2519 2520 // Unable to find a difference, so add no extra info. 2521 PDiag << ft_default; 2522 } 2523 2524 /// FunctionArgTypesAreEqual - This routine checks two function proto types 2525 /// for equality of their argument types. Caller has already checked that 2526 /// they have same number of arguments. This routine assumes that Objective-C 2527 /// pointer types which only differ in their protocol qualifiers are equal. 2528 /// If the parameters are different, ArgPos will have the parameter index 2529 /// of the first different parameter. 2530 bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 2531 const FunctionProtoType *NewType, 2532 unsigned *ArgPos) { 2533 if (!getLangOpts().ObjC1) { 2534 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2535 N = NewType->arg_type_begin(), 2536 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2537 if (!Context.hasSameType(*O, *N)) { 2538 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2539 return false; 2540 } 2541 } 2542 return true; 2543 } 2544 2545 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2546 N = NewType->arg_type_begin(), 2547 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2548 QualType ToType = (*O); 2549 QualType FromType = (*N); 2550 if (!Context.hasSameType(ToType, FromType)) { 2551 if (const PointerType *PTTo = ToType->getAs<PointerType>()) { 2552 if (const PointerType *PTFr = FromType->getAs<PointerType>()) 2553 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() && 2554 PTFr->getPointeeType()->isObjCQualifiedIdType()) || 2555 (PTTo->getPointeeType()->isObjCQualifiedClassType() && 2556 PTFr->getPointeeType()->isObjCQualifiedClassType())) 2557 continue; 2558 } 2559 else if (const ObjCObjectPointerType *PTTo = 2560 ToType->getAs<ObjCObjectPointerType>()) { 2561 if (const ObjCObjectPointerType *PTFr = 2562 FromType->getAs<ObjCObjectPointerType>()) 2563 if (Context.hasSameUnqualifiedType( 2564 PTTo->getObjectType()->getBaseType(), 2565 PTFr->getObjectType()->getBaseType())) 2566 continue; 2567 } 2568 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2569 return false; 2570 } 2571 } 2572 return true; 2573 } 2574 2575 /// CheckPointerConversion - Check the pointer conversion from the 2576 /// expression From to the type ToType. This routine checks for 2577 /// ambiguous or inaccessible derived-to-base pointer 2578 /// conversions for which IsPointerConversion has already returned 2579 /// true. It returns true and produces a diagnostic if there was an 2580 /// error, or returns false otherwise. 2581 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2582 CastKind &Kind, 2583 CXXCastPath& BasePath, 2584 bool IgnoreBaseAccess) { 2585 QualType FromType = From->getType(); 2586 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2587 2588 Kind = CK_BitCast; 2589 2590 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2591 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2592 Expr::NPCK_ZeroExpression) { 2593 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2594 DiagRuntimeBehavior(From->getExprLoc(), From, 2595 PDiag(diag::warn_impcast_bool_to_null_pointer) 2596 << ToType << From->getSourceRange()); 2597 else if (!isUnevaluatedContext()) 2598 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2599 << ToType << From->getSourceRange(); 2600 } 2601 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2602 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2603 QualType FromPointeeType = FromPtrType->getPointeeType(), 2604 ToPointeeType = ToPtrType->getPointeeType(); 2605 2606 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2607 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2608 // We must have a derived-to-base conversion. Check an 2609 // ambiguous or inaccessible conversion. 2610 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2611 From->getExprLoc(), 2612 From->getSourceRange(), &BasePath, 2613 IgnoreBaseAccess)) 2614 return true; 2615 2616 // The conversion was successful. 2617 Kind = CK_DerivedToBase; 2618 } 2619 } 2620 } else if (const ObjCObjectPointerType *ToPtrType = 2621 ToType->getAs<ObjCObjectPointerType>()) { 2622 if (const ObjCObjectPointerType *FromPtrType = 2623 FromType->getAs<ObjCObjectPointerType>()) { 2624 // Objective-C++ conversions are always okay. 2625 // FIXME: We should have a different class of conversions for the 2626 // Objective-C++ implicit conversions. 2627 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2628 return false; 2629 } else if (FromType->isBlockPointerType()) { 2630 Kind = CK_BlockPointerToObjCPointerCast; 2631 } else { 2632 Kind = CK_CPointerToObjCPointerCast; 2633 } 2634 } else if (ToType->isBlockPointerType()) { 2635 if (!FromType->isBlockPointerType()) 2636 Kind = CK_AnyPointerToBlockPointerCast; 2637 } 2638 2639 // We shouldn't fall into this case unless it's valid for other 2640 // reasons. 2641 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2642 Kind = CK_NullToPointer; 2643 2644 return false; 2645 } 2646 2647 /// IsMemberPointerConversion - Determines whether the conversion of the 2648 /// expression From, which has the (possibly adjusted) type FromType, can be 2649 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2650 /// If so, returns true and places the converted type (that might differ from 2651 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2652 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2653 QualType ToType, 2654 bool InOverloadResolution, 2655 QualType &ConvertedType) { 2656 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2657 if (!ToTypePtr) 2658 return false; 2659 2660 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2661 if (From->isNullPointerConstant(Context, 2662 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2663 : Expr::NPC_ValueDependentIsNull)) { 2664 ConvertedType = ToType; 2665 return true; 2666 } 2667 2668 // Otherwise, both types have to be member pointers. 2669 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2670 if (!FromTypePtr) 2671 return false; 2672 2673 // A pointer to member of B can be converted to a pointer to member of D, 2674 // where D is derived from B (C++ 4.11p2). 2675 QualType FromClass(FromTypePtr->getClass(), 0); 2676 QualType ToClass(ToTypePtr->getClass(), 0); 2677 2678 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2679 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2680 IsDerivedFrom(ToClass, FromClass)) { 2681 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2682 ToClass.getTypePtr()); 2683 return true; 2684 } 2685 2686 return false; 2687 } 2688 2689 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2690 /// expression From to the type ToType. This routine checks for ambiguous or 2691 /// virtual or inaccessible base-to-derived member pointer conversions 2692 /// for which IsMemberPointerConversion has already returned true. It returns 2693 /// true and produces a diagnostic if there was an error, or returns false 2694 /// otherwise. 2695 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2696 CastKind &Kind, 2697 CXXCastPath &BasePath, 2698 bool IgnoreBaseAccess) { 2699 QualType FromType = From->getType(); 2700 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2701 if (!FromPtrType) { 2702 // This must be a null pointer to member pointer conversion 2703 assert(From->isNullPointerConstant(Context, 2704 Expr::NPC_ValueDependentIsNull) && 2705 "Expr must be null pointer constant!"); 2706 Kind = CK_NullToMemberPointer; 2707 return false; 2708 } 2709 2710 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2711 assert(ToPtrType && "No member pointer cast has a target type " 2712 "that is not a member pointer."); 2713 2714 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2715 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2716 2717 // FIXME: What about dependent types? 2718 assert(FromClass->isRecordType() && "Pointer into non-class."); 2719 assert(ToClass->isRecordType() && "Pointer into non-class."); 2720 2721 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2722 /*DetectVirtual=*/true); 2723 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2724 assert(DerivationOkay && 2725 "Should not have been called if derivation isn't OK."); 2726 (void)DerivationOkay; 2727 2728 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2729 getUnqualifiedType())) { 2730 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2731 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2732 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2733 return true; 2734 } 2735 2736 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2737 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2738 << FromClass << ToClass << QualType(VBase, 0) 2739 << From->getSourceRange(); 2740 return true; 2741 } 2742 2743 if (!IgnoreBaseAccess) 2744 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2745 Paths.front(), 2746 diag::err_downcast_from_inaccessible_base); 2747 2748 // Must be a base to derived member conversion. 2749 BuildBasePathArray(Paths, BasePath); 2750 Kind = CK_BaseToDerivedMemberPointer; 2751 return false; 2752 } 2753 2754 /// IsQualificationConversion - Determines whether the conversion from 2755 /// an rvalue of type FromType to ToType is a qualification conversion 2756 /// (C++ 4.4). 2757 /// 2758 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2759 /// when the qualification conversion involves a change in the Objective-C 2760 /// object lifetime. 2761 bool 2762 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2763 bool CStyle, bool &ObjCLifetimeConversion) { 2764 FromType = Context.getCanonicalType(FromType); 2765 ToType = Context.getCanonicalType(ToType); 2766 ObjCLifetimeConversion = false; 2767 2768 // If FromType and ToType are the same type, this is not a 2769 // qualification conversion. 2770 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2771 return false; 2772 2773 // (C++ 4.4p4): 2774 // A conversion can add cv-qualifiers at levels other than the first 2775 // in multi-level pointers, subject to the following rules: [...] 2776 bool PreviousToQualsIncludeConst = true; 2777 bool UnwrappedAnyPointer = false; 2778 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2779 // Within each iteration of the loop, we check the qualifiers to 2780 // determine if this still looks like a qualification 2781 // conversion. Then, if all is well, we unwrap one more level of 2782 // pointers or pointers-to-members and do it all again 2783 // until there are no more pointers or pointers-to-members left to 2784 // unwrap. 2785 UnwrappedAnyPointer = true; 2786 2787 Qualifiers FromQuals = FromType.getQualifiers(); 2788 Qualifiers ToQuals = ToType.getQualifiers(); 2789 2790 // Objective-C ARC: 2791 // Check Objective-C lifetime conversions. 2792 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2793 UnwrappedAnyPointer) { 2794 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2795 ObjCLifetimeConversion = true; 2796 FromQuals.removeObjCLifetime(); 2797 ToQuals.removeObjCLifetime(); 2798 } else { 2799 // Qualification conversions cannot cast between different 2800 // Objective-C lifetime qualifiers. 2801 return false; 2802 } 2803 } 2804 2805 // Allow addition/removal of GC attributes but not changing GC attributes. 2806 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2807 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2808 FromQuals.removeObjCGCAttr(); 2809 ToQuals.removeObjCGCAttr(); 2810 } 2811 2812 // -- for every j > 0, if const is in cv 1,j then const is in cv 2813 // 2,j, and similarly for volatile. 2814 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2815 return false; 2816 2817 // -- if the cv 1,j and cv 2,j are different, then const is in 2818 // every cv for 0 < k < j. 2819 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2820 && !PreviousToQualsIncludeConst) 2821 return false; 2822 2823 // Keep track of whether all prior cv-qualifiers in the "to" type 2824 // include const. 2825 PreviousToQualsIncludeConst 2826 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2827 } 2828 2829 // We are left with FromType and ToType being the pointee types 2830 // after unwrapping the original FromType and ToType the same number 2831 // of types. If we unwrapped any pointers, and if FromType and 2832 // ToType have the same unqualified type (since we checked 2833 // qualifiers above), then this is a qualification conversion. 2834 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2835 } 2836 2837 /// \brief - Determine whether this is a conversion from a scalar type to an 2838 /// atomic type. 2839 /// 2840 /// If successful, updates \c SCS's second and third steps in the conversion 2841 /// sequence to finish the conversion. 2842 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2843 bool InOverloadResolution, 2844 StandardConversionSequence &SCS, 2845 bool CStyle) { 2846 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2847 if (!ToAtomic) 2848 return false; 2849 2850 StandardConversionSequence InnerSCS; 2851 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2852 InOverloadResolution, InnerSCS, 2853 CStyle, /*AllowObjCWritebackConversion=*/false)) 2854 return false; 2855 2856 SCS.Second = InnerSCS.Second; 2857 SCS.setToType(1, InnerSCS.getToType(1)); 2858 SCS.Third = InnerSCS.Third; 2859 SCS.QualificationIncludesObjCLifetime 2860 = InnerSCS.QualificationIncludesObjCLifetime; 2861 SCS.setToType(2, InnerSCS.getToType(2)); 2862 return true; 2863 } 2864 2865 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2866 CXXConstructorDecl *Constructor, 2867 QualType Type) { 2868 const FunctionProtoType *CtorType = 2869 Constructor->getType()->getAs<FunctionProtoType>(); 2870 if (CtorType->getNumArgs() > 0) { 2871 QualType FirstArg = CtorType->getArgType(0); 2872 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2873 return true; 2874 } 2875 return false; 2876 } 2877 2878 static OverloadingResult 2879 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2880 CXXRecordDecl *To, 2881 UserDefinedConversionSequence &User, 2882 OverloadCandidateSet &CandidateSet, 2883 bool AllowExplicit) { 2884 DeclContext::lookup_iterator Con, ConEnd; 2885 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To); 2886 Con != ConEnd; ++Con) { 2887 NamedDecl *D = *Con; 2888 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2889 2890 // Find the constructor (which may be a template). 2891 CXXConstructorDecl *Constructor = 0; 2892 FunctionTemplateDecl *ConstructorTmpl 2893 = dyn_cast<FunctionTemplateDecl>(D); 2894 if (ConstructorTmpl) 2895 Constructor 2896 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2897 else 2898 Constructor = cast<CXXConstructorDecl>(D); 2899 2900 bool Usable = !Constructor->isInvalidDecl() && 2901 S.isInitListConstructor(Constructor) && 2902 (AllowExplicit || !Constructor->isExplicit()); 2903 if (Usable) { 2904 // If the first argument is (a reference to) the target type, 2905 // suppress conversions. 2906 bool SuppressUserConversions = 2907 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2908 if (ConstructorTmpl) 2909 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2910 /*ExplicitArgs*/ 0, 2911 From, CandidateSet, 2912 SuppressUserConversions); 2913 else 2914 S.AddOverloadCandidate(Constructor, FoundDecl, 2915 From, CandidateSet, 2916 SuppressUserConversions); 2917 } 2918 } 2919 2920 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2921 2922 OverloadCandidateSet::iterator Best; 2923 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2924 case OR_Success: { 2925 // Record the standard conversion we used and the conversion function. 2926 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2927 QualType ThisType = Constructor->getThisType(S.Context); 2928 // Initializer lists don't have conversions as such. 2929 User.Before.setAsIdentityConversion(); 2930 User.HadMultipleCandidates = HadMultipleCandidates; 2931 User.ConversionFunction = Constructor; 2932 User.FoundConversionFunction = Best->FoundDecl; 2933 User.After.setAsIdentityConversion(); 2934 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2935 User.After.setAllToTypes(ToType); 2936 return OR_Success; 2937 } 2938 2939 case OR_No_Viable_Function: 2940 return OR_No_Viable_Function; 2941 case OR_Deleted: 2942 return OR_Deleted; 2943 case OR_Ambiguous: 2944 return OR_Ambiguous; 2945 } 2946 2947 llvm_unreachable("Invalid OverloadResult!"); 2948 } 2949 2950 /// Determines whether there is a user-defined conversion sequence 2951 /// (C++ [over.ics.user]) that converts expression From to the type 2952 /// ToType. If such a conversion exists, User will contain the 2953 /// user-defined conversion sequence that performs such a conversion 2954 /// and this routine will return true. Otherwise, this routine returns 2955 /// false and User is unspecified. 2956 /// 2957 /// \param AllowExplicit true if the conversion should consider C++0x 2958 /// "explicit" conversion functions as well as non-explicit conversion 2959 /// functions (C++0x [class.conv.fct]p2). 2960 static OverloadingResult 2961 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 2962 UserDefinedConversionSequence &User, 2963 OverloadCandidateSet &CandidateSet, 2964 bool AllowExplicit) { 2965 // Whether we will only visit constructors. 2966 bool ConstructorsOnly = false; 2967 2968 // If the type we are conversion to is a class type, enumerate its 2969 // constructors. 2970 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 2971 // C++ [over.match.ctor]p1: 2972 // When objects of class type are direct-initialized (8.5), or 2973 // copy-initialized from an expression of the same or a 2974 // derived class type (8.5), overload resolution selects the 2975 // constructor. [...] For copy-initialization, the candidate 2976 // functions are all the converting constructors (12.3.1) of 2977 // that class. The argument list is the expression-list within 2978 // the parentheses of the initializer. 2979 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 2980 (From->getType()->getAs<RecordType>() && 2981 S.IsDerivedFrom(From->getType(), ToType))) 2982 ConstructorsOnly = true; 2983 2984 S.RequireCompleteType(From->getExprLoc(), ToType, 0); 2985 // RequireCompleteType may have returned true due to some invalid decl 2986 // during template instantiation, but ToType may be complete enough now 2987 // to try to recover. 2988 if (ToType->isIncompleteType()) { 2989 // We're not going to find any constructors. 2990 } else if (CXXRecordDecl *ToRecordDecl 2991 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 2992 2993 Expr **Args = &From; 2994 unsigned NumArgs = 1; 2995 bool ListInitializing = false; 2996 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 2997 // But first, see if there is an init-list-contructor that will work. 2998 OverloadingResult Result = IsInitializerListConstructorConversion( 2999 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3000 if (Result != OR_No_Viable_Function) 3001 return Result; 3002 // Never mind. 3003 CandidateSet.clear(); 3004 3005 // If we're list-initializing, we pass the individual elements as 3006 // arguments, not the entire list. 3007 Args = InitList->getInits(); 3008 NumArgs = InitList->getNumInits(); 3009 ListInitializing = true; 3010 } 3011 3012 DeclContext::lookup_iterator Con, ConEnd; 3013 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl); 3014 Con != ConEnd; ++Con) { 3015 NamedDecl *D = *Con; 3016 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3017 3018 // Find the constructor (which may be a template). 3019 CXXConstructorDecl *Constructor = 0; 3020 FunctionTemplateDecl *ConstructorTmpl 3021 = dyn_cast<FunctionTemplateDecl>(D); 3022 if (ConstructorTmpl) 3023 Constructor 3024 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3025 else 3026 Constructor = cast<CXXConstructorDecl>(D); 3027 3028 bool Usable = !Constructor->isInvalidDecl(); 3029 if (ListInitializing) 3030 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3031 else 3032 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3033 if (Usable) { 3034 bool SuppressUserConversions = !ConstructorsOnly; 3035 if (SuppressUserConversions && ListInitializing) { 3036 SuppressUserConversions = false; 3037 if (NumArgs == 1) { 3038 // If the first argument is (a reference to) the target type, 3039 // suppress conversions. 3040 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3041 S.Context, Constructor, ToType); 3042 } 3043 } 3044 if (ConstructorTmpl) 3045 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3046 /*ExplicitArgs*/ 0, 3047 llvm::makeArrayRef(Args, NumArgs), 3048 CandidateSet, SuppressUserConversions); 3049 else 3050 // Allow one user-defined conversion when user specifies a 3051 // From->ToType conversion via an static cast (c-style, etc). 3052 S.AddOverloadCandidate(Constructor, FoundDecl, 3053 llvm::makeArrayRef(Args, NumArgs), 3054 CandidateSet, SuppressUserConversions); 3055 } 3056 } 3057 } 3058 } 3059 3060 // Enumerate conversion functions, if we're allowed to. 3061 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3062 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3063 // No conversion functions from incomplete types. 3064 } else if (const RecordType *FromRecordType 3065 = From->getType()->getAs<RecordType>()) { 3066 if (CXXRecordDecl *FromRecordDecl 3067 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3068 // Add all of the conversion functions as candidates. 3069 std::pair<CXXRecordDecl::conversion_iterator, 3070 CXXRecordDecl::conversion_iterator> 3071 Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3072 for (CXXRecordDecl::conversion_iterator 3073 I = Conversions.first, E = Conversions.second; I != E; ++I) { 3074 DeclAccessPair FoundDecl = I.getPair(); 3075 NamedDecl *D = FoundDecl.getDecl(); 3076 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3077 if (isa<UsingShadowDecl>(D)) 3078 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3079 3080 CXXConversionDecl *Conv; 3081 FunctionTemplateDecl *ConvTemplate; 3082 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3083 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3084 else 3085 Conv = cast<CXXConversionDecl>(D); 3086 3087 if (AllowExplicit || !Conv->isExplicit()) { 3088 if (ConvTemplate) 3089 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3090 ActingContext, From, ToType, 3091 CandidateSet); 3092 else 3093 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3094 From, ToType, CandidateSet); 3095 } 3096 } 3097 } 3098 } 3099 3100 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3101 3102 OverloadCandidateSet::iterator Best; 3103 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3104 case OR_Success: 3105 // Record the standard conversion we used and the conversion function. 3106 if (CXXConstructorDecl *Constructor 3107 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3108 // C++ [over.ics.user]p1: 3109 // If the user-defined conversion is specified by a 3110 // constructor (12.3.1), the initial standard conversion 3111 // sequence converts the source type to the type required by 3112 // the argument of the constructor. 3113 // 3114 QualType ThisType = Constructor->getThisType(S.Context); 3115 if (isa<InitListExpr>(From)) { 3116 // Initializer lists don't have conversions as such. 3117 User.Before.setAsIdentityConversion(); 3118 } else { 3119 if (Best->Conversions[0].isEllipsis()) 3120 User.EllipsisConversion = true; 3121 else { 3122 User.Before = Best->Conversions[0].Standard; 3123 User.EllipsisConversion = false; 3124 } 3125 } 3126 User.HadMultipleCandidates = HadMultipleCandidates; 3127 User.ConversionFunction = Constructor; 3128 User.FoundConversionFunction = Best->FoundDecl; 3129 User.After.setAsIdentityConversion(); 3130 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3131 User.After.setAllToTypes(ToType); 3132 return OR_Success; 3133 } 3134 if (CXXConversionDecl *Conversion 3135 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3136 // C++ [over.ics.user]p1: 3137 // 3138 // [...] If the user-defined conversion is specified by a 3139 // conversion function (12.3.2), the initial standard 3140 // conversion sequence converts the source type to the 3141 // implicit object parameter of the conversion function. 3142 User.Before = Best->Conversions[0].Standard; 3143 User.HadMultipleCandidates = HadMultipleCandidates; 3144 User.ConversionFunction = Conversion; 3145 User.FoundConversionFunction = Best->FoundDecl; 3146 User.EllipsisConversion = false; 3147 3148 // C++ [over.ics.user]p2: 3149 // The second standard conversion sequence converts the 3150 // result of the user-defined conversion to the target type 3151 // for the sequence. Since an implicit conversion sequence 3152 // is an initialization, the special rules for 3153 // initialization by user-defined conversion apply when 3154 // selecting the best user-defined conversion for a 3155 // user-defined conversion sequence (see 13.3.3 and 3156 // 13.3.3.1). 3157 User.After = Best->FinalConversion; 3158 return OR_Success; 3159 } 3160 llvm_unreachable("Not a constructor or conversion function?"); 3161 3162 case OR_No_Viable_Function: 3163 return OR_No_Viable_Function; 3164 case OR_Deleted: 3165 // No conversion here! We're done. 3166 return OR_Deleted; 3167 3168 case OR_Ambiguous: 3169 return OR_Ambiguous; 3170 } 3171 3172 llvm_unreachable("Invalid OverloadResult!"); 3173 } 3174 3175 bool 3176 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3177 ImplicitConversionSequence ICS; 3178 OverloadCandidateSet CandidateSet(From->getExprLoc()); 3179 OverloadingResult OvResult = 3180 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3181 CandidateSet, false); 3182 if (OvResult == OR_Ambiguous) 3183 Diag(From->getLocStart(), 3184 diag::err_typecheck_ambiguous_condition) 3185 << From->getType() << ToType << From->getSourceRange(); 3186 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) 3187 Diag(From->getLocStart(), 3188 diag::err_typecheck_nonviable_condition) 3189 << From->getType() << ToType << From->getSourceRange(); 3190 else 3191 return false; 3192 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3193 return true; 3194 } 3195 3196 /// \brief Compare the user-defined conversion functions or constructors 3197 /// of two user-defined conversion sequences to determine whether any ordering 3198 /// is possible. 3199 static ImplicitConversionSequence::CompareKind 3200 compareConversionFunctions(Sema &S, 3201 FunctionDecl *Function1, 3202 FunctionDecl *Function2) { 3203 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x) 3204 return ImplicitConversionSequence::Indistinguishable; 3205 3206 // Objective-C++: 3207 // If both conversion functions are implicitly-declared conversions from 3208 // a lambda closure type to a function pointer and a block pointer, 3209 // respectively, always prefer the conversion to a function pointer, 3210 // because the function pointer is more lightweight and is more likely 3211 // to keep code working. 3212 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1); 3213 if (!Conv1) 3214 return ImplicitConversionSequence::Indistinguishable; 3215 3216 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3217 if (!Conv2) 3218 return ImplicitConversionSequence::Indistinguishable; 3219 3220 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3221 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3222 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3223 if (Block1 != Block2) 3224 return Block1? ImplicitConversionSequence::Worse 3225 : ImplicitConversionSequence::Better; 3226 } 3227 3228 return ImplicitConversionSequence::Indistinguishable; 3229 } 3230 3231 /// CompareImplicitConversionSequences - Compare two implicit 3232 /// conversion sequences to determine whether one is better than the 3233 /// other or if they are indistinguishable (C++ 13.3.3.2). 3234 static ImplicitConversionSequence::CompareKind 3235 CompareImplicitConversionSequences(Sema &S, 3236 const ImplicitConversionSequence& ICS1, 3237 const ImplicitConversionSequence& ICS2) 3238 { 3239 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3240 // conversion sequences (as defined in 13.3.3.1) 3241 // -- a standard conversion sequence (13.3.3.1.1) is a better 3242 // conversion sequence than a user-defined conversion sequence or 3243 // an ellipsis conversion sequence, and 3244 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3245 // conversion sequence than an ellipsis conversion sequence 3246 // (13.3.3.1.3). 3247 // 3248 // C++0x [over.best.ics]p10: 3249 // For the purpose of ranking implicit conversion sequences as 3250 // described in 13.3.3.2, the ambiguous conversion sequence is 3251 // treated as a user-defined sequence that is indistinguishable 3252 // from any other user-defined conversion sequence. 3253 if (ICS1.getKindRank() < ICS2.getKindRank()) 3254 return ImplicitConversionSequence::Better; 3255 if (ICS2.getKindRank() < ICS1.getKindRank()) 3256 return ImplicitConversionSequence::Worse; 3257 3258 // The following checks require both conversion sequences to be of 3259 // the same kind. 3260 if (ICS1.getKind() != ICS2.getKind()) 3261 return ImplicitConversionSequence::Indistinguishable; 3262 3263 ImplicitConversionSequence::CompareKind Result = 3264 ImplicitConversionSequence::Indistinguishable; 3265 3266 // Two implicit conversion sequences of the same form are 3267 // indistinguishable conversion sequences unless one of the 3268 // following rules apply: (C++ 13.3.3.2p3): 3269 if (ICS1.isStandard()) 3270 Result = CompareStandardConversionSequences(S, 3271 ICS1.Standard, ICS2.Standard); 3272 else if (ICS1.isUserDefined()) { 3273 // User-defined conversion sequence U1 is a better conversion 3274 // sequence than another user-defined conversion sequence U2 if 3275 // they contain the same user-defined conversion function or 3276 // constructor and if the second standard conversion sequence of 3277 // U1 is better than the second standard conversion sequence of 3278 // U2 (C++ 13.3.3.2p3). 3279 if (ICS1.UserDefined.ConversionFunction == 3280 ICS2.UserDefined.ConversionFunction) 3281 Result = CompareStandardConversionSequences(S, 3282 ICS1.UserDefined.After, 3283 ICS2.UserDefined.After); 3284 else 3285 Result = compareConversionFunctions(S, 3286 ICS1.UserDefined.ConversionFunction, 3287 ICS2.UserDefined.ConversionFunction); 3288 } 3289 3290 // List-initialization sequence L1 is a better conversion sequence than 3291 // list-initialization sequence L2 if L1 converts to std::initializer_list<X> 3292 // for some X and L2 does not. 3293 if (Result == ImplicitConversionSequence::Indistinguishable && 3294 !ICS1.isBad() && 3295 ICS1.isListInitializationSequence() && 3296 ICS2.isListInitializationSequence()) { 3297 if (ICS1.isStdInitializerListElement() && 3298 !ICS2.isStdInitializerListElement()) 3299 return ImplicitConversionSequence::Better; 3300 if (!ICS1.isStdInitializerListElement() && 3301 ICS2.isStdInitializerListElement()) 3302 return ImplicitConversionSequence::Worse; 3303 } 3304 3305 return Result; 3306 } 3307 3308 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3309 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3310 Qualifiers Quals; 3311 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3312 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3313 } 3314 3315 return Context.hasSameUnqualifiedType(T1, T2); 3316 } 3317 3318 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3319 // determine if one is a proper subset of the other. 3320 static ImplicitConversionSequence::CompareKind 3321 compareStandardConversionSubsets(ASTContext &Context, 3322 const StandardConversionSequence& SCS1, 3323 const StandardConversionSequence& SCS2) { 3324 ImplicitConversionSequence::CompareKind Result 3325 = ImplicitConversionSequence::Indistinguishable; 3326 3327 // the identity conversion sequence is considered to be a subsequence of 3328 // any non-identity conversion sequence 3329 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3330 return ImplicitConversionSequence::Better; 3331 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3332 return ImplicitConversionSequence::Worse; 3333 3334 if (SCS1.Second != SCS2.Second) { 3335 if (SCS1.Second == ICK_Identity) 3336 Result = ImplicitConversionSequence::Better; 3337 else if (SCS2.Second == ICK_Identity) 3338 Result = ImplicitConversionSequence::Worse; 3339 else 3340 return ImplicitConversionSequence::Indistinguishable; 3341 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3342 return ImplicitConversionSequence::Indistinguishable; 3343 3344 if (SCS1.Third == SCS2.Third) { 3345 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3346 : ImplicitConversionSequence::Indistinguishable; 3347 } 3348 3349 if (SCS1.Third == ICK_Identity) 3350 return Result == ImplicitConversionSequence::Worse 3351 ? ImplicitConversionSequence::Indistinguishable 3352 : ImplicitConversionSequence::Better; 3353 3354 if (SCS2.Third == ICK_Identity) 3355 return Result == ImplicitConversionSequence::Better 3356 ? ImplicitConversionSequence::Indistinguishable 3357 : ImplicitConversionSequence::Worse; 3358 3359 return ImplicitConversionSequence::Indistinguishable; 3360 } 3361 3362 /// \brief Determine whether one of the given reference bindings is better 3363 /// than the other based on what kind of bindings they are. 3364 static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3365 const StandardConversionSequence &SCS2) { 3366 // C++0x [over.ics.rank]p3b4: 3367 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3368 // implicit object parameter of a non-static member function declared 3369 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3370 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3371 // lvalue reference to a function lvalue and S2 binds an rvalue 3372 // reference*. 3373 // 3374 // FIXME: Rvalue references. We're going rogue with the above edits, 3375 // because the semantics in the current C++0x working paper (N3225 at the 3376 // time of this writing) break the standard definition of std::forward 3377 // and std::reference_wrapper when dealing with references to functions. 3378 // Proposed wording changes submitted to CWG for consideration. 3379 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3380 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3381 return false; 3382 3383 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3384 SCS2.IsLvalueReference) || 3385 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3386 !SCS2.IsLvalueReference); 3387 } 3388 3389 /// CompareStandardConversionSequences - Compare two standard 3390 /// conversion sequences to determine whether one is better than the 3391 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3392 static ImplicitConversionSequence::CompareKind 3393 CompareStandardConversionSequences(Sema &S, 3394 const StandardConversionSequence& SCS1, 3395 const StandardConversionSequence& SCS2) 3396 { 3397 // Standard conversion sequence S1 is a better conversion sequence 3398 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3399 3400 // -- S1 is a proper subsequence of S2 (comparing the conversion 3401 // sequences in the canonical form defined by 13.3.3.1.1, 3402 // excluding any Lvalue Transformation; the identity conversion 3403 // sequence is considered to be a subsequence of any 3404 // non-identity conversion sequence) or, if not that, 3405 if (ImplicitConversionSequence::CompareKind CK 3406 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3407 return CK; 3408 3409 // -- the rank of S1 is better than the rank of S2 (by the rules 3410 // defined below), or, if not that, 3411 ImplicitConversionRank Rank1 = SCS1.getRank(); 3412 ImplicitConversionRank Rank2 = SCS2.getRank(); 3413 if (Rank1 < Rank2) 3414 return ImplicitConversionSequence::Better; 3415 else if (Rank2 < Rank1) 3416 return ImplicitConversionSequence::Worse; 3417 3418 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3419 // are indistinguishable unless one of the following rules 3420 // applies: 3421 3422 // A conversion that is not a conversion of a pointer, or 3423 // pointer to member, to bool is better than another conversion 3424 // that is such a conversion. 3425 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3426 return SCS2.isPointerConversionToBool() 3427 ? ImplicitConversionSequence::Better 3428 : ImplicitConversionSequence::Worse; 3429 3430 // C++ [over.ics.rank]p4b2: 3431 // 3432 // If class B is derived directly or indirectly from class A, 3433 // conversion of B* to A* is better than conversion of B* to 3434 // void*, and conversion of A* to void* is better than conversion 3435 // of B* to void*. 3436 bool SCS1ConvertsToVoid 3437 = SCS1.isPointerConversionToVoidPointer(S.Context); 3438 bool SCS2ConvertsToVoid 3439 = SCS2.isPointerConversionToVoidPointer(S.Context); 3440 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3441 // Exactly one of the conversion sequences is a conversion to 3442 // a void pointer; it's the worse conversion. 3443 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3444 : ImplicitConversionSequence::Worse; 3445 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3446 // Neither conversion sequence converts to a void pointer; compare 3447 // their derived-to-base conversions. 3448 if (ImplicitConversionSequence::CompareKind DerivedCK 3449 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3450 return DerivedCK; 3451 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3452 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3453 // Both conversion sequences are conversions to void 3454 // pointers. Compare the source types to determine if there's an 3455 // inheritance relationship in their sources. 3456 QualType FromType1 = SCS1.getFromType(); 3457 QualType FromType2 = SCS2.getFromType(); 3458 3459 // Adjust the types we're converting from via the array-to-pointer 3460 // conversion, if we need to. 3461 if (SCS1.First == ICK_Array_To_Pointer) 3462 FromType1 = S.Context.getArrayDecayedType(FromType1); 3463 if (SCS2.First == ICK_Array_To_Pointer) 3464 FromType2 = S.Context.getArrayDecayedType(FromType2); 3465 3466 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3467 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3468 3469 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3470 return ImplicitConversionSequence::Better; 3471 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3472 return ImplicitConversionSequence::Worse; 3473 3474 // Objective-C++: If one interface is more specific than the 3475 // other, it is the better one. 3476 const ObjCObjectPointerType* FromObjCPtr1 3477 = FromType1->getAs<ObjCObjectPointerType>(); 3478 const ObjCObjectPointerType* FromObjCPtr2 3479 = FromType2->getAs<ObjCObjectPointerType>(); 3480 if (FromObjCPtr1 && FromObjCPtr2) { 3481 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3482 FromObjCPtr2); 3483 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3484 FromObjCPtr1); 3485 if (AssignLeft != AssignRight) { 3486 return AssignLeft? ImplicitConversionSequence::Better 3487 : ImplicitConversionSequence::Worse; 3488 } 3489 } 3490 } 3491 3492 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3493 // bullet 3). 3494 if (ImplicitConversionSequence::CompareKind QualCK 3495 = CompareQualificationConversions(S, SCS1, SCS2)) 3496 return QualCK; 3497 3498 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3499 // Check for a better reference binding based on the kind of bindings. 3500 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3501 return ImplicitConversionSequence::Better; 3502 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3503 return ImplicitConversionSequence::Worse; 3504 3505 // C++ [over.ics.rank]p3b4: 3506 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3507 // which the references refer are the same type except for 3508 // top-level cv-qualifiers, and the type to which the reference 3509 // initialized by S2 refers is more cv-qualified than the type 3510 // to which the reference initialized by S1 refers. 3511 QualType T1 = SCS1.getToType(2); 3512 QualType T2 = SCS2.getToType(2); 3513 T1 = S.Context.getCanonicalType(T1); 3514 T2 = S.Context.getCanonicalType(T2); 3515 Qualifiers T1Quals, T2Quals; 3516 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3517 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3518 if (UnqualT1 == UnqualT2) { 3519 // Objective-C++ ARC: If the references refer to objects with different 3520 // lifetimes, prefer bindings that don't change lifetime. 3521 if (SCS1.ObjCLifetimeConversionBinding != 3522 SCS2.ObjCLifetimeConversionBinding) { 3523 return SCS1.ObjCLifetimeConversionBinding 3524 ? ImplicitConversionSequence::Worse 3525 : ImplicitConversionSequence::Better; 3526 } 3527 3528 // If the type is an array type, promote the element qualifiers to the 3529 // type for comparison. 3530 if (isa<ArrayType>(T1) && T1Quals) 3531 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3532 if (isa<ArrayType>(T2) && T2Quals) 3533 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3534 if (T2.isMoreQualifiedThan(T1)) 3535 return ImplicitConversionSequence::Better; 3536 else if (T1.isMoreQualifiedThan(T2)) 3537 return ImplicitConversionSequence::Worse; 3538 } 3539 } 3540 3541 // In Microsoft mode, prefer an integral conversion to a 3542 // floating-to-integral conversion if the integral conversion 3543 // is between types of the same size. 3544 // For example: 3545 // void f(float); 3546 // void f(int); 3547 // int main { 3548 // long a; 3549 // f(a); 3550 // } 3551 // Here, MSVC will call f(int) instead of generating a compile error 3552 // as clang will do in standard mode. 3553 if (S.getLangOpts().MicrosoftMode && 3554 SCS1.Second == ICK_Integral_Conversion && 3555 SCS2.Second == ICK_Floating_Integral && 3556 S.Context.getTypeSize(SCS1.getFromType()) == 3557 S.Context.getTypeSize(SCS1.getToType(2))) 3558 return ImplicitConversionSequence::Better; 3559 3560 return ImplicitConversionSequence::Indistinguishable; 3561 } 3562 3563 /// CompareQualificationConversions - Compares two standard conversion 3564 /// sequences to determine whether they can be ranked based on their 3565 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3566 ImplicitConversionSequence::CompareKind 3567 CompareQualificationConversions(Sema &S, 3568 const StandardConversionSequence& SCS1, 3569 const StandardConversionSequence& SCS2) { 3570 // C++ 13.3.3.2p3: 3571 // -- S1 and S2 differ only in their qualification conversion and 3572 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3573 // cv-qualification signature of type T1 is a proper subset of 3574 // the cv-qualification signature of type T2, and S1 is not the 3575 // deprecated string literal array-to-pointer conversion (4.2). 3576 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3577 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3578 return ImplicitConversionSequence::Indistinguishable; 3579 3580 // FIXME: the example in the standard doesn't use a qualification 3581 // conversion (!) 3582 QualType T1 = SCS1.getToType(2); 3583 QualType T2 = SCS2.getToType(2); 3584 T1 = S.Context.getCanonicalType(T1); 3585 T2 = S.Context.getCanonicalType(T2); 3586 Qualifiers T1Quals, T2Quals; 3587 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3588 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3589 3590 // If the types are the same, we won't learn anything by unwrapped 3591 // them. 3592 if (UnqualT1 == UnqualT2) 3593 return ImplicitConversionSequence::Indistinguishable; 3594 3595 // If the type is an array type, promote the element qualifiers to the type 3596 // for comparison. 3597 if (isa<ArrayType>(T1) && T1Quals) 3598 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3599 if (isa<ArrayType>(T2) && T2Quals) 3600 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3601 3602 ImplicitConversionSequence::CompareKind Result 3603 = ImplicitConversionSequence::Indistinguishable; 3604 3605 // Objective-C++ ARC: 3606 // Prefer qualification conversions not involving a change in lifetime 3607 // to qualification conversions that do not change lifetime. 3608 if (SCS1.QualificationIncludesObjCLifetime != 3609 SCS2.QualificationIncludesObjCLifetime) { 3610 Result = SCS1.QualificationIncludesObjCLifetime 3611 ? ImplicitConversionSequence::Worse 3612 : ImplicitConversionSequence::Better; 3613 } 3614 3615 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3616 // Within each iteration of the loop, we check the qualifiers to 3617 // determine if this still looks like a qualification 3618 // conversion. Then, if all is well, we unwrap one more level of 3619 // pointers or pointers-to-members and do it all again 3620 // until there are no more pointers or pointers-to-members left 3621 // to unwrap. This essentially mimics what 3622 // IsQualificationConversion does, but here we're checking for a 3623 // strict subset of qualifiers. 3624 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3625 // The qualifiers are the same, so this doesn't tell us anything 3626 // about how the sequences rank. 3627 ; 3628 else if (T2.isMoreQualifiedThan(T1)) { 3629 // T1 has fewer qualifiers, so it could be the better sequence. 3630 if (Result == ImplicitConversionSequence::Worse) 3631 // Neither has qualifiers that are a subset of the other's 3632 // qualifiers. 3633 return ImplicitConversionSequence::Indistinguishable; 3634 3635 Result = ImplicitConversionSequence::Better; 3636 } else if (T1.isMoreQualifiedThan(T2)) { 3637 // T2 has fewer qualifiers, so it could be the better sequence. 3638 if (Result == ImplicitConversionSequence::Better) 3639 // Neither has qualifiers that are a subset of the other's 3640 // qualifiers. 3641 return ImplicitConversionSequence::Indistinguishable; 3642 3643 Result = ImplicitConversionSequence::Worse; 3644 } else { 3645 // Qualifiers are disjoint. 3646 return ImplicitConversionSequence::Indistinguishable; 3647 } 3648 3649 // If the types after this point are equivalent, we're done. 3650 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3651 break; 3652 } 3653 3654 // Check that the winning standard conversion sequence isn't using 3655 // the deprecated string literal array to pointer conversion. 3656 switch (Result) { 3657 case ImplicitConversionSequence::Better: 3658 if (SCS1.DeprecatedStringLiteralToCharPtr) 3659 Result = ImplicitConversionSequence::Indistinguishable; 3660 break; 3661 3662 case ImplicitConversionSequence::Indistinguishable: 3663 break; 3664 3665 case ImplicitConversionSequence::Worse: 3666 if (SCS2.DeprecatedStringLiteralToCharPtr) 3667 Result = ImplicitConversionSequence::Indistinguishable; 3668 break; 3669 } 3670 3671 return Result; 3672 } 3673 3674 /// CompareDerivedToBaseConversions - Compares two standard conversion 3675 /// sequences to determine whether they can be ranked based on their 3676 /// various kinds of derived-to-base conversions (C++ 3677 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3678 /// conversions between Objective-C interface types. 3679 ImplicitConversionSequence::CompareKind 3680 CompareDerivedToBaseConversions(Sema &S, 3681 const StandardConversionSequence& SCS1, 3682 const StandardConversionSequence& SCS2) { 3683 QualType FromType1 = SCS1.getFromType(); 3684 QualType ToType1 = SCS1.getToType(1); 3685 QualType FromType2 = SCS2.getFromType(); 3686 QualType ToType2 = SCS2.getToType(1); 3687 3688 // Adjust the types we're converting from via the array-to-pointer 3689 // conversion, if we need to. 3690 if (SCS1.First == ICK_Array_To_Pointer) 3691 FromType1 = S.Context.getArrayDecayedType(FromType1); 3692 if (SCS2.First == ICK_Array_To_Pointer) 3693 FromType2 = S.Context.getArrayDecayedType(FromType2); 3694 3695 // Canonicalize all of the types. 3696 FromType1 = S.Context.getCanonicalType(FromType1); 3697 ToType1 = S.Context.getCanonicalType(ToType1); 3698 FromType2 = S.Context.getCanonicalType(FromType2); 3699 ToType2 = S.Context.getCanonicalType(ToType2); 3700 3701 // C++ [over.ics.rank]p4b3: 3702 // 3703 // If class B is derived directly or indirectly from class A and 3704 // class C is derived directly or indirectly from B, 3705 // 3706 // Compare based on pointer conversions. 3707 if (SCS1.Second == ICK_Pointer_Conversion && 3708 SCS2.Second == ICK_Pointer_Conversion && 3709 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3710 FromType1->isPointerType() && FromType2->isPointerType() && 3711 ToType1->isPointerType() && ToType2->isPointerType()) { 3712 QualType FromPointee1 3713 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3714 QualType ToPointee1 3715 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3716 QualType FromPointee2 3717 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3718 QualType ToPointee2 3719 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3720 3721 // -- conversion of C* to B* is better than conversion of C* to A*, 3722 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3723 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3724 return ImplicitConversionSequence::Better; 3725 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3726 return ImplicitConversionSequence::Worse; 3727 } 3728 3729 // -- conversion of B* to A* is better than conversion of C* to A*, 3730 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3731 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3732 return ImplicitConversionSequence::Better; 3733 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3734 return ImplicitConversionSequence::Worse; 3735 } 3736 } else if (SCS1.Second == ICK_Pointer_Conversion && 3737 SCS2.Second == ICK_Pointer_Conversion) { 3738 const ObjCObjectPointerType *FromPtr1 3739 = FromType1->getAs<ObjCObjectPointerType>(); 3740 const ObjCObjectPointerType *FromPtr2 3741 = FromType2->getAs<ObjCObjectPointerType>(); 3742 const ObjCObjectPointerType *ToPtr1 3743 = ToType1->getAs<ObjCObjectPointerType>(); 3744 const ObjCObjectPointerType *ToPtr2 3745 = ToType2->getAs<ObjCObjectPointerType>(); 3746 3747 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3748 // Apply the same conversion ranking rules for Objective-C pointer types 3749 // that we do for C++ pointers to class types. However, we employ the 3750 // Objective-C pseudo-subtyping relationship used for assignment of 3751 // Objective-C pointer types. 3752 bool FromAssignLeft 3753 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3754 bool FromAssignRight 3755 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3756 bool ToAssignLeft 3757 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3758 bool ToAssignRight 3759 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3760 3761 // A conversion to an a non-id object pointer type or qualified 'id' 3762 // type is better than a conversion to 'id'. 3763 if (ToPtr1->isObjCIdType() && 3764 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3765 return ImplicitConversionSequence::Worse; 3766 if (ToPtr2->isObjCIdType() && 3767 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3768 return ImplicitConversionSequence::Better; 3769 3770 // A conversion to a non-id object pointer type is better than a 3771 // conversion to a qualified 'id' type 3772 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3773 return ImplicitConversionSequence::Worse; 3774 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3775 return ImplicitConversionSequence::Better; 3776 3777 // A conversion to an a non-Class object pointer type or qualified 'Class' 3778 // type is better than a conversion to 'Class'. 3779 if (ToPtr1->isObjCClassType() && 3780 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3781 return ImplicitConversionSequence::Worse; 3782 if (ToPtr2->isObjCClassType() && 3783 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3784 return ImplicitConversionSequence::Better; 3785 3786 // A conversion to a non-Class object pointer type is better than a 3787 // conversion to a qualified 'Class' type. 3788 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3789 return ImplicitConversionSequence::Worse; 3790 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3791 return ImplicitConversionSequence::Better; 3792 3793 // -- "conversion of C* to B* is better than conversion of C* to A*," 3794 if (S.Context.hasSameType(FromType1, FromType2) && 3795 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3796 (ToAssignLeft != ToAssignRight)) 3797 return ToAssignLeft? ImplicitConversionSequence::Worse 3798 : ImplicitConversionSequence::Better; 3799 3800 // -- "conversion of B* to A* is better than conversion of C* to A*," 3801 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3802 (FromAssignLeft != FromAssignRight)) 3803 return FromAssignLeft? ImplicitConversionSequence::Better 3804 : ImplicitConversionSequence::Worse; 3805 } 3806 } 3807 3808 // Ranking of member-pointer types. 3809 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3810 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3811 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3812 const MemberPointerType * FromMemPointer1 = 3813 FromType1->getAs<MemberPointerType>(); 3814 const MemberPointerType * ToMemPointer1 = 3815 ToType1->getAs<MemberPointerType>(); 3816 const MemberPointerType * FromMemPointer2 = 3817 FromType2->getAs<MemberPointerType>(); 3818 const MemberPointerType * ToMemPointer2 = 3819 ToType2->getAs<MemberPointerType>(); 3820 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3821 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3822 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3823 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3824 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3825 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3826 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3827 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3828 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3829 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3830 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3831 return ImplicitConversionSequence::Worse; 3832 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3833 return ImplicitConversionSequence::Better; 3834 } 3835 // conversion of B::* to C::* is better than conversion of A::* to C::* 3836 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3837 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3838 return ImplicitConversionSequence::Better; 3839 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3840 return ImplicitConversionSequence::Worse; 3841 } 3842 } 3843 3844 if (SCS1.Second == ICK_Derived_To_Base) { 3845 // -- conversion of C to B is better than conversion of C to A, 3846 // -- binding of an expression of type C to a reference of type 3847 // B& is better than binding an expression of type C to a 3848 // reference of type A&, 3849 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3850 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3851 if (S.IsDerivedFrom(ToType1, ToType2)) 3852 return ImplicitConversionSequence::Better; 3853 else if (S.IsDerivedFrom(ToType2, ToType1)) 3854 return ImplicitConversionSequence::Worse; 3855 } 3856 3857 // -- conversion of B to A is better than conversion of C to A. 3858 // -- binding of an expression of type B to a reference of type 3859 // A& is better than binding an expression of type C to a 3860 // reference of type A&, 3861 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3862 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3863 if (S.IsDerivedFrom(FromType2, FromType1)) 3864 return ImplicitConversionSequence::Better; 3865 else if (S.IsDerivedFrom(FromType1, FromType2)) 3866 return ImplicitConversionSequence::Worse; 3867 } 3868 } 3869 3870 return ImplicitConversionSequence::Indistinguishable; 3871 } 3872 3873 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 3874 /// determine whether they are reference-related, 3875 /// reference-compatible, reference-compatible with added 3876 /// qualification, or incompatible, for use in C++ initialization by 3877 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3878 /// type, and the first type (T1) is the pointee type of the reference 3879 /// type being initialized. 3880 Sema::ReferenceCompareResult 3881 Sema::CompareReferenceRelationship(SourceLocation Loc, 3882 QualType OrigT1, QualType OrigT2, 3883 bool &DerivedToBase, 3884 bool &ObjCConversion, 3885 bool &ObjCLifetimeConversion) { 3886 assert(!OrigT1->isReferenceType() && 3887 "T1 must be the pointee type of the reference type"); 3888 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3889 3890 QualType T1 = Context.getCanonicalType(OrigT1); 3891 QualType T2 = Context.getCanonicalType(OrigT2); 3892 Qualifiers T1Quals, T2Quals; 3893 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3894 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3895 3896 // C++ [dcl.init.ref]p4: 3897 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3898 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3899 // T1 is a base class of T2. 3900 DerivedToBase = false; 3901 ObjCConversion = false; 3902 ObjCLifetimeConversion = false; 3903 if (UnqualT1 == UnqualT2) { 3904 // Nothing to do. 3905 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 3906 IsDerivedFrom(UnqualT2, UnqualT1)) 3907 DerivedToBase = true; 3908 else if (UnqualT1->isObjCObjectOrInterfaceType() && 3909 UnqualT2->isObjCObjectOrInterfaceType() && 3910 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 3911 ObjCConversion = true; 3912 else 3913 return Ref_Incompatible; 3914 3915 // At this point, we know that T1 and T2 are reference-related (at 3916 // least). 3917 3918 // If the type is an array type, promote the element qualifiers to the type 3919 // for comparison. 3920 if (isa<ArrayType>(T1) && T1Quals) 3921 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 3922 if (isa<ArrayType>(T2) && T2Quals) 3923 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 3924 3925 // C++ [dcl.init.ref]p4: 3926 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 3927 // reference-related to T2 and cv1 is the same cv-qualification 3928 // as, or greater cv-qualification than, cv2. For purposes of 3929 // overload resolution, cases for which cv1 is greater 3930 // cv-qualification than cv2 are identified as 3931 // reference-compatible with added qualification (see 13.3.3.2). 3932 // 3933 // Note that we also require equivalence of Objective-C GC and address-space 3934 // qualifiers when performing these computations, so that e.g., an int in 3935 // address space 1 is not reference-compatible with an int in address 3936 // space 2. 3937 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 3938 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 3939 T1Quals.removeObjCLifetime(); 3940 T2Quals.removeObjCLifetime(); 3941 ObjCLifetimeConversion = true; 3942 } 3943 3944 if (T1Quals == T2Quals) 3945 return Ref_Compatible; 3946 else if (T1Quals.compatiblyIncludes(T2Quals)) 3947 return Ref_Compatible_With_Added_Qualification; 3948 else 3949 return Ref_Related; 3950 } 3951 3952 /// \brief Look for a user-defined conversion to an value reference-compatible 3953 /// with DeclType. Return true if something definite is found. 3954 static bool 3955 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 3956 QualType DeclType, SourceLocation DeclLoc, 3957 Expr *Init, QualType T2, bool AllowRvalues, 3958 bool AllowExplicit) { 3959 assert(T2->isRecordType() && "Can only find conversions of record types."); 3960 CXXRecordDecl *T2RecordDecl 3961 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 3962 3963 OverloadCandidateSet CandidateSet(DeclLoc); 3964 std::pair<CXXRecordDecl::conversion_iterator, 3965 CXXRecordDecl::conversion_iterator> 3966 Conversions = T2RecordDecl->getVisibleConversionFunctions(); 3967 for (CXXRecordDecl::conversion_iterator 3968 I = Conversions.first, E = Conversions.second; I != E; ++I) { 3969 NamedDecl *D = *I; 3970 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 3971 if (isa<UsingShadowDecl>(D)) 3972 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3973 3974 FunctionTemplateDecl *ConvTemplate 3975 = dyn_cast<FunctionTemplateDecl>(D); 3976 CXXConversionDecl *Conv; 3977 if (ConvTemplate) 3978 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3979 else 3980 Conv = cast<CXXConversionDecl>(D); 3981 3982 // If this is an explicit conversion, and we're not allowed to consider 3983 // explicit conversions, skip it. 3984 if (!AllowExplicit && Conv->isExplicit()) 3985 continue; 3986 3987 if (AllowRvalues) { 3988 bool DerivedToBase = false; 3989 bool ObjCConversion = false; 3990 bool ObjCLifetimeConversion = false; 3991 3992 // If we are initializing an rvalue reference, don't permit conversion 3993 // functions that return lvalues. 3994 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 3995 const ReferenceType *RefType 3996 = Conv->getConversionType()->getAs<LValueReferenceType>(); 3997 if (RefType && !RefType->getPointeeType()->isFunctionType()) 3998 continue; 3999 } 4000 4001 if (!ConvTemplate && 4002 S.CompareReferenceRelationship( 4003 DeclLoc, 4004 Conv->getConversionType().getNonReferenceType() 4005 .getUnqualifiedType(), 4006 DeclType.getNonReferenceType().getUnqualifiedType(), 4007 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4008 Sema::Ref_Incompatible) 4009 continue; 4010 } else { 4011 // If the conversion function doesn't return a reference type, 4012 // it can't be considered for this conversion. An rvalue reference 4013 // is only acceptable if its referencee is a function type. 4014 4015 const ReferenceType *RefType = 4016 Conv->getConversionType()->getAs<ReferenceType>(); 4017 if (!RefType || 4018 (!RefType->isLValueReferenceType() && 4019 !RefType->getPointeeType()->isFunctionType())) 4020 continue; 4021 } 4022 4023 if (ConvTemplate) 4024 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4025 Init, DeclType, CandidateSet); 4026 else 4027 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4028 DeclType, CandidateSet); 4029 } 4030 4031 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4032 4033 OverloadCandidateSet::iterator Best; 4034 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4035 case OR_Success: 4036 // C++ [over.ics.ref]p1: 4037 // 4038 // [...] If the parameter binds directly to the result of 4039 // applying a conversion function to the argument 4040 // expression, the implicit conversion sequence is a 4041 // user-defined conversion sequence (13.3.3.1.2), with the 4042 // second standard conversion sequence either an identity 4043 // conversion or, if the conversion function returns an 4044 // entity of a type that is a derived class of the parameter 4045 // type, a derived-to-base Conversion. 4046 if (!Best->FinalConversion.DirectBinding) 4047 return false; 4048 4049 ICS.setUserDefined(); 4050 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4051 ICS.UserDefined.After = Best->FinalConversion; 4052 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4053 ICS.UserDefined.ConversionFunction = Best->Function; 4054 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4055 ICS.UserDefined.EllipsisConversion = false; 4056 assert(ICS.UserDefined.After.ReferenceBinding && 4057 ICS.UserDefined.After.DirectBinding && 4058 "Expected a direct reference binding!"); 4059 return true; 4060 4061 case OR_Ambiguous: 4062 ICS.setAmbiguous(); 4063 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4064 Cand != CandidateSet.end(); ++Cand) 4065 if (Cand->Viable) 4066 ICS.Ambiguous.addConversion(Cand->Function); 4067 return true; 4068 4069 case OR_No_Viable_Function: 4070 case OR_Deleted: 4071 // There was no suitable conversion, or we found a deleted 4072 // conversion; continue with other checks. 4073 return false; 4074 } 4075 4076 llvm_unreachable("Invalid OverloadResult!"); 4077 } 4078 4079 /// \brief Compute an implicit conversion sequence for reference 4080 /// initialization. 4081 static ImplicitConversionSequence 4082 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4083 SourceLocation DeclLoc, 4084 bool SuppressUserConversions, 4085 bool AllowExplicit) { 4086 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4087 4088 // Most paths end in a failed conversion. 4089 ImplicitConversionSequence ICS; 4090 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4091 4092 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4093 QualType T2 = Init->getType(); 4094 4095 // If the initializer is the address of an overloaded function, try 4096 // to resolve the overloaded function. If all goes well, T2 is the 4097 // type of the resulting function. 4098 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4099 DeclAccessPair Found; 4100 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4101 false, Found)) 4102 T2 = Fn->getType(); 4103 } 4104 4105 // Compute some basic properties of the types and the initializer. 4106 bool isRValRef = DeclType->isRValueReferenceType(); 4107 bool DerivedToBase = false; 4108 bool ObjCConversion = false; 4109 bool ObjCLifetimeConversion = false; 4110 Expr::Classification InitCategory = Init->Classify(S.Context); 4111 Sema::ReferenceCompareResult RefRelationship 4112 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4113 ObjCConversion, ObjCLifetimeConversion); 4114 4115 4116 // C++0x [dcl.init.ref]p5: 4117 // A reference to type "cv1 T1" is initialized by an expression 4118 // of type "cv2 T2" as follows: 4119 4120 // -- If reference is an lvalue reference and the initializer expression 4121 if (!isRValRef) { 4122 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4123 // reference-compatible with "cv2 T2," or 4124 // 4125 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4126 if (InitCategory.isLValue() && 4127 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4128 // C++ [over.ics.ref]p1: 4129 // When a parameter of reference type binds directly (8.5.3) 4130 // to an argument expression, the implicit conversion sequence 4131 // is the identity conversion, unless the argument expression 4132 // has a type that is a derived class of the parameter type, 4133 // in which case the implicit conversion sequence is a 4134 // derived-to-base Conversion (13.3.3.1). 4135 ICS.setStandard(); 4136 ICS.Standard.First = ICK_Identity; 4137 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4138 : ObjCConversion? ICK_Compatible_Conversion 4139 : ICK_Identity; 4140 ICS.Standard.Third = ICK_Identity; 4141 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4142 ICS.Standard.setToType(0, T2); 4143 ICS.Standard.setToType(1, T1); 4144 ICS.Standard.setToType(2, T1); 4145 ICS.Standard.ReferenceBinding = true; 4146 ICS.Standard.DirectBinding = true; 4147 ICS.Standard.IsLvalueReference = !isRValRef; 4148 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4149 ICS.Standard.BindsToRvalue = false; 4150 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4151 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4152 ICS.Standard.CopyConstructor = 0; 4153 4154 // Nothing more to do: the inaccessibility/ambiguity check for 4155 // derived-to-base conversions is suppressed when we're 4156 // computing the implicit conversion sequence (C++ 4157 // [over.best.ics]p2). 4158 return ICS; 4159 } 4160 4161 // -- has a class type (i.e., T2 is a class type), where T1 is 4162 // not reference-related to T2, and can be implicitly 4163 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4164 // is reference-compatible with "cv3 T3" 92) (this 4165 // conversion is selected by enumerating the applicable 4166 // conversion functions (13.3.1.6) and choosing the best 4167 // one through overload resolution (13.3)), 4168 if (!SuppressUserConversions && T2->isRecordType() && 4169 !S.RequireCompleteType(DeclLoc, T2, 0) && 4170 RefRelationship == Sema::Ref_Incompatible) { 4171 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4172 Init, T2, /*AllowRvalues=*/false, 4173 AllowExplicit)) 4174 return ICS; 4175 } 4176 } 4177 4178 // -- Otherwise, the reference shall be an lvalue reference to a 4179 // non-volatile const type (i.e., cv1 shall be const), or the reference 4180 // shall be an rvalue reference. 4181 // 4182 // We actually handle one oddity of C++ [over.ics.ref] at this 4183 // point, which is that, due to p2 (which short-circuits reference 4184 // binding by only attempting a simple conversion for non-direct 4185 // bindings) and p3's strange wording, we allow a const volatile 4186 // reference to bind to an rvalue. Hence the check for the presence 4187 // of "const" rather than checking for "const" being the only 4188 // qualifier. 4189 // This is also the point where rvalue references and lvalue inits no longer 4190 // go together. 4191 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4192 return ICS; 4193 4194 // -- If the initializer expression 4195 // 4196 // -- is an xvalue, class prvalue, array prvalue or function 4197 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4198 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4199 (InitCategory.isXValue() || 4200 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4201 (InitCategory.isLValue() && T2->isFunctionType()))) { 4202 ICS.setStandard(); 4203 ICS.Standard.First = ICK_Identity; 4204 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4205 : ObjCConversion? ICK_Compatible_Conversion 4206 : ICK_Identity; 4207 ICS.Standard.Third = ICK_Identity; 4208 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4209 ICS.Standard.setToType(0, T2); 4210 ICS.Standard.setToType(1, T1); 4211 ICS.Standard.setToType(2, T1); 4212 ICS.Standard.ReferenceBinding = true; 4213 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4214 // binding unless we're binding to a class prvalue. 4215 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4216 // allow the use of rvalue references in C++98/03 for the benefit of 4217 // standard library implementors; therefore, we need the xvalue check here. 4218 ICS.Standard.DirectBinding = 4219 S.getLangOpts().CPlusPlus0x || 4220 (InitCategory.isPRValue() && !T2->isRecordType()); 4221 ICS.Standard.IsLvalueReference = !isRValRef; 4222 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4223 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4224 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4225 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4226 ICS.Standard.CopyConstructor = 0; 4227 return ICS; 4228 } 4229 4230 // -- has a class type (i.e., T2 is a class type), where T1 is not 4231 // reference-related to T2, and can be implicitly converted to 4232 // an xvalue, class prvalue, or function lvalue of type 4233 // "cv3 T3", where "cv1 T1" is reference-compatible with 4234 // "cv3 T3", 4235 // 4236 // then the reference is bound to the value of the initializer 4237 // expression in the first case and to the result of the conversion 4238 // in the second case (or, in either case, to an appropriate base 4239 // class subobject). 4240 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4241 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4242 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4243 Init, T2, /*AllowRvalues=*/true, 4244 AllowExplicit)) { 4245 // In the second case, if the reference is an rvalue reference 4246 // and the second standard conversion sequence of the 4247 // user-defined conversion sequence includes an lvalue-to-rvalue 4248 // conversion, the program is ill-formed. 4249 if (ICS.isUserDefined() && isRValRef && 4250 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4251 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4252 4253 return ICS; 4254 } 4255 4256 // -- Otherwise, a temporary of type "cv1 T1" is created and 4257 // initialized from the initializer expression using the 4258 // rules for a non-reference copy initialization (8.5). The 4259 // reference is then bound to the temporary. If T1 is 4260 // reference-related to T2, cv1 must be the same 4261 // cv-qualification as, or greater cv-qualification than, 4262 // cv2; otherwise, the program is ill-formed. 4263 if (RefRelationship == Sema::Ref_Related) { 4264 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4265 // we would be reference-compatible or reference-compatible with 4266 // added qualification. But that wasn't the case, so the reference 4267 // initialization fails. 4268 // 4269 // Note that we only want to check address spaces and cvr-qualifiers here. 4270 // ObjC GC and lifetime qualifiers aren't important. 4271 Qualifiers T1Quals = T1.getQualifiers(); 4272 Qualifiers T2Quals = T2.getQualifiers(); 4273 T1Quals.removeObjCGCAttr(); 4274 T1Quals.removeObjCLifetime(); 4275 T2Quals.removeObjCGCAttr(); 4276 T2Quals.removeObjCLifetime(); 4277 if (!T1Quals.compatiblyIncludes(T2Quals)) 4278 return ICS; 4279 } 4280 4281 // If at least one of the types is a class type, the types are not 4282 // related, and we aren't allowed any user conversions, the 4283 // reference binding fails. This case is important for breaking 4284 // recursion, since TryImplicitConversion below will attempt to 4285 // create a temporary through the use of a copy constructor. 4286 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4287 (T1->isRecordType() || T2->isRecordType())) 4288 return ICS; 4289 4290 // If T1 is reference-related to T2 and the reference is an rvalue 4291 // reference, the initializer expression shall not be an lvalue. 4292 if (RefRelationship >= Sema::Ref_Related && 4293 isRValRef && Init->Classify(S.Context).isLValue()) 4294 return ICS; 4295 4296 // C++ [over.ics.ref]p2: 4297 // When a parameter of reference type is not bound directly to 4298 // an argument expression, the conversion sequence is the one 4299 // required to convert the argument expression to the 4300 // underlying type of the reference according to 4301 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4302 // to copy-initializing a temporary of the underlying type with 4303 // the argument expression. Any difference in top-level 4304 // cv-qualification is subsumed by the initialization itself 4305 // and does not constitute a conversion. 4306 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4307 /*AllowExplicit=*/false, 4308 /*InOverloadResolution=*/false, 4309 /*CStyle=*/false, 4310 /*AllowObjCWritebackConversion=*/false); 4311 4312 // Of course, that's still a reference binding. 4313 if (ICS.isStandard()) { 4314 ICS.Standard.ReferenceBinding = true; 4315 ICS.Standard.IsLvalueReference = !isRValRef; 4316 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4317 ICS.Standard.BindsToRvalue = true; 4318 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4319 ICS.Standard.ObjCLifetimeConversionBinding = false; 4320 } else if (ICS.isUserDefined()) { 4321 // Don't allow rvalue references to bind to lvalues. 4322 if (DeclType->isRValueReferenceType()) { 4323 if (const ReferenceType *RefType 4324 = ICS.UserDefined.ConversionFunction->getResultType() 4325 ->getAs<LValueReferenceType>()) { 4326 if (!RefType->getPointeeType()->isFunctionType()) { 4327 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, 4328 DeclType); 4329 return ICS; 4330 } 4331 } 4332 } 4333 4334 ICS.UserDefined.After.ReferenceBinding = true; 4335 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4336 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType(); 4337 ICS.UserDefined.After.BindsToRvalue = true; 4338 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4339 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4340 } 4341 4342 return ICS; 4343 } 4344 4345 static ImplicitConversionSequence 4346 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4347 bool SuppressUserConversions, 4348 bool InOverloadResolution, 4349 bool AllowObjCWritebackConversion, 4350 bool AllowExplicit = false); 4351 4352 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4353 /// initializer list From. 4354 static ImplicitConversionSequence 4355 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4356 bool SuppressUserConversions, 4357 bool InOverloadResolution, 4358 bool AllowObjCWritebackConversion) { 4359 // C++11 [over.ics.list]p1: 4360 // When an argument is an initializer list, it is not an expression and 4361 // special rules apply for converting it to a parameter type. 4362 4363 ImplicitConversionSequence Result; 4364 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4365 Result.setListInitializationSequence(); 4366 4367 // We need a complete type for what follows. Incomplete types can never be 4368 // initialized from init lists. 4369 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4370 return Result; 4371 4372 // C++11 [over.ics.list]p2: 4373 // If the parameter type is std::initializer_list<X> or "array of X" and 4374 // all the elements can be implicitly converted to X, the implicit 4375 // conversion sequence is the worst conversion necessary to convert an 4376 // element of the list to X. 4377 bool toStdInitializerList = false; 4378 QualType X; 4379 if (ToType->isArrayType()) 4380 X = S.Context.getBaseElementType(ToType); 4381 else 4382 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4383 if (!X.isNull()) { 4384 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4385 Expr *Init = From->getInit(i); 4386 ImplicitConversionSequence ICS = 4387 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4388 InOverloadResolution, 4389 AllowObjCWritebackConversion); 4390 // If a single element isn't convertible, fail. 4391 if (ICS.isBad()) { 4392 Result = ICS; 4393 break; 4394 } 4395 // Otherwise, look for the worst conversion. 4396 if (Result.isBad() || 4397 CompareImplicitConversionSequences(S, ICS, Result) == 4398 ImplicitConversionSequence::Worse) 4399 Result = ICS; 4400 } 4401 4402 // For an empty list, we won't have computed any conversion sequence. 4403 // Introduce the identity conversion sequence. 4404 if (From->getNumInits() == 0) { 4405 Result.setStandard(); 4406 Result.Standard.setAsIdentityConversion(); 4407 Result.Standard.setFromType(ToType); 4408 Result.Standard.setAllToTypes(ToType); 4409 } 4410 4411 Result.setListInitializationSequence(); 4412 Result.setStdInitializerListElement(toStdInitializerList); 4413 return Result; 4414 } 4415 4416 // C++11 [over.ics.list]p3: 4417 // Otherwise, if the parameter is a non-aggregate class X and overload 4418 // resolution chooses a single best constructor [...] the implicit 4419 // conversion sequence is a user-defined conversion sequence. If multiple 4420 // constructors are viable but none is better than the others, the 4421 // implicit conversion sequence is a user-defined conversion sequence. 4422 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4423 // This function can deal with initializer lists. 4424 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4425 /*AllowExplicit=*/false, 4426 InOverloadResolution, /*CStyle=*/false, 4427 AllowObjCWritebackConversion); 4428 Result.setListInitializationSequence(); 4429 return Result; 4430 } 4431 4432 // C++11 [over.ics.list]p4: 4433 // Otherwise, if the parameter has an aggregate type which can be 4434 // initialized from the initializer list [...] the implicit conversion 4435 // sequence is a user-defined conversion sequence. 4436 if (ToType->isAggregateType()) { 4437 // Type is an aggregate, argument is an init list. At this point it comes 4438 // down to checking whether the initialization works. 4439 // FIXME: Find out whether this parameter is consumed or not. 4440 InitializedEntity Entity = 4441 InitializedEntity::InitializeParameter(S.Context, ToType, 4442 /*Consumed=*/false); 4443 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) { 4444 Result.setUserDefined(); 4445 Result.UserDefined.Before.setAsIdentityConversion(); 4446 // Initializer lists don't have a type. 4447 Result.UserDefined.Before.setFromType(QualType()); 4448 Result.UserDefined.Before.setAllToTypes(QualType()); 4449 4450 Result.UserDefined.After.setAsIdentityConversion(); 4451 Result.UserDefined.After.setFromType(ToType); 4452 Result.UserDefined.After.setAllToTypes(ToType); 4453 Result.UserDefined.ConversionFunction = 0; 4454 } 4455 return Result; 4456 } 4457 4458 // C++11 [over.ics.list]p5: 4459 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4460 if (ToType->isReferenceType()) { 4461 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4462 // mention initializer lists in any way. So we go by what list- 4463 // initialization would do and try to extrapolate from that. 4464 4465 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4466 4467 // If the initializer list has a single element that is reference-related 4468 // to the parameter type, we initialize the reference from that. 4469 if (From->getNumInits() == 1) { 4470 Expr *Init = From->getInit(0); 4471 4472 QualType T2 = Init->getType(); 4473 4474 // If the initializer is the address of an overloaded function, try 4475 // to resolve the overloaded function. If all goes well, T2 is the 4476 // type of the resulting function. 4477 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4478 DeclAccessPair Found; 4479 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4480 Init, ToType, false, Found)) 4481 T2 = Fn->getType(); 4482 } 4483 4484 // Compute some basic properties of the types and the initializer. 4485 bool dummy1 = false; 4486 bool dummy2 = false; 4487 bool dummy3 = false; 4488 Sema::ReferenceCompareResult RefRelationship 4489 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4490 dummy2, dummy3); 4491 4492 if (RefRelationship >= Sema::Ref_Related) 4493 return TryReferenceInit(S, Init, ToType, 4494 /*FIXME:*/From->getLocStart(), 4495 SuppressUserConversions, 4496 /*AllowExplicit=*/false); 4497 } 4498 4499 // Otherwise, we bind the reference to a temporary created from the 4500 // initializer list. 4501 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4502 InOverloadResolution, 4503 AllowObjCWritebackConversion); 4504 if (Result.isFailure()) 4505 return Result; 4506 assert(!Result.isEllipsis() && 4507 "Sub-initialization cannot result in ellipsis conversion."); 4508 4509 // Can we even bind to a temporary? 4510 if (ToType->isRValueReferenceType() || 4511 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4512 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4513 Result.UserDefined.After; 4514 SCS.ReferenceBinding = true; 4515 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4516 SCS.BindsToRvalue = true; 4517 SCS.BindsToFunctionLvalue = false; 4518 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4519 SCS.ObjCLifetimeConversionBinding = false; 4520 } else 4521 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4522 From, ToType); 4523 return Result; 4524 } 4525 4526 // C++11 [over.ics.list]p6: 4527 // Otherwise, if the parameter type is not a class: 4528 if (!ToType->isRecordType()) { 4529 // - if the initializer list has one element, the implicit conversion 4530 // sequence is the one required to convert the element to the 4531 // parameter type. 4532 unsigned NumInits = From->getNumInits(); 4533 if (NumInits == 1) 4534 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4535 SuppressUserConversions, 4536 InOverloadResolution, 4537 AllowObjCWritebackConversion); 4538 // - if the initializer list has no elements, the implicit conversion 4539 // sequence is the identity conversion. 4540 else if (NumInits == 0) { 4541 Result.setStandard(); 4542 Result.Standard.setAsIdentityConversion(); 4543 Result.Standard.setFromType(ToType); 4544 Result.Standard.setAllToTypes(ToType); 4545 } 4546 Result.setListInitializationSequence(); 4547 return Result; 4548 } 4549 4550 // C++11 [over.ics.list]p7: 4551 // In all cases other than those enumerated above, no conversion is possible 4552 return Result; 4553 } 4554 4555 /// TryCopyInitialization - Try to copy-initialize a value of type 4556 /// ToType from the expression From. Return the implicit conversion 4557 /// sequence required to pass this argument, which may be a bad 4558 /// conversion sequence (meaning that the argument cannot be passed to 4559 /// a parameter of this type). If @p SuppressUserConversions, then we 4560 /// do not permit any user-defined conversion sequences. 4561 static ImplicitConversionSequence 4562 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4563 bool SuppressUserConversions, 4564 bool InOverloadResolution, 4565 bool AllowObjCWritebackConversion, 4566 bool AllowExplicit) { 4567 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4568 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4569 InOverloadResolution,AllowObjCWritebackConversion); 4570 4571 if (ToType->isReferenceType()) 4572 return TryReferenceInit(S, From, ToType, 4573 /*FIXME:*/From->getLocStart(), 4574 SuppressUserConversions, 4575 AllowExplicit); 4576 4577 return TryImplicitConversion(S, From, ToType, 4578 SuppressUserConversions, 4579 /*AllowExplicit=*/false, 4580 InOverloadResolution, 4581 /*CStyle=*/false, 4582 AllowObjCWritebackConversion); 4583 } 4584 4585 static bool TryCopyInitialization(const CanQualType FromQTy, 4586 const CanQualType ToQTy, 4587 Sema &S, 4588 SourceLocation Loc, 4589 ExprValueKind FromVK) { 4590 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4591 ImplicitConversionSequence ICS = 4592 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4593 4594 return !ICS.isBad(); 4595 } 4596 4597 /// TryObjectArgumentInitialization - Try to initialize the object 4598 /// parameter of the given member function (@c Method) from the 4599 /// expression @p From. 4600 static ImplicitConversionSequence 4601 TryObjectArgumentInitialization(Sema &S, QualType OrigFromType, 4602 Expr::Classification FromClassification, 4603 CXXMethodDecl *Method, 4604 CXXRecordDecl *ActingContext) { 4605 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4606 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4607 // const volatile object. 4608 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4609 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4610 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4611 4612 // Set up the conversion sequence as a "bad" conversion, to allow us 4613 // to exit early. 4614 ImplicitConversionSequence ICS; 4615 4616 // We need to have an object of class type. 4617 QualType FromType = OrigFromType; 4618 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4619 FromType = PT->getPointeeType(); 4620 4621 // When we had a pointer, it's implicitly dereferenced, so we 4622 // better have an lvalue. 4623 assert(FromClassification.isLValue()); 4624 } 4625 4626 assert(FromType->isRecordType()); 4627 4628 // C++0x [over.match.funcs]p4: 4629 // For non-static member functions, the type of the implicit object 4630 // parameter is 4631 // 4632 // - "lvalue reference to cv X" for functions declared without a 4633 // ref-qualifier or with the & ref-qualifier 4634 // - "rvalue reference to cv X" for functions declared with the && 4635 // ref-qualifier 4636 // 4637 // where X is the class of which the function is a member and cv is the 4638 // cv-qualification on the member function declaration. 4639 // 4640 // However, when finding an implicit conversion sequence for the argument, we 4641 // are not allowed to create temporaries or perform user-defined conversions 4642 // (C++ [over.match.funcs]p5). We perform a simplified version of 4643 // reference binding here, that allows class rvalues to bind to 4644 // non-constant references. 4645 4646 // First check the qualifiers. 4647 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4648 if (ImplicitParamType.getCVRQualifiers() 4649 != FromTypeCanon.getLocalCVRQualifiers() && 4650 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4651 ICS.setBad(BadConversionSequence::bad_qualifiers, 4652 OrigFromType, ImplicitParamType); 4653 return ICS; 4654 } 4655 4656 // Check that we have either the same type or a derived type. It 4657 // affects the conversion rank. 4658 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4659 ImplicitConversionKind SecondKind; 4660 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4661 SecondKind = ICK_Identity; 4662 } else if (S.IsDerivedFrom(FromType, ClassType)) 4663 SecondKind = ICK_Derived_To_Base; 4664 else { 4665 ICS.setBad(BadConversionSequence::unrelated_class, 4666 FromType, ImplicitParamType); 4667 return ICS; 4668 } 4669 4670 // Check the ref-qualifier. 4671 switch (Method->getRefQualifier()) { 4672 case RQ_None: 4673 // Do nothing; we don't care about lvalueness or rvalueness. 4674 break; 4675 4676 case RQ_LValue: 4677 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4678 // non-const lvalue reference cannot bind to an rvalue 4679 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4680 ImplicitParamType); 4681 return ICS; 4682 } 4683 break; 4684 4685 case RQ_RValue: 4686 if (!FromClassification.isRValue()) { 4687 // rvalue reference cannot bind to an lvalue 4688 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4689 ImplicitParamType); 4690 return ICS; 4691 } 4692 break; 4693 } 4694 4695 // Success. Mark this as a reference binding. 4696 ICS.setStandard(); 4697 ICS.Standard.setAsIdentityConversion(); 4698 ICS.Standard.Second = SecondKind; 4699 ICS.Standard.setFromType(FromType); 4700 ICS.Standard.setAllToTypes(ImplicitParamType); 4701 ICS.Standard.ReferenceBinding = true; 4702 ICS.Standard.DirectBinding = true; 4703 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4704 ICS.Standard.BindsToFunctionLvalue = false; 4705 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4706 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4707 = (Method->getRefQualifier() == RQ_None); 4708 return ICS; 4709 } 4710 4711 /// PerformObjectArgumentInitialization - Perform initialization of 4712 /// the implicit object parameter for the given Method with the given 4713 /// expression. 4714 ExprResult 4715 Sema::PerformObjectArgumentInitialization(Expr *From, 4716 NestedNameSpecifier *Qualifier, 4717 NamedDecl *FoundDecl, 4718 CXXMethodDecl *Method) { 4719 QualType FromRecordType, DestType; 4720 QualType ImplicitParamRecordType = 4721 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4722 4723 Expr::Classification FromClassification; 4724 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4725 FromRecordType = PT->getPointeeType(); 4726 DestType = Method->getThisType(Context); 4727 FromClassification = Expr::Classification::makeSimpleLValue(); 4728 } else { 4729 FromRecordType = From->getType(); 4730 DestType = ImplicitParamRecordType; 4731 FromClassification = From->Classify(Context); 4732 } 4733 4734 // Note that we always use the true parent context when performing 4735 // the actual argument initialization. 4736 ImplicitConversionSequence ICS 4737 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification, 4738 Method, Method->getParent()); 4739 if (ICS.isBad()) { 4740 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4741 Qualifiers FromQs = FromRecordType.getQualifiers(); 4742 Qualifiers ToQs = DestType.getQualifiers(); 4743 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4744 if (CVR) { 4745 Diag(From->getLocStart(), 4746 diag::err_member_function_call_bad_cvr) 4747 << Method->getDeclName() << FromRecordType << (CVR - 1) 4748 << From->getSourceRange(); 4749 Diag(Method->getLocation(), diag::note_previous_decl) 4750 << Method->getDeclName(); 4751 return ExprError(); 4752 } 4753 } 4754 4755 return Diag(From->getLocStart(), 4756 diag::err_implicit_object_parameter_init) 4757 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4758 } 4759 4760 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4761 ExprResult FromRes = 4762 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4763 if (FromRes.isInvalid()) 4764 return ExprError(); 4765 From = FromRes.take(); 4766 } 4767 4768 if (!Context.hasSameType(From->getType(), DestType)) 4769 From = ImpCastExprToType(From, DestType, CK_NoOp, 4770 From->getValueKind()).take(); 4771 return Owned(From); 4772 } 4773 4774 /// TryContextuallyConvertToBool - Attempt to contextually convert the 4775 /// expression From to bool (C++0x [conv]p3). 4776 static ImplicitConversionSequence 4777 TryContextuallyConvertToBool(Sema &S, Expr *From) { 4778 // FIXME: This is pretty broken. 4779 return TryImplicitConversion(S, From, S.Context.BoolTy, 4780 // FIXME: Are these flags correct? 4781 /*SuppressUserConversions=*/false, 4782 /*AllowExplicit=*/true, 4783 /*InOverloadResolution=*/false, 4784 /*CStyle=*/false, 4785 /*AllowObjCWritebackConversion=*/false); 4786 } 4787 4788 /// PerformContextuallyConvertToBool - Perform a contextual conversion 4789 /// of the expression From to bool (C++0x [conv]p3). 4790 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4791 if (checkPlaceholderForOverload(*this, From)) 4792 return ExprError(); 4793 4794 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4795 if (!ICS.isBad()) 4796 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4797 4798 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4799 return Diag(From->getLocStart(), 4800 diag::err_typecheck_bool_condition) 4801 << From->getType() << From->getSourceRange(); 4802 return ExprError(); 4803 } 4804 4805 /// Check that the specified conversion is permitted in a converted constant 4806 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 4807 /// is acceptable. 4808 static bool CheckConvertedConstantConversions(Sema &S, 4809 StandardConversionSequence &SCS) { 4810 // Since we know that the target type is an integral or unscoped enumeration 4811 // type, most conversion kinds are impossible. All possible First and Third 4812 // conversions are fine. 4813 switch (SCS.Second) { 4814 case ICK_Identity: 4815 case ICK_Integral_Promotion: 4816 case ICK_Integral_Conversion: 4817 return true; 4818 4819 case ICK_Boolean_Conversion: 4820 // Conversion from an integral or unscoped enumeration type to bool is 4821 // classified as ICK_Boolean_Conversion, but it's also an integral 4822 // conversion, so it's permitted in a converted constant expression. 4823 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4824 SCS.getToType(2)->isBooleanType(); 4825 4826 case ICK_Floating_Integral: 4827 case ICK_Complex_Real: 4828 return false; 4829 4830 case ICK_Lvalue_To_Rvalue: 4831 case ICK_Array_To_Pointer: 4832 case ICK_Function_To_Pointer: 4833 case ICK_NoReturn_Adjustment: 4834 case ICK_Qualification: 4835 case ICK_Compatible_Conversion: 4836 case ICK_Vector_Conversion: 4837 case ICK_Vector_Splat: 4838 case ICK_Derived_To_Base: 4839 case ICK_Pointer_Conversion: 4840 case ICK_Pointer_Member: 4841 case ICK_Block_Pointer_Conversion: 4842 case ICK_Writeback_Conversion: 4843 case ICK_Floating_Promotion: 4844 case ICK_Complex_Promotion: 4845 case ICK_Complex_Conversion: 4846 case ICK_Floating_Conversion: 4847 case ICK_TransparentUnionConversion: 4848 llvm_unreachable("unexpected second conversion kind"); 4849 4850 case ICK_Num_Conversion_Kinds: 4851 break; 4852 } 4853 4854 llvm_unreachable("unknown conversion kind"); 4855 } 4856 4857 /// CheckConvertedConstantExpression - Check that the expression From is a 4858 /// converted constant expression of type T, perform the conversion and produce 4859 /// the converted expression, per C++11 [expr.const]p3. 4860 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 4861 llvm::APSInt &Value, 4862 CCEKind CCE) { 4863 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11"); 4864 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 4865 4866 if (checkPlaceholderForOverload(*this, From)) 4867 return ExprError(); 4868 4869 // C++11 [expr.const]p3 with proposed wording fixes: 4870 // A converted constant expression of type T is a core constant expression, 4871 // implicitly converted to a prvalue of type T, where the converted 4872 // expression is a literal constant expression and the implicit conversion 4873 // sequence contains only user-defined conversions, lvalue-to-rvalue 4874 // conversions, integral promotions, and integral conversions other than 4875 // narrowing conversions. 4876 ImplicitConversionSequence ICS = 4877 TryImplicitConversion(From, T, 4878 /*SuppressUserConversions=*/false, 4879 /*AllowExplicit=*/false, 4880 /*InOverloadResolution=*/false, 4881 /*CStyle=*/false, 4882 /*AllowObjcWritebackConversion=*/false); 4883 StandardConversionSequence *SCS = 0; 4884 switch (ICS.getKind()) { 4885 case ImplicitConversionSequence::StandardConversion: 4886 if (!CheckConvertedConstantConversions(*this, ICS.Standard)) 4887 return Diag(From->getLocStart(), 4888 diag::err_typecheck_converted_constant_expression_disallowed) 4889 << From->getType() << From->getSourceRange() << T; 4890 SCS = &ICS.Standard; 4891 break; 4892 case ImplicitConversionSequence::UserDefinedConversion: 4893 // We are converting from class type to an integral or enumeration type, so 4894 // the Before sequence must be trivial. 4895 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After)) 4896 return Diag(From->getLocStart(), 4897 diag::err_typecheck_converted_constant_expression_disallowed) 4898 << From->getType() << From->getSourceRange() << T; 4899 SCS = &ICS.UserDefined.After; 4900 break; 4901 case ImplicitConversionSequence::AmbiguousConversion: 4902 case ImplicitConversionSequence::BadConversion: 4903 if (!DiagnoseMultipleUserDefinedConversion(From, T)) 4904 return Diag(From->getLocStart(), 4905 diag::err_typecheck_converted_constant_expression) 4906 << From->getType() << From->getSourceRange() << T; 4907 return ExprError(); 4908 4909 case ImplicitConversionSequence::EllipsisConversion: 4910 llvm_unreachable("ellipsis conversion in converted constant expression"); 4911 } 4912 4913 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting); 4914 if (Result.isInvalid()) 4915 return Result; 4916 4917 // Check for a narrowing implicit conversion. 4918 APValue PreNarrowingValue; 4919 QualType PreNarrowingType; 4920 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue, 4921 PreNarrowingType)) { 4922 case NK_Variable_Narrowing: 4923 // Implicit conversion to a narrower type, and the value is not a constant 4924 // expression. We'll diagnose this in a moment. 4925 case NK_Not_Narrowing: 4926 break; 4927 4928 case NK_Constant_Narrowing: 4929 Diag(From->getLocStart(), 4930 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4931 diag::err_cce_narrowing) 4932 << CCE << /*Constant*/1 4933 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T; 4934 break; 4935 4936 case NK_Type_Narrowing: 4937 Diag(From->getLocStart(), 4938 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4939 diag::err_cce_narrowing) 4940 << CCE << /*Constant*/0 << From->getType() << T; 4941 break; 4942 } 4943 4944 // Check the expression is a constant expression. 4945 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 4946 Expr::EvalResult Eval; 4947 Eval.Diag = &Notes; 4948 4949 if (!Result.get()->EvaluateAsRValue(Eval, Context)) { 4950 // The expression can't be folded, so we can't keep it at this position in 4951 // the AST. 4952 Result = ExprError(); 4953 } else { 4954 Value = Eval.Val.getInt(); 4955 4956 if (Notes.empty()) { 4957 // It's a constant expression. 4958 return Result; 4959 } 4960 } 4961 4962 // It's not a constant expression. Produce an appropriate diagnostic. 4963 if (Notes.size() == 1 && 4964 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 4965 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 4966 else { 4967 Diag(From->getLocStart(), diag::err_expr_not_cce) 4968 << CCE << From->getSourceRange(); 4969 for (unsigned I = 0; I < Notes.size(); ++I) 4970 Diag(Notes[I].first, Notes[I].second); 4971 } 4972 return Result; 4973 } 4974 4975 /// dropPointerConversions - If the given standard conversion sequence 4976 /// involves any pointer conversions, remove them. This may change 4977 /// the result type of the conversion sequence. 4978 static void dropPointerConversion(StandardConversionSequence &SCS) { 4979 if (SCS.Second == ICK_Pointer_Conversion) { 4980 SCS.Second = ICK_Identity; 4981 SCS.Third = ICK_Identity; 4982 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 4983 } 4984 } 4985 4986 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 4987 /// convert the expression From to an Objective-C pointer type. 4988 static ImplicitConversionSequence 4989 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 4990 // Do an implicit conversion to 'id'. 4991 QualType Ty = S.Context.getObjCIdType(); 4992 ImplicitConversionSequence ICS 4993 = TryImplicitConversion(S, From, Ty, 4994 // FIXME: Are these flags correct? 4995 /*SuppressUserConversions=*/false, 4996 /*AllowExplicit=*/true, 4997 /*InOverloadResolution=*/false, 4998 /*CStyle=*/false, 4999 /*AllowObjCWritebackConversion=*/false); 5000 5001 // Strip off any final conversions to 'id'. 5002 switch (ICS.getKind()) { 5003 case ImplicitConversionSequence::BadConversion: 5004 case ImplicitConversionSequence::AmbiguousConversion: 5005 case ImplicitConversionSequence::EllipsisConversion: 5006 break; 5007 5008 case ImplicitConversionSequence::UserDefinedConversion: 5009 dropPointerConversion(ICS.UserDefined.After); 5010 break; 5011 5012 case ImplicitConversionSequence::StandardConversion: 5013 dropPointerConversion(ICS.Standard); 5014 break; 5015 } 5016 5017 return ICS; 5018 } 5019 5020 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5021 /// conversion of the expression From to an Objective-C pointer type. 5022 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5023 if (checkPlaceholderForOverload(*this, From)) 5024 return ExprError(); 5025 5026 QualType Ty = Context.getObjCIdType(); 5027 ImplicitConversionSequence ICS = 5028 TryContextuallyConvertToObjCPointer(*this, From); 5029 if (!ICS.isBad()) 5030 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5031 return ExprError(); 5032 } 5033 5034 /// Determine whether the provided type is an integral type, or an enumeration 5035 /// type of a permitted flavor. 5036 static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) { 5037 return AllowScopedEnum ? T->isIntegralOrEnumerationType() 5038 : T->isIntegralOrUnscopedEnumerationType(); 5039 } 5040 5041 /// \brief Attempt to convert the given expression to an integral or 5042 /// enumeration type. 5043 /// 5044 /// This routine will attempt to convert an expression of class type to an 5045 /// integral or enumeration type, if that class type only has a single 5046 /// conversion to an integral or enumeration type. 5047 /// 5048 /// \param Loc The source location of the construct that requires the 5049 /// conversion. 5050 /// 5051 /// \param From The expression we're converting from. 5052 /// 5053 /// \param Diagnoser Used to output any diagnostics. 5054 /// 5055 /// \param AllowScopedEnumerations Specifies whether conversions to scoped 5056 /// enumerations should be considered. 5057 /// 5058 /// \returns The expression, converted to an integral or enumeration type if 5059 /// successful. 5060 ExprResult 5061 Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From, 5062 ICEConvertDiagnoser &Diagnoser, 5063 bool AllowScopedEnumerations) { 5064 // We can't perform any more checking for type-dependent expressions. 5065 if (From->isTypeDependent()) 5066 return Owned(From); 5067 5068 // Process placeholders immediately. 5069 if (From->hasPlaceholderType()) { 5070 ExprResult result = CheckPlaceholderExpr(From); 5071 if (result.isInvalid()) return result; 5072 From = result.take(); 5073 } 5074 5075 // If the expression already has integral or enumeration type, we're golden. 5076 QualType T = From->getType(); 5077 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations)) 5078 return DefaultLvalueConversion(From); 5079 5080 // FIXME: Check for missing '()' if T is a function type? 5081 5082 // If we don't have a class type in C++, there's no way we can get an 5083 // expression of integral or enumeration type. 5084 const RecordType *RecordTy = T->getAs<RecordType>(); 5085 if (!RecordTy || !getLangOpts().CPlusPlus) { 5086 if (!Diagnoser.Suppress) 5087 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange(); 5088 return Owned(From); 5089 } 5090 5091 // We must have a complete class type. 5092 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5093 ICEConvertDiagnoser &Diagnoser; 5094 Expr *From; 5095 5096 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From) 5097 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {} 5098 5099 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 5100 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5101 } 5102 } IncompleteDiagnoser(Diagnoser, From); 5103 5104 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5105 return Owned(From); 5106 5107 // Look for a conversion to an integral or enumeration type. 5108 UnresolvedSet<4> ViableConversions; 5109 UnresolvedSet<4> ExplicitConversions; 5110 std::pair<CXXRecordDecl::conversion_iterator, 5111 CXXRecordDecl::conversion_iterator> Conversions 5112 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5113 5114 bool HadMultipleCandidates 5115 = (std::distance(Conversions.first, Conversions.second) > 1); 5116 5117 for (CXXRecordDecl::conversion_iterator 5118 I = Conversions.first, E = Conversions.second; I != E; ++I) { 5119 if (CXXConversionDecl *Conversion 5120 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) { 5121 if (isIntegralOrEnumerationType( 5122 Conversion->getConversionType().getNonReferenceType(), 5123 AllowScopedEnumerations)) { 5124 if (Conversion->isExplicit()) 5125 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5126 else 5127 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5128 } 5129 } 5130 } 5131 5132 switch (ViableConversions.size()) { 5133 case 0: 5134 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) { 5135 DeclAccessPair Found = ExplicitConversions[0]; 5136 CXXConversionDecl *Conversion 5137 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5138 5139 // The user probably meant to invoke the given explicit 5140 // conversion; use it. 5141 QualType ConvTy 5142 = Conversion->getConversionType().getNonReferenceType(); 5143 std::string TypeStr; 5144 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy()); 5145 5146 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy) 5147 << FixItHint::CreateInsertion(From->getLocStart(), 5148 "static_cast<" + TypeStr + ">(") 5149 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()), 5150 ")"); 5151 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy); 5152 5153 // If we aren't in a SFINAE context, build a call to the 5154 // explicit conversion function. 5155 if (isSFINAEContext()) 5156 return ExprError(); 5157 5158 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5159 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion, 5160 HadMultipleCandidates); 5161 if (Result.isInvalid()) 5162 return ExprError(); 5163 // Record usage of conversion in an implicit cast. 5164 From = ImplicitCastExpr::Create(Context, Result.get()->getType(), 5165 CK_UserDefinedConversion, 5166 Result.get(), 0, 5167 Result.get()->getValueKind()); 5168 } 5169 5170 // We'll complain below about a non-integral condition type. 5171 break; 5172 5173 case 1: { 5174 // Apply this conversion. 5175 DeclAccessPair Found = ViableConversions[0]; 5176 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5177 5178 CXXConversionDecl *Conversion 5179 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5180 QualType ConvTy 5181 = Conversion->getConversionType().getNonReferenceType(); 5182 if (!Diagnoser.SuppressConversion) { 5183 if (isSFINAEContext()) 5184 return ExprError(); 5185 5186 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy) 5187 << From->getSourceRange(); 5188 } 5189 5190 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion, 5191 HadMultipleCandidates); 5192 if (Result.isInvalid()) 5193 return ExprError(); 5194 // Record usage of conversion in an implicit cast. 5195 From = ImplicitCastExpr::Create(Context, Result.get()->getType(), 5196 CK_UserDefinedConversion, 5197 Result.get(), 0, 5198 Result.get()->getValueKind()); 5199 break; 5200 } 5201 5202 default: 5203 if (Diagnoser.Suppress) 5204 return ExprError(); 5205 5206 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange(); 5207 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5208 CXXConversionDecl *Conv 5209 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5210 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5211 Diagnoser.noteAmbiguous(*this, Conv, ConvTy); 5212 } 5213 return Owned(From); 5214 } 5215 5216 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) && 5217 !Diagnoser.Suppress) { 5218 Diagnoser.diagnoseNotInt(*this, Loc, From->getType()) 5219 << From->getSourceRange(); 5220 } 5221 5222 return DefaultLvalueConversion(From); 5223 } 5224 5225 /// AddOverloadCandidate - Adds the given function to the set of 5226 /// candidate functions, using the given function call arguments. If 5227 /// @p SuppressUserConversions, then don't allow user-defined 5228 /// conversions via constructors or conversion operators. 5229 /// 5230 /// \param PartialOverloading true if we are performing "partial" overloading 5231 /// based on an incomplete set of function arguments. This feature is used by 5232 /// code completion. 5233 void 5234 Sema::AddOverloadCandidate(FunctionDecl *Function, 5235 DeclAccessPair FoundDecl, 5236 llvm::ArrayRef<Expr *> Args, 5237 OverloadCandidateSet& CandidateSet, 5238 bool SuppressUserConversions, 5239 bool PartialOverloading, 5240 bool AllowExplicit) { 5241 const FunctionProtoType* Proto 5242 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5243 assert(Proto && "Functions without a prototype cannot be overloaded"); 5244 assert(!Function->getDescribedFunctionTemplate() && 5245 "Use AddTemplateOverloadCandidate for function templates"); 5246 5247 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5248 if (!isa<CXXConstructorDecl>(Method)) { 5249 // If we get here, it's because we're calling a member function 5250 // that is named without a member access expression (e.g., 5251 // "this->f") that was either written explicitly or created 5252 // implicitly. This can happen with a qualified call to a member 5253 // function, e.g., X::f(). We use an empty type for the implied 5254 // object argument (C++ [over.call.func]p3), and the acting context 5255 // is irrelevant. 5256 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5257 QualType(), Expr::Classification::makeSimpleLValue(), 5258 Args, CandidateSet, SuppressUserConversions); 5259 return; 5260 } 5261 // We treat a constructor like a non-member function, since its object 5262 // argument doesn't participate in overload resolution. 5263 } 5264 5265 if (!CandidateSet.isNewCandidate(Function)) 5266 return; 5267 5268 // Overload resolution is always an unevaluated context. 5269 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5270 5271 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){ 5272 // C++ [class.copy]p3: 5273 // A member function template is never instantiated to perform the copy 5274 // of a class object to an object of its class type. 5275 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5276 if (Args.size() == 1 && 5277 Constructor->isSpecializationCopyingObject() && 5278 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5279 IsDerivedFrom(Args[0]->getType(), ClassType))) 5280 return; 5281 } 5282 5283 // Add this candidate 5284 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5285 Candidate.FoundDecl = FoundDecl; 5286 Candidate.Function = Function; 5287 Candidate.Viable = true; 5288 Candidate.IsSurrogate = false; 5289 Candidate.IgnoreObjectArgument = false; 5290 Candidate.ExplicitCallArguments = Args.size(); 5291 5292 unsigned NumArgsInProto = Proto->getNumArgs(); 5293 5294 // (C++ 13.3.2p2): A candidate function having fewer than m 5295 // parameters is viable only if it has an ellipsis in its parameter 5296 // list (8.3.5). 5297 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto && 5298 !Proto->isVariadic()) { 5299 Candidate.Viable = false; 5300 Candidate.FailureKind = ovl_fail_too_many_arguments; 5301 return; 5302 } 5303 5304 // (C++ 13.3.2p2): A candidate function having more than m parameters 5305 // is viable only if the (m+1)st parameter has a default argument 5306 // (8.3.6). For the purposes of overload resolution, the 5307 // parameter list is truncated on the right, so that there are 5308 // exactly m parameters. 5309 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5310 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5311 // Not enough arguments. 5312 Candidate.Viable = false; 5313 Candidate.FailureKind = ovl_fail_too_few_arguments; 5314 return; 5315 } 5316 5317 // (CUDA B.1): Check for invalid calls between targets. 5318 if (getLangOpts().CUDA) 5319 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5320 if (CheckCUDATarget(Caller, Function)) { 5321 Candidate.Viable = false; 5322 Candidate.FailureKind = ovl_fail_bad_target; 5323 return; 5324 } 5325 5326 // Determine the implicit conversion sequences for each of the 5327 // arguments. 5328 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5329 if (ArgIdx < NumArgsInProto) { 5330 // (C++ 13.3.2p3): for F to be a viable function, there shall 5331 // exist for each argument an implicit conversion sequence 5332 // (13.3.3.1) that converts that argument to the corresponding 5333 // parameter of F. 5334 QualType ParamType = Proto->getArgType(ArgIdx); 5335 Candidate.Conversions[ArgIdx] 5336 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5337 SuppressUserConversions, 5338 /*InOverloadResolution=*/true, 5339 /*AllowObjCWritebackConversion=*/ 5340 getLangOpts().ObjCAutoRefCount, 5341 AllowExplicit); 5342 if (Candidate.Conversions[ArgIdx].isBad()) { 5343 Candidate.Viable = false; 5344 Candidate.FailureKind = ovl_fail_bad_conversion; 5345 break; 5346 } 5347 } else { 5348 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5349 // argument for which there is no corresponding parameter is 5350 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5351 Candidate.Conversions[ArgIdx].setEllipsis(); 5352 } 5353 } 5354 } 5355 5356 /// \brief Add all of the function declarations in the given function set to 5357 /// the overload canddiate set. 5358 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5359 llvm::ArrayRef<Expr *> Args, 5360 OverloadCandidateSet& CandidateSet, 5361 bool SuppressUserConversions, 5362 TemplateArgumentListInfo *ExplicitTemplateArgs) { 5363 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5364 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5365 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5366 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5367 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5368 cast<CXXMethodDecl>(FD)->getParent(), 5369 Args[0]->getType(), Args[0]->Classify(Context), 5370 Args.slice(1), CandidateSet, 5371 SuppressUserConversions); 5372 else 5373 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5374 SuppressUserConversions); 5375 } else { 5376 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5377 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5378 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5379 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5380 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5381 ExplicitTemplateArgs, 5382 Args[0]->getType(), 5383 Args[0]->Classify(Context), Args.slice(1), 5384 CandidateSet, SuppressUserConversions); 5385 else 5386 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5387 ExplicitTemplateArgs, Args, 5388 CandidateSet, SuppressUserConversions); 5389 } 5390 } 5391 } 5392 5393 /// AddMethodCandidate - Adds a named decl (which is some kind of 5394 /// method) as a method candidate to the given overload set. 5395 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5396 QualType ObjectType, 5397 Expr::Classification ObjectClassification, 5398 Expr **Args, unsigned NumArgs, 5399 OverloadCandidateSet& CandidateSet, 5400 bool SuppressUserConversions) { 5401 NamedDecl *Decl = FoundDecl.getDecl(); 5402 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5403 5404 if (isa<UsingShadowDecl>(Decl)) 5405 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5406 5407 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5408 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5409 "Expected a member function template"); 5410 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5411 /*ExplicitArgs*/ 0, 5412 ObjectType, ObjectClassification, 5413 llvm::makeArrayRef(Args, NumArgs), CandidateSet, 5414 SuppressUserConversions); 5415 } else { 5416 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5417 ObjectType, ObjectClassification, 5418 llvm::makeArrayRef(Args, NumArgs), 5419 CandidateSet, SuppressUserConversions); 5420 } 5421 } 5422 5423 /// AddMethodCandidate - Adds the given C++ member function to the set 5424 /// of candidate functions, using the given function call arguments 5425 /// and the object argument (@c Object). For example, in a call 5426 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5427 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5428 /// allow user-defined conversions via constructors or conversion 5429 /// operators. 5430 void 5431 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5432 CXXRecordDecl *ActingContext, QualType ObjectType, 5433 Expr::Classification ObjectClassification, 5434 llvm::ArrayRef<Expr *> Args, 5435 OverloadCandidateSet& CandidateSet, 5436 bool SuppressUserConversions) { 5437 const FunctionProtoType* Proto 5438 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5439 assert(Proto && "Methods without a prototype cannot be overloaded"); 5440 assert(!isa<CXXConstructorDecl>(Method) && 5441 "Use AddOverloadCandidate for constructors"); 5442 5443 if (!CandidateSet.isNewCandidate(Method)) 5444 return; 5445 5446 // Overload resolution is always an unevaluated context. 5447 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5448 5449 // Add this candidate 5450 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5451 Candidate.FoundDecl = FoundDecl; 5452 Candidate.Function = Method; 5453 Candidate.IsSurrogate = false; 5454 Candidate.IgnoreObjectArgument = false; 5455 Candidate.ExplicitCallArguments = Args.size(); 5456 5457 unsigned NumArgsInProto = Proto->getNumArgs(); 5458 5459 // (C++ 13.3.2p2): A candidate function having fewer than m 5460 // parameters is viable only if it has an ellipsis in its parameter 5461 // list (8.3.5). 5462 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5463 Candidate.Viable = false; 5464 Candidate.FailureKind = ovl_fail_too_many_arguments; 5465 return; 5466 } 5467 5468 // (C++ 13.3.2p2): A candidate function having more than m parameters 5469 // is viable only if the (m+1)st parameter has a default argument 5470 // (8.3.6). For the purposes of overload resolution, the 5471 // parameter list is truncated on the right, so that there are 5472 // exactly m parameters. 5473 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 5474 if (Args.size() < MinRequiredArgs) { 5475 // Not enough arguments. 5476 Candidate.Viable = false; 5477 Candidate.FailureKind = ovl_fail_too_few_arguments; 5478 return; 5479 } 5480 5481 Candidate.Viable = true; 5482 5483 if (Method->isStatic() || ObjectType.isNull()) 5484 // The implicit object argument is ignored. 5485 Candidate.IgnoreObjectArgument = true; 5486 else { 5487 // Determine the implicit conversion sequence for the object 5488 // parameter. 5489 Candidate.Conversions[0] 5490 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 5491 Method, ActingContext); 5492 if (Candidate.Conversions[0].isBad()) { 5493 Candidate.Viable = false; 5494 Candidate.FailureKind = ovl_fail_bad_conversion; 5495 return; 5496 } 5497 } 5498 5499 // Determine the implicit conversion sequences for each of the 5500 // arguments. 5501 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5502 if (ArgIdx < NumArgsInProto) { 5503 // (C++ 13.3.2p3): for F to be a viable function, there shall 5504 // exist for each argument an implicit conversion sequence 5505 // (13.3.3.1) that converts that argument to the corresponding 5506 // parameter of F. 5507 QualType ParamType = Proto->getArgType(ArgIdx); 5508 Candidate.Conversions[ArgIdx + 1] 5509 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5510 SuppressUserConversions, 5511 /*InOverloadResolution=*/true, 5512 /*AllowObjCWritebackConversion=*/ 5513 getLangOpts().ObjCAutoRefCount); 5514 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5515 Candidate.Viable = false; 5516 Candidate.FailureKind = ovl_fail_bad_conversion; 5517 break; 5518 } 5519 } else { 5520 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5521 // argument for which there is no corresponding parameter is 5522 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5523 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5524 } 5525 } 5526 } 5527 5528 /// \brief Add a C++ member function template as a candidate to the candidate 5529 /// set, using template argument deduction to produce an appropriate member 5530 /// function template specialization. 5531 void 5532 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 5533 DeclAccessPair FoundDecl, 5534 CXXRecordDecl *ActingContext, 5535 TemplateArgumentListInfo *ExplicitTemplateArgs, 5536 QualType ObjectType, 5537 Expr::Classification ObjectClassification, 5538 llvm::ArrayRef<Expr *> Args, 5539 OverloadCandidateSet& CandidateSet, 5540 bool SuppressUserConversions) { 5541 if (!CandidateSet.isNewCandidate(MethodTmpl)) 5542 return; 5543 5544 // C++ [over.match.funcs]p7: 5545 // In each case where a candidate is a function template, candidate 5546 // function template specializations are generated using template argument 5547 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5548 // candidate functions in the usual way.113) A given name can refer to one 5549 // or more function templates and also to a set of overloaded non-template 5550 // functions. In such a case, the candidate functions generated from each 5551 // function template are combined with the set of non-template candidate 5552 // functions. 5553 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5554 FunctionDecl *Specialization = 0; 5555 if (TemplateDeductionResult Result 5556 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 5557 Specialization, Info)) { 5558 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5559 Candidate.FoundDecl = FoundDecl; 5560 Candidate.Function = MethodTmpl->getTemplatedDecl(); 5561 Candidate.Viable = false; 5562 Candidate.FailureKind = ovl_fail_bad_deduction; 5563 Candidate.IsSurrogate = false; 5564 Candidate.IgnoreObjectArgument = false; 5565 Candidate.ExplicitCallArguments = Args.size(); 5566 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5567 Info); 5568 return; 5569 } 5570 5571 // Add the function template specialization produced by template argument 5572 // deduction as a candidate. 5573 assert(Specialization && "Missing member function template specialization?"); 5574 assert(isa<CXXMethodDecl>(Specialization) && 5575 "Specialization is not a member function?"); 5576 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 5577 ActingContext, ObjectType, ObjectClassification, Args, 5578 CandidateSet, SuppressUserConversions); 5579 } 5580 5581 /// \brief Add a C++ function template specialization as a candidate 5582 /// in the candidate set, using template argument deduction to produce 5583 /// an appropriate function template specialization. 5584 void 5585 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 5586 DeclAccessPair FoundDecl, 5587 TemplateArgumentListInfo *ExplicitTemplateArgs, 5588 llvm::ArrayRef<Expr *> Args, 5589 OverloadCandidateSet& CandidateSet, 5590 bool SuppressUserConversions) { 5591 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5592 return; 5593 5594 // C++ [over.match.funcs]p7: 5595 // In each case where a candidate is a function template, candidate 5596 // function template specializations are generated using template argument 5597 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5598 // candidate functions in the usual way.113) A given name can refer to one 5599 // or more function templates and also to a set of overloaded non-template 5600 // functions. In such a case, the candidate functions generated from each 5601 // function template are combined with the set of non-template candidate 5602 // functions. 5603 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5604 FunctionDecl *Specialization = 0; 5605 if (TemplateDeductionResult Result 5606 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 5607 Specialization, Info)) { 5608 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5609 Candidate.FoundDecl = FoundDecl; 5610 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5611 Candidate.Viable = false; 5612 Candidate.FailureKind = ovl_fail_bad_deduction; 5613 Candidate.IsSurrogate = false; 5614 Candidate.IgnoreObjectArgument = false; 5615 Candidate.ExplicitCallArguments = Args.size(); 5616 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5617 Info); 5618 return; 5619 } 5620 5621 // Add the function template specialization produced by template argument 5622 // deduction as a candidate. 5623 assert(Specialization && "Missing function template specialization?"); 5624 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 5625 SuppressUserConversions); 5626 } 5627 5628 /// AddConversionCandidate - Add a C++ conversion function as a 5629 /// candidate in the candidate set (C++ [over.match.conv], 5630 /// C++ [over.match.copy]). From is the expression we're converting from, 5631 /// and ToType is the type that we're eventually trying to convert to 5632 /// (which may or may not be the same type as the type that the 5633 /// conversion function produces). 5634 void 5635 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 5636 DeclAccessPair FoundDecl, 5637 CXXRecordDecl *ActingContext, 5638 Expr *From, QualType ToType, 5639 OverloadCandidateSet& CandidateSet) { 5640 assert(!Conversion->getDescribedFunctionTemplate() && 5641 "Conversion function templates use AddTemplateConversionCandidate"); 5642 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 5643 if (!CandidateSet.isNewCandidate(Conversion)) 5644 return; 5645 5646 // Overload resolution is always an unevaluated context. 5647 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5648 5649 // Add this candidate 5650 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 5651 Candidate.FoundDecl = FoundDecl; 5652 Candidate.Function = Conversion; 5653 Candidate.IsSurrogate = false; 5654 Candidate.IgnoreObjectArgument = false; 5655 Candidate.FinalConversion.setAsIdentityConversion(); 5656 Candidate.FinalConversion.setFromType(ConvType); 5657 Candidate.FinalConversion.setAllToTypes(ToType); 5658 Candidate.Viable = true; 5659 Candidate.ExplicitCallArguments = 1; 5660 5661 // C++ [over.match.funcs]p4: 5662 // For conversion functions, the function is considered to be a member of 5663 // the class of the implicit implied object argument for the purpose of 5664 // defining the type of the implicit object parameter. 5665 // 5666 // Determine the implicit conversion sequence for the implicit 5667 // object parameter. 5668 QualType ImplicitParamType = From->getType(); 5669 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 5670 ImplicitParamType = FromPtrType->getPointeeType(); 5671 CXXRecordDecl *ConversionContext 5672 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 5673 5674 Candidate.Conversions[0] 5675 = TryObjectArgumentInitialization(*this, From->getType(), 5676 From->Classify(Context), 5677 Conversion, ConversionContext); 5678 5679 if (Candidate.Conversions[0].isBad()) { 5680 Candidate.Viable = false; 5681 Candidate.FailureKind = ovl_fail_bad_conversion; 5682 return; 5683 } 5684 5685 // We won't go through a user-define type conversion function to convert a 5686 // derived to base as such conversions are given Conversion Rank. They only 5687 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 5688 QualType FromCanon 5689 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 5690 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 5691 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 5692 Candidate.Viable = false; 5693 Candidate.FailureKind = ovl_fail_trivial_conversion; 5694 return; 5695 } 5696 5697 // To determine what the conversion from the result of calling the 5698 // conversion function to the type we're eventually trying to 5699 // convert to (ToType), we need to synthesize a call to the 5700 // conversion function and attempt copy initialization from it. This 5701 // makes sure that we get the right semantics with respect to 5702 // lvalues/rvalues and the type. Fortunately, we can allocate this 5703 // call on the stack and we don't need its arguments to be 5704 // well-formed. 5705 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 5706 VK_LValue, From->getLocStart()); 5707 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 5708 Context.getPointerType(Conversion->getType()), 5709 CK_FunctionToPointerDecay, 5710 &ConversionRef, VK_RValue); 5711 5712 QualType ConversionType = Conversion->getConversionType(); 5713 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 5714 Candidate.Viable = false; 5715 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5716 return; 5717 } 5718 5719 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 5720 5721 // Note that it is safe to allocate CallExpr on the stack here because 5722 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 5723 // allocator). 5724 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 5725 CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK, 5726 From->getLocStart()); 5727 ImplicitConversionSequence ICS = 5728 TryCopyInitialization(*this, &Call, ToType, 5729 /*SuppressUserConversions=*/true, 5730 /*InOverloadResolution=*/false, 5731 /*AllowObjCWritebackConversion=*/false); 5732 5733 switch (ICS.getKind()) { 5734 case ImplicitConversionSequence::StandardConversion: 5735 Candidate.FinalConversion = ICS.Standard; 5736 5737 // C++ [over.ics.user]p3: 5738 // If the user-defined conversion is specified by a specialization of a 5739 // conversion function template, the second standard conversion sequence 5740 // shall have exact match rank. 5741 if (Conversion->getPrimaryTemplate() && 5742 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 5743 Candidate.Viable = false; 5744 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 5745 } 5746 5747 // C++0x [dcl.init.ref]p5: 5748 // In the second case, if the reference is an rvalue reference and 5749 // the second standard conversion sequence of the user-defined 5750 // conversion sequence includes an lvalue-to-rvalue conversion, the 5751 // program is ill-formed. 5752 if (ToType->isRValueReferenceType() && 5753 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 5754 Candidate.Viable = false; 5755 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5756 } 5757 break; 5758 5759 case ImplicitConversionSequence::BadConversion: 5760 Candidate.Viable = false; 5761 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5762 break; 5763 5764 default: 5765 llvm_unreachable( 5766 "Can only end up with a standard conversion sequence or failure"); 5767 } 5768 } 5769 5770 /// \brief Adds a conversion function template specialization 5771 /// candidate to the overload set, using template argument deduction 5772 /// to deduce the template arguments of the conversion function 5773 /// template from the type that we are converting to (C++ 5774 /// [temp.deduct.conv]). 5775 void 5776 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 5777 DeclAccessPair FoundDecl, 5778 CXXRecordDecl *ActingDC, 5779 Expr *From, QualType ToType, 5780 OverloadCandidateSet &CandidateSet) { 5781 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 5782 "Only conversion function templates permitted here"); 5783 5784 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5785 return; 5786 5787 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5788 CXXConversionDecl *Specialization = 0; 5789 if (TemplateDeductionResult Result 5790 = DeduceTemplateArguments(FunctionTemplate, ToType, 5791 Specialization, Info)) { 5792 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5793 Candidate.FoundDecl = FoundDecl; 5794 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5795 Candidate.Viable = false; 5796 Candidate.FailureKind = ovl_fail_bad_deduction; 5797 Candidate.IsSurrogate = false; 5798 Candidate.IgnoreObjectArgument = false; 5799 Candidate.ExplicitCallArguments = 1; 5800 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5801 Info); 5802 return; 5803 } 5804 5805 // Add the conversion function template specialization produced by 5806 // template argument deduction as a candidate. 5807 assert(Specialization && "Missing function template specialization?"); 5808 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 5809 CandidateSet); 5810 } 5811 5812 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 5813 /// converts the given @c Object to a function pointer via the 5814 /// conversion function @c Conversion, and then attempts to call it 5815 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 5816 /// the type of function that we'll eventually be calling. 5817 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 5818 DeclAccessPair FoundDecl, 5819 CXXRecordDecl *ActingContext, 5820 const FunctionProtoType *Proto, 5821 Expr *Object, 5822 llvm::ArrayRef<Expr *> Args, 5823 OverloadCandidateSet& CandidateSet) { 5824 if (!CandidateSet.isNewCandidate(Conversion)) 5825 return; 5826 5827 // Overload resolution is always an unevaluated context. 5828 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5829 5830 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5831 Candidate.FoundDecl = FoundDecl; 5832 Candidate.Function = 0; 5833 Candidate.Surrogate = Conversion; 5834 Candidate.Viable = true; 5835 Candidate.IsSurrogate = true; 5836 Candidate.IgnoreObjectArgument = false; 5837 Candidate.ExplicitCallArguments = Args.size(); 5838 5839 // Determine the implicit conversion sequence for the implicit 5840 // object parameter. 5841 ImplicitConversionSequence ObjectInit 5842 = TryObjectArgumentInitialization(*this, Object->getType(), 5843 Object->Classify(Context), 5844 Conversion, ActingContext); 5845 if (ObjectInit.isBad()) { 5846 Candidate.Viable = false; 5847 Candidate.FailureKind = ovl_fail_bad_conversion; 5848 Candidate.Conversions[0] = ObjectInit; 5849 return; 5850 } 5851 5852 // The first conversion is actually a user-defined conversion whose 5853 // first conversion is ObjectInit's standard conversion (which is 5854 // effectively a reference binding). Record it as such. 5855 Candidate.Conversions[0].setUserDefined(); 5856 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 5857 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 5858 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 5859 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 5860 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 5861 Candidate.Conversions[0].UserDefined.After 5862 = Candidate.Conversions[0].UserDefined.Before; 5863 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 5864 5865 // Find the 5866 unsigned NumArgsInProto = Proto->getNumArgs(); 5867 5868 // (C++ 13.3.2p2): A candidate function having fewer than m 5869 // parameters is viable only if it has an ellipsis in its parameter 5870 // list (8.3.5). 5871 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5872 Candidate.Viable = false; 5873 Candidate.FailureKind = ovl_fail_too_many_arguments; 5874 return; 5875 } 5876 5877 // Function types don't have any default arguments, so just check if 5878 // we have enough arguments. 5879 if (Args.size() < NumArgsInProto) { 5880 // Not enough arguments. 5881 Candidate.Viable = false; 5882 Candidate.FailureKind = ovl_fail_too_few_arguments; 5883 return; 5884 } 5885 5886 // Determine the implicit conversion sequences for each of the 5887 // arguments. 5888 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5889 if (ArgIdx < NumArgsInProto) { 5890 // (C++ 13.3.2p3): for F to be a viable function, there shall 5891 // exist for each argument an implicit conversion sequence 5892 // (13.3.3.1) that converts that argument to the corresponding 5893 // parameter of F. 5894 QualType ParamType = Proto->getArgType(ArgIdx); 5895 Candidate.Conversions[ArgIdx + 1] 5896 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5897 /*SuppressUserConversions=*/false, 5898 /*InOverloadResolution=*/false, 5899 /*AllowObjCWritebackConversion=*/ 5900 getLangOpts().ObjCAutoRefCount); 5901 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5902 Candidate.Viable = false; 5903 Candidate.FailureKind = ovl_fail_bad_conversion; 5904 break; 5905 } 5906 } else { 5907 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5908 // argument for which there is no corresponding parameter is 5909 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5910 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5911 } 5912 } 5913 } 5914 5915 /// \brief Add overload candidates for overloaded operators that are 5916 /// member functions. 5917 /// 5918 /// Add the overloaded operator candidates that are member functions 5919 /// for the operator Op that was used in an operator expression such 5920 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 5921 /// CandidateSet will store the added overload candidates. (C++ 5922 /// [over.match.oper]). 5923 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 5924 SourceLocation OpLoc, 5925 Expr **Args, unsigned NumArgs, 5926 OverloadCandidateSet& CandidateSet, 5927 SourceRange OpRange) { 5928 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 5929 5930 // C++ [over.match.oper]p3: 5931 // For a unary operator @ with an operand of a type whose 5932 // cv-unqualified version is T1, and for a binary operator @ with 5933 // a left operand of a type whose cv-unqualified version is T1 and 5934 // a right operand of a type whose cv-unqualified version is T2, 5935 // three sets of candidate functions, designated member 5936 // candidates, non-member candidates and built-in candidates, are 5937 // constructed as follows: 5938 QualType T1 = Args[0]->getType(); 5939 5940 // -- If T1 is a class type, the set of member candidates is the 5941 // result of the qualified lookup of T1::operator@ 5942 // (13.3.1.1.1); otherwise, the set of member candidates is 5943 // empty. 5944 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 5945 // Complete the type if it can be completed. Otherwise, we're done. 5946 if (RequireCompleteType(OpLoc, T1, 0)) 5947 return; 5948 5949 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 5950 LookupQualifiedName(Operators, T1Rec->getDecl()); 5951 Operators.suppressDiagnostics(); 5952 5953 for (LookupResult::iterator Oper = Operators.begin(), 5954 OperEnd = Operators.end(); 5955 Oper != OperEnd; 5956 ++Oper) 5957 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 5958 Args[0]->Classify(Context), Args + 1, NumArgs - 1, 5959 CandidateSet, 5960 /* SuppressUserConversions = */ false); 5961 } 5962 } 5963 5964 /// AddBuiltinCandidate - Add a candidate for a built-in 5965 /// operator. ResultTy and ParamTys are the result and parameter types 5966 /// of the built-in candidate, respectively. Args and NumArgs are the 5967 /// arguments being passed to the candidate. IsAssignmentOperator 5968 /// should be true when this built-in candidate is an assignment 5969 /// operator. NumContextualBoolArguments is the number of arguments 5970 /// (at the beginning of the argument list) that will be contextually 5971 /// converted to bool. 5972 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 5973 Expr **Args, unsigned NumArgs, 5974 OverloadCandidateSet& CandidateSet, 5975 bool IsAssignmentOperator, 5976 unsigned NumContextualBoolArguments) { 5977 // Overload resolution is always an unevaluated context. 5978 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5979 5980 // Add this candidate 5981 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs); 5982 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 5983 Candidate.Function = 0; 5984 Candidate.IsSurrogate = false; 5985 Candidate.IgnoreObjectArgument = false; 5986 Candidate.BuiltinTypes.ResultTy = ResultTy; 5987 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 5988 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 5989 5990 // Determine the implicit conversion sequences for each of the 5991 // arguments. 5992 Candidate.Viable = true; 5993 Candidate.ExplicitCallArguments = NumArgs; 5994 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 5995 // C++ [over.match.oper]p4: 5996 // For the built-in assignment operators, conversions of the 5997 // left operand are restricted as follows: 5998 // -- no temporaries are introduced to hold the left operand, and 5999 // -- no user-defined conversions are applied to the left 6000 // operand to achieve a type match with the left-most 6001 // parameter of a built-in candidate. 6002 // 6003 // We block these conversions by turning off user-defined 6004 // conversions, since that is the only way that initialization of 6005 // a reference to a non-class type can occur from something that 6006 // is not of the same type. 6007 if (ArgIdx < NumContextualBoolArguments) { 6008 assert(ParamTys[ArgIdx] == Context.BoolTy && 6009 "Contextual conversion to bool requires bool type"); 6010 Candidate.Conversions[ArgIdx] 6011 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6012 } else { 6013 Candidate.Conversions[ArgIdx] 6014 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6015 ArgIdx == 0 && IsAssignmentOperator, 6016 /*InOverloadResolution=*/false, 6017 /*AllowObjCWritebackConversion=*/ 6018 getLangOpts().ObjCAutoRefCount); 6019 } 6020 if (Candidate.Conversions[ArgIdx].isBad()) { 6021 Candidate.Viable = false; 6022 Candidate.FailureKind = ovl_fail_bad_conversion; 6023 break; 6024 } 6025 } 6026 } 6027 6028 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6029 /// candidate operator functions for built-in operators (C++ 6030 /// [over.built]). The types are separated into pointer types and 6031 /// enumeration types. 6032 class BuiltinCandidateTypeSet { 6033 /// TypeSet - A set of types. 6034 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6035 6036 /// PointerTypes - The set of pointer types that will be used in the 6037 /// built-in candidates. 6038 TypeSet PointerTypes; 6039 6040 /// MemberPointerTypes - The set of member pointer types that will be 6041 /// used in the built-in candidates. 6042 TypeSet MemberPointerTypes; 6043 6044 /// EnumerationTypes - The set of enumeration types that will be 6045 /// used in the built-in candidates. 6046 TypeSet EnumerationTypes; 6047 6048 /// \brief The set of vector types that will be used in the built-in 6049 /// candidates. 6050 TypeSet VectorTypes; 6051 6052 /// \brief A flag indicating non-record types are viable candidates 6053 bool HasNonRecordTypes; 6054 6055 /// \brief A flag indicating whether either arithmetic or enumeration types 6056 /// were present in the candidate set. 6057 bool HasArithmeticOrEnumeralTypes; 6058 6059 /// \brief A flag indicating whether the nullptr type was present in the 6060 /// candidate set. 6061 bool HasNullPtrType; 6062 6063 /// Sema - The semantic analysis instance where we are building the 6064 /// candidate type set. 6065 Sema &SemaRef; 6066 6067 /// Context - The AST context in which we will build the type sets. 6068 ASTContext &Context; 6069 6070 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6071 const Qualifiers &VisibleQuals); 6072 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6073 6074 public: 6075 /// iterator - Iterates through the types that are part of the set. 6076 typedef TypeSet::iterator iterator; 6077 6078 BuiltinCandidateTypeSet(Sema &SemaRef) 6079 : HasNonRecordTypes(false), 6080 HasArithmeticOrEnumeralTypes(false), 6081 HasNullPtrType(false), 6082 SemaRef(SemaRef), 6083 Context(SemaRef.Context) { } 6084 6085 void AddTypesConvertedFrom(QualType Ty, 6086 SourceLocation Loc, 6087 bool AllowUserConversions, 6088 bool AllowExplicitConversions, 6089 const Qualifiers &VisibleTypeConversionsQuals); 6090 6091 /// pointer_begin - First pointer type found; 6092 iterator pointer_begin() { return PointerTypes.begin(); } 6093 6094 /// pointer_end - Past the last pointer type found; 6095 iterator pointer_end() { return PointerTypes.end(); } 6096 6097 /// member_pointer_begin - First member pointer type found; 6098 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6099 6100 /// member_pointer_end - Past the last member pointer type found; 6101 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6102 6103 /// enumeration_begin - First enumeration type found; 6104 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6105 6106 /// enumeration_end - Past the last enumeration type found; 6107 iterator enumeration_end() { return EnumerationTypes.end(); } 6108 6109 iterator vector_begin() { return VectorTypes.begin(); } 6110 iterator vector_end() { return VectorTypes.end(); } 6111 6112 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6113 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6114 bool hasNullPtrType() const { return HasNullPtrType; } 6115 }; 6116 6117 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6118 /// the set of pointer types along with any more-qualified variants of 6119 /// that type. For example, if @p Ty is "int const *", this routine 6120 /// will add "int const *", "int const volatile *", "int const 6121 /// restrict *", and "int const volatile restrict *" to the set of 6122 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6123 /// false otherwise. 6124 /// 6125 /// FIXME: what to do about extended qualifiers? 6126 bool 6127 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6128 const Qualifiers &VisibleQuals) { 6129 6130 // Insert this type. 6131 if (!PointerTypes.insert(Ty)) 6132 return false; 6133 6134 QualType PointeeTy; 6135 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6136 bool buildObjCPtr = false; 6137 if (!PointerTy) { 6138 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6139 PointeeTy = PTy->getPointeeType(); 6140 buildObjCPtr = true; 6141 } else { 6142 PointeeTy = PointerTy->getPointeeType(); 6143 } 6144 6145 // Don't add qualified variants of arrays. For one, they're not allowed 6146 // (the qualifier would sink to the element type), and for another, the 6147 // only overload situation where it matters is subscript or pointer +- int, 6148 // and those shouldn't have qualifier variants anyway. 6149 if (PointeeTy->isArrayType()) 6150 return true; 6151 6152 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6153 bool hasVolatile = VisibleQuals.hasVolatile(); 6154 bool hasRestrict = VisibleQuals.hasRestrict(); 6155 6156 // Iterate through all strict supersets of BaseCVR. 6157 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6158 if ((CVR | BaseCVR) != CVR) continue; 6159 // Skip over volatile if no volatile found anywhere in the types. 6160 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6161 6162 // Skip over restrict if no restrict found anywhere in the types, or if 6163 // the type cannot be restrict-qualified. 6164 if ((CVR & Qualifiers::Restrict) && 6165 (!hasRestrict || 6166 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6167 continue; 6168 6169 // Build qualified pointee type. 6170 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6171 6172 // Build qualified pointer type. 6173 QualType QPointerTy; 6174 if (!buildObjCPtr) 6175 QPointerTy = Context.getPointerType(QPointeeTy); 6176 else 6177 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6178 6179 // Insert qualified pointer type. 6180 PointerTypes.insert(QPointerTy); 6181 } 6182 6183 return true; 6184 } 6185 6186 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6187 /// to the set of pointer types along with any more-qualified variants of 6188 /// that type. For example, if @p Ty is "int const *", this routine 6189 /// will add "int const *", "int const volatile *", "int const 6190 /// restrict *", and "int const volatile restrict *" to the set of 6191 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6192 /// false otherwise. 6193 /// 6194 /// FIXME: what to do about extended qualifiers? 6195 bool 6196 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6197 QualType Ty) { 6198 // Insert this type. 6199 if (!MemberPointerTypes.insert(Ty)) 6200 return false; 6201 6202 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6203 assert(PointerTy && "type was not a member pointer type!"); 6204 6205 QualType PointeeTy = PointerTy->getPointeeType(); 6206 // Don't add qualified variants of arrays. For one, they're not allowed 6207 // (the qualifier would sink to the element type), and for another, the 6208 // only overload situation where it matters is subscript or pointer +- int, 6209 // and those shouldn't have qualifier variants anyway. 6210 if (PointeeTy->isArrayType()) 6211 return true; 6212 const Type *ClassTy = PointerTy->getClass(); 6213 6214 // Iterate through all strict supersets of the pointee type's CVR 6215 // qualifiers. 6216 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6217 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6218 if ((CVR | BaseCVR) != CVR) continue; 6219 6220 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6221 MemberPointerTypes.insert( 6222 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6223 } 6224 6225 return true; 6226 } 6227 6228 /// AddTypesConvertedFrom - Add each of the types to which the type @p 6229 /// Ty can be implicit converted to the given set of @p Types. We're 6230 /// primarily interested in pointer types and enumeration types. We also 6231 /// take member pointer types, for the conditional operator. 6232 /// AllowUserConversions is true if we should look at the conversion 6233 /// functions of a class type, and AllowExplicitConversions if we 6234 /// should also include the explicit conversion functions of a class 6235 /// type. 6236 void 6237 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6238 SourceLocation Loc, 6239 bool AllowUserConversions, 6240 bool AllowExplicitConversions, 6241 const Qualifiers &VisibleQuals) { 6242 // Only deal with canonical types. 6243 Ty = Context.getCanonicalType(Ty); 6244 6245 // Look through reference types; they aren't part of the type of an 6246 // expression for the purposes of conversions. 6247 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6248 Ty = RefTy->getPointeeType(); 6249 6250 // If we're dealing with an array type, decay to the pointer. 6251 if (Ty->isArrayType()) 6252 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6253 6254 // Otherwise, we don't care about qualifiers on the type. 6255 Ty = Ty.getLocalUnqualifiedType(); 6256 6257 // Flag if we ever add a non-record type. 6258 const RecordType *TyRec = Ty->getAs<RecordType>(); 6259 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6260 6261 // Flag if we encounter an arithmetic type. 6262 HasArithmeticOrEnumeralTypes = 6263 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6264 6265 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6266 PointerTypes.insert(Ty); 6267 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6268 // Insert our type, and its more-qualified variants, into the set 6269 // of types. 6270 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6271 return; 6272 } else if (Ty->isMemberPointerType()) { 6273 // Member pointers are far easier, since the pointee can't be converted. 6274 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6275 return; 6276 } else if (Ty->isEnumeralType()) { 6277 HasArithmeticOrEnumeralTypes = true; 6278 EnumerationTypes.insert(Ty); 6279 } else if (Ty->isVectorType()) { 6280 // We treat vector types as arithmetic types in many contexts as an 6281 // extension. 6282 HasArithmeticOrEnumeralTypes = true; 6283 VectorTypes.insert(Ty); 6284 } else if (Ty->isNullPtrType()) { 6285 HasNullPtrType = true; 6286 } else if (AllowUserConversions && TyRec) { 6287 // No conversion functions in incomplete types. 6288 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6289 return; 6290 6291 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6292 std::pair<CXXRecordDecl::conversion_iterator, 6293 CXXRecordDecl::conversion_iterator> 6294 Conversions = ClassDecl->getVisibleConversionFunctions(); 6295 for (CXXRecordDecl::conversion_iterator 6296 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6297 NamedDecl *D = I.getDecl(); 6298 if (isa<UsingShadowDecl>(D)) 6299 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6300 6301 // Skip conversion function templates; they don't tell us anything 6302 // about which builtin types we can convert to. 6303 if (isa<FunctionTemplateDecl>(D)) 6304 continue; 6305 6306 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6307 if (AllowExplicitConversions || !Conv->isExplicit()) { 6308 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6309 VisibleQuals); 6310 } 6311 } 6312 } 6313 } 6314 6315 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6316 /// the volatile- and non-volatile-qualified assignment operators for the 6317 /// given type to the candidate set. 6318 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6319 QualType T, 6320 Expr **Args, 6321 unsigned NumArgs, 6322 OverloadCandidateSet &CandidateSet) { 6323 QualType ParamTypes[2]; 6324 6325 // T& operator=(T&, T) 6326 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6327 ParamTypes[1] = T; 6328 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 6329 /*IsAssignmentOperator=*/true); 6330 6331 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6332 // volatile T& operator=(volatile T&, T) 6333 ParamTypes[0] 6334 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6335 ParamTypes[1] = T; 6336 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 6337 /*IsAssignmentOperator=*/true); 6338 } 6339 } 6340 6341 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6342 /// if any, found in visible type conversion functions found in ArgExpr's type. 6343 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6344 Qualifiers VRQuals; 6345 const RecordType *TyRec; 6346 if (const MemberPointerType *RHSMPType = 6347 ArgExpr->getType()->getAs<MemberPointerType>()) 6348 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6349 else 6350 TyRec = ArgExpr->getType()->getAs<RecordType>(); 6351 if (!TyRec) { 6352 // Just to be safe, assume the worst case. 6353 VRQuals.addVolatile(); 6354 VRQuals.addRestrict(); 6355 return VRQuals; 6356 } 6357 6358 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6359 if (!ClassDecl->hasDefinition()) 6360 return VRQuals; 6361 6362 std::pair<CXXRecordDecl::conversion_iterator, 6363 CXXRecordDecl::conversion_iterator> 6364 Conversions = ClassDecl->getVisibleConversionFunctions(); 6365 6366 for (CXXRecordDecl::conversion_iterator 6367 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6368 NamedDecl *D = I.getDecl(); 6369 if (isa<UsingShadowDecl>(D)) 6370 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6371 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6372 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 6373 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 6374 CanTy = ResTypeRef->getPointeeType(); 6375 // Need to go down the pointer/mempointer chain and add qualifiers 6376 // as see them. 6377 bool done = false; 6378 while (!done) { 6379 if (CanTy.isRestrictQualified()) 6380 VRQuals.addRestrict(); 6381 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 6382 CanTy = ResTypePtr->getPointeeType(); 6383 else if (const MemberPointerType *ResTypeMPtr = 6384 CanTy->getAs<MemberPointerType>()) 6385 CanTy = ResTypeMPtr->getPointeeType(); 6386 else 6387 done = true; 6388 if (CanTy.isVolatileQualified()) 6389 VRQuals.addVolatile(); 6390 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 6391 return VRQuals; 6392 } 6393 } 6394 } 6395 return VRQuals; 6396 } 6397 6398 namespace { 6399 6400 /// \brief Helper class to manage the addition of builtin operator overload 6401 /// candidates. It provides shared state and utility methods used throughout 6402 /// the process, as well as a helper method to add each group of builtin 6403 /// operator overloads from the standard to a candidate set. 6404 class BuiltinOperatorOverloadBuilder { 6405 // Common instance state available to all overload candidate addition methods. 6406 Sema &S; 6407 Expr **Args; 6408 unsigned NumArgs; 6409 Qualifiers VisibleTypeConversionsQuals; 6410 bool HasArithmeticOrEnumeralCandidateType; 6411 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 6412 OverloadCandidateSet &CandidateSet; 6413 6414 // Define some constants used to index and iterate over the arithemetic types 6415 // provided via the getArithmeticType() method below. 6416 // The "promoted arithmetic types" are the arithmetic 6417 // types are that preserved by promotion (C++ [over.built]p2). 6418 static const unsigned FirstIntegralType = 3; 6419 static const unsigned LastIntegralType = 20; 6420 static const unsigned FirstPromotedIntegralType = 3, 6421 LastPromotedIntegralType = 11; 6422 static const unsigned FirstPromotedArithmeticType = 0, 6423 LastPromotedArithmeticType = 11; 6424 static const unsigned NumArithmeticTypes = 20; 6425 6426 /// \brief Get the canonical type for a given arithmetic type index. 6427 CanQualType getArithmeticType(unsigned index) { 6428 assert(index < NumArithmeticTypes); 6429 static CanQualType ASTContext::* const 6430 ArithmeticTypes[NumArithmeticTypes] = { 6431 // Start of promoted types. 6432 &ASTContext::FloatTy, 6433 &ASTContext::DoubleTy, 6434 &ASTContext::LongDoubleTy, 6435 6436 // Start of integral types. 6437 &ASTContext::IntTy, 6438 &ASTContext::LongTy, 6439 &ASTContext::LongLongTy, 6440 &ASTContext::Int128Ty, 6441 &ASTContext::UnsignedIntTy, 6442 &ASTContext::UnsignedLongTy, 6443 &ASTContext::UnsignedLongLongTy, 6444 &ASTContext::UnsignedInt128Ty, 6445 // End of promoted types. 6446 6447 &ASTContext::BoolTy, 6448 &ASTContext::CharTy, 6449 &ASTContext::WCharTy, 6450 &ASTContext::Char16Ty, 6451 &ASTContext::Char32Ty, 6452 &ASTContext::SignedCharTy, 6453 &ASTContext::ShortTy, 6454 &ASTContext::UnsignedCharTy, 6455 &ASTContext::UnsignedShortTy, 6456 // End of integral types. 6457 // FIXME: What about complex? What about half? 6458 }; 6459 return S.Context.*ArithmeticTypes[index]; 6460 } 6461 6462 /// \brief Gets the canonical type resulting from the usual arithemetic 6463 /// converions for the given arithmetic types. 6464 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 6465 // Accelerator table for performing the usual arithmetic conversions. 6466 // The rules are basically: 6467 // - if either is floating-point, use the wider floating-point 6468 // - if same signedness, use the higher rank 6469 // - if same size, use unsigned of the higher rank 6470 // - use the larger type 6471 // These rules, together with the axiom that higher ranks are 6472 // never smaller, are sufficient to precompute all of these results 6473 // *except* when dealing with signed types of higher rank. 6474 // (we could precompute SLL x UI for all known platforms, but it's 6475 // better not to make any assumptions). 6476 // We assume that int128 has a higher rank than long long on all platforms. 6477 enum PromotedType { 6478 Dep=-1, 6479 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 6480 }; 6481 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 6482 [LastPromotedArithmeticType] = { 6483 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 6484 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 6485 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 6486 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 6487 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 6488 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 6489 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 6490 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 6491 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 6492 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 6493 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 6494 }; 6495 6496 assert(L < LastPromotedArithmeticType); 6497 assert(R < LastPromotedArithmeticType); 6498 int Idx = ConversionsTable[L][R]; 6499 6500 // Fast path: the table gives us a concrete answer. 6501 if (Idx != Dep) return getArithmeticType(Idx); 6502 6503 // Slow path: we need to compare widths. 6504 // An invariant is that the signed type has higher rank. 6505 CanQualType LT = getArithmeticType(L), 6506 RT = getArithmeticType(R); 6507 unsigned LW = S.Context.getIntWidth(LT), 6508 RW = S.Context.getIntWidth(RT); 6509 6510 // If they're different widths, use the signed type. 6511 if (LW > RW) return LT; 6512 else if (LW < RW) return RT; 6513 6514 // Otherwise, use the unsigned type of the signed type's rank. 6515 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 6516 assert(L == SLL || R == SLL); 6517 return S.Context.UnsignedLongLongTy; 6518 } 6519 6520 /// \brief Helper method to factor out the common pattern of adding overloads 6521 /// for '++' and '--' builtin operators. 6522 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 6523 bool HasVolatile, 6524 bool HasRestrict) { 6525 QualType ParamTypes[2] = { 6526 S.Context.getLValueReferenceType(CandidateTy), 6527 S.Context.IntTy 6528 }; 6529 6530 // Non-volatile version. 6531 if (NumArgs == 1) 6532 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6533 else 6534 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6535 6536 // Use a heuristic to reduce number of builtin candidates in the set: 6537 // add volatile version only if there are conversions to a volatile type. 6538 if (HasVolatile) { 6539 ParamTypes[0] = 6540 S.Context.getLValueReferenceType( 6541 S.Context.getVolatileType(CandidateTy)); 6542 if (NumArgs == 1) 6543 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6544 else 6545 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6546 } 6547 6548 // Add restrict version only if there are conversions to a restrict type 6549 // and our candidate type is a non-restrict-qualified pointer. 6550 if (HasRestrict && CandidateTy->isAnyPointerType() && 6551 !CandidateTy.isRestrictQualified()) { 6552 ParamTypes[0] 6553 = S.Context.getLValueReferenceType( 6554 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 6555 if (NumArgs == 1) 6556 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6557 else 6558 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6559 6560 if (HasVolatile) { 6561 ParamTypes[0] 6562 = S.Context.getLValueReferenceType( 6563 S.Context.getCVRQualifiedType(CandidateTy, 6564 (Qualifiers::Volatile | 6565 Qualifiers::Restrict))); 6566 if (NumArgs == 1) 6567 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, 6568 CandidateSet); 6569 else 6570 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6571 } 6572 } 6573 6574 } 6575 6576 public: 6577 BuiltinOperatorOverloadBuilder( 6578 Sema &S, Expr **Args, unsigned NumArgs, 6579 Qualifiers VisibleTypeConversionsQuals, 6580 bool HasArithmeticOrEnumeralCandidateType, 6581 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 6582 OverloadCandidateSet &CandidateSet) 6583 : S(S), Args(Args), NumArgs(NumArgs), 6584 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 6585 HasArithmeticOrEnumeralCandidateType( 6586 HasArithmeticOrEnumeralCandidateType), 6587 CandidateTypes(CandidateTypes), 6588 CandidateSet(CandidateSet) { 6589 // Validate some of our static helper constants in debug builds. 6590 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 6591 "Invalid first promoted integral type"); 6592 assert(getArithmeticType(LastPromotedIntegralType - 1) 6593 == S.Context.UnsignedInt128Ty && 6594 "Invalid last promoted integral type"); 6595 assert(getArithmeticType(FirstPromotedArithmeticType) 6596 == S.Context.FloatTy && 6597 "Invalid first promoted arithmetic type"); 6598 assert(getArithmeticType(LastPromotedArithmeticType - 1) 6599 == S.Context.UnsignedInt128Ty && 6600 "Invalid last promoted arithmetic type"); 6601 } 6602 6603 // C++ [over.built]p3: 6604 // 6605 // For every pair (T, VQ), where T is an arithmetic type, and VQ 6606 // is either volatile or empty, there exist candidate operator 6607 // functions of the form 6608 // 6609 // VQ T& operator++(VQ T&); 6610 // T operator++(VQ T&, int); 6611 // 6612 // C++ [over.built]p4: 6613 // 6614 // For every pair (T, VQ), where T is an arithmetic type other 6615 // than bool, and VQ is either volatile or empty, there exist 6616 // candidate operator functions of the form 6617 // 6618 // VQ T& operator--(VQ T&); 6619 // T operator--(VQ T&, int); 6620 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 6621 if (!HasArithmeticOrEnumeralCandidateType) 6622 return; 6623 6624 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 6625 Arith < NumArithmeticTypes; ++Arith) { 6626 addPlusPlusMinusMinusStyleOverloads( 6627 getArithmeticType(Arith), 6628 VisibleTypeConversionsQuals.hasVolatile(), 6629 VisibleTypeConversionsQuals.hasRestrict()); 6630 } 6631 } 6632 6633 // C++ [over.built]p5: 6634 // 6635 // For every pair (T, VQ), where T is a cv-qualified or 6636 // cv-unqualified object type, and VQ is either volatile or 6637 // empty, there exist candidate operator functions of the form 6638 // 6639 // T*VQ& operator++(T*VQ&); 6640 // T*VQ& operator--(T*VQ&); 6641 // T* operator++(T*VQ&, int); 6642 // T* operator--(T*VQ&, int); 6643 void addPlusPlusMinusMinusPointerOverloads() { 6644 for (BuiltinCandidateTypeSet::iterator 6645 Ptr = CandidateTypes[0].pointer_begin(), 6646 PtrEnd = CandidateTypes[0].pointer_end(); 6647 Ptr != PtrEnd; ++Ptr) { 6648 // Skip pointer types that aren't pointers to object types. 6649 if (!(*Ptr)->getPointeeType()->isObjectType()) 6650 continue; 6651 6652 addPlusPlusMinusMinusStyleOverloads(*Ptr, 6653 (!(*Ptr).isVolatileQualified() && 6654 VisibleTypeConversionsQuals.hasVolatile()), 6655 (!(*Ptr).isRestrictQualified() && 6656 VisibleTypeConversionsQuals.hasRestrict())); 6657 } 6658 } 6659 6660 // C++ [over.built]p6: 6661 // For every cv-qualified or cv-unqualified object type T, there 6662 // exist candidate operator functions of the form 6663 // 6664 // T& operator*(T*); 6665 // 6666 // C++ [over.built]p7: 6667 // For every function type T that does not have cv-qualifiers or a 6668 // ref-qualifier, there exist candidate operator functions of the form 6669 // T& operator*(T*); 6670 void addUnaryStarPointerOverloads() { 6671 for (BuiltinCandidateTypeSet::iterator 6672 Ptr = CandidateTypes[0].pointer_begin(), 6673 PtrEnd = CandidateTypes[0].pointer_end(); 6674 Ptr != PtrEnd; ++Ptr) { 6675 QualType ParamTy = *Ptr; 6676 QualType PointeeTy = ParamTy->getPointeeType(); 6677 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 6678 continue; 6679 6680 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 6681 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 6682 continue; 6683 6684 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 6685 &ParamTy, Args, 1, CandidateSet); 6686 } 6687 } 6688 6689 // C++ [over.built]p9: 6690 // For every promoted arithmetic type T, there exist candidate 6691 // operator functions of the form 6692 // 6693 // T operator+(T); 6694 // T operator-(T); 6695 void addUnaryPlusOrMinusArithmeticOverloads() { 6696 if (!HasArithmeticOrEnumeralCandidateType) 6697 return; 6698 6699 for (unsigned Arith = FirstPromotedArithmeticType; 6700 Arith < LastPromotedArithmeticType; ++Arith) { 6701 QualType ArithTy = getArithmeticType(Arith); 6702 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet); 6703 } 6704 6705 // Extension: We also add these operators for vector types. 6706 for (BuiltinCandidateTypeSet::iterator 6707 Vec = CandidateTypes[0].vector_begin(), 6708 VecEnd = CandidateTypes[0].vector_end(); 6709 Vec != VecEnd; ++Vec) { 6710 QualType VecTy = *Vec; 6711 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 6712 } 6713 } 6714 6715 // C++ [over.built]p8: 6716 // For every type T, there exist candidate operator functions of 6717 // the form 6718 // 6719 // T* operator+(T*); 6720 void addUnaryPlusPointerOverloads() { 6721 for (BuiltinCandidateTypeSet::iterator 6722 Ptr = CandidateTypes[0].pointer_begin(), 6723 PtrEnd = CandidateTypes[0].pointer_end(); 6724 Ptr != PtrEnd; ++Ptr) { 6725 QualType ParamTy = *Ptr; 6726 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 6727 } 6728 } 6729 6730 // C++ [over.built]p10: 6731 // For every promoted integral type T, there exist candidate 6732 // operator functions of the form 6733 // 6734 // T operator~(T); 6735 void addUnaryTildePromotedIntegralOverloads() { 6736 if (!HasArithmeticOrEnumeralCandidateType) 6737 return; 6738 6739 for (unsigned Int = FirstPromotedIntegralType; 6740 Int < LastPromotedIntegralType; ++Int) { 6741 QualType IntTy = getArithmeticType(Int); 6742 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet); 6743 } 6744 6745 // Extension: We also add this operator for vector types. 6746 for (BuiltinCandidateTypeSet::iterator 6747 Vec = CandidateTypes[0].vector_begin(), 6748 VecEnd = CandidateTypes[0].vector_end(); 6749 Vec != VecEnd; ++Vec) { 6750 QualType VecTy = *Vec; 6751 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 6752 } 6753 } 6754 6755 // C++ [over.match.oper]p16: 6756 // For every pointer to member type T, there exist candidate operator 6757 // functions of the form 6758 // 6759 // bool operator==(T,T); 6760 // bool operator!=(T,T); 6761 void addEqualEqualOrNotEqualMemberPointerOverloads() { 6762 /// Set of (canonical) types that we've already handled. 6763 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6764 6765 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6766 for (BuiltinCandidateTypeSet::iterator 6767 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 6768 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 6769 MemPtr != MemPtrEnd; 6770 ++MemPtr) { 6771 // Don't add the same builtin candidate twice. 6772 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 6773 continue; 6774 6775 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 6776 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6777 CandidateSet); 6778 } 6779 } 6780 } 6781 6782 // C++ [over.built]p15: 6783 // 6784 // For every T, where T is an enumeration type, a pointer type, or 6785 // std::nullptr_t, there exist candidate operator functions of the form 6786 // 6787 // bool operator<(T, T); 6788 // bool operator>(T, T); 6789 // bool operator<=(T, T); 6790 // bool operator>=(T, T); 6791 // bool operator==(T, T); 6792 // bool operator!=(T, T); 6793 void addRelationalPointerOrEnumeralOverloads() { 6794 // C++ [over.match.oper]p3: 6795 // [...]the built-in candidates include all of the candidate operator 6796 // functions defined in 13.6 that, compared to the given operator, [...] 6797 // do not have the same parameter-type-list as any non-template non-member 6798 // candidate. 6799 // 6800 // Note that in practice, this only affects enumeration types because there 6801 // aren't any built-in candidates of record type, and a user-defined operator 6802 // must have an operand of record or enumeration type. Also, the only other 6803 // overloaded operator with enumeration arguments, operator=, 6804 // cannot be overloaded for enumeration types, so this is the only place 6805 // where we must suppress candidates like this. 6806 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 6807 UserDefinedBinaryOperators; 6808 6809 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6810 if (CandidateTypes[ArgIdx].enumeration_begin() != 6811 CandidateTypes[ArgIdx].enumeration_end()) { 6812 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 6813 CEnd = CandidateSet.end(); 6814 C != CEnd; ++C) { 6815 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 6816 continue; 6817 6818 if (C->Function->isFunctionTemplateSpecialization()) 6819 continue; 6820 6821 QualType FirstParamType = 6822 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 6823 QualType SecondParamType = 6824 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 6825 6826 // Skip if either parameter isn't of enumeral type. 6827 if (!FirstParamType->isEnumeralType() || 6828 !SecondParamType->isEnumeralType()) 6829 continue; 6830 6831 // Add this operator to the set of known user-defined operators. 6832 UserDefinedBinaryOperators.insert( 6833 std::make_pair(S.Context.getCanonicalType(FirstParamType), 6834 S.Context.getCanonicalType(SecondParamType))); 6835 } 6836 } 6837 } 6838 6839 /// Set of (canonical) types that we've already handled. 6840 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6841 6842 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6843 for (BuiltinCandidateTypeSet::iterator 6844 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 6845 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 6846 Ptr != PtrEnd; ++Ptr) { 6847 // Don't add the same builtin candidate twice. 6848 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 6849 continue; 6850 6851 QualType ParamTypes[2] = { *Ptr, *Ptr }; 6852 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6853 CandidateSet); 6854 } 6855 for (BuiltinCandidateTypeSet::iterator 6856 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 6857 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 6858 Enum != EnumEnd; ++Enum) { 6859 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 6860 6861 // Don't add the same builtin candidate twice, or if a user defined 6862 // candidate exists. 6863 if (!AddedTypes.insert(CanonType) || 6864 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 6865 CanonType))) 6866 continue; 6867 6868 QualType ParamTypes[2] = { *Enum, *Enum }; 6869 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6870 CandidateSet); 6871 } 6872 6873 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 6874 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 6875 if (AddedTypes.insert(NullPtrTy) && 6876 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 6877 NullPtrTy))) { 6878 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 6879 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6880 CandidateSet); 6881 } 6882 } 6883 } 6884 } 6885 6886 // C++ [over.built]p13: 6887 // 6888 // For every cv-qualified or cv-unqualified object type T 6889 // there exist candidate operator functions of the form 6890 // 6891 // T* operator+(T*, ptrdiff_t); 6892 // T& operator[](T*, ptrdiff_t); [BELOW] 6893 // T* operator-(T*, ptrdiff_t); 6894 // T* operator+(ptrdiff_t, T*); 6895 // T& operator[](ptrdiff_t, T*); [BELOW] 6896 // 6897 // C++ [over.built]p14: 6898 // 6899 // For every T, where T is a pointer to object type, there 6900 // exist candidate operator functions of the form 6901 // 6902 // ptrdiff_t operator-(T, T); 6903 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 6904 /// Set of (canonical) types that we've already handled. 6905 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6906 6907 for (int Arg = 0; Arg < 2; ++Arg) { 6908 QualType AsymetricParamTypes[2] = { 6909 S.Context.getPointerDiffType(), 6910 S.Context.getPointerDiffType(), 6911 }; 6912 for (BuiltinCandidateTypeSet::iterator 6913 Ptr = CandidateTypes[Arg].pointer_begin(), 6914 PtrEnd = CandidateTypes[Arg].pointer_end(); 6915 Ptr != PtrEnd; ++Ptr) { 6916 QualType PointeeTy = (*Ptr)->getPointeeType(); 6917 if (!PointeeTy->isObjectType()) 6918 continue; 6919 6920 AsymetricParamTypes[Arg] = *Ptr; 6921 if (Arg == 0 || Op == OO_Plus) { 6922 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 6923 // T* operator+(ptrdiff_t, T*); 6924 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2, 6925 CandidateSet); 6926 } 6927 if (Op == OO_Minus) { 6928 // ptrdiff_t operator-(T, T); 6929 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 6930 continue; 6931 6932 QualType ParamTypes[2] = { *Ptr, *Ptr }; 6933 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 6934 Args, 2, CandidateSet); 6935 } 6936 } 6937 } 6938 } 6939 6940 // C++ [over.built]p12: 6941 // 6942 // For every pair of promoted arithmetic types L and R, there 6943 // exist candidate operator functions of the form 6944 // 6945 // LR operator*(L, R); 6946 // LR operator/(L, R); 6947 // LR operator+(L, R); 6948 // LR operator-(L, R); 6949 // bool operator<(L, R); 6950 // bool operator>(L, R); 6951 // bool operator<=(L, R); 6952 // bool operator>=(L, R); 6953 // bool operator==(L, R); 6954 // bool operator!=(L, R); 6955 // 6956 // where LR is the result of the usual arithmetic conversions 6957 // between types L and R. 6958 // 6959 // C++ [over.built]p24: 6960 // 6961 // For every pair of promoted arithmetic types L and R, there exist 6962 // candidate operator functions of the form 6963 // 6964 // LR operator?(bool, L, R); 6965 // 6966 // where LR is the result of the usual arithmetic conversions 6967 // between types L and R. 6968 // Our candidates ignore the first parameter. 6969 void addGenericBinaryArithmeticOverloads(bool isComparison) { 6970 if (!HasArithmeticOrEnumeralCandidateType) 6971 return; 6972 6973 for (unsigned Left = FirstPromotedArithmeticType; 6974 Left < LastPromotedArithmeticType; ++Left) { 6975 for (unsigned Right = FirstPromotedArithmeticType; 6976 Right < LastPromotedArithmeticType; ++Right) { 6977 QualType LandR[2] = { getArithmeticType(Left), 6978 getArithmeticType(Right) }; 6979 QualType Result = 6980 isComparison ? S.Context.BoolTy 6981 : getUsualArithmeticConversions(Left, Right); 6982 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 6983 } 6984 } 6985 6986 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 6987 // conditional operator for vector types. 6988 for (BuiltinCandidateTypeSet::iterator 6989 Vec1 = CandidateTypes[0].vector_begin(), 6990 Vec1End = CandidateTypes[0].vector_end(); 6991 Vec1 != Vec1End; ++Vec1) { 6992 for (BuiltinCandidateTypeSet::iterator 6993 Vec2 = CandidateTypes[1].vector_begin(), 6994 Vec2End = CandidateTypes[1].vector_end(); 6995 Vec2 != Vec2End; ++Vec2) { 6996 QualType LandR[2] = { *Vec1, *Vec2 }; 6997 QualType Result = S.Context.BoolTy; 6998 if (!isComparison) { 6999 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7000 Result = *Vec1; 7001 else 7002 Result = *Vec2; 7003 } 7004 7005 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 7006 } 7007 } 7008 } 7009 7010 // C++ [over.built]p17: 7011 // 7012 // For every pair of promoted integral types L and R, there 7013 // exist candidate operator functions of the form 7014 // 7015 // LR operator%(L, R); 7016 // LR operator&(L, R); 7017 // LR operator^(L, R); 7018 // LR operator|(L, R); 7019 // L operator<<(L, R); 7020 // L operator>>(L, R); 7021 // 7022 // where LR is the result of the usual arithmetic conversions 7023 // between types L and R. 7024 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7025 if (!HasArithmeticOrEnumeralCandidateType) 7026 return; 7027 7028 for (unsigned Left = FirstPromotedIntegralType; 7029 Left < LastPromotedIntegralType; ++Left) { 7030 for (unsigned Right = FirstPromotedIntegralType; 7031 Right < LastPromotedIntegralType; ++Right) { 7032 QualType LandR[2] = { getArithmeticType(Left), 7033 getArithmeticType(Right) }; 7034 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7035 ? LandR[0] 7036 : getUsualArithmeticConversions(Left, Right); 7037 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 7038 } 7039 } 7040 } 7041 7042 // C++ [over.built]p20: 7043 // 7044 // For every pair (T, VQ), where T is an enumeration or 7045 // pointer to member type and VQ is either volatile or 7046 // empty, there exist candidate operator functions of the form 7047 // 7048 // VQ T& operator=(VQ T&, T); 7049 void addAssignmentMemberPointerOrEnumeralOverloads() { 7050 /// Set of (canonical) types that we've already handled. 7051 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7052 7053 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7054 for (BuiltinCandidateTypeSet::iterator 7055 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7056 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7057 Enum != EnumEnd; ++Enum) { 7058 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7059 continue; 7060 7061 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2, 7062 CandidateSet); 7063 } 7064 7065 for (BuiltinCandidateTypeSet::iterator 7066 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7067 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7068 MemPtr != MemPtrEnd; ++MemPtr) { 7069 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7070 continue; 7071 7072 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2, 7073 CandidateSet); 7074 } 7075 } 7076 } 7077 7078 // C++ [over.built]p19: 7079 // 7080 // For every pair (T, VQ), where T is any type and VQ is either 7081 // volatile or empty, there exist candidate operator functions 7082 // of the form 7083 // 7084 // T*VQ& operator=(T*VQ&, T*); 7085 // 7086 // C++ [over.built]p21: 7087 // 7088 // For every pair (T, VQ), where T is a cv-qualified or 7089 // cv-unqualified object type and VQ is either volatile or 7090 // empty, there exist candidate operator functions of the form 7091 // 7092 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7093 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7094 void addAssignmentPointerOverloads(bool isEqualOp) { 7095 /// Set of (canonical) types that we've already handled. 7096 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7097 7098 for (BuiltinCandidateTypeSet::iterator 7099 Ptr = CandidateTypes[0].pointer_begin(), 7100 PtrEnd = CandidateTypes[0].pointer_end(); 7101 Ptr != PtrEnd; ++Ptr) { 7102 // If this is operator=, keep track of the builtin candidates we added. 7103 if (isEqualOp) 7104 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7105 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7106 continue; 7107 7108 // non-volatile version 7109 QualType ParamTypes[2] = { 7110 S.Context.getLValueReferenceType(*Ptr), 7111 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7112 }; 7113 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7114 /*IsAssigmentOperator=*/ isEqualOp); 7115 7116 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7117 VisibleTypeConversionsQuals.hasVolatile(); 7118 if (NeedVolatile) { 7119 // volatile version 7120 ParamTypes[0] = 7121 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7122 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7123 /*IsAssigmentOperator=*/isEqualOp); 7124 } 7125 7126 if (!(*Ptr).isRestrictQualified() && 7127 VisibleTypeConversionsQuals.hasRestrict()) { 7128 // restrict version 7129 ParamTypes[0] 7130 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7131 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7132 /*IsAssigmentOperator=*/isEqualOp); 7133 7134 if (NeedVolatile) { 7135 // volatile restrict version 7136 ParamTypes[0] 7137 = S.Context.getLValueReferenceType( 7138 S.Context.getCVRQualifiedType(*Ptr, 7139 (Qualifiers::Volatile | 7140 Qualifiers::Restrict))); 7141 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7142 CandidateSet, 7143 /*IsAssigmentOperator=*/isEqualOp); 7144 } 7145 } 7146 } 7147 7148 if (isEqualOp) { 7149 for (BuiltinCandidateTypeSet::iterator 7150 Ptr = CandidateTypes[1].pointer_begin(), 7151 PtrEnd = CandidateTypes[1].pointer_end(); 7152 Ptr != PtrEnd; ++Ptr) { 7153 // Make sure we don't add the same candidate twice. 7154 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7155 continue; 7156 7157 QualType ParamTypes[2] = { 7158 S.Context.getLValueReferenceType(*Ptr), 7159 *Ptr, 7160 }; 7161 7162 // non-volatile version 7163 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7164 /*IsAssigmentOperator=*/true); 7165 7166 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7167 VisibleTypeConversionsQuals.hasVolatile(); 7168 if (NeedVolatile) { 7169 // volatile version 7170 ParamTypes[0] = 7171 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7172 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7173 CandidateSet, /*IsAssigmentOperator=*/true); 7174 } 7175 7176 if (!(*Ptr).isRestrictQualified() && 7177 VisibleTypeConversionsQuals.hasRestrict()) { 7178 // restrict version 7179 ParamTypes[0] 7180 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7181 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7182 CandidateSet, /*IsAssigmentOperator=*/true); 7183 7184 if (NeedVolatile) { 7185 // volatile restrict version 7186 ParamTypes[0] 7187 = S.Context.getLValueReferenceType( 7188 S.Context.getCVRQualifiedType(*Ptr, 7189 (Qualifiers::Volatile | 7190 Qualifiers::Restrict))); 7191 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7192 CandidateSet, /*IsAssigmentOperator=*/true); 7193 7194 } 7195 } 7196 } 7197 } 7198 } 7199 7200 // C++ [over.built]p18: 7201 // 7202 // For every triple (L, VQ, R), where L is an arithmetic type, 7203 // VQ is either volatile or empty, and R is a promoted 7204 // arithmetic type, there exist candidate operator functions of 7205 // the form 7206 // 7207 // VQ L& operator=(VQ L&, R); 7208 // VQ L& operator*=(VQ L&, R); 7209 // VQ L& operator/=(VQ L&, R); 7210 // VQ L& operator+=(VQ L&, R); 7211 // VQ L& operator-=(VQ L&, R); 7212 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7213 if (!HasArithmeticOrEnumeralCandidateType) 7214 return; 7215 7216 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7217 for (unsigned Right = FirstPromotedArithmeticType; 7218 Right < LastPromotedArithmeticType; ++Right) { 7219 QualType ParamTypes[2]; 7220 ParamTypes[1] = getArithmeticType(Right); 7221 7222 // Add this built-in operator as a candidate (VQ is empty). 7223 ParamTypes[0] = 7224 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7225 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7226 /*IsAssigmentOperator=*/isEqualOp); 7227 7228 // Add this built-in operator as a candidate (VQ is 'volatile'). 7229 if (VisibleTypeConversionsQuals.hasVolatile()) { 7230 ParamTypes[0] = 7231 S.Context.getVolatileType(getArithmeticType(Left)); 7232 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7233 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7234 CandidateSet, 7235 /*IsAssigmentOperator=*/isEqualOp); 7236 } 7237 } 7238 } 7239 7240 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7241 for (BuiltinCandidateTypeSet::iterator 7242 Vec1 = CandidateTypes[0].vector_begin(), 7243 Vec1End = CandidateTypes[0].vector_end(); 7244 Vec1 != Vec1End; ++Vec1) { 7245 for (BuiltinCandidateTypeSet::iterator 7246 Vec2 = CandidateTypes[1].vector_begin(), 7247 Vec2End = CandidateTypes[1].vector_end(); 7248 Vec2 != Vec2End; ++Vec2) { 7249 QualType ParamTypes[2]; 7250 ParamTypes[1] = *Vec2; 7251 // Add this built-in operator as a candidate (VQ is empty). 7252 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7253 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7254 /*IsAssigmentOperator=*/isEqualOp); 7255 7256 // Add this built-in operator as a candidate (VQ is 'volatile'). 7257 if (VisibleTypeConversionsQuals.hasVolatile()) { 7258 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7259 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7260 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7261 CandidateSet, 7262 /*IsAssigmentOperator=*/isEqualOp); 7263 } 7264 } 7265 } 7266 } 7267 7268 // C++ [over.built]p22: 7269 // 7270 // For every triple (L, VQ, R), where L is an integral type, VQ 7271 // is either volatile or empty, and R is a promoted integral 7272 // type, there exist candidate operator functions of the form 7273 // 7274 // VQ L& operator%=(VQ L&, R); 7275 // VQ L& operator<<=(VQ L&, R); 7276 // VQ L& operator>>=(VQ L&, R); 7277 // VQ L& operator&=(VQ L&, R); 7278 // VQ L& operator^=(VQ L&, R); 7279 // VQ L& operator|=(VQ L&, R); 7280 void addAssignmentIntegralOverloads() { 7281 if (!HasArithmeticOrEnumeralCandidateType) 7282 return; 7283 7284 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7285 for (unsigned Right = FirstPromotedIntegralType; 7286 Right < LastPromotedIntegralType; ++Right) { 7287 QualType ParamTypes[2]; 7288 ParamTypes[1] = getArithmeticType(Right); 7289 7290 // Add this built-in operator as a candidate (VQ is empty). 7291 ParamTypes[0] = 7292 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7293 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 7294 if (VisibleTypeConversionsQuals.hasVolatile()) { 7295 // Add this built-in operator as a candidate (VQ is 'volatile'). 7296 ParamTypes[0] = getArithmeticType(Left); 7297 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7298 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7299 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7300 CandidateSet); 7301 } 7302 } 7303 } 7304 } 7305 7306 // C++ [over.operator]p23: 7307 // 7308 // There also exist candidate operator functions of the form 7309 // 7310 // bool operator!(bool); 7311 // bool operator&&(bool, bool); 7312 // bool operator||(bool, bool); 7313 void addExclaimOverload() { 7314 QualType ParamTy = S.Context.BoolTy; 7315 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet, 7316 /*IsAssignmentOperator=*/false, 7317 /*NumContextualBoolArguments=*/1); 7318 } 7319 void addAmpAmpOrPipePipeOverload() { 7320 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7321 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet, 7322 /*IsAssignmentOperator=*/false, 7323 /*NumContextualBoolArguments=*/2); 7324 } 7325 7326 // C++ [over.built]p13: 7327 // 7328 // For every cv-qualified or cv-unqualified object type T there 7329 // exist candidate operator functions of the form 7330 // 7331 // T* operator+(T*, ptrdiff_t); [ABOVE] 7332 // T& operator[](T*, ptrdiff_t); 7333 // T* operator-(T*, ptrdiff_t); [ABOVE] 7334 // T* operator+(ptrdiff_t, T*); [ABOVE] 7335 // T& operator[](ptrdiff_t, T*); 7336 void addSubscriptOverloads() { 7337 for (BuiltinCandidateTypeSet::iterator 7338 Ptr = CandidateTypes[0].pointer_begin(), 7339 PtrEnd = CandidateTypes[0].pointer_end(); 7340 Ptr != PtrEnd; ++Ptr) { 7341 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7342 QualType PointeeType = (*Ptr)->getPointeeType(); 7343 if (!PointeeType->isObjectType()) 7344 continue; 7345 7346 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7347 7348 // T& operator[](T*, ptrdiff_t) 7349 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7350 } 7351 7352 for (BuiltinCandidateTypeSet::iterator 7353 Ptr = CandidateTypes[1].pointer_begin(), 7354 PtrEnd = CandidateTypes[1].pointer_end(); 7355 Ptr != PtrEnd; ++Ptr) { 7356 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7357 QualType PointeeType = (*Ptr)->getPointeeType(); 7358 if (!PointeeType->isObjectType()) 7359 continue; 7360 7361 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7362 7363 // T& operator[](ptrdiff_t, T*) 7364 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7365 } 7366 } 7367 7368 // C++ [over.built]p11: 7369 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7370 // C1 is the same type as C2 or is a derived class of C2, T is an object 7371 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7372 // there exist candidate operator functions of the form 7373 // 7374 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7375 // 7376 // where CV12 is the union of CV1 and CV2. 7377 void addArrowStarOverloads() { 7378 for (BuiltinCandidateTypeSet::iterator 7379 Ptr = CandidateTypes[0].pointer_begin(), 7380 PtrEnd = CandidateTypes[0].pointer_end(); 7381 Ptr != PtrEnd; ++Ptr) { 7382 QualType C1Ty = (*Ptr); 7383 QualType C1; 7384 QualifierCollector Q1; 7385 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 7386 if (!isa<RecordType>(C1)) 7387 continue; 7388 // heuristic to reduce number of builtin candidates in the set. 7389 // Add volatile/restrict version only if there are conversions to a 7390 // volatile/restrict type. 7391 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 7392 continue; 7393 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 7394 continue; 7395 for (BuiltinCandidateTypeSet::iterator 7396 MemPtr = CandidateTypes[1].member_pointer_begin(), 7397 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 7398 MemPtr != MemPtrEnd; ++MemPtr) { 7399 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 7400 QualType C2 = QualType(mptr->getClass(), 0); 7401 C2 = C2.getUnqualifiedType(); 7402 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 7403 break; 7404 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 7405 // build CV12 T& 7406 QualType T = mptr->getPointeeType(); 7407 if (!VisibleTypeConversionsQuals.hasVolatile() && 7408 T.isVolatileQualified()) 7409 continue; 7410 if (!VisibleTypeConversionsQuals.hasRestrict() && 7411 T.isRestrictQualified()) 7412 continue; 7413 T = Q1.apply(S.Context, T); 7414 QualType ResultTy = S.Context.getLValueReferenceType(T); 7415 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7416 } 7417 } 7418 } 7419 7420 // Note that we don't consider the first argument, since it has been 7421 // contextually converted to bool long ago. The candidates below are 7422 // therefore added as binary. 7423 // 7424 // C++ [over.built]p25: 7425 // For every type T, where T is a pointer, pointer-to-member, or scoped 7426 // enumeration type, there exist candidate operator functions of the form 7427 // 7428 // T operator?(bool, T, T); 7429 // 7430 void addConditionalOperatorOverloads() { 7431 /// Set of (canonical) types that we've already handled. 7432 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7433 7434 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7435 for (BuiltinCandidateTypeSet::iterator 7436 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7437 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7438 Ptr != PtrEnd; ++Ptr) { 7439 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7440 continue; 7441 7442 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7443 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 7444 } 7445 7446 for (BuiltinCandidateTypeSet::iterator 7447 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7448 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7449 MemPtr != MemPtrEnd; ++MemPtr) { 7450 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7451 continue; 7452 7453 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7454 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet); 7455 } 7456 7457 if (S.getLangOpts().CPlusPlus0x) { 7458 for (BuiltinCandidateTypeSet::iterator 7459 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7460 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7461 Enum != EnumEnd; ++Enum) { 7462 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 7463 continue; 7464 7465 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7466 continue; 7467 7468 QualType ParamTypes[2] = { *Enum, *Enum }; 7469 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet); 7470 } 7471 } 7472 } 7473 } 7474 }; 7475 7476 } // end anonymous namespace 7477 7478 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 7479 /// operator overloads to the candidate set (C++ [over.built]), based 7480 /// on the operator @p Op and the arguments given. For example, if the 7481 /// operator is a binary '+', this routine might add "int 7482 /// operator+(int, int)" to cover integer addition. 7483 void 7484 Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 7485 SourceLocation OpLoc, 7486 Expr **Args, unsigned NumArgs, 7487 OverloadCandidateSet& CandidateSet) { 7488 // Find all of the types that the arguments can convert to, but only 7489 // if the operator we're looking at has built-in operator candidates 7490 // that make use of these types. Also record whether we encounter non-record 7491 // candidate types or either arithmetic or enumeral candidate types. 7492 Qualifiers VisibleTypeConversionsQuals; 7493 VisibleTypeConversionsQuals.addConst(); 7494 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 7495 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 7496 7497 bool HasNonRecordCandidateType = false; 7498 bool HasArithmeticOrEnumeralCandidateType = false; 7499 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 7500 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 7501 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 7502 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 7503 OpLoc, 7504 true, 7505 (Op == OO_Exclaim || 7506 Op == OO_AmpAmp || 7507 Op == OO_PipePipe), 7508 VisibleTypeConversionsQuals); 7509 HasNonRecordCandidateType = HasNonRecordCandidateType || 7510 CandidateTypes[ArgIdx].hasNonRecordTypes(); 7511 HasArithmeticOrEnumeralCandidateType = 7512 HasArithmeticOrEnumeralCandidateType || 7513 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 7514 } 7515 7516 // Exit early when no non-record types have been added to the candidate set 7517 // for any of the arguments to the operator. 7518 // 7519 // We can't exit early for !, ||, or &&, since there we have always have 7520 // 'bool' overloads. 7521 if (!HasNonRecordCandidateType && 7522 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 7523 return; 7524 7525 // Setup an object to manage the common state for building overloads. 7526 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs, 7527 VisibleTypeConversionsQuals, 7528 HasArithmeticOrEnumeralCandidateType, 7529 CandidateTypes, CandidateSet); 7530 7531 // Dispatch over the operation to add in only those overloads which apply. 7532 switch (Op) { 7533 case OO_None: 7534 case NUM_OVERLOADED_OPERATORS: 7535 llvm_unreachable("Expected an overloaded operator"); 7536 7537 case OO_New: 7538 case OO_Delete: 7539 case OO_Array_New: 7540 case OO_Array_Delete: 7541 case OO_Call: 7542 llvm_unreachable( 7543 "Special operators don't use AddBuiltinOperatorCandidates"); 7544 7545 case OO_Comma: 7546 case OO_Arrow: 7547 // C++ [over.match.oper]p3: 7548 // -- For the operator ',', the unary operator '&', or the 7549 // operator '->', the built-in candidates set is empty. 7550 break; 7551 7552 case OO_Plus: // '+' is either unary or binary 7553 if (NumArgs == 1) 7554 OpBuilder.addUnaryPlusPointerOverloads(); 7555 // Fall through. 7556 7557 case OO_Minus: // '-' is either unary or binary 7558 if (NumArgs == 1) { 7559 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 7560 } else { 7561 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 7562 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7563 } 7564 break; 7565 7566 case OO_Star: // '*' is either unary or binary 7567 if (NumArgs == 1) 7568 OpBuilder.addUnaryStarPointerOverloads(); 7569 else 7570 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7571 break; 7572 7573 case OO_Slash: 7574 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7575 break; 7576 7577 case OO_PlusPlus: 7578 case OO_MinusMinus: 7579 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 7580 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 7581 break; 7582 7583 case OO_EqualEqual: 7584 case OO_ExclaimEqual: 7585 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 7586 // Fall through. 7587 7588 case OO_Less: 7589 case OO_Greater: 7590 case OO_LessEqual: 7591 case OO_GreaterEqual: 7592 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 7593 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 7594 break; 7595 7596 case OO_Percent: 7597 case OO_Caret: 7598 case OO_Pipe: 7599 case OO_LessLess: 7600 case OO_GreaterGreater: 7601 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7602 break; 7603 7604 case OO_Amp: // '&' is either unary or binary 7605 if (NumArgs == 1) 7606 // C++ [over.match.oper]p3: 7607 // -- For the operator ',', the unary operator '&', or the 7608 // operator '->', the built-in candidates set is empty. 7609 break; 7610 7611 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7612 break; 7613 7614 case OO_Tilde: 7615 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 7616 break; 7617 7618 case OO_Equal: 7619 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 7620 // Fall through. 7621 7622 case OO_PlusEqual: 7623 case OO_MinusEqual: 7624 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 7625 // Fall through. 7626 7627 case OO_StarEqual: 7628 case OO_SlashEqual: 7629 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 7630 break; 7631 7632 case OO_PercentEqual: 7633 case OO_LessLessEqual: 7634 case OO_GreaterGreaterEqual: 7635 case OO_AmpEqual: 7636 case OO_CaretEqual: 7637 case OO_PipeEqual: 7638 OpBuilder.addAssignmentIntegralOverloads(); 7639 break; 7640 7641 case OO_Exclaim: 7642 OpBuilder.addExclaimOverload(); 7643 break; 7644 7645 case OO_AmpAmp: 7646 case OO_PipePipe: 7647 OpBuilder.addAmpAmpOrPipePipeOverload(); 7648 break; 7649 7650 case OO_Subscript: 7651 OpBuilder.addSubscriptOverloads(); 7652 break; 7653 7654 case OO_ArrowStar: 7655 OpBuilder.addArrowStarOverloads(); 7656 break; 7657 7658 case OO_Conditional: 7659 OpBuilder.addConditionalOperatorOverloads(); 7660 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7661 break; 7662 } 7663 } 7664 7665 /// \brief Add function candidates found via argument-dependent lookup 7666 /// to the set of overloading candidates. 7667 /// 7668 /// This routine performs argument-dependent name lookup based on the 7669 /// given function name (which may also be an operator name) and adds 7670 /// all of the overload candidates found by ADL to the overload 7671 /// candidate set (C++ [basic.lookup.argdep]). 7672 void 7673 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 7674 bool Operator, SourceLocation Loc, 7675 llvm::ArrayRef<Expr *> Args, 7676 TemplateArgumentListInfo *ExplicitTemplateArgs, 7677 OverloadCandidateSet& CandidateSet, 7678 bool PartialOverloading) { 7679 ADLResult Fns; 7680 7681 // FIXME: This approach for uniquing ADL results (and removing 7682 // redundant candidates from the set) relies on pointer-equality, 7683 // which means we need to key off the canonical decl. However, 7684 // always going back to the canonical decl might not get us the 7685 // right set of default arguments. What default arguments are 7686 // we supposed to consider on ADL candidates, anyway? 7687 7688 // FIXME: Pass in the explicit template arguments? 7689 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns); 7690 7691 // Erase all of the candidates we already knew about. 7692 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 7693 CandEnd = CandidateSet.end(); 7694 Cand != CandEnd; ++Cand) 7695 if (Cand->Function) { 7696 Fns.erase(Cand->Function); 7697 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 7698 Fns.erase(FunTmpl); 7699 } 7700 7701 // For each of the ADL candidates we found, add it to the overload 7702 // set. 7703 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 7704 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 7705 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 7706 if (ExplicitTemplateArgs) 7707 continue; 7708 7709 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 7710 PartialOverloading); 7711 } else 7712 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 7713 FoundDecl, ExplicitTemplateArgs, 7714 Args, CandidateSet); 7715 } 7716 } 7717 7718 /// isBetterOverloadCandidate - Determines whether the first overload 7719 /// candidate is a better candidate than the second (C++ 13.3.3p1). 7720 bool 7721 isBetterOverloadCandidate(Sema &S, 7722 const OverloadCandidate &Cand1, 7723 const OverloadCandidate &Cand2, 7724 SourceLocation Loc, 7725 bool UserDefinedConversion) { 7726 // Define viable functions to be better candidates than non-viable 7727 // functions. 7728 if (!Cand2.Viable) 7729 return Cand1.Viable; 7730 else if (!Cand1.Viable) 7731 return false; 7732 7733 // C++ [over.match.best]p1: 7734 // 7735 // -- if F is a static member function, ICS1(F) is defined such 7736 // that ICS1(F) is neither better nor worse than ICS1(G) for 7737 // any function G, and, symmetrically, ICS1(G) is neither 7738 // better nor worse than ICS1(F). 7739 unsigned StartArg = 0; 7740 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 7741 StartArg = 1; 7742 7743 // C++ [over.match.best]p1: 7744 // A viable function F1 is defined to be a better function than another 7745 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 7746 // conversion sequence than ICSi(F2), and then... 7747 unsigned NumArgs = Cand1.NumConversions; 7748 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 7749 bool HasBetterConversion = false; 7750 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 7751 switch (CompareImplicitConversionSequences(S, 7752 Cand1.Conversions[ArgIdx], 7753 Cand2.Conversions[ArgIdx])) { 7754 case ImplicitConversionSequence::Better: 7755 // Cand1 has a better conversion sequence. 7756 HasBetterConversion = true; 7757 break; 7758 7759 case ImplicitConversionSequence::Worse: 7760 // Cand1 can't be better than Cand2. 7761 return false; 7762 7763 case ImplicitConversionSequence::Indistinguishable: 7764 // Do nothing. 7765 break; 7766 } 7767 } 7768 7769 // -- for some argument j, ICSj(F1) is a better conversion sequence than 7770 // ICSj(F2), or, if not that, 7771 if (HasBetterConversion) 7772 return true; 7773 7774 // - F1 is a non-template function and F2 is a function template 7775 // specialization, or, if not that, 7776 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 7777 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 7778 return true; 7779 7780 // -- F1 and F2 are function template specializations, and the function 7781 // template for F1 is more specialized than the template for F2 7782 // according to the partial ordering rules described in 14.5.5.2, or, 7783 // if not that, 7784 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 7785 Cand2.Function && Cand2.Function->getPrimaryTemplate()) { 7786 if (FunctionTemplateDecl *BetterTemplate 7787 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 7788 Cand2.Function->getPrimaryTemplate(), 7789 Loc, 7790 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 7791 : TPOC_Call, 7792 Cand1.ExplicitCallArguments)) 7793 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 7794 } 7795 7796 // -- the context is an initialization by user-defined conversion 7797 // (see 8.5, 13.3.1.5) and the standard conversion sequence 7798 // from the return type of F1 to the destination type (i.e., 7799 // the type of the entity being initialized) is a better 7800 // conversion sequence than the standard conversion sequence 7801 // from the return type of F2 to the destination type. 7802 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 7803 isa<CXXConversionDecl>(Cand1.Function) && 7804 isa<CXXConversionDecl>(Cand2.Function)) { 7805 // First check whether we prefer one of the conversion functions over the 7806 // other. This only distinguishes the results in non-standard, extension 7807 // cases such as the conversion from a lambda closure type to a function 7808 // pointer or block. 7809 ImplicitConversionSequence::CompareKind FuncResult 7810 = compareConversionFunctions(S, Cand1.Function, Cand2.Function); 7811 if (FuncResult != ImplicitConversionSequence::Indistinguishable) 7812 return FuncResult; 7813 7814 switch (CompareStandardConversionSequences(S, 7815 Cand1.FinalConversion, 7816 Cand2.FinalConversion)) { 7817 case ImplicitConversionSequence::Better: 7818 // Cand1 has a better conversion sequence. 7819 return true; 7820 7821 case ImplicitConversionSequence::Worse: 7822 // Cand1 can't be better than Cand2. 7823 return false; 7824 7825 case ImplicitConversionSequence::Indistinguishable: 7826 // Do nothing 7827 break; 7828 } 7829 } 7830 7831 return false; 7832 } 7833 7834 /// \brief Computes the best viable function (C++ 13.3.3) 7835 /// within an overload candidate set. 7836 /// 7837 /// \param Loc The location of the function name (or operator symbol) for 7838 /// which overload resolution occurs. 7839 /// 7840 /// \param Best If overload resolution was successful or found a deleted 7841 /// function, \p Best points to the candidate function found. 7842 /// 7843 /// \returns The result of overload resolution. 7844 OverloadingResult 7845 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 7846 iterator &Best, 7847 bool UserDefinedConversion) { 7848 // Find the best viable function. 7849 Best = end(); 7850 for (iterator Cand = begin(); Cand != end(); ++Cand) { 7851 if (Cand->Viable) 7852 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 7853 UserDefinedConversion)) 7854 Best = Cand; 7855 } 7856 7857 // If we didn't find any viable functions, abort. 7858 if (Best == end()) 7859 return OR_No_Viable_Function; 7860 7861 // Make sure that this function is better than every other viable 7862 // function. If not, we have an ambiguity. 7863 for (iterator Cand = begin(); Cand != end(); ++Cand) { 7864 if (Cand->Viable && 7865 Cand != Best && 7866 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 7867 UserDefinedConversion)) { 7868 Best = end(); 7869 return OR_Ambiguous; 7870 } 7871 } 7872 7873 // Best is the best viable function. 7874 if (Best->Function && 7875 (Best->Function->isDeleted() || 7876 S.isFunctionConsideredUnavailable(Best->Function))) 7877 return OR_Deleted; 7878 7879 return OR_Success; 7880 } 7881 7882 namespace { 7883 7884 enum OverloadCandidateKind { 7885 oc_function, 7886 oc_method, 7887 oc_constructor, 7888 oc_function_template, 7889 oc_method_template, 7890 oc_constructor_template, 7891 oc_implicit_default_constructor, 7892 oc_implicit_copy_constructor, 7893 oc_implicit_move_constructor, 7894 oc_implicit_copy_assignment, 7895 oc_implicit_move_assignment, 7896 oc_implicit_inherited_constructor 7897 }; 7898 7899 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 7900 FunctionDecl *Fn, 7901 std::string &Description) { 7902 bool isTemplate = false; 7903 7904 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 7905 isTemplate = true; 7906 Description = S.getTemplateArgumentBindingsText( 7907 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 7908 } 7909 7910 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 7911 if (!Ctor->isImplicit()) 7912 return isTemplate ? oc_constructor_template : oc_constructor; 7913 7914 if (Ctor->getInheritedConstructor()) 7915 return oc_implicit_inherited_constructor; 7916 7917 if (Ctor->isDefaultConstructor()) 7918 return oc_implicit_default_constructor; 7919 7920 if (Ctor->isMoveConstructor()) 7921 return oc_implicit_move_constructor; 7922 7923 assert(Ctor->isCopyConstructor() && 7924 "unexpected sort of implicit constructor"); 7925 return oc_implicit_copy_constructor; 7926 } 7927 7928 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 7929 // This actually gets spelled 'candidate function' for now, but 7930 // it doesn't hurt to split it out. 7931 if (!Meth->isImplicit()) 7932 return isTemplate ? oc_method_template : oc_method; 7933 7934 if (Meth->isMoveAssignmentOperator()) 7935 return oc_implicit_move_assignment; 7936 7937 if (Meth->isCopyAssignmentOperator()) 7938 return oc_implicit_copy_assignment; 7939 7940 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 7941 return oc_method; 7942 } 7943 7944 return isTemplate ? oc_function_template : oc_function; 7945 } 7946 7947 void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) { 7948 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 7949 if (!Ctor) return; 7950 7951 Ctor = Ctor->getInheritedConstructor(); 7952 if (!Ctor) return; 7953 7954 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 7955 } 7956 7957 } // end anonymous namespace 7958 7959 // Notes the location of an overload candidate. 7960 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 7961 std::string FnDesc; 7962 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 7963 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 7964 << (unsigned) K << FnDesc; 7965 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 7966 Diag(Fn->getLocation(), PD); 7967 MaybeEmitInheritedConstructorNote(*this, Fn); 7968 } 7969 7970 //Notes the location of all overload candidates designated through 7971 // OverloadedExpr 7972 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 7973 assert(OverloadedExpr->getType() == Context.OverloadTy); 7974 7975 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 7976 OverloadExpr *OvlExpr = Ovl.Expression; 7977 7978 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 7979 IEnd = OvlExpr->decls_end(); 7980 I != IEnd; ++I) { 7981 if (FunctionTemplateDecl *FunTmpl = 7982 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 7983 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 7984 } else if (FunctionDecl *Fun 7985 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 7986 NoteOverloadCandidate(Fun, DestType); 7987 } 7988 } 7989 } 7990 7991 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 7992 /// "lead" diagnostic; it will be given two arguments, the source and 7993 /// target types of the conversion. 7994 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 7995 Sema &S, 7996 SourceLocation CaretLoc, 7997 const PartialDiagnostic &PDiag) const { 7998 S.Diag(CaretLoc, PDiag) 7999 << Ambiguous.getFromType() << Ambiguous.getToType(); 8000 // FIXME: The note limiting machinery is borrowed from 8001 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8002 // refactoring here. 8003 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8004 unsigned CandsShown = 0; 8005 AmbiguousConversionSequence::const_iterator I, E; 8006 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8007 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8008 break; 8009 ++CandsShown; 8010 S.NoteOverloadCandidate(*I); 8011 } 8012 if (I != E) 8013 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8014 } 8015 8016 namespace { 8017 8018 void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 8019 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8020 assert(Conv.isBad()); 8021 assert(Cand->Function && "for now, candidate must be a function"); 8022 FunctionDecl *Fn = Cand->Function; 8023 8024 // There's a conversion slot for the object argument if this is a 8025 // non-constructor method. Note that 'I' corresponds the 8026 // conversion-slot index. 8027 bool isObjectArgument = false; 8028 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8029 if (I == 0) 8030 isObjectArgument = true; 8031 else 8032 I--; 8033 } 8034 8035 std::string FnDesc; 8036 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8037 8038 Expr *FromExpr = Conv.Bad.FromExpr; 8039 QualType FromTy = Conv.Bad.getFromType(); 8040 QualType ToTy = Conv.Bad.getToType(); 8041 8042 if (FromTy == S.Context.OverloadTy) { 8043 assert(FromExpr && "overload set argument came from implicit argument?"); 8044 Expr *E = FromExpr->IgnoreParens(); 8045 if (isa<UnaryOperator>(E)) 8046 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8047 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8048 8049 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8050 << (unsigned) FnKind << FnDesc 8051 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8052 << ToTy << Name << I+1; 8053 MaybeEmitInheritedConstructorNote(S, Fn); 8054 return; 8055 } 8056 8057 // Do some hand-waving analysis to see if the non-viability is due 8058 // to a qualifier mismatch. 8059 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8060 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8061 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8062 CToTy = RT->getPointeeType(); 8063 else { 8064 // TODO: detect and diagnose the full richness of const mismatches. 8065 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8066 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8067 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8068 } 8069 8070 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8071 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8072 Qualifiers FromQs = CFromTy.getQualifiers(); 8073 Qualifiers ToQs = CToTy.getQualifiers(); 8074 8075 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8076 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8077 << (unsigned) FnKind << FnDesc 8078 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8079 << FromTy 8080 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8081 << (unsigned) isObjectArgument << I+1; 8082 MaybeEmitInheritedConstructorNote(S, Fn); 8083 return; 8084 } 8085 8086 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8087 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8088 << (unsigned) FnKind << FnDesc 8089 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8090 << FromTy 8091 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8092 << (unsigned) isObjectArgument << I+1; 8093 MaybeEmitInheritedConstructorNote(S, Fn); 8094 return; 8095 } 8096 8097 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8098 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8099 << (unsigned) FnKind << FnDesc 8100 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8101 << FromTy 8102 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8103 << (unsigned) isObjectArgument << I+1; 8104 MaybeEmitInheritedConstructorNote(S, Fn); 8105 return; 8106 } 8107 8108 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8109 assert(CVR && "unexpected qualifiers mismatch"); 8110 8111 if (isObjectArgument) { 8112 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8113 << (unsigned) FnKind << FnDesc 8114 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8115 << FromTy << (CVR - 1); 8116 } else { 8117 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8118 << (unsigned) FnKind << FnDesc 8119 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8120 << FromTy << (CVR - 1) << I+1; 8121 } 8122 MaybeEmitInheritedConstructorNote(S, Fn); 8123 return; 8124 } 8125 8126 // Special diagnostic for failure to convert an initializer list, since 8127 // telling the user that it has type void is not useful. 8128 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8129 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8130 << (unsigned) FnKind << FnDesc 8131 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8132 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8133 MaybeEmitInheritedConstructorNote(S, Fn); 8134 return; 8135 } 8136 8137 // Diagnose references or pointers to incomplete types differently, 8138 // since it's far from impossible that the incompleteness triggered 8139 // the failure. 8140 QualType TempFromTy = FromTy.getNonReferenceType(); 8141 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8142 TempFromTy = PTy->getPointeeType(); 8143 if (TempFromTy->isIncompleteType()) { 8144 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8145 << (unsigned) FnKind << FnDesc 8146 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8147 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8148 MaybeEmitInheritedConstructorNote(S, Fn); 8149 return; 8150 } 8151 8152 // Diagnose base -> derived pointer conversions. 8153 unsigned BaseToDerivedConversion = 0; 8154 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8155 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8156 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8157 FromPtrTy->getPointeeType()) && 8158 !FromPtrTy->getPointeeType()->isIncompleteType() && 8159 !ToPtrTy->getPointeeType()->isIncompleteType() && 8160 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8161 FromPtrTy->getPointeeType())) 8162 BaseToDerivedConversion = 1; 8163 } 8164 } else if (const ObjCObjectPointerType *FromPtrTy 8165 = FromTy->getAs<ObjCObjectPointerType>()) { 8166 if (const ObjCObjectPointerType *ToPtrTy 8167 = ToTy->getAs<ObjCObjectPointerType>()) 8168 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8169 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8170 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8171 FromPtrTy->getPointeeType()) && 8172 FromIface->isSuperClassOf(ToIface)) 8173 BaseToDerivedConversion = 2; 8174 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8175 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8176 !FromTy->isIncompleteType() && 8177 !ToRefTy->getPointeeType()->isIncompleteType() && 8178 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8179 BaseToDerivedConversion = 3; 8180 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8181 ToTy.getNonReferenceType().getCanonicalType() == 8182 FromTy.getNonReferenceType().getCanonicalType()) { 8183 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8184 << (unsigned) FnKind << FnDesc 8185 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8186 << (unsigned) isObjectArgument << I + 1; 8187 MaybeEmitInheritedConstructorNote(S, Fn); 8188 return; 8189 } 8190 } 8191 8192 if (BaseToDerivedConversion) { 8193 S.Diag(Fn->getLocation(), 8194 diag::note_ovl_candidate_bad_base_to_derived_conv) 8195 << (unsigned) FnKind << FnDesc 8196 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8197 << (BaseToDerivedConversion - 1) 8198 << FromTy << ToTy << I+1; 8199 MaybeEmitInheritedConstructorNote(S, Fn); 8200 return; 8201 } 8202 8203 if (isa<ObjCObjectPointerType>(CFromTy) && 8204 isa<PointerType>(CToTy)) { 8205 Qualifiers FromQs = CFromTy.getQualifiers(); 8206 Qualifiers ToQs = CToTy.getQualifiers(); 8207 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8208 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8209 << (unsigned) FnKind << FnDesc 8210 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8211 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8212 MaybeEmitInheritedConstructorNote(S, Fn); 8213 return; 8214 } 8215 } 8216 8217 // Emit the generic diagnostic and, optionally, add the hints to it. 8218 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8219 FDiag << (unsigned) FnKind << FnDesc 8220 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8221 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8222 << (unsigned) (Cand->Fix.Kind); 8223 8224 // If we can fix the conversion, suggest the FixIts. 8225 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8226 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8227 FDiag << *HI; 8228 S.Diag(Fn->getLocation(), FDiag); 8229 8230 MaybeEmitInheritedConstructorNote(S, Fn); 8231 } 8232 8233 void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8234 unsigned NumFormalArgs) { 8235 // TODO: treat calls to a missing default constructor as a special case 8236 8237 FunctionDecl *Fn = Cand->Function; 8238 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8239 8240 unsigned MinParams = Fn->getMinRequiredArguments(); 8241 8242 // With invalid overloaded operators, it's possible that we think we 8243 // have an arity mismatch when it fact it looks like we have the 8244 // right number of arguments, because only overloaded operators have 8245 // the weird behavior of overloading member and non-member functions. 8246 // Just don't report anything. 8247 if (Fn->isInvalidDecl() && 8248 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8249 return; 8250 8251 // at least / at most / exactly 8252 unsigned mode, modeCount; 8253 if (NumFormalArgs < MinParams) { 8254 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8255 (Cand->FailureKind == ovl_fail_bad_deduction && 8256 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8257 if (MinParams != FnTy->getNumArgs() || 8258 FnTy->isVariadic() || FnTy->isTemplateVariadic()) 8259 mode = 0; // "at least" 8260 else 8261 mode = 2; // "exactly" 8262 modeCount = MinParams; 8263 } else { 8264 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8265 (Cand->FailureKind == ovl_fail_bad_deduction && 8266 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8267 if (MinParams != FnTy->getNumArgs()) 8268 mode = 1; // "at most" 8269 else 8270 mode = 2; // "exactly" 8271 modeCount = FnTy->getNumArgs(); 8272 } 8273 8274 std::string Description; 8275 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8276 8277 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8278 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8279 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8280 << Fn->getParamDecl(0) << NumFormalArgs; 8281 else 8282 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8283 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8284 << modeCount << NumFormalArgs; 8285 MaybeEmitInheritedConstructorNote(S, Fn); 8286 } 8287 8288 /// Diagnose a failed template-argument deduction. 8289 void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 8290 unsigned NumArgs) { 8291 FunctionDecl *Fn = Cand->Function; // pattern 8292 8293 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter(); 8294 NamedDecl *ParamD; 8295 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8296 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8297 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8298 switch (Cand->DeductionFailure.Result) { 8299 case Sema::TDK_Success: 8300 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8301 8302 case Sema::TDK_Incomplete: { 8303 assert(ParamD && "no parameter found for incomplete deduction result"); 8304 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction) 8305 << ParamD->getDeclName(); 8306 MaybeEmitInheritedConstructorNote(S, Fn); 8307 return; 8308 } 8309 8310 case Sema::TDK_Underqualified: { 8311 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8312 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 8313 8314 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType(); 8315 8316 // Param will have been canonicalized, but it should just be a 8317 // qualified version of ParamD, so move the qualifiers to that. 8318 QualifierCollector Qs; 8319 Qs.strip(Param); 8320 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 8321 assert(S.Context.hasSameType(Param, NonCanonParam)); 8322 8323 // Arg has also been canonicalized, but there's nothing we can do 8324 // about that. It also doesn't matter as much, because it won't 8325 // have any template parameters in it (because deduction isn't 8326 // done on dependent types). 8327 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType(); 8328 8329 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified) 8330 << ParamD->getDeclName() << Arg << NonCanonParam; 8331 MaybeEmitInheritedConstructorNote(S, Fn); 8332 return; 8333 } 8334 8335 case Sema::TDK_Inconsistent: { 8336 assert(ParamD && "no parameter found for inconsistent deduction result"); 8337 int which = 0; 8338 if (isa<TemplateTypeParmDecl>(ParamD)) 8339 which = 0; 8340 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 8341 which = 1; 8342 else { 8343 which = 2; 8344 } 8345 8346 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction) 8347 << which << ParamD->getDeclName() 8348 << *Cand->DeductionFailure.getFirstArg() 8349 << *Cand->DeductionFailure.getSecondArg(); 8350 MaybeEmitInheritedConstructorNote(S, Fn); 8351 return; 8352 } 8353 8354 case Sema::TDK_InvalidExplicitArguments: 8355 assert(ParamD && "no parameter found for invalid explicit arguments"); 8356 if (ParamD->getDeclName()) 8357 S.Diag(Fn->getLocation(), 8358 diag::note_ovl_candidate_explicit_arg_mismatch_named) 8359 << ParamD->getDeclName(); 8360 else { 8361 int index = 0; 8362 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 8363 index = TTP->getIndex(); 8364 else if (NonTypeTemplateParmDecl *NTTP 8365 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 8366 index = NTTP->getIndex(); 8367 else 8368 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 8369 S.Diag(Fn->getLocation(), 8370 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 8371 << (index + 1); 8372 } 8373 MaybeEmitInheritedConstructorNote(S, Fn); 8374 return; 8375 8376 case Sema::TDK_TooManyArguments: 8377 case Sema::TDK_TooFewArguments: 8378 DiagnoseArityMismatch(S, Cand, NumArgs); 8379 return; 8380 8381 case Sema::TDK_InstantiationDepth: 8382 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth); 8383 MaybeEmitInheritedConstructorNote(S, Fn); 8384 return; 8385 8386 case Sema::TDK_SubstitutionFailure: { 8387 // Format the template argument list into the argument string. 8388 llvm::SmallString<128> TemplateArgString; 8389 if (TemplateArgumentList *Args = 8390 Cand->DeductionFailure.getTemplateArgumentList()) { 8391 TemplateArgString = " "; 8392 TemplateArgString += S.getTemplateArgumentBindingsText( 8393 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args); 8394 } 8395 8396 // If this candidate was disabled by enable_if, say so. 8397 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic(); 8398 if (PDiag && PDiag->second.getDiagID() == 8399 diag::err_typename_nested_not_found_enable_if) { 8400 // FIXME: Use the source range of the condition, and the fully-qualified 8401 // name of the enable_if template. These are both present in PDiag. 8402 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 8403 << "'enable_if'" << TemplateArgString; 8404 return; 8405 } 8406 8407 // Format the SFINAE diagnostic into the argument string. 8408 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 8409 // formatted message in another diagnostic. 8410 llvm::SmallString<128> SFINAEArgString; 8411 SourceRange R; 8412 if (PDiag) { 8413 SFINAEArgString = ": "; 8414 R = SourceRange(PDiag->first, PDiag->first); 8415 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 8416 } 8417 8418 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure) 8419 << TemplateArgString << SFINAEArgString << R; 8420 MaybeEmitInheritedConstructorNote(S, Fn); 8421 return; 8422 } 8423 8424 // TODO: diagnose these individually, then kill off 8425 // note_ovl_candidate_bad_deduction, which is uselessly vague. 8426 case Sema::TDK_NonDeducedMismatch: 8427 case Sema::TDK_FailedOverloadResolution: 8428 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction); 8429 MaybeEmitInheritedConstructorNote(S, Fn); 8430 return; 8431 } 8432 } 8433 8434 /// CUDA: diagnose an invalid call across targets. 8435 void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 8436 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 8437 FunctionDecl *Callee = Cand->Function; 8438 8439 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 8440 CalleeTarget = S.IdentifyCUDATarget(Callee); 8441 8442 std::string FnDesc; 8443 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 8444 8445 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 8446 << (unsigned) FnKind << CalleeTarget << CallerTarget; 8447 } 8448 8449 /// Generates a 'note' diagnostic for an overload candidate. We've 8450 /// already generated a primary error at the call site. 8451 /// 8452 /// It really does need to be a single diagnostic with its caret 8453 /// pointed at the candidate declaration. Yes, this creates some 8454 /// major challenges of technical writing. Yes, this makes pointing 8455 /// out problems with specific arguments quite awkward. It's still 8456 /// better than generating twenty screens of text for every failed 8457 /// overload. 8458 /// 8459 /// It would be great to be able to express per-candidate problems 8460 /// more richly for those diagnostic clients that cared, but we'd 8461 /// still have to be just as careful with the default diagnostics. 8462 void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 8463 unsigned NumArgs) { 8464 FunctionDecl *Fn = Cand->Function; 8465 8466 // Note deleted candidates, but only if they're viable. 8467 if (Cand->Viable && (Fn->isDeleted() || 8468 S.isFunctionConsideredUnavailable(Fn))) { 8469 std::string FnDesc; 8470 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8471 8472 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 8473 << FnKind << FnDesc 8474 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 8475 MaybeEmitInheritedConstructorNote(S, Fn); 8476 return; 8477 } 8478 8479 // We don't really have anything else to say about viable candidates. 8480 if (Cand->Viable) { 8481 S.NoteOverloadCandidate(Fn); 8482 return; 8483 } 8484 8485 switch (Cand->FailureKind) { 8486 case ovl_fail_too_many_arguments: 8487 case ovl_fail_too_few_arguments: 8488 return DiagnoseArityMismatch(S, Cand, NumArgs); 8489 8490 case ovl_fail_bad_deduction: 8491 return DiagnoseBadDeduction(S, Cand, NumArgs); 8492 8493 case ovl_fail_trivial_conversion: 8494 case ovl_fail_bad_final_conversion: 8495 case ovl_fail_final_conversion_not_exact: 8496 return S.NoteOverloadCandidate(Fn); 8497 8498 case ovl_fail_bad_conversion: { 8499 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 8500 for (unsigned N = Cand->NumConversions; I != N; ++I) 8501 if (Cand->Conversions[I].isBad()) 8502 return DiagnoseBadConversion(S, Cand, I); 8503 8504 // FIXME: this currently happens when we're called from SemaInit 8505 // when user-conversion overload fails. Figure out how to handle 8506 // those conditions and diagnose them well. 8507 return S.NoteOverloadCandidate(Fn); 8508 } 8509 8510 case ovl_fail_bad_target: 8511 return DiagnoseBadTarget(S, Cand); 8512 } 8513 } 8514 8515 void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 8516 // Desugar the type of the surrogate down to a function type, 8517 // retaining as many typedefs as possible while still showing 8518 // the function type (and, therefore, its parameter types). 8519 QualType FnType = Cand->Surrogate->getConversionType(); 8520 bool isLValueReference = false; 8521 bool isRValueReference = false; 8522 bool isPointer = false; 8523 if (const LValueReferenceType *FnTypeRef = 8524 FnType->getAs<LValueReferenceType>()) { 8525 FnType = FnTypeRef->getPointeeType(); 8526 isLValueReference = true; 8527 } else if (const RValueReferenceType *FnTypeRef = 8528 FnType->getAs<RValueReferenceType>()) { 8529 FnType = FnTypeRef->getPointeeType(); 8530 isRValueReference = true; 8531 } 8532 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 8533 FnType = FnTypePtr->getPointeeType(); 8534 isPointer = true; 8535 } 8536 // Desugar down to a function type. 8537 FnType = QualType(FnType->getAs<FunctionType>(), 0); 8538 // Reconstruct the pointer/reference as appropriate. 8539 if (isPointer) FnType = S.Context.getPointerType(FnType); 8540 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 8541 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 8542 8543 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 8544 << FnType; 8545 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 8546 } 8547 8548 void NoteBuiltinOperatorCandidate(Sema &S, 8549 StringRef Opc, 8550 SourceLocation OpLoc, 8551 OverloadCandidate *Cand) { 8552 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 8553 std::string TypeStr("operator"); 8554 TypeStr += Opc; 8555 TypeStr += "("; 8556 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 8557 if (Cand->NumConversions == 1) { 8558 TypeStr += ")"; 8559 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 8560 } else { 8561 TypeStr += ", "; 8562 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 8563 TypeStr += ")"; 8564 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 8565 } 8566 } 8567 8568 void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 8569 OverloadCandidate *Cand) { 8570 unsigned NoOperands = Cand->NumConversions; 8571 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 8572 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 8573 if (ICS.isBad()) break; // all meaningless after first invalid 8574 if (!ICS.isAmbiguous()) continue; 8575 8576 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 8577 S.PDiag(diag::note_ambiguous_type_conversion)); 8578 } 8579 } 8580 8581 SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 8582 if (Cand->Function) 8583 return Cand->Function->getLocation(); 8584 if (Cand->IsSurrogate) 8585 return Cand->Surrogate->getLocation(); 8586 return SourceLocation(); 8587 } 8588 8589 static unsigned 8590 RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) { 8591 switch ((Sema::TemplateDeductionResult)DFI.Result) { 8592 case Sema::TDK_Success: 8593 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8594 8595 case Sema::TDK_Invalid: 8596 case Sema::TDK_Incomplete: 8597 return 1; 8598 8599 case Sema::TDK_Underqualified: 8600 case Sema::TDK_Inconsistent: 8601 return 2; 8602 8603 case Sema::TDK_SubstitutionFailure: 8604 case Sema::TDK_NonDeducedMismatch: 8605 return 3; 8606 8607 case Sema::TDK_InstantiationDepth: 8608 case Sema::TDK_FailedOverloadResolution: 8609 return 4; 8610 8611 case Sema::TDK_InvalidExplicitArguments: 8612 return 5; 8613 8614 case Sema::TDK_TooManyArguments: 8615 case Sema::TDK_TooFewArguments: 8616 return 6; 8617 } 8618 llvm_unreachable("Unhandled deduction result"); 8619 } 8620 8621 struct CompareOverloadCandidatesForDisplay { 8622 Sema &S; 8623 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 8624 8625 bool operator()(const OverloadCandidate *L, 8626 const OverloadCandidate *R) { 8627 // Fast-path this check. 8628 if (L == R) return false; 8629 8630 // Order first by viability. 8631 if (L->Viable) { 8632 if (!R->Viable) return true; 8633 8634 // TODO: introduce a tri-valued comparison for overload 8635 // candidates. Would be more worthwhile if we had a sort 8636 // that could exploit it. 8637 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 8638 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 8639 } else if (R->Viable) 8640 return false; 8641 8642 assert(L->Viable == R->Viable); 8643 8644 // Criteria by which we can sort non-viable candidates: 8645 if (!L->Viable) { 8646 // 1. Arity mismatches come after other candidates. 8647 if (L->FailureKind == ovl_fail_too_many_arguments || 8648 L->FailureKind == ovl_fail_too_few_arguments) 8649 return false; 8650 if (R->FailureKind == ovl_fail_too_many_arguments || 8651 R->FailureKind == ovl_fail_too_few_arguments) 8652 return true; 8653 8654 // 2. Bad conversions come first and are ordered by the number 8655 // of bad conversions and quality of good conversions. 8656 if (L->FailureKind == ovl_fail_bad_conversion) { 8657 if (R->FailureKind != ovl_fail_bad_conversion) 8658 return true; 8659 8660 // The conversion that can be fixed with a smaller number of changes, 8661 // comes first. 8662 unsigned numLFixes = L->Fix.NumConversionsFixed; 8663 unsigned numRFixes = R->Fix.NumConversionsFixed; 8664 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 8665 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 8666 if (numLFixes != numRFixes) { 8667 if (numLFixes < numRFixes) 8668 return true; 8669 else 8670 return false; 8671 } 8672 8673 // If there's any ordering between the defined conversions... 8674 // FIXME: this might not be transitive. 8675 assert(L->NumConversions == R->NumConversions); 8676 8677 int leftBetter = 0; 8678 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 8679 for (unsigned E = L->NumConversions; I != E; ++I) { 8680 switch (CompareImplicitConversionSequences(S, 8681 L->Conversions[I], 8682 R->Conversions[I])) { 8683 case ImplicitConversionSequence::Better: 8684 leftBetter++; 8685 break; 8686 8687 case ImplicitConversionSequence::Worse: 8688 leftBetter--; 8689 break; 8690 8691 case ImplicitConversionSequence::Indistinguishable: 8692 break; 8693 } 8694 } 8695 if (leftBetter > 0) return true; 8696 if (leftBetter < 0) return false; 8697 8698 } else if (R->FailureKind == ovl_fail_bad_conversion) 8699 return false; 8700 8701 if (L->FailureKind == ovl_fail_bad_deduction) { 8702 if (R->FailureKind != ovl_fail_bad_deduction) 8703 return true; 8704 8705 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 8706 return RankDeductionFailure(L->DeductionFailure) 8707 < RankDeductionFailure(R->DeductionFailure); 8708 } else if (R->FailureKind == ovl_fail_bad_deduction) 8709 return false; 8710 8711 // TODO: others? 8712 } 8713 8714 // Sort everything else by location. 8715 SourceLocation LLoc = GetLocationForCandidate(L); 8716 SourceLocation RLoc = GetLocationForCandidate(R); 8717 8718 // Put candidates without locations (e.g. builtins) at the end. 8719 if (LLoc.isInvalid()) return false; 8720 if (RLoc.isInvalid()) return true; 8721 8722 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 8723 } 8724 }; 8725 8726 /// CompleteNonViableCandidate - Normally, overload resolution only 8727 /// computes up to the first. Produces the FixIt set if possible. 8728 void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 8729 llvm::ArrayRef<Expr *> Args) { 8730 assert(!Cand->Viable); 8731 8732 // Don't do anything on failures other than bad conversion. 8733 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 8734 8735 // We only want the FixIts if all the arguments can be corrected. 8736 bool Unfixable = false; 8737 // Use a implicit copy initialization to check conversion fixes. 8738 Cand->Fix.setConversionChecker(TryCopyInitialization); 8739 8740 // Skip forward to the first bad conversion. 8741 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 8742 unsigned ConvCount = Cand->NumConversions; 8743 while (true) { 8744 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 8745 ConvIdx++; 8746 if (Cand->Conversions[ConvIdx - 1].isBad()) { 8747 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 8748 break; 8749 } 8750 } 8751 8752 if (ConvIdx == ConvCount) 8753 return; 8754 8755 assert(!Cand->Conversions[ConvIdx].isInitialized() && 8756 "remaining conversion is initialized?"); 8757 8758 // FIXME: this should probably be preserved from the overload 8759 // operation somehow. 8760 bool SuppressUserConversions = false; 8761 8762 const FunctionProtoType* Proto; 8763 unsigned ArgIdx = ConvIdx; 8764 8765 if (Cand->IsSurrogate) { 8766 QualType ConvType 8767 = Cand->Surrogate->getConversionType().getNonReferenceType(); 8768 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 8769 ConvType = ConvPtrType->getPointeeType(); 8770 Proto = ConvType->getAs<FunctionProtoType>(); 8771 ArgIdx--; 8772 } else if (Cand->Function) { 8773 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 8774 if (isa<CXXMethodDecl>(Cand->Function) && 8775 !isa<CXXConstructorDecl>(Cand->Function)) 8776 ArgIdx--; 8777 } else { 8778 // Builtin binary operator with a bad first conversion. 8779 assert(ConvCount <= 3); 8780 for (; ConvIdx != ConvCount; ++ConvIdx) 8781 Cand->Conversions[ConvIdx] 8782 = TryCopyInitialization(S, Args[ConvIdx], 8783 Cand->BuiltinTypes.ParamTypes[ConvIdx], 8784 SuppressUserConversions, 8785 /*InOverloadResolution*/ true, 8786 /*AllowObjCWritebackConversion=*/ 8787 S.getLangOpts().ObjCAutoRefCount); 8788 return; 8789 } 8790 8791 // Fill in the rest of the conversions. 8792 unsigned NumArgsInProto = Proto->getNumArgs(); 8793 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 8794 if (ArgIdx < NumArgsInProto) { 8795 Cand->Conversions[ConvIdx] 8796 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx), 8797 SuppressUserConversions, 8798 /*InOverloadResolution=*/true, 8799 /*AllowObjCWritebackConversion=*/ 8800 S.getLangOpts().ObjCAutoRefCount); 8801 // Store the FixIt in the candidate if it exists. 8802 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 8803 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 8804 } 8805 else 8806 Cand->Conversions[ConvIdx].setEllipsis(); 8807 } 8808 } 8809 8810 } // end anonymous namespace 8811 8812 /// PrintOverloadCandidates - When overload resolution fails, prints 8813 /// diagnostic messages containing the candidates in the candidate 8814 /// set. 8815 void OverloadCandidateSet::NoteCandidates(Sema &S, 8816 OverloadCandidateDisplayKind OCD, 8817 llvm::ArrayRef<Expr *> Args, 8818 StringRef Opc, 8819 SourceLocation OpLoc) { 8820 // Sort the candidates by viability and position. Sorting directly would 8821 // be prohibitive, so we make a set of pointers and sort those. 8822 SmallVector<OverloadCandidate*, 32> Cands; 8823 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 8824 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 8825 if (Cand->Viable) 8826 Cands.push_back(Cand); 8827 else if (OCD == OCD_AllCandidates) { 8828 CompleteNonViableCandidate(S, Cand, Args); 8829 if (Cand->Function || Cand->IsSurrogate) 8830 Cands.push_back(Cand); 8831 // Otherwise, this a non-viable builtin candidate. We do not, in general, 8832 // want to list every possible builtin candidate. 8833 } 8834 } 8835 8836 std::sort(Cands.begin(), Cands.end(), 8837 CompareOverloadCandidatesForDisplay(S)); 8838 8839 bool ReportedAmbiguousConversions = false; 8840 8841 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 8842 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8843 unsigned CandsShown = 0; 8844 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 8845 OverloadCandidate *Cand = *I; 8846 8847 // Set an arbitrary limit on the number of candidate functions we'll spam 8848 // the user with. FIXME: This limit should depend on details of the 8849 // candidate list. 8850 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 8851 break; 8852 } 8853 ++CandsShown; 8854 8855 if (Cand->Function) 8856 NoteFunctionCandidate(S, Cand, Args.size()); 8857 else if (Cand->IsSurrogate) 8858 NoteSurrogateCandidate(S, Cand); 8859 else { 8860 assert(Cand->Viable && 8861 "Non-viable built-in candidates are not added to Cands."); 8862 // Generally we only see ambiguities including viable builtin 8863 // operators if overload resolution got screwed up by an 8864 // ambiguous user-defined conversion. 8865 // 8866 // FIXME: It's quite possible for different conversions to see 8867 // different ambiguities, though. 8868 if (!ReportedAmbiguousConversions) { 8869 NoteAmbiguousUserConversions(S, OpLoc, Cand); 8870 ReportedAmbiguousConversions = true; 8871 } 8872 8873 // If this is a viable builtin, print it. 8874 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 8875 } 8876 } 8877 8878 if (I != E) 8879 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 8880 } 8881 8882 // [PossiblyAFunctionType] --> [Return] 8883 // NonFunctionType --> NonFunctionType 8884 // R (A) --> R(A) 8885 // R (*)(A) --> R (A) 8886 // R (&)(A) --> R (A) 8887 // R (S::*)(A) --> R (A) 8888 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 8889 QualType Ret = PossiblyAFunctionType; 8890 if (const PointerType *ToTypePtr = 8891 PossiblyAFunctionType->getAs<PointerType>()) 8892 Ret = ToTypePtr->getPointeeType(); 8893 else if (const ReferenceType *ToTypeRef = 8894 PossiblyAFunctionType->getAs<ReferenceType>()) 8895 Ret = ToTypeRef->getPointeeType(); 8896 else if (const MemberPointerType *MemTypePtr = 8897 PossiblyAFunctionType->getAs<MemberPointerType>()) 8898 Ret = MemTypePtr->getPointeeType(); 8899 Ret = 8900 Context.getCanonicalType(Ret).getUnqualifiedType(); 8901 return Ret; 8902 } 8903 8904 // A helper class to help with address of function resolution 8905 // - allows us to avoid passing around all those ugly parameters 8906 class AddressOfFunctionResolver 8907 { 8908 Sema& S; 8909 Expr* SourceExpr; 8910 const QualType& TargetType; 8911 QualType TargetFunctionType; // Extracted function type from target type 8912 8913 bool Complain; 8914 //DeclAccessPair& ResultFunctionAccessPair; 8915 ASTContext& Context; 8916 8917 bool TargetTypeIsNonStaticMemberFunction; 8918 bool FoundNonTemplateFunction; 8919 8920 OverloadExpr::FindResult OvlExprInfo; 8921 OverloadExpr *OvlExpr; 8922 TemplateArgumentListInfo OvlExplicitTemplateArgs; 8923 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 8924 8925 public: 8926 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr, 8927 const QualType& TargetType, bool Complain) 8928 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 8929 Complain(Complain), Context(S.getASTContext()), 8930 TargetTypeIsNonStaticMemberFunction( 8931 !!TargetType->getAs<MemberPointerType>()), 8932 FoundNonTemplateFunction(false), 8933 OvlExprInfo(OverloadExpr::find(SourceExpr)), 8934 OvlExpr(OvlExprInfo.Expression) 8935 { 8936 ExtractUnqualifiedFunctionTypeFromTargetType(); 8937 8938 if (!TargetFunctionType->isFunctionType()) { 8939 if (OvlExpr->hasExplicitTemplateArgs()) { 8940 DeclAccessPair dap; 8941 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization( 8942 OvlExpr, false, &dap) ) { 8943 8944 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 8945 if (!Method->isStatic()) { 8946 // If the target type is a non-function type and the function 8947 // found is a non-static member function, pretend as if that was 8948 // the target, it's the only possible type to end up with. 8949 TargetTypeIsNonStaticMemberFunction = true; 8950 8951 // And skip adding the function if its not in the proper form. 8952 // We'll diagnose this due to an empty set of functions. 8953 if (!OvlExprInfo.HasFormOfMemberPointer) 8954 return; 8955 } 8956 } 8957 8958 Matches.push_back(std::make_pair(dap,Fn)); 8959 } 8960 } 8961 return; 8962 } 8963 8964 if (OvlExpr->hasExplicitTemplateArgs()) 8965 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 8966 8967 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 8968 // C++ [over.over]p4: 8969 // If more than one function is selected, [...] 8970 if (Matches.size() > 1) { 8971 if (FoundNonTemplateFunction) 8972 EliminateAllTemplateMatches(); 8973 else 8974 EliminateAllExceptMostSpecializedTemplate(); 8975 } 8976 } 8977 } 8978 8979 private: 8980 bool isTargetTypeAFunction() const { 8981 return TargetFunctionType->isFunctionType(); 8982 } 8983 8984 // [ToType] [Return] 8985 8986 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 8987 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 8988 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 8989 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 8990 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 8991 } 8992 8993 // return true if any matching specializations were found 8994 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 8995 const DeclAccessPair& CurAccessFunPair) { 8996 if (CXXMethodDecl *Method 8997 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 8998 // Skip non-static function templates when converting to pointer, and 8999 // static when converting to member pointer. 9000 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9001 return false; 9002 } 9003 else if (TargetTypeIsNonStaticMemberFunction) 9004 return false; 9005 9006 // C++ [over.over]p2: 9007 // If the name is a function template, template argument deduction is 9008 // done (14.8.2.2), and if the argument deduction succeeds, the 9009 // resulting template argument list is used to generate a single 9010 // function template specialization, which is added to the set of 9011 // overloaded functions considered. 9012 FunctionDecl *Specialization = 0; 9013 TemplateDeductionInfo Info(OvlExpr->getNameLoc()); 9014 if (Sema::TemplateDeductionResult Result 9015 = S.DeduceTemplateArguments(FunctionTemplate, 9016 &OvlExplicitTemplateArgs, 9017 TargetFunctionType, Specialization, 9018 Info)) { 9019 // FIXME: make a note of the failed deduction for diagnostics. 9020 (void)Result; 9021 return false; 9022 } 9023 9024 // Template argument deduction ensures that we have an exact match. 9025 // This function template specicalization works. 9026 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 9027 assert(TargetFunctionType 9028 == Context.getCanonicalType(Specialization->getType())); 9029 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 9030 return true; 9031 } 9032 9033 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9034 const DeclAccessPair& CurAccessFunPair) { 9035 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9036 // Skip non-static functions when converting to pointer, and static 9037 // when converting to member pointer. 9038 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9039 return false; 9040 } 9041 else if (TargetTypeIsNonStaticMemberFunction) 9042 return false; 9043 9044 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9045 if (S.getLangOpts().CUDA) 9046 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9047 if (S.CheckCUDATarget(Caller, FunDecl)) 9048 return false; 9049 9050 QualType ResultTy; 9051 if (Context.hasSameUnqualifiedType(TargetFunctionType, 9052 FunDecl->getType()) || 9053 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9054 ResultTy)) { 9055 Matches.push_back(std::make_pair(CurAccessFunPair, 9056 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9057 FoundNonTemplateFunction = true; 9058 return true; 9059 } 9060 } 9061 9062 return false; 9063 } 9064 9065 bool FindAllFunctionsThatMatchTargetTypeExactly() { 9066 bool Ret = false; 9067 9068 // If the overload expression doesn't have the form of a pointer to 9069 // member, don't try to convert it to a pointer-to-member type. 9070 if (IsInvalidFormOfPointerToMemberFunction()) 9071 return false; 9072 9073 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9074 E = OvlExpr->decls_end(); 9075 I != E; ++I) { 9076 // Look through any using declarations to find the underlying function. 9077 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 9078 9079 // C++ [over.over]p3: 9080 // Non-member functions and static member functions match 9081 // targets of type "pointer-to-function" or "reference-to-function." 9082 // Nonstatic member functions match targets of 9083 // type "pointer-to-member-function." 9084 // Note that according to DR 247, the containing class does not matter. 9085 if (FunctionTemplateDecl *FunctionTemplate 9086 = dyn_cast<FunctionTemplateDecl>(Fn)) { 9087 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 9088 Ret = true; 9089 } 9090 // If we have explicit template arguments supplied, skip non-templates. 9091 else if (!OvlExpr->hasExplicitTemplateArgs() && 9092 AddMatchingNonTemplateFunction(Fn, I.getPair())) 9093 Ret = true; 9094 } 9095 assert(Ret || Matches.empty()); 9096 return Ret; 9097 } 9098 9099 void EliminateAllExceptMostSpecializedTemplate() { 9100 // [...] and any given function template specialization F1 is 9101 // eliminated if the set contains a second function template 9102 // specialization whose function template is more specialized 9103 // than the function template of F1 according to the partial 9104 // ordering rules of 14.5.5.2. 9105 9106 // The algorithm specified above is quadratic. We instead use a 9107 // two-pass algorithm (similar to the one used to identify the 9108 // best viable function in an overload set) that identifies the 9109 // best function template (if it exists). 9110 9111 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 9112 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 9113 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 9114 9115 UnresolvedSetIterator Result = 9116 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(), 9117 TPOC_Other, 0, SourceExpr->getLocStart(), 9118 S.PDiag(), 9119 S.PDiag(diag::err_addr_ovl_ambiguous) 9120 << Matches[0].second->getDeclName(), 9121 S.PDiag(diag::note_ovl_candidate) 9122 << (unsigned) oc_function_template, 9123 Complain, TargetFunctionType); 9124 9125 if (Result != MatchesCopy.end()) { 9126 // Make it the first and only element 9127 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 9128 Matches[0].second = cast<FunctionDecl>(*Result); 9129 Matches.resize(1); 9130 } 9131 } 9132 9133 void EliminateAllTemplateMatches() { 9134 // [...] any function template specializations in the set are 9135 // eliminated if the set also contains a non-template function, [...] 9136 for (unsigned I = 0, N = Matches.size(); I != N; ) { 9137 if (Matches[I].second->getPrimaryTemplate() == 0) 9138 ++I; 9139 else { 9140 Matches[I] = Matches[--N]; 9141 Matches.set_size(N); 9142 } 9143 } 9144 } 9145 9146 public: 9147 void ComplainNoMatchesFound() const { 9148 assert(Matches.empty()); 9149 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 9150 << OvlExpr->getName() << TargetFunctionType 9151 << OvlExpr->getSourceRange(); 9152 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9153 } 9154 9155 bool IsInvalidFormOfPointerToMemberFunction() const { 9156 return TargetTypeIsNonStaticMemberFunction && 9157 !OvlExprInfo.HasFormOfMemberPointer; 9158 } 9159 9160 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 9161 // TODO: Should we condition this on whether any functions might 9162 // have matched, or is it more appropriate to do that in callers? 9163 // TODO: a fixit wouldn't hurt. 9164 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 9165 << TargetType << OvlExpr->getSourceRange(); 9166 } 9167 9168 void ComplainOfInvalidConversion() const { 9169 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 9170 << OvlExpr->getName() << TargetType; 9171 } 9172 9173 void ComplainMultipleMatchesFound() const { 9174 assert(Matches.size() > 1); 9175 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 9176 << OvlExpr->getName() 9177 << OvlExpr->getSourceRange(); 9178 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9179 } 9180 9181 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 9182 9183 int getNumMatches() const { return Matches.size(); } 9184 9185 FunctionDecl* getMatchingFunctionDecl() const { 9186 if (Matches.size() != 1) return 0; 9187 return Matches[0].second; 9188 } 9189 9190 const DeclAccessPair* getMatchingFunctionAccessPair() const { 9191 if (Matches.size() != 1) return 0; 9192 return &Matches[0].first; 9193 } 9194 }; 9195 9196 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 9197 /// an overloaded function (C++ [over.over]), where @p From is an 9198 /// expression with overloaded function type and @p ToType is the type 9199 /// we're trying to resolve to. For example: 9200 /// 9201 /// @code 9202 /// int f(double); 9203 /// int f(int); 9204 /// 9205 /// int (*pfd)(double) = f; // selects f(double) 9206 /// @endcode 9207 /// 9208 /// This routine returns the resulting FunctionDecl if it could be 9209 /// resolved, and NULL otherwise. When @p Complain is true, this 9210 /// routine will emit diagnostics if there is an error. 9211 FunctionDecl * 9212 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 9213 QualType TargetType, 9214 bool Complain, 9215 DeclAccessPair &FoundResult, 9216 bool *pHadMultipleCandidates) { 9217 assert(AddressOfExpr->getType() == Context.OverloadTy); 9218 9219 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 9220 Complain); 9221 int NumMatches = Resolver.getNumMatches(); 9222 FunctionDecl* Fn = 0; 9223 if (NumMatches == 0 && Complain) { 9224 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 9225 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 9226 else 9227 Resolver.ComplainNoMatchesFound(); 9228 } 9229 else if (NumMatches > 1 && Complain) 9230 Resolver.ComplainMultipleMatchesFound(); 9231 else if (NumMatches == 1) { 9232 Fn = Resolver.getMatchingFunctionDecl(); 9233 assert(Fn); 9234 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 9235 if (Complain) 9236 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 9237 } 9238 9239 if (pHadMultipleCandidates) 9240 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 9241 return Fn; 9242 } 9243 9244 /// \brief Given an expression that refers to an overloaded function, try to 9245 /// resolve that overloaded function expression down to a single function. 9246 /// 9247 /// This routine can only resolve template-ids that refer to a single function 9248 /// template, where that template-id refers to a single template whose template 9249 /// arguments are either provided by the template-id or have defaults, 9250 /// as described in C++0x [temp.arg.explicit]p3. 9251 FunctionDecl * 9252 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 9253 bool Complain, 9254 DeclAccessPair *FoundResult) { 9255 // C++ [over.over]p1: 9256 // [...] [Note: any redundant set of parentheses surrounding the 9257 // overloaded function name is ignored (5.1). ] 9258 // C++ [over.over]p1: 9259 // [...] The overloaded function name can be preceded by the & 9260 // operator. 9261 9262 // If we didn't actually find any template-ids, we're done. 9263 if (!ovl->hasExplicitTemplateArgs()) 9264 return 0; 9265 9266 TemplateArgumentListInfo ExplicitTemplateArgs; 9267 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 9268 9269 // Look through all of the overloaded functions, searching for one 9270 // whose type matches exactly. 9271 FunctionDecl *Matched = 0; 9272 for (UnresolvedSetIterator I = ovl->decls_begin(), 9273 E = ovl->decls_end(); I != E; ++I) { 9274 // C++0x [temp.arg.explicit]p3: 9275 // [...] In contexts where deduction is done and fails, or in contexts 9276 // where deduction is not done, if a template argument list is 9277 // specified and it, along with any default template arguments, 9278 // identifies a single function template specialization, then the 9279 // template-id is an lvalue for the function template specialization. 9280 FunctionTemplateDecl *FunctionTemplate 9281 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 9282 9283 // C++ [over.over]p2: 9284 // If the name is a function template, template argument deduction is 9285 // done (14.8.2.2), and if the argument deduction succeeds, the 9286 // resulting template argument list is used to generate a single 9287 // function template specialization, which is added to the set of 9288 // overloaded functions considered. 9289 FunctionDecl *Specialization = 0; 9290 TemplateDeductionInfo Info(ovl->getNameLoc()); 9291 if (TemplateDeductionResult Result 9292 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 9293 Specialization, Info)) { 9294 // FIXME: make a note of the failed deduction for diagnostics. 9295 (void)Result; 9296 continue; 9297 } 9298 9299 assert(Specialization && "no specialization and no error?"); 9300 9301 // Multiple matches; we can't resolve to a single declaration. 9302 if (Matched) { 9303 if (Complain) { 9304 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 9305 << ovl->getName(); 9306 NoteAllOverloadCandidates(ovl); 9307 } 9308 return 0; 9309 } 9310 9311 Matched = Specialization; 9312 if (FoundResult) *FoundResult = I.getPair(); 9313 } 9314 9315 return Matched; 9316 } 9317 9318 9319 9320 9321 // Resolve and fix an overloaded expression that can be resolved 9322 // because it identifies a single function template specialization. 9323 // 9324 // Last three arguments should only be supplied if Complain = true 9325 // 9326 // Return true if it was logically possible to so resolve the 9327 // expression, regardless of whether or not it succeeded. Always 9328 // returns true if 'complain' is set. 9329 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 9330 ExprResult &SrcExpr, bool doFunctionPointerConverion, 9331 bool complain, const SourceRange& OpRangeForComplaining, 9332 QualType DestTypeForComplaining, 9333 unsigned DiagIDForComplaining) { 9334 assert(SrcExpr.get()->getType() == Context.OverloadTy); 9335 9336 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 9337 9338 DeclAccessPair found; 9339 ExprResult SingleFunctionExpression; 9340 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 9341 ovl.Expression, /*complain*/ false, &found)) { 9342 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 9343 SrcExpr = ExprError(); 9344 return true; 9345 } 9346 9347 // It is only correct to resolve to an instance method if we're 9348 // resolving a form that's permitted to be a pointer to member. 9349 // Otherwise we'll end up making a bound member expression, which 9350 // is illegal in all the contexts we resolve like this. 9351 if (!ovl.HasFormOfMemberPointer && 9352 isa<CXXMethodDecl>(fn) && 9353 cast<CXXMethodDecl>(fn)->isInstance()) { 9354 if (!complain) return false; 9355 9356 Diag(ovl.Expression->getExprLoc(), 9357 diag::err_bound_member_function) 9358 << 0 << ovl.Expression->getSourceRange(); 9359 9360 // TODO: I believe we only end up here if there's a mix of 9361 // static and non-static candidates (otherwise the expression 9362 // would have 'bound member' type, not 'overload' type). 9363 // Ideally we would note which candidate was chosen and why 9364 // the static candidates were rejected. 9365 SrcExpr = ExprError(); 9366 return true; 9367 } 9368 9369 // Fix the expression to refer to 'fn'. 9370 SingleFunctionExpression = 9371 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn)); 9372 9373 // If desired, do function-to-pointer decay. 9374 if (doFunctionPointerConverion) { 9375 SingleFunctionExpression = 9376 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take()); 9377 if (SingleFunctionExpression.isInvalid()) { 9378 SrcExpr = ExprError(); 9379 return true; 9380 } 9381 } 9382 } 9383 9384 if (!SingleFunctionExpression.isUsable()) { 9385 if (complain) { 9386 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 9387 << ovl.Expression->getName() 9388 << DestTypeForComplaining 9389 << OpRangeForComplaining 9390 << ovl.Expression->getQualifierLoc().getSourceRange(); 9391 NoteAllOverloadCandidates(SrcExpr.get()); 9392 9393 SrcExpr = ExprError(); 9394 return true; 9395 } 9396 9397 return false; 9398 } 9399 9400 SrcExpr = SingleFunctionExpression; 9401 return true; 9402 } 9403 9404 /// \brief Add a single candidate to the overload set. 9405 static void AddOverloadedCallCandidate(Sema &S, 9406 DeclAccessPair FoundDecl, 9407 TemplateArgumentListInfo *ExplicitTemplateArgs, 9408 llvm::ArrayRef<Expr *> Args, 9409 OverloadCandidateSet &CandidateSet, 9410 bool PartialOverloading, 9411 bool KnownValid) { 9412 NamedDecl *Callee = FoundDecl.getDecl(); 9413 if (isa<UsingShadowDecl>(Callee)) 9414 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 9415 9416 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 9417 if (ExplicitTemplateArgs) { 9418 assert(!KnownValid && "Explicit template arguments?"); 9419 return; 9420 } 9421 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false, 9422 PartialOverloading); 9423 return; 9424 } 9425 9426 if (FunctionTemplateDecl *FuncTemplate 9427 = dyn_cast<FunctionTemplateDecl>(Callee)) { 9428 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 9429 ExplicitTemplateArgs, Args, CandidateSet); 9430 return; 9431 } 9432 9433 assert(!KnownValid && "unhandled case in overloaded call candidate"); 9434 } 9435 9436 /// \brief Add the overload candidates named by callee and/or found by argument 9437 /// dependent lookup to the given overload set. 9438 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 9439 llvm::ArrayRef<Expr *> Args, 9440 OverloadCandidateSet &CandidateSet, 9441 bool PartialOverloading) { 9442 9443 #ifndef NDEBUG 9444 // Verify that ArgumentDependentLookup is consistent with the rules 9445 // in C++0x [basic.lookup.argdep]p3: 9446 // 9447 // Let X be the lookup set produced by unqualified lookup (3.4.1) 9448 // and let Y be the lookup set produced by argument dependent 9449 // lookup (defined as follows). If X contains 9450 // 9451 // -- a declaration of a class member, or 9452 // 9453 // -- a block-scope function declaration that is not a 9454 // using-declaration, or 9455 // 9456 // -- a declaration that is neither a function or a function 9457 // template 9458 // 9459 // then Y is empty. 9460 9461 if (ULE->requiresADL()) { 9462 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9463 E = ULE->decls_end(); I != E; ++I) { 9464 assert(!(*I)->getDeclContext()->isRecord()); 9465 assert(isa<UsingShadowDecl>(*I) || 9466 !(*I)->getDeclContext()->isFunctionOrMethod()); 9467 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 9468 } 9469 } 9470 #endif 9471 9472 // It would be nice to avoid this copy. 9473 TemplateArgumentListInfo TABuffer; 9474 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9475 if (ULE->hasExplicitTemplateArgs()) { 9476 ULE->copyTemplateArgumentsInto(TABuffer); 9477 ExplicitTemplateArgs = &TABuffer; 9478 } 9479 9480 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9481 E = ULE->decls_end(); I != E; ++I) 9482 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 9483 CandidateSet, PartialOverloading, 9484 /*KnownValid*/ true); 9485 9486 if (ULE->requiresADL()) 9487 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 9488 ULE->getExprLoc(), 9489 Args, ExplicitTemplateArgs, 9490 CandidateSet, PartialOverloading); 9491 } 9492 9493 /// Attempt to recover from an ill-formed use of a non-dependent name in a 9494 /// template, where the non-dependent name was declared after the template 9495 /// was defined. This is common in code written for a compilers which do not 9496 /// correctly implement two-stage name lookup. 9497 /// 9498 /// Returns true if a viable candidate was found and a diagnostic was issued. 9499 static bool 9500 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 9501 const CXXScopeSpec &SS, LookupResult &R, 9502 TemplateArgumentListInfo *ExplicitTemplateArgs, 9503 llvm::ArrayRef<Expr *> Args) { 9504 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 9505 return false; 9506 9507 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 9508 if (DC->isTransparentContext()) 9509 continue; 9510 9511 SemaRef.LookupQualifiedName(R, DC); 9512 9513 if (!R.empty()) { 9514 R.suppressDiagnostics(); 9515 9516 if (isa<CXXRecordDecl>(DC)) { 9517 // Don't diagnose names we find in classes; we get much better 9518 // diagnostics for these from DiagnoseEmptyLookup. 9519 R.clear(); 9520 return false; 9521 } 9522 9523 OverloadCandidateSet Candidates(FnLoc); 9524 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9525 AddOverloadedCallCandidate(SemaRef, I.getPair(), 9526 ExplicitTemplateArgs, Args, 9527 Candidates, false, /*KnownValid*/ false); 9528 9529 OverloadCandidateSet::iterator Best; 9530 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 9531 // No viable functions. Don't bother the user with notes for functions 9532 // which don't work and shouldn't be found anyway. 9533 R.clear(); 9534 return false; 9535 } 9536 9537 // Find the namespaces where ADL would have looked, and suggest 9538 // declaring the function there instead. 9539 Sema::AssociatedNamespaceSet AssociatedNamespaces; 9540 Sema::AssociatedClassSet AssociatedClasses; 9541 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 9542 AssociatedNamespaces, 9543 AssociatedClasses); 9544 // Never suggest declaring a function within namespace 'std'. 9545 Sema::AssociatedNamespaceSet SuggestedNamespaces; 9546 DeclContext *Std = SemaRef.getStdNamespace(); 9547 for (Sema::AssociatedNamespaceSet::iterator 9548 it = AssociatedNamespaces.begin(), 9549 end = AssociatedNamespaces.end(); it != end; ++it) { 9550 NamespaceDecl *Assoc = cast<NamespaceDecl>(*it); 9551 if ((!Std || !Std->Encloses(Assoc)) && 9552 Assoc->getQualifiedNameAsString().find("__") == std::string::npos) 9553 SuggestedNamespaces.insert(Assoc); 9554 } 9555 9556 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 9557 << R.getLookupName(); 9558 if (SuggestedNamespaces.empty()) { 9559 SemaRef.Diag(Best->Function->getLocation(), 9560 diag::note_not_found_by_two_phase_lookup) 9561 << R.getLookupName() << 0; 9562 } else if (SuggestedNamespaces.size() == 1) { 9563 SemaRef.Diag(Best->Function->getLocation(), 9564 diag::note_not_found_by_two_phase_lookup) 9565 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 9566 } else { 9567 // FIXME: It would be useful to list the associated namespaces here, 9568 // but the diagnostics infrastructure doesn't provide a way to produce 9569 // a localized representation of a list of items. 9570 SemaRef.Diag(Best->Function->getLocation(), 9571 diag::note_not_found_by_two_phase_lookup) 9572 << R.getLookupName() << 2; 9573 } 9574 9575 // Try to recover by calling this function. 9576 return true; 9577 } 9578 9579 R.clear(); 9580 } 9581 9582 return false; 9583 } 9584 9585 /// Attempt to recover from ill-formed use of a non-dependent operator in a 9586 /// template, where the non-dependent operator was declared after the template 9587 /// was defined. 9588 /// 9589 /// Returns true if a viable candidate was found and a diagnostic was issued. 9590 static bool 9591 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 9592 SourceLocation OpLoc, 9593 llvm::ArrayRef<Expr *> Args) { 9594 DeclarationName OpName = 9595 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 9596 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 9597 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 9598 /*ExplicitTemplateArgs=*/0, Args); 9599 } 9600 9601 namespace { 9602 // Callback to limit the allowed keywords and to only accept typo corrections 9603 // that are keywords or whose decls refer to functions (or template functions) 9604 // that accept the given number of arguments. 9605 class RecoveryCallCCC : public CorrectionCandidateCallback { 9606 public: 9607 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs) 9608 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) { 9609 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus; 9610 WantRemainingKeywords = false; 9611 } 9612 9613 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9614 if (!candidate.getCorrectionDecl()) 9615 return candidate.isKeyword(); 9616 9617 for (TypoCorrection::const_decl_iterator DI = candidate.begin(), 9618 DIEnd = candidate.end(); DI != DIEnd; ++DI) { 9619 FunctionDecl *FD = 0; 9620 NamedDecl *ND = (*DI)->getUnderlyingDecl(); 9621 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 9622 FD = FTD->getTemplatedDecl(); 9623 if (!HasExplicitTemplateArgs && !FD) { 9624 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) { 9625 // If the Decl is neither a function nor a template function, 9626 // determine if it is a pointer or reference to a function. If so, 9627 // check against the number of arguments expected for the pointee. 9628 QualType ValType = cast<ValueDecl>(ND)->getType(); 9629 if (ValType->isAnyPointerType() || ValType->isReferenceType()) 9630 ValType = ValType->getPointeeType(); 9631 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>()) 9632 if (FPT->getNumArgs() == NumArgs) 9633 return true; 9634 } 9635 } 9636 if (FD && FD->getNumParams() >= NumArgs && 9637 FD->getMinRequiredArguments() <= NumArgs) 9638 return true; 9639 } 9640 return false; 9641 } 9642 9643 private: 9644 unsigned NumArgs; 9645 bool HasExplicitTemplateArgs; 9646 }; 9647 9648 // Callback that effectively disabled typo correction 9649 class NoTypoCorrectionCCC : public CorrectionCandidateCallback { 9650 public: 9651 NoTypoCorrectionCCC() { 9652 WantTypeSpecifiers = false; 9653 WantExpressionKeywords = false; 9654 WantCXXNamedCasts = false; 9655 WantRemainingKeywords = false; 9656 } 9657 9658 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9659 return false; 9660 } 9661 }; 9662 9663 class BuildRecoveryCallExprRAII { 9664 Sema &SemaRef; 9665 public: 9666 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 9667 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 9668 SemaRef.IsBuildingRecoveryCallExpr = true; 9669 } 9670 9671 ~BuildRecoveryCallExprRAII() { 9672 SemaRef.IsBuildingRecoveryCallExpr = false; 9673 } 9674 }; 9675 9676 } 9677 9678 /// Attempts to recover from a call where no functions were found. 9679 /// 9680 /// Returns true if new candidates were found. 9681 static ExprResult 9682 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9683 UnresolvedLookupExpr *ULE, 9684 SourceLocation LParenLoc, 9685 llvm::MutableArrayRef<Expr *> Args, 9686 SourceLocation RParenLoc, 9687 bool EmptyLookup, bool AllowTypoCorrection) { 9688 // Do not try to recover if it is already building a recovery call. 9689 // This stops infinite loops for template instantiations like 9690 // 9691 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 9692 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 9693 // 9694 if (SemaRef.IsBuildingRecoveryCallExpr) 9695 return ExprError(); 9696 BuildRecoveryCallExprRAII RCE(SemaRef); 9697 9698 CXXScopeSpec SS; 9699 SS.Adopt(ULE->getQualifierLoc()); 9700 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 9701 9702 TemplateArgumentListInfo TABuffer; 9703 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9704 if (ULE->hasExplicitTemplateArgs()) { 9705 ULE->copyTemplateArgumentsInto(TABuffer); 9706 ExplicitTemplateArgs = &TABuffer; 9707 } 9708 9709 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 9710 Sema::LookupOrdinaryName); 9711 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0); 9712 NoTypoCorrectionCCC RejectAll; 9713 CorrectionCandidateCallback *CCC = AllowTypoCorrection ? 9714 (CorrectionCandidateCallback*)&Validator : 9715 (CorrectionCandidateCallback*)&RejectAll; 9716 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 9717 ExplicitTemplateArgs, Args) && 9718 (!EmptyLookup || 9719 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC, 9720 ExplicitTemplateArgs, Args))) 9721 return ExprError(); 9722 9723 assert(!R.empty() && "lookup results empty despite recovery"); 9724 9725 // Build an implicit member call if appropriate. Just drop the 9726 // casts and such from the call, we don't really care. 9727 ExprResult NewFn = ExprError(); 9728 if ((*R.begin())->isCXXClassMember()) 9729 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 9730 R, ExplicitTemplateArgs); 9731 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 9732 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 9733 ExplicitTemplateArgs); 9734 else 9735 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 9736 9737 if (NewFn.isInvalid()) 9738 return ExprError(); 9739 9740 // This shouldn't cause an infinite loop because we're giving it 9741 // an expression with viable lookup results, which should never 9742 // end up here. 9743 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 9744 MultiExprArg(Args.data(), Args.size()), 9745 RParenLoc); 9746 } 9747 9748 /// \brief Constructs and populates an OverloadedCandidateSet from 9749 /// the given function. 9750 /// \returns true when an the ExprResult output parameter has been set. 9751 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 9752 UnresolvedLookupExpr *ULE, 9753 Expr **Args, unsigned NumArgs, 9754 SourceLocation RParenLoc, 9755 OverloadCandidateSet *CandidateSet, 9756 ExprResult *Result) { 9757 #ifndef NDEBUG 9758 if (ULE->requiresADL()) { 9759 // To do ADL, we must have found an unqualified name. 9760 assert(!ULE->getQualifier() && "qualified name with ADL"); 9761 9762 // We don't perform ADL for implicit declarations of builtins. 9763 // Verify that this was correctly set up. 9764 FunctionDecl *F; 9765 if (ULE->decls_begin() + 1 == ULE->decls_end() && 9766 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 9767 F->getBuiltinID() && F->isImplicit()) 9768 llvm_unreachable("performing ADL for builtin"); 9769 9770 // We don't perform ADL in C. 9771 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 9772 } 9773 #endif 9774 9775 UnbridgedCastsSet UnbridgedCasts; 9776 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) { 9777 *Result = ExprError(); 9778 return true; 9779 } 9780 9781 // Add the functions denoted by the callee to the set of candidate 9782 // functions, including those from argument-dependent lookup. 9783 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs), 9784 *CandidateSet); 9785 9786 // If we found nothing, try to recover. 9787 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 9788 // out if it fails. 9789 if (CandidateSet->empty()) { 9790 // In Microsoft mode, if we are inside a template class member function then 9791 // create a type dependent CallExpr. The goal is to postpone name lookup 9792 // to instantiation time to be able to search into type dependent base 9793 // classes. 9794 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() && 9795 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 9796 CallExpr *CE = new (Context) CallExpr(Context, Fn, 9797 llvm::makeArrayRef(Args, NumArgs), 9798 Context.DependentTy, VK_RValue, 9799 RParenLoc); 9800 CE->setTypeDependent(true); 9801 *Result = Owned(CE); 9802 return true; 9803 } 9804 return false; 9805 } 9806 9807 UnbridgedCasts.restore(); 9808 return false; 9809 } 9810 9811 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 9812 /// the completed call expression. If overload resolution fails, emits 9813 /// diagnostics and returns ExprError() 9814 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9815 UnresolvedLookupExpr *ULE, 9816 SourceLocation LParenLoc, 9817 Expr **Args, unsigned NumArgs, 9818 SourceLocation RParenLoc, 9819 Expr *ExecConfig, 9820 OverloadCandidateSet *CandidateSet, 9821 OverloadCandidateSet::iterator *Best, 9822 OverloadingResult OverloadResult, 9823 bool AllowTypoCorrection) { 9824 if (CandidateSet->empty()) 9825 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 9826 llvm::MutableArrayRef<Expr *>(Args, NumArgs), 9827 RParenLoc, /*EmptyLookup=*/true, 9828 AllowTypoCorrection); 9829 9830 switch (OverloadResult) { 9831 case OR_Success: { 9832 FunctionDecl *FDecl = (*Best)->Function; 9833 SemaRef.MarkFunctionReferenced(Fn->getExprLoc(), FDecl); 9834 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 9835 SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()); 9836 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 9837 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, 9838 RParenLoc, ExecConfig); 9839 } 9840 9841 case OR_No_Viable_Function: { 9842 // Try to recover by looking for viable functions which the user might 9843 // have meant to call. 9844 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 9845 llvm::MutableArrayRef<Expr *>(Args, NumArgs), 9846 RParenLoc, 9847 /*EmptyLookup=*/false, 9848 AllowTypoCorrection); 9849 if (!Recovery.isInvalid()) 9850 return Recovery; 9851 9852 SemaRef.Diag(Fn->getLocStart(), 9853 diag::err_ovl_no_viable_function_in_call) 9854 << ULE->getName() << Fn->getSourceRange(); 9855 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, 9856 llvm::makeArrayRef(Args, NumArgs)); 9857 break; 9858 } 9859 9860 case OR_Ambiguous: 9861 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 9862 << ULE->getName() << Fn->getSourceRange(); 9863 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, 9864 llvm::makeArrayRef(Args, NumArgs)); 9865 break; 9866 9867 case OR_Deleted: { 9868 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 9869 << (*Best)->Function->isDeleted() 9870 << ULE->getName() 9871 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 9872 << Fn->getSourceRange(); 9873 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, 9874 llvm::makeArrayRef(Args, NumArgs)); 9875 9876 // We emitted an error for the unvailable/deleted function call but keep 9877 // the call in the AST. 9878 FunctionDecl *FDecl = (*Best)->Function; 9879 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 9880 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, 9881 RParenLoc, ExecConfig); 9882 } 9883 } 9884 9885 // Overload resolution failed. 9886 return ExprError(); 9887 } 9888 9889 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 9890 /// (which eventually refers to the declaration Func) and the call 9891 /// arguments Args/NumArgs, attempt to resolve the function call down 9892 /// to a specific function. If overload resolution succeeds, returns 9893 /// the call expression produced by overload resolution. 9894 /// Otherwise, emits diagnostics and returns ExprError. 9895 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 9896 UnresolvedLookupExpr *ULE, 9897 SourceLocation LParenLoc, 9898 Expr **Args, unsigned NumArgs, 9899 SourceLocation RParenLoc, 9900 Expr *ExecConfig, 9901 bool AllowTypoCorrection) { 9902 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 9903 ExprResult result; 9904 9905 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc, 9906 &CandidateSet, &result)) 9907 return result; 9908 9909 OverloadCandidateSet::iterator Best; 9910 OverloadingResult OverloadResult = 9911 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 9912 9913 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs, 9914 RParenLoc, ExecConfig, &CandidateSet, 9915 &Best, OverloadResult, 9916 AllowTypoCorrection); 9917 } 9918 9919 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 9920 return Functions.size() > 1 || 9921 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 9922 } 9923 9924 /// \brief Create a unary operation that may resolve to an overloaded 9925 /// operator. 9926 /// 9927 /// \param OpLoc The location of the operator itself (e.g., '*'). 9928 /// 9929 /// \param OpcIn The UnaryOperator::Opcode that describes this 9930 /// operator. 9931 /// 9932 /// \param Fns The set of non-member functions that will be 9933 /// considered by overload resolution. The caller needs to build this 9934 /// set based on the context using, e.g., 9935 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 9936 /// set should not contain any member functions; those will be added 9937 /// by CreateOverloadedUnaryOp(). 9938 /// 9939 /// \param Input The input argument. 9940 ExprResult 9941 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 9942 const UnresolvedSetImpl &Fns, 9943 Expr *Input) { 9944 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 9945 9946 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 9947 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 9948 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 9949 // TODO: provide better source location info. 9950 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 9951 9952 if (checkPlaceholderForOverload(*this, Input)) 9953 return ExprError(); 9954 9955 Expr *Args[2] = { Input, 0 }; 9956 unsigned NumArgs = 1; 9957 9958 // For post-increment and post-decrement, add the implicit '0' as 9959 // the second argument, so that we know this is a post-increment or 9960 // post-decrement. 9961 if (Opc == UO_PostInc || Opc == UO_PostDec) { 9962 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 9963 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 9964 SourceLocation()); 9965 NumArgs = 2; 9966 } 9967 9968 if (Input->isTypeDependent()) { 9969 if (Fns.empty()) 9970 return Owned(new (Context) UnaryOperator(Input, 9971 Opc, 9972 Context.DependentTy, 9973 VK_RValue, OK_Ordinary, 9974 OpLoc)); 9975 9976 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 9977 UnresolvedLookupExpr *Fn 9978 = UnresolvedLookupExpr::Create(Context, NamingClass, 9979 NestedNameSpecifierLoc(), OpNameInfo, 9980 /*ADL*/ true, IsOverloaded(Fns), 9981 Fns.begin(), Fns.end()); 9982 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 9983 llvm::makeArrayRef(Args, NumArgs), 9984 Context.DependentTy, 9985 VK_RValue, 9986 OpLoc, false)); 9987 } 9988 9989 // Build an empty overload set. 9990 OverloadCandidateSet CandidateSet(OpLoc); 9991 9992 // Add the candidates from the given function set. 9993 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet, 9994 false); 9995 9996 // Add operator candidates that are member functions. 9997 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 9998 9999 // Add candidates from ADL. 10000 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10001 OpLoc, llvm::makeArrayRef(Args, NumArgs), 10002 /*ExplicitTemplateArgs*/ 0, 10003 CandidateSet); 10004 10005 // Add builtin operator candidates. 10006 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 10007 10008 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10009 10010 // Perform overload resolution. 10011 OverloadCandidateSet::iterator Best; 10012 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10013 case OR_Success: { 10014 // We found a built-in operator or an overloaded operator. 10015 FunctionDecl *FnDecl = Best->Function; 10016 10017 if (FnDecl) { 10018 // We matched an overloaded operator. Build a call to that 10019 // operator. 10020 10021 MarkFunctionReferenced(OpLoc, FnDecl); 10022 10023 // Convert the arguments. 10024 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10025 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 10026 10027 ExprResult InputRes = 10028 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 10029 Best->FoundDecl, Method); 10030 if (InputRes.isInvalid()) 10031 return ExprError(); 10032 Input = InputRes.take(); 10033 } else { 10034 // Convert the arguments. 10035 ExprResult InputInit 10036 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10037 Context, 10038 FnDecl->getParamDecl(0)), 10039 SourceLocation(), 10040 Input); 10041 if (InputInit.isInvalid()) 10042 return ExprError(); 10043 Input = InputInit.take(); 10044 } 10045 10046 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 10047 10048 // Determine the result type. 10049 QualType ResultTy = FnDecl->getResultType(); 10050 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10051 ResultTy = ResultTy.getNonLValueExprType(Context); 10052 10053 // Build the actual expression node. 10054 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10055 HadMultipleCandidates, OpLoc); 10056 if (FnExpr.isInvalid()) 10057 return ExprError(); 10058 10059 Args[0] = Input; 10060 CallExpr *TheCall = 10061 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10062 llvm::makeArrayRef(Args, NumArgs), 10063 ResultTy, VK, OpLoc, false); 10064 10065 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10066 FnDecl)) 10067 return ExprError(); 10068 10069 return MaybeBindToTemporary(TheCall); 10070 } else { 10071 // We matched a built-in operator. Convert the arguments, then 10072 // break out so that we will build the appropriate built-in 10073 // operator node. 10074 ExprResult InputRes = 10075 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 10076 Best->Conversions[0], AA_Passing); 10077 if (InputRes.isInvalid()) 10078 return ExprError(); 10079 Input = InputRes.take(); 10080 break; 10081 } 10082 } 10083 10084 case OR_No_Viable_Function: 10085 // This is an erroneous use of an operator which can be overloaded by 10086 // a non-member function. Check for non-member operators which were 10087 // defined too late to be candidates. 10088 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, 10089 llvm::makeArrayRef(Args, NumArgs))) 10090 // FIXME: Recover by calling the found function. 10091 return ExprError(); 10092 10093 // No viable function; fall through to handling this as a 10094 // built-in operator, which will produce an error message for us. 10095 break; 10096 10097 case OR_Ambiguous: 10098 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 10099 << UnaryOperator::getOpcodeStr(Opc) 10100 << Input->getType() 10101 << Input->getSourceRange(); 10102 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 10103 llvm::makeArrayRef(Args, NumArgs), 10104 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10105 return ExprError(); 10106 10107 case OR_Deleted: 10108 Diag(OpLoc, diag::err_ovl_deleted_oper) 10109 << Best->Function->isDeleted() 10110 << UnaryOperator::getOpcodeStr(Opc) 10111 << getDeletedOrUnavailableSuffix(Best->Function) 10112 << Input->getSourceRange(); 10113 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10114 llvm::makeArrayRef(Args, NumArgs), 10115 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10116 return ExprError(); 10117 } 10118 10119 // Either we found no viable overloaded operator or we matched a 10120 // built-in operator. In either case, fall through to trying to 10121 // build a built-in operation. 10122 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10123 } 10124 10125 /// \brief Create a binary operation that may resolve to an overloaded 10126 /// operator. 10127 /// 10128 /// \param OpLoc The location of the operator itself (e.g., '+'). 10129 /// 10130 /// \param OpcIn The BinaryOperator::Opcode that describes this 10131 /// operator. 10132 /// 10133 /// \param Fns The set of non-member functions that will be 10134 /// considered by overload resolution. The caller needs to build this 10135 /// set based on the context using, e.g., 10136 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10137 /// set should not contain any member functions; those will be added 10138 /// by CreateOverloadedBinOp(). 10139 /// 10140 /// \param LHS Left-hand argument. 10141 /// \param RHS Right-hand argument. 10142 ExprResult 10143 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 10144 unsigned OpcIn, 10145 const UnresolvedSetImpl &Fns, 10146 Expr *LHS, Expr *RHS) { 10147 Expr *Args[2] = { LHS, RHS }; 10148 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 10149 10150 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 10151 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 10152 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10153 10154 // If either side is type-dependent, create an appropriate dependent 10155 // expression. 10156 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10157 if (Fns.empty()) { 10158 // If there are no functions to store, just build a dependent 10159 // BinaryOperator or CompoundAssignment. 10160 if (Opc <= BO_Assign || Opc > BO_OrAssign) 10161 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 10162 Context.DependentTy, 10163 VK_RValue, OK_Ordinary, 10164 OpLoc, 10165 FPFeatures.fp_contract)); 10166 10167 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 10168 Context.DependentTy, 10169 VK_LValue, 10170 OK_Ordinary, 10171 Context.DependentTy, 10172 Context.DependentTy, 10173 OpLoc, 10174 FPFeatures.fp_contract)); 10175 } 10176 10177 // FIXME: save results of ADL from here? 10178 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10179 // TODO: provide better source location info in DNLoc component. 10180 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10181 UnresolvedLookupExpr *Fn 10182 = UnresolvedLookupExpr::Create(Context, NamingClass, 10183 NestedNameSpecifierLoc(), OpNameInfo, 10184 /*ADL*/ true, IsOverloaded(Fns), 10185 Fns.begin(), Fns.end()); 10186 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args, 10187 Context.DependentTy, VK_RValue, 10188 OpLoc, FPFeatures.fp_contract)); 10189 } 10190 10191 // Always do placeholder-like conversions on the RHS. 10192 if (checkPlaceholderForOverload(*this, Args[1])) 10193 return ExprError(); 10194 10195 // Do placeholder-like conversion on the LHS; note that we should 10196 // not get here with a PseudoObject LHS. 10197 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 10198 if (checkPlaceholderForOverload(*this, Args[0])) 10199 return ExprError(); 10200 10201 // If this is the assignment operator, we only perform overload resolution 10202 // if the left-hand side is a class or enumeration type. This is actually 10203 // a hack. The standard requires that we do overload resolution between the 10204 // various built-in candidates, but as DR507 points out, this can lead to 10205 // problems. So we do it this way, which pretty much follows what GCC does. 10206 // Note that we go the traditional code path for compound assignment forms. 10207 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 10208 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10209 10210 // If this is the .* operator, which is not overloadable, just 10211 // create a built-in binary operator. 10212 if (Opc == BO_PtrMemD) 10213 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10214 10215 // Build an empty overload set. 10216 OverloadCandidateSet CandidateSet(OpLoc); 10217 10218 // Add the candidates from the given function set. 10219 AddFunctionCandidates(Fns, Args, CandidateSet, false); 10220 10221 // Add operator candidates that are member functions. 10222 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 10223 10224 // Add candidates from ADL. 10225 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10226 OpLoc, Args, 10227 /*ExplicitTemplateArgs*/ 0, 10228 CandidateSet); 10229 10230 // Add builtin operator candidates. 10231 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 10232 10233 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10234 10235 // Perform overload resolution. 10236 OverloadCandidateSet::iterator Best; 10237 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10238 case OR_Success: { 10239 // We found a built-in operator or an overloaded operator. 10240 FunctionDecl *FnDecl = Best->Function; 10241 10242 if (FnDecl) { 10243 // We matched an overloaded operator. Build a call to that 10244 // operator. 10245 10246 MarkFunctionReferenced(OpLoc, FnDecl); 10247 10248 // Convert the arguments. 10249 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10250 // Best->Access is only meaningful for class members. 10251 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 10252 10253 ExprResult Arg1 = 10254 PerformCopyInitialization( 10255 InitializedEntity::InitializeParameter(Context, 10256 FnDecl->getParamDecl(0)), 10257 SourceLocation(), Owned(Args[1])); 10258 if (Arg1.isInvalid()) 10259 return ExprError(); 10260 10261 ExprResult Arg0 = 10262 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10263 Best->FoundDecl, Method); 10264 if (Arg0.isInvalid()) 10265 return ExprError(); 10266 Args[0] = Arg0.takeAs<Expr>(); 10267 Args[1] = RHS = Arg1.takeAs<Expr>(); 10268 } else { 10269 // Convert the arguments. 10270 ExprResult Arg0 = PerformCopyInitialization( 10271 InitializedEntity::InitializeParameter(Context, 10272 FnDecl->getParamDecl(0)), 10273 SourceLocation(), Owned(Args[0])); 10274 if (Arg0.isInvalid()) 10275 return ExprError(); 10276 10277 ExprResult Arg1 = 10278 PerformCopyInitialization( 10279 InitializedEntity::InitializeParameter(Context, 10280 FnDecl->getParamDecl(1)), 10281 SourceLocation(), Owned(Args[1])); 10282 if (Arg1.isInvalid()) 10283 return ExprError(); 10284 Args[0] = LHS = Arg0.takeAs<Expr>(); 10285 Args[1] = RHS = Arg1.takeAs<Expr>(); 10286 } 10287 10288 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 10289 10290 // Determine the result type. 10291 QualType ResultTy = FnDecl->getResultType(); 10292 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10293 ResultTy = ResultTy.getNonLValueExprType(Context); 10294 10295 // Build the actual expression node. 10296 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10297 HadMultipleCandidates, OpLoc); 10298 if (FnExpr.isInvalid()) 10299 return ExprError(); 10300 10301 CXXOperatorCallExpr *TheCall = 10302 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10303 Args, ResultTy, VK, OpLoc, 10304 FPFeatures.fp_contract); 10305 10306 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10307 FnDecl)) 10308 return ExprError(); 10309 10310 return MaybeBindToTemporary(TheCall); 10311 } else { 10312 // We matched a built-in operator. Convert the arguments, then 10313 // break out so that we will build the appropriate built-in 10314 // operator node. 10315 ExprResult ArgsRes0 = 10316 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10317 Best->Conversions[0], AA_Passing); 10318 if (ArgsRes0.isInvalid()) 10319 return ExprError(); 10320 Args[0] = ArgsRes0.take(); 10321 10322 ExprResult ArgsRes1 = 10323 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10324 Best->Conversions[1], AA_Passing); 10325 if (ArgsRes1.isInvalid()) 10326 return ExprError(); 10327 Args[1] = ArgsRes1.take(); 10328 break; 10329 } 10330 } 10331 10332 case OR_No_Viable_Function: { 10333 // C++ [over.match.oper]p9: 10334 // If the operator is the operator , [...] and there are no 10335 // viable functions, then the operator is assumed to be the 10336 // built-in operator and interpreted according to clause 5. 10337 if (Opc == BO_Comma) 10338 break; 10339 10340 // For class as left operand for assignment or compound assigment 10341 // operator do not fall through to handling in built-in, but report that 10342 // no overloaded assignment operator found 10343 ExprResult Result = ExprError(); 10344 if (Args[0]->getType()->isRecordType() && 10345 Opc >= BO_Assign && Opc <= BO_OrAssign) { 10346 Diag(OpLoc, diag::err_ovl_no_viable_oper) 10347 << BinaryOperator::getOpcodeStr(Opc) 10348 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10349 } else { 10350 // This is an erroneous use of an operator which can be overloaded by 10351 // a non-member function. Check for non-member operators which were 10352 // defined too late to be candidates. 10353 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 10354 // FIXME: Recover by calling the found function. 10355 return ExprError(); 10356 10357 // No viable function; try to create a built-in operation, which will 10358 // produce an error. Then, show the non-viable candidates. 10359 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10360 } 10361 assert(Result.isInvalid() && 10362 "C++ binary operator overloading is missing candidates!"); 10363 if (Result.isInvalid()) 10364 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10365 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10366 return Result; 10367 } 10368 10369 case OR_Ambiguous: 10370 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 10371 << BinaryOperator::getOpcodeStr(Opc) 10372 << Args[0]->getType() << Args[1]->getType() 10373 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10374 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10375 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10376 return ExprError(); 10377 10378 case OR_Deleted: 10379 if (isImplicitlyDeleted(Best->Function)) { 10380 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 10381 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 10382 << getSpecialMember(Method) 10383 << BinaryOperator::getOpcodeStr(Opc) 10384 << getDeletedOrUnavailableSuffix(Best->Function); 10385 10386 if (getSpecialMember(Method) != CXXInvalid) { 10387 // The user probably meant to call this special member. Just 10388 // explain why it's deleted. 10389 NoteDeletedFunction(Method); 10390 return ExprError(); 10391 } 10392 } else { 10393 Diag(OpLoc, diag::err_ovl_deleted_oper) 10394 << Best->Function->isDeleted() 10395 << BinaryOperator::getOpcodeStr(Opc) 10396 << getDeletedOrUnavailableSuffix(Best->Function) 10397 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10398 } 10399 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10400 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10401 return ExprError(); 10402 } 10403 10404 // We matched a built-in operator; build it. 10405 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10406 } 10407 10408 ExprResult 10409 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 10410 SourceLocation RLoc, 10411 Expr *Base, Expr *Idx) { 10412 Expr *Args[2] = { Base, Idx }; 10413 DeclarationName OpName = 10414 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 10415 10416 // If either side is type-dependent, create an appropriate dependent 10417 // expression. 10418 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10419 10420 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10421 // CHECKME: no 'operator' keyword? 10422 DeclarationNameInfo OpNameInfo(OpName, LLoc); 10423 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10424 UnresolvedLookupExpr *Fn 10425 = UnresolvedLookupExpr::Create(Context, NamingClass, 10426 NestedNameSpecifierLoc(), OpNameInfo, 10427 /*ADL*/ true, /*Overloaded*/ false, 10428 UnresolvedSetIterator(), 10429 UnresolvedSetIterator()); 10430 // Can't add any actual overloads yet 10431 10432 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 10433 Args, 10434 Context.DependentTy, 10435 VK_RValue, 10436 RLoc, false)); 10437 } 10438 10439 // Handle placeholders on both operands. 10440 if (checkPlaceholderForOverload(*this, Args[0])) 10441 return ExprError(); 10442 if (checkPlaceholderForOverload(*this, Args[1])) 10443 return ExprError(); 10444 10445 // Build an empty overload set. 10446 OverloadCandidateSet CandidateSet(LLoc); 10447 10448 // Subscript can only be overloaded as a member function. 10449 10450 // Add operator candidates that are member functions. 10451 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 10452 10453 // Add builtin operator candidates. 10454 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 10455 10456 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10457 10458 // Perform overload resolution. 10459 OverloadCandidateSet::iterator Best; 10460 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 10461 case OR_Success: { 10462 // We found a built-in operator or an overloaded operator. 10463 FunctionDecl *FnDecl = Best->Function; 10464 10465 if (FnDecl) { 10466 // We matched an overloaded operator. Build a call to that 10467 // operator. 10468 10469 MarkFunctionReferenced(LLoc, FnDecl); 10470 10471 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 10472 DiagnoseUseOfDecl(Best->FoundDecl, LLoc); 10473 10474 // Convert the arguments. 10475 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 10476 ExprResult Arg0 = 10477 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10478 Best->FoundDecl, Method); 10479 if (Arg0.isInvalid()) 10480 return ExprError(); 10481 Args[0] = Arg0.take(); 10482 10483 // Convert the arguments. 10484 ExprResult InputInit 10485 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10486 Context, 10487 FnDecl->getParamDecl(0)), 10488 SourceLocation(), 10489 Owned(Args[1])); 10490 if (InputInit.isInvalid()) 10491 return ExprError(); 10492 10493 Args[1] = InputInit.takeAs<Expr>(); 10494 10495 // Determine the result type 10496 QualType ResultTy = FnDecl->getResultType(); 10497 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10498 ResultTy = ResultTy.getNonLValueExprType(Context); 10499 10500 // Build the actual expression node. 10501 DeclarationNameInfo OpLocInfo(OpName, LLoc); 10502 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10503 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10504 HadMultipleCandidates, 10505 OpLocInfo.getLoc(), 10506 OpLocInfo.getInfo()); 10507 if (FnExpr.isInvalid()) 10508 return ExprError(); 10509 10510 CXXOperatorCallExpr *TheCall = 10511 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 10512 FnExpr.take(), Args, 10513 ResultTy, VK, RLoc, 10514 false); 10515 10516 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall, 10517 FnDecl)) 10518 return ExprError(); 10519 10520 return MaybeBindToTemporary(TheCall); 10521 } else { 10522 // We matched a built-in operator. Convert the arguments, then 10523 // break out so that we will build the appropriate built-in 10524 // operator node. 10525 ExprResult ArgsRes0 = 10526 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10527 Best->Conversions[0], AA_Passing); 10528 if (ArgsRes0.isInvalid()) 10529 return ExprError(); 10530 Args[0] = ArgsRes0.take(); 10531 10532 ExprResult ArgsRes1 = 10533 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10534 Best->Conversions[1], AA_Passing); 10535 if (ArgsRes1.isInvalid()) 10536 return ExprError(); 10537 Args[1] = ArgsRes1.take(); 10538 10539 break; 10540 } 10541 } 10542 10543 case OR_No_Viable_Function: { 10544 if (CandidateSet.empty()) 10545 Diag(LLoc, diag::err_ovl_no_oper) 10546 << Args[0]->getType() << /*subscript*/ 0 10547 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10548 else 10549 Diag(LLoc, diag::err_ovl_no_viable_subscript) 10550 << Args[0]->getType() 10551 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10552 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10553 "[]", LLoc); 10554 return ExprError(); 10555 } 10556 10557 case OR_Ambiguous: 10558 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 10559 << "[]" 10560 << Args[0]->getType() << Args[1]->getType() 10561 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10562 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10563 "[]", LLoc); 10564 return ExprError(); 10565 10566 case OR_Deleted: 10567 Diag(LLoc, diag::err_ovl_deleted_oper) 10568 << Best->Function->isDeleted() << "[]" 10569 << getDeletedOrUnavailableSuffix(Best->Function) 10570 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10571 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10572 "[]", LLoc); 10573 return ExprError(); 10574 } 10575 10576 // We matched a built-in operator; build it. 10577 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 10578 } 10579 10580 /// BuildCallToMemberFunction - Build a call to a member 10581 /// function. MemExpr is the expression that refers to the member 10582 /// function (and includes the object parameter), Args/NumArgs are the 10583 /// arguments to the function call (not including the object 10584 /// parameter). The caller needs to validate that the member 10585 /// expression refers to a non-static member function or an overloaded 10586 /// member function. 10587 ExprResult 10588 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 10589 SourceLocation LParenLoc, Expr **Args, 10590 unsigned NumArgs, SourceLocation RParenLoc) { 10591 assert(MemExprE->getType() == Context.BoundMemberTy || 10592 MemExprE->getType() == Context.OverloadTy); 10593 10594 // Dig out the member expression. This holds both the object 10595 // argument and the member function we're referring to. 10596 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 10597 10598 // Determine whether this is a call to a pointer-to-member function. 10599 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 10600 assert(op->getType() == Context.BoundMemberTy); 10601 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 10602 10603 QualType fnType = 10604 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 10605 10606 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 10607 QualType resultType = proto->getCallResultType(Context); 10608 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType()); 10609 10610 // Check that the object type isn't more qualified than the 10611 // member function we're calling. 10612 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 10613 10614 QualType objectType = op->getLHS()->getType(); 10615 if (op->getOpcode() == BO_PtrMemI) 10616 objectType = objectType->castAs<PointerType>()->getPointeeType(); 10617 Qualifiers objectQuals = objectType.getQualifiers(); 10618 10619 Qualifiers difference = objectQuals - funcQuals; 10620 difference.removeObjCGCAttr(); 10621 difference.removeAddressSpace(); 10622 if (difference) { 10623 std::string qualsString = difference.getAsString(); 10624 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 10625 << fnType.getUnqualifiedType() 10626 << qualsString 10627 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 10628 } 10629 10630 CXXMemberCallExpr *call 10631 = new (Context) CXXMemberCallExpr(Context, MemExprE, 10632 llvm::makeArrayRef(Args, NumArgs), 10633 resultType, valueKind, RParenLoc); 10634 10635 if (CheckCallReturnType(proto->getResultType(), 10636 op->getRHS()->getLocStart(), 10637 call, 0)) 10638 return ExprError(); 10639 10640 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc)) 10641 return ExprError(); 10642 10643 return MaybeBindToTemporary(call); 10644 } 10645 10646 UnbridgedCastsSet UnbridgedCasts; 10647 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 10648 return ExprError(); 10649 10650 MemberExpr *MemExpr; 10651 CXXMethodDecl *Method = 0; 10652 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 10653 NestedNameSpecifier *Qualifier = 0; 10654 if (isa<MemberExpr>(NakedMemExpr)) { 10655 MemExpr = cast<MemberExpr>(NakedMemExpr); 10656 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 10657 FoundDecl = MemExpr->getFoundDecl(); 10658 Qualifier = MemExpr->getQualifier(); 10659 UnbridgedCasts.restore(); 10660 } else { 10661 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 10662 Qualifier = UnresExpr->getQualifier(); 10663 10664 QualType ObjectType = UnresExpr->getBaseType(); 10665 Expr::Classification ObjectClassification 10666 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 10667 : UnresExpr->getBase()->Classify(Context); 10668 10669 // Add overload candidates 10670 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 10671 10672 // FIXME: avoid copy. 10673 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 10674 if (UnresExpr->hasExplicitTemplateArgs()) { 10675 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 10676 TemplateArgs = &TemplateArgsBuffer; 10677 } 10678 10679 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 10680 E = UnresExpr->decls_end(); I != E; ++I) { 10681 10682 NamedDecl *Func = *I; 10683 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 10684 if (isa<UsingShadowDecl>(Func)) 10685 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 10686 10687 10688 // Microsoft supports direct constructor calls. 10689 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 10690 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 10691 llvm::makeArrayRef(Args, NumArgs), CandidateSet); 10692 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 10693 // If explicit template arguments were provided, we can't call a 10694 // non-template member function. 10695 if (TemplateArgs) 10696 continue; 10697 10698 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 10699 ObjectClassification, 10700 llvm::makeArrayRef(Args, NumArgs), CandidateSet, 10701 /*SuppressUserConversions=*/false); 10702 } else { 10703 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 10704 I.getPair(), ActingDC, TemplateArgs, 10705 ObjectType, ObjectClassification, 10706 llvm::makeArrayRef(Args, NumArgs), 10707 CandidateSet, 10708 /*SuppressUsedConversions=*/false); 10709 } 10710 } 10711 10712 DeclarationName DeclName = UnresExpr->getMemberName(); 10713 10714 UnbridgedCasts.restore(); 10715 10716 OverloadCandidateSet::iterator Best; 10717 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 10718 Best)) { 10719 case OR_Success: 10720 Method = cast<CXXMethodDecl>(Best->Function); 10721 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method); 10722 FoundDecl = Best->FoundDecl; 10723 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 10724 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()); 10725 break; 10726 10727 case OR_No_Viable_Function: 10728 Diag(UnresExpr->getMemberLoc(), 10729 diag::err_ovl_no_viable_member_function_in_call) 10730 << DeclName << MemExprE->getSourceRange(); 10731 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10732 llvm::makeArrayRef(Args, NumArgs)); 10733 // FIXME: Leaking incoming expressions! 10734 return ExprError(); 10735 10736 case OR_Ambiguous: 10737 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 10738 << DeclName << MemExprE->getSourceRange(); 10739 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10740 llvm::makeArrayRef(Args, NumArgs)); 10741 // FIXME: Leaking incoming expressions! 10742 return ExprError(); 10743 10744 case OR_Deleted: 10745 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 10746 << Best->Function->isDeleted() 10747 << DeclName 10748 << getDeletedOrUnavailableSuffix(Best->Function) 10749 << MemExprE->getSourceRange(); 10750 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10751 llvm::makeArrayRef(Args, NumArgs)); 10752 // FIXME: Leaking incoming expressions! 10753 return ExprError(); 10754 } 10755 10756 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 10757 10758 // If overload resolution picked a static member, build a 10759 // non-member call based on that function. 10760 if (Method->isStatic()) { 10761 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, 10762 Args, NumArgs, RParenLoc); 10763 } 10764 10765 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 10766 } 10767 10768 QualType ResultType = Method->getResultType(); 10769 ExprValueKind VK = Expr::getValueKindForType(ResultType); 10770 ResultType = ResultType.getNonLValueExprType(Context); 10771 10772 assert(Method && "Member call to something that isn't a method?"); 10773 CXXMemberCallExpr *TheCall = 10774 new (Context) CXXMemberCallExpr(Context, MemExprE, 10775 llvm::makeArrayRef(Args, NumArgs), 10776 ResultType, VK, RParenLoc); 10777 10778 // Check for a valid return type. 10779 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 10780 TheCall, Method)) 10781 return ExprError(); 10782 10783 // Convert the object argument (for a non-static member function call). 10784 // We only need to do this if there was actually an overload; otherwise 10785 // it was done at lookup. 10786 if (!Method->isStatic()) { 10787 ExprResult ObjectArg = 10788 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 10789 FoundDecl, Method); 10790 if (ObjectArg.isInvalid()) 10791 return ExprError(); 10792 MemExpr->setBase(ObjectArg.take()); 10793 } 10794 10795 // Convert the rest of the arguments 10796 const FunctionProtoType *Proto = 10797 Method->getType()->getAs<FunctionProtoType>(); 10798 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs, 10799 RParenLoc)) 10800 return ExprError(); 10801 10802 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs); 10803 10804 if (CheckFunctionCall(Method, TheCall, Proto)) 10805 return ExprError(); 10806 10807 if ((isa<CXXConstructorDecl>(CurContext) || 10808 isa<CXXDestructorDecl>(CurContext)) && 10809 TheCall->getMethodDecl()->isPure()) { 10810 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 10811 10812 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 10813 Diag(MemExpr->getLocStart(), 10814 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 10815 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 10816 << MD->getParent()->getDeclName(); 10817 10818 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 10819 } 10820 } 10821 return MaybeBindToTemporary(TheCall); 10822 } 10823 10824 /// BuildCallToObjectOfClassType - Build a call to an object of class 10825 /// type (C++ [over.call.object]), which can end up invoking an 10826 /// overloaded function call operator (@c operator()) or performing a 10827 /// user-defined conversion on the object argument. 10828 ExprResult 10829 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 10830 SourceLocation LParenLoc, 10831 Expr **Args, unsigned NumArgs, 10832 SourceLocation RParenLoc) { 10833 if (checkPlaceholderForOverload(*this, Obj)) 10834 return ExprError(); 10835 ExprResult Object = Owned(Obj); 10836 10837 UnbridgedCastsSet UnbridgedCasts; 10838 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 10839 return ExprError(); 10840 10841 assert(Object.get()->getType()->isRecordType() && "Requires object type argument"); 10842 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 10843 10844 // C++ [over.call.object]p1: 10845 // If the primary-expression E in the function call syntax 10846 // evaluates to a class object of type "cv T", then the set of 10847 // candidate functions includes at least the function call 10848 // operators of T. The function call operators of T are obtained by 10849 // ordinary lookup of the name operator() in the context of 10850 // (E).operator(). 10851 OverloadCandidateSet CandidateSet(LParenLoc); 10852 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 10853 10854 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 10855 diag::err_incomplete_object_call, Object.get())) 10856 return true; 10857 10858 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 10859 LookupQualifiedName(R, Record->getDecl()); 10860 R.suppressDiagnostics(); 10861 10862 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 10863 Oper != OperEnd; ++Oper) { 10864 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 10865 Object.get()->Classify(Context), Args, NumArgs, CandidateSet, 10866 /*SuppressUserConversions=*/ false); 10867 } 10868 10869 // C++ [over.call.object]p2: 10870 // In addition, for each (non-explicit in C++0x) conversion function 10871 // declared in T of the form 10872 // 10873 // operator conversion-type-id () cv-qualifier; 10874 // 10875 // where cv-qualifier is the same cv-qualification as, or a 10876 // greater cv-qualification than, cv, and where conversion-type-id 10877 // denotes the type "pointer to function of (P1,...,Pn) returning 10878 // R", or the type "reference to pointer to function of 10879 // (P1,...,Pn) returning R", or the type "reference to function 10880 // of (P1,...,Pn) returning R", a surrogate call function [...] 10881 // is also considered as a candidate function. Similarly, 10882 // surrogate call functions are added to the set of candidate 10883 // functions for each conversion function declared in an 10884 // accessible base class provided the function is not hidden 10885 // within T by another intervening declaration. 10886 std::pair<CXXRecordDecl::conversion_iterator, 10887 CXXRecordDecl::conversion_iterator> Conversions 10888 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 10889 for (CXXRecordDecl::conversion_iterator 10890 I = Conversions.first, E = Conversions.second; I != E; ++I) { 10891 NamedDecl *D = *I; 10892 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 10893 if (isa<UsingShadowDecl>(D)) 10894 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 10895 10896 // Skip over templated conversion functions; they aren't 10897 // surrogates. 10898 if (isa<FunctionTemplateDecl>(D)) 10899 continue; 10900 10901 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 10902 if (!Conv->isExplicit()) { 10903 // Strip the reference type (if any) and then the pointer type (if 10904 // any) to get down to what might be a function type. 10905 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 10906 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10907 ConvType = ConvPtrType->getPointeeType(); 10908 10909 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 10910 { 10911 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 10912 Object.get(), llvm::makeArrayRef(Args, NumArgs), 10913 CandidateSet); 10914 } 10915 } 10916 } 10917 10918 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10919 10920 // Perform overload resolution. 10921 OverloadCandidateSet::iterator Best; 10922 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 10923 Best)) { 10924 case OR_Success: 10925 // Overload resolution succeeded; we'll build the appropriate call 10926 // below. 10927 break; 10928 10929 case OR_No_Viable_Function: 10930 if (CandidateSet.empty()) 10931 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 10932 << Object.get()->getType() << /*call*/ 1 10933 << Object.get()->getSourceRange(); 10934 else 10935 Diag(Object.get()->getLocStart(), 10936 diag::err_ovl_no_viable_object_call) 10937 << Object.get()->getType() << Object.get()->getSourceRange(); 10938 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10939 llvm::makeArrayRef(Args, NumArgs)); 10940 break; 10941 10942 case OR_Ambiguous: 10943 Diag(Object.get()->getLocStart(), 10944 diag::err_ovl_ambiguous_object_call) 10945 << Object.get()->getType() << Object.get()->getSourceRange(); 10946 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 10947 llvm::makeArrayRef(Args, NumArgs)); 10948 break; 10949 10950 case OR_Deleted: 10951 Diag(Object.get()->getLocStart(), 10952 diag::err_ovl_deleted_object_call) 10953 << Best->Function->isDeleted() 10954 << Object.get()->getType() 10955 << getDeletedOrUnavailableSuffix(Best->Function) 10956 << Object.get()->getSourceRange(); 10957 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10958 llvm::makeArrayRef(Args, NumArgs)); 10959 break; 10960 } 10961 10962 if (Best == CandidateSet.end()) 10963 return true; 10964 10965 UnbridgedCasts.restore(); 10966 10967 if (Best->Function == 0) { 10968 // Since there is no function declaration, this is one of the 10969 // surrogate candidates. Dig out the conversion function. 10970 CXXConversionDecl *Conv 10971 = cast<CXXConversionDecl>( 10972 Best->Conversions[0].UserDefined.ConversionFunction); 10973 10974 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 10975 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 10976 10977 // We selected one of the surrogate functions that converts the 10978 // object parameter to a function pointer. Perform the conversion 10979 // on the object argument, then let ActOnCallExpr finish the job. 10980 10981 // Create an implicit member expr to refer to the conversion operator. 10982 // and then call it. 10983 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 10984 Conv, HadMultipleCandidates); 10985 if (Call.isInvalid()) 10986 return ExprError(); 10987 // Record usage of conversion in an implicit cast. 10988 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(), 10989 CK_UserDefinedConversion, 10990 Call.get(), 0, VK_RValue)); 10991 10992 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs), 10993 RParenLoc); 10994 } 10995 10996 MarkFunctionReferenced(LParenLoc, Best->Function); 10997 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 10998 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 10999 11000 // We found an overloaded operator(). Build a CXXOperatorCallExpr 11001 // that calls this method, using Object for the implicit object 11002 // parameter and passing along the remaining arguments. 11003 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11004 11005 // An error diagnostic has already been printed when parsing the declaration. 11006 if (Method->isInvalidDecl()) 11007 return ExprError(); 11008 11009 const FunctionProtoType *Proto = 11010 Method->getType()->getAs<FunctionProtoType>(); 11011 11012 unsigned NumArgsInProto = Proto->getNumArgs(); 11013 unsigned NumArgsToCheck = NumArgs; 11014 11015 // Build the full argument list for the method call (the 11016 // implicit object parameter is placed at the beginning of the 11017 // list). 11018 Expr **MethodArgs; 11019 if (NumArgs < NumArgsInProto) { 11020 NumArgsToCheck = NumArgsInProto; 11021 MethodArgs = new Expr*[NumArgsInProto + 1]; 11022 } else { 11023 MethodArgs = new Expr*[NumArgs + 1]; 11024 } 11025 MethodArgs[0] = Object.get(); 11026 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 11027 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 11028 11029 DeclarationNameInfo OpLocInfo( 11030 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 11031 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 11032 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, 11033 HadMultipleCandidates, 11034 OpLocInfo.getLoc(), 11035 OpLocInfo.getInfo()); 11036 if (NewFn.isInvalid()) 11037 return true; 11038 11039 // Once we've built TheCall, all of the expressions are properly 11040 // owned. 11041 QualType ResultTy = Method->getResultType(); 11042 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11043 ResultTy = ResultTy.getNonLValueExprType(Context); 11044 11045 CXXOperatorCallExpr *TheCall = 11046 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(), 11047 llvm::makeArrayRef(MethodArgs, NumArgs+1), 11048 ResultTy, VK, RParenLoc, false); 11049 delete [] MethodArgs; 11050 11051 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall, 11052 Method)) 11053 return true; 11054 11055 // We may have default arguments. If so, we need to allocate more 11056 // slots in the call for them. 11057 if (NumArgs < NumArgsInProto) 11058 TheCall->setNumArgs(Context, NumArgsInProto + 1); 11059 else if (NumArgs > NumArgsInProto) 11060 NumArgsToCheck = NumArgsInProto; 11061 11062 bool IsError = false; 11063 11064 // Initialize the implicit object parameter. 11065 ExprResult ObjRes = 11066 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0, 11067 Best->FoundDecl, Method); 11068 if (ObjRes.isInvalid()) 11069 IsError = true; 11070 else 11071 Object = ObjRes; 11072 TheCall->setArg(0, Object.take()); 11073 11074 // Check the argument types. 11075 for (unsigned i = 0; i != NumArgsToCheck; i++) { 11076 Expr *Arg; 11077 if (i < NumArgs) { 11078 Arg = Args[i]; 11079 11080 // Pass the argument. 11081 11082 ExprResult InputInit 11083 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11084 Context, 11085 Method->getParamDecl(i)), 11086 SourceLocation(), Arg); 11087 11088 IsError |= InputInit.isInvalid(); 11089 Arg = InputInit.takeAs<Expr>(); 11090 } else { 11091 ExprResult DefArg 11092 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 11093 if (DefArg.isInvalid()) { 11094 IsError = true; 11095 break; 11096 } 11097 11098 Arg = DefArg.takeAs<Expr>(); 11099 } 11100 11101 TheCall->setArg(i + 1, Arg); 11102 } 11103 11104 // If this is a variadic call, handle args passed through "...". 11105 if (Proto->isVariadic()) { 11106 // Promote the arguments (C99 6.5.2.2p7). 11107 for (unsigned i = NumArgsInProto; i < NumArgs; i++) { 11108 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); 11109 IsError |= Arg.isInvalid(); 11110 TheCall->setArg(i + 1, Arg.take()); 11111 } 11112 } 11113 11114 if (IsError) return true; 11115 11116 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs); 11117 11118 if (CheckFunctionCall(Method, TheCall, Proto)) 11119 return true; 11120 11121 return MaybeBindToTemporary(TheCall); 11122 } 11123 11124 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 11125 /// (if one exists), where @c Base is an expression of class type and 11126 /// @c Member is the name of the member we're trying to find. 11127 ExprResult 11128 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) { 11129 assert(Base->getType()->isRecordType() && 11130 "left-hand side must have class type"); 11131 11132 if (checkPlaceholderForOverload(*this, Base)) 11133 return ExprError(); 11134 11135 SourceLocation Loc = Base->getExprLoc(); 11136 11137 // C++ [over.ref]p1: 11138 // 11139 // [...] An expression x->m is interpreted as (x.operator->())->m 11140 // for a class object x of type T if T::operator->() exists and if 11141 // the operator is selected as the best match function by the 11142 // overload resolution mechanism (13.3). 11143 DeclarationName OpName = 11144 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 11145 OverloadCandidateSet CandidateSet(Loc); 11146 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 11147 11148 if (RequireCompleteType(Loc, Base->getType(), 11149 diag::err_typecheck_incomplete_tag, Base)) 11150 return ExprError(); 11151 11152 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 11153 LookupQualifiedName(R, BaseRecord->getDecl()); 11154 R.suppressDiagnostics(); 11155 11156 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11157 Oper != OperEnd; ++Oper) { 11158 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 11159 0, 0, CandidateSet, /*SuppressUserConversions=*/false); 11160 } 11161 11162 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11163 11164 // Perform overload resolution. 11165 OverloadCandidateSet::iterator Best; 11166 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11167 case OR_Success: 11168 // Overload resolution succeeded; we'll build the call below. 11169 break; 11170 11171 case OR_No_Viable_Function: 11172 if (CandidateSet.empty()) 11173 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 11174 << Base->getType() << Base->getSourceRange(); 11175 else 11176 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11177 << "operator->" << Base->getSourceRange(); 11178 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11179 return ExprError(); 11180 11181 case OR_Ambiguous: 11182 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11183 << "->" << Base->getType() << Base->getSourceRange(); 11184 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 11185 return ExprError(); 11186 11187 case OR_Deleted: 11188 Diag(OpLoc, diag::err_ovl_deleted_oper) 11189 << Best->Function->isDeleted() 11190 << "->" 11191 << getDeletedOrUnavailableSuffix(Best->Function) 11192 << Base->getSourceRange(); 11193 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11194 return ExprError(); 11195 } 11196 11197 MarkFunctionReferenced(OpLoc, Best->Function); 11198 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 11199 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 11200 11201 // Convert the object parameter. 11202 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11203 ExprResult BaseResult = 11204 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 11205 Best->FoundDecl, Method); 11206 if (BaseResult.isInvalid()) 11207 return ExprError(); 11208 Base = BaseResult.take(); 11209 11210 // Build the operator call. 11211 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, 11212 HadMultipleCandidates, OpLoc); 11213 if (FnExpr.isInvalid()) 11214 return ExprError(); 11215 11216 QualType ResultTy = Method->getResultType(); 11217 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11218 ResultTy = ResultTy.getNonLValueExprType(Context); 11219 CXXOperatorCallExpr *TheCall = 11220 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(), 11221 Base, ResultTy, VK, OpLoc, false); 11222 11223 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall, 11224 Method)) 11225 return ExprError(); 11226 11227 return MaybeBindToTemporary(TheCall); 11228 } 11229 11230 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 11231 /// a literal operator described by the provided lookup results. 11232 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 11233 DeclarationNameInfo &SuffixInfo, 11234 ArrayRef<Expr*> Args, 11235 SourceLocation LitEndLoc, 11236 TemplateArgumentListInfo *TemplateArgs) { 11237 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 11238 11239 OverloadCandidateSet CandidateSet(UDSuffixLoc); 11240 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true, 11241 TemplateArgs); 11242 11243 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11244 11245 // Perform overload resolution. This will usually be trivial, but might need 11246 // to perform substitutions for a literal operator template. 11247 OverloadCandidateSet::iterator Best; 11248 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 11249 case OR_Success: 11250 case OR_Deleted: 11251 break; 11252 11253 case OR_No_Viable_Function: 11254 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 11255 << R.getLookupName(); 11256 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11257 return ExprError(); 11258 11259 case OR_Ambiguous: 11260 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 11261 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11262 return ExprError(); 11263 } 11264 11265 FunctionDecl *FD = Best->Function; 11266 MarkFunctionReferenced(UDSuffixLoc, FD); 11267 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc); 11268 11269 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates, 11270 SuffixInfo.getLoc(), 11271 SuffixInfo.getInfo()); 11272 if (Fn.isInvalid()) 11273 return true; 11274 11275 // Check the argument types. This should almost always be a no-op, except 11276 // that array-to-pointer decay is applied to string literals. 11277 Expr *ConvArgs[2]; 11278 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 11279 ExprResult InputInit = PerformCopyInitialization( 11280 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 11281 SourceLocation(), Args[ArgIdx]); 11282 if (InputInit.isInvalid()) 11283 return true; 11284 ConvArgs[ArgIdx] = InputInit.take(); 11285 } 11286 11287 QualType ResultTy = FD->getResultType(); 11288 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11289 ResultTy = ResultTy.getNonLValueExprType(Context); 11290 11291 UserDefinedLiteral *UDL = 11292 new (Context) UserDefinedLiteral(Context, Fn.take(), 11293 llvm::makeArrayRef(ConvArgs, Args.size()), 11294 ResultTy, VK, LitEndLoc, UDSuffixLoc); 11295 11296 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD)) 11297 return ExprError(); 11298 11299 if (CheckFunctionCall(FD, UDL, NULL)) 11300 return ExprError(); 11301 11302 return MaybeBindToTemporary(UDL); 11303 } 11304 11305 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 11306 /// given LookupResult is non-empty, it is assumed to describe a member which 11307 /// will be invoked. Otherwise, the function will be found via argument 11308 /// dependent lookup. 11309 /// CallExpr is set to a valid expression and FRS_Success returned on success, 11310 /// otherwise CallExpr is set to ExprError() and some non-success value 11311 /// is returned. 11312 Sema::ForRangeStatus 11313 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 11314 SourceLocation RangeLoc, VarDecl *Decl, 11315 BeginEndFunction BEF, 11316 const DeclarationNameInfo &NameInfo, 11317 LookupResult &MemberLookup, 11318 OverloadCandidateSet *CandidateSet, 11319 Expr *Range, ExprResult *CallExpr) { 11320 CandidateSet->clear(); 11321 if (!MemberLookup.empty()) { 11322 ExprResult MemberRef = 11323 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 11324 /*IsPtr=*/false, CXXScopeSpec(), 11325 /*TemplateKWLoc=*/SourceLocation(), 11326 /*FirstQualifierInScope=*/0, 11327 MemberLookup, 11328 /*TemplateArgs=*/0); 11329 if (MemberRef.isInvalid()) { 11330 *CallExpr = ExprError(); 11331 Diag(Range->getLocStart(), diag::note_in_for_range) 11332 << RangeLoc << BEF << Range->getType(); 11333 return FRS_DiagnosticIssued; 11334 } 11335 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0); 11336 if (CallExpr->isInvalid()) { 11337 *CallExpr = ExprError(); 11338 Diag(Range->getLocStart(), diag::note_in_for_range) 11339 << RangeLoc << BEF << Range->getType(); 11340 return FRS_DiagnosticIssued; 11341 } 11342 } else { 11343 UnresolvedSet<0> FoundNames; 11344 UnresolvedLookupExpr *Fn = 11345 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0, 11346 NestedNameSpecifierLoc(), NameInfo, 11347 /*NeedsADL=*/true, /*Overloaded=*/false, 11348 FoundNames.begin(), FoundNames.end()); 11349 11350 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc, 11351 CandidateSet, CallExpr); 11352 if (CandidateSet->empty() || CandidateSetError) { 11353 *CallExpr = ExprError(); 11354 return FRS_NoViableFunction; 11355 } 11356 OverloadCandidateSet::iterator Best; 11357 OverloadingResult OverloadResult = 11358 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 11359 11360 if (OverloadResult == OR_No_Viable_Function) { 11361 *CallExpr = ExprError(); 11362 return FRS_NoViableFunction; 11363 } 11364 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1, 11365 Loc, 0, CandidateSet, &Best, 11366 OverloadResult, 11367 /*AllowTypoCorrection=*/false); 11368 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 11369 *CallExpr = ExprError(); 11370 Diag(Range->getLocStart(), diag::note_in_for_range) 11371 << RangeLoc << BEF << Range->getType(); 11372 return FRS_DiagnosticIssued; 11373 } 11374 } 11375 return FRS_Success; 11376 } 11377 11378 11379 /// FixOverloadedFunctionReference - E is an expression that refers to 11380 /// a C++ overloaded function (possibly with some parentheses and 11381 /// perhaps a '&' around it). We have resolved the overloaded function 11382 /// to the function declaration Fn, so patch up the expression E to 11383 /// refer (possibly indirectly) to Fn. Returns the new expr. 11384 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 11385 FunctionDecl *Fn) { 11386 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 11387 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 11388 Found, Fn); 11389 if (SubExpr == PE->getSubExpr()) 11390 return PE; 11391 11392 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 11393 } 11394 11395 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11396 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 11397 Found, Fn); 11398 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 11399 SubExpr->getType()) && 11400 "Implicit cast type cannot be determined from overload"); 11401 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 11402 if (SubExpr == ICE->getSubExpr()) 11403 return ICE; 11404 11405 return ImplicitCastExpr::Create(Context, ICE->getType(), 11406 ICE->getCastKind(), 11407 SubExpr, 0, 11408 ICE->getValueKind()); 11409 } 11410 11411 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 11412 assert(UnOp->getOpcode() == UO_AddrOf && 11413 "Can only take the address of an overloaded function"); 11414 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11415 if (Method->isStatic()) { 11416 // Do nothing: static member functions aren't any different 11417 // from non-member functions. 11418 } else { 11419 // Fix the sub expression, which really has to be an 11420 // UnresolvedLookupExpr holding an overloaded member function 11421 // or template. 11422 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11423 Found, Fn); 11424 if (SubExpr == UnOp->getSubExpr()) 11425 return UnOp; 11426 11427 assert(isa<DeclRefExpr>(SubExpr) 11428 && "fixed to something other than a decl ref"); 11429 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 11430 && "fixed to a member ref with no nested name qualifier"); 11431 11432 // We have taken the address of a pointer to member 11433 // function. Perform the computation here so that we get the 11434 // appropriate pointer to member type. 11435 QualType ClassType 11436 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 11437 QualType MemPtrType 11438 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 11439 11440 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 11441 VK_RValue, OK_Ordinary, 11442 UnOp->getOperatorLoc()); 11443 } 11444 } 11445 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11446 Found, Fn); 11447 if (SubExpr == UnOp->getSubExpr()) 11448 return UnOp; 11449 11450 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 11451 Context.getPointerType(SubExpr->getType()), 11452 VK_RValue, OK_Ordinary, 11453 UnOp->getOperatorLoc()); 11454 } 11455 11456 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11457 // FIXME: avoid copy. 11458 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11459 if (ULE->hasExplicitTemplateArgs()) { 11460 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 11461 TemplateArgs = &TemplateArgsBuffer; 11462 } 11463 11464 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11465 ULE->getQualifierLoc(), 11466 ULE->getTemplateKeywordLoc(), 11467 Fn, 11468 /*enclosing*/ false, // FIXME? 11469 ULE->getNameLoc(), 11470 Fn->getType(), 11471 VK_LValue, 11472 Found.getDecl(), 11473 TemplateArgs); 11474 MarkDeclRefReferenced(DRE); 11475 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 11476 return DRE; 11477 } 11478 11479 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 11480 // FIXME: avoid copy. 11481 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11482 if (MemExpr->hasExplicitTemplateArgs()) { 11483 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11484 TemplateArgs = &TemplateArgsBuffer; 11485 } 11486 11487 Expr *Base; 11488 11489 // If we're filling in a static method where we used to have an 11490 // implicit member access, rewrite to a simple decl ref. 11491 if (MemExpr->isImplicitAccess()) { 11492 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11493 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11494 MemExpr->getQualifierLoc(), 11495 MemExpr->getTemplateKeywordLoc(), 11496 Fn, 11497 /*enclosing*/ false, 11498 MemExpr->getMemberLoc(), 11499 Fn->getType(), 11500 VK_LValue, 11501 Found.getDecl(), 11502 TemplateArgs); 11503 MarkDeclRefReferenced(DRE); 11504 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 11505 return DRE; 11506 } else { 11507 SourceLocation Loc = MemExpr->getMemberLoc(); 11508 if (MemExpr->getQualifier()) 11509 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 11510 CheckCXXThisCapture(Loc); 11511 Base = new (Context) CXXThisExpr(Loc, 11512 MemExpr->getBaseType(), 11513 /*isImplicit=*/true); 11514 } 11515 } else 11516 Base = MemExpr->getBase(); 11517 11518 ExprValueKind valueKind; 11519 QualType type; 11520 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11521 valueKind = VK_LValue; 11522 type = Fn->getType(); 11523 } else { 11524 valueKind = VK_RValue; 11525 type = Context.BoundMemberTy; 11526 } 11527 11528 MemberExpr *ME = MemberExpr::Create(Context, Base, 11529 MemExpr->isArrow(), 11530 MemExpr->getQualifierLoc(), 11531 MemExpr->getTemplateKeywordLoc(), 11532 Fn, 11533 Found, 11534 MemExpr->getMemberNameInfo(), 11535 TemplateArgs, 11536 type, valueKind, OK_Ordinary); 11537 ME->setHadMultipleCandidates(true); 11538 MarkMemberReferenced(ME); 11539 return ME; 11540 } 11541 11542 llvm_unreachable("Invalid reference to overloaded function"); 11543 } 11544 11545 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 11546 DeclAccessPair Found, 11547 FunctionDecl *Fn) { 11548 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 11549 } 11550 11551 } // end namespace clang 11552