1 //===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file provides Sema routines for C++ overloading. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/SemaInternal.h" 15 #include "clang/Sema/Lookup.h" 16 #include "clang/Sema/Initialization.h" 17 #include "clang/Sema/Template.h" 18 #include "clang/Sema/TemplateDeduction.h" 19 #include "clang/Basic/Diagnostic.h" 20 #include "clang/Lex/Preprocessor.h" 21 #include "clang/AST/ASTContext.h" 22 #include "clang/AST/CXXInheritance.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/ExprObjC.h" 27 #include "clang/AST/TypeOrdering.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "llvm/ADT/DenseSet.h" 30 #include "llvm/ADT/SmallPtrSet.h" 31 #include "llvm/ADT/SmallString.h" 32 #include "llvm/ADT/STLExtras.h" 33 #include <algorithm> 34 35 namespace clang { 36 using namespace sema; 37 38 /// A convenience routine for creating a decayed reference to a 39 /// function. 40 static ExprResult 41 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates, 42 SourceLocation Loc = SourceLocation(), 43 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 44 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 45 VK_LValue, Loc, LocInfo); 46 if (HadMultipleCandidates) 47 DRE->setHadMultipleCandidates(true); 48 ExprResult E = S.Owned(DRE); 49 E = S.DefaultFunctionArrayConversion(E.take()); 50 if (E.isInvalid()) 51 return ExprError(); 52 return E; 53 } 54 55 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 56 bool InOverloadResolution, 57 StandardConversionSequence &SCS, 58 bool CStyle, 59 bool AllowObjCWritebackConversion); 60 61 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 62 QualType &ToType, 63 bool InOverloadResolution, 64 StandardConversionSequence &SCS, 65 bool CStyle); 66 static OverloadingResult 67 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 68 UserDefinedConversionSequence& User, 69 OverloadCandidateSet& Conversions, 70 bool AllowExplicit); 71 72 73 static ImplicitConversionSequence::CompareKind 74 CompareStandardConversionSequences(Sema &S, 75 const StandardConversionSequence& SCS1, 76 const StandardConversionSequence& SCS2); 77 78 static ImplicitConversionSequence::CompareKind 79 CompareQualificationConversions(Sema &S, 80 const StandardConversionSequence& SCS1, 81 const StandardConversionSequence& SCS2); 82 83 static ImplicitConversionSequence::CompareKind 84 CompareDerivedToBaseConversions(Sema &S, 85 const StandardConversionSequence& SCS1, 86 const StandardConversionSequence& SCS2); 87 88 89 90 /// GetConversionCategory - Retrieve the implicit conversion 91 /// category corresponding to the given implicit conversion kind. 92 ImplicitConversionCategory 93 GetConversionCategory(ImplicitConversionKind Kind) { 94 static const ImplicitConversionCategory 95 Category[(int)ICK_Num_Conversion_Kinds] = { 96 ICC_Identity, 97 ICC_Lvalue_Transformation, 98 ICC_Lvalue_Transformation, 99 ICC_Lvalue_Transformation, 100 ICC_Identity, 101 ICC_Qualification_Adjustment, 102 ICC_Promotion, 103 ICC_Promotion, 104 ICC_Promotion, 105 ICC_Conversion, 106 ICC_Conversion, 107 ICC_Conversion, 108 ICC_Conversion, 109 ICC_Conversion, 110 ICC_Conversion, 111 ICC_Conversion, 112 ICC_Conversion, 113 ICC_Conversion, 114 ICC_Conversion, 115 ICC_Conversion, 116 ICC_Conversion, 117 ICC_Conversion 118 }; 119 return Category[(int)Kind]; 120 } 121 122 /// GetConversionRank - Retrieve the implicit conversion rank 123 /// corresponding to the given implicit conversion kind. 124 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 125 static const ImplicitConversionRank 126 Rank[(int)ICK_Num_Conversion_Kinds] = { 127 ICR_Exact_Match, 128 ICR_Exact_Match, 129 ICR_Exact_Match, 130 ICR_Exact_Match, 131 ICR_Exact_Match, 132 ICR_Exact_Match, 133 ICR_Promotion, 134 ICR_Promotion, 135 ICR_Promotion, 136 ICR_Conversion, 137 ICR_Conversion, 138 ICR_Conversion, 139 ICR_Conversion, 140 ICR_Conversion, 141 ICR_Conversion, 142 ICR_Conversion, 143 ICR_Conversion, 144 ICR_Conversion, 145 ICR_Conversion, 146 ICR_Conversion, 147 ICR_Complex_Real_Conversion, 148 ICR_Conversion, 149 ICR_Conversion, 150 ICR_Writeback_Conversion 151 }; 152 return Rank[(int)Kind]; 153 } 154 155 /// GetImplicitConversionName - Return the name of this kind of 156 /// implicit conversion. 157 const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 158 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 159 "No conversion", 160 "Lvalue-to-rvalue", 161 "Array-to-pointer", 162 "Function-to-pointer", 163 "Noreturn adjustment", 164 "Qualification", 165 "Integral promotion", 166 "Floating point promotion", 167 "Complex promotion", 168 "Integral conversion", 169 "Floating conversion", 170 "Complex conversion", 171 "Floating-integral conversion", 172 "Pointer conversion", 173 "Pointer-to-member conversion", 174 "Boolean conversion", 175 "Compatible-types conversion", 176 "Derived-to-base conversion", 177 "Vector conversion", 178 "Vector splat", 179 "Complex-real conversion", 180 "Block Pointer conversion", 181 "Transparent Union Conversion" 182 "Writeback conversion" 183 }; 184 return Name[Kind]; 185 } 186 187 /// StandardConversionSequence - Set the standard conversion 188 /// sequence to the identity conversion. 189 void StandardConversionSequence::setAsIdentityConversion() { 190 First = ICK_Identity; 191 Second = ICK_Identity; 192 Third = ICK_Identity; 193 DeprecatedStringLiteralToCharPtr = false; 194 QualificationIncludesObjCLifetime = false; 195 ReferenceBinding = false; 196 DirectBinding = false; 197 IsLvalueReference = true; 198 BindsToFunctionLvalue = false; 199 BindsToRvalue = false; 200 BindsImplicitObjectArgumentWithoutRefQualifier = false; 201 ObjCLifetimeConversionBinding = false; 202 CopyConstructor = 0; 203 } 204 205 /// getRank - Retrieve the rank of this standard conversion sequence 206 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 207 /// implicit conversions. 208 ImplicitConversionRank StandardConversionSequence::getRank() const { 209 ImplicitConversionRank Rank = ICR_Exact_Match; 210 if (GetConversionRank(First) > Rank) 211 Rank = GetConversionRank(First); 212 if (GetConversionRank(Second) > Rank) 213 Rank = GetConversionRank(Second); 214 if (GetConversionRank(Third) > Rank) 215 Rank = GetConversionRank(Third); 216 return Rank; 217 } 218 219 /// isPointerConversionToBool - Determines whether this conversion is 220 /// a conversion of a pointer or pointer-to-member to bool. This is 221 /// used as part of the ranking of standard conversion sequences 222 /// (C++ 13.3.3.2p4). 223 bool StandardConversionSequence::isPointerConversionToBool() const { 224 // Note that FromType has not necessarily been transformed by the 225 // array-to-pointer or function-to-pointer implicit conversions, so 226 // check for their presence as well as checking whether FromType is 227 // a pointer. 228 if (getToType(1)->isBooleanType() && 229 (getFromType()->isPointerType() || 230 getFromType()->isObjCObjectPointerType() || 231 getFromType()->isBlockPointerType() || 232 getFromType()->isNullPtrType() || 233 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 234 return true; 235 236 return false; 237 } 238 239 /// isPointerConversionToVoidPointer - Determines whether this 240 /// conversion is a conversion of a pointer to a void pointer. This is 241 /// used as part of the ranking of standard conversion sequences (C++ 242 /// 13.3.3.2p4). 243 bool 244 StandardConversionSequence:: 245 isPointerConversionToVoidPointer(ASTContext& Context) const { 246 QualType FromType = getFromType(); 247 QualType ToType = getToType(1); 248 249 // Note that FromType has not necessarily been transformed by the 250 // array-to-pointer implicit conversion, so check for its presence 251 // and redo the conversion to get a pointer. 252 if (First == ICK_Array_To_Pointer) 253 FromType = Context.getArrayDecayedType(FromType); 254 255 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 256 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 257 return ToPtrType->getPointeeType()->isVoidType(); 258 259 return false; 260 } 261 262 /// Skip any implicit casts which could be either part of a narrowing conversion 263 /// or after one in an implicit conversion. 264 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 265 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 266 switch (ICE->getCastKind()) { 267 case CK_NoOp: 268 case CK_IntegralCast: 269 case CK_IntegralToBoolean: 270 case CK_IntegralToFloating: 271 case CK_FloatingToIntegral: 272 case CK_FloatingToBoolean: 273 case CK_FloatingCast: 274 Converted = ICE->getSubExpr(); 275 continue; 276 277 default: 278 return Converted; 279 } 280 } 281 282 return Converted; 283 } 284 285 /// Check if this standard conversion sequence represents a narrowing 286 /// conversion, according to C++11 [dcl.init.list]p7. 287 /// 288 /// \param Ctx The AST context. 289 /// \param Converted The result of applying this standard conversion sequence. 290 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 291 /// value of the expression prior to the narrowing conversion. 292 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 293 /// type of the expression prior to the narrowing conversion. 294 NarrowingKind 295 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 296 const Expr *Converted, 297 APValue &ConstantValue, 298 QualType &ConstantType) const { 299 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 300 301 // C++11 [dcl.init.list]p7: 302 // A narrowing conversion is an implicit conversion ... 303 QualType FromType = getToType(0); 304 QualType ToType = getToType(1); 305 switch (Second) { 306 // -- from a floating-point type to an integer type, or 307 // 308 // -- from an integer type or unscoped enumeration type to a floating-point 309 // type, except where the source is a constant expression and the actual 310 // value after conversion will fit into the target type and will produce 311 // the original value when converted back to the original type, or 312 case ICK_Floating_Integral: 313 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 314 return NK_Type_Narrowing; 315 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 316 llvm::APSInt IntConstantValue; 317 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 318 if (Initializer && 319 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 320 // Convert the integer to the floating type. 321 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 322 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 323 llvm::APFloat::rmNearestTiesToEven); 324 // And back. 325 llvm::APSInt ConvertedValue = IntConstantValue; 326 bool ignored; 327 Result.convertToInteger(ConvertedValue, 328 llvm::APFloat::rmTowardZero, &ignored); 329 // If the resulting value is different, this was a narrowing conversion. 330 if (IntConstantValue != ConvertedValue) { 331 ConstantValue = APValue(IntConstantValue); 332 ConstantType = Initializer->getType(); 333 return NK_Constant_Narrowing; 334 } 335 } else { 336 // Variables are always narrowings. 337 return NK_Variable_Narrowing; 338 } 339 } 340 return NK_Not_Narrowing; 341 342 // -- from long double to double or float, or from double to float, except 343 // where the source is a constant expression and the actual value after 344 // conversion is within the range of values that can be represented (even 345 // if it cannot be represented exactly), or 346 case ICK_Floating_Conversion: 347 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 348 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 349 // FromType is larger than ToType. 350 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 351 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 352 // Constant! 353 assert(ConstantValue.isFloat()); 354 llvm::APFloat FloatVal = ConstantValue.getFloat(); 355 // Convert the source value into the target type. 356 bool ignored; 357 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 358 Ctx.getFloatTypeSemantics(ToType), 359 llvm::APFloat::rmNearestTiesToEven, &ignored); 360 // If there was no overflow, the source value is within the range of 361 // values that can be represented. 362 if (ConvertStatus & llvm::APFloat::opOverflow) { 363 ConstantType = Initializer->getType(); 364 return NK_Constant_Narrowing; 365 } 366 } else { 367 return NK_Variable_Narrowing; 368 } 369 } 370 return NK_Not_Narrowing; 371 372 // -- from an integer type or unscoped enumeration type to an integer type 373 // that cannot represent all the values of the original type, except where 374 // the source is a constant expression and the actual value after 375 // conversion will fit into the target type and will produce the original 376 // value when converted back to the original type. 377 case ICK_Boolean_Conversion: // Bools are integers too. 378 if (!FromType->isIntegralOrUnscopedEnumerationType()) { 379 // Boolean conversions can be from pointers and pointers to members 380 // [conv.bool], and those aren't considered narrowing conversions. 381 return NK_Not_Narrowing; 382 } // Otherwise, fall through to the integral case. 383 case ICK_Integral_Conversion: { 384 assert(FromType->isIntegralOrUnscopedEnumerationType()); 385 assert(ToType->isIntegralOrUnscopedEnumerationType()); 386 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 387 const unsigned FromWidth = Ctx.getIntWidth(FromType); 388 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 389 const unsigned ToWidth = Ctx.getIntWidth(ToType); 390 391 if (FromWidth > ToWidth || 392 (FromWidth == ToWidth && FromSigned != ToSigned) || 393 (FromSigned && !ToSigned)) { 394 // Not all values of FromType can be represented in ToType. 395 llvm::APSInt InitializerValue; 396 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 397 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 398 // Such conversions on variables are always narrowing. 399 return NK_Variable_Narrowing; 400 } 401 bool Narrowing = false; 402 if (FromWidth < ToWidth) { 403 // Negative -> unsigned is narrowing. Otherwise, more bits is never 404 // narrowing. 405 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 406 Narrowing = true; 407 } else { 408 // Add a bit to the InitializerValue so we don't have to worry about 409 // signed vs. unsigned comparisons. 410 InitializerValue = InitializerValue.extend( 411 InitializerValue.getBitWidth() + 1); 412 // Convert the initializer to and from the target width and signed-ness. 413 llvm::APSInt ConvertedValue = InitializerValue; 414 ConvertedValue = ConvertedValue.trunc(ToWidth); 415 ConvertedValue.setIsSigned(ToSigned); 416 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 417 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 418 // If the result is different, this was a narrowing conversion. 419 if (ConvertedValue != InitializerValue) 420 Narrowing = true; 421 } 422 if (Narrowing) { 423 ConstantType = Initializer->getType(); 424 ConstantValue = APValue(InitializerValue); 425 return NK_Constant_Narrowing; 426 } 427 } 428 return NK_Not_Narrowing; 429 } 430 431 default: 432 // Other kinds of conversions are not narrowings. 433 return NK_Not_Narrowing; 434 } 435 } 436 437 /// DebugPrint - Print this standard conversion sequence to standard 438 /// error. Useful for debugging overloading issues. 439 void StandardConversionSequence::DebugPrint() const { 440 raw_ostream &OS = llvm::errs(); 441 bool PrintedSomething = false; 442 if (First != ICK_Identity) { 443 OS << GetImplicitConversionName(First); 444 PrintedSomething = true; 445 } 446 447 if (Second != ICK_Identity) { 448 if (PrintedSomething) { 449 OS << " -> "; 450 } 451 OS << GetImplicitConversionName(Second); 452 453 if (CopyConstructor) { 454 OS << " (by copy constructor)"; 455 } else if (DirectBinding) { 456 OS << " (direct reference binding)"; 457 } else if (ReferenceBinding) { 458 OS << " (reference binding)"; 459 } 460 PrintedSomething = true; 461 } 462 463 if (Third != ICK_Identity) { 464 if (PrintedSomething) { 465 OS << " -> "; 466 } 467 OS << GetImplicitConversionName(Third); 468 PrintedSomething = true; 469 } 470 471 if (!PrintedSomething) { 472 OS << "No conversions required"; 473 } 474 } 475 476 /// DebugPrint - Print this user-defined conversion sequence to standard 477 /// error. Useful for debugging overloading issues. 478 void UserDefinedConversionSequence::DebugPrint() const { 479 raw_ostream &OS = llvm::errs(); 480 if (Before.First || Before.Second || Before.Third) { 481 Before.DebugPrint(); 482 OS << " -> "; 483 } 484 if (ConversionFunction) 485 OS << '\'' << *ConversionFunction << '\''; 486 else 487 OS << "aggregate initialization"; 488 if (After.First || After.Second || After.Third) { 489 OS << " -> "; 490 After.DebugPrint(); 491 } 492 } 493 494 /// DebugPrint - Print this implicit conversion sequence to standard 495 /// error. Useful for debugging overloading issues. 496 void ImplicitConversionSequence::DebugPrint() const { 497 raw_ostream &OS = llvm::errs(); 498 switch (ConversionKind) { 499 case StandardConversion: 500 OS << "Standard conversion: "; 501 Standard.DebugPrint(); 502 break; 503 case UserDefinedConversion: 504 OS << "User-defined conversion: "; 505 UserDefined.DebugPrint(); 506 break; 507 case EllipsisConversion: 508 OS << "Ellipsis conversion"; 509 break; 510 case AmbiguousConversion: 511 OS << "Ambiguous conversion"; 512 break; 513 case BadConversion: 514 OS << "Bad conversion"; 515 break; 516 } 517 518 OS << "\n"; 519 } 520 521 void AmbiguousConversionSequence::construct() { 522 new (&conversions()) ConversionSet(); 523 } 524 525 void AmbiguousConversionSequence::destruct() { 526 conversions().~ConversionSet(); 527 } 528 529 void 530 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 531 FromTypePtr = O.FromTypePtr; 532 ToTypePtr = O.ToTypePtr; 533 new (&conversions()) ConversionSet(O.conversions()); 534 } 535 536 namespace { 537 // Structure used by OverloadCandidate::DeductionFailureInfo to store 538 // template parameter and template argument information. 539 struct DFIParamWithArguments { 540 TemplateParameter Param; 541 TemplateArgument FirstArg; 542 TemplateArgument SecondArg; 543 }; 544 } 545 546 /// \brief Convert from Sema's representation of template deduction information 547 /// to the form used in overload-candidate information. 548 OverloadCandidate::DeductionFailureInfo 549 static MakeDeductionFailureInfo(ASTContext &Context, 550 Sema::TemplateDeductionResult TDK, 551 TemplateDeductionInfo &Info) { 552 OverloadCandidate::DeductionFailureInfo Result; 553 Result.Result = static_cast<unsigned>(TDK); 554 Result.HasDiagnostic = false; 555 Result.Data = 0; 556 switch (TDK) { 557 case Sema::TDK_Success: 558 case Sema::TDK_Invalid: 559 case Sema::TDK_InstantiationDepth: 560 case Sema::TDK_TooManyArguments: 561 case Sema::TDK_TooFewArguments: 562 break; 563 564 case Sema::TDK_Incomplete: 565 case Sema::TDK_InvalidExplicitArguments: 566 Result.Data = Info.Param.getOpaqueValue(); 567 break; 568 569 case Sema::TDK_Inconsistent: 570 case Sema::TDK_Underqualified: { 571 // FIXME: Should allocate from normal heap so that we can free this later. 572 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 573 Saved->Param = Info.Param; 574 Saved->FirstArg = Info.FirstArg; 575 Saved->SecondArg = Info.SecondArg; 576 Result.Data = Saved; 577 break; 578 } 579 580 case Sema::TDK_SubstitutionFailure: 581 Result.Data = Info.take(); 582 if (Info.hasSFINAEDiagnostic()) { 583 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 584 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 585 Info.takeSFINAEDiagnostic(*Diag); 586 Result.HasDiagnostic = true; 587 } 588 break; 589 590 case Sema::TDK_NonDeducedMismatch: 591 case Sema::TDK_FailedOverloadResolution: 592 break; 593 } 594 595 return Result; 596 } 597 598 void OverloadCandidate::DeductionFailureInfo::Destroy() { 599 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 600 case Sema::TDK_Success: 601 case Sema::TDK_Invalid: 602 case Sema::TDK_InstantiationDepth: 603 case Sema::TDK_Incomplete: 604 case Sema::TDK_TooManyArguments: 605 case Sema::TDK_TooFewArguments: 606 case Sema::TDK_InvalidExplicitArguments: 607 break; 608 609 case Sema::TDK_Inconsistent: 610 case Sema::TDK_Underqualified: 611 // FIXME: Destroy the data? 612 Data = 0; 613 break; 614 615 case Sema::TDK_SubstitutionFailure: 616 // FIXME: Destroy the template argument list? 617 Data = 0; 618 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 619 Diag->~PartialDiagnosticAt(); 620 HasDiagnostic = false; 621 } 622 break; 623 624 // Unhandled 625 case Sema::TDK_NonDeducedMismatch: 626 case Sema::TDK_FailedOverloadResolution: 627 break; 628 } 629 } 630 631 PartialDiagnosticAt * 632 OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() { 633 if (HasDiagnostic) 634 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 635 return 0; 636 } 637 638 TemplateParameter 639 OverloadCandidate::DeductionFailureInfo::getTemplateParameter() { 640 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 641 case Sema::TDK_Success: 642 case Sema::TDK_Invalid: 643 case Sema::TDK_InstantiationDepth: 644 case Sema::TDK_TooManyArguments: 645 case Sema::TDK_TooFewArguments: 646 case Sema::TDK_SubstitutionFailure: 647 return TemplateParameter(); 648 649 case Sema::TDK_Incomplete: 650 case Sema::TDK_InvalidExplicitArguments: 651 return TemplateParameter::getFromOpaqueValue(Data); 652 653 case Sema::TDK_Inconsistent: 654 case Sema::TDK_Underqualified: 655 return static_cast<DFIParamWithArguments*>(Data)->Param; 656 657 // Unhandled 658 case Sema::TDK_NonDeducedMismatch: 659 case Sema::TDK_FailedOverloadResolution: 660 break; 661 } 662 663 return TemplateParameter(); 664 } 665 666 TemplateArgumentList * 667 OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() { 668 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 669 case Sema::TDK_Success: 670 case Sema::TDK_Invalid: 671 case Sema::TDK_InstantiationDepth: 672 case Sema::TDK_TooManyArguments: 673 case Sema::TDK_TooFewArguments: 674 case Sema::TDK_Incomplete: 675 case Sema::TDK_InvalidExplicitArguments: 676 case Sema::TDK_Inconsistent: 677 case Sema::TDK_Underqualified: 678 return 0; 679 680 case Sema::TDK_SubstitutionFailure: 681 return static_cast<TemplateArgumentList*>(Data); 682 683 // Unhandled 684 case Sema::TDK_NonDeducedMismatch: 685 case Sema::TDK_FailedOverloadResolution: 686 break; 687 } 688 689 return 0; 690 } 691 692 const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() { 693 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 694 case Sema::TDK_Success: 695 case Sema::TDK_Invalid: 696 case Sema::TDK_InstantiationDepth: 697 case Sema::TDK_Incomplete: 698 case Sema::TDK_TooManyArguments: 699 case Sema::TDK_TooFewArguments: 700 case Sema::TDK_InvalidExplicitArguments: 701 case Sema::TDK_SubstitutionFailure: 702 return 0; 703 704 case Sema::TDK_Inconsistent: 705 case Sema::TDK_Underqualified: 706 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg; 707 708 // Unhandled 709 case Sema::TDK_NonDeducedMismatch: 710 case Sema::TDK_FailedOverloadResolution: 711 break; 712 } 713 714 return 0; 715 } 716 717 const TemplateArgument * 718 OverloadCandidate::DeductionFailureInfo::getSecondArg() { 719 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 720 case Sema::TDK_Success: 721 case Sema::TDK_Invalid: 722 case Sema::TDK_InstantiationDepth: 723 case Sema::TDK_Incomplete: 724 case Sema::TDK_TooManyArguments: 725 case Sema::TDK_TooFewArguments: 726 case Sema::TDK_InvalidExplicitArguments: 727 case Sema::TDK_SubstitutionFailure: 728 return 0; 729 730 case Sema::TDK_Inconsistent: 731 case Sema::TDK_Underqualified: 732 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg; 733 734 // Unhandled 735 case Sema::TDK_NonDeducedMismatch: 736 case Sema::TDK_FailedOverloadResolution: 737 break; 738 } 739 740 return 0; 741 } 742 743 void OverloadCandidateSet::clear() { 744 for (iterator i = begin(), e = end(); i != e; ++i) { 745 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 746 i->Conversions[ii].~ImplicitConversionSequence(); 747 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 748 i->DeductionFailure.Destroy(); 749 } 750 NumInlineSequences = 0; 751 Candidates.clear(); 752 Functions.clear(); 753 } 754 755 namespace { 756 class UnbridgedCastsSet { 757 struct Entry { 758 Expr **Addr; 759 Expr *Saved; 760 }; 761 SmallVector<Entry, 2> Entries; 762 763 public: 764 void save(Sema &S, Expr *&E) { 765 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 766 Entry entry = { &E, E }; 767 Entries.push_back(entry); 768 E = S.stripARCUnbridgedCast(E); 769 } 770 771 void restore() { 772 for (SmallVectorImpl<Entry>::iterator 773 i = Entries.begin(), e = Entries.end(); i != e; ++i) 774 *i->Addr = i->Saved; 775 } 776 }; 777 } 778 779 /// checkPlaceholderForOverload - Do any interesting placeholder-like 780 /// preprocessing on the given expression. 781 /// 782 /// \param unbridgedCasts a collection to which to add unbridged casts; 783 /// without this, they will be immediately diagnosed as errors 784 /// 785 /// Return true on unrecoverable error. 786 static bool checkPlaceholderForOverload(Sema &S, Expr *&E, 787 UnbridgedCastsSet *unbridgedCasts = 0) { 788 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 789 // We can't handle overloaded expressions here because overload 790 // resolution might reasonably tweak them. 791 if (placeholder->getKind() == BuiltinType::Overload) return false; 792 793 // If the context potentially accepts unbridged ARC casts, strip 794 // the unbridged cast and add it to the collection for later restoration. 795 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 796 unbridgedCasts) { 797 unbridgedCasts->save(S, E); 798 return false; 799 } 800 801 // Go ahead and check everything else. 802 ExprResult result = S.CheckPlaceholderExpr(E); 803 if (result.isInvalid()) 804 return true; 805 806 E = result.take(); 807 return false; 808 } 809 810 // Nothing to do. 811 return false; 812 } 813 814 /// checkArgPlaceholdersForOverload - Check a set of call operands for 815 /// placeholders. 816 static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args, 817 unsigned numArgs, 818 UnbridgedCastsSet &unbridged) { 819 for (unsigned i = 0; i != numArgs; ++i) 820 if (checkPlaceholderForOverload(S, args[i], &unbridged)) 821 return true; 822 823 return false; 824 } 825 826 // IsOverload - Determine whether the given New declaration is an 827 // overload of the declarations in Old. This routine returns false if 828 // New and Old cannot be overloaded, e.g., if New has the same 829 // signature as some function in Old (C++ 1.3.10) or if the Old 830 // declarations aren't functions (or function templates) at all. When 831 // it does return false, MatchedDecl will point to the decl that New 832 // cannot be overloaded with. This decl may be a UsingShadowDecl on 833 // top of the underlying declaration. 834 // 835 // Example: Given the following input: 836 // 837 // void f(int, float); // #1 838 // void f(int, int); // #2 839 // int f(int, int); // #3 840 // 841 // When we process #1, there is no previous declaration of "f", 842 // so IsOverload will not be used. 843 // 844 // When we process #2, Old contains only the FunctionDecl for #1. By 845 // comparing the parameter types, we see that #1 and #2 are overloaded 846 // (since they have different signatures), so this routine returns 847 // false; MatchedDecl is unchanged. 848 // 849 // When we process #3, Old is an overload set containing #1 and #2. We 850 // compare the signatures of #3 to #1 (they're overloaded, so we do 851 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 852 // identical (return types of functions are not part of the 853 // signature), IsOverload returns false and MatchedDecl will be set to 854 // point to the FunctionDecl for #2. 855 // 856 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 857 // into a class by a using declaration. The rules for whether to hide 858 // shadow declarations ignore some properties which otherwise figure 859 // into a function template's signature. 860 Sema::OverloadKind 861 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 862 NamedDecl *&Match, bool NewIsUsingDecl) { 863 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 864 I != E; ++I) { 865 NamedDecl *OldD = *I; 866 867 bool OldIsUsingDecl = false; 868 if (isa<UsingShadowDecl>(OldD)) { 869 OldIsUsingDecl = true; 870 871 // We can always introduce two using declarations into the same 872 // context, even if they have identical signatures. 873 if (NewIsUsingDecl) continue; 874 875 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 876 } 877 878 // If either declaration was introduced by a using declaration, 879 // we'll need to use slightly different rules for matching. 880 // Essentially, these rules are the normal rules, except that 881 // function templates hide function templates with different 882 // return types or template parameter lists. 883 bool UseMemberUsingDeclRules = 884 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord(); 885 886 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) { 887 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) { 888 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 889 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 890 continue; 891 } 892 893 Match = *I; 894 return Ovl_Match; 895 } 896 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) { 897 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 898 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 899 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 900 continue; 901 } 902 903 Match = *I; 904 return Ovl_Match; 905 } 906 } else if (isa<UsingDecl>(OldD)) { 907 // We can overload with these, which can show up when doing 908 // redeclaration checks for UsingDecls. 909 assert(Old.getLookupKind() == LookupUsingDeclName); 910 } else if (isa<TagDecl>(OldD)) { 911 // We can always overload with tags by hiding them. 912 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 913 // Optimistically assume that an unresolved using decl will 914 // overload; if it doesn't, we'll have to diagnose during 915 // template instantiation. 916 } else { 917 // (C++ 13p1): 918 // Only function declarations can be overloaded; object and type 919 // declarations cannot be overloaded. 920 Match = *I; 921 return Ovl_NonFunction; 922 } 923 } 924 925 return Ovl_Overload; 926 } 927 928 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 929 bool UseUsingDeclRules) { 930 // If both of the functions are extern "C", then they are not 931 // overloads. 932 if (Old->isExternC() && New->isExternC()) 933 return false; 934 935 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 936 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 937 938 // C++ [temp.fct]p2: 939 // A function template can be overloaded with other function templates 940 // and with normal (non-template) functions. 941 if ((OldTemplate == 0) != (NewTemplate == 0)) 942 return true; 943 944 // Is the function New an overload of the function Old? 945 QualType OldQType = Context.getCanonicalType(Old->getType()); 946 QualType NewQType = Context.getCanonicalType(New->getType()); 947 948 // Compare the signatures (C++ 1.3.10) of the two functions to 949 // determine whether they are overloads. If we find any mismatch 950 // in the signature, they are overloads. 951 952 // If either of these functions is a K&R-style function (no 953 // prototype), then we consider them to have matching signatures. 954 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 955 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 956 return false; 957 958 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType); 959 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType); 960 961 // The signature of a function includes the types of its 962 // parameters (C++ 1.3.10), which includes the presence or absence 963 // of the ellipsis; see C++ DR 357). 964 if (OldQType != NewQType && 965 (OldType->getNumArgs() != NewType->getNumArgs() || 966 OldType->isVariadic() != NewType->isVariadic() || 967 !FunctionArgTypesAreEqual(OldType, NewType))) 968 return true; 969 970 // C++ [temp.over.link]p4: 971 // The signature of a function template consists of its function 972 // signature, its return type and its template parameter list. The names 973 // of the template parameters are significant only for establishing the 974 // relationship between the template parameters and the rest of the 975 // signature. 976 // 977 // We check the return type and template parameter lists for function 978 // templates first; the remaining checks follow. 979 // 980 // However, we don't consider either of these when deciding whether 981 // a member introduced by a shadow declaration is hidden. 982 if (!UseUsingDeclRules && NewTemplate && 983 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 984 OldTemplate->getTemplateParameters(), 985 false, TPL_TemplateMatch) || 986 OldType->getResultType() != NewType->getResultType())) 987 return true; 988 989 // If the function is a class member, its signature includes the 990 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 991 // 992 // As part of this, also check whether one of the member functions 993 // is static, in which case they are not overloads (C++ 994 // 13.1p2). While not part of the definition of the signature, 995 // this check is important to determine whether these functions 996 // can be overloaded. 997 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 998 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 999 if (OldMethod && NewMethod && 1000 !OldMethod->isStatic() && !NewMethod->isStatic() && 1001 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() || 1002 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) { 1003 if (!UseUsingDeclRules && 1004 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() && 1005 (OldMethod->getRefQualifier() == RQ_None || 1006 NewMethod->getRefQualifier() == RQ_None)) { 1007 // C++0x [over.load]p2: 1008 // - Member function declarations with the same name and the same 1009 // parameter-type-list as well as member function template 1010 // declarations with the same name, the same parameter-type-list, and 1011 // the same template parameter lists cannot be overloaded if any of 1012 // them, but not all, have a ref-qualifier (8.3.5). 1013 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1014 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1015 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1016 } 1017 1018 return true; 1019 } 1020 1021 // The signatures match; this is not an overload. 1022 return false; 1023 } 1024 1025 /// \brief Checks availability of the function depending on the current 1026 /// function context. Inside an unavailable function, unavailability is ignored. 1027 /// 1028 /// \returns true if \arg FD is unavailable and current context is inside 1029 /// an available function, false otherwise. 1030 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1031 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1032 } 1033 1034 /// \brief Tries a user-defined conversion from From to ToType. 1035 /// 1036 /// Produces an implicit conversion sequence for when a standard conversion 1037 /// is not an option. See TryImplicitConversion for more information. 1038 static ImplicitConversionSequence 1039 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1040 bool SuppressUserConversions, 1041 bool AllowExplicit, 1042 bool InOverloadResolution, 1043 bool CStyle, 1044 bool AllowObjCWritebackConversion) { 1045 ImplicitConversionSequence ICS; 1046 1047 if (SuppressUserConversions) { 1048 // We're not in the case above, so there is no conversion that 1049 // we can perform. 1050 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1051 return ICS; 1052 } 1053 1054 // Attempt user-defined conversion. 1055 OverloadCandidateSet Conversions(From->getExprLoc()); 1056 OverloadingResult UserDefResult 1057 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 1058 AllowExplicit); 1059 1060 if (UserDefResult == OR_Success) { 1061 ICS.setUserDefined(); 1062 // C++ [over.ics.user]p4: 1063 // A conversion of an expression of class type to the same class 1064 // type is given Exact Match rank, and a conversion of an 1065 // expression of class type to a base class of that type is 1066 // given Conversion rank, in spite of the fact that a copy 1067 // constructor (i.e., a user-defined conversion function) is 1068 // called for those cases. 1069 if (CXXConstructorDecl *Constructor 1070 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1071 QualType FromCanon 1072 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1073 QualType ToCanon 1074 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1075 if (Constructor->isCopyConstructor() && 1076 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1077 // Turn this into a "standard" conversion sequence, so that it 1078 // gets ranked with standard conversion sequences. 1079 ICS.setStandard(); 1080 ICS.Standard.setAsIdentityConversion(); 1081 ICS.Standard.setFromType(From->getType()); 1082 ICS.Standard.setAllToTypes(ToType); 1083 ICS.Standard.CopyConstructor = Constructor; 1084 if (ToCanon != FromCanon) 1085 ICS.Standard.Second = ICK_Derived_To_Base; 1086 } 1087 } 1088 1089 // C++ [over.best.ics]p4: 1090 // However, when considering the argument of a user-defined 1091 // conversion function that is a candidate by 13.3.1.3 when 1092 // invoked for the copying of the temporary in the second step 1093 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 1094 // 13.3.1.6 in all cases, only standard conversion sequences and 1095 // ellipsis conversion sequences are allowed. 1096 if (SuppressUserConversions && ICS.isUserDefined()) { 1097 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 1098 } 1099 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 1100 ICS.setAmbiguous(); 1101 ICS.Ambiguous.setFromType(From->getType()); 1102 ICS.Ambiguous.setToType(ToType); 1103 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1104 Cand != Conversions.end(); ++Cand) 1105 if (Cand->Viable) 1106 ICS.Ambiguous.addConversion(Cand->Function); 1107 } else { 1108 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1109 } 1110 1111 return ICS; 1112 } 1113 1114 /// TryImplicitConversion - Attempt to perform an implicit conversion 1115 /// from the given expression (Expr) to the given type (ToType). This 1116 /// function returns an implicit conversion sequence that can be used 1117 /// to perform the initialization. Given 1118 /// 1119 /// void f(float f); 1120 /// void g(int i) { f(i); } 1121 /// 1122 /// this routine would produce an implicit conversion sequence to 1123 /// describe the initialization of f from i, which will be a standard 1124 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1125 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1126 // 1127 /// Note that this routine only determines how the conversion can be 1128 /// performed; it does not actually perform the conversion. As such, 1129 /// it will not produce any diagnostics if no conversion is available, 1130 /// but will instead return an implicit conversion sequence of kind 1131 /// "BadConversion". 1132 /// 1133 /// If @p SuppressUserConversions, then user-defined conversions are 1134 /// not permitted. 1135 /// If @p AllowExplicit, then explicit user-defined conversions are 1136 /// permitted. 1137 /// 1138 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1139 /// writeback conversion, which allows __autoreleasing id* parameters to 1140 /// be initialized with __strong id* or __weak id* arguments. 1141 static ImplicitConversionSequence 1142 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1143 bool SuppressUserConversions, 1144 bool AllowExplicit, 1145 bool InOverloadResolution, 1146 bool CStyle, 1147 bool AllowObjCWritebackConversion) { 1148 ImplicitConversionSequence ICS; 1149 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1150 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1151 ICS.setStandard(); 1152 return ICS; 1153 } 1154 1155 if (!S.getLangOpts().CPlusPlus) { 1156 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1157 return ICS; 1158 } 1159 1160 // C++ [over.ics.user]p4: 1161 // A conversion of an expression of class type to the same class 1162 // type is given Exact Match rank, and a conversion of an 1163 // expression of class type to a base class of that type is 1164 // given Conversion rank, in spite of the fact that a copy/move 1165 // constructor (i.e., a user-defined conversion function) is 1166 // called for those cases. 1167 QualType FromType = From->getType(); 1168 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1169 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1170 S.IsDerivedFrom(FromType, ToType))) { 1171 ICS.setStandard(); 1172 ICS.Standard.setAsIdentityConversion(); 1173 ICS.Standard.setFromType(FromType); 1174 ICS.Standard.setAllToTypes(ToType); 1175 1176 // We don't actually check at this point whether there is a valid 1177 // copy/move constructor, since overloading just assumes that it 1178 // exists. When we actually perform initialization, we'll find the 1179 // appropriate constructor to copy the returned object, if needed. 1180 ICS.Standard.CopyConstructor = 0; 1181 1182 // Determine whether this is considered a derived-to-base conversion. 1183 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1184 ICS.Standard.Second = ICK_Derived_To_Base; 1185 1186 return ICS; 1187 } 1188 1189 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1190 AllowExplicit, InOverloadResolution, CStyle, 1191 AllowObjCWritebackConversion); 1192 } 1193 1194 ImplicitConversionSequence 1195 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1196 bool SuppressUserConversions, 1197 bool AllowExplicit, 1198 bool InOverloadResolution, 1199 bool CStyle, 1200 bool AllowObjCWritebackConversion) { 1201 return clang::TryImplicitConversion(*this, From, ToType, 1202 SuppressUserConversions, AllowExplicit, 1203 InOverloadResolution, CStyle, 1204 AllowObjCWritebackConversion); 1205 } 1206 1207 /// PerformImplicitConversion - Perform an implicit conversion of the 1208 /// expression From to the type ToType. Returns the 1209 /// converted expression. Flavor is the kind of conversion we're 1210 /// performing, used in the error message. If @p AllowExplicit, 1211 /// explicit user-defined conversions are permitted. 1212 ExprResult 1213 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1214 AssignmentAction Action, bool AllowExplicit) { 1215 ImplicitConversionSequence ICS; 1216 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1217 } 1218 1219 ExprResult 1220 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1221 AssignmentAction Action, bool AllowExplicit, 1222 ImplicitConversionSequence& ICS) { 1223 if (checkPlaceholderForOverload(*this, From)) 1224 return ExprError(); 1225 1226 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1227 bool AllowObjCWritebackConversion 1228 = getLangOpts().ObjCAutoRefCount && 1229 (Action == AA_Passing || Action == AA_Sending); 1230 1231 ICS = clang::TryImplicitConversion(*this, From, ToType, 1232 /*SuppressUserConversions=*/false, 1233 AllowExplicit, 1234 /*InOverloadResolution=*/false, 1235 /*CStyle=*/false, 1236 AllowObjCWritebackConversion); 1237 return PerformImplicitConversion(From, ToType, ICS, Action); 1238 } 1239 1240 /// \brief Determine whether the conversion from FromType to ToType is a valid 1241 /// conversion that strips "noreturn" off the nested function type. 1242 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1243 QualType &ResultTy) { 1244 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1245 return false; 1246 1247 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1248 // where F adds one of the following at most once: 1249 // - a pointer 1250 // - a member pointer 1251 // - a block pointer 1252 CanQualType CanTo = Context.getCanonicalType(ToType); 1253 CanQualType CanFrom = Context.getCanonicalType(FromType); 1254 Type::TypeClass TyClass = CanTo->getTypeClass(); 1255 if (TyClass != CanFrom->getTypeClass()) return false; 1256 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1257 if (TyClass == Type::Pointer) { 1258 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1259 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1260 } else if (TyClass == Type::BlockPointer) { 1261 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1262 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1263 } else if (TyClass == Type::MemberPointer) { 1264 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1265 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1266 } else { 1267 return false; 1268 } 1269 1270 TyClass = CanTo->getTypeClass(); 1271 if (TyClass != CanFrom->getTypeClass()) return false; 1272 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1273 return false; 1274 } 1275 1276 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1277 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1278 if (!EInfo.getNoReturn()) return false; 1279 1280 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1281 assert(QualType(FromFn, 0).isCanonical()); 1282 if (QualType(FromFn, 0) != CanTo) return false; 1283 1284 ResultTy = ToType; 1285 return true; 1286 } 1287 1288 /// \brief Determine whether the conversion from FromType to ToType is a valid 1289 /// vector conversion. 1290 /// 1291 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1292 /// conversion. 1293 static bool IsVectorConversion(ASTContext &Context, QualType FromType, 1294 QualType ToType, ImplicitConversionKind &ICK) { 1295 // We need at least one of these types to be a vector type to have a vector 1296 // conversion. 1297 if (!ToType->isVectorType() && !FromType->isVectorType()) 1298 return false; 1299 1300 // Identical types require no conversions. 1301 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1302 return false; 1303 1304 // There are no conversions between extended vector types, only identity. 1305 if (ToType->isExtVectorType()) { 1306 // There are no conversions between extended vector types other than the 1307 // identity conversion. 1308 if (FromType->isExtVectorType()) 1309 return false; 1310 1311 // Vector splat from any arithmetic type to a vector. 1312 if (FromType->isArithmeticType()) { 1313 ICK = ICK_Vector_Splat; 1314 return true; 1315 } 1316 } 1317 1318 // We can perform the conversion between vector types in the following cases: 1319 // 1)vector types are equivalent AltiVec and GCC vector types 1320 // 2)lax vector conversions are permitted and the vector types are of the 1321 // same size 1322 if (ToType->isVectorType() && FromType->isVectorType()) { 1323 if (Context.areCompatibleVectorTypes(FromType, ToType) || 1324 (Context.getLangOpts().LaxVectorConversions && 1325 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) { 1326 ICK = ICK_Vector_Conversion; 1327 return true; 1328 } 1329 } 1330 1331 return false; 1332 } 1333 1334 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1335 bool InOverloadResolution, 1336 StandardConversionSequence &SCS, 1337 bool CStyle); 1338 1339 /// IsStandardConversion - Determines whether there is a standard 1340 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1341 /// expression From to the type ToType. Standard conversion sequences 1342 /// only consider non-class types; for conversions that involve class 1343 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1344 /// contain the standard conversion sequence required to perform this 1345 /// conversion and this routine will return true. Otherwise, this 1346 /// routine will return false and the value of SCS is unspecified. 1347 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1348 bool InOverloadResolution, 1349 StandardConversionSequence &SCS, 1350 bool CStyle, 1351 bool AllowObjCWritebackConversion) { 1352 QualType FromType = From->getType(); 1353 1354 // Standard conversions (C++ [conv]) 1355 SCS.setAsIdentityConversion(); 1356 SCS.DeprecatedStringLiteralToCharPtr = false; 1357 SCS.IncompatibleObjC = false; 1358 SCS.setFromType(FromType); 1359 SCS.CopyConstructor = 0; 1360 1361 // There are no standard conversions for class types in C++, so 1362 // abort early. When overloading in C, however, we do permit 1363 if (FromType->isRecordType() || ToType->isRecordType()) { 1364 if (S.getLangOpts().CPlusPlus) 1365 return false; 1366 1367 // When we're overloading in C, we allow, as standard conversions, 1368 } 1369 1370 // The first conversion can be an lvalue-to-rvalue conversion, 1371 // array-to-pointer conversion, or function-to-pointer conversion 1372 // (C++ 4p1). 1373 1374 if (FromType == S.Context.OverloadTy) { 1375 DeclAccessPair AccessPair; 1376 if (FunctionDecl *Fn 1377 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1378 AccessPair)) { 1379 // We were able to resolve the address of the overloaded function, 1380 // so we can convert to the type of that function. 1381 FromType = Fn->getType(); 1382 1383 // we can sometimes resolve &foo<int> regardless of ToType, so check 1384 // if the type matches (identity) or we are converting to bool 1385 if (!S.Context.hasSameUnqualifiedType( 1386 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1387 QualType resultTy; 1388 // if the function type matches except for [[noreturn]], it's ok 1389 if (!S.IsNoReturnConversion(FromType, 1390 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1391 // otherwise, only a boolean conversion is standard 1392 if (!ToType->isBooleanType()) 1393 return false; 1394 } 1395 1396 // Check if the "from" expression is taking the address of an overloaded 1397 // function and recompute the FromType accordingly. Take advantage of the 1398 // fact that non-static member functions *must* have such an address-of 1399 // expression. 1400 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1401 if (Method && !Method->isStatic()) { 1402 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1403 "Non-unary operator on non-static member address"); 1404 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1405 == UO_AddrOf && 1406 "Non-address-of operator on non-static member address"); 1407 const Type *ClassType 1408 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1409 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1410 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1411 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1412 UO_AddrOf && 1413 "Non-address-of operator for overloaded function expression"); 1414 FromType = S.Context.getPointerType(FromType); 1415 } 1416 1417 // Check that we've computed the proper type after overload resolution. 1418 assert(S.Context.hasSameType( 1419 FromType, 1420 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1421 } else { 1422 return false; 1423 } 1424 } 1425 // Lvalue-to-rvalue conversion (C++11 4.1): 1426 // A glvalue (3.10) of a non-function, non-array type T can 1427 // be converted to a prvalue. 1428 bool argIsLValue = From->isGLValue(); 1429 if (argIsLValue && 1430 !FromType->isFunctionType() && !FromType->isArrayType() && 1431 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1432 SCS.First = ICK_Lvalue_To_Rvalue; 1433 1434 // C11 6.3.2.1p2: 1435 // ... if the lvalue has atomic type, the value has the non-atomic version 1436 // of the type of the lvalue ... 1437 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1438 FromType = Atomic->getValueType(); 1439 1440 // If T is a non-class type, the type of the rvalue is the 1441 // cv-unqualified version of T. Otherwise, the type of the rvalue 1442 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1443 // just strip the qualifiers because they don't matter. 1444 FromType = FromType.getUnqualifiedType(); 1445 } else if (FromType->isArrayType()) { 1446 // Array-to-pointer conversion (C++ 4.2) 1447 SCS.First = ICK_Array_To_Pointer; 1448 1449 // An lvalue or rvalue of type "array of N T" or "array of unknown 1450 // bound of T" can be converted to an rvalue of type "pointer to 1451 // T" (C++ 4.2p1). 1452 FromType = S.Context.getArrayDecayedType(FromType); 1453 1454 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1455 // This conversion is deprecated. (C++ D.4). 1456 SCS.DeprecatedStringLiteralToCharPtr = true; 1457 1458 // For the purpose of ranking in overload resolution 1459 // (13.3.3.1.1), this conversion is considered an 1460 // array-to-pointer conversion followed by a qualification 1461 // conversion (4.4). (C++ 4.2p2) 1462 SCS.Second = ICK_Identity; 1463 SCS.Third = ICK_Qualification; 1464 SCS.QualificationIncludesObjCLifetime = false; 1465 SCS.setAllToTypes(FromType); 1466 return true; 1467 } 1468 } else if (FromType->isFunctionType() && argIsLValue) { 1469 // Function-to-pointer conversion (C++ 4.3). 1470 SCS.First = ICK_Function_To_Pointer; 1471 1472 // An lvalue of function type T can be converted to an rvalue of 1473 // type "pointer to T." The result is a pointer to the 1474 // function. (C++ 4.3p1). 1475 FromType = S.Context.getPointerType(FromType); 1476 } else { 1477 // We don't require any conversions for the first step. 1478 SCS.First = ICK_Identity; 1479 } 1480 SCS.setToType(0, FromType); 1481 1482 // The second conversion can be an integral promotion, floating 1483 // point promotion, integral conversion, floating point conversion, 1484 // floating-integral conversion, pointer conversion, 1485 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1486 // For overloading in C, this can also be a "compatible-type" 1487 // conversion. 1488 bool IncompatibleObjC = false; 1489 ImplicitConversionKind SecondICK = ICK_Identity; 1490 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1491 // The unqualified versions of the types are the same: there's no 1492 // conversion to do. 1493 SCS.Second = ICK_Identity; 1494 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1495 // Integral promotion (C++ 4.5). 1496 SCS.Second = ICK_Integral_Promotion; 1497 FromType = ToType.getUnqualifiedType(); 1498 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1499 // Floating point promotion (C++ 4.6). 1500 SCS.Second = ICK_Floating_Promotion; 1501 FromType = ToType.getUnqualifiedType(); 1502 } else if (S.IsComplexPromotion(FromType, ToType)) { 1503 // Complex promotion (Clang extension) 1504 SCS.Second = ICK_Complex_Promotion; 1505 FromType = ToType.getUnqualifiedType(); 1506 } else if (ToType->isBooleanType() && 1507 (FromType->isArithmeticType() || 1508 FromType->isAnyPointerType() || 1509 FromType->isBlockPointerType() || 1510 FromType->isMemberPointerType() || 1511 FromType->isNullPtrType())) { 1512 // Boolean conversions (C++ 4.12). 1513 SCS.Second = ICK_Boolean_Conversion; 1514 FromType = S.Context.BoolTy; 1515 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1516 ToType->isIntegralType(S.Context)) { 1517 // Integral conversions (C++ 4.7). 1518 SCS.Second = ICK_Integral_Conversion; 1519 FromType = ToType.getUnqualifiedType(); 1520 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) { 1521 // Complex conversions (C99 6.3.1.6) 1522 SCS.Second = ICK_Complex_Conversion; 1523 FromType = ToType.getUnqualifiedType(); 1524 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1525 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1526 // Complex-real conversions (C99 6.3.1.7) 1527 SCS.Second = ICK_Complex_Real; 1528 FromType = ToType.getUnqualifiedType(); 1529 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1530 // Floating point conversions (C++ 4.8). 1531 SCS.Second = ICK_Floating_Conversion; 1532 FromType = ToType.getUnqualifiedType(); 1533 } else if ((FromType->isRealFloatingType() && 1534 ToType->isIntegralType(S.Context)) || 1535 (FromType->isIntegralOrUnscopedEnumerationType() && 1536 ToType->isRealFloatingType())) { 1537 // Floating-integral conversions (C++ 4.9). 1538 SCS.Second = ICK_Floating_Integral; 1539 FromType = ToType.getUnqualifiedType(); 1540 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1541 SCS.Second = ICK_Block_Pointer_Conversion; 1542 } else if (AllowObjCWritebackConversion && 1543 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1544 SCS.Second = ICK_Writeback_Conversion; 1545 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1546 FromType, IncompatibleObjC)) { 1547 // Pointer conversions (C++ 4.10). 1548 SCS.Second = ICK_Pointer_Conversion; 1549 SCS.IncompatibleObjC = IncompatibleObjC; 1550 FromType = FromType.getUnqualifiedType(); 1551 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1552 InOverloadResolution, FromType)) { 1553 // Pointer to member conversions (4.11). 1554 SCS.Second = ICK_Pointer_Member; 1555 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) { 1556 SCS.Second = SecondICK; 1557 FromType = ToType.getUnqualifiedType(); 1558 } else if (!S.getLangOpts().CPlusPlus && 1559 S.Context.typesAreCompatible(ToType, FromType)) { 1560 // Compatible conversions (Clang extension for C function overloading) 1561 SCS.Second = ICK_Compatible_Conversion; 1562 FromType = ToType.getUnqualifiedType(); 1563 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1564 // Treat a conversion that strips "noreturn" as an identity conversion. 1565 SCS.Second = ICK_NoReturn_Adjustment; 1566 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1567 InOverloadResolution, 1568 SCS, CStyle)) { 1569 SCS.Second = ICK_TransparentUnionConversion; 1570 FromType = ToType; 1571 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1572 CStyle)) { 1573 // tryAtomicConversion has updated the standard conversion sequence 1574 // appropriately. 1575 return true; 1576 } else { 1577 // No second conversion required. 1578 SCS.Second = ICK_Identity; 1579 } 1580 SCS.setToType(1, FromType); 1581 1582 QualType CanonFrom; 1583 QualType CanonTo; 1584 // The third conversion can be a qualification conversion (C++ 4p1). 1585 bool ObjCLifetimeConversion; 1586 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1587 ObjCLifetimeConversion)) { 1588 SCS.Third = ICK_Qualification; 1589 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1590 FromType = ToType; 1591 CanonFrom = S.Context.getCanonicalType(FromType); 1592 CanonTo = S.Context.getCanonicalType(ToType); 1593 } else { 1594 // No conversion required 1595 SCS.Third = ICK_Identity; 1596 1597 // C++ [over.best.ics]p6: 1598 // [...] Any difference in top-level cv-qualification is 1599 // subsumed by the initialization itself and does not constitute 1600 // a conversion. [...] 1601 CanonFrom = S.Context.getCanonicalType(FromType); 1602 CanonTo = S.Context.getCanonicalType(ToType); 1603 if (CanonFrom.getLocalUnqualifiedType() 1604 == CanonTo.getLocalUnqualifiedType() && 1605 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers() 1606 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr() 1607 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) { 1608 FromType = ToType; 1609 CanonFrom = CanonTo; 1610 } 1611 } 1612 SCS.setToType(2, FromType); 1613 1614 // If we have not converted the argument type to the parameter type, 1615 // this is a bad conversion sequence. 1616 if (CanonFrom != CanonTo) 1617 return false; 1618 1619 return true; 1620 } 1621 1622 static bool 1623 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1624 QualType &ToType, 1625 bool InOverloadResolution, 1626 StandardConversionSequence &SCS, 1627 bool CStyle) { 1628 1629 const RecordType *UT = ToType->getAsUnionType(); 1630 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1631 return false; 1632 // The field to initialize within the transparent union. 1633 RecordDecl *UD = UT->getDecl(); 1634 // It's compatible if the expression matches any of the fields. 1635 for (RecordDecl::field_iterator it = UD->field_begin(), 1636 itend = UD->field_end(); 1637 it != itend; ++it) { 1638 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1639 CStyle, /*ObjCWritebackConversion=*/false)) { 1640 ToType = it->getType(); 1641 return true; 1642 } 1643 } 1644 return false; 1645 } 1646 1647 /// IsIntegralPromotion - Determines whether the conversion from the 1648 /// expression From (whose potentially-adjusted type is FromType) to 1649 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1650 /// sets PromotedType to the promoted type. 1651 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1652 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1653 // All integers are built-in. 1654 if (!To) { 1655 return false; 1656 } 1657 1658 // An rvalue of type char, signed char, unsigned char, short int, or 1659 // unsigned short int can be converted to an rvalue of type int if 1660 // int can represent all the values of the source type; otherwise, 1661 // the source rvalue can be converted to an rvalue of type unsigned 1662 // int (C++ 4.5p1). 1663 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1664 !FromType->isEnumeralType()) { 1665 if (// We can promote any signed, promotable integer type to an int 1666 (FromType->isSignedIntegerType() || 1667 // We can promote any unsigned integer type whose size is 1668 // less than int to an int. 1669 (!FromType->isSignedIntegerType() && 1670 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1671 return To->getKind() == BuiltinType::Int; 1672 } 1673 1674 return To->getKind() == BuiltinType::UInt; 1675 } 1676 1677 // C++11 [conv.prom]p3: 1678 // A prvalue of an unscoped enumeration type whose underlying type is not 1679 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1680 // following types that can represent all the values of the enumeration 1681 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1682 // unsigned int, long int, unsigned long int, long long int, or unsigned 1683 // long long int. If none of the types in that list can represent all the 1684 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1685 // type can be converted to an rvalue a prvalue of the extended integer type 1686 // with lowest integer conversion rank (4.13) greater than the rank of long 1687 // long in which all the values of the enumeration can be represented. If 1688 // there are two such extended types, the signed one is chosen. 1689 // C++11 [conv.prom]p4: 1690 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1691 // can be converted to a prvalue of its underlying type. Moreover, if 1692 // integral promotion can be applied to its underlying type, a prvalue of an 1693 // unscoped enumeration type whose underlying type is fixed can also be 1694 // converted to a prvalue of the promoted underlying type. 1695 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1696 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1697 // provided for a scoped enumeration. 1698 if (FromEnumType->getDecl()->isScoped()) 1699 return false; 1700 1701 // We can perform an integral promotion to the underlying type of the enum, 1702 // even if that's not the promoted type. 1703 if (FromEnumType->getDecl()->isFixed()) { 1704 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1705 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1706 IsIntegralPromotion(From, Underlying, ToType); 1707 } 1708 1709 // We have already pre-calculated the promotion type, so this is trivial. 1710 if (ToType->isIntegerType() && 1711 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1712 return Context.hasSameUnqualifiedType(ToType, 1713 FromEnumType->getDecl()->getPromotionType()); 1714 } 1715 1716 // C++0x [conv.prom]p2: 1717 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1718 // to an rvalue a prvalue of the first of the following types that can 1719 // represent all the values of its underlying type: int, unsigned int, 1720 // long int, unsigned long int, long long int, or unsigned long long int. 1721 // If none of the types in that list can represent all the values of its 1722 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1723 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1724 // type. 1725 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1726 ToType->isIntegerType()) { 1727 // Determine whether the type we're converting from is signed or 1728 // unsigned. 1729 bool FromIsSigned = FromType->isSignedIntegerType(); 1730 uint64_t FromSize = Context.getTypeSize(FromType); 1731 1732 // The types we'll try to promote to, in the appropriate 1733 // order. Try each of these types. 1734 QualType PromoteTypes[6] = { 1735 Context.IntTy, Context.UnsignedIntTy, 1736 Context.LongTy, Context.UnsignedLongTy , 1737 Context.LongLongTy, Context.UnsignedLongLongTy 1738 }; 1739 for (int Idx = 0; Idx < 6; ++Idx) { 1740 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1741 if (FromSize < ToSize || 1742 (FromSize == ToSize && 1743 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1744 // We found the type that we can promote to. If this is the 1745 // type we wanted, we have a promotion. Otherwise, no 1746 // promotion. 1747 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1748 } 1749 } 1750 } 1751 1752 // An rvalue for an integral bit-field (9.6) can be converted to an 1753 // rvalue of type int if int can represent all the values of the 1754 // bit-field; otherwise, it can be converted to unsigned int if 1755 // unsigned int can represent all the values of the bit-field. If 1756 // the bit-field is larger yet, no integral promotion applies to 1757 // it. If the bit-field has an enumerated type, it is treated as any 1758 // other value of that type for promotion purposes (C++ 4.5p3). 1759 // FIXME: We should delay checking of bit-fields until we actually perform the 1760 // conversion. 1761 using llvm::APSInt; 1762 if (From) 1763 if (FieldDecl *MemberDecl = From->getBitField()) { 1764 APSInt BitWidth; 1765 if (FromType->isIntegralType(Context) && 1766 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1767 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1768 ToSize = Context.getTypeSize(ToType); 1769 1770 // Are we promoting to an int from a bitfield that fits in an int? 1771 if (BitWidth < ToSize || 1772 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1773 return To->getKind() == BuiltinType::Int; 1774 } 1775 1776 // Are we promoting to an unsigned int from an unsigned bitfield 1777 // that fits into an unsigned int? 1778 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1779 return To->getKind() == BuiltinType::UInt; 1780 } 1781 1782 return false; 1783 } 1784 } 1785 1786 // An rvalue of type bool can be converted to an rvalue of type int, 1787 // with false becoming zero and true becoming one (C++ 4.5p4). 1788 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1789 return true; 1790 } 1791 1792 return false; 1793 } 1794 1795 /// IsFloatingPointPromotion - Determines whether the conversion from 1796 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1797 /// returns true and sets PromotedType to the promoted type. 1798 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1799 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1800 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1801 /// An rvalue of type float can be converted to an rvalue of type 1802 /// double. (C++ 4.6p1). 1803 if (FromBuiltin->getKind() == BuiltinType::Float && 1804 ToBuiltin->getKind() == BuiltinType::Double) 1805 return true; 1806 1807 // C99 6.3.1.5p1: 1808 // When a float is promoted to double or long double, or a 1809 // double is promoted to long double [...]. 1810 if (!getLangOpts().CPlusPlus && 1811 (FromBuiltin->getKind() == BuiltinType::Float || 1812 FromBuiltin->getKind() == BuiltinType::Double) && 1813 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1814 return true; 1815 1816 // Half can be promoted to float. 1817 if (FromBuiltin->getKind() == BuiltinType::Half && 1818 ToBuiltin->getKind() == BuiltinType::Float) 1819 return true; 1820 } 1821 1822 return false; 1823 } 1824 1825 /// \brief Determine if a conversion is a complex promotion. 1826 /// 1827 /// A complex promotion is defined as a complex -> complex conversion 1828 /// where the conversion between the underlying real types is a 1829 /// floating-point or integral promotion. 1830 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1831 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1832 if (!FromComplex) 1833 return false; 1834 1835 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1836 if (!ToComplex) 1837 return false; 1838 1839 return IsFloatingPointPromotion(FromComplex->getElementType(), 1840 ToComplex->getElementType()) || 1841 IsIntegralPromotion(0, FromComplex->getElementType(), 1842 ToComplex->getElementType()); 1843 } 1844 1845 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1846 /// the pointer type FromPtr to a pointer to type ToPointee, with the 1847 /// same type qualifiers as FromPtr has on its pointee type. ToType, 1848 /// if non-empty, will be a pointer to ToType that may or may not have 1849 /// the right set of qualifiers on its pointee. 1850 /// 1851 static QualType 1852 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1853 QualType ToPointee, QualType ToType, 1854 ASTContext &Context, 1855 bool StripObjCLifetime = false) { 1856 assert((FromPtr->getTypeClass() == Type::Pointer || 1857 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1858 "Invalid similarly-qualified pointer type"); 1859 1860 /// Conversions to 'id' subsume cv-qualifier conversions. 1861 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1862 return ToType.getUnqualifiedType(); 1863 1864 QualType CanonFromPointee 1865 = Context.getCanonicalType(FromPtr->getPointeeType()); 1866 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1867 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1868 1869 if (StripObjCLifetime) 1870 Quals.removeObjCLifetime(); 1871 1872 // Exact qualifier match -> return the pointer type we're converting to. 1873 if (CanonToPointee.getLocalQualifiers() == Quals) { 1874 // ToType is exactly what we need. Return it. 1875 if (!ToType.isNull()) 1876 return ToType.getUnqualifiedType(); 1877 1878 // Build a pointer to ToPointee. It has the right qualifiers 1879 // already. 1880 if (isa<ObjCObjectPointerType>(ToType)) 1881 return Context.getObjCObjectPointerType(ToPointee); 1882 return Context.getPointerType(ToPointee); 1883 } 1884 1885 // Just build a canonical type that has the right qualifiers. 1886 QualType QualifiedCanonToPointee 1887 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1888 1889 if (isa<ObjCObjectPointerType>(ToType)) 1890 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1891 return Context.getPointerType(QualifiedCanonToPointee); 1892 } 1893 1894 static bool isNullPointerConstantForConversion(Expr *Expr, 1895 bool InOverloadResolution, 1896 ASTContext &Context) { 1897 // Handle value-dependent integral null pointer constants correctly. 1898 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1899 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1900 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1901 return !InOverloadResolution; 1902 1903 return Expr->isNullPointerConstant(Context, 1904 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1905 : Expr::NPC_ValueDependentIsNull); 1906 } 1907 1908 /// IsPointerConversion - Determines whether the conversion of the 1909 /// expression From, which has the (possibly adjusted) type FromType, 1910 /// can be converted to the type ToType via a pointer conversion (C++ 1911 /// 4.10). If so, returns true and places the converted type (that 1912 /// might differ from ToType in its cv-qualifiers at some level) into 1913 /// ConvertedType. 1914 /// 1915 /// This routine also supports conversions to and from block pointers 1916 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 1917 /// pointers to interfaces. FIXME: Once we've determined the 1918 /// appropriate overloading rules for Objective-C, we may want to 1919 /// split the Objective-C checks into a different routine; however, 1920 /// GCC seems to consider all of these conversions to be pointer 1921 /// conversions, so for now they live here. IncompatibleObjC will be 1922 /// set if the conversion is an allowed Objective-C conversion that 1923 /// should result in a warning. 1924 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1925 bool InOverloadResolution, 1926 QualType& ConvertedType, 1927 bool &IncompatibleObjC) { 1928 IncompatibleObjC = false; 1929 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 1930 IncompatibleObjC)) 1931 return true; 1932 1933 // Conversion from a null pointer constant to any Objective-C pointer type. 1934 if (ToType->isObjCObjectPointerType() && 1935 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1936 ConvertedType = ToType; 1937 return true; 1938 } 1939 1940 // Blocks: Block pointers can be converted to void*. 1941 if (FromType->isBlockPointerType() && ToType->isPointerType() && 1942 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 1943 ConvertedType = ToType; 1944 return true; 1945 } 1946 // Blocks: A null pointer constant can be converted to a block 1947 // pointer type. 1948 if (ToType->isBlockPointerType() && 1949 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1950 ConvertedType = ToType; 1951 return true; 1952 } 1953 1954 // If the left-hand-side is nullptr_t, the right side can be a null 1955 // pointer constant. 1956 if (ToType->isNullPtrType() && 1957 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1958 ConvertedType = ToType; 1959 return true; 1960 } 1961 1962 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 1963 if (!ToTypePtr) 1964 return false; 1965 1966 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 1967 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1968 ConvertedType = ToType; 1969 return true; 1970 } 1971 1972 // Beyond this point, both types need to be pointers 1973 // , including objective-c pointers. 1974 QualType ToPointeeType = ToTypePtr->getPointeeType(); 1975 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 1976 !getLangOpts().ObjCAutoRefCount) { 1977 ConvertedType = BuildSimilarlyQualifiedPointerType( 1978 FromType->getAs<ObjCObjectPointerType>(), 1979 ToPointeeType, 1980 ToType, Context); 1981 return true; 1982 } 1983 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 1984 if (!FromTypePtr) 1985 return false; 1986 1987 QualType FromPointeeType = FromTypePtr->getPointeeType(); 1988 1989 // If the unqualified pointee types are the same, this can't be a 1990 // pointer conversion, so don't do all of the work below. 1991 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 1992 return false; 1993 1994 // An rvalue of type "pointer to cv T," where T is an object type, 1995 // can be converted to an rvalue of type "pointer to cv void" (C++ 1996 // 4.10p2). 1997 if (FromPointeeType->isIncompleteOrObjectType() && 1998 ToPointeeType->isVoidType()) { 1999 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2000 ToPointeeType, 2001 ToType, Context, 2002 /*StripObjCLifetime=*/true); 2003 return true; 2004 } 2005 2006 // MSVC allows implicit function to void* type conversion. 2007 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 2008 ToPointeeType->isVoidType()) { 2009 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2010 ToPointeeType, 2011 ToType, Context); 2012 return true; 2013 } 2014 2015 // When we're overloading in C, we allow a special kind of pointer 2016 // conversion for compatible-but-not-identical pointee types. 2017 if (!getLangOpts().CPlusPlus && 2018 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2019 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2020 ToPointeeType, 2021 ToType, Context); 2022 return true; 2023 } 2024 2025 // C++ [conv.ptr]p3: 2026 // 2027 // An rvalue of type "pointer to cv D," where D is a class type, 2028 // can be converted to an rvalue of type "pointer to cv B," where 2029 // B is a base class (clause 10) of D. If B is an inaccessible 2030 // (clause 11) or ambiguous (10.2) base class of D, a program that 2031 // necessitates this conversion is ill-formed. The result of the 2032 // conversion is a pointer to the base class sub-object of the 2033 // derived class object. The null pointer value is converted to 2034 // the null pointer value of the destination type. 2035 // 2036 // Note that we do not check for ambiguity or inaccessibility 2037 // here. That is handled by CheckPointerConversion. 2038 if (getLangOpts().CPlusPlus && 2039 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2040 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2041 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2042 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2043 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2044 ToPointeeType, 2045 ToType, Context); 2046 return true; 2047 } 2048 2049 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2050 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2051 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2052 ToPointeeType, 2053 ToType, Context); 2054 return true; 2055 } 2056 2057 return false; 2058 } 2059 2060 /// \brief Adopt the given qualifiers for the given type. 2061 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2062 Qualifiers TQs = T.getQualifiers(); 2063 2064 // Check whether qualifiers already match. 2065 if (TQs == Qs) 2066 return T; 2067 2068 if (Qs.compatiblyIncludes(TQs)) 2069 return Context.getQualifiedType(T, Qs); 2070 2071 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2072 } 2073 2074 /// isObjCPointerConversion - Determines whether this is an 2075 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2076 /// with the same arguments and return values. 2077 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2078 QualType& ConvertedType, 2079 bool &IncompatibleObjC) { 2080 if (!getLangOpts().ObjC1) 2081 return false; 2082 2083 // The set of qualifiers on the type we're converting from. 2084 Qualifiers FromQualifiers = FromType.getQualifiers(); 2085 2086 // First, we handle all conversions on ObjC object pointer types. 2087 const ObjCObjectPointerType* ToObjCPtr = 2088 ToType->getAs<ObjCObjectPointerType>(); 2089 const ObjCObjectPointerType *FromObjCPtr = 2090 FromType->getAs<ObjCObjectPointerType>(); 2091 2092 if (ToObjCPtr && FromObjCPtr) { 2093 // If the pointee types are the same (ignoring qualifications), 2094 // then this is not a pointer conversion. 2095 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2096 FromObjCPtr->getPointeeType())) 2097 return false; 2098 2099 // Check for compatible 2100 // Objective C++: We're able to convert between "id" or "Class" and a 2101 // pointer to any interface (in both directions). 2102 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2103 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2104 return true; 2105 } 2106 // Conversions with Objective-C's id<...>. 2107 if ((FromObjCPtr->isObjCQualifiedIdType() || 2108 ToObjCPtr->isObjCQualifiedIdType()) && 2109 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2110 /*compare=*/false)) { 2111 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2112 return true; 2113 } 2114 // Objective C++: We're able to convert from a pointer to an 2115 // interface to a pointer to a different interface. 2116 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2117 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2118 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2119 if (getLangOpts().CPlusPlus && LHS && RHS && 2120 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2121 FromObjCPtr->getPointeeType())) 2122 return false; 2123 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2124 ToObjCPtr->getPointeeType(), 2125 ToType, Context); 2126 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2127 return true; 2128 } 2129 2130 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2131 // Okay: this is some kind of implicit downcast of Objective-C 2132 // interfaces, which is permitted. However, we're going to 2133 // complain about it. 2134 IncompatibleObjC = true; 2135 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2136 ToObjCPtr->getPointeeType(), 2137 ToType, Context); 2138 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2139 return true; 2140 } 2141 } 2142 // Beyond this point, both types need to be C pointers or block pointers. 2143 QualType ToPointeeType; 2144 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2145 ToPointeeType = ToCPtr->getPointeeType(); 2146 else if (const BlockPointerType *ToBlockPtr = 2147 ToType->getAs<BlockPointerType>()) { 2148 // Objective C++: We're able to convert from a pointer to any object 2149 // to a block pointer type. 2150 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2151 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2152 return true; 2153 } 2154 ToPointeeType = ToBlockPtr->getPointeeType(); 2155 } 2156 else if (FromType->getAs<BlockPointerType>() && 2157 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2158 // Objective C++: We're able to convert from a block pointer type to a 2159 // pointer to any object. 2160 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2161 return true; 2162 } 2163 else 2164 return false; 2165 2166 QualType FromPointeeType; 2167 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2168 FromPointeeType = FromCPtr->getPointeeType(); 2169 else if (const BlockPointerType *FromBlockPtr = 2170 FromType->getAs<BlockPointerType>()) 2171 FromPointeeType = FromBlockPtr->getPointeeType(); 2172 else 2173 return false; 2174 2175 // If we have pointers to pointers, recursively check whether this 2176 // is an Objective-C conversion. 2177 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2178 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2179 IncompatibleObjC)) { 2180 // We always complain about this conversion. 2181 IncompatibleObjC = true; 2182 ConvertedType = Context.getPointerType(ConvertedType); 2183 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2184 return true; 2185 } 2186 // Allow conversion of pointee being objective-c pointer to another one; 2187 // as in I* to id. 2188 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2189 ToPointeeType->getAs<ObjCObjectPointerType>() && 2190 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2191 IncompatibleObjC)) { 2192 2193 ConvertedType = Context.getPointerType(ConvertedType); 2194 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2195 return true; 2196 } 2197 2198 // If we have pointers to functions or blocks, check whether the only 2199 // differences in the argument and result types are in Objective-C 2200 // pointer conversions. If so, we permit the conversion (but 2201 // complain about it). 2202 const FunctionProtoType *FromFunctionType 2203 = FromPointeeType->getAs<FunctionProtoType>(); 2204 const FunctionProtoType *ToFunctionType 2205 = ToPointeeType->getAs<FunctionProtoType>(); 2206 if (FromFunctionType && ToFunctionType) { 2207 // If the function types are exactly the same, this isn't an 2208 // Objective-C pointer conversion. 2209 if (Context.getCanonicalType(FromPointeeType) 2210 == Context.getCanonicalType(ToPointeeType)) 2211 return false; 2212 2213 // Perform the quick checks that will tell us whether these 2214 // function types are obviously different. 2215 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2216 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2217 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2218 return false; 2219 2220 bool HasObjCConversion = false; 2221 if (Context.getCanonicalType(FromFunctionType->getResultType()) 2222 == Context.getCanonicalType(ToFunctionType->getResultType())) { 2223 // Okay, the types match exactly. Nothing to do. 2224 } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 2225 ToFunctionType->getResultType(), 2226 ConvertedType, IncompatibleObjC)) { 2227 // Okay, we have an Objective-C pointer conversion. 2228 HasObjCConversion = true; 2229 } else { 2230 // Function types are too different. Abort. 2231 return false; 2232 } 2233 2234 // Check argument types. 2235 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2236 ArgIdx != NumArgs; ++ArgIdx) { 2237 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2238 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2239 if (Context.getCanonicalType(FromArgType) 2240 == Context.getCanonicalType(ToArgType)) { 2241 // Okay, the types match exactly. Nothing to do. 2242 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2243 ConvertedType, IncompatibleObjC)) { 2244 // Okay, we have an Objective-C pointer conversion. 2245 HasObjCConversion = true; 2246 } else { 2247 // Argument types are too different. Abort. 2248 return false; 2249 } 2250 } 2251 2252 if (HasObjCConversion) { 2253 // We had an Objective-C conversion. Allow this pointer 2254 // conversion, but complain about it. 2255 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2256 IncompatibleObjC = true; 2257 return true; 2258 } 2259 } 2260 2261 return false; 2262 } 2263 2264 /// \brief Determine whether this is an Objective-C writeback conversion, 2265 /// used for parameter passing when performing automatic reference counting. 2266 /// 2267 /// \param FromType The type we're converting form. 2268 /// 2269 /// \param ToType The type we're converting to. 2270 /// 2271 /// \param ConvertedType The type that will be produced after applying 2272 /// this conversion. 2273 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2274 QualType &ConvertedType) { 2275 if (!getLangOpts().ObjCAutoRefCount || 2276 Context.hasSameUnqualifiedType(FromType, ToType)) 2277 return false; 2278 2279 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2280 QualType ToPointee; 2281 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2282 ToPointee = ToPointer->getPointeeType(); 2283 else 2284 return false; 2285 2286 Qualifiers ToQuals = ToPointee.getQualifiers(); 2287 if (!ToPointee->isObjCLifetimeType() || 2288 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2289 !ToQuals.withoutObjCLifetime().empty()) 2290 return false; 2291 2292 // Argument must be a pointer to __strong to __weak. 2293 QualType FromPointee; 2294 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2295 FromPointee = FromPointer->getPointeeType(); 2296 else 2297 return false; 2298 2299 Qualifiers FromQuals = FromPointee.getQualifiers(); 2300 if (!FromPointee->isObjCLifetimeType() || 2301 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2302 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2303 return false; 2304 2305 // Make sure that we have compatible qualifiers. 2306 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2307 if (!ToQuals.compatiblyIncludes(FromQuals)) 2308 return false; 2309 2310 // Remove qualifiers from the pointee type we're converting from; they 2311 // aren't used in the compatibility check belong, and we'll be adding back 2312 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2313 FromPointee = FromPointee.getUnqualifiedType(); 2314 2315 // The unqualified form of the pointee types must be compatible. 2316 ToPointee = ToPointee.getUnqualifiedType(); 2317 bool IncompatibleObjC; 2318 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2319 FromPointee = ToPointee; 2320 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2321 IncompatibleObjC)) 2322 return false; 2323 2324 /// \brief Construct the type we're converting to, which is a pointer to 2325 /// __autoreleasing pointee. 2326 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2327 ConvertedType = Context.getPointerType(FromPointee); 2328 return true; 2329 } 2330 2331 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2332 QualType& ConvertedType) { 2333 QualType ToPointeeType; 2334 if (const BlockPointerType *ToBlockPtr = 2335 ToType->getAs<BlockPointerType>()) 2336 ToPointeeType = ToBlockPtr->getPointeeType(); 2337 else 2338 return false; 2339 2340 QualType FromPointeeType; 2341 if (const BlockPointerType *FromBlockPtr = 2342 FromType->getAs<BlockPointerType>()) 2343 FromPointeeType = FromBlockPtr->getPointeeType(); 2344 else 2345 return false; 2346 // We have pointer to blocks, check whether the only 2347 // differences in the argument and result types are in Objective-C 2348 // pointer conversions. If so, we permit the conversion. 2349 2350 const FunctionProtoType *FromFunctionType 2351 = FromPointeeType->getAs<FunctionProtoType>(); 2352 const FunctionProtoType *ToFunctionType 2353 = ToPointeeType->getAs<FunctionProtoType>(); 2354 2355 if (!FromFunctionType || !ToFunctionType) 2356 return false; 2357 2358 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2359 return true; 2360 2361 // Perform the quick checks that will tell us whether these 2362 // function types are obviously different. 2363 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2364 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2365 return false; 2366 2367 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2368 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2369 if (FromEInfo != ToEInfo) 2370 return false; 2371 2372 bool IncompatibleObjC = false; 2373 if (Context.hasSameType(FromFunctionType->getResultType(), 2374 ToFunctionType->getResultType())) { 2375 // Okay, the types match exactly. Nothing to do. 2376 } else { 2377 QualType RHS = FromFunctionType->getResultType(); 2378 QualType LHS = ToFunctionType->getResultType(); 2379 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2380 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2381 LHS = LHS.getUnqualifiedType(); 2382 2383 if (Context.hasSameType(RHS,LHS)) { 2384 // OK exact match. 2385 } else if (isObjCPointerConversion(RHS, LHS, 2386 ConvertedType, IncompatibleObjC)) { 2387 if (IncompatibleObjC) 2388 return false; 2389 // Okay, we have an Objective-C pointer conversion. 2390 } 2391 else 2392 return false; 2393 } 2394 2395 // Check argument types. 2396 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2397 ArgIdx != NumArgs; ++ArgIdx) { 2398 IncompatibleObjC = false; 2399 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2400 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2401 if (Context.hasSameType(FromArgType, ToArgType)) { 2402 // Okay, the types match exactly. Nothing to do. 2403 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2404 ConvertedType, IncompatibleObjC)) { 2405 if (IncompatibleObjC) 2406 return false; 2407 // Okay, we have an Objective-C pointer conversion. 2408 } else 2409 // Argument types are too different. Abort. 2410 return false; 2411 } 2412 if (LangOpts.ObjCAutoRefCount && 2413 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2414 ToFunctionType)) 2415 return false; 2416 2417 ConvertedType = ToType; 2418 return true; 2419 } 2420 2421 enum { 2422 ft_default, 2423 ft_different_class, 2424 ft_parameter_arity, 2425 ft_parameter_mismatch, 2426 ft_return_type, 2427 ft_qualifer_mismatch 2428 }; 2429 2430 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2431 /// function types. Catches different number of parameter, mismatch in 2432 /// parameter types, and different return types. 2433 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2434 QualType FromType, QualType ToType) { 2435 // If either type is not valid, include no extra info. 2436 if (FromType.isNull() || ToType.isNull()) { 2437 PDiag << ft_default; 2438 return; 2439 } 2440 2441 // Get the function type from the pointers. 2442 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2443 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2444 *ToMember = ToType->getAs<MemberPointerType>(); 2445 if (FromMember->getClass() != ToMember->getClass()) { 2446 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2447 << QualType(FromMember->getClass(), 0); 2448 return; 2449 } 2450 FromType = FromMember->getPointeeType(); 2451 ToType = ToMember->getPointeeType(); 2452 } 2453 2454 if (FromType->isPointerType()) 2455 FromType = FromType->getPointeeType(); 2456 if (ToType->isPointerType()) 2457 ToType = ToType->getPointeeType(); 2458 2459 // Remove references. 2460 FromType = FromType.getNonReferenceType(); 2461 ToType = ToType.getNonReferenceType(); 2462 2463 // Don't print extra info for non-specialized template functions. 2464 if (FromType->isInstantiationDependentType() && 2465 !FromType->getAs<TemplateSpecializationType>()) { 2466 PDiag << ft_default; 2467 return; 2468 } 2469 2470 // No extra info for same types. 2471 if (Context.hasSameType(FromType, ToType)) { 2472 PDiag << ft_default; 2473 return; 2474 } 2475 2476 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2477 *ToFunction = ToType->getAs<FunctionProtoType>(); 2478 2479 // Both types need to be function types. 2480 if (!FromFunction || !ToFunction) { 2481 PDiag << ft_default; 2482 return; 2483 } 2484 2485 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) { 2486 PDiag << ft_parameter_arity << ToFunction->getNumArgs() 2487 << FromFunction->getNumArgs(); 2488 return; 2489 } 2490 2491 // Handle different parameter types. 2492 unsigned ArgPos; 2493 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2494 PDiag << ft_parameter_mismatch << ArgPos + 1 2495 << ToFunction->getArgType(ArgPos) 2496 << FromFunction->getArgType(ArgPos); 2497 return; 2498 } 2499 2500 // Handle different return type. 2501 if (!Context.hasSameType(FromFunction->getResultType(), 2502 ToFunction->getResultType())) { 2503 PDiag << ft_return_type << ToFunction->getResultType() 2504 << FromFunction->getResultType(); 2505 return; 2506 } 2507 2508 unsigned FromQuals = FromFunction->getTypeQuals(), 2509 ToQuals = ToFunction->getTypeQuals(); 2510 if (FromQuals != ToQuals) { 2511 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2512 return; 2513 } 2514 2515 // Unable to find a difference, so add no extra info. 2516 PDiag << ft_default; 2517 } 2518 2519 /// FunctionArgTypesAreEqual - This routine checks two function proto types 2520 /// for equality of their argument types. Caller has already checked that 2521 /// they have same number of arguments. This routine assumes that Objective-C 2522 /// pointer types which only differ in their protocol qualifiers are equal. 2523 /// If the parameters are different, ArgPos will have the parameter index 2524 /// of the first different parameter. 2525 bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 2526 const FunctionProtoType *NewType, 2527 unsigned *ArgPos) { 2528 if (!getLangOpts().ObjC1) { 2529 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2530 N = NewType->arg_type_begin(), 2531 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2532 if (!Context.hasSameType(*O, *N)) { 2533 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2534 return false; 2535 } 2536 } 2537 return true; 2538 } 2539 2540 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2541 N = NewType->arg_type_begin(), 2542 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2543 QualType ToType = (*O); 2544 QualType FromType = (*N); 2545 if (!Context.hasSameType(ToType, FromType)) { 2546 if (const PointerType *PTTo = ToType->getAs<PointerType>()) { 2547 if (const PointerType *PTFr = FromType->getAs<PointerType>()) 2548 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() && 2549 PTFr->getPointeeType()->isObjCQualifiedIdType()) || 2550 (PTTo->getPointeeType()->isObjCQualifiedClassType() && 2551 PTFr->getPointeeType()->isObjCQualifiedClassType())) 2552 continue; 2553 } 2554 else if (const ObjCObjectPointerType *PTTo = 2555 ToType->getAs<ObjCObjectPointerType>()) { 2556 if (const ObjCObjectPointerType *PTFr = 2557 FromType->getAs<ObjCObjectPointerType>()) 2558 if (Context.hasSameUnqualifiedType( 2559 PTTo->getObjectType()->getBaseType(), 2560 PTFr->getObjectType()->getBaseType())) 2561 continue; 2562 } 2563 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2564 return false; 2565 } 2566 } 2567 return true; 2568 } 2569 2570 /// CheckPointerConversion - Check the pointer conversion from the 2571 /// expression From to the type ToType. This routine checks for 2572 /// ambiguous or inaccessible derived-to-base pointer 2573 /// conversions for which IsPointerConversion has already returned 2574 /// true. It returns true and produces a diagnostic if there was an 2575 /// error, or returns false otherwise. 2576 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2577 CastKind &Kind, 2578 CXXCastPath& BasePath, 2579 bool IgnoreBaseAccess) { 2580 QualType FromType = From->getType(); 2581 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2582 2583 Kind = CK_BitCast; 2584 2585 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2586 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2587 Expr::NPCK_ZeroExpression) { 2588 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2589 DiagRuntimeBehavior(From->getExprLoc(), From, 2590 PDiag(diag::warn_impcast_bool_to_null_pointer) 2591 << ToType << From->getSourceRange()); 2592 else if (!isUnevaluatedContext()) 2593 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2594 << ToType << From->getSourceRange(); 2595 } 2596 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2597 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2598 QualType FromPointeeType = FromPtrType->getPointeeType(), 2599 ToPointeeType = ToPtrType->getPointeeType(); 2600 2601 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2602 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2603 // We must have a derived-to-base conversion. Check an 2604 // ambiguous or inaccessible conversion. 2605 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2606 From->getExprLoc(), 2607 From->getSourceRange(), &BasePath, 2608 IgnoreBaseAccess)) 2609 return true; 2610 2611 // The conversion was successful. 2612 Kind = CK_DerivedToBase; 2613 } 2614 } 2615 } else if (const ObjCObjectPointerType *ToPtrType = 2616 ToType->getAs<ObjCObjectPointerType>()) { 2617 if (const ObjCObjectPointerType *FromPtrType = 2618 FromType->getAs<ObjCObjectPointerType>()) { 2619 // Objective-C++ conversions are always okay. 2620 // FIXME: We should have a different class of conversions for the 2621 // Objective-C++ implicit conversions. 2622 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2623 return false; 2624 } else if (FromType->isBlockPointerType()) { 2625 Kind = CK_BlockPointerToObjCPointerCast; 2626 } else { 2627 Kind = CK_CPointerToObjCPointerCast; 2628 } 2629 } else if (ToType->isBlockPointerType()) { 2630 if (!FromType->isBlockPointerType()) 2631 Kind = CK_AnyPointerToBlockPointerCast; 2632 } 2633 2634 // We shouldn't fall into this case unless it's valid for other 2635 // reasons. 2636 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2637 Kind = CK_NullToPointer; 2638 2639 return false; 2640 } 2641 2642 /// IsMemberPointerConversion - Determines whether the conversion of the 2643 /// expression From, which has the (possibly adjusted) type FromType, can be 2644 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2645 /// If so, returns true and places the converted type (that might differ from 2646 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2647 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2648 QualType ToType, 2649 bool InOverloadResolution, 2650 QualType &ConvertedType) { 2651 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2652 if (!ToTypePtr) 2653 return false; 2654 2655 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2656 if (From->isNullPointerConstant(Context, 2657 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2658 : Expr::NPC_ValueDependentIsNull)) { 2659 ConvertedType = ToType; 2660 return true; 2661 } 2662 2663 // Otherwise, both types have to be member pointers. 2664 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2665 if (!FromTypePtr) 2666 return false; 2667 2668 // A pointer to member of B can be converted to a pointer to member of D, 2669 // where D is derived from B (C++ 4.11p2). 2670 QualType FromClass(FromTypePtr->getClass(), 0); 2671 QualType ToClass(ToTypePtr->getClass(), 0); 2672 2673 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2674 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2675 IsDerivedFrom(ToClass, FromClass)) { 2676 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2677 ToClass.getTypePtr()); 2678 return true; 2679 } 2680 2681 return false; 2682 } 2683 2684 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2685 /// expression From to the type ToType. This routine checks for ambiguous or 2686 /// virtual or inaccessible base-to-derived member pointer conversions 2687 /// for which IsMemberPointerConversion has already returned true. It returns 2688 /// true and produces a diagnostic if there was an error, or returns false 2689 /// otherwise. 2690 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2691 CastKind &Kind, 2692 CXXCastPath &BasePath, 2693 bool IgnoreBaseAccess) { 2694 QualType FromType = From->getType(); 2695 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2696 if (!FromPtrType) { 2697 // This must be a null pointer to member pointer conversion 2698 assert(From->isNullPointerConstant(Context, 2699 Expr::NPC_ValueDependentIsNull) && 2700 "Expr must be null pointer constant!"); 2701 Kind = CK_NullToMemberPointer; 2702 return false; 2703 } 2704 2705 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2706 assert(ToPtrType && "No member pointer cast has a target type " 2707 "that is not a member pointer."); 2708 2709 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2710 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2711 2712 // FIXME: What about dependent types? 2713 assert(FromClass->isRecordType() && "Pointer into non-class."); 2714 assert(ToClass->isRecordType() && "Pointer into non-class."); 2715 2716 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2717 /*DetectVirtual=*/true); 2718 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2719 assert(DerivationOkay && 2720 "Should not have been called if derivation isn't OK."); 2721 (void)DerivationOkay; 2722 2723 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2724 getUnqualifiedType())) { 2725 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2726 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2727 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2728 return true; 2729 } 2730 2731 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2732 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2733 << FromClass << ToClass << QualType(VBase, 0) 2734 << From->getSourceRange(); 2735 return true; 2736 } 2737 2738 if (!IgnoreBaseAccess) 2739 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2740 Paths.front(), 2741 diag::err_downcast_from_inaccessible_base); 2742 2743 // Must be a base to derived member conversion. 2744 BuildBasePathArray(Paths, BasePath); 2745 Kind = CK_BaseToDerivedMemberPointer; 2746 return false; 2747 } 2748 2749 /// IsQualificationConversion - Determines whether the conversion from 2750 /// an rvalue of type FromType to ToType is a qualification conversion 2751 /// (C++ 4.4). 2752 /// 2753 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2754 /// when the qualification conversion involves a change in the Objective-C 2755 /// object lifetime. 2756 bool 2757 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2758 bool CStyle, bool &ObjCLifetimeConversion) { 2759 FromType = Context.getCanonicalType(FromType); 2760 ToType = Context.getCanonicalType(ToType); 2761 ObjCLifetimeConversion = false; 2762 2763 // If FromType and ToType are the same type, this is not a 2764 // qualification conversion. 2765 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2766 return false; 2767 2768 // (C++ 4.4p4): 2769 // A conversion can add cv-qualifiers at levels other than the first 2770 // in multi-level pointers, subject to the following rules: [...] 2771 bool PreviousToQualsIncludeConst = true; 2772 bool UnwrappedAnyPointer = false; 2773 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2774 // Within each iteration of the loop, we check the qualifiers to 2775 // determine if this still looks like a qualification 2776 // conversion. Then, if all is well, we unwrap one more level of 2777 // pointers or pointers-to-members and do it all again 2778 // until there are no more pointers or pointers-to-members left to 2779 // unwrap. 2780 UnwrappedAnyPointer = true; 2781 2782 Qualifiers FromQuals = FromType.getQualifiers(); 2783 Qualifiers ToQuals = ToType.getQualifiers(); 2784 2785 // Objective-C ARC: 2786 // Check Objective-C lifetime conversions. 2787 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2788 UnwrappedAnyPointer) { 2789 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2790 ObjCLifetimeConversion = true; 2791 FromQuals.removeObjCLifetime(); 2792 ToQuals.removeObjCLifetime(); 2793 } else { 2794 // Qualification conversions cannot cast between different 2795 // Objective-C lifetime qualifiers. 2796 return false; 2797 } 2798 } 2799 2800 // Allow addition/removal of GC attributes but not changing GC attributes. 2801 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2802 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2803 FromQuals.removeObjCGCAttr(); 2804 ToQuals.removeObjCGCAttr(); 2805 } 2806 2807 // -- for every j > 0, if const is in cv 1,j then const is in cv 2808 // 2,j, and similarly for volatile. 2809 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2810 return false; 2811 2812 // -- if the cv 1,j and cv 2,j are different, then const is in 2813 // every cv for 0 < k < j. 2814 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2815 && !PreviousToQualsIncludeConst) 2816 return false; 2817 2818 // Keep track of whether all prior cv-qualifiers in the "to" type 2819 // include const. 2820 PreviousToQualsIncludeConst 2821 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2822 } 2823 2824 // We are left with FromType and ToType being the pointee types 2825 // after unwrapping the original FromType and ToType the same number 2826 // of types. If we unwrapped any pointers, and if FromType and 2827 // ToType have the same unqualified type (since we checked 2828 // qualifiers above), then this is a qualification conversion. 2829 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2830 } 2831 2832 /// \brief - Determine whether this is a conversion from a scalar type to an 2833 /// atomic type. 2834 /// 2835 /// If successful, updates \c SCS's second and third steps in the conversion 2836 /// sequence to finish the conversion. 2837 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2838 bool InOverloadResolution, 2839 StandardConversionSequence &SCS, 2840 bool CStyle) { 2841 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2842 if (!ToAtomic) 2843 return false; 2844 2845 StandardConversionSequence InnerSCS; 2846 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2847 InOverloadResolution, InnerSCS, 2848 CStyle, /*AllowObjCWritebackConversion=*/false)) 2849 return false; 2850 2851 SCS.Second = InnerSCS.Second; 2852 SCS.setToType(1, InnerSCS.getToType(1)); 2853 SCS.Third = InnerSCS.Third; 2854 SCS.QualificationIncludesObjCLifetime 2855 = InnerSCS.QualificationIncludesObjCLifetime; 2856 SCS.setToType(2, InnerSCS.getToType(2)); 2857 return true; 2858 } 2859 2860 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2861 CXXConstructorDecl *Constructor, 2862 QualType Type) { 2863 const FunctionProtoType *CtorType = 2864 Constructor->getType()->getAs<FunctionProtoType>(); 2865 if (CtorType->getNumArgs() > 0) { 2866 QualType FirstArg = CtorType->getArgType(0); 2867 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2868 return true; 2869 } 2870 return false; 2871 } 2872 2873 static OverloadingResult 2874 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2875 CXXRecordDecl *To, 2876 UserDefinedConversionSequence &User, 2877 OverloadCandidateSet &CandidateSet, 2878 bool AllowExplicit) { 2879 DeclContext::lookup_iterator Con, ConEnd; 2880 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To); 2881 Con != ConEnd; ++Con) { 2882 NamedDecl *D = *Con; 2883 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2884 2885 // Find the constructor (which may be a template). 2886 CXXConstructorDecl *Constructor = 0; 2887 FunctionTemplateDecl *ConstructorTmpl 2888 = dyn_cast<FunctionTemplateDecl>(D); 2889 if (ConstructorTmpl) 2890 Constructor 2891 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2892 else 2893 Constructor = cast<CXXConstructorDecl>(D); 2894 2895 bool Usable = !Constructor->isInvalidDecl() && 2896 S.isInitListConstructor(Constructor) && 2897 (AllowExplicit || !Constructor->isExplicit()); 2898 if (Usable) { 2899 // If the first argument is (a reference to) the target type, 2900 // suppress conversions. 2901 bool SuppressUserConversions = 2902 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2903 if (ConstructorTmpl) 2904 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2905 /*ExplicitArgs*/ 0, 2906 From, CandidateSet, 2907 SuppressUserConversions); 2908 else 2909 S.AddOverloadCandidate(Constructor, FoundDecl, 2910 From, CandidateSet, 2911 SuppressUserConversions); 2912 } 2913 } 2914 2915 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2916 2917 OverloadCandidateSet::iterator Best; 2918 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2919 case OR_Success: { 2920 // Record the standard conversion we used and the conversion function. 2921 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2922 S.MarkFunctionReferenced(From->getLocStart(), Constructor); 2923 2924 QualType ThisType = Constructor->getThisType(S.Context); 2925 // Initializer lists don't have conversions as such. 2926 User.Before.setAsIdentityConversion(); 2927 User.HadMultipleCandidates = HadMultipleCandidates; 2928 User.ConversionFunction = Constructor; 2929 User.FoundConversionFunction = Best->FoundDecl; 2930 User.After.setAsIdentityConversion(); 2931 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2932 User.After.setAllToTypes(ToType); 2933 return OR_Success; 2934 } 2935 2936 case OR_No_Viable_Function: 2937 return OR_No_Viable_Function; 2938 case OR_Deleted: 2939 return OR_Deleted; 2940 case OR_Ambiguous: 2941 return OR_Ambiguous; 2942 } 2943 2944 llvm_unreachable("Invalid OverloadResult!"); 2945 } 2946 2947 /// Determines whether there is a user-defined conversion sequence 2948 /// (C++ [over.ics.user]) that converts expression From to the type 2949 /// ToType. If such a conversion exists, User will contain the 2950 /// user-defined conversion sequence that performs such a conversion 2951 /// and this routine will return true. Otherwise, this routine returns 2952 /// false and User is unspecified. 2953 /// 2954 /// \param AllowExplicit true if the conversion should consider C++0x 2955 /// "explicit" conversion functions as well as non-explicit conversion 2956 /// functions (C++0x [class.conv.fct]p2). 2957 static OverloadingResult 2958 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 2959 UserDefinedConversionSequence &User, 2960 OverloadCandidateSet &CandidateSet, 2961 bool AllowExplicit) { 2962 // Whether we will only visit constructors. 2963 bool ConstructorsOnly = false; 2964 2965 // If the type we are conversion to is a class type, enumerate its 2966 // constructors. 2967 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 2968 // C++ [over.match.ctor]p1: 2969 // When objects of class type are direct-initialized (8.5), or 2970 // copy-initialized from an expression of the same or a 2971 // derived class type (8.5), overload resolution selects the 2972 // constructor. [...] For copy-initialization, the candidate 2973 // functions are all the converting constructors (12.3.1) of 2974 // that class. The argument list is the expression-list within 2975 // the parentheses of the initializer. 2976 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 2977 (From->getType()->getAs<RecordType>() && 2978 S.IsDerivedFrom(From->getType(), ToType))) 2979 ConstructorsOnly = true; 2980 2981 S.RequireCompleteType(From->getLocStart(), ToType, 0); 2982 // RequireCompleteType may have returned true due to some invalid decl 2983 // during template instantiation, but ToType may be complete enough now 2984 // to try to recover. 2985 if (ToType->isIncompleteType()) { 2986 // We're not going to find any constructors. 2987 } else if (CXXRecordDecl *ToRecordDecl 2988 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 2989 2990 Expr **Args = &From; 2991 unsigned NumArgs = 1; 2992 bool ListInitializing = false; 2993 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 2994 // But first, see if there is an init-list-contructor that will work. 2995 OverloadingResult Result = IsInitializerListConstructorConversion( 2996 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 2997 if (Result != OR_No_Viable_Function) 2998 return Result; 2999 // Never mind. 3000 CandidateSet.clear(); 3001 3002 // If we're list-initializing, we pass the individual elements as 3003 // arguments, not the entire list. 3004 Args = InitList->getInits(); 3005 NumArgs = InitList->getNumInits(); 3006 ListInitializing = true; 3007 } 3008 3009 DeclContext::lookup_iterator Con, ConEnd; 3010 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl); 3011 Con != ConEnd; ++Con) { 3012 NamedDecl *D = *Con; 3013 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3014 3015 // Find the constructor (which may be a template). 3016 CXXConstructorDecl *Constructor = 0; 3017 FunctionTemplateDecl *ConstructorTmpl 3018 = dyn_cast<FunctionTemplateDecl>(D); 3019 if (ConstructorTmpl) 3020 Constructor 3021 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3022 else 3023 Constructor = cast<CXXConstructorDecl>(D); 3024 3025 bool Usable = !Constructor->isInvalidDecl(); 3026 if (ListInitializing) 3027 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3028 else 3029 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3030 if (Usable) { 3031 bool SuppressUserConversions = !ConstructorsOnly; 3032 if (SuppressUserConversions && ListInitializing) { 3033 SuppressUserConversions = false; 3034 if (NumArgs == 1) { 3035 // If the first argument is (a reference to) the target type, 3036 // suppress conversions. 3037 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3038 S.Context, Constructor, ToType); 3039 } 3040 } 3041 if (ConstructorTmpl) 3042 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3043 /*ExplicitArgs*/ 0, 3044 llvm::makeArrayRef(Args, NumArgs), 3045 CandidateSet, SuppressUserConversions); 3046 else 3047 // Allow one user-defined conversion when user specifies a 3048 // From->ToType conversion via an static cast (c-style, etc). 3049 S.AddOverloadCandidate(Constructor, FoundDecl, 3050 llvm::makeArrayRef(Args, NumArgs), 3051 CandidateSet, SuppressUserConversions); 3052 } 3053 } 3054 } 3055 } 3056 3057 // Enumerate conversion functions, if we're allowed to. 3058 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3059 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3060 // No conversion functions from incomplete types. 3061 } else if (const RecordType *FromRecordType 3062 = From->getType()->getAs<RecordType>()) { 3063 if (CXXRecordDecl *FromRecordDecl 3064 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3065 // Add all of the conversion functions as candidates. 3066 const UnresolvedSetImpl *Conversions 3067 = FromRecordDecl->getVisibleConversionFunctions(); 3068 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 3069 E = Conversions->end(); I != E; ++I) { 3070 DeclAccessPair FoundDecl = I.getPair(); 3071 NamedDecl *D = FoundDecl.getDecl(); 3072 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3073 if (isa<UsingShadowDecl>(D)) 3074 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3075 3076 CXXConversionDecl *Conv; 3077 FunctionTemplateDecl *ConvTemplate; 3078 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3079 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3080 else 3081 Conv = cast<CXXConversionDecl>(D); 3082 3083 if (AllowExplicit || !Conv->isExplicit()) { 3084 if (ConvTemplate) 3085 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3086 ActingContext, From, ToType, 3087 CandidateSet); 3088 else 3089 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3090 From, ToType, CandidateSet); 3091 } 3092 } 3093 } 3094 } 3095 3096 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3097 3098 OverloadCandidateSet::iterator Best; 3099 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3100 case OR_Success: 3101 // Record the standard conversion we used and the conversion function. 3102 if (CXXConstructorDecl *Constructor 3103 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3104 S.MarkFunctionReferenced(From->getLocStart(), Constructor); 3105 3106 // C++ [over.ics.user]p1: 3107 // If the user-defined conversion is specified by a 3108 // constructor (12.3.1), the initial standard conversion 3109 // sequence converts the source type to the type required by 3110 // the argument of the constructor. 3111 // 3112 QualType ThisType = Constructor->getThisType(S.Context); 3113 if (isa<InitListExpr>(From)) { 3114 // Initializer lists don't have conversions as such. 3115 User.Before.setAsIdentityConversion(); 3116 } else { 3117 if (Best->Conversions[0].isEllipsis()) 3118 User.EllipsisConversion = true; 3119 else { 3120 User.Before = Best->Conversions[0].Standard; 3121 User.EllipsisConversion = false; 3122 } 3123 } 3124 User.HadMultipleCandidates = HadMultipleCandidates; 3125 User.ConversionFunction = Constructor; 3126 User.FoundConversionFunction = Best->FoundDecl; 3127 User.After.setAsIdentityConversion(); 3128 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3129 User.After.setAllToTypes(ToType); 3130 return OR_Success; 3131 } 3132 if (CXXConversionDecl *Conversion 3133 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3134 S.MarkFunctionReferenced(From->getLocStart(), Conversion); 3135 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 const UnresolvedSetImpl *Conversions 3965 = T2RecordDecl->getVisibleConversionFunctions(); 3966 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 3967 E = Conversions->end(); I != E; ++I) { 3968 NamedDecl *D = *I; 3969 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 3970 if (isa<UsingShadowDecl>(D)) 3971 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3972 3973 FunctionTemplateDecl *ConvTemplate 3974 = dyn_cast<FunctionTemplateDecl>(D); 3975 CXXConversionDecl *Conv; 3976 if (ConvTemplate) 3977 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3978 else 3979 Conv = cast<CXXConversionDecl>(D); 3980 3981 // If this is an explicit conversion, and we're not allowed to consider 3982 // explicit conversions, skip it. 3983 if (!AllowExplicit && Conv->isExplicit()) 3984 continue; 3985 3986 if (AllowRvalues) { 3987 bool DerivedToBase = false; 3988 bool ObjCConversion = false; 3989 bool ObjCLifetimeConversion = false; 3990 3991 // If we are initializing an rvalue reference, don't permit conversion 3992 // functions that return lvalues. 3993 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 3994 const ReferenceType *RefType 3995 = Conv->getConversionType()->getAs<LValueReferenceType>(); 3996 if (RefType && !RefType->getPointeeType()->isFunctionType()) 3997 continue; 3998 } 3999 4000 if (!ConvTemplate && 4001 S.CompareReferenceRelationship( 4002 DeclLoc, 4003 Conv->getConversionType().getNonReferenceType() 4004 .getUnqualifiedType(), 4005 DeclType.getNonReferenceType().getUnqualifiedType(), 4006 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4007 Sema::Ref_Incompatible) 4008 continue; 4009 } else { 4010 // If the conversion function doesn't return a reference type, 4011 // it can't be considered for this conversion. An rvalue reference 4012 // is only acceptable if its referencee is a function type. 4013 4014 const ReferenceType *RefType = 4015 Conv->getConversionType()->getAs<ReferenceType>(); 4016 if (!RefType || 4017 (!RefType->isLValueReferenceType() && 4018 !RefType->getPointeeType()->isFunctionType())) 4019 continue; 4020 } 4021 4022 if (ConvTemplate) 4023 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4024 Init, DeclType, CandidateSet); 4025 else 4026 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4027 DeclType, CandidateSet); 4028 } 4029 4030 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4031 4032 OverloadCandidateSet::iterator Best; 4033 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4034 case OR_Success: 4035 // C++ [over.ics.ref]p1: 4036 // 4037 // [...] If the parameter binds directly to the result of 4038 // applying a conversion function to the argument 4039 // expression, the implicit conversion sequence is a 4040 // user-defined conversion sequence (13.3.3.1.2), with the 4041 // second standard conversion sequence either an identity 4042 // conversion or, if the conversion function returns an 4043 // entity of a type that is a derived class of the parameter 4044 // type, a derived-to-base Conversion. 4045 if (!Best->FinalConversion.DirectBinding) 4046 return false; 4047 4048 if (Best->Function) 4049 S.MarkFunctionReferenced(DeclLoc, Best->Function); 4050 ICS.setUserDefined(); 4051 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4052 ICS.UserDefined.After = Best->FinalConversion; 4053 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4054 ICS.UserDefined.ConversionFunction = Best->Function; 4055 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4056 ICS.UserDefined.EllipsisConversion = false; 4057 assert(ICS.UserDefined.After.ReferenceBinding && 4058 ICS.UserDefined.After.DirectBinding && 4059 "Expected a direct reference binding!"); 4060 return true; 4061 4062 case OR_Ambiguous: 4063 ICS.setAmbiguous(); 4064 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4065 Cand != CandidateSet.end(); ++Cand) 4066 if (Cand->Viable) 4067 ICS.Ambiguous.addConversion(Cand->Function); 4068 return true; 4069 4070 case OR_No_Viable_Function: 4071 case OR_Deleted: 4072 // There was no suitable conversion, or we found a deleted 4073 // conversion; continue with other checks. 4074 return false; 4075 } 4076 4077 llvm_unreachable("Invalid OverloadResult!"); 4078 } 4079 4080 /// \brief Compute an implicit conversion sequence for reference 4081 /// initialization. 4082 static ImplicitConversionSequence 4083 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4084 SourceLocation DeclLoc, 4085 bool SuppressUserConversions, 4086 bool AllowExplicit) { 4087 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4088 4089 // Most paths end in a failed conversion. 4090 ImplicitConversionSequence ICS; 4091 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4092 4093 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4094 QualType T2 = Init->getType(); 4095 4096 // If the initializer is the address of an overloaded function, try 4097 // to resolve the overloaded function. If all goes well, T2 is the 4098 // type of the resulting function. 4099 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4100 DeclAccessPair Found; 4101 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4102 false, Found)) 4103 T2 = Fn->getType(); 4104 } 4105 4106 // Compute some basic properties of the types and the initializer. 4107 bool isRValRef = DeclType->isRValueReferenceType(); 4108 bool DerivedToBase = false; 4109 bool ObjCConversion = false; 4110 bool ObjCLifetimeConversion = false; 4111 Expr::Classification InitCategory = Init->Classify(S.Context); 4112 Sema::ReferenceCompareResult RefRelationship 4113 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4114 ObjCConversion, ObjCLifetimeConversion); 4115 4116 4117 // C++0x [dcl.init.ref]p5: 4118 // A reference to type "cv1 T1" is initialized by an expression 4119 // of type "cv2 T2" as follows: 4120 4121 // -- If reference is an lvalue reference and the initializer expression 4122 if (!isRValRef) { 4123 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4124 // reference-compatible with "cv2 T2," or 4125 // 4126 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4127 if (InitCategory.isLValue() && 4128 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4129 // C++ [over.ics.ref]p1: 4130 // When a parameter of reference type binds directly (8.5.3) 4131 // to an argument expression, the implicit conversion sequence 4132 // is the identity conversion, unless the argument expression 4133 // has a type that is a derived class of the parameter type, 4134 // in which case the implicit conversion sequence is a 4135 // derived-to-base Conversion (13.3.3.1). 4136 ICS.setStandard(); 4137 ICS.Standard.First = ICK_Identity; 4138 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4139 : ObjCConversion? ICK_Compatible_Conversion 4140 : ICK_Identity; 4141 ICS.Standard.Third = ICK_Identity; 4142 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4143 ICS.Standard.setToType(0, T2); 4144 ICS.Standard.setToType(1, T1); 4145 ICS.Standard.setToType(2, T1); 4146 ICS.Standard.ReferenceBinding = true; 4147 ICS.Standard.DirectBinding = true; 4148 ICS.Standard.IsLvalueReference = !isRValRef; 4149 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4150 ICS.Standard.BindsToRvalue = false; 4151 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4152 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4153 ICS.Standard.CopyConstructor = 0; 4154 4155 // Nothing more to do: the inaccessibility/ambiguity check for 4156 // derived-to-base conversions is suppressed when we're 4157 // computing the implicit conversion sequence (C++ 4158 // [over.best.ics]p2). 4159 return ICS; 4160 } 4161 4162 // -- has a class type (i.e., T2 is a class type), where T1 is 4163 // not reference-related to T2, and can be implicitly 4164 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4165 // is reference-compatible with "cv3 T3" 92) (this 4166 // conversion is selected by enumerating the applicable 4167 // conversion functions (13.3.1.6) and choosing the best 4168 // one through overload resolution (13.3)), 4169 if (!SuppressUserConversions && T2->isRecordType() && 4170 !S.RequireCompleteType(DeclLoc, T2, 0) && 4171 RefRelationship == Sema::Ref_Incompatible) { 4172 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4173 Init, T2, /*AllowRvalues=*/false, 4174 AllowExplicit)) 4175 return ICS; 4176 } 4177 } 4178 4179 // -- Otherwise, the reference shall be an lvalue reference to a 4180 // non-volatile const type (i.e., cv1 shall be const), or the reference 4181 // shall be an rvalue reference. 4182 // 4183 // We actually handle one oddity of C++ [over.ics.ref] at this 4184 // point, which is that, due to p2 (which short-circuits reference 4185 // binding by only attempting a simple conversion for non-direct 4186 // bindings) and p3's strange wording, we allow a const volatile 4187 // reference to bind to an rvalue. Hence the check for the presence 4188 // of "const" rather than checking for "const" being the only 4189 // qualifier. 4190 // This is also the point where rvalue references and lvalue inits no longer 4191 // go together. 4192 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4193 return ICS; 4194 4195 // -- If the initializer expression 4196 // 4197 // -- is an xvalue, class prvalue, array prvalue or function 4198 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4199 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4200 (InitCategory.isXValue() || 4201 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4202 (InitCategory.isLValue() && T2->isFunctionType()))) { 4203 ICS.setStandard(); 4204 ICS.Standard.First = ICK_Identity; 4205 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4206 : ObjCConversion? ICK_Compatible_Conversion 4207 : ICK_Identity; 4208 ICS.Standard.Third = ICK_Identity; 4209 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4210 ICS.Standard.setToType(0, T2); 4211 ICS.Standard.setToType(1, T1); 4212 ICS.Standard.setToType(2, T1); 4213 ICS.Standard.ReferenceBinding = true; 4214 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4215 // binding unless we're binding to a class prvalue. 4216 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4217 // allow the use of rvalue references in C++98/03 for the benefit of 4218 // standard library implementors; therefore, we need the xvalue check here. 4219 ICS.Standard.DirectBinding = 4220 S.getLangOpts().CPlusPlus0x || 4221 (InitCategory.isPRValue() && !T2->isRecordType()); 4222 ICS.Standard.IsLvalueReference = !isRValRef; 4223 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4224 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4225 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4226 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4227 ICS.Standard.CopyConstructor = 0; 4228 return ICS; 4229 } 4230 4231 // -- has a class type (i.e., T2 is a class type), where T1 is not 4232 // reference-related to T2, and can be implicitly converted to 4233 // an xvalue, class prvalue, or function lvalue of type 4234 // "cv3 T3", where "cv1 T1" is reference-compatible with 4235 // "cv3 T3", 4236 // 4237 // then the reference is bound to the value of the initializer 4238 // expression in the first case and to the result of the conversion 4239 // in the second case (or, in either case, to an appropriate base 4240 // class subobject). 4241 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4242 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4243 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4244 Init, T2, /*AllowRvalues=*/true, 4245 AllowExplicit)) { 4246 // In the second case, if the reference is an rvalue reference 4247 // and the second standard conversion sequence of the 4248 // user-defined conversion sequence includes an lvalue-to-rvalue 4249 // conversion, the program is ill-formed. 4250 if (ICS.isUserDefined() && isRValRef && 4251 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4252 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4253 4254 return ICS; 4255 } 4256 4257 // -- Otherwise, a temporary of type "cv1 T1" is created and 4258 // initialized from the initializer expression using the 4259 // rules for a non-reference copy initialization (8.5). The 4260 // reference is then bound to the temporary. If T1 is 4261 // reference-related to T2, cv1 must be the same 4262 // cv-qualification as, or greater cv-qualification than, 4263 // cv2; otherwise, the program is ill-formed. 4264 if (RefRelationship == Sema::Ref_Related) { 4265 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4266 // we would be reference-compatible or reference-compatible with 4267 // added qualification. But that wasn't the case, so the reference 4268 // initialization fails. 4269 // 4270 // Note that we only want to check address spaces and cvr-qualifiers here. 4271 // ObjC GC and lifetime qualifiers aren't important. 4272 Qualifiers T1Quals = T1.getQualifiers(); 4273 Qualifiers T2Quals = T2.getQualifiers(); 4274 T1Quals.removeObjCGCAttr(); 4275 T1Quals.removeObjCLifetime(); 4276 T2Quals.removeObjCGCAttr(); 4277 T2Quals.removeObjCLifetime(); 4278 if (!T1Quals.compatiblyIncludes(T2Quals)) 4279 return ICS; 4280 } 4281 4282 // If at least one of the types is a class type, the types are not 4283 // related, and we aren't allowed any user conversions, the 4284 // reference binding fails. This case is important for breaking 4285 // recursion, since TryImplicitConversion below will attempt to 4286 // create a temporary through the use of a copy constructor. 4287 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4288 (T1->isRecordType() || T2->isRecordType())) 4289 return ICS; 4290 4291 // If T1 is reference-related to T2 and the reference is an rvalue 4292 // reference, the initializer expression shall not be an lvalue. 4293 if (RefRelationship >= Sema::Ref_Related && 4294 isRValRef && Init->Classify(S.Context).isLValue()) 4295 return ICS; 4296 4297 // C++ [over.ics.ref]p2: 4298 // When a parameter of reference type is not bound directly to 4299 // an argument expression, the conversion sequence is the one 4300 // required to convert the argument expression to the 4301 // underlying type of the reference according to 4302 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4303 // to copy-initializing a temporary of the underlying type with 4304 // the argument expression. Any difference in top-level 4305 // cv-qualification is subsumed by the initialization itself 4306 // and does not constitute a conversion. 4307 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4308 /*AllowExplicit=*/false, 4309 /*InOverloadResolution=*/false, 4310 /*CStyle=*/false, 4311 /*AllowObjCWritebackConversion=*/false); 4312 4313 // Of course, that's still a reference binding. 4314 if (ICS.isStandard()) { 4315 ICS.Standard.ReferenceBinding = true; 4316 ICS.Standard.IsLvalueReference = !isRValRef; 4317 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4318 ICS.Standard.BindsToRvalue = true; 4319 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4320 ICS.Standard.ObjCLifetimeConversionBinding = false; 4321 } else if (ICS.isUserDefined()) { 4322 // Don't allow rvalue references to bind to lvalues. 4323 if (DeclType->isRValueReferenceType()) { 4324 if (const ReferenceType *RefType 4325 = ICS.UserDefined.ConversionFunction->getResultType() 4326 ->getAs<LValueReferenceType>()) { 4327 if (!RefType->getPointeeType()->isFunctionType()) { 4328 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, 4329 DeclType); 4330 return ICS; 4331 } 4332 } 4333 } 4334 4335 ICS.UserDefined.After.ReferenceBinding = true; 4336 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4337 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType(); 4338 ICS.UserDefined.After.BindsToRvalue = true; 4339 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4340 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4341 } 4342 4343 return ICS; 4344 } 4345 4346 static ImplicitConversionSequence 4347 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4348 bool SuppressUserConversions, 4349 bool InOverloadResolution, 4350 bool AllowObjCWritebackConversion, 4351 bool AllowExplicit = false); 4352 4353 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4354 /// initializer list From. 4355 static ImplicitConversionSequence 4356 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4357 bool SuppressUserConversions, 4358 bool InOverloadResolution, 4359 bool AllowObjCWritebackConversion) { 4360 // C++11 [over.ics.list]p1: 4361 // When an argument is an initializer list, it is not an expression and 4362 // special rules apply for converting it to a parameter type. 4363 4364 ImplicitConversionSequence Result; 4365 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4366 Result.setListInitializationSequence(); 4367 4368 // We need a complete type for what follows. Incomplete types can never be 4369 // initialized from init lists. 4370 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4371 return Result; 4372 4373 // C++11 [over.ics.list]p2: 4374 // If the parameter type is std::initializer_list<X> or "array of X" and 4375 // all the elements can be implicitly converted to X, the implicit 4376 // conversion sequence is the worst conversion necessary to convert an 4377 // element of the list to X. 4378 bool toStdInitializerList = false; 4379 QualType X; 4380 if (ToType->isArrayType()) 4381 X = S.Context.getBaseElementType(ToType); 4382 else 4383 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4384 if (!X.isNull()) { 4385 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4386 Expr *Init = From->getInit(i); 4387 ImplicitConversionSequence ICS = 4388 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4389 InOverloadResolution, 4390 AllowObjCWritebackConversion); 4391 // If a single element isn't convertible, fail. 4392 if (ICS.isBad()) { 4393 Result = ICS; 4394 break; 4395 } 4396 // Otherwise, look for the worst conversion. 4397 if (Result.isBad() || 4398 CompareImplicitConversionSequences(S, ICS, Result) == 4399 ImplicitConversionSequence::Worse) 4400 Result = ICS; 4401 } 4402 4403 // For an empty list, we won't have computed any conversion sequence. 4404 // Introduce the identity conversion sequence. 4405 if (From->getNumInits() == 0) { 4406 Result.setStandard(); 4407 Result.Standard.setAsIdentityConversion(); 4408 Result.Standard.setFromType(ToType); 4409 Result.Standard.setAllToTypes(ToType); 4410 } 4411 4412 Result.setListInitializationSequence(); 4413 Result.setStdInitializerListElement(toStdInitializerList); 4414 return Result; 4415 } 4416 4417 // C++11 [over.ics.list]p3: 4418 // Otherwise, if the parameter is a non-aggregate class X and overload 4419 // resolution chooses a single best constructor [...] the implicit 4420 // conversion sequence is a user-defined conversion sequence. If multiple 4421 // constructors are viable but none is better than the others, the 4422 // implicit conversion sequence is a user-defined conversion sequence. 4423 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4424 // This function can deal with initializer lists. 4425 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4426 /*AllowExplicit=*/false, 4427 InOverloadResolution, /*CStyle=*/false, 4428 AllowObjCWritebackConversion); 4429 Result.setListInitializationSequence(); 4430 return Result; 4431 } 4432 4433 // C++11 [over.ics.list]p4: 4434 // Otherwise, if the parameter has an aggregate type which can be 4435 // initialized from the initializer list [...] the implicit conversion 4436 // sequence is a user-defined conversion sequence. 4437 if (ToType->isAggregateType()) { 4438 // Type is an aggregate, argument is an init list. At this point it comes 4439 // down to checking whether the initialization works. 4440 // FIXME: Find out whether this parameter is consumed or not. 4441 InitializedEntity Entity = 4442 InitializedEntity::InitializeParameter(S.Context, ToType, 4443 /*Consumed=*/false); 4444 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) { 4445 Result.setUserDefined(); 4446 Result.UserDefined.Before.setAsIdentityConversion(); 4447 // Initializer lists don't have a type. 4448 Result.UserDefined.Before.setFromType(QualType()); 4449 Result.UserDefined.Before.setAllToTypes(QualType()); 4450 4451 Result.UserDefined.After.setAsIdentityConversion(); 4452 Result.UserDefined.After.setFromType(ToType); 4453 Result.UserDefined.After.setAllToTypes(ToType); 4454 Result.UserDefined.ConversionFunction = 0; 4455 } 4456 return Result; 4457 } 4458 4459 // C++11 [over.ics.list]p5: 4460 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4461 if (ToType->isReferenceType()) { 4462 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4463 // mention initializer lists in any way. So we go by what list- 4464 // initialization would do and try to extrapolate from that. 4465 4466 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4467 4468 // If the initializer list has a single element that is reference-related 4469 // to the parameter type, we initialize the reference from that. 4470 if (From->getNumInits() == 1) { 4471 Expr *Init = From->getInit(0); 4472 4473 QualType T2 = Init->getType(); 4474 4475 // If the initializer is the address of an overloaded function, try 4476 // to resolve the overloaded function. If all goes well, T2 is the 4477 // type of the resulting function. 4478 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4479 DeclAccessPair Found; 4480 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4481 Init, ToType, false, Found)) 4482 T2 = Fn->getType(); 4483 } 4484 4485 // Compute some basic properties of the types and the initializer. 4486 bool dummy1 = false; 4487 bool dummy2 = false; 4488 bool dummy3 = false; 4489 Sema::ReferenceCompareResult RefRelationship 4490 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4491 dummy2, dummy3); 4492 4493 if (RefRelationship >= Sema::Ref_Related) 4494 return TryReferenceInit(S, Init, ToType, 4495 /*FIXME:*/From->getLocStart(), 4496 SuppressUserConversions, 4497 /*AllowExplicit=*/false); 4498 } 4499 4500 // Otherwise, we bind the reference to a temporary created from the 4501 // initializer list. 4502 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4503 InOverloadResolution, 4504 AllowObjCWritebackConversion); 4505 if (Result.isFailure()) 4506 return Result; 4507 assert(!Result.isEllipsis() && 4508 "Sub-initialization cannot result in ellipsis conversion."); 4509 4510 // Can we even bind to a temporary? 4511 if (ToType->isRValueReferenceType() || 4512 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4513 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4514 Result.UserDefined.After; 4515 SCS.ReferenceBinding = true; 4516 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4517 SCS.BindsToRvalue = true; 4518 SCS.BindsToFunctionLvalue = false; 4519 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4520 SCS.ObjCLifetimeConversionBinding = false; 4521 } else 4522 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4523 From, ToType); 4524 return Result; 4525 } 4526 4527 // C++11 [over.ics.list]p6: 4528 // Otherwise, if the parameter type is not a class: 4529 if (!ToType->isRecordType()) { 4530 // - if the initializer list has one element, the implicit conversion 4531 // sequence is the one required to convert the element to the 4532 // parameter type. 4533 unsigned NumInits = From->getNumInits(); 4534 if (NumInits == 1) 4535 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4536 SuppressUserConversions, 4537 InOverloadResolution, 4538 AllowObjCWritebackConversion); 4539 // - if the initializer list has no elements, the implicit conversion 4540 // sequence is the identity conversion. 4541 else if (NumInits == 0) { 4542 Result.setStandard(); 4543 Result.Standard.setAsIdentityConversion(); 4544 Result.Standard.setFromType(ToType); 4545 Result.Standard.setAllToTypes(ToType); 4546 } 4547 Result.setListInitializationSequence(); 4548 return Result; 4549 } 4550 4551 // C++11 [over.ics.list]p7: 4552 // In all cases other than those enumerated above, no conversion is possible 4553 return Result; 4554 } 4555 4556 /// TryCopyInitialization - Try to copy-initialize a value of type 4557 /// ToType from the expression From. Return the implicit conversion 4558 /// sequence required to pass this argument, which may be a bad 4559 /// conversion sequence (meaning that the argument cannot be passed to 4560 /// a parameter of this type). If @p SuppressUserConversions, then we 4561 /// do not permit any user-defined conversion sequences. 4562 static ImplicitConversionSequence 4563 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4564 bool SuppressUserConversions, 4565 bool InOverloadResolution, 4566 bool AllowObjCWritebackConversion, 4567 bool AllowExplicit) { 4568 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4569 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4570 InOverloadResolution,AllowObjCWritebackConversion); 4571 4572 if (ToType->isReferenceType()) 4573 return TryReferenceInit(S, From, ToType, 4574 /*FIXME:*/From->getLocStart(), 4575 SuppressUserConversions, 4576 AllowExplicit); 4577 4578 return TryImplicitConversion(S, From, ToType, 4579 SuppressUserConversions, 4580 /*AllowExplicit=*/false, 4581 InOverloadResolution, 4582 /*CStyle=*/false, 4583 AllowObjCWritebackConversion); 4584 } 4585 4586 static bool TryCopyInitialization(const CanQualType FromQTy, 4587 const CanQualType ToQTy, 4588 Sema &S, 4589 SourceLocation Loc, 4590 ExprValueKind FromVK) { 4591 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4592 ImplicitConversionSequence ICS = 4593 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4594 4595 return !ICS.isBad(); 4596 } 4597 4598 /// TryObjectArgumentInitialization - Try to initialize the object 4599 /// parameter of the given member function (@c Method) from the 4600 /// expression @p From. 4601 static ImplicitConversionSequence 4602 TryObjectArgumentInitialization(Sema &S, QualType OrigFromType, 4603 Expr::Classification FromClassification, 4604 CXXMethodDecl *Method, 4605 CXXRecordDecl *ActingContext) { 4606 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4607 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4608 // const volatile object. 4609 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4610 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4611 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4612 4613 // Set up the conversion sequence as a "bad" conversion, to allow us 4614 // to exit early. 4615 ImplicitConversionSequence ICS; 4616 4617 // We need to have an object of class type. 4618 QualType FromType = OrigFromType; 4619 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4620 FromType = PT->getPointeeType(); 4621 4622 // When we had a pointer, it's implicitly dereferenced, so we 4623 // better have an lvalue. 4624 assert(FromClassification.isLValue()); 4625 } 4626 4627 assert(FromType->isRecordType()); 4628 4629 // C++0x [over.match.funcs]p4: 4630 // For non-static member functions, the type of the implicit object 4631 // parameter is 4632 // 4633 // - "lvalue reference to cv X" for functions declared without a 4634 // ref-qualifier or with the & ref-qualifier 4635 // - "rvalue reference to cv X" for functions declared with the && 4636 // ref-qualifier 4637 // 4638 // where X is the class of which the function is a member and cv is the 4639 // cv-qualification on the member function declaration. 4640 // 4641 // However, when finding an implicit conversion sequence for the argument, we 4642 // are not allowed to create temporaries or perform user-defined conversions 4643 // (C++ [over.match.funcs]p5). We perform a simplified version of 4644 // reference binding here, that allows class rvalues to bind to 4645 // non-constant references. 4646 4647 // First check the qualifiers. 4648 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4649 if (ImplicitParamType.getCVRQualifiers() 4650 != FromTypeCanon.getLocalCVRQualifiers() && 4651 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4652 ICS.setBad(BadConversionSequence::bad_qualifiers, 4653 OrigFromType, ImplicitParamType); 4654 return ICS; 4655 } 4656 4657 // Check that we have either the same type or a derived type. It 4658 // affects the conversion rank. 4659 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4660 ImplicitConversionKind SecondKind; 4661 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4662 SecondKind = ICK_Identity; 4663 } else if (S.IsDerivedFrom(FromType, ClassType)) 4664 SecondKind = ICK_Derived_To_Base; 4665 else { 4666 ICS.setBad(BadConversionSequence::unrelated_class, 4667 FromType, ImplicitParamType); 4668 return ICS; 4669 } 4670 4671 // Check the ref-qualifier. 4672 switch (Method->getRefQualifier()) { 4673 case RQ_None: 4674 // Do nothing; we don't care about lvalueness or rvalueness. 4675 break; 4676 4677 case RQ_LValue: 4678 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4679 // non-const lvalue reference cannot bind to an rvalue 4680 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4681 ImplicitParamType); 4682 return ICS; 4683 } 4684 break; 4685 4686 case RQ_RValue: 4687 if (!FromClassification.isRValue()) { 4688 // rvalue reference cannot bind to an lvalue 4689 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4690 ImplicitParamType); 4691 return ICS; 4692 } 4693 break; 4694 } 4695 4696 // Success. Mark this as a reference binding. 4697 ICS.setStandard(); 4698 ICS.Standard.setAsIdentityConversion(); 4699 ICS.Standard.Second = SecondKind; 4700 ICS.Standard.setFromType(FromType); 4701 ICS.Standard.setAllToTypes(ImplicitParamType); 4702 ICS.Standard.ReferenceBinding = true; 4703 ICS.Standard.DirectBinding = true; 4704 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4705 ICS.Standard.BindsToFunctionLvalue = false; 4706 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4707 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4708 = (Method->getRefQualifier() == RQ_None); 4709 return ICS; 4710 } 4711 4712 /// PerformObjectArgumentInitialization - Perform initialization of 4713 /// the implicit object parameter for the given Method with the given 4714 /// expression. 4715 ExprResult 4716 Sema::PerformObjectArgumentInitialization(Expr *From, 4717 NestedNameSpecifier *Qualifier, 4718 NamedDecl *FoundDecl, 4719 CXXMethodDecl *Method) { 4720 QualType FromRecordType, DestType; 4721 QualType ImplicitParamRecordType = 4722 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4723 4724 Expr::Classification FromClassification; 4725 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4726 FromRecordType = PT->getPointeeType(); 4727 DestType = Method->getThisType(Context); 4728 FromClassification = Expr::Classification::makeSimpleLValue(); 4729 } else { 4730 FromRecordType = From->getType(); 4731 DestType = ImplicitParamRecordType; 4732 FromClassification = From->Classify(Context); 4733 } 4734 4735 // Note that we always use the true parent context when performing 4736 // the actual argument initialization. 4737 ImplicitConversionSequence ICS 4738 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification, 4739 Method, Method->getParent()); 4740 if (ICS.isBad()) { 4741 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4742 Qualifiers FromQs = FromRecordType.getQualifiers(); 4743 Qualifiers ToQs = DestType.getQualifiers(); 4744 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4745 if (CVR) { 4746 Diag(From->getLocStart(), 4747 diag::err_member_function_call_bad_cvr) 4748 << Method->getDeclName() << FromRecordType << (CVR - 1) 4749 << From->getSourceRange(); 4750 Diag(Method->getLocation(), diag::note_previous_decl) 4751 << Method->getDeclName(); 4752 return ExprError(); 4753 } 4754 } 4755 4756 return Diag(From->getLocStart(), 4757 diag::err_implicit_object_parameter_init) 4758 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4759 } 4760 4761 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4762 ExprResult FromRes = 4763 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4764 if (FromRes.isInvalid()) 4765 return ExprError(); 4766 From = FromRes.take(); 4767 } 4768 4769 if (!Context.hasSameType(From->getType(), DestType)) 4770 From = ImpCastExprToType(From, DestType, CK_NoOp, 4771 From->getValueKind()).take(); 4772 return Owned(From); 4773 } 4774 4775 /// TryContextuallyConvertToBool - Attempt to contextually convert the 4776 /// expression From to bool (C++0x [conv]p3). 4777 static ImplicitConversionSequence 4778 TryContextuallyConvertToBool(Sema &S, Expr *From) { 4779 // FIXME: This is pretty broken. 4780 return TryImplicitConversion(S, From, S.Context.BoolTy, 4781 // FIXME: Are these flags correct? 4782 /*SuppressUserConversions=*/false, 4783 /*AllowExplicit=*/true, 4784 /*InOverloadResolution=*/false, 4785 /*CStyle=*/false, 4786 /*AllowObjCWritebackConversion=*/false); 4787 } 4788 4789 /// PerformContextuallyConvertToBool - Perform a contextual conversion 4790 /// of the expression From to bool (C++0x [conv]p3). 4791 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4792 if (checkPlaceholderForOverload(*this, From)) 4793 return ExprError(); 4794 4795 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4796 if (!ICS.isBad()) 4797 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4798 4799 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4800 return Diag(From->getLocStart(), 4801 diag::err_typecheck_bool_condition) 4802 << From->getType() << From->getSourceRange(); 4803 return ExprError(); 4804 } 4805 4806 /// Check that the specified conversion is permitted in a converted constant 4807 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 4808 /// is acceptable. 4809 static bool CheckConvertedConstantConversions(Sema &S, 4810 StandardConversionSequence &SCS) { 4811 // Since we know that the target type is an integral or unscoped enumeration 4812 // type, most conversion kinds are impossible. All possible First and Third 4813 // conversions are fine. 4814 switch (SCS.Second) { 4815 case ICK_Identity: 4816 case ICK_Integral_Promotion: 4817 case ICK_Integral_Conversion: 4818 return true; 4819 4820 case ICK_Boolean_Conversion: 4821 // Conversion from an integral or unscoped enumeration type to bool is 4822 // classified as ICK_Boolean_Conversion, but it's also an integral 4823 // conversion, so it's permitted in a converted constant expression. 4824 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4825 SCS.getToType(2)->isBooleanType(); 4826 4827 case ICK_Floating_Integral: 4828 case ICK_Complex_Real: 4829 return false; 4830 4831 case ICK_Lvalue_To_Rvalue: 4832 case ICK_Array_To_Pointer: 4833 case ICK_Function_To_Pointer: 4834 case ICK_NoReturn_Adjustment: 4835 case ICK_Qualification: 4836 case ICK_Compatible_Conversion: 4837 case ICK_Vector_Conversion: 4838 case ICK_Vector_Splat: 4839 case ICK_Derived_To_Base: 4840 case ICK_Pointer_Conversion: 4841 case ICK_Pointer_Member: 4842 case ICK_Block_Pointer_Conversion: 4843 case ICK_Writeback_Conversion: 4844 case ICK_Floating_Promotion: 4845 case ICK_Complex_Promotion: 4846 case ICK_Complex_Conversion: 4847 case ICK_Floating_Conversion: 4848 case ICK_TransparentUnionConversion: 4849 llvm_unreachable("unexpected second conversion kind"); 4850 4851 case ICK_Num_Conversion_Kinds: 4852 break; 4853 } 4854 4855 llvm_unreachable("unknown conversion kind"); 4856 } 4857 4858 /// CheckConvertedConstantExpression - Check that the expression From is a 4859 /// converted constant expression of type T, perform the conversion and produce 4860 /// the converted expression, per C++11 [expr.const]p3. 4861 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 4862 llvm::APSInt &Value, 4863 CCEKind CCE) { 4864 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11"); 4865 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 4866 4867 if (checkPlaceholderForOverload(*this, From)) 4868 return ExprError(); 4869 4870 // C++11 [expr.const]p3 with proposed wording fixes: 4871 // A converted constant expression of type T is a core constant expression, 4872 // implicitly converted to a prvalue of type T, where the converted 4873 // expression is a literal constant expression and the implicit conversion 4874 // sequence contains only user-defined conversions, lvalue-to-rvalue 4875 // conversions, integral promotions, and integral conversions other than 4876 // narrowing conversions. 4877 ImplicitConversionSequence ICS = 4878 TryImplicitConversion(From, T, 4879 /*SuppressUserConversions=*/false, 4880 /*AllowExplicit=*/false, 4881 /*InOverloadResolution=*/false, 4882 /*CStyle=*/false, 4883 /*AllowObjcWritebackConversion=*/false); 4884 StandardConversionSequence *SCS = 0; 4885 switch (ICS.getKind()) { 4886 case ImplicitConversionSequence::StandardConversion: 4887 if (!CheckConvertedConstantConversions(*this, ICS.Standard)) 4888 return Diag(From->getLocStart(), 4889 diag::err_typecheck_converted_constant_expression_disallowed) 4890 << From->getType() << From->getSourceRange() << T; 4891 SCS = &ICS.Standard; 4892 break; 4893 case ImplicitConversionSequence::UserDefinedConversion: 4894 // We are converting from class type to an integral or enumeration type, so 4895 // the Before sequence must be trivial. 4896 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After)) 4897 return Diag(From->getLocStart(), 4898 diag::err_typecheck_converted_constant_expression_disallowed) 4899 << From->getType() << From->getSourceRange() << T; 4900 SCS = &ICS.UserDefined.After; 4901 break; 4902 case ImplicitConversionSequence::AmbiguousConversion: 4903 case ImplicitConversionSequence::BadConversion: 4904 if (!DiagnoseMultipleUserDefinedConversion(From, T)) 4905 return Diag(From->getLocStart(), 4906 diag::err_typecheck_converted_constant_expression) 4907 << From->getType() << From->getSourceRange() << T; 4908 return ExprError(); 4909 4910 case ImplicitConversionSequence::EllipsisConversion: 4911 llvm_unreachable("ellipsis conversion in converted constant expression"); 4912 } 4913 4914 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting); 4915 if (Result.isInvalid()) 4916 return Result; 4917 4918 // Check for a narrowing implicit conversion. 4919 APValue PreNarrowingValue; 4920 QualType PreNarrowingType; 4921 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue, 4922 PreNarrowingType)) { 4923 case NK_Variable_Narrowing: 4924 // Implicit conversion to a narrower type, and the value is not a constant 4925 // expression. We'll diagnose this in a moment. 4926 case NK_Not_Narrowing: 4927 break; 4928 4929 case NK_Constant_Narrowing: 4930 Diag(From->getLocStart(), 4931 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4932 diag::err_cce_narrowing) 4933 << CCE << /*Constant*/1 4934 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T; 4935 break; 4936 4937 case NK_Type_Narrowing: 4938 Diag(From->getLocStart(), 4939 isSFINAEContext() ? diag::err_cce_narrowing_sfinae : 4940 diag::err_cce_narrowing) 4941 << CCE << /*Constant*/0 << From->getType() << T; 4942 break; 4943 } 4944 4945 // Check the expression is a constant expression. 4946 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 4947 Expr::EvalResult Eval; 4948 Eval.Diag = &Notes; 4949 4950 if (!Result.get()->EvaluateAsRValue(Eval, Context)) { 4951 // The expression can't be folded, so we can't keep it at this position in 4952 // the AST. 4953 Result = ExprError(); 4954 } else { 4955 Value = Eval.Val.getInt(); 4956 4957 if (Notes.empty()) { 4958 // It's a constant expression. 4959 return Result; 4960 } 4961 } 4962 4963 // It's not a constant expression. Produce an appropriate diagnostic. 4964 if (Notes.size() == 1 && 4965 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 4966 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 4967 else { 4968 Diag(From->getLocStart(), diag::err_expr_not_cce) 4969 << CCE << From->getSourceRange(); 4970 for (unsigned I = 0; I < Notes.size(); ++I) 4971 Diag(Notes[I].first, Notes[I].second); 4972 } 4973 return Result; 4974 } 4975 4976 /// dropPointerConversions - If the given standard conversion sequence 4977 /// involves any pointer conversions, remove them. This may change 4978 /// the result type of the conversion sequence. 4979 static void dropPointerConversion(StandardConversionSequence &SCS) { 4980 if (SCS.Second == ICK_Pointer_Conversion) { 4981 SCS.Second = ICK_Identity; 4982 SCS.Third = ICK_Identity; 4983 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 4984 } 4985 } 4986 4987 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 4988 /// convert the expression From to an Objective-C pointer type. 4989 static ImplicitConversionSequence 4990 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 4991 // Do an implicit conversion to 'id'. 4992 QualType Ty = S.Context.getObjCIdType(); 4993 ImplicitConversionSequence ICS 4994 = TryImplicitConversion(S, From, Ty, 4995 // FIXME: Are these flags correct? 4996 /*SuppressUserConversions=*/false, 4997 /*AllowExplicit=*/true, 4998 /*InOverloadResolution=*/false, 4999 /*CStyle=*/false, 5000 /*AllowObjCWritebackConversion=*/false); 5001 5002 // Strip off any final conversions to 'id'. 5003 switch (ICS.getKind()) { 5004 case ImplicitConversionSequence::BadConversion: 5005 case ImplicitConversionSequence::AmbiguousConversion: 5006 case ImplicitConversionSequence::EllipsisConversion: 5007 break; 5008 5009 case ImplicitConversionSequence::UserDefinedConversion: 5010 dropPointerConversion(ICS.UserDefined.After); 5011 break; 5012 5013 case ImplicitConversionSequence::StandardConversion: 5014 dropPointerConversion(ICS.Standard); 5015 break; 5016 } 5017 5018 return ICS; 5019 } 5020 5021 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5022 /// conversion of the expression From to an Objective-C pointer type. 5023 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5024 if (checkPlaceholderForOverload(*this, From)) 5025 return ExprError(); 5026 5027 QualType Ty = Context.getObjCIdType(); 5028 ImplicitConversionSequence ICS = 5029 TryContextuallyConvertToObjCPointer(*this, From); 5030 if (!ICS.isBad()) 5031 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5032 return ExprError(); 5033 } 5034 5035 /// Determine whether the provided type is an integral type, or an enumeration 5036 /// type of a permitted flavor. 5037 static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) { 5038 return AllowScopedEnum ? T->isIntegralOrEnumerationType() 5039 : T->isIntegralOrUnscopedEnumerationType(); 5040 } 5041 5042 /// \brief Attempt to convert the given expression to an integral or 5043 /// enumeration type. 5044 /// 5045 /// This routine will attempt to convert an expression of class type to an 5046 /// integral or enumeration type, if that class type only has a single 5047 /// conversion to an integral or enumeration type. 5048 /// 5049 /// \param Loc The source location of the construct that requires the 5050 /// conversion. 5051 /// 5052 /// \param From The expression we're converting from. 5053 /// 5054 /// \param Diagnoser Used to output any diagnostics. 5055 /// 5056 /// \param AllowScopedEnumerations Specifies whether conversions to scoped 5057 /// enumerations should be considered. 5058 /// 5059 /// \returns The expression, converted to an integral or enumeration type if 5060 /// successful. 5061 ExprResult 5062 Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From, 5063 ICEConvertDiagnoser &Diagnoser, 5064 bool AllowScopedEnumerations) { 5065 // We can't perform any more checking for type-dependent expressions. 5066 if (From->isTypeDependent()) 5067 return Owned(From); 5068 5069 // Process placeholders immediately. 5070 if (From->hasPlaceholderType()) { 5071 ExprResult result = CheckPlaceholderExpr(From); 5072 if (result.isInvalid()) return result; 5073 From = result.take(); 5074 } 5075 5076 // If the expression already has integral or enumeration type, we're golden. 5077 QualType T = From->getType(); 5078 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations)) 5079 return DefaultLvalueConversion(From); 5080 5081 // FIXME: Check for missing '()' if T is a function type? 5082 5083 // If we don't have a class type in C++, there's no way we can get an 5084 // expression of integral or enumeration type. 5085 const RecordType *RecordTy = T->getAs<RecordType>(); 5086 if (!RecordTy || !getLangOpts().CPlusPlus) { 5087 if (!Diagnoser.Suppress) 5088 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange(); 5089 return Owned(From); 5090 } 5091 5092 // We must have a complete class type. 5093 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5094 ICEConvertDiagnoser &Diagnoser; 5095 Expr *From; 5096 5097 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From) 5098 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {} 5099 5100 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 5101 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5102 } 5103 } IncompleteDiagnoser(Diagnoser, From); 5104 5105 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5106 return Owned(From); 5107 5108 // Look for a conversion to an integral or enumeration type. 5109 UnresolvedSet<4> ViableConversions; 5110 UnresolvedSet<4> ExplicitConversions; 5111 const UnresolvedSetImpl *Conversions 5112 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5113 5114 bool HadMultipleCandidates = (Conversions->size() > 1); 5115 5116 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 5117 E = Conversions->end(); 5118 I != E; 5119 ++I) { 5120 if (CXXConversionDecl *Conversion 5121 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) { 5122 if (isIntegralOrEnumerationType( 5123 Conversion->getConversionType().getNonReferenceType(), 5124 AllowScopedEnumerations)) { 5125 if (Conversion->isExplicit()) 5126 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5127 else 5128 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5129 } 5130 } 5131 } 5132 5133 switch (ViableConversions.size()) { 5134 case 0: 5135 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) { 5136 DeclAccessPair Found = ExplicitConversions[0]; 5137 CXXConversionDecl *Conversion 5138 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5139 5140 // The user probably meant to invoke the given explicit 5141 // conversion; use it. 5142 QualType ConvTy 5143 = Conversion->getConversionType().getNonReferenceType(); 5144 std::string TypeStr; 5145 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy()); 5146 5147 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy) 5148 << FixItHint::CreateInsertion(From->getLocStart(), 5149 "static_cast<" + TypeStr + ">(") 5150 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()), 5151 ")"); 5152 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy); 5153 5154 // If we aren't in a SFINAE context, build a call to the 5155 // explicit conversion function. 5156 if (isSFINAEContext()) 5157 return ExprError(); 5158 5159 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5160 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion, 5161 HadMultipleCandidates); 5162 if (Result.isInvalid()) 5163 return ExprError(); 5164 // Record usage of conversion in an implicit cast. 5165 From = ImplicitCastExpr::Create(Context, Result.get()->getType(), 5166 CK_UserDefinedConversion, 5167 Result.get(), 0, 5168 Result.get()->getValueKind()); 5169 } 5170 5171 // We'll complain below about a non-integral condition type. 5172 break; 5173 5174 case 1: { 5175 // Apply this conversion. 5176 DeclAccessPair Found = ViableConversions[0]; 5177 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5178 5179 CXXConversionDecl *Conversion 5180 = cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5181 QualType ConvTy 5182 = Conversion->getConversionType().getNonReferenceType(); 5183 if (!Diagnoser.SuppressConversion) { 5184 if (isSFINAEContext()) 5185 return ExprError(); 5186 5187 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy) 5188 << From->getSourceRange(); 5189 } 5190 5191 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion, 5192 HadMultipleCandidates); 5193 if (Result.isInvalid()) 5194 return ExprError(); 5195 // Record usage of conversion in an implicit cast. 5196 From = ImplicitCastExpr::Create(Context, Result.get()->getType(), 5197 CK_UserDefinedConversion, 5198 Result.get(), 0, 5199 Result.get()->getValueKind()); 5200 break; 5201 } 5202 5203 default: 5204 if (Diagnoser.Suppress) 5205 return ExprError(); 5206 5207 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange(); 5208 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5209 CXXConversionDecl *Conv 5210 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5211 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5212 Diagnoser.noteAmbiguous(*this, Conv, ConvTy); 5213 } 5214 return Owned(From); 5215 } 5216 5217 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) && 5218 !Diagnoser.Suppress) { 5219 Diagnoser.diagnoseNotInt(*this, Loc, From->getType()) 5220 << From->getSourceRange(); 5221 } 5222 5223 return DefaultLvalueConversion(From); 5224 } 5225 5226 /// AddOverloadCandidate - Adds the given function to the set of 5227 /// candidate functions, using the given function call arguments. If 5228 /// @p SuppressUserConversions, then don't allow user-defined 5229 /// conversions via constructors or conversion operators. 5230 /// 5231 /// \param PartialOverloading true if we are performing "partial" overloading 5232 /// based on an incomplete set of function arguments. This feature is used by 5233 /// code completion. 5234 void 5235 Sema::AddOverloadCandidate(FunctionDecl *Function, 5236 DeclAccessPair FoundDecl, 5237 llvm::ArrayRef<Expr *> Args, 5238 OverloadCandidateSet& CandidateSet, 5239 bool SuppressUserConversions, 5240 bool PartialOverloading, 5241 bool AllowExplicit) { 5242 const FunctionProtoType* Proto 5243 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5244 assert(Proto && "Functions without a prototype cannot be overloaded"); 5245 assert(!Function->getDescribedFunctionTemplate() && 5246 "Use AddTemplateOverloadCandidate for function templates"); 5247 5248 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5249 if (!isa<CXXConstructorDecl>(Method)) { 5250 // If we get here, it's because we're calling a member function 5251 // that is named without a member access expression (e.g., 5252 // "this->f") that was either written explicitly or created 5253 // implicitly. This can happen with a qualified call to a member 5254 // function, e.g., X::f(). We use an empty type for the implied 5255 // object argument (C++ [over.call.func]p3), and the acting context 5256 // is irrelevant. 5257 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5258 QualType(), Expr::Classification::makeSimpleLValue(), 5259 Args, CandidateSet, SuppressUserConversions); 5260 return; 5261 } 5262 // We treat a constructor like a non-member function, since its object 5263 // argument doesn't participate in overload resolution. 5264 } 5265 5266 if (!CandidateSet.isNewCandidate(Function)) 5267 return; 5268 5269 // Overload resolution is always an unevaluated context. 5270 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5271 5272 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){ 5273 // C++ [class.copy]p3: 5274 // A member function template is never instantiated to perform the copy 5275 // of a class object to an object of its class type. 5276 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5277 if (Args.size() == 1 && 5278 Constructor->isSpecializationCopyingObject() && 5279 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5280 IsDerivedFrom(Args[0]->getType(), ClassType))) 5281 return; 5282 } 5283 5284 // Add this candidate 5285 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5286 Candidate.FoundDecl = FoundDecl; 5287 Candidate.Function = Function; 5288 Candidate.Viable = true; 5289 Candidate.IsSurrogate = false; 5290 Candidate.IgnoreObjectArgument = false; 5291 Candidate.ExplicitCallArguments = Args.size(); 5292 5293 unsigned NumArgsInProto = Proto->getNumArgs(); 5294 5295 // (C++ 13.3.2p2): A candidate function having fewer than m 5296 // parameters is viable only if it has an ellipsis in its parameter 5297 // list (8.3.5). 5298 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto && 5299 !Proto->isVariadic()) { 5300 Candidate.Viable = false; 5301 Candidate.FailureKind = ovl_fail_too_many_arguments; 5302 return; 5303 } 5304 5305 // (C++ 13.3.2p2): A candidate function having more than m parameters 5306 // is viable only if the (m+1)st parameter has a default argument 5307 // (8.3.6). For the purposes of overload resolution, the 5308 // parameter list is truncated on the right, so that there are 5309 // exactly m parameters. 5310 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5311 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5312 // Not enough arguments. 5313 Candidate.Viable = false; 5314 Candidate.FailureKind = ovl_fail_too_few_arguments; 5315 return; 5316 } 5317 5318 // (CUDA B.1): Check for invalid calls between targets. 5319 if (getLangOpts().CUDA) 5320 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5321 if (CheckCUDATarget(Caller, Function)) { 5322 Candidate.Viable = false; 5323 Candidate.FailureKind = ovl_fail_bad_target; 5324 return; 5325 } 5326 5327 // Determine the implicit conversion sequences for each of the 5328 // arguments. 5329 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5330 if (ArgIdx < NumArgsInProto) { 5331 // (C++ 13.3.2p3): for F to be a viable function, there shall 5332 // exist for each argument an implicit conversion sequence 5333 // (13.3.3.1) that converts that argument to the corresponding 5334 // parameter of F. 5335 QualType ParamType = Proto->getArgType(ArgIdx); 5336 Candidate.Conversions[ArgIdx] 5337 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5338 SuppressUserConversions, 5339 /*InOverloadResolution=*/true, 5340 /*AllowObjCWritebackConversion=*/ 5341 getLangOpts().ObjCAutoRefCount, 5342 AllowExplicit); 5343 if (Candidate.Conversions[ArgIdx].isBad()) { 5344 Candidate.Viable = false; 5345 Candidate.FailureKind = ovl_fail_bad_conversion; 5346 break; 5347 } 5348 } else { 5349 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5350 // argument for which there is no corresponding parameter is 5351 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5352 Candidate.Conversions[ArgIdx].setEllipsis(); 5353 } 5354 } 5355 } 5356 5357 /// \brief Add all of the function declarations in the given function set to 5358 /// the overload canddiate set. 5359 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5360 llvm::ArrayRef<Expr *> Args, 5361 OverloadCandidateSet& CandidateSet, 5362 bool SuppressUserConversions, 5363 TemplateArgumentListInfo *ExplicitTemplateArgs) { 5364 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5365 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5366 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5367 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5368 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5369 cast<CXXMethodDecl>(FD)->getParent(), 5370 Args[0]->getType(), Args[0]->Classify(Context), 5371 Args.slice(1), CandidateSet, 5372 SuppressUserConversions); 5373 else 5374 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5375 SuppressUserConversions); 5376 } else { 5377 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5378 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5379 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5380 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5381 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5382 ExplicitTemplateArgs, 5383 Args[0]->getType(), 5384 Args[0]->Classify(Context), Args.slice(1), 5385 CandidateSet, SuppressUserConversions); 5386 else 5387 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5388 ExplicitTemplateArgs, Args, 5389 CandidateSet, SuppressUserConversions); 5390 } 5391 } 5392 } 5393 5394 /// AddMethodCandidate - Adds a named decl (which is some kind of 5395 /// method) as a method candidate to the given overload set. 5396 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5397 QualType ObjectType, 5398 Expr::Classification ObjectClassification, 5399 Expr **Args, unsigned NumArgs, 5400 OverloadCandidateSet& CandidateSet, 5401 bool SuppressUserConversions) { 5402 NamedDecl *Decl = FoundDecl.getDecl(); 5403 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5404 5405 if (isa<UsingShadowDecl>(Decl)) 5406 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5407 5408 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5409 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5410 "Expected a member function template"); 5411 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5412 /*ExplicitArgs*/ 0, 5413 ObjectType, ObjectClassification, 5414 llvm::makeArrayRef(Args, NumArgs), CandidateSet, 5415 SuppressUserConversions); 5416 } else { 5417 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5418 ObjectType, ObjectClassification, 5419 llvm::makeArrayRef(Args, NumArgs), 5420 CandidateSet, SuppressUserConversions); 5421 } 5422 } 5423 5424 /// AddMethodCandidate - Adds the given C++ member function to the set 5425 /// of candidate functions, using the given function call arguments 5426 /// and the object argument (@c Object). For example, in a call 5427 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5428 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5429 /// allow user-defined conversions via constructors or conversion 5430 /// operators. 5431 void 5432 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5433 CXXRecordDecl *ActingContext, QualType ObjectType, 5434 Expr::Classification ObjectClassification, 5435 llvm::ArrayRef<Expr *> Args, 5436 OverloadCandidateSet& CandidateSet, 5437 bool SuppressUserConversions) { 5438 const FunctionProtoType* Proto 5439 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5440 assert(Proto && "Methods without a prototype cannot be overloaded"); 5441 assert(!isa<CXXConstructorDecl>(Method) && 5442 "Use AddOverloadCandidate for constructors"); 5443 5444 if (!CandidateSet.isNewCandidate(Method)) 5445 return; 5446 5447 // Overload resolution is always an unevaluated context. 5448 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5449 5450 // Add this candidate 5451 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5452 Candidate.FoundDecl = FoundDecl; 5453 Candidate.Function = Method; 5454 Candidate.IsSurrogate = false; 5455 Candidate.IgnoreObjectArgument = false; 5456 Candidate.ExplicitCallArguments = Args.size(); 5457 5458 unsigned NumArgsInProto = Proto->getNumArgs(); 5459 5460 // (C++ 13.3.2p2): A candidate function having fewer than m 5461 // parameters is viable only if it has an ellipsis in its parameter 5462 // list (8.3.5). 5463 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5464 Candidate.Viable = false; 5465 Candidate.FailureKind = ovl_fail_too_many_arguments; 5466 return; 5467 } 5468 5469 // (C++ 13.3.2p2): A candidate function having more than m parameters 5470 // is viable only if the (m+1)st parameter has a default argument 5471 // (8.3.6). For the purposes of overload resolution, the 5472 // parameter list is truncated on the right, so that there are 5473 // exactly m parameters. 5474 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 5475 if (Args.size() < MinRequiredArgs) { 5476 // Not enough arguments. 5477 Candidate.Viable = false; 5478 Candidate.FailureKind = ovl_fail_too_few_arguments; 5479 return; 5480 } 5481 5482 Candidate.Viable = true; 5483 5484 if (Method->isStatic() || ObjectType.isNull()) 5485 // The implicit object argument is ignored. 5486 Candidate.IgnoreObjectArgument = true; 5487 else { 5488 // Determine the implicit conversion sequence for the object 5489 // parameter. 5490 Candidate.Conversions[0] 5491 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 5492 Method, ActingContext); 5493 if (Candidate.Conversions[0].isBad()) { 5494 Candidate.Viable = false; 5495 Candidate.FailureKind = ovl_fail_bad_conversion; 5496 return; 5497 } 5498 } 5499 5500 // Determine the implicit conversion sequences for each of the 5501 // arguments. 5502 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5503 if (ArgIdx < NumArgsInProto) { 5504 // (C++ 13.3.2p3): for F to be a viable function, there shall 5505 // exist for each argument an implicit conversion sequence 5506 // (13.3.3.1) that converts that argument to the corresponding 5507 // parameter of F. 5508 QualType ParamType = Proto->getArgType(ArgIdx); 5509 Candidate.Conversions[ArgIdx + 1] 5510 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5511 SuppressUserConversions, 5512 /*InOverloadResolution=*/true, 5513 /*AllowObjCWritebackConversion=*/ 5514 getLangOpts().ObjCAutoRefCount); 5515 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5516 Candidate.Viable = false; 5517 Candidate.FailureKind = ovl_fail_bad_conversion; 5518 break; 5519 } 5520 } else { 5521 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5522 // argument for which there is no corresponding parameter is 5523 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5524 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5525 } 5526 } 5527 } 5528 5529 /// \brief Add a C++ member function template as a candidate to the candidate 5530 /// set, using template argument deduction to produce an appropriate member 5531 /// function template specialization. 5532 void 5533 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 5534 DeclAccessPair FoundDecl, 5535 CXXRecordDecl *ActingContext, 5536 TemplateArgumentListInfo *ExplicitTemplateArgs, 5537 QualType ObjectType, 5538 Expr::Classification ObjectClassification, 5539 llvm::ArrayRef<Expr *> Args, 5540 OverloadCandidateSet& CandidateSet, 5541 bool SuppressUserConversions) { 5542 if (!CandidateSet.isNewCandidate(MethodTmpl)) 5543 return; 5544 5545 // C++ [over.match.funcs]p7: 5546 // In each case where a candidate is a function template, candidate 5547 // function template specializations are generated using template argument 5548 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5549 // candidate functions in the usual way.113) A given name can refer to one 5550 // or more function templates and also to a set of overloaded non-template 5551 // functions. In such a case, the candidate functions generated from each 5552 // function template are combined with the set of non-template candidate 5553 // functions. 5554 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5555 FunctionDecl *Specialization = 0; 5556 if (TemplateDeductionResult Result 5557 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 5558 Specialization, Info)) { 5559 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5560 Candidate.FoundDecl = FoundDecl; 5561 Candidate.Function = MethodTmpl->getTemplatedDecl(); 5562 Candidate.Viable = false; 5563 Candidate.FailureKind = ovl_fail_bad_deduction; 5564 Candidate.IsSurrogate = false; 5565 Candidate.IgnoreObjectArgument = false; 5566 Candidate.ExplicitCallArguments = Args.size(); 5567 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5568 Info); 5569 return; 5570 } 5571 5572 // Add the function template specialization produced by template argument 5573 // deduction as a candidate. 5574 assert(Specialization && "Missing member function template specialization?"); 5575 assert(isa<CXXMethodDecl>(Specialization) && 5576 "Specialization is not a member function?"); 5577 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 5578 ActingContext, ObjectType, ObjectClassification, Args, 5579 CandidateSet, SuppressUserConversions); 5580 } 5581 5582 /// \brief Add a C++ function template specialization as a candidate 5583 /// in the candidate set, using template argument deduction to produce 5584 /// an appropriate function template specialization. 5585 void 5586 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 5587 DeclAccessPair FoundDecl, 5588 TemplateArgumentListInfo *ExplicitTemplateArgs, 5589 llvm::ArrayRef<Expr *> Args, 5590 OverloadCandidateSet& CandidateSet, 5591 bool SuppressUserConversions) { 5592 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5593 return; 5594 5595 // C++ [over.match.funcs]p7: 5596 // In each case where a candidate is a function template, candidate 5597 // function template specializations are generated using template argument 5598 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5599 // candidate functions in the usual way.113) A given name can refer to one 5600 // or more function templates and also to a set of overloaded non-template 5601 // functions. In such a case, the candidate functions generated from each 5602 // function template are combined with the set of non-template candidate 5603 // functions. 5604 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5605 FunctionDecl *Specialization = 0; 5606 if (TemplateDeductionResult Result 5607 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 5608 Specialization, Info)) { 5609 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5610 Candidate.FoundDecl = FoundDecl; 5611 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5612 Candidate.Viable = false; 5613 Candidate.FailureKind = ovl_fail_bad_deduction; 5614 Candidate.IsSurrogate = false; 5615 Candidate.IgnoreObjectArgument = false; 5616 Candidate.ExplicitCallArguments = Args.size(); 5617 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5618 Info); 5619 return; 5620 } 5621 5622 // Add the function template specialization produced by template argument 5623 // deduction as a candidate. 5624 assert(Specialization && "Missing function template specialization?"); 5625 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 5626 SuppressUserConversions); 5627 } 5628 5629 /// AddConversionCandidate - Add a C++ conversion function as a 5630 /// candidate in the candidate set (C++ [over.match.conv], 5631 /// C++ [over.match.copy]). From is the expression we're converting from, 5632 /// and ToType is the type that we're eventually trying to convert to 5633 /// (which may or may not be the same type as the type that the 5634 /// conversion function produces). 5635 void 5636 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 5637 DeclAccessPair FoundDecl, 5638 CXXRecordDecl *ActingContext, 5639 Expr *From, QualType ToType, 5640 OverloadCandidateSet& CandidateSet) { 5641 assert(!Conversion->getDescribedFunctionTemplate() && 5642 "Conversion function templates use AddTemplateConversionCandidate"); 5643 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 5644 if (!CandidateSet.isNewCandidate(Conversion)) 5645 return; 5646 5647 // Overload resolution is always an unevaluated context. 5648 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5649 5650 // Add this candidate 5651 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 5652 Candidate.FoundDecl = FoundDecl; 5653 Candidate.Function = Conversion; 5654 Candidate.IsSurrogate = false; 5655 Candidate.IgnoreObjectArgument = false; 5656 Candidate.FinalConversion.setAsIdentityConversion(); 5657 Candidate.FinalConversion.setFromType(ConvType); 5658 Candidate.FinalConversion.setAllToTypes(ToType); 5659 Candidate.Viable = true; 5660 Candidate.ExplicitCallArguments = 1; 5661 5662 // C++ [over.match.funcs]p4: 5663 // For conversion functions, the function is considered to be a member of 5664 // the class of the implicit implied object argument for the purpose of 5665 // defining the type of the implicit object parameter. 5666 // 5667 // Determine the implicit conversion sequence for the implicit 5668 // object parameter. 5669 QualType ImplicitParamType = From->getType(); 5670 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 5671 ImplicitParamType = FromPtrType->getPointeeType(); 5672 CXXRecordDecl *ConversionContext 5673 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 5674 5675 Candidate.Conversions[0] 5676 = TryObjectArgumentInitialization(*this, From->getType(), 5677 From->Classify(Context), 5678 Conversion, ConversionContext); 5679 5680 if (Candidate.Conversions[0].isBad()) { 5681 Candidate.Viable = false; 5682 Candidate.FailureKind = ovl_fail_bad_conversion; 5683 return; 5684 } 5685 5686 // We won't go through a user-define type conversion function to convert a 5687 // derived to base as such conversions are given Conversion Rank. They only 5688 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 5689 QualType FromCanon 5690 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 5691 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 5692 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 5693 Candidate.Viable = false; 5694 Candidate.FailureKind = ovl_fail_trivial_conversion; 5695 return; 5696 } 5697 5698 // To determine what the conversion from the result of calling the 5699 // conversion function to the type we're eventually trying to 5700 // convert to (ToType), we need to synthesize a call to the 5701 // conversion function and attempt copy initialization from it. This 5702 // makes sure that we get the right semantics with respect to 5703 // lvalues/rvalues and the type. Fortunately, we can allocate this 5704 // call on the stack and we don't need its arguments to be 5705 // well-formed. 5706 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 5707 VK_LValue, From->getLocStart()); 5708 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 5709 Context.getPointerType(Conversion->getType()), 5710 CK_FunctionToPointerDecay, 5711 &ConversionRef, VK_RValue); 5712 5713 QualType ConversionType = Conversion->getConversionType(); 5714 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 5715 Candidate.Viable = false; 5716 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5717 return; 5718 } 5719 5720 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 5721 5722 // Note that it is safe to allocate CallExpr on the stack here because 5723 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 5724 // allocator). 5725 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 5726 CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK, 5727 From->getLocStart()); 5728 ImplicitConversionSequence ICS = 5729 TryCopyInitialization(*this, &Call, ToType, 5730 /*SuppressUserConversions=*/true, 5731 /*InOverloadResolution=*/false, 5732 /*AllowObjCWritebackConversion=*/false); 5733 5734 switch (ICS.getKind()) { 5735 case ImplicitConversionSequence::StandardConversion: 5736 Candidate.FinalConversion = ICS.Standard; 5737 5738 // C++ [over.ics.user]p3: 5739 // If the user-defined conversion is specified by a specialization of a 5740 // conversion function template, the second standard conversion sequence 5741 // shall have exact match rank. 5742 if (Conversion->getPrimaryTemplate() && 5743 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 5744 Candidate.Viable = false; 5745 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 5746 } 5747 5748 // C++0x [dcl.init.ref]p5: 5749 // In the second case, if the reference is an rvalue reference and 5750 // the second standard conversion sequence of the user-defined 5751 // conversion sequence includes an lvalue-to-rvalue conversion, the 5752 // program is ill-formed. 5753 if (ToType->isRValueReferenceType() && 5754 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 5755 Candidate.Viable = false; 5756 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5757 } 5758 break; 5759 5760 case ImplicitConversionSequence::BadConversion: 5761 Candidate.Viable = false; 5762 Candidate.FailureKind = ovl_fail_bad_final_conversion; 5763 break; 5764 5765 default: 5766 llvm_unreachable( 5767 "Can only end up with a standard conversion sequence or failure"); 5768 } 5769 } 5770 5771 /// \brief Adds a conversion function template specialization 5772 /// candidate to the overload set, using template argument deduction 5773 /// to deduce the template arguments of the conversion function 5774 /// template from the type that we are converting to (C++ 5775 /// [temp.deduct.conv]). 5776 void 5777 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 5778 DeclAccessPair FoundDecl, 5779 CXXRecordDecl *ActingDC, 5780 Expr *From, QualType ToType, 5781 OverloadCandidateSet &CandidateSet) { 5782 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 5783 "Only conversion function templates permitted here"); 5784 5785 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5786 return; 5787 5788 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5789 CXXConversionDecl *Specialization = 0; 5790 if (TemplateDeductionResult Result 5791 = DeduceTemplateArguments(FunctionTemplate, ToType, 5792 Specialization, Info)) { 5793 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5794 Candidate.FoundDecl = FoundDecl; 5795 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5796 Candidate.Viable = false; 5797 Candidate.FailureKind = ovl_fail_bad_deduction; 5798 Candidate.IsSurrogate = false; 5799 Candidate.IgnoreObjectArgument = false; 5800 Candidate.ExplicitCallArguments = 1; 5801 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5802 Info); 5803 return; 5804 } 5805 5806 // Add the conversion function template specialization produced by 5807 // template argument deduction as a candidate. 5808 assert(Specialization && "Missing function template specialization?"); 5809 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 5810 CandidateSet); 5811 } 5812 5813 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 5814 /// converts the given @c Object to a function pointer via the 5815 /// conversion function @c Conversion, and then attempts to call it 5816 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 5817 /// the type of function that we'll eventually be calling. 5818 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 5819 DeclAccessPair FoundDecl, 5820 CXXRecordDecl *ActingContext, 5821 const FunctionProtoType *Proto, 5822 Expr *Object, 5823 llvm::ArrayRef<Expr *> Args, 5824 OverloadCandidateSet& CandidateSet) { 5825 if (!CandidateSet.isNewCandidate(Conversion)) 5826 return; 5827 5828 // Overload resolution is always an unevaluated context. 5829 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5830 5831 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5832 Candidate.FoundDecl = FoundDecl; 5833 Candidate.Function = 0; 5834 Candidate.Surrogate = Conversion; 5835 Candidate.Viable = true; 5836 Candidate.IsSurrogate = true; 5837 Candidate.IgnoreObjectArgument = false; 5838 Candidate.ExplicitCallArguments = Args.size(); 5839 5840 // Determine the implicit conversion sequence for the implicit 5841 // object parameter. 5842 ImplicitConversionSequence ObjectInit 5843 = TryObjectArgumentInitialization(*this, Object->getType(), 5844 Object->Classify(Context), 5845 Conversion, ActingContext); 5846 if (ObjectInit.isBad()) { 5847 Candidate.Viable = false; 5848 Candidate.FailureKind = ovl_fail_bad_conversion; 5849 Candidate.Conversions[0] = ObjectInit; 5850 return; 5851 } 5852 5853 // The first conversion is actually a user-defined conversion whose 5854 // first conversion is ObjectInit's standard conversion (which is 5855 // effectively a reference binding). Record it as such. 5856 Candidate.Conversions[0].setUserDefined(); 5857 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 5858 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 5859 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 5860 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 5861 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 5862 Candidate.Conversions[0].UserDefined.After 5863 = Candidate.Conversions[0].UserDefined.Before; 5864 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 5865 5866 // Find the 5867 unsigned NumArgsInProto = Proto->getNumArgs(); 5868 5869 // (C++ 13.3.2p2): A candidate function having fewer than m 5870 // parameters is viable only if it has an ellipsis in its parameter 5871 // list (8.3.5). 5872 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) { 5873 Candidate.Viable = false; 5874 Candidate.FailureKind = ovl_fail_too_many_arguments; 5875 return; 5876 } 5877 5878 // Function types don't have any default arguments, so just check if 5879 // we have enough arguments. 5880 if (Args.size() < NumArgsInProto) { 5881 // Not enough arguments. 5882 Candidate.Viable = false; 5883 Candidate.FailureKind = ovl_fail_too_few_arguments; 5884 return; 5885 } 5886 5887 // Determine the implicit conversion sequences for each of the 5888 // arguments. 5889 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5890 if (ArgIdx < NumArgsInProto) { 5891 // (C++ 13.3.2p3): for F to be a viable function, there shall 5892 // exist for each argument an implicit conversion sequence 5893 // (13.3.3.1) that converts that argument to the corresponding 5894 // parameter of F. 5895 QualType ParamType = Proto->getArgType(ArgIdx); 5896 Candidate.Conversions[ArgIdx + 1] 5897 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5898 /*SuppressUserConversions=*/false, 5899 /*InOverloadResolution=*/false, 5900 /*AllowObjCWritebackConversion=*/ 5901 getLangOpts().ObjCAutoRefCount); 5902 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5903 Candidate.Viable = false; 5904 Candidate.FailureKind = ovl_fail_bad_conversion; 5905 break; 5906 } 5907 } else { 5908 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5909 // argument for which there is no corresponding parameter is 5910 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5911 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5912 } 5913 } 5914 } 5915 5916 /// \brief Add overload candidates for overloaded operators that are 5917 /// member functions. 5918 /// 5919 /// Add the overloaded operator candidates that are member functions 5920 /// for the operator Op that was used in an operator expression such 5921 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 5922 /// CandidateSet will store the added overload candidates. (C++ 5923 /// [over.match.oper]). 5924 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 5925 SourceLocation OpLoc, 5926 Expr **Args, unsigned NumArgs, 5927 OverloadCandidateSet& CandidateSet, 5928 SourceRange OpRange) { 5929 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 5930 5931 // C++ [over.match.oper]p3: 5932 // For a unary operator @ with an operand of a type whose 5933 // cv-unqualified version is T1, and for a binary operator @ with 5934 // a left operand of a type whose cv-unqualified version is T1 and 5935 // a right operand of a type whose cv-unqualified version is T2, 5936 // three sets of candidate functions, designated member 5937 // candidates, non-member candidates and built-in candidates, are 5938 // constructed as follows: 5939 QualType T1 = Args[0]->getType(); 5940 5941 // -- If T1 is a class type, the set of member candidates is the 5942 // result of the qualified lookup of T1::operator@ 5943 // (13.3.1.1.1); otherwise, the set of member candidates is 5944 // empty. 5945 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 5946 // Complete the type if it can be completed. Otherwise, we're done. 5947 if (RequireCompleteType(OpLoc, T1, 0)) 5948 return; 5949 5950 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 5951 LookupQualifiedName(Operators, T1Rec->getDecl()); 5952 Operators.suppressDiagnostics(); 5953 5954 for (LookupResult::iterator Oper = Operators.begin(), 5955 OperEnd = Operators.end(); 5956 Oper != OperEnd; 5957 ++Oper) 5958 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 5959 Args[0]->Classify(Context), Args + 1, NumArgs - 1, 5960 CandidateSet, 5961 /* SuppressUserConversions = */ false); 5962 } 5963 } 5964 5965 /// AddBuiltinCandidate - Add a candidate for a built-in 5966 /// operator. ResultTy and ParamTys are the result and parameter types 5967 /// of the built-in candidate, respectively. Args and NumArgs are the 5968 /// arguments being passed to the candidate. IsAssignmentOperator 5969 /// should be true when this built-in candidate is an assignment 5970 /// operator. NumContextualBoolArguments is the number of arguments 5971 /// (at the beginning of the argument list) that will be contextually 5972 /// converted to bool. 5973 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 5974 Expr **Args, unsigned NumArgs, 5975 OverloadCandidateSet& CandidateSet, 5976 bool IsAssignmentOperator, 5977 unsigned NumContextualBoolArguments) { 5978 // Overload resolution is always an unevaluated context. 5979 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5980 5981 // Add this candidate 5982 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs); 5983 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 5984 Candidate.Function = 0; 5985 Candidate.IsSurrogate = false; 5986 Candidate.IgnoreObjectArgument = false; 5987 Candidate.BuiltinTypes.ResultTy = ResultTy; 5988 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 5989 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 5990 5991 // Determine the implicit conversion sequences for each of the 5992 // arguments. 5993 Candidate.Viable = true; 5994 Candidate.ExplicitCallArguments = NumArgs; 5995 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 5996 // C++ [over.match.oper]p4: 5997 // For the built-in assignment operators, conversions of the 5998 // left operand are restricted as follows: 5999 // -- no temporaries are introduced to hold the left operand, and 6000 // -- no user-defined conversions are applied to the left 6001 // operand to achieve a type match with the left-most 6002 // parameter of a built-in candidate. 6003 // 6004 // We block these conversions by turning off user-defined 6005 // conversions, since that is the only way that initialization of 6006 // a reference to a non-class type can occur from something that 6007 // is not of the same type. 6008 if (ArgIdx < NumContextualBoolArguments) { 6009 assert(ParamTys[ArgIdx] == Context.BoolTy && 6010 "Contextual conversion to bool requires bool type"); 6011 Candidate.Conversions[ArgIdx] 6012 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6013 } else { 6014 Candidate.Conversions[ArgIdx] 6015 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6016 ArgIdx == 0 && IsAssignmentOperator, 6017 /*InOverloadResolution=*/false, 6018 /*AllowObjCWritebackConversion=*/ 6019 getLangOpts().ObjCAutoRefCount); 6020 } 6021 if (Candidate.Conversions[ArgIdx].isBad()) { 6022 Candidate.Viable = false; 6023 Candidate.FailureKind = ovl_fail_bad_conversion; 6024 break; 6025 } 6026 } 6027 } 6028 6029 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6030 /// candidate operator functions for built-in operators (C++ 6031 /// [over.built]). The types are separated into pointer types and 6032 /// enumeration types. 6033 class BuiltinCandidateTypeSet { 6034 /// TypeSet - A set of types. 6035 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6036 6037 /// PointerTypes - The set of pointer types that will be used in the 6038 /// built-in candidates. 6039 TypeSet PointerTypes; 6040 6041 /// MemberPointerTypes - The set of member pointer types that will be 6042 /// used in the built-in candidates. 6043 TypeSet MemberPointerTypes; 6044 6045 /// EnumerationTypes - The set of enumeration types that will be 6046 /// used in the built-in candidates. 6047 TypeSet EnumerationTypes; 6048 6049 /// \brief The set of vector types that will be used in the built-in 6050 /// candidates. 6051 TypeSet VectorTypes; 6052 6053 /// \brief A flag indicating non-record types are viable candidates 6054 bool HasNonRecordTypes; 6055 6056 /// \brief A flag indicating whether either arithmetic or enumeration types 6057 /// were present in the candidate set. 6058 bool HasArithmeticOrEnumeralTypes; 6059 6060 /// \brief A flag indicating whether the nullptr type was present in the 6061 /// candidate set. 6062 bool HasNullPtrType; 6063 6064 /// Sema - The semantic analysis instance where we are building the 6065 /// candidate type set. 6066 Sema &SemaRef; 6067 6068 /// Context - The AST context in which we will build the type sets. 6069 ASTContext &Context; 6070 6071 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6072 const Qualifiers &VisibleQuals); 6073 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6074 6075 public: 6076 /// iterator - Iterates through the types that are part of the set. 6077 typedef TypeSet::iterator iterator; 6078 6079 BuiltinCandidateTypeSet(Sema &SemaRef) 6080 : HasNonRecordTypes(false), 6081 HasArithmeticOrEnumeralTypes(false), 6082 HasNullPtrType(false), 6083 SemaRef(SemaRef), 6084 Context(SemaRef.Context) { } 6085 6086 void AddTypesConvertedFrom(QualType Ty, 6087 SourceLocation Loc, 6088 bool AllowUserConversions, 6089 bool AllowExplicitConversions, 6090 const Qualifiers &VisibleTypeConversionsQuals); 6091 6092 /// pointer_begin - First pointer type found; 6093 iterator pointer_begin() { return PointerTypes.begin(); } 6094 6095 /// pointer_end - Past the last pointer type found; 6096 iterator pointer_end() { return PointerTypes.end(); } 6097 6098 /// member_pointer_begin - First member pointer type found; 6099 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6100 6101 /// member_pointer_end - Past the last member pointer type found; 6102 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6103 6104 /// enumeration_begin - First enumeration type found; 6105 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6106 6107 /// enumeration_end - Past the last enumeration type found; 6108 iterator enumeration_end() { return EnumerationTypes.end(); } 6109 6110 iterator vector_begin() { return VectorTypes.begin(); } 6111 iterator vector_end() { return VectorTypes.end(); } 6112 6113 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6114 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6115 bool hasNullPtrType() const { return HasNullPtrType; } 6116 }; 6117 6118 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6119 /// the set of pointer types along with any more-qualified variants of 6120 /// that type. For example, if @p Ty is "int const *", this routine 6121 /// will add "int const *", "int const volatile *", "int const 6122 /// restrict *", and "int const volatile restrict *" to the set of 6123 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6124 /// false otherwise. 6125 /// 6126 /// FIXME: what to do about extended qualifiers? 6127 bool 6128 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6129 const Qualifiers &VisibleQuals) { 6130 6131 // Insert this type. 6132 if (!PointerTypes.insert(Ty)) 6133 return false; 6134 6135 QualType PointeeTy; 6136 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6137 bool buildObjCPtr = false; 6138 if (!PointerTy) { 6139 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6140 PointeeTy = PTy->getPointeeType(); 6141 buildObjCPtr = true; 6142 } else { 6143 PointeeTy = PointerTy->getPointeeType(); 6144 } 6145 6146 // Don't add qualified variants of arrays. For one, they're not allowed 6147 // (the qualifier would sink to the element type), and for another, the 6148 // only overload situation where it matters is subscript or pointer +- int, 6149 // and those shouldn't have qualifier variants anyway. 6150 if (PointeeTy->isArrayType()) 6151 return true; 6152 6153 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6154 bool hasVolatile = VisibleQuals.hasVolatile(); 6155 bool hasRestrict = VisibleQuals.hasRestrict(); 6156 6157 // Iterate through all strict supersets of BaseCVR. 6158 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6159 if ((CVR | BaseCVR) != CVR) continue; 6160 // Skip over volatile if no volatile found anywhere in the types. 6161 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6162 6163 // Skip over restrict if no restrict found anywhere in the types, or if 6164 // the type cannot be restrict-qualified. 6165 if ((CVR & Qualifiers::Restrict) && 6166 (!hasRestrict || 6167 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6168 continue; 6169 6170 // Build qualified pointee type. 6171 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6172 6173 // Build qualified pointer type. 6174 QualType QPointerTy; 6175 if (!buildObjCPtr) 6176 QPointerTy = Context.getPointerType(QPointeeTy); 6177 else 6178 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6179 6180 // Insert qualified pointer type. 6181 PointerTypes.insert(QPointerTy); 6182 } 6183 6184 return true; 6185 } 6186 6187 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6188 /// to the set of pointer types along with any more-qualified variants of 6189 /// that type. For example, if @p Ty is "int const *", this routine 6190 /// will add "int const *", "int const volatile *", "int const 6191 /// restrict *", and "int const volatile restrict *" to the set of 6192 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6193 /// false otherwise. 6194 /// 6195 /// FIXME: what to do about extended qualifiers? 6196 bool 6197 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6198 QualType Ty) { 6199 // Insert this type. 6200 if (!MemberPointerTypes.insert(Ty)) 6201 return false; 6202 6203 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6204 assert(PointerTy && "type was not a member pointer type!"); 6205 6206 QualType PointeeTy = PointerTy->getPointeeType(); 6207 // Don't add qualified variants of arrays. For one, they're not allowed 6208 // (the qualifier would sink to the element type), and for another, the 6209 // only overload situation where it matters is subscript or pointer +- int, 6210 // and those shouldn't have qualifier variants anyway. 6211 if (PointeeTy->isArrayType()) 6212 return true; 6213 const Type *ClassTy = PointerTy->getClass(); 6214 6215 // Iterate through all strict supersets of the pointee type's CVR 6216 // qualifiers. 6217 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6218 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6219 if ((CVR | BaseCVR) != CVR) continue; 6220 6221 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6222 MemberPointerTypes.insert( 6223 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6224 } 6225 6226 return true; 6227 } 6228 6229 /// AddTypesConvertedFrom - Add each of the types to which the type @p 6230 /// Ty can be implicit converted to the given set of @p Types. We're 6231 /// primarily interested in pointer types and enumeration types. We also 6232 /// take member pointer types, for the conditional operator. 6233 /// AllowUserConversions is true if we should look at the conversion 6234 /// functions of a class type, and AllowExplicitConversions if we 6235 /// should also include the explicit conversion functions of a class 6236 /// type. 6237 void 6238 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6239 SourceLocation Loc, 6240 bool AllowUserConversions, 6241 bool AllowExplicitConversions, 6242 const Qualifiers &VisibleQuals) { 6243 // Only deal with canonical types. 6244 Ty = Context.getCanonicalType(Ty); 6245 6246 // Look through reference types; they aren't part of the type of an 6247 // expression for the purposes of conversions. 6248 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6249 Ty = RefTy->getPointeeType(); 6250 6251 // If we're dealing with an array type, decay to the pointer. 6252 if (Ty->isArrayType()) 6253 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6254 6255 // Otherwise, we don't care about qualifiers on the type. 6256 Ty = Ty.getLocalUnqualifiedType(); 6257 6258 // Flag if we ever add a non-record type. 6259 const RecordType *TyRec = Ty->getAs<RecordType>(); 6260 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6261 6262 // Flag if we encounter an arithmetic type. 6263 HasArithmeticOrEnumeralTypes = 6264 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6265 6266 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6267 PointerTypes.insert(Ty); 6268 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6269 // Insert our type, and its more-qualified variants, into the set 6270 // of types. 6271 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6272 return; 6273 } else if (Ty->isMemberPointerType()) { 6274 // Member pointers are far easier, since the pointee can't be converted. 6275 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6276 return; 6277 } else if (Ty->isEnumeralType()) { 6278 HasArithmeticOrEnumeralTypes = true; 6279 EnumerationTypes.insert(Ty); 6280 } else if (Ty->isVectorType()) { 6281 // We treat vector types as arithmetic types in many contexts as an 6282 // extension. 6283 HasArithmeticOrEnumeralTypes = true; 6284 VectorTypes.insert(Ty); 6285 } else if (Ty->isNullPtrType()) { 6286 HasNullPtrType = true; 6287 } else if (AllowUserConversions && TyRec) { 6288 // No conversion functions in incomplete types. 6289 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6290 return; 6291 6292 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6293 const UnresolvedSetImpl *Conversions 6294 = ClassDecl->getVisibleConversionFunctions(); 6295 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 6296 E = Conversions->end(); 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 const UnresolvedSetImpl *Conversions = 6363 ClassDecl->getVisibleConversionFunctions(); 6364 6365 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 6366 E = Conversions->end(); I != E; ++I) { 6367 NamedDecl *D = I.getDecl(); 6368 if (isa<UsingShadowDecl>(D)) 6369 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6370 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6371 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 6372 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 6373 CanTy = ResTypeRef->getPointeeType(); 6374 // Need to go down the pointer/mempointer chain and add qualifiers 6375 // as see them. 6376 bool done = false; 6377 while (!done) { 6378 if (CanTy.isRestrictQualified()) 6379 VRQuals.addRestrict(); 6380 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 6381 CanTy = ResTypePtr->getPointeeType(); 6382 else if (const MemberPointerType *ResTypeMPtr = 6383 CanTy->getAs<MemberPointerType>()) 6384 CanTy = ResTypeMPtr->getPointeeType(); 6385 else 6386 done = true; 6387 if (CanTy.isVolatileQualified()) 6388 VRQuals.addVolatile(); 6389 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 6390 return VRQuals; 6391 } 6392 } 6393 } 6394 return VRQuals; 6395 } 6396 6397 namespace { 6398 6399 /// \brief Helper class to manage the addition of builtin operator overload 6400 /// candidates. It provides shared state and utility methods used throughout 6401 /// the process, as well as a helper method to add each group of builtin 6402 /// operator overloads from the standard to a candidate set. 6403 class BuiltinOperatorOverloadBuilder { 6404 // Common instance state available to all overload candidate addition methods. 6405 Sema &S; 6406 Expr **Args; 6407 unsigned NumArgs; 6408 Qualifiers VisibleTypeConversionsQuals; 6409 bool HasArithmeticOrEnumeralCandidateType; 6410 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 6411 OverloadCandidateSet &CandidateSet; 6412 6413 // Define some constants used to index and iterate over the arithemetic types 6414 // provided via the getArithmeticType() method below. 6415 // The "promoted arithmetic types" are the arithmetic 6416 // types are that preserved by promotion (C++ [over.built]p2). 6417 static const unsigned FirstIntegralType = 3; 6418 static const unsigned LastIntegralType = 20; 6419 static const unsigned FirstPromotedIntegralType = 3, 6420 LastPromotedIntegralType = 11; 6421 static const unsigned FirstPromotedArithmeticType = 0, 6422 LastPromotedArithmeticType = 11; 6423 static const unsigned NumArithmeticTypes = 20; 6424 6425 /// \brief Get the canonical type for a given arithmetic type index. 6426 CanQualType getArithmeticType(unsigned index) { 6427 assert(index < NumArithmeticTypes); 6428 static CanQualType ASTContext::* const 6429 ArithmeticTypes[NumArithmeticTypes] = { 6430 // Start of promoted types. 6431 &ASTContext::FloatTy, 6432 &ASTContext::DoubleTy, 6433 &ASTContext::LongDoubleTy, 6434 6435 // Start of integral types. 6436 &ASTContext::IntTy, 6437 &ASTContext::LongTy, 6438 &ASTContext::LongLongTy, 6439 &ASTContext::Int128Ty, 6440 &ASTContext::UnsignedIntTy, 6441 &ASTContext::UnsignedLongTy, 6442 &ASTContext::UnsignedLongLongTy, 6443 &ASTContext::UnsignedInt128Ty, 6444 // End of promoted types. 6445 6446 &ASTContext::BoolTy, 6447 &ASTContext::CharTy, 6448 &ASTContext::WCharTy, 6449 &ASTContext::Char16Ty, 6450 &ASTContext::Char32Ty, 6451 &ASTContext::SignedCharTy, 6452 &ASTContext::ShortTy, 6453 &ASTContext::UnsignedCharTy, 6454 &ASTContext::UnsignedShortTy, 6455 // End of integral types. 6456 // FIXME: What about complex? What about half? 6457 }; 6458 return S.Context.*ArithmeticTypes[index]; 6459 } 6460 6461 /// \brief Gets the canonical type resulting from the usual arithemetic 6462 /// converions for the given arithmetic types. 6463 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 6464 // Accelerator table for performing the usual arithmetic conversions. 6465 // The rules are basically: 6466 // - if either is floating-point, use the wider floating-point 6467 // - if same signedness, use the higher rank 6468 // - if same size, use unsigned of the higher rank 6469 // - use the larger type 6470 // These rules, together with the axiom that higher ranks are 6471 // never smaller, are sufficient to precompute all of these results 6472 // *except* when dealing with signed types of higher rank. 6473 // (we could precompute SLL x UI for all known platforms, but it's 6474 // better not to make any assumptions). 6475 // We assume that int128 has a higher rank than long long on all platforms. 6476 enum PromotedType { 6477 Dep=-1, 6478 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 6479 }; 6480 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 6481 [LastPromotedArithmeticType] = { 6482 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 6483 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 6484 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 6485 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 6486 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 6487 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 6488 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 6489 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 6490 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 6491 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 6492 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 6493 }; 6494 6495 assert(L < LastPromotedArithmeticType); 6496 assert(R < LastPromotedArithmeticType); 6497 int Idx = ConversionsTable[L][R]; 6498 6499 // Fast path: the table gives us a concrete answer. 6500 if (Idx != Dep) return getArithmeticType(Idx); 6501 6502 // Slow path: we need to compare widths. 6503 // An invariant is that the signed type has higher rank. 6504 CanQualType LT = getArithmeticType(L), 6505 RT = getArithmeticType(R); 6506 unsigned LW = S.Context.getIntWidth(LT), 6507 RW = S.Context.getIntWidth(RT); 6508 6509 // If they're different widths, use the signed type. 6510 if (LW > RW) return LT; 6511 else if (LW < RW) return RT; 6512 6513 // Otherwise, use the unsigned type of the signed type's rank. 6514 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 6515 assert(L == SLL || R == SLL); 6516 return S.Context.UnsignedLongLongTy; 6517 } 6518 6519 /// \brief Helper method to factor out the common pattern of adding overloads 6520 /// for '++' and '--' builtin operators. 6521 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 6522 bool HasVolatile, 6523 bool HasRestrict) { 6524 QualType ParamTypes[2] = { 6525 S.Context.getLValueReferenceType(CandidateTy), 6526 S.Context.IntTy 6527 }; 6528 6529 // Non-volatile version. 6530 if (NumArgs == 1) 6531 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6532 else 6533 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6534 6535 // Use a heuristic to reduce number of builtin candidates in the set: 6536 // add volatile version only if there are conversions to a volatile type. 6537 if (HasVolatile) { 6538 ParamTypes[0] = 6539 S.Context.getLValueReferenceType( 6540 S.Context.getVolatileType(CandidateTy)); 6541 if (NumArgs == 1) 6542 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6543 else 6544 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6545 } 6546 6547 // Add restrict version only if there are conversions to a restrict type 6548 // and our candidate type is a non-restrict-qualified pointer. 6549 if (HasRestrict && CandidateTy->isAnyPointerType() && 6550 !CandidateTy.isRestrictQualified()) { 6551 ParamTypes[0] 6552 = S.Context.getLValueReferenceType( 6553 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 6554 if (NumArgs == 1) 6555 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 6556 else 6557 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6558 6559 if (HasVolatile) { 6560 ParamTypes[0] 6561 = S.Context.getLValueReferenceType( 6562 S.Context.getCVRQualifiedType(CandidateTy, 6563 (Qualifiers::Volatile | 6564 Qualifiers::Restrict))); 6565 if (NumArgs == 1) 6566 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, 6567 CandidateSet); 6568 else 6569 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet); 6570 } 6571 } 6572 6573 } 6574 6575 public: 6576 BuiltinOperatorOverloadBuilder( 6577 Sema &S, Expr **Args, unsigned NumArgs, 6578 Qualifiers VisibleTypeConversionsQuals, 6579 bool HasArithmeticOrEnumeralCandidateType, 6580 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 6581 OverloadCandidateSet &CandidateSet) 6582 : S(S), Args(Args), NumArgs(NumArgs), 6583 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 6584 HasArithmeticOrEnumeralCandidateType( 6585 HasArithmeticOrEnumeralCandidateType), 6586 CandidateTypes(CandidateTypes), 6587 CandidateSet(CandidateSet) { 6588 // Validate some of our static helper constants in debug builds. 6589 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 6590 "Invalid first promoted integral type"); 6591 assert(getArithmeticType(LastPromotedIntegralType - 1) 6592 == S.Context.UnsignedInt128Ty && 6593 "Invalid last promoted integral type"); 6594 assert(getArithmeticType(FirstPromotedArithmeticType) 6595 == S.Context.FloatTy && 6596 "Invalid first promoted arithmetic type"); 6597 assert(getArithmeticType(LastPromotedArithmeticType - 1) 6598 == S.Context.UnsignedInt128Ty && 6599 "Invalid last promoted arithmetic type"); 6600 } 6601 6602 // C++ [over.built]p3: 6603 // 6604 // For every pair (T, VQ), where T is an arithmetic type, and VQ 6605 // is either volatile or empty, there exist candidate operator 6606 // functions of the form 6607 // 6608 // VQ T& operator++(VQ T&); 6609 // T operator++(VQ T&, int); 6610 // 6611 // C++ [over.built]p4: 6612 // 6613 // For every pair (T, VQ), where T is an arithmetic type other 6614 // than bool, and VQ is either volatile or empty, there exist 6615 // candidate operator functions of the form 6616 // 6617 // VQ T& operator--(VQ T&); 6618 // T operator--(VQ T&, int); 6619 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 6620 if (!HasArithmeticOrEnumeralCandidateType) 6621 return; 6622 6623 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 6624 Arith < NumArithmeticTypes; ++Arith) { 6625 addPlusPlusMinusMinusStyleOverloads( 6626 getArithmeticType(Arith), 6627 VisibleTypeConversionsQuals.hasVolatile(), 6628 VisibleTypeConversionsQuals.hasRestrict()); 6629 } 6630 } 6631 6632 // C++ [over.built]p5: 6633 // 6634 // For every pair (T, VQ), where T is a cv-qualified or 6635 // cv-unqualified object type, and VQ is either volatile or 6636 // empty, there exist candidate operator functions of the form 6637 // 6638 // T*VQ& operator++(T*VQ&); 6639 // T*VQ& operator--(T*VQ&); 6640 // T* operator++(T*VQ&, int); 6641 // T* operator--(T*VQ&, int); 6642 void addPlusPlusMinusMinusPointerOverloads() { 6643 for (BuiltinCandidateTypeSet::iterator 6644 Ptr = CandidateTypes[0].pointer_begin(), 6645 PtrEnd = CandidateTypes[0].pointer_end(); 6646 Ptr != PtrEnd; ++Ptr) { 6647 // Skip pointer types that aren't pointers to object types. 6648 if (!(*Ptr)->getPointeeType()->isObjectType()) 6649 continue; 6650 6651 addPlusPlusMinusMinusStyleOverloads(*Ptr, 6652 (!(*Ptr).isVolatileQualified() && 6653 VisibleTypeConversionsQuals.hasVolatile()), 6654 (!(*Ptr).isRestrictQualified() && 6655 VisibleTypeConversionsQuals.hasRestrict())); 6656 } 6657 } 6658 6659 // C++ [over.built]p6: 6660 // For every cv-qualified or cv-unqualified object type T, there 6661 // exist candidate operator functions of the form 6662 // 6663 // T& operator*(T*); 6664 // 6665 // C++ [over.built]p7: 6666 // For every function type T that does not have cv-qualifiers or a 6667 // ref-qualifier, there exist candidate operator functions of the form 6668 // T& operator*(T*); 6669 void addUnaryStarPointerOverloads() { 6670 for (BuiltinCandidateTypeSet::iterator 6671 Ptr = CandidateTypes[0].pointer_begin(), 6672 PtrEnd = CandidateTypes[0].pointer_end(); 6673 Ptr != PtrEnd; ++Ptr) { 6674 QualType ParamTy = *Ptr; 6675 QualType PointeeTy = ParamTy->getPointeeType(); 6676 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 6677 continue; 6678 6679 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 6680 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 6681 continue; 6682 6683 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 6684 &ParamTy, Args, 1, CandidateSet); 6685 } 6686 } 6687 6688 // C++ [over.built]p9: 6689 // For every promoted arithmetic type T, there exist candidate 6690 // operator functions of the form 6691 // 6692 // T operator+(T); 6693 // T operator-(T); 6694 void addUnaryPlusOrMinusArithmeticOverloads() { 6695 if (!HasArithmeticOrEnumeralCandidateType) 6696 return; 6697 6698 for (unsigned Arith = FirstPromotedArithmeticType; 6699 Arith < LastPromotedArithmeticType; ++Arith) { 6700 QualType ArithTy = getArithmeticType(Arith); 6701 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet); 6702 } 6703 6704 // Extension: We also add these operators for vector types. 6705 for (BuiltinCandidateTypeSet::iterator 6706 Vec = CandidateTypes[0].vector_begin(), 6707 VecEnd = CandidateTypes[0].vector_end(); 6708 Vec != VecEnd; ++Vec) { 6709 QualType VecTy = *Vec; 6710 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 6711 } 6712 } 6713 6714 // C++ [over.built]p8: 6715 // For every type T, there exist candidate operator functions of 6716 // the form 6717 // 6718 // T* operator+(T*); 6719 void addUnaryPlusPointerOverloads() { 6720 for (BuiltinCandidateTypeSet::iterator 6721 Ptr = CandidateTypes[0].pointer_begin(), 6722 PtrEnd = CandidateTypes[0].pointer_end(); 6723 Ptr != PtrEnd; ++Ptr) { 6724 QualType ParamTy = *Ptr; 6725 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 6726 } 6727 } 6728 6729 // C++ [over.built]p10: 6730 // For every promoted integral type T, there exist candidate 6731 // operator functions of the form 6732 // 6733 // T operator~(T); 6734 void addUnaryTildePromotedIntegralOverloads() { 6735 if (!HasArithmeticOrEnumeralCandidateType) 6736 return; 6737 6738 for (unsigned Int = FirstPromotedIntegralType; 6739 Int < LastPromotedIntegralType; ++Int) { 6740 QualType IntTy = getArithmeticType(Int); 6741 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet); 6742 } 6743 6744 // Extension: We also add this operator for vector types. 6745 for (BuiltinCandidateTypeSet::iterator 6746 Vec = CandidateTypes[0].vector_begin(), 6747 VecEnd = CandidateTypes[0].vector_end(); 6748 Vec != VecEnd; ++Vec) { 6749 QualType VecTy = *Vec; 6750 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet); 6751 } 6752 } 6753 6754 // C++ [over.match.oper]p16: 6755 // For every pointer to member type T, there exist candidate operator 6756 // functions of the form 6757 // 6758 // bool operator==(T,T); 6759 // bool operator!=(T,T); 6760 void addEqualEqualOrNotEqualMemberPointerOverloads() { 6761 /// Set of (canonical) types that we've already handled. 6762 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6763 6764 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6765 for (BuiltinCandidateTypeSet::iterator 6766 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 6767 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 6768 MemPtr != MemPtrEnd; 6769 ++MemPtr) { 6770 // Don't add the same builtin candidate twice. 6771 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 6772 continue; 6773 6774 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 6775 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6776 CandidateSet); 6777 } 6778 } 6779 } 6780 6781 // C++ [over.built]p15: 6782 // 6783 // For every T, where T is an enumeration type, a pointer type, or 6784 // std::nullptr_t, there exist candidate operator functions of the form 6785 // 6786 // bool operator<(T, T); 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 void addRelationalPointerOrEnumeralOverloads() { 6793 // C++ [over.match.oper]p3: 6794 // [...]the built-in candidates include all of the candidate operator 6795 // functions defined in 13.6 that, compared to the given operator, [...] 6796 // do not have the same parameter-type-list as any non-template non-member 6797 // candidate. 6798 // 6799 // Note that in practice, this only affects enumeration types because there 6800 // aren't any built-in candidates of record type, and a user-defined operator 6801 // must have an operand of record or enumeration type. Also, the only other 6802 // overloaded operator with enumeration arguments, operator=, 6803 // cannot be overloaded for enumeration types, so this is the only place 6804 // where we must suppress candidates like this. 6805 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 6806 UserDefinedBinaryOperators; 6807 6808 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6809 if (CandidateTypes[ArgIdx].enumeration_begin() != 6810 CandidateTypes[ArgIdx].enumeration_end()) { 6811 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 6812 CEnd = CandidateSet.end(); 6813 C != CEnd; ++C) { 6814 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 6815 continue; 6816 6817 if (C->Function->isFunctionTemplateSpecialization()) 6818 continue; 6819 6820 QualType FirstParamType = 6821 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 6822 QualType SecondParamType = 6823 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 6824 6825 // Skip if either parameter isn't of enumeral type. 6826 if (!FirstParamType->isEnumeralType() || 6827 !SecondParamType->isEnumeralType()) 6828 continue; 6829 6830 // Add this operator to the set of known user-defined operators. 6831 UserDefinedBinaryOperators.insert( 6832 std::make_pair(S.Context.getCanonicalType(FirstParamType), 6833 S.Context.getCanonicalType(SecondParamType))); 6834 } 6835 } 6836 } 6837 6838 /// Set of (canonical) types that we've already handled. 6839 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6840 6841 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 6842 for (BuiltinCandidateTypeSet::iterator 6843 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 6844 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 6845 Ptr != PtrEnd; ++Ptr) { 6846 // Don't add the same builtin candidate twice. 6847 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 6848 continue; 6849 6850 QualType ParamTypes[2] = { *Ptr, *Ptr }; 6851 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6852 CandidateSet); 6853 } 6854 for (BuiltinCandidateTypeSet::iterator 6855 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 6856 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 6857 Enum != EnumEnd; ++Enum) { 6858 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 6859 6860 // Don't add the same builtin candidate twice, or if a user defined 6861 // candidate exists. 6862 if (!AddedTypes.insert(CanonType) || 6863 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 6864 CanonType))) 6865 continue; 6866 6867 QualType ParamTypes[2] = { *Enum, *Enum }; 6868 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6869 CandidateSet); 6870 } 6871 6872 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 6873 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 6874 if (AddedTypes.insert(NullPtrTy) && 6875 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 6876 NullPtrTy))) { 6877 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 6878 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, 6879 CandidateSet); 6880 } 6881 } 6882 } 6883 } 6884 6885 // C++ [over.built]p13: 6886 // 6887 // For every cv-qualified or cv-unqualified object type T 6888 // there exist candidate operator functions of the form 6889 // 6890 // T* operator+(T*, ptrdiff_t); 6891 // T& operator[](T*, ptrdiff_t); [BELOW] 6892 // T* operator-(T*, ptrdiff_t); 6893 // T* operator+(ptrdiff_t, T*); 6894 // T& operator[](ptrdiff_t, T*); [BELOW] 6895 // 6896 // C++ [over.built]p14: 6897 // 6898 // For every T, where T is a pointer to object type, there 6899 // exist candidate operator functions of the form 6900 // 6901 // ptrdiff_t operator-(T, T); 6902 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 6903 /// Set of (canonical) types that we've already handled. 6904 llvm::SmallPtrSet<QualType, 8> AddedTypes; 6905 6906 for (int Arg = 0; Arg < 2; ++Arg) { 6907 QualType AsymetricParamTypes[2] = { 6908 S.Context.getPointerDiffType(), 6909 S.Context.getPointerDiffType(), 6910 }; 6911 for (BuiltinCandidateTypeSet::iterator 6912 Ptr = CandidateTypes[Arg].pointer_begin(), 6913 PtrEnd = CandidateTypes[Arg].pointer_end(); 6914 Ptr != PtrEnd; ++Ptr) { 6915 QualType PointeeTy = (*Ptr)->getPointeeType(); 6916 if (!PointeeTy->isObjectType()) 6917 continue; 6918 6919 AsymetricParamTypes[Arg] = *Ptr; 6920 if (Arg == 0 || Op == OO_Plus) { 6921 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 6922 // T* operator+(ptrdiff_t, T*); 6923 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2, 6924 CandidateSet); 6925 } 6926 if (Op == OO_Minus) { 6927 // ptrdiff_t operator-(T, T); 6928 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 6929 continue; 6930 6931 QualType ParamTypes[2] = { *Ptr, *Ptr }; 6932 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 6933 Args, 2, CandidateSet); 6934 } 6935 } 6936 } 6937 } 6938 6939 // C++ [over.built]p12: 6940 // 6941 // For every pair of promoted arithmetic types L and R, there 6942 // exist candidate operator functions of the form 6943 // 6944 // LR operator*(L, R); 6945 // LR operator/(L, R); 6946 // LR operator+(L, R); 6947 // LR operator-(L, R); 6948 // bool 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 // 6955 // where LR is the result of the usual arithmetic conversions 6956 // between types L and R. 6957 // 6958 // C++ [over.built]p24: 6959 // 6960 // For every pair of promoted arithmetic types L and R, there exist 6961 // candidate operator functions of the form 6962 // 6963 // LR operator?(bool, L, R); 6964 // 6965 // where LR is the result of the usual arithmetic conversions 6966 // between types L and R. 6967 // Our candidates ignore the first parameter. 6968 void addGenericBinaryArithmeticOverloads(bool isComparison) { 6969 if (!HasArithmeticOrEnumeralCandidateType) 6970 return; 6971 6972 for (unsigned Left = FirstPromotedArithmeticType; 6973 Left < LastPromotedArithmeticType; ++Left) { 6974 for (unsigned Right = FirstPromotedArithmeticType; 6975 Right < LastPromotedArithmeticType; ++Right) { 6976 QualType LandR[2] = { getArithmeticType(Left), 6977 getArithmeticType(Right) }; 6978 QualType Result = 6979 isComparison ? S.Context.BoolTy 6980 : getUsualArithmeticConversions(Left, Right); 6981 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 6982 } 6983 } 6984 6985 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 6986 // conditional operator for vector types. 6987 for (BuiltinCandidateTypeSet::iterator 6988 Vec1 = CandidateTypes[0].vector_begin(), 6989 Vec1End = CandidateTypes[0].vector_end(); 6990 Vec1 != Vec1End; ++Vec1) { 6991 for (BuiltinCandidateTypeSet::iterator 6992 Vec2 = CandidateTypes[1].vector_begin(), 6993 Vec2End = CandidateTypes[1].vector_end(); 6994 Vec2 != Vec2End; ++Vec2) { 6995 QualType LandR[2] = { *Vec1, *Vec2 }; 6996 QualType Result = S.Context.BoolTy; 6997 if (!isComparison) { 6998 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 6999 Result = *Vec1; 7000 else 7001 Result = *Vec2; 7002 } 7003 7004 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 7005 } 7006 } 7007 } 7008 7009 // C++ [over.built]p17: 7010 // 7011 // For every pair of promoted integral types L and R, there 7012 // exist candidate operator functions of the form 7013 // 7014 // LR operator%(L, R); 7015 // LR operator&(L, R); 7016 // LR operator^(L, R); 7017 // LR operator|(L, R); 7018 // L operator<<(L, R); 7019 // L operator>>(L, R); 7020 // 7021 // where LR is the result of the usual arithmetic conversions 7022 // between types L and R. 7023 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7024 if (!HasArithmeticOrEnumeralCandidateType) 7025 return; 7026 7027 for (unsigned Left = FirstPromotedIntegralType; 7028 Left < LastPromotedIntegralType; ++Left) { 7029 for (unsigned Right = FirstPromotedIntegralType; 7030 Right < LastPromotedIntegralType; ++Right) { 7031 QualType LandR[2] = { getArithmeticType(Left), 7032 getArithmeticType(Right) }; 7033 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7034 ? LandR[0] 7035 : getUsualArithmeticConversions(Left, Right); 7036 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 7037 } 7038 } 7039 } 7040 7041 // C++ [over.built]p20: 7042 // 7043 // For every pair (T, VQ), where T is an enumeration or 7044 // pointer to member type and VQ is either volatile or 7045 // empty, there exist candidate operator functions of the form 7046 // 7047 // VQ T& operator=(VQ T&, T); 7048 void addAssignmentMemberPointerOrEnumeralOverloads() { 7049 /// Set of (canonical) types that we've already handled. 7050 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7051 7052 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7053 for (BuiltinCandidateTypeSet::iterator 7054 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7055 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7056 Enum != EnumEnd; ++Enum) { 7057 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7058 continue; 7059 7060 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2, 7061 CandidateSet); 7062 } 7063 7064 for (BuiltinCandidateTypeSet::iterator 7065 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7066 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7067 MemPtr != MemPtrEnd; ++MemPtr) { 7068 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7069 continue; 7070 7071 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2, 7072 CandidateSet); 7073 } 7074 } 7075 } 7076 7077 // C++ [over.built]p19: 7078 // 7079 // For every pair (T, VQ), where T is any type and VQ is either 7080 // volatile or empty, there exist candidate operator functions 7081 // of the form 7082 // 7083 // T*VQ& operator=(T*VQ&, T*); 7084 // 7085 // C++ [over.built]p21: 7086 // 7087 // For every pair (T, VQ), where T is a cv-qualified or 7088 // cv-unqualified object type and VQ is either volatile or 7089 // empty, there exist candidate operator functions of the form 7090 // 7091 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7092 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7093 void addAssignmentPointerOverloads(bool isEqualOp) { 7094 /// Set of (canonical) types that we've already handled. 7095 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7096 7097 for (BuiltinCandidateTypeSet::iterator 7098 Ptr = CandidateTypes[0].pointer_begin(), 7099 PtrEnd = CandidateTypes[0].pointer_end(); 7100 Ptr != PtrEnd; ++Ptr) { 7101 // If this is operator=, keep track of the builtin candidates we added. 7102 if (isEqualOp) 7103 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7104 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7105 continue; 7106 7107 // non-volatile version 7108 QualType ParamTypes[2] = { 7109 S.Context.getLValueReferenceType(*Ptr), 7110 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7111 }; 7112 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7113 /*IsAssigmentOperator=*/ isEqualOp); 7114 7115 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7116 VisibleTypeConversionsQuals.hasVolatile(); 7117 if (NeedVolatile) { 7118 // volatile version 7119 ParamTypes[0] = 7120 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7121 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7122 /*IsAssigmentOperator=*/isEqualOp); 7123 } 7124 7125 if (!(*Ptr).isRestrictQualified() && 7126 VisibleTypeConversionsQuals.hasRestrict()) { 7127 // restrict version 7128 ParamTypes[0] 7129 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7130 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7131 /*IsAssigmentOperator=*/isEqualOp); 7132 7133 if (NeedVolatile) { 7134 // volatile restrict version 7135 ParamTypes[0] 7136 = S.Context.getLValueReferenceType( 7137 S.Context.getCVRQualifiedType(*Ptr, 7138 (Qualifiers::Volatile | 7139 Qualifiers::Restrict))); 7140 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7141 CandidateSet, 7142 /*IsAssigmentOperator=*/isEqualOp); 7143 } 7144 } 7145 } 7146 7147 if (isEqualOp) { 7148 for (BuiltinCandidateTypeSet::iterator 7149 Ptr = CandidateTypes[1].pointer_begin(), 7150 PtrEnd = CandidateTypes[1].pointer_end(); 7151 Ptr != PtrEnd; ++Ptr) { 7152 // Make sure we don't add the same candidate twice. 7153 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7154 continue; 7155 7156 QualType ParamTypes[2] = { 7157 S.Context.getLValueReferenceType(*Ptr), 7158 *Ptr, 7159 }; 7160 7161 // non-volatile version 7162 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7163 /*IsAssigmentOperator=*/true); 7164 7165 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7166 VisibleTypeConversionsQuals.hasVolatile(); 7167 if (NeedVolatile) { 7168 // volatile version 7169 ParamTypes[0] = 7170 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7171 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7172 CandidateSet, /*IsAssigmentOperator=*/true); 7173 } 7174 7175 if (!(*Ptr).isRestrictQualified() && 7176 VisibleTypeConversionsQuals.hasRestrict()) { 7177 // restrict version 7178 ParamTypes[0] 7179 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7180 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7181 CandidateSet, /*IsAssigmentOperator=*/true); 7182 7183 if (NeedVolatile) { 7184 // volatile restrict version 7185 ParamTypes[0] 7186 = S.Context.getLValueReferenceType( 7187 S.Context.getCVRQualifiedType(*Ptr, 7188 (Qualifiers::Volatile | 7189 Qualifiers::Restrict))); 7190 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7191 CandidateSet, /*IsAssigmentOperator=*/true); 7192 7193 } 7194 } 7195 } 7196 } 7197 } 7198 7199 // C++ [over.built]p18: 7200 // 7201 // For every triple (L, VQ, R), where L is an arithmetic type, 7202 // VQ is either volatile or empty, and R is a promoted 7203 // arithmetic type, there exist candidate operator functions of 7204 // the form 7205 // 7206 // VQ L& operator=(VQ L&, R); 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 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7212 if (!HasArithmeticOrEnumeralCandidateType) 7213 return; 7214 7215 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7216 for (unsigned Right = FirstPromotedArithmeticType; 7217 Right < LastPromotedArithmeticType; ++Right) { 7218 QualType ParamTypes[2]; 7219 ParamTypes[1] = getArithmeticType(Right); 7220 7221 // Add this built-in operator as a candidate (VQ is empty). 7222 ParamTypes[0] = 7223 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7224 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7225 /*IsAssigmentOperator=*/isEqualOp); 7226 7227 // Add this built-in operator as a candidate (VQ is 'volatile'). 7228 if (VisibleTypeConversionsQuals.hasVolatile()) { 7229 ParamTypes[0] = 7230 S.Context.getVolatileType(getArithmeticType(Left)); 7231 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7232 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7233 CandidateSet, 7234 /*IsAssigmentOperator=*/isEqualOp); 7235 } 7236 } 7237 } 7238 7239 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7240 for (BuiltinCandidateTypeSet::iterator 7241 Vec1 = CandidateTypes[0].vector_begin(), 7242 Vec1End = CandidateTypes[0].vector_end(); 7243 Vec1 != Vec1End; ++Vec1) { 7244 for (BuiltinCandidateTypeSet::iterator 7245 Vec2 = CandidateTypes[1].vector_begin(), 7246 Vec2End = CandidateTypes[1].vector_end(); 7247 Vec2 != Vec2End; ++Vec2) { 7248 QualType ParamTypes[2]; 7249 ParamTypes[1] = *Vec2; 7250 // Add this built-in operator as a candidate (VQ is empty). 7251 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7252 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet, 7253 /*IsAssigmentOperator=*/isEqualOp); 7254 7255 // Add this built-in operator as a candidate (VQ is 'volatile'). 7256 if (VisibleTypeConversionsQuals.hasVolatile()) { 7257 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7258 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7259 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7260 CandidateSet, 7261 /*IsAssigmentOperator=*/isEqualOp); 7262 } 7263 } 7264 } 7265 } 7266 7267 // C++ [over.built]p22: 7268 // 7269 // For every triple (L, VQ, R), where L is an integral type, VQ 7270 // is either volatile or empty, and R is a promoted integral 7271 // type, there exist candidate operator functions of the form 7272 // 7273 // VQ L& operator%=(VQ L&, R); 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 void addAssignmentIntegralOverloads() { 7280 if (!HasArithmeticOrEnumeralCandidateType) 7281 return; 7282 7283 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7284 for (unsigned Right = FirstPromotedIntegralType; 7285 Right < LastPromotedIntegralType; ++Right) { 7286 QualType ParamTypes[2]; 7287 ParamTypes[1] = getArithmeticType(Right); 7288 7289 // Add this built-in operator as a candidate (VQ is empty). 7290 ParamTypes[0] = 7291 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7292 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 7293 if (VisibleTypeConversionsQuals.hasVolatile()) { 7294 // Add this built-in operator as a candidate (VQ is 'volatile'). 7295 ParamTypes[0] = getArithmeticType(Left); 7296 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7297 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7298 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, 7299 CandidateSet); 7300 } 7301 } 7302 } 7303 } 7304 7305 // C++ [over.operator]p23: 7306 // 7307 // There also exist candidate operator functions of the form 7308 // 7309 // bool operator!(bool); 7310 // bool operator&&(bool, bool); 7311 // bool operator||(bool, bool); 7312 void addExclaimOverload() { 7313 QualType ParamTy = S.Context.BoolTy; 7314 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet, 7315 /*IsAssignmentOperator=*/false, 7316 /*NumContextualBoolArguments=*/1); 7317 } 7318 void addAmpAmpOrPipePipeOverload() { 7319 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7320 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet, 7321 /*IsAssignmentOperator=*/false, 7322 /*NumContextualBoolArguments=*/2); 7323 } 7324 7325 // C++ [over.built]p13: 7326 // 7327 // For every cv-qualified or cv-unqualified object type T there 7328 // exist candidate operator functions of the form 7329 // 7330 // T* operator+(T*, ptrdiff_t); [ABOVE] 7331 // T& operator[](T*, ptrdiff_t); 7332 // T* operator-(T*, ptrdiff_t); [ABOVE] 7333 // T* operator+(ptrdiff_t, T*); [ABOVE] 7334 // T& operator[](ptrdiff_t, T*); 7335 void addSubscriptOverloads() { 7336 for (BuiltinCandidateTypeSet::iterator 7337 Ptr = CandidateTypes[0].pointer_begin(), 7338 PtrEnd = CandidateTypes[0].pointer_end(); 7339 Ptr != PtrEnd; ++Ptr) { 7340 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7341 QualType PointeeType = (*Ptr)->getPointeeType(); 7342 if (!PointeeType->isObjectType()) 7343 continue; 7344 7345 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7346 7347 // T& operator[](T*, ptrdiff_t) 7348 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7349 } 7350 7351 for (BuiltinCandidateTypeSet::iterator 7352 Ptr = CandidateTypes[1].pointer_begin(), 7353 PtrEnd = CandidateTypes[1].pointer_end(); 7354 Ptr != PtrEnd; ++Ptr) { 7355 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7356 QualType PointeeType = (*Ptr)->getPointeeType(); 7357 if (!PointeeType->isObjectType()) 7358 continue; 7359 7360 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7361 7362 // T& operator[](ptrdiff_t, T*) 7363 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7364 } 7365 } 7366 7367 // C++ [over.built]p11: 7368 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7369 // C1 is the same type as C2 or is a derived class of C2, T is an object 7370 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7371 // there exist candidate operator functions of the form 7372 // 7373 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7374 // 7375 // where CV12 is the union of CV1 and CV2. 7376 void addArrowStarOverloads() { 7377 for (BuiltinCandidateTypeSet::iterator 7378 Ptr = CandidateTypes[0].pointer_begin(), 7379 PtrEnd = CandidateTypes[0].pointer_end(); 7380 Ptr != PtrEnd; ++Ptr) { 7381 QualType C1Ty = (*Ptr); 7382 QualType C1; 7383 QualifierCollector Q1; 7384 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 7385 if (!isa<RecordType>(C1)) 7386 continue; 7387 // heuristic to reduce number of builtin candidates in the set. 7388 // Add volatile/restrict version only if there are conversions to a 7389 // volatile/restrict type. 7390 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 7391 continue; 7392 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 7393 continue; 7394 for (BuiltinCandidateTypeSet::iterator 7395 MemPtr = CandidateTypes[1].member_pointer_begin(), 7396 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 7397 MemPtr != MemPtrEnd; ++MemPtr) { 7398 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 7399 QualType C2 = QualType(mptr->getClass(), 0); 7400 C2 = C2.getUnqualifiedType(); 7401 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 7402 break; 7403 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 7404 // build CV12 T& 7405 QualType T = mptr->getPointeeType(); 7406 if (!VisibleTypeConversionsQuals.hasVolatile() && 7407 T.isVolatileQualified()) 7408 continue; 7409 if (!VisibleTypeConversionsQuals.hasRestrict() && 7410 T.isRestrictQualified()) 7411 continue; 7412 T = Q1.apply(S.Context, T); 7413 QualType ResultTy = S.Context.getLValueReferenceType(T); 7414 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 7415 } 7416 } 7417 } 7418 7419 // Note that we don't consider the first argument, since it has been 7420 // contextually converted to bool long ago. The candidates below are 7421 // therefore added as binary. 7422 // 7423 // C++ [over.built]p25: 7424 // For every type T, where T is a pointer, pointer-to-member, or scoped 7425 // enumeration type, there exist candidate operator functions of the form 7426 // 7427 // T operator?(bool, T, T); 7428 // 7429 void addConditionalOperatorOverloads() { 7430 /// Set of (canonical) types that we've already handled. 7431 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7432 7433 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7434 for (BuiltinCandidateTypeSet::iterator 7435 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7436 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7437 Ptr != PtrEnd; ++Ptr) { 7438 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7439 continue; 7440 7441 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7442 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 7443 } 7444 7445 for (BuiltinCandidateTypeSet::iterator 7446 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7447 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7448 MemPtr != MemPtrEnd; ++MemPtr) { 7449 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7450 continue; 7451 7452 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7453 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet); 7454 } 7455 7456 if (S.getLangOpts().CPlusPlus0x) { 7457 for (BuiltinCandidateTypeSet::iterator 7458 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7459 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7460 Enum != EnumEnd; ++Enum) { 7461 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 7462 continue; 7463 7464 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7465 continue; 7466 7467 QualType ParamTypes[2] = { *Enum, *Enum }; 7468 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet); 7469 } 7470 } 7471 } 7472 } 7473 }; 7474 7475 } // end anonymous namespace 7476 7477 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 7478 /// operator overloads to the candidate set (C++ [over.built]), based 7479 /// on the operator @p Op and the arguments given. For example, if the 7480 /// operator is a binary '+', this routine might add "int 7481 /// operator+(int, int)" to cover integer addition. 7482 void 7483 Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 7484 SourceLocation OpLoc, 7485 Expr **Args, unsigned NumArgs, 7486 OverloadCandidateSet& CandidateSet) { 7487 // Find all of the types that the arguments can convert to, but only 7488 // if the operator we're looking at has built-in operator candidates 7489 // that make use of these types. Also record whether we encounter non-record 7490 // candidate types or either arithmetic or enumeral candidate types. 7491 Qualifiers VisibleTypeConversionsQuals; 7492 VisibleTypeConversionsQuals.addConst(); 7493 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 7494 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 7495 7496 bool HasNonRecordCandidateType = false; 7497 bool HasArithmeticOrEnumeralCandidateType = false; 7498 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 7499 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 7500 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 7501 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 7502 OpLoc, 7503 true, 7504 (Op == OO_Exclaim || 7505 Op == OO_AmpAmp || 7506 Op == OO_PipePipe), 7507 VisibleTypeConversionsQuals); 7508 HasNonRecordCandidateType = HasNonRecordCandidateType || 7509 CandidateTypes[ArgIdx].hasNonRecordTypes(); 7510 HasArithmeticOrEnumeralCandidateType = 7511 HasArithmeticOrEnumeralCandidateType || 7512 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 7513 } 7514 7515 // Exit early when no non-record types have been added to the candidate set 7516 // for any of the arguments to the operator. 7517 // 7518 // We can't exit early for !, ||, or &&, since there we have always have 7519 // 'bool' overloads. 7520 if (!HasNonRecordCandidateType && 7521 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 7522 return; 7523 7524 // Setup an object to manage the common state for building overloads. 7525 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs, 7526 VisibleTypeConversionsQuals, 7527 HasArithmeticOrEnumeralCandidateType, 7528 CandidateTypes, CandidateSet); 7529 7530 // Dispatch over the operation to add in only those overloads which apply. 7531 switch (Op) { 7532 case OO_None: 7533 case NUM_OVERLOADED_OPERATORS: 7534 llvm_unreachable("Expected an overloaded operator"); 7535 7536 case OO_New: 7537 case OO_Delete: 7538 case OO_Array_New: 7539 case OO_Array_Delete: 7540 case OO_Call: 7541 llvm_unreachable( 7542 "Special operators don't use AddBuiltinOperatorCandidates"); 7543 7544 case OO_Comma: 7545 case OO_Arrow: 7546 // C++ [over.match.oper]p3: 7547 // -- For the operator ',', the unary operator '&', or the 7548 // operator '->', the built-in candidates set is empty. 7549 break; 7550 7551 case OO_Plus: // '+' is either unary or binary 7552 if (NumArgs == 1) 7553 OpBuilder.addUnaryPlusPointerOverloads(); 7554 // Fall through. 7555 7556 case OO_Minus: // '-' is either unary or binary 7557 if (NumArgs == 1) { 7558 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 7559 } else { 7560 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 7561 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7562 } 7563 break; 7564 7565 case OO_Star: // '*' is either unary or binary 7566 if (NumArgs == 1) 7567 OpBuilder.addUnaryStarPointerOverloads(); 7568 else 7569 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7570 break; 7571 7572 case OO_Slash: 7573 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7574 break; 7575 7576 case OO_PlusPlus: 7577 case OO_MinusMinus: 7578 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 7579 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 7580 break; 7581 7582 case OO_EqualEqual: 7583 case OO_ExclaimEqual: 7584 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 7585 // Fall through. 7586 7587 case OO_Less: 7588 case OO_Greater: 7589 case OO_LessEqual: 7590 case OO_GreaterEqual: 7591 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 7592 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 7593 break; 7594 7595 case OO_Percent: 7596 case OO_Caret: 7597 case OO_Pipe: 7598 case OO_LessLess: 7599 case OO_GreaterGreater: 7600 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7601 break; 7602 7603 case OO_Amp: // '&' is either unary or binary 7604 if (NumArgs == 1) 7605 // C++ [over.match.oper]p3: 7606 // -- For the operator ',', the unary operator '&', or the 7607 // operator '->', the built-in candidates set is empty. 7608 break; 7609 7610 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 7611 break; 7612 7613 case OO_Tilde: 7614 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 7615 break; 7616 7617 case OO_Equal: 7618 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 7619 // Fall through. 7620 7621 case OO_PlusEqual: 7622 case OO_MinusEqual: 7623 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 7624 // Fall through. 7625 7626 case OO_StarEqual: 7627 case OO_SlashEqual: 7628 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 7629 break; 7630 7631 case OO_PercentEqual: 7632 case OO_LessLessEqual: 7633 case OO_GreaterGreaterEqual: 7634 case OO_AmpEqual: 7635 case OO_CaretEqual: 7636 case OO_PipeEqual: 7637 OpBuilder.addAssignmentIntegralOverloads(); 7638 break; 7639 7640 case OO_Exclaim: 7641 OpBuilder.addExclaimOverload(); 7642 break; 7643 7644 case OO_AmpAmp: 7645 case OO_PipePipe: 7646 OpBuilder.addAmpAmpOrPipePipeOverload(); 7647 break; 7648 7649 case OO_Subscript: 7650 OpBuilder.addSubscriptOverloads(); 7651 break; 7652 7653 case OO_ArrowStar: 7654 OpBuilder.addArrowStarOverloads(); 7655 break; 7656 7657 case OO_Conditional: 7658 OpBuilder.addConditionalOperatorOverloads(); 7659 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7660 break; 7661 } 7662 } 7663 7664 /// \brief Add function candidates found via argument-dependent lookup 7665 /// to the set of overloading candidates. 7666 /// 7667 /// This routine performs argument-dependent name lookup based on the 7668 /// given function name (which may also be an operator name) and adds 7669 /// all of the overload candidates found by ADL to the overload 7670 /// candidate set (C++ [basic.lookup.argdep]). 7671 void 7672 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 7673 bool Operator, SourceLocation Loc, 7674 llvm::ArrayRef<Expr *> Args, 7675 TemplateArgumentListInfo *ExplicitTemplateArgs, 7676 OverloadCandidateSet& CandidateSet, 7677 bool PartialOverloading, 7678 bool StdNamespaceIsAssociated) { 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 StdNamespaceIsAssociated); 7691 7692 // Erase all of the candidates we already knew about. 7693 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 7694 CandEnd = CandidateSet.end(); 7695 Cand != CandEnd; ++Cand) 7696 if (Cand->Function) { 7697 Fns.erase(Cand->Function); 7698 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 7699 Fns.erase(FunTmpl); 7700 } 7701 7702 // For each of the ADL candidates we found, add it to the overload 7703 // set. 7704 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 7705 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 7706 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 7707 if (ExplicitTemplateArgs) 7708 continue; 7709 7710 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 7711 PartialOverloading); 7712 } else 7713 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 7714 FoundDecl, ExplicitTemplateArgs, 7715 Args, CandidateSet); 7716 } 7717 } 7718 7719 /// isBetterOverloadCandidate - Determines whether the first overload 7720 /// candidate is a better candidate than the second (C++ 13.3.3p1). 7721 bool 7722 isBetterOverloadCandidate(Sema &S, 7723 const OverloadCandidate &Cand1, 7724 const OverloadCandidate &Cand2, 7725 SourceLocation Loc, 7726 bool UserDefinedConversion) { 7727 // Define viable functions to be better candidates than non-viable 7728 // functions. 7729 if (!Cand2.Viable) 7730 return Cand1.Viable; 7731 else if (!Cand1.Viable) 7732 return false; 7733 7734 // C++ [over.match.best]p1: 7735 // 7736 // -- if F is a static member function, ICS1(F) is defined such 7737 // that ICS1(F) is neither better nor worse than ICS1(G) for 7738 // any function G, and, symmetrically, ICS1(G) is neither 7739 // better nor worse than ICS1(F). 7740 unsigned StartArg = 0; 7741 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 7742 StartArg = 1; 7743 7744 // C++ [over.match.best]p1: 7745 // A viable function F1 is defined to be a better function than another 7746 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 7747 // conversion sequence than ICSi(F2), and then... 7748 unsigned NumArgs = Cand1.NumConversions; 7749 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 7750 bool HasBetterConversion = false; 7751 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 7752 switch (CompareImplicitConversionSequences(S, 7753 Cand1.Conversions[ArgIdx], 7754 Cand2.Conversions[ArgIdx])) { 7755 case ImplicitConversionSequence::Better: 7756 // Cand1 has a better conversion sequence. 7757 HasBetterConversion = true; 7758 break; 7759 7760 case ImplicitConversionSequence::Worse: 7761 // Cand1 can't be better than Cand2. 7762 return false; 7763 7764 case ImplicitConversionSequence::Indistinguishable: 7765 // Do nothing. 7766 break; 7767 } 7768 } 7769 7770 // -- for some argument j, ICSj(F1) is a better conversion sequence than 7771 // ICSj(F2), or, if not that, 7772 if (HasBetterConversion) 7773 return true; 7774 7775 // - F1 is a non-template function and F2 is a function template 7776 // specialization, or, if not that, 7777 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 7778 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 7779 return true; 7780 7781 // -- F1 and F2 are function template specializations, and the function 7782 // template for F1 is more specialized than the template for F2 7783 // according to the partial ordering rules described in 14.5.5.2, or, 7784 // if not that, 7785 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 7786 Cand2.Function && Cand2.Function->getPrimaryTemplate()) { 7787 if (FunctionTemplateDecl *BetterTemplate 7788 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 7789 Cand2.Function->getPrimaryTemplate(), 7790 Loc, 7791 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 7792 : TPOC_Call, 7793 Cand1.ExplicitCallArguments)) 7794 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 7795 } 7796 7797 // -- the context is an initialization by user-defined conversion 7798 // (see 8.5, 13.3.1.5) and the standard conversion sequence 7799 // from the return type of F1 to the destination type (i.e., 7800 // the type of the entity being initialized) is a better 7801 // conversion sequence than the standard conversion sequence 7802 // from the return type of F2 to the destination type. 7803 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 7804 isa<CXXConversionDecl>(Cand1.Function) && 7805 isa<CXXConversionDecl>(Cand2.Function)) { 7806 // First check whether we prefer one of the conversion functions over the 7807 // other. This only distinguishes the results in non-standard, extension 7808 // cases such as the conversion from a lambda closure type to a function 7809 // pointer or block. 7810 ImplicitConversionSequence::CompareKind FuncResult 7811 = compareConversionFunctions(S, Cand1.Function, Cand2.Function); 7812 if (FuncResult != ImplicitConversionSequence::Indistinguishable) 7813 return FuncResult; 7814 7815 switch (CompareStandardConversionSequences(S, 7816 Cand1.FinalConversion, 7817 Cand2.FinalConversion)) { 7818 case ImplicitConversionSequence::Better: 7819 // Cand1 has a better conversion sequence. 7820 return true; 7821 7822 case ImplicitConversionSequence::Worse: 7823 // Cand1 can't be better than Cand2. 7824 return false; 7825 7826 case ImplicitConversionSequence::Indistinguishable: 7827 // Do nothing 7828 break; 7829 } 7830 } 7831 7832 return false; 7833 } 7834 7835 /// \brief Computes the best viable function (C++ 13.3.3) 7836 /// within an overload candidate set. 7837 /// 7838 /// \param Loc The location of the function name (or operator symbol) for 7839 /// which overload resolution occurs. 7840 /// 7841 /// \param Best If overload resolution was successful or found a deleted 7842 /// function, \p Best points to the candidate function found. 7843 /// 7844 /// \returns The result of overload resolution. 7845 OverloadingResult 7846 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 7847 iterator &Best, 7848 bool UserDefinedConversion) { 7849 // Find the best viable function. 7850 Best = end(); 7851 for (iterator Cand = begin(); Cand != end(); ++Cand) { 7852 if (Cand->Viable) 7853 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 7854 UserDefinedConversion)) 7855 Best = Cand; 7856 } 7857 7858 // If we didn't find any viable functions, abort. 7859 if (Best == end()) 7860 return OR_No_Viable_Function; 7861 7862 // Make sure that this function is better than every other viable 7863 // function. If not, we have an ambiguity. 7864 for (iterator Cand = begin(); Cand != end(); ++Cand) { 7865 if (Cand->Viable && 7866 Cand != Best && 7867 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 7868 UserDefinedConversion)) { 7869 Best = end(); 7870 return OR_Ambiguous; 7871 } 7872 } 7873 7874 // Best is the best viable function. 7875 if (Best->Function && 7876 (Best->Function->isDeleted() || 7877 S.isFunctionConsideredUnavailable(Best->Function))) 7878 return OR_Deleted; 7879 7880 return OR_Success; 7881 } 7882 7883 namespace { 7884 7885 enum OverloadCandidateKind { 7886 oc_function, 7887 oc_method, 7888 oc_constructor, 7889 oc_function_template, 7890 oc_method_template, 7891 oc_constructor_template, 7892 oc_implicit_default_constructor, 7893 oc_implicit_copy_constructor, 7894 oc_implicit_move_constructor, 7895 oc_implicit_copy_assignment, 7896 oc_implicit_move_assignment, 7897 oc_implicit_inherited_constructor 7898 }; 7899 7900 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 7901 FunctionDecl *Fn, 7902 std::string &Description) { 7903 bool isTemplate = false; 7904 7905 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 7906 isTemplate = true; 7907 Description = S.getTemplateArgumentBindingsText( 7908 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 7909 } 7910 7911 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 7912 if (!Ctor->isImplicit()) 7913 return isTemplate ? oc_constructor_template : oc_constructor; 7914 7915 if (Ctor->getInheritedConstructor()) 7916 return oc_implicit_inherited_constructor; 7917 7918 if (Ctor->isDefaultConstructor()) 7919 return oc_implicit_default_constructor; 7920 7921 if (Ctor->isMoveConstructor()) 7922 return oc_implicit_move_constructor; 7923 7924 assert(Ctor->isCopyConstructor() && 7925 "unexpected sort of implicit constructor"); 7926 return oc_implicit_copy_constructor; 7927 } 7928 7929 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 7930 // This actually gets spelled 'candidate function' for now, but 7931 // it doesn't hurt to split it out. 7932 if (!Meth->isImplicit()) 7933 return isTemplate ? oc_method_template : oc_method; 7934 7935 if (Meth->isMoveAssignmentOperator()) 7936 return oc_implicit_move_assignment; 7937 7938 if (Meth->isCopyAssignmentOperator()) 7939 return oc_implicit_copy_assignment; 7940 7941 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 7942 return oc_method; 7943 } 7944 7945 return isTemplate ? oc_function_template : oc_function; 7946 } 7947 7948 void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) { 7949 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 7950 if (!Ctor) return; 7951 7952 Ctor = Ctor->getInheritedConstructor(); 7953 if (!Ctor) return; 7954 7955 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 7956 } 7957 7958 } // end anonymous namespace 7959 7960 // Notes the location of an overload candidate. 7961 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 7962 std::string FnDesc; 7963 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 7964 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 7965 << (unsigned) K << FnDesc; 7966 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 7967 Diag(Fn->getLocation(), PD); 7968 MaybeEmitInheritedConstructorNote(*this, Fn); 7969 } 7970 7971 //Notes the location of all overload candidates designated through 7972 // OverloadedExpr 7973 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 7974 assert(OverloadedExpr->getType() == Context.OverloadTy); 7975 7976 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 7977 OverloadExpr *OvlExpr = Ovl.Expression; 7978 7979 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 7980 IEnd = OvlExpr->decls_end(); 7981 I != IEnd; ++I) { 7982 if (FunctionTemplateDecl *FunTmpl = 7983 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 7984 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 7985 } else if (FunctionDecl *Fun 7986 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 7987 NoteOverloadCandidate(Fun, DestType); 7988 } 7989 } 7990 } 7991 7992 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 7993 /// "lead" diagnostic; it will be given two arguments, the source and 7994 /// target types of the conversion. 7995 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 7996 Sema &S, 7997 SourceLocation CaretLoc, 7998 const PartialDiagnostic &PDiag) const { 7999 S.Diag(CaretLoc, PDiag) 8000 << Ambiguous.getFromType() << Ambiguous.getToType(); 8001 for (AmbiguousConversionSequence::const_iterator 8002 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8003 S.NoteOverloadCandidate(*I); 8004 } 8005 } 8006 8007 namespace { 8008 8009 void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 8010 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8011 assert(Conv.isBad()); 8012 assert(Cand->Function && "for now, candidate must be a function"); 8013 FunctionDecl *Fn = Cand->Function; 8014 8015 // There's a conversion slot for the object argument if this is a 8016 // non-constructor method. Note that 'I' corresponds the 8017 // conversion-slot index. 8018 bool isObjectArgument = false; 8019 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8020 if (I == 0) 8021 isObjectArgument = true; 8022 else 8023 I--; 8024 } 8025 8026 std::string FnDesc; 8027 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8028 8029 Expr *FromExpr = Conv.Bad.FromExpr; 8030 QualType FromTy = Conv.Bad.getFromType(); 8031 QualType ToTy = Conv.Bad.getToType(); 8032 8033 if (FromTy == S.Context.OverloadTy) { 8034 assert(FromExpr && "overload set argument came from implicit argument?"); 8035 Expr *E = FromExpr->IgnoreParens(); 8036 if (isa<UnaryOperator>(E)) 8037 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8038 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8039 8040 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8041 << (unsigned) FnKind << FnDesc 8042 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8043 << ToTy << Name << I+1; 8044 MaybeEmitInheritedConstructorNote(S, Fn); 8045 return; 8046 } 8047 8048 // Do some hand-waving analysis to see if the non-viability is due 8049 // to a qualifier mismatch. 8050 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8051 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8052 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8053 CToTy = RT->getPointeeType(); 8054 else { 8055 // TODO: detect and diagnose the full richness of const mismatches. 8056 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8057 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8058 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8059 } 8060 8061 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8062 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8063 Qualifiers FromQs = CFromTy.getQualifiers(); 8064 Qualifiers ToQs = CToTy.getQualifiers(); 8065 8066 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8067 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8068 << (unsigned) FnKind << FnDesc 8069 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8070 << FromTy 8071 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8072 << (unsigned) isObjectArgument << I+1; 8073 MaybeEmitInheritedConstructorNote(S, Fn); 8074 return; 8075 } 8076 8077 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8078 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8079 << (unsigned) FnKind << FnDesc 8080 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8081 << FromTy 8082 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8083 << (unsigned) isObjectArgument << I+1; 8084 MaybeEmitInheritedConstructorNote(S, Fn); 8085 return; 8086 } 8087 8088 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8089 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8090 << (unsigned) FnKind << FnDesc 8091 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8092 << FromTy 8093 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8094 << (unsigned) isObjectArgument << I+1; 8095 MaybeEmitInheritedConstructorNote(S, Fn); 8096 return; 8097 } 8098 8099 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8100 assert(CVR && "unexpected qualifiers mismatch"); 8101 8102 if (isObjectArgument) { 8103 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8104 << (unsigned) FnKind << FnDesc 8105 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8106 << FromTy << (CVR - 1); 8107 } else { 8108 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8109 << (unsigned) FnKind << FnDesc 8110 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8111 << FromTy << (CVR - 1) << I+1; 8112 } 8113 MaybeEmitInheritedConstructorNote(S, Fn); 8114 return; 8115 } 8116 8117 // Special diagnostic for failure to convert an initializer list, since 8118 // telling the user that it has type void is not useful. 8119 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8120 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8121 << (unsigned) FnKind << FnDesc 8122 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8123 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8124 MaybeEmitInheritedConstructorNote(S, Fn); 8125 return; 8126 } 8127 8128 // Diagnose references or pointers to incomplete types differently, 8129 // since it's far from impossible that the incompleteness triggered 8130 // the failure. 8131 QualType TempFromTy = FromTy.getNonReferenceType(); 8132 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8133 TempFromTy = PTy->getPointeeType(); 8134 if (TempFromTy->isIncompleteType()) { 8135 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8136 << (unsigned) FnKind << FnDesc 8137 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8138 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8139 MaybeEmitInheritedConstructorNote(S, Fn); 8140 return; 8141 } 8142 8143 // Diagnose base -> derived pointer conversions. 8144 unsigned BaseToDerivedConversion = 0; 8145 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8146 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8147 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8148 FromPtrTy->getPointeeType()) && 8149 !FromPtrTy->getPointeeType()->isIncompleteType() && 8150 !ToPtrTy->getPointeeType()->isIncompleteType() && 8151 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8152 FromPtrTy->getPointeeType())) 8153 BaseToDerivedConversion = 1; 8154 } 8155 } else if (const ObjCObjectPointerType *FromPtrTy 8156 = FromTy->getAs<ObjCObjectPointerType>()) { 8157 if (const ObjCObjectPointerType *ToPtrTy 8158 = ToTy->getAs<ObjCObjectPointerType>()) 8159 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8160 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8161 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8162 FromPtrTy->getPointeeType()) && 8163 FromIface->isSuperClassOf(ToIface)) 8164 BaseToDerivedConversion = 2; 8165 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8166 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8167 !FromTy->isIncompleteType() && 8168 !ToRefTy->getPointeeType()->isIncompleteType() && 8169 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8170 BaseToDerivedConversion = 3; 8171 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8172 ToTy.getNonReferenceType().getCanonicalType() == 8173 FromTy.getNonReferenceType().getCanonicalType()) { 8174 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8175 << (unsigned) FnKind << FnDesc 8176 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8177 << (unsigned) isObjectArgument << I + 1; 8178 MaybeEmitInheritedConstructorNote(S, Fn); 8179 return; 8180 } 8181 } 8182 8183 if (BaseToDerivedConversion) { 8184 S.Diag(Fn->getLocation(), 8185 diag::note_ovl_candidate_bad_base_to_derived_conv) 8186 << (unsigned) FnKind << FnDesc 8187 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8188 << (BaseToDerivedConversion - 1) 8189 << FromTy << ToTy << I+1; 8190 MaybeEmitInheritedConstructorNote(S, Fn); 8191 return; 8192 } 8193 8194 if (isa<ObjCObjectPointerType>(CFromTy) && 8195 isa<PointerType>(CToTy)) { 8196 Qualifiers FromQs = CFromTy.getQualifiers(); 8197 Qualifiers ToQs = CToTy.getQualifiers(); 8198 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8199 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8200 << (unsigned) FnKind << FnDesc 8201 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8202 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8203 MaybeEmitInheritedConstructorNote(S, Fn); 8204 return; 8205 } 8206 } 8207 8208 // Emit the generic diagnostic and, optionally, add the hints to it. 8209 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8210 FDiag << (unsigned) FnKind << FnDesc 8211 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8212 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8213 << (unsigned) (Cand->Fix.Kind); 8214 8215 // If we can fix the conversion, suggest the FixIts. 8216 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8217 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8218 FDiag << *HI; 8219 S.Diag(Fn->getLocation(), FDiag); 8220 8221 MaybeEmitInheritedConstructorNote(S, Fn); 8222 } 8223 8224 void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8225 unsigned NumFormalArgs) { 8226 // TODO: treat calls to a missing default constructor as a special case 8227 8228 FunctionDecl *Fn = Cand->Function; 8229 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8230 8231 unsigned MinParams = Fn->getMinRequiredArguments(); 8232 8233 // With invalid overloaded operators, it's possible that we think we 8234 // have an arity mismatch when it fact it looks like we have the 8235 // right number of arguments, because only overloaded operators have 8236 // the weird behavior of overloading member and non-member functions. 8237 // Just don't report anything. 8238 if (Fn->isInvalidDecl() && 8239 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8240 return; 8241 8242 // at least / at most / exactly 8243 unsigned mode, modeCount; 8244 if (NumFormalArgs < MinParams) { 8245 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8246 (Cand->FailureKind == ovl_fail_bad_deduction && 8247 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8248 if (MinParams != FnTy->getNumArgs() || 8249 FnTy->isVariadic() || FnTy->isTemplateVariadic()) 8250 mode = 0; // "at least" 8251 else 8252 mode = 2; // "exactly" 8253 modeCount = MinParams; 8254 } else { 8255 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8256 (Cand->FailureKind == ovl_fail_bad_deduction && 8257 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8258 if (MinParams != FnTy->getNumArgs()) 8259 mode = 1; // "at most" 8260 else 8261 mode = 2; // "exactly" 8262 modeCount = FnTy->getNumArgs(); 8263 } 8264 8265 std::string Description; 8266 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8267 8268 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8269 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8270 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8271 << Fn->getParamDecl(0) << NumFormalArgs; 8272 else 8273 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8274 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8275 << modeCount << NumFormalArgs; 8276 MaybeEmitInheritedConstructorNote(S, Fn); 8277 } 8278 8279 /// Diagnose a failed template-argument deduction. 8280 void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 8281 unsigned NumArgs) { 8282 FunctionDecl *Fn = Cand->Function; // pattern 8283 8284 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter(); 8285 NamedDecl *ParamD; 8286 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8287 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8288 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8289 switch (Cand->DeductionFailure.Result) { 8290 case Sema::TDK_Success: 8291 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8292 8293 case Sema::TDK_Incomplete: { 8294 assert(ParamD && "no parameter found for incomplete deduction result"); 8295 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction) 8296 << ParamD->getDeclName(); 8297 MaybeEmitInheritedConstructorNote(S, Fn); 8298 return; 8299 } 8300 8301 case Sema::TDK_Underqualified: { 8302 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8303 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 8304 8305 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType(); 8306 8307 // Param will have been canonicalized, but it should just be a 8308 // qualified version of ParamD, so move the qualifiers to that. 8309 QualifierCollector Qs; 8310 Qs.strip(Param); 8311 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 8312 assert(S.Context.hasSameType(Param, NonCanonParam)); 8313 8314 // Arg has also been canonicalized, but there's nothing we can do 8315 // about that. It also doesn't matter as much, because it won't 8316 // have any template parameters in it (because deduction isn't 8317 // done on dependent types). 8318 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType(); 8319 8320 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified) 8321 << ParamD->getDeclName() << Arg << NonCanonParam; 8322 MaybeEmitInheritedConstructorNote(S, Fn); 8323 return; 8324 } 8325 8326 case Sema::TDK_Inconsistent: { 8327 assert(ParamD && "no parameter found for inconsistent deduction result"); 8328 int which = 0; 8329 if (isa<TemplateTypeParmDecl>(ParamD)) 8330 which = 0; 8331 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 8332 which = 1; 8333 else { 8334 which = 2; 8335 } 8336 8337 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction) 8338 << which << ParamD->getDeclName() 8339 << *Cand->DeductionFailure.getFirstArg() 8340 << *Cand->DeductionFailure.getSecondArg(); 8341 MaybeEmitInheritedConstructorNote(S, Fn); 8342 return; 8343 } 8344 8345 case Sema::TDK_InvalidExplicitArguments: 8346 assert(ParamD && "no parameter found for invalid explicit arguments"); 8347 if (ParamD->getDeclName()) 8348 S.Diag(Fn->getLocation(), 8349 diag::note_ovl_candidate_explicit_arg_mismatch_named) 8350 << ParamD->getDeclName(); 8351 else { 8352 int index = 0; 8353 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 8354 index = TTP->getIndex(); 8355 else if (NonTypeTemplateParmDecl *NTTP 8356 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 8357 index = NTTP->getIndex(); 8358 else 8359 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 8360 S.Diag(Fn->getLocation(), 8361 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 8362 << (index + 1); 8363 } 8364 MaybeEmitInheritedConstructorNote(S, Fn); 8365 return; 8366 8367 case Sema::TDK_TooManyArguments: 8368 case Sema::TDK_TooFewArguments: 8369 DiagnoseArityMismatch(S, Cand, NumArgs); 8370 return; 8371 8372 case Sema::TDK_InstantiationDepth: 8373 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth); 8374 MaybeEmitInheritedConstructorNote(S, Fn); 8375 return; 8376 8377 case Sema::TDK_SubstitutionFailure: { 8378 // Format the template argument list into the argument string. 8379 llvm::SmallString<128> TemplateArgString; 8380 if (TemplateArgumentList *Args = 8381 Cand->DeductionFailure.getTemplateArgumentList()) { 8382 TemplateArgString = " "; 8383 TemplateArgString += S.getTemplateArgumentBindingsText( 8384 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args); 8385 } 8386 8387 // If this candidate was disabled by enable_if, say so. 8388 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic(); 8389 if (PDiag && PDiag->second.getDiagID() == 8390 diag::err_typename_nested_not_found_enable_if) { 8391 // FIXME: Use the source range of the condition, and the fully-qualified 8392 // name of the enable_if template. These are both present in PDiag. 8393 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 8394 << "'enable_if'" << TemplateArgString; 8395 return; 8396 } 8397 8398 // Format the SFINAE diagnostic into the argument string. 8399 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 8400 // formatted message in another diagnostic. 8401 llvm::SmallString<128> SFINAEArgString; 8402 SourceRange R; 8403 if (PDiag) { 8404 SFINAEArgString = ": "; 8405 R = SourceRange(PDiag->first, PDiag->first); 8406 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 8407 } 8408 8409 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure) 8410 << TemplateArgString << SFINAEArgString << R; 8411 MaybeEmitInheritedConstructorNote(S, Fn); 8412 return; 8413 } 8414 8415 // TODO: diagnose these individually, then kill off 8416 // note_ovl_candidate_bad_deduction, which is uselessly vague. 8417 case Sema::TDK_NonDeducedMismatch: 8418 case Sema::TDK_FailedOverloadResolution: 8419 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction); 8420 MaybeEmitInheritedConstructorNote(S, Fn); 8421 return; 8422 } 8423 } 8424 8425 /// CUDA: diagnose an invalid call across targets. 8426 void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 8427 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 8428 FunctionDecl *Callee = Cand->Function; 8429 8430 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 8431 CalleeTarget = S.IdentifyCUDATarget(Callee); 8432 8433 std::string FnDesc; 8434 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 8435 8436 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 8437 << (unsigned) FnKind << CalleeTarget << CallerTarget; 8438 } 8439 8440 /// Generates a 'note' diagnostic for an overload candidate. We've 8441 /// already generated a primary error at the call site. 8442 /// 8443 /// It really does need to be a single diagnostic with its caret 8444 /// pointed at the candidate declaration. Yes, this creates some 8445 /// major challenges of technical writing. Yes, this makes pointing 8446 /// out problems with specific arguments quite awkward. It's still 8447 /// better than generating twenty screens of text for every failed 8448 /// overload. 8449 /// 8450 /// It would be great to be able to express per-candidate problems 8451 /// more richly for those diagnostic clients that cared, but we'd 8452 /// still have to be just as careful with the default diagnostics. 8453 void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 8454 unsigned NumArgs) { 8455 FunctionDecl *Fn = Cand->Function; 8456 8457 // Note deleted candidates, but only if they're viable. 8458 if (Cand->Viable && (Fn->isDeleted() || 8459 S.isFunctionConsideredUnavailable(Fn))) { 8460 std::string FnDesc; 8461 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8462 8463 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 8464 << FnKind << FnDesc 8465 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 8466 MaybeEmitInheritedConstructorNote(S, Fn); 8467 return; 8468 } 8469 8470 // We don't really have anything else to say about viable candidates. 8471 if (Cand->Viable) { 8472 S.NoteOverloadCandidate(Fn); 8473 return; 8474 } 8475 8476 switch (Cand->FailureKind) { 8477 case ovl_fail_too_many_arguments: 8478 case ovl_fail_too_few_arguments: 8479 return DiagnoseArityMismatch(S, Cand, NumArgs); 8480 8481 case ovl_fail_bad_deduction: 8482 return DiagnoseBadDeduction(S, Cand, NumArgs); 8483 8484 case ovl_fail_trivial_conversion: 8485 case ovl_fail_bad_final_conversion: 8486 case ovl_fail_final_conversion_not_exact: 8487 return S.NoteOverloadCandidate(Fn); 8488 8489 case ovl_fail_bad_conversion: { 8490 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 8491 for (unsigned N = Cand->NumConversions; I != N; ++I) 8492 if (Cand->Conversions[I].isBad()) 8493 return DiagnoseBadConversion(S, Cand, I); 8494 8495 // FIXME: this currently happens when we're called from SemaInit 8496 // when user-conversion overload fails. Figure out how to handle 8497 // those conditions and diagnose them well. 8498 return S.NoteOverloadCandidate(Fn); 8499 } 8500 8501 case ovl_fail_bad_target: 8502 return DiagnoseBadTarget(S, Cand); 8503 } 8504 } 8505 8506 void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 8507 // Desugar the type of the surrogate down to a function type, 8508 // retaining as many typedefs as possible while still showing 8509 // the function type (and, therefore, its parameter types). 8510 QualType FnType = Cand->Surrogate->getConversionType(); 8511 bool isLValueReference = false; 8512 bool isRValueReference = false; 8513 bool isPointer = false; 8514 if (const LValueReferenceType *FnTypeRef = 8515 FnType->getAs<LValueReferenceType>()) { 8516 FnType = FnTypeRef->getPointeeType(); 8517 isLValueReference = true; 8518 } else if (const RValueReferenceType *FnTypeRef = 8519 FnType->getAs<RValueReferenceType>()) { 8520 FnType = FnTypeRef->getPointeeType(); 8521 isRValueReference = true; 8522 } 8523 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 8524 FnType = FnTypePtr->getPointeeType(); 8525 isPointer = true; 8526 } 8527 // Desugar down to a function type. 8528 FnType = QualType(FnType->getAs<FunctionType>(), 0); 8529 // Reconstruct the pointer/reference as appropriate. 8530 if (isPointer) FnType = S.Context.getPointerType(FnType); 8531 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 8532 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 8533 8534 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 8535 << FnType; 8536 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 8537 } 8538 8539 void NoteBuiltinOperatorCandidate(Sema &S, 8540 const char *Opc, 8541 SourceLocation OpLoc, 8542 OverloadCandidate *Cand) { 8543 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 8544 std::string TypeStr("operator"); 8545 TypeStr += Opc; 8546 TypeStr += "("; 8547 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 8548 if (Cand->NumConversions == 1) { 8549 TypeStr += ")"; 8550 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 8551 } else { 8552 TypeStr += ", "; 8553 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 8554 TypeStr += ")"; 8555 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 8556 } 8557 } 8558 8559 void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 8560 OverloadCandidate *Cand) { 8561 unsigned NoOperands = Cand->NumConversions; 8562 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 8563 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 8564 if (ICS.isBad()) break; // all meaningless after first invalid 8565 if (!ICS.isAmbiguous()) continue; 8566 8567 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 8568 S.PDiag(diag::note_ambiguous_type_conversion)); 8569 } 8570 } 8571 8572 SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 8573 if (Cand->Function) 8574 return Cand->Function->getLocation(); 8575 if (Cand->IsSurrogate) 8576 return Cand->Surrogate->getLocation(); 8577 return SourceLocation(); 8578 } 8579 8580 static unsigned 8581 RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) { 8582 switch ((Sema::TemplateDeductionResult)DFI.Result) { 8583 case Sema::TDK_Success: 8584 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8585 8586 case Sema::TDK_Invalid: 8587 case Sema::TDK_Incomplete: 8588 return 1; 8589 8590 case Sema::TDK_Underqualified: 8591 case Sema::TDK_Inconsistent: 8592 return 2; 8593 8594 case Sema::TDK_SubstitutionFailure: 8595 case Sema::TDK_NonDeducedMismatch: 8596 return 3; 8597 8598 case Sema::TDK_InstantiationDepth: 8599 case Sema::TDK_FailedOverloadResolution: 8600 return 4; 8601 8602 case Sema::TDK_InvalidExplicitArguments: 8603 return 5; 8604 8605 case Sema::TDK_TooManyArguments: 8606 case Sema::TDK_TooFewArguments: 8607 return 6; 8608 } 8609 llvm_unreachable("Unhandled deduction result"); 8610 } 8611 8612 struct CompareOverloadCandidatesForDisplay { 8613 Sema &S; 8614 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 8615 8616 bool operator()(const OverloadCandidate *L, 8617 const OverloadCandidate *R) { 8618 // Fast-path this check. 8619 if (L == R) return false; 8620 8621 // Order first by viability. 8622 if (L->Viable) { 8623 if (!R->Viable) return true; 8624 8625 // TODO: introduce a tri-valued comparison for overload 8626 // candidates. Would be more worthwhile if we had a sort 8627 // that could exploit it. 8628 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 8629 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 8630 } else if (R->Viable) 8631 return false; 8632 8633 assert(L->Viable == R->Viable); 8634 8635 // Criteria by which we can sort non-viable candidates: 8636 if (!L->Viable) { 8637 // 1. Arity mismatches come after other candidates. 8638 if (L->FailureKind == ovl_fail_too_many_arguments || 8639 L->FailureKind == ovl_fail_too_few_arguments) 8640 return false; 8641 if (R->FailureKind == ovl_fail_too_many_arguments || 8642 R->FailureKind == ovl_fail_too_few_arguments) 8643 return true; 8644 8645 // 2. Bad conversions come first and are ordered by the number 8646 // of bad conversions and quality of good conversions. 8647 if (L->FailureKind == ovl_fail_bad_conversion) { 8648 if (R->FailureKind != ovl_fail_bad_conversion) 8649 return true; 8650 8651 // The conversion that can be fixed with a smaller number of changes, 8652 // comes first. 8653 unsigned numLFixes = L->Fix.NumConversionsFixed; 8654 unsigned numRFixes = R->Fix.NumConversionsFixed; 8655 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 8656 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 8657 if (numLFixes != numRFixes) { 8658 if (numLFixes < numRFixes) 8659 return true; 8660 else 8661 return false; 8662 } 8663 8664 // If there's any ordering between the defined conversions... 8665 // FIXME: this might not be transitive. 8666 assert(L->NumConversions == R->NumConversions); 8667 8668 int leftBetter = 0; 8669 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 8670 for (unsigned E = L->NumConversions; I != E; ++I) { 8671 switch (CompareImplicitConversionSequences(S, 8672 L->Conversions[I], 8673 R->Conversions[I])) { 8674 case ImplicitConversionSequence::Better: 8675 leftBetter++; 8676 break; 8677 8678 case ImplicitConversionSequence::Worse: 8679 leftBetter--; 8680 break; 8681 8682 case ImplicitConversionSequence::Indistinguishable: 8683 break; 8684 } 8685 } 8686 if (leftBetter > 0) return true; 8687 if (leftBetter < 0) return false; 8688 8689 } else if (R->FailureKind == ovl_fail_bad_conversion) 8690 return false; 8691 8692 if (L->FailureKind == ovl_fail_bad_deduction) { 8693 if (R->FailureKind != ovl_fail_bad_deduction) 8694 return true; 8695 8696 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 8697 return RankDeductionFailure(L->DeductionFailure) 8698 < RankDeductionFailure(R->DeductionFailure); 8699 } else if (R->FailureKind == ovl_fail_bad_deduction) 8700 return false; 8701 8702 // TODO: others? 8703 } 8704 8705 // Sort everything else by location. 8706 SourceLocation LLoc = GetLocationForCandidate(L); 8707 SourceLocation RLoc = GetLocationForCandidate(R); 8708 8709 // Put candidates without locations (e.g. builtins) at the end. 8710 if (LLoc.isInvalid()) return false; 8711 if (RLoc.isInvalid()) return true; 8712 8713 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 8714 } 8715 }; 8716 8717 /// CompleteNonViableCandidate - Normally, overload resolution only 8718 /// computes up to the first. Produces the FixIt set if possible. 8719 void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 8720 llvm::ArrayRef<Expr *> Args) { 8721 assert(!Cand->Viable); 8722 8723 // Don't do anything on failures other than bad conversion. 8724 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 8725 8726 // We only want the FixIts if all the arguments can be corrected. 8727 bool Unfixable = false; 8728 // Use a implicit copy initialization to check conversion fixes. 8729 Cand->Fix.setConversionChecker(TryCopyInitialization); 8730 8731 // Skip forward to the first bad conversion. 8732 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 8733 unsigned ConvCount = Cand->NumConversions; 8734 while (true) { 8735 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 8736 ConvIdx++; 8737 if (Cand->Conversions[ConvIdx - 1].isBad()) { 8738 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 8739 break; 8740 } 8741 } 8742 8743 if (ConvIdx == ConvCount) 8744 return; 8745 8746 assert(!Cand->Conversions[ConvIdx].isInitialized() && 8747 "remaining conversion is initialized?"); 8748 8749 // FIXME: this should probably be preserved from the overload 8750 // operation somehow. 8751 bool SuppressUserConversions = false; 8752 8753 const FunctionProtoType* Proto; 8754 unsigned ArgIdx = ConvIdx; 8755 8756 if (Cand->IsSurrogate) { 8757 QualType ConvType 8758 = Cand->Surrogate->getConversionType().getNonReferenceType(); 8759 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 8760 ConvType = ConvPtrType->getPointeeType(); 8761 Proto = ConvType->getAs<FunctionProtoType>(); 8762 ArgIdx--; 8763 } else if (Cand->Function) { 8764 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 8765 if (isa<CXXMethodDecl>(Cand->Function) && 8766 !isa<CXXConstructorDecl>(Cand->Function)) 8767 ArgIdx--; 8768 } else { 8769 // Builtin binary operator with a bad first conversion. 8770 assert(ConvCount <= 3); 8771 for (; ConvIdx != ConvCount; ++ConvIdx) 8772 Cand->Conversions[ConvIdx] 8773 = TryCopyInitialization(S, Args[ConvIdx], 8774 Cand->BuiltinTypes.ParamTypes[ConvIdx], 8775 SuppressUserConversions, 8776 /*InOverloadResolution*/ true, 8777 /*AllowObjCWritebackConversion=*/ 8778 S.getLangOpts().ObjCAutoRefCount); 8779 return; 8780 } 8781 8782 // Fill in the rest of the conversions. 8783 unsigned NumArgsInProto = Proto->getNumArgs(); 8784 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 8785 if (ArgIdx < NumArgsInProto) { 8786 Cand->Conversions[ConvIdx] 8787 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx), 8788 SuppressUserConversions, 8789 /*InOverloadResolution=*/true, 8790 /*AllowObjCWritebackConversion=*/ 8791 S.getLangOpts().ObjCAutoRefCount); 8792 // Store the FixIt in the candidate if it exists. 8793 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 8794 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 8795 } 8796 else 8797 Cand->Conversions[ConvIdx].setEllipsis(); 8798 } 8799 } 8800 8801 } // end anonymous namespace 8802 8803 /// PrintOverloadCandidates - When overload resolution fails, prints 8804 /// diagnostic messages containing the candidates in the candidate 8805 /// set. 8806 void OverloadCandidateSet::NoteCandidates(Sema &S, 8807 OverloadCandidateDisplayKind OCD, 8808 llvm::ArrayRef<Expr *> Args, 8809 const char *Opc, 8810 SourceLocation OpLoc) { 8811 // Sort the candidates by viability and position. Sorting directly would 8812 // be prohibitive, so we make a set of pointers and sort those. 8813 SmallVector<OverloadCandidate*, 32> Cands; 8814 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 8815 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 8816 if (Cand->Viable) 8817 Cands.push_back(Cand); 8818 else if (OCD == OCD_AllCandidates) { 8819 CompleteNonViableCandidate(S, Cand, Args); 8820 if (Cand->Function || Cand->IsSurrogate) 8821 Cands.push_back(Cand); 8822 // Otherwise, this a non-viable builtin candidate. We do not, in general, 8823 // want to list every possible builtin candidate. 8824 } 8825 } 8826 8827 std::sort(Cands.begin(), Cands.end(), 8828 CompareOverloadCandidatesForDisplay(S)); 8829 8830 bool ReportedAmbiguousConversions = false; 8831 8832 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 8833 const DiagnosticsEngine::OverloadsShown ShowOverloads = 8834 S.Diags.getShowOverloads(); 8835 unsigned CandsShown = 0; 8836 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 8837 OverloadCandidate *Cand = *I; 8838 8839 // Set an arbitrary limit on the number of candidate functions we'll spam 8840 // the user with. FIXME: This limit should depend on details of the 8841 // candidate list. 8842 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) { 8843 break; 8844 } 8845 ++CandsShown; 8846 8847 if (Cand->Function) 8848 NoteFunctionCandidate(S, Cand, Args.size()); 8849 else if (Cand->IsSurrogate) 8850 NoteSurrogateCandidate(S, Cand); 8851 else { 8852 assert(Cand->Viable && 8853 "Non-viable built-in candidates are not added to Cands."); 8854 // Generally we only see ambiguities including viable builtin 8855 // operators if overload resolution got screwed up by an 8856 // ambiguous user-defined conversion. 8857 // 8858 // FIXME: It's quite possible for different conversions to see 8859 // different ambiguities, though. 8860 if (!ReportedAmbiguousConversions) { 8861 NoteAmbiguousUserConversions(S, OpLoc, Cand); 8862 ReportedAmbiguousConversions = true; 8863 } 8864 8865 // If this is a viable builtin, print it. 8866 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 8867 } 8868 } 8869 8870 if (I != E) 8871 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 8872 } 8873 8874 // [PossiblyAFunctionType] --> [Return] 8875 // NonFunctionType --> NonFunctionType 8876 // R (A) --> R(A) 8877 // R (*)(A) --> R (A) 8878 // R (&)(A) --> R (A) 8879 // R (S::*)(A) --> R (A) 8880 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 8881 QualType Ret = PossiblyAFunctionType; 8882 if (const PointerType *ToTypePtr = 8883 PossiblyAFunctionType->getAs<PointerType>()) 8884 Ret = ToTypePtr->getPointeeType(); 8885 else if (const ReferenceType *ToTypeRef = 8886 PossiblyAFunctionType->getAs<ReferenceType>()) 8887 Ret = ToTypeRef->getPointeeType(); 8888 else if (const MemberPointerType *MemTypePtr = 8889 PossiblyAFunctionType->getAs<MemberPointerType>()) 8890 Ret = MemTypePtr->getPointeeType(); 8891 Ret = 8892 Context.getCanonicalType(Ret).getUnqualifiedType(); 8893 return Ret; 8894 } 8895 8896 // A helper class to help with address of function resolution 8897 // - allows us to avoid passing around all those ugly parameters 8898 class AddressOfFunctionResolver 8899 { 8900 Sema& S; 8901 Expr* SourceExpr; 8902 const QualType& TargetType; 8903 QualType TargetFunctionType; // Extracted function type from target type 8904 8905 bool Complain; 8906 //DeclAccessPair& ResultFunctionAccessPair; 8907 ASTContext& Context; 8908 8909 bool TargetTypeIsNonStaticMemberFunction; 8910 bool FoundNonTemplateFunction; 8911 8912 OverloadExpr::FindResult OvlExprInfo; 8913 OverloadExpr *OvlExpr; 8914 TemplateArgumentListInfo OvlExplicitTemplateArgs; 8915 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 8916 8917 public: 8918 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr, 8919 const QualType& TargetType, bool Complain) 8920 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 8921 Complain(Complain), Context(S.getASTContext()), 8922 TargetTypeIsNonStaticMemberFunction( 8923 !!TargetType->getAs<MemberPointerType>()), 8924 FoundNonTemplateFunction(false), 8925 OvlExprInfo(OverloadExpr::find(SourceExpr)), 8926 OvlExpr(OvlExprInfo.Expression) 8927 { 8928 ExtractUnqualifiedFunctionTypeFromTargetType(); 8929 8930 if (!TargetFunctionType->isFunctionType()) { 8931 if (OvlExpr->hasExplicitTemplateArgs()) { 8932 DeclAccessPair dap; 8933 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization( 8934 OvlExpr, false, &dap) ) { 8935 8936 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 8937 if (!Method->isStatic()) { 8938 // If the target type is a non-function type and the function 8939 // found is a non-static member function, pretend as if that was 8940 // the target, it's the only possible type to end up with. 8941 TargetTypeIsNonStaticMemberFunction = true; 8942 8943 // And skip adding the function if its not in the proper form. 8944 // We'll diagnose this due to an empty set of functions. 8945 if (!OvlExprInfo.HasFormOfMemberPointer) 8946 return; 8947 } 8948 } 8949 8950 Matches.push_back(std::make_pair(dap,Fn)); 8951 } 8952 } 8953 return; 8954 } 8955 8956 if (OvlExpr->hasExplicitTemplateArgs()) 8957 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 8958 8959 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 8960 // C++ [over.over]p4: 8961 // If more than one function is selected, [...] 8962 if (Matches.size() > 1) { 8963 if (FoundNonTemplateFunction) 8964 EliminateAllTemplateMatches(); 8965 else 8966 EliminateAllExceptMostSpecializedTemplate(); 8967 } 8968 } 8969 } 8970 8971 private: 8972 bool isTargetTypeAFunction() const { 8973 return TargetFunctionType->isFunctionType(); 8974 } 8975 8976 // [ToType] [Return] 8977 8978 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 8979 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 8980 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 8981 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 8982 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 8983 } 8984 8985 // return true if any matching specializations were found 8986 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 8987 const DeclAccessPair& CurAccessFunPair) { 8988 if (CXXMethodDecl *Method 8989 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 8990 // Skip non-static function templates when converting to pointer, and 8991 // static when converting to member pointer. 8992 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 8993 return false; 8994 } 8995 else if (TargetTypeIsNonStaticMemberFunction) 8996 return false; 8997 8998 // C++ [over.over]p2: 8999 // If the name is a function template, template argument deduction is 9000 // done (14.8.2.2), and if the argument deduction succeeds, the 9001 // resulting template argument list is used to generate a single 9002 // function template specialization, which is added to the set of 9003 // overloaded functions considered. 9004 FunctionDecl *Specialization = 0; 9005 TemplateDeductionInfo Info(OvlExpr->getNameLoc()); 9006 if (Sema::TemplateDeductionResult Result 9007 = S.DeduceTemplateArguments(FunctionTemplate, 9008 &OvlExplicitTemplateArgs, 9009 TargetFunctionType, Specialization, 9010 Info)) { 9011 // FIXME: make a note of the failed deduction for diagnostics. 9012 (void)Result; 9013 return false; 9014 } 9015 9016 // Template argument deduction ensures that we have an exact match. 9017 // This function template specicalization works. 9018 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 9019 assert(TargetFunctionType 9020 == Context.getCanonicalType(Specialization->getType())); 9021 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 9022 return true; 9023 } 9024 9025 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9026 const DeclAccessPair& CurAccessFunPair) { 9027 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9028 // Skip non-static functions when converting to pointer, and static 9029 // when converting to member pointer. 9030 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9031 return false; 9032 } 9033 else if (TargetTypeIsNonStaticMemberFunction) 9034 return false; 9035 9036 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9037 if (S.getLangOpts().CUDA) 9038 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9039 if (S.CheckCUDATarget(Caller, FunDecl)) 9040 return false; 9041 9042 QualType ResultTy; 9043 if (Context.hasSameUnqualifiedType(TargetFunctionType, 9044 FunDecl->getType()) || 9045 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9046 ResultTy)) { 9047 Matches.push_back(std::make_pair(CurAccessFunPair, 9048 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9049 FoundNonTemplateFunction = true; 9050 return true; 9051 } 9052 } 9053 9054 return false; 9055 } 9056 9057 bool FindAllFunctionsThatMatchTargetTypeExactly() { 9058 bool Ret = false; 9059 9060 // If the overload expression doesn't have the form of a pointer to 9061 // member, don't try to convert it to a pointer-to-member type. 9062 if (IsInvalidFormOfPointerToMemberFunction()) 9063 return false; 9064 9065 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9066 E = OvlExpr->decls_end(); 9067 I != E; ++I) { 9068 // Look through any using declarations to find the underlying function. 9069 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 9070 9071 // C++ [over.over]p3: 9072 // Non-member functions and static member functions match 9073 // targets of type "pointer-to-function" or "reference-to-function." 9074 // Nonstatic member functions match targets of 9075 // type "pointer-to-member-function." 9076 // Note that according to DR 247, the containing class does not matter. 9077 if (FunctionTemplateDecl *FunctionTemplate 9078 = dyn_cast<FunctionTemplateDecl>(Fn)) { 9079 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 9080 Ret = true; 9081 } 9082 // If we have explicit template arguments supplied, skip non-templates. 9083 else if (!OvlExpr->hasExplicitTemplateArgs() && 9084 AddMatchingNonTemplateFunction(Fn, I.getPair())) 9085 Ret = true; 9086 } 9087 assert(Ret || Matches.empty()); 9088 return Ret; 9089 } 9090 9091 void EliminateAllExceptMostSpecializedTemplate() { 9092 // [...] and any given function template specialization F1 is 9093 // eliminated if the set contains a second function template 9094 // specialization whose function template is more specialized 9095 // than the function template of F1 according to the partial 9096 // ordering rules of 14.5.5.2. 9097 9098 // The algorithm specified above is quadratic. We instead use a 9099 // two-pass algorithm (similar to the one used to identify the 9100 // best viable function in an overload set) that identifies the 9101 // best function template (if it exists). 9102 9103 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 9104 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 9105 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 9106 9107 UnresolvedSetIterator Result = 9108 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(), 9109 TPOC_Other, 0, SourceExpr->getLocStart(), 9110 S.PDiag(), 9111 S.PDiag(diag::err_addr_ovl_ambiguous) 9112 << Matches[0].second->getDeclName(), 9113 S.PDiag(diag::note_ovl_candidate) 9114 << (unsigned) oc_function_template, 9115 Complain, TargetFunctionType); 9116 9117 if (Result != MatchesCopy.end()) { 9118 // Make it the first and only element 9119 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 9120 Matches[0].second = cast<FunctionDecl>(*Result); 9121 Matches.resize(1); 9122 } 9123 } 9124 9125 void EliminateAllTemplateMatches() { 9126 // [...] any function template specializations in the set are 9127 // eliminated if the set also contains a non-template function, [...] 9128 for (unsigned I = 0, N = Matches.size(); I != N; ) { 9129 if (Matches[I].second->getPrimaryTemplate() == 0) 9130 ++I; 9131 else { 9132 Matches[I] = Matches[--N]; 9133 Matches.set_size(N); 9134 } 9135 } 9136 } 9137 9138 public: 9139 void ComplainNoMatchesFound() const { 9140 assert(Matches.empty()); 9141 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 9142 << OvlExpr->getName() << TargetFunctionType 9143 << OvlExpr->getSourceRange(); 9144 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9145 } 9146 9147 bool IsInvalidFormOfPointerToMemberFunction() const { 9148 return TargetTypeIsNonStaticMemberFunction && 9149 !OvlExprInfo.HasFormOfMemberPointer; 9150 } 9151 9152 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 9153 // TODO: Should we condition this on whether any functions might 9154 // have matched, or is it more appropriate to do that in callers? 9155 // TODO: a fixit wouldn't hurt. 9156 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 9157 << TargetType << OvlExpr->getSourceRange(); 9158 } 9159 9160 void ComplainOfInvalidConversion() const { 9161 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 9162 << OvlExpr->getName() << TargetType; 9163 } 9164 9165 void ComplainMultipleMatchesFound() const { 9166 assert(Matches.size() > 1); 9167 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 9168 << OvlExpr->getName() 9169 << OvlExpr->getSourceRange(); 9170 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9171 } 9172 9173 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 9174 9175 int getNumMatches() const { return Matches.size(); } 9176 9177 FunctionDecl* getMatchingFunctionDecl() const { 9178 if (Matches.size() != 1) return 0; 9179 return Matches[0].second; 9180 } 9181 9182 const DeclAccessPair* getMatchingFunctionAccessPair() const { 9183 if (Matches.size() != 1) return 0; 9184 return &Matches[0].first; 9185 } 9186 }; 9187 9188 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 9189 /// an overloaded function (C++ [over.over]), where @p From is an 9190 /// expression with overloaded function type and @p ToType is the type 9191 /// we're trying to resolve to. For example: 9192 /// 9193 /// @code 9194 /// int f(double); 9195 /// int f(int); 9196 /// 9197 /// int (*pfd)(double) = f; // selects f(double) 9198 /// @endcode 9199 /// 9200 /// This routine returns the resulting FunctionDecl if it could be 9201 /// resolved, and NULL otherwise. When @p Complain is true, this 9202 /// routine will emit diagnostics if there is an error. 9203 FunctionDecl * 9204 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 9205 QualType TargetType, 9206 bool Complain, 9207 DeclAccessPair &FoundResult, 9208 bool *pHadMultipleCandidates) { 9209 assert(AddressOfExpr->getType() == Context.OverloadTy); 9210 9211 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 9212 Complain); 9213 int NumMatches = Resolver.getNumMatches(); 9214 FunctionDecl* Fn = 0; 9215 if (NumMatches == 0 && Complain) { 9216 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 9217 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 9218 else 9219 Resolver.ComplainNoMatchesFound(); 9220 } 9221 else if (NumMatches > 1 && Complain) 9222 Resolver.ComplainMultipleMatchesFound(); 9223 else if (NumMatches == 1) { 9224 Fn = Resolver.getMatchingFunctionDecl(); 9225 assert(Fn); 9226 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 9227 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn); 9228 if (Complain) 9229 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 9230 } 9231 9232 if (pHadMultipleCandidates) 9233 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 9234 return Fn; 9235 } 9236 9237 /// \brief Given an expression that refers to an overloaded function, try to 9238 /// resolve that overloaded function expression down to a single function. 9239 /// 9240 /// This routine can only resolve template-ids that refer to a single function 9241 /// template, where that template-id refers to a single template whose template 9242 /// arguments are either provided by the template-id or have defaults, 9243 /// as described in C++0x [temp.arg.explicit]p3. 9244 FunctionDecl * 9245 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 9246 bool Complain, 9247 DeclAccessPair *FoundResult) { 9248 // C++ [over.over]p1: 9249 // [...] [Note: any redundant set of parentheses surrounding the 9250 // overloaded function name is ignored (5.1). ] 9251 // C++ [over.over]p1: 9252 // [...] The overloaded function name can be preceded by the & 9253 // operator. 9254 9255 // If we didn't actually find any template-ids, we're done. 9256 if (!ovl->hasExplicitTemplateArgs()) 9257 return 0; 9258 9259 TemplateArgumentListInfo ExplicitTemplateArgs; 9260 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 9261 9262 // Look through all of the overloaded functions, searching for one 9263 // whose type matches exactly. 9264 FunctionDecl *Matched = 0; 9265 for (UnresolvedSetIterator I = ovl->decls_begin(), 9266 E = ovl->decls_end(); I != E; ++I) { 9267 // C++0x [temp.arg.explicit]p3: 9268 // [...] In contexts where deduction is done and fails, or in contexts 9269 // where deduction is not done, if a template argument list is 9270 // specified and it, along with any default template arguments, 9271 // identifies a single function template specialization, then the 9272 // template-id is an lvalue for the function template specialization. 9273 FunctionTemplateDecl *FunctionTemplate 9274 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 9275 9276 // C++ [over.over]p2: 9277 // If the name is a function template, template argument deduction is 9278 // done (14.8.2.2), and if the argument deduction succeeds, the 9279 // resulting template argument list is used to generate a single 9280 // function template specialization, which is added to the set of 9281 // overloaded functions considered. 9282 FunctionDecl *Specialization = 0; 9283 TemplateDeductionInfo Info(ovl->getNameLoc()); 9284 if (TemplateDeductionResult Result 9285 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 9286 Specialization, Info)) { 9287 // FIXME: make a note of the failed deduction for diagnostics. 9288 (void)Result; 9289 continue; 9290 } 9291 9292 assert(Specialization && "no specialization and no error?"); 9293 9294 // Multiple matches; we can't resolve to a single declaration. 9295 if (Matched) { 9296 if (Complain) { 9297 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 9298 << ovl->getName(); 9299 NoteAllOverloadCandidates(ovl); 9300 } 9301 return 0; 9302 } 9303 9304 Matched = Specialization; 9305 if (FoundResult) *FoundResult = I.getPair(); 9306 } 9307 9308 return Matched; 9309 } 9310 9311 9312 9313 9314 // Resolve and fix an overloaded expression that can be resolved 9315 // because it identifies a single function template specialization. 9316 // 9317 // Last three arguments should only be supplied if Complain = true 9318 // 9319 // Return true if it was logically possible to so resolve the 9320 // expression, regardless of whether or not it succeeded. Always 9321 // returns true if 'complain' is set. 9322 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 9323 ExprResult &SrcExpr, bool doFunctionPointerConverion, 9324 bool complain, const SourceRange& OpRangeForComplaining, 9325 QualType DestTypeForComplaining, 9326 unsigned DiagIDForComplaining) { 9327 assert(SrcExpr.get()->getType() == Context.OverloadTy); 9328 9329 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 9330 9331 DeclAccessPair found; 9332 ExprResult SingleFunctionExpression; 9333 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 9334 ovl.Expression, /*complain*/ false, &found)) { 9335 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 9336 SrcExpr = ExprError(); 9337 return true; 9338 } 9339 9340 // It is only correct to resolve to an instance method if we're 9341 // resolving a form that's permitted to be a pointer to member. 9342 // Otherwise we'll end up making a bound member expression, which 9343 // is illegal in all the contexts we resolve like this. 9344 if (!ovl.HasFormOfMemberPointer && 9345 isa<CXXMethodDecl>(fn) && 9346 cast<CXXMethodDecl>(fn)->isInstance()) { 9347 if (!complain) return false; 9348 9349 Diag(ovl.Expression->getExprLoc(), 9350 diag::err_bound_member_function) 9351 << 0 << ovl.Expression->getSourceRange(); 9352 9353 // TODO: I believe we only end up here if there's a mix of 9354 // static and non-static candidates (otherwise the expression 9355 // would have 'bound member' type, not 'overload' type). 9356 // Ideally we would note which candidate was chosen and why 9357 // the static candidates were rejected. 9358 SrcExpr = ExprError(); 9359 return true; 9360 } 9361 9362 // Fix the expression to refer to 'fn'. 9363 SingleFunctionExpression = 9364 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn)); 9365 9366 // If desired, do function-to-pointer decay. 9367 if (doFunctionPointerConverion) { 9368 SingleFunctionExpression = 9369 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take()); 9370 if (SingleFunctionExpression.isInvalid()) { 9371 SrcExpr = ExprError(); 9372 return true; 9373 } 9374 } 9375 } 9376 9377 if (!SingleFunctionExpression.isUsable()) { 9378 if (complain) { 9379 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 9380 << ovl.Expression->getName() 9381 << DestTypeForComplaining 9382 << OpRangeForComplaining 9383 << ovl.Expression->getQualifierLoc().getSourceRange(); 9384 NoteAllOverloadCandidates(SrcExpr.get()); 9385 9386 SrcExpr = ExprError(); 9387 return true; 9388 } 9389 9390 return false; 9391 } 9392 9393 SrcExpr = SingleFunctionExpression; 9394 return true; 9395 } 9396 9397 /// \brief Add a single candidate to the overload set. 9398 static void AddOverloadedCallCandidate(Sema &S, 9399 DeclAccessPair FoundDecl, 9400 TemplateArgumentListInfo *ExplicitTemplateArgs, 9401 llvm::ArrayRef<Expr *> Args, 9402 OverloadCandidateSet &CandidateSet, 9403 bool PartialOverloading, 9404 bool KnownValid) { 9405 NamedDecl *Callee = FoundDecl.getDecl(); 9406 if (isa<UsingShadowDecl>(Callee)) 9407 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 9408 9409 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 9410 if (ExplicitTemplateArgs) { 9411 assert(!KnownValid && "Explicit template arguments?"); 9412 return; 9413 } 9414 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false, 9415 PartialOverloading); 9416 return; 9417 } 9418 9419 if (FunctionTemplateDecl *FuncTemplate 9420 = dyn_cast<FunctionTemplateDecl>(Callee)) { 9421 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 9422 ExplicitTemplateArgs, Args, CandidateSet); 9423 return; 9424 } 9425 9426 assert(!KnownValid && "unhandled case in overloaded call candidate"); 9427 } 9428 9429 /// \brief Add the overload candidates named by callee and/or found by argument 9430 /// dependent lookup to the given overload set. 9431 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 9432 llvm::ArrayRef<Expr *> Args, 9433 OverloadCandidateSet &CandidateSet, 9434 bool PartialOverloading) { 9435 9436 #ifndef NDEBUG 9437 // Verify that ArgumentDependentLookup is consistent with the rules 9438 // in C++0x [basic.lookup.argdep]p3: 9439 // 9440 // Let X be the lookup set produced by unqualified lookup (3.4.1) 9441 // and let Y be the lookup set produced by argument dependent 9442 // lookup (defined as follows). If X contains 9443 // 9444 // -- a declaration of a class member, or 9445 // 9446 // -- a block-scope function declaration that is not a 9447 // using-declaration, or 9448 // 9449 // -- a declaration that is neither a function or a function 9450 // template 9451 // 9452 // then Y is empty. 9453 9454 if (ULE->requiresADL()) { 9455 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9456 E = ULE->decls_end(); I != E; ++I) { 9457 assert(!(*I)->getDeclContext()->isRecord()); 9458 assert(isa<UsingShadowDecl>(*I) || 9459 !(*I)->getDeclContext()->isFunctionOrMethod()); 9460 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 9461 } 9462 } 9463 #endif 9464 9465 // It would be nice to avoid this copy. 9466 TemplateArgumentListInfo TABuffer; 9467 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9468 if (ULE->hasExplicitTemplateArgs()) { 9469 ULE->copyTemplateArgumentsInto(TABuffer); 9470 ExplicitTemplateArgs = &TABuffer; 9471 } 9472 9473 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 9474 E = ULE->decls_end(); I != E; ++I) 9475 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 9476 CandidateSet, PartialOverloading, 9477 /*KnownValid*/ true); 9478 9479 if (ULE->requiresADL()) 9480 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 9481 ULE->getExprLoc(), 9482 Args, ExplicitTemplateArgs, 9483 CandidateSet, PartialOverloading, 9484 ULE->isStdAssociatedNamespace()); 9485 } 9486 9487 /// Attempt to recover from an ill-formed use of a non-dependent name in a 9488 /// template, where the non-dependent name was declared after the template 9489 /// was defined. This is common in code written for a compilers which do not 9490 /// correctly implement two-stage name lookup. 9491 /// 9492 /// Returns true if a viable candidate was found and a diagnostic was issued. 9493 static bool 9494 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 9495 const CXXScopeSpec &SS, LookupResult &R, 9496 TemplateArgumentListInfo *ExplicitTemplateArgs, 9497 llvm::ArrayRef<Expr *> Args) { 9498 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 9499 return false; 9500 9501 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 9502 if (DC->isTransparentContext()) 9503 continue; 9504 9505 SemaRef.LookupQualifiedName(R, DC); 9506 9507 if (!R.empty()) { 9508 R.suppressDiagnostics(); 9509 9510 if (isa<CXXRecordDecl>(DC)) { 9511 // Don't diagnose names we find in classes; we get much better 9512 // diagnostics for these from DiagnoseEmptyLookup. 9513 R.clear(); 9514 return false; 9515 } 9516 9517 OverloadCandidateSet Candidates(FnLoc); 9518 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 9519 AddOverloadedCallCandidate(SemaRef, I.getPair(), 9520 ExplicitTemplateArgs, Args, 9521 Candidates, false, /*KnownValid*/ false); 9522 9523 OverloadCandidateSet::iterator Best; 9524 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 9525 // No viable functions. Don't bother the user with notes for functions 9526 // which don't work and shouldn't be found anyway. 9527 R.clear(); 9528 return false; 9529 } 9530 9531 // Find the namespaces where ADL would have looked, and suggest 9532 // declaring the function there instead. 9533 Sema::AssociatedNamespaceSet AssociatedNamespaces; 9534 Sema::AssociatedClassSet AssociatedClasses; 9535 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 9536 AssociatedNamespaces, 9537 AssociatedClasses); 9538 // Never suggest declaring a function within namespace 'std'. 9539 Sema::AssociatedNamespaceSet SuggestedNamespaces; 9540 if (DeclContext *Std = SemaRef.getStdNamespace()) { 9541 for (Sema::AssociatedNamespaceSet::iterator 9542 it = AssociatedNamespaces.begin(), 9543 end = AssociatedNamespaces.end(); it != end; ++it) { 9544 if (!Std->Encloses(*it)) 9545 SuggestedNamespaces.insert(*it); 9546 } 9547 } else { 9548 // Lacking the 'std::' namespace, use all of the associated namespaces. 9549 SuggestedNamespaces = AssociatedNamespaces; 9550 } 9551 9552 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 9553 << R.getLookupName(); 9554 if (SuggestedNamespaces.empty()) { 9555 SemaRef.Diag(Best->Function->getLocation(), 9556 diag::note_not_found_by_two_phase_lookup) 9557 << R.getLookupName() << 0; 9558 } else if (SuggestedNamespaces.size() == 1) { 9559 SemaRef.Diag(Best->Function->getLocation(), 9560 diag::note_not_found_by_two_phase_lookup) 9561 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 9562 } else { 9563 // FIXME: It would be useful to list the associated namespaces here, 9564 // but the diagnostics infrastructure doesn't provide a way to produce 9565 // a localized representation of a list of items. 9566 SemaRef.Diag(Best->Function->getLocation(), 9567 diag::note_not_found_by_two_phase_lookup) 9568 << R.getLookupName() << 2; 9569 } 9570 9571 // Try to recover by calling this function. 9572 return true; 9573 } 9574 9575 R.clear(); 9576 } 9577 9578 return false; 9579 } 9580 9581 /// Attempt to recover from ill-formed use of a non-dependent operator in a 9582 /// template, where the non-dependent operator was declared after the template 9583 /// was defined. 9584 /// 9585 /// Returns true if a viable candidate was found and a diagnostic was issued. 9586 static bool 9587 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 9588 SourceLocation OpLoc, 9589 llvm::ArrayRef<Expr *> Args) { 9590 DeclarationName OpName = 9591 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 9592 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 9593 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 9594 /*ExplicitTemplateArgs=*/0, Args); 9595 } 9596 9597 namespace { 9598 // Callback to limit the allowed keywords and to only accept typo corrections 9599 // that are keywords or whose decls refer to functions (or template functions) 9600 // that accept the given number of arguments. 9601 class RecoveryCallCCC : public CorrectionCandidateCallback { 9602 public: 9603 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs) 9604 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) { 9605 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus; 9606 WantRemainingKeywords = false; 9607 } 9608 9609 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9610 if (!candidate.getCorrectionDecl()) 9611 return candidate.isKeyword(); 9612 9613 for (TypoCorrection::const_decl_iterator DI = candidate.begin(), 9614 DIEnd = candidate.end(); DI != DIEnd; ++DI) { 9615 FunctionDecl *FD = 0; 9616 NamedDecl *ND = (*DI)->getUnderlyingDecl(); 9617 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) 9618 FD = FTD->getTemplatedDecl(); 9619 if (!HasExplicitTemplateArgs && !FD) { 9620 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) { 9621 // If the Decl is neither a function nor a template function, 9622 // determine if it is a pointer or reference to a function. If so, 9623 // check against the number of arguments expected for the pointee. 9624 QualType ValType = cast<ValueDecl>(ND)->getType(); 9625 if (ValType->isAnyPointerType() || ValType->isReferenceType()) 9626 ValType = ValType->getPointeeType(); 9627 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>()) 9628 if (FPT->getNumArgs() == NumArgs) 9629 return true; 9630 } 9631 } 9632 if (FD && FD->getNumParams() >= NumArgs && 9633 FD->getMinRequiredArguments() <= NumArgs) 9634 return true; 9635 } 9636 return false; 9637 } 9638 9639 private: 9640 unsigned NumArgs; 9641 bool HasExplicitTemplateArgs; 9642 }; 9643 9644 // Callback that effectively disabled typo correction 9645 class NoTypoCorrectionCCC : public CorrectionCandidateCallback { 9646 public: 9647 NoTypoCorrectionCCC() { 9648 WantTypeSpecifiers = false; 9649 WantExpressionKeywords = false; 9650 WantCXXNamedCasts = false; 9651 WantRemainingKeywords = false; 9652 } 9653 9654 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 9655 return false; 9656 } 9657 }; 9658 9659 class BuildRecoveryCallExprRAII { 9660 Sema &SemaRef; 9661 public: 9662 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 9663 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 9664 SemaRef.IsBuildingRecoveryCallExpr = true; 9665 } 9666 9667 ~BuildRecoveryCallExprRAII() { 9668 SemaRef.IsBuildingRecoveryCallExpr = false; 9669 } 9670 }; 9671 9672 } 9673 9674 /// Attempts to recover from a call where no functions were found. 9675 /// 9676 /// Returns true if new candidates were found. 9677 static ExprResult 9678 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9679 UnresolvedLookupExpr *ULE, 9680 SourceLocation LParenLoc, 9681 llvm::MutableArrayRef<Expr *> Args, 9682 SourceLocation RParenLoc, 9683 bool EmptyLookup, bool AllowTypoCorrection) { 9684 // Do not try to recover if it is already building a recovery call. 9685 // This stops infinite loops for template instantiations like 9686 // 9687 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 9688 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 9689 // 9690 if (SemaRef.IsBuildingRecoveryCallExpr) 9691 return ExprError(); 9692 BuildRecoveryCallExprRAII RCE(SemaRef); 9693 9694 CXXScopeSpec SS; 9695 SS.Adopt(ULE->getQualifierLoc()); 9696 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 9697 9698 TemplateArgumentListInfo TABuffer; 9699 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 9700 if (ULE->hasExplicitTemplateArgs()) { 9701 ULE->copyTemplateArgumentsInto(TABuffer); 9702 ExplicitTemplateArgs = &TABuffer; 9703 } 9704 9705 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 9706 Sema::LookupOrdinaryName); 9707 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0); 9708 NoTypoCorrectionCCC RejectAll; 9709 CorrectionCandidateCallback *CCC = AllowTypoCorrection ? 9710 (CorrectionCandidateCallback*)&Validator : 9711 (CorrectionCandidateCallback*)&RejectAll; 9712 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 9713 ExplicitTemplateArgs, Args) && 9714 (!EmptyLookup || 9715 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC, 9716 ExplicitTemplateArgs, Args))) 9717 return ExprError(); 9718 9719 assert(!R.empty() && "lookup results empty despite recovery"); 9720 9721 // Build an implicit member call if appropriate. Just drop the 9722 // casts and such from the call, we don't really care. 9723 ExprResult NewFn = ExprError(); 9724 if ((*R.begin())->isCXXClassMember()) 9725 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 9726 R, ExplicitTemplateArgs); 9727 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 9728 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 9729 ExplicitTemplateArgs); 9730 else 9731 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 9732 9733 if (NewFn.isInvalid()) 9734 return ExprError(); 9735 9736 // This shouldn't cause an infinite loop because we're giving it 9737 // an expression with viable lookup results, which should never 9738 // end up here. 9739 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 9740 MultiExprArg(Args.data(), Args.size()), 9741 RParenLoc); 9742 } 9743 9744 /// \brief Constructs and populates an OverloadedCandidateSet from 9745 /// the given function. 9746 /// \returns true when an the ExprResult output parameter has been set. 9747 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 9748 UnresolvedLookupExpr *ULE, 9749 Expr **Args, unsigned NumArgs, 9750 SourceLocation RParenLoc, 9751 OverloadCandidateSet *CandidateSet, 9752 ExprResult *Result) { 9753 #ifndef NDEBUG 9754 if (ULE->requiresADL()) { 9755 // To do ADL, we must have found an unqualified name. 9756 assert(!ULE->getQualifier() && "qualified name with ADL"); 9757 9758 // We don't perform ADL for implicit declarations of builtins. 9759 // Verify that this was correctly set up. 9760 FunctionDecl *F; 9761 if (ULE->decls_begin() + 1 == ULE->decls_end() && 9762 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 9763 F->getBuiltinID() && F->isImplicit()) 9764 llvm_unreachable("performing ADL for builtin"); 9765 9766 // We don't perform ADL in C. 9767 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 9768 } else 9769 assert(!ULE->isStdAssociatedNamespace() && 9770 "std is associated namespace but not doing ADL"); 9771 #endif 9772 9773 UnbridgedCastsSet UnbridgedCasts; 9774 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) { 9775 *Result = ExprError(); 9776 return true; 9777 } 9778 9779 // Add the functions denoted by the callee to the set of candidate 9780 // functions, including those from argument-dependent lookup. 9781 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs), 9782 *CandidateSet); 9783 9784 // If we found nothing, try to recover. 9785 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 9786 // out if it fails. 9787 if (CandidateSet->empty()) { 9788 // In Microsoft mode, if we are inside a template class member function then 9789 // create a type dependent CallExpr. The goal is to postpone name lookup 9790 // to instantiation time to be able to search into type dependent base 9791 // classes. 9792 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() && 9793 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 9794 CallExpr *CE = new (Context) CallExpr(Context, Fn, 9795 llvm::makeArrayRef(Args, NumArgs), 9796 Context.DependentTy, VK_RValue, 9797 RParenLoc); 9798 CE->setTypeDependent(true); 9799 *Result = Owned(CE); 9800 return true; 9801 } 9802 return false; 9803 } 9804 9805 UnbridgedCasts.restore(); 9806 return false; 9807 } 9808 9809 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 9810 /// the completed call expression. If overload resolution fails, emits 9811 /// diagnostics and returns ExprError() 9812 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 9813 UnresolvedLookupExpr *ULE, 9814 SourceLocation LParenLoc, 9815 Expr **Args, unsigned NumArgs, 9816 SourceLocation RParenLoc, 9817 Expr *ExecConfig, 9818 OverloadCandidateSet *CandidateSet, 9819 OverloadCandidateSet::iterator *Best, 9820 OverloadingResult OverloadResult, 9821 bool AllowTypoCorrection) { 9822 if (CandidateSet->empty()) 9823 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 9824 llvm::MutableArrayRef<Expr *>(Args, NumArgs), 9825 RParenLoc, /*EmptyLookup=*/true, 9826 AllowTypoCorrection); 9827 9828 switch (OverloadResult) { 9829 case OR_Success: { 9830 FunctionDecl *FDecl = (*Best)->Function; 9831 SemaRef.MarkFunctionReferenced(Fn->getExprLoc(), FDecl); 9832 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 9833 SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()); 9834 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 9835 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, 9836 RParenLoc, ExecConfig); 9837 } 9838 9839 case OR_No_Viable_Function: { 9840 // Try to recover by looking for viable functions which the user might 9841 // have meant to call. 9842 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 9843 llvm::MutableArrayRef<Expr *>(Args, NumArgs), 9844 RParenLoc, 9845 /*EmptyLookup=*/false, 9846 AllowTypoCorrection); 9847 if (!Recovery.isInvalid()) 9848 return Recovery; 9849 9850 SemaRef.Diag(Fn->getLocStart(), 9851 diag::err_ovl_no_viable_function_in_call) 9852 << ULE->getName() << Fn->getSourceRange(); 9853 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, 9854 llvm::makeArrayRef(Args, NumArgs)); 9855 break; 9856 } 9857 9858 case OR_Ambiguous: 9859 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 9860 << ULE->getName() << Fn->getSourceRange(); 9861 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, 9862 llvm::makeArrayRef(Args, NumArgs)); 9863 break; 9864 9865 case OR_Deleted: { 9866 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 9867 << (*Best)->Function->isDeleted() 9868 << ULE->getName() 9869 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 9870 << Fn->getSourceRange(); 9871 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, 9872 llvm::makeArrayRef(Args, NumArgs)); 9873 9874 // We emitted an error for the unvailable/deleted function call but keep 9875 // the call in the AST. 9876 FunctionDecl *FDecl = (*Best)->Function; 9877 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 9878 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, 9879 RParenLoc, ExecConfig); 9880 } 9881 } 9882 9883 // Overload resolution failed. 9884 return ExprError(); 9885 } 9886 9887 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 9888 /// (which eventually refers to the declaration Func) and the call 9889 /// arguments Args/NumArgs, attempt to resolve the function call down 9890 /// to a specific function. If overload resolution succeeds, returns 9891 /// the call expression produced by overload resolution. 9892 /// Otherwise, emits diagnostics and returns ExprError. 9893 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 9894 UnresolvedLookupExpr *ULE, 9895 SourceLocation LParenLoc, 9896 Expr **Args, unsigned NumArgs, 9897 SourceLocation RParenLoc, 9898 Expr *ExecConfig, 9899 bool AllowTypoCorrection) { 9900 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 9901 ExprResult result; 9902 9903 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc, 9904 &CandidateSet, &result)) 9905 return result; 9906 9907 OverloadCandidateSet::iterator Best; 9908 OverloadingResult OverloadResult = 9909 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 9910 9911 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs, 9912 RParenLoc, ExecConfig, &CandidateSet, 9913 &Best, OverloadResult, 9914 AllowTypoCorrection); 9915 } 9916 9917 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 9918 return Functions.size() > 1 || 9919 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 9920 } 9921 9922 /// \brief Create a unary operation that may resolve to an overloaded 9923 /// operator. 9924 /// 9925 /// \param OpLoc The location of the operator itself (e.g., '*'). 9926 /// 9927 /// \param OpcIn The UnaryOperator::Opcode that describes this 9928 /// operator. 9929 /// 9930 /// \param Fns The set of non-member functions that will be 9931 /// considered by overload resolution. The caller needs to build this 9932 /// set based on the context using, e.g., 9933 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 9934 /// set should not contain any member functions; those will be added 9935 /// by CreateOverloadedUnaryOp(). 9936 /// 9937 /// \param Input The input argument. 9938 ExprResult 9939 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 9940 const UnresolvedSetImpl &Fns, 9941 Expr *Input) { 9942 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 9943 9944 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 9945 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 9946 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 9947 // TODO: provide better source location info. 9948 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 9949 9950 if (checkPlaceholderForOverload(*this, Input)) 9951 return ExprError(); 9952 9953 Expr *Args[2] = { Input, 0 }; 9954 unsigned NumArgs = 1; 9955 9956 // For post-increment and post-decrement, add the implicit '0' as 9957 // the second argument, so that we know this is a post-increment or 9958 // post-decrement. 9959 if (Opc == UO_PostInc || Opc == UO_PostDec) { 9960 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 9961 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 9962 SourceLocation()); 9963 NumArgs = 2; 9964 } 9965 9966 if (Input->isTypeDependent()) { 9967 if (Fns.empty()) 9968 return Owned(new (Context) UnaryOperator(Input, 9969 Opc, 9970 Context.DependentTy, 9971 VK_RValue, OK_Ordinary, 9972 OpLoc)); 9973 9974 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 9975 UnresolvedLookupExpr *Fn 9976 = UnresolvedLookupExpr::Create(Context, NamingClass, 9977 NestedNameSpecifierLoc(), OpNameInfo, 9978 /*ADL*/ true, IsOverloaded(Fns), 9979 Fns.begin(), Fns.end()); 9980 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, 9981 llvm::makeArrayRef(Args, NumArgs), 9982 Context.DependentTy, 9983 VK_RValue, 9984 OpLoc, false)); 9985 } 9986 9987 // Build an empty overload set. 9988 OverloadCandidateSet CandidateSet(OpLoc); 9989 9990 // Add the candidates from the given function set. 9991 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet, 9992 false); 9993 9994 // Add operator candidates that are member functions. 9995 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 9996 9997 // Add candidates from ADL. 9998 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 9999 OpLoc, llvm::makeArrayRef(Args, NumArgs), 10000 /*ExplicitTemplateArgs*/ 0, 10001 CandidateSet); 10002 10003 // Add builtin operator candidates. 10004 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet); 10005 10006 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10007 10008 // Perform overload resolution. 10009 OverloadCandidateSet::iterator Best; 10010 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10011 case OR_Success: { 10012 // We found a built-in operator or an overloaded operator. 10013 FunctionDecl *FnDecl = Best->Function; 10014 10015 if (FnDecl) { 10016 // We matched an overloaded operator. Build a call to that 10017 // operator. 10018 10019 MarkFunctionReferenced(OpLoc, FnDecl); 10020 10021 // Convert the arguments. 10022 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10023 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 10024 10025 ExprResult InputRes = 10026 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 10027 Best->FoundDecl, Method); 10028 if (InputRes.isInvalid()) 10029 return ExprError(); 10030 Input = InputRes.take(); 10031 } else { 10032 // Convert the arguments. 10033 ExprResult InputInit 10034 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10035 Context, 10036 FnDecl->getParamDecl(0)), 10037 SourceLocation(), 10038 Input); 10039 if (InputInit.isInvalid()) 10040 return ExprError(); 10041 Input = InputInit.take(); 10042 } 10043 10044 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 10045 10046 // Determine the result type. 10047 QualType ResultTy = FnDecl->getResultType(); 10048 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10049 ResultTy = ResultTy.getNonLValueExprType(Context); 10050 10051 // Build the actual expression node. 10052 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10053 HadMultipleCandidates, OpLoc); 10054 if (FnExpr.isInvalid()) 10055 return ExprError(); 10056 10057 Args[0] = Input; 10058 CallExpr *TheCall = 10059 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10060 llvm::makeArrayRef(Args, NumArgs), 10061 ResultTy, VK, OpLoc, false); 10062 10063 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10064 FnDecl)) 10065 return ExprError(); 10066 10067 return MaybeBindToTemporary(TheCall); 10068 } else { 10069 // We matched a built-in operator. Convert the arguments, then 10070 // break out so that we will build the appropriate built-in 10071 // operator node. 10072 ExprResult InputRes = 10073 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 10074 Best->Conversions[0], AA_Passing); 10075 if (InputRes.isInvalid()) 10076 return ExprError(); 10077 Input = InputRes.take(); 10078 break; 10079 } 10080 } 10081 10082 case OR_No_Viable_Function: 10083 // This is an erroneous use of an operator which can be overloaded by 10084 // a non-member function. Check for non-member operators which were 10085 // defined too late to be candidates. 10086 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, 10087 llvm::makeArrayRef(Args, NumArgs))) 10088 // FIXME: Recover by calling the found function. 10089 return ExprError(); 10090 10091 // No viable function; fall through to handling this as a 10092 // built-in operator, which will produce an error message for us. 10093 break; 10094 10095 case OR_Ambiguous: 10096 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 10097 << UnaryOperator::getOpcodeStr(Opc) 10098 << Input->getType() 10099 << Input->getSourceRange(); 10100 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 10101 llvm::makeArrayRef(Args, NumArgs), 10102 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10103 return ExprError(); 10104 10105 case OR_Deleted: 10106 Diag(OpLoc, diag::err_ovl_deleted_oper) 10107 << Best->Function->isDeleted() 10108 << UnaryOperator::getOpcodeStr(Opc) 10109 << getDeletedOrUnavailableSuffix(Best->Function) 10110 << Input->getSourceRange(); 10111 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10112 llvm::makeArrayRef(Args, NumArgs), 10113 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10114 return ExprError(); 10115 } 10116 10117 // Either we found no viable overloaded operator or we matched a 10118 // built-in operator. In either case, fall through to trying to 10119 // build a built-in operation. 10120 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10121 } 10122 10123 /// \brief Create a binary operation that may resolve to an overloaded 10124 /// operator. 10125 /// 10126 /// \param OpLoc The location of the operator itself (e.g., '+'). 10127 /// 10128 /// \param OpcIn The BinaryOperator::Opcode that describes this 10129 /// operator. 10130 /// 10131 /// \param Fns The set of non-member functions that will be 10132 /// considered by overload resolution. The caller needs to build this 10133 /// set based on the context using, e.g., 10134 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10135 /// set should not contain any member functions; those will be added 10136 /// by CreateOverloadedBinOp(). 10137 /// 10138 /// \param LHS Left-hand argument. 10139 /// \param RHS Right-hand argument. 10140 ExprResult 10141 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 10142 unsigned OpcIn, 10143 const UnresolvedSetImpl &Fns, 10144 Expr *LHS, Expr *RHS) { 10145 Expr *Args[2] = { LHS, RHS }; 10146 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 10147 10148 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 10149 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 10150 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10151 10152 // If either side is type-dependent, create an appropriate dependent 10153 // expression. 10154 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10155 if (Fns.empty()) { 10156 // If there are no functions to store, just build a dependent 10157 // BinaryOperator or CompoundAssignment. 10158 if (Opc <= BO_Assign || Opc > BO_OrAssign) 10159 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 10160 Context.DependentTy, 10161 VK_RValue, OK_Ordinary, 10162 OpLoc, 10163 FPFeatures.fp_contract)); 10164 10165 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 10166 Context.DependentTy, 10167 VK_LValue, 10168 OK_Ordinary, 10169 Context.DependentTy, 10170 Context.DependentTy, 10171 OpLoc, 10172 FPFeatures.fp_contract)); 10173 } 10174 10175 // FIXME: save results of ADL from here? 10176 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10177 // TODO: provide better source location info in DNLoc component. 10178 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10179 UnresolvedLookupExpr *Fn 10180 = UnresolvedLookupExpr::Create(Context, NamingClass, 10181 NestedNameSpecifierLoc(), OpNameInfo, 10182 /*ADL*/ true, IsOverloaded(Fns), 10183 Fns.begin(), Fns.end()); 10184 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args, 10185 Context.DependentTy, VK_RValue, 10186 OpLoc, FPFeatures.fp_contract)); 10187 } 10188 10189 // Always do placeholder-like conversions on the RHS. 10190 if (checkPlaceholderForOverload(*this, Args[1])) 10191 return ExprError(); 10192 10193 // Do placeholder-like conversion on the LHS; note that we should 10194 // not get here with a PseudoObject LHS. 10195 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 10196 if (checkPlaceholderForOverload(*this, Args[0])) 10197 return ExprError(); 10198 10199 // If this is the assignment operator, we only perform overload resolution 10200 // if the left-hand side is a class or enumeration type. This is actually 10201 // a hack. The standard requires that we do overload resolution between the 10202 // various built-in candidates, but as DR507 points out, this can lead to 10203 // problems. So we do it this way, which pretty much follows what GCC does. 10204 // Note that we go the traditional code path for compound assignment forms. 10205 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 10206 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10207 10208 // If this is the .* operator, which is not overloadable, just 10209 // create a built-in binary operator. 10210 if (Opc == BO_PtrMemD) 10211 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10212 10213 // Build an empty overload set. 10214 OverloadCandidateSet CandidateSet(OpLoc); 10215 10216 // Add the candidates from the given function set. 10217 AddFunctionCandidates(Fns, Args, CandidateSet, false); 10218 10219 // Add operator candidates that are member functions. 10220 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 10221 10222 // Add candidates from ADL. 10223 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10224 OpLoc, Args, 10225 /*ExplicitTemplateArgs*/ 0, 10226 CandidateSet); 10227 10228 // Add builtin operator candidates. 10229 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet); 10230 10231 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10232 10233 // Perform overload resolution. 10234 OverloadCandidateSet::iterator Best; 10235 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10236 case OR_Success: { 10237 // We found a built-in operator or an overloaded operator. 10238 FunctionDecl *FnDecl = Best->Function; 10239 10240 if (FnDecl) { 10241 // We matched an overloaded operator. Build a call to that 10242 // operator. 10243 10244 MarkFunctionReferenced(OpLoc, FnDecl); 10245 10246 // Convert the arguments. 10247 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10248 // Best->Access is only meaningful for class members. 10249 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 10250 10251 ExprResult Arg1 = 10252 PerformCopyInitialization( 10253 InitializedEntity::InitializeParameter(Context, 10254 FnDecl->getParamDecl(0)), 10255 SourceLocation(), Owned(Args[1])); 10256 if (Arg1.isInvalid()) 10257 return ExprError(); 10258 10259 ExprResult Arg0 = 10260 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10261 Best->FoundDecl, Method); 10262 if (Arg0.isInvalid()) 10263 return ExprError(); 10264 Args[0] = Arg0.takeAs<Expr>(); 10265 Args[1] = RHS = Arg1.takeAs<Expr>(); 10266 } else { 10267 // Convert the arguments. 10268 ExprResult Arg0 = PerformCopyInitialization( 10269 InitializedEntity::InitializeParameter(Context, 10270 FnDecl->getParamDecl(0)), 10271 SourceLocation(), Owned(Args[0])); 10272 if (Arg0.isInvalid()) 10273 return ExprError(); 10274 10275 ExprResult Arg1 = 10276 PerformCopyInitialization( 10277 InitializedEntity::InitializeParameter(Context, 10278 FnDecl->getParamDecl(1)), 10279 SourceLocation(), Owned(Args[1])); 10280 if (Arg1.isInvalid()) 10281 return ExprError(); 10282 Args[0] = LHS = Arg0.takeAs<Expr>(); 10283 Args[1] = RHS = Arg1.takeAs<Expr>(); 10284 } 10285 10286 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 10287 10288 // Determine the result type. 10289 QualType ResultTy = FnDecl->getResultType(); 10290 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10291 ResultTy = ResultTy.getNonLValueExprType(Context); 10292 10293 // Build the actual expression node. 10294 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10295 HadMultipleCandidates, OpLoc); 10296 if (FnExpr.isInvalid()) 10297 return ExprError(); 10298 10299 CXXOperatorCallExpr *TheCall = 10300 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10301 Args, ResultTy, VK, OpLoc, 10302 FPFeatures.fp_contract); 10303 10304 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall, 10305 FnDecl)) 10306 return ExprError(); 10307 10308 return MaybeBindToTemporary(TheCall); 10309 } else { 10310 // We matched a built-in operator. Convert the arguments, then 10311 // break out so that we will build the appropriate built-in 10312 // operator node. 10313 ExprResult ArgsRes0 = 10314 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10315 Best->Conversions[0], AA_Passing); 10316 if (ArgsRes0.isInvalid()) 10317 return ExprError(); 10318 Args[0] = ArgsRes0.take(); 10319 10320 ExprResult ArgsRes1 = 10321 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10322 Best->Conversions[1], AA_Passing); 10323 if (ArgsRes1.isInvalid()) 10324 return ExprError(); 10325 Args[1] = ArgsRes1.take(); 10326 break; 10327 } 10328 } 10329 10330 case OR_No_Viable_Function: { 10331 // C++ [over.match.oper]p9: 10332 // If the operator is the operator , [...] and there are no 10333 // viable functions, then the operator is assumed to be the 10334 // built-in operator and interpreted according to clause 5. 10335 if (Opc == BO_Comma) 10336 break; 10337 10338 // For class as left operand for assignment or compound assigment 10339 // operator do not fall through to handling in built-in, but report that 10340 // no overloaded assignment operator found 10341 ExprResult Result = ExprError(); 10342 if (Args[0]->getType()->isRecordType() && 10343 Opc >= BO_Assign && Opc <= BO_OrAssign) { 10344 Diag(OpLoc, diag::err_ovl_no_viable_oper) 10345 << BinaryOperator::getOpcodeStr(Opc) 10346 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10347 } else { 10348 // This is an erroneous use of an operator which can be overloaded by 10349 // a non-member function. Check for non-member operators which were 10350 // defined too late to be candidates. 10351 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 10352 // FIXME: Recover by calling the found function. 10353 return ExprError(); 10354 10355 // No viable function; try to create a built-in operation, which will 10356 // produce an error. Then, show the non-viable candidates. 10357 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10358 } 10359 assert(Result.isInvalid() && 10360 "C++ binary operator overloading is missing candidates!"); 10361 if (Result.isInvalid()) 10362 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10363 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10364 return Result; 10365 } 10366 10367 case OR_Ambiguous: 10368 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 10369 << BinaryOperator::getOpcodeStr(Opc) 10370 << Args[0]->getType() << Args[1]->getType() 10371 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10372 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10373 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10374 return ExprError(); 10375 10376 case OR_Deleted: 10377 if (isImplicitlyDeleted(Best->Function)) { 10378 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 10379 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 10380 << getSpecialMember(Method) 10381 << BinaryOperator::getOpcodeStr(Opc) 10382 << getDeletedOrUnavailableSuffix(Best->Function); 10383 10384 if (getSpecialMember(Method) != CXXInvalid) { 10385 // The user probably meant to call this special member. Just 10386 // explain why it's deleted. 10387 NoteDeletedFunction(Method); 10388 return ExprError(); 10389 } 10390 } else { 10391 Diag(OpLoc, diag::err_ovl_deleted_oper) 10392 << Best->Function->isDeleted() 10393 << BinaryOperator::getOpcodeStr(Opc) 10394 << getDeletedOrUnavailableSuffix(Best->Function) 10395 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10396 } 10397 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10398 BinaryOperator::getOpcodeStr(Opc), OpLoc); 10399 return ExprError(); 10400 } 10401 10402 // We matched a built-in operator; build it. 10403 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10404 } 10405 10406 ExprResult 10407 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 10408 SourceLocation RLoc, 10409 Expr *Base, Expr *Idx) { 10410 Expr *Args[2] = { Base, Idx }; 10411 DeclarationName OpName = 10412 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 10413 10414 // If either side is type-dependent, create an appropriate dependent 10415 // expression. 10416 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10417 10418 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10419 // CHECKME: no 'operator' keyword? 10420 DeclarationNameInfo OpNameInfo(OpName, LLoc); 10421 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10422 UnresolvedLookupExpr *Fn 10423 = UnresolvedLookupExpr::Create(Context, NamingClass, 10424 NestedNameSpecifierLoc(), OpNameInfo, 10425 /*ADL*/ true, /*Overloaded*/ false, 10426 UnresolvedSetIterator(), 10427 UnresolvedSetIterator()); 10428 // Can't add any actual overloads yet 10429 10430 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 10431 Args, 10432 Context.DependentTy, 10433 VK_RValue, 10434 RLoc, false)); 10435 } 10436 10437 // Handle placeholders on both operands. 10438 if (checkPlaceholderForOverload(*this, Args[0])) 10439 return ExprError(); 10440 if (checkPlaceholderForOverload(*this, Args[1])) 10441 return ExprError(); 10442 10443 // Build an empty overload set. 10444 OverloadCandidateSet CandidateSet(LLoc); 10445 10446 // Subscript can only be overloaded as a member function. 10447 10448 // Add operator candidates that are member functions. 10449 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 10450 10451 // Add builtin operator candidates. 10452 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet); 10453 10454 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10455 10456 // Perform overload resolution. 10457 OverloadCandidateSet::iterator Best; 10458 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 10459 case OR_Success: { 10460 // We found a built-in operator or an overloaded operator. 10461 FunctionDecl *FnDecl = Best->Function; 10462 10463 if (FnDecl) { 10464 // We matched an overloaded operator. Build a call to that 10465 // operator. 10466 10467 MarkFunctionReferenced(LLoc, FnDecl); 10468 10469 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 10470 DiagnoseUseOfDecl(Best->FoundDecl, LLoc); 10471 10472 // Convert the arguments. 10473 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 10474 ExprResult Arg0 = 10475 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10476 Best->FoundDecl, Method); 10477 if (Arg0.isInvalid()) 10478 return ExprError(); 10479 Args[0] = Arg0.take(); 10480 10481 // Convert the arguments. 10482 ExprResult InputInit 10483 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10484 Context, 10485 FnDecl->getParamDecl(0)), 10486 SourceLocation(), 10487 Owned(Args[1])); 10488 if (InputInit.isInvalid()) 10489 return ExprError(); 10490 10491 Args[1] = InputInit.takeAs<Expr>(); 10492 10493 // Determine the result type 10494 QualType ResultTy = FnDecl->getResultType(); 10495 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10496 ResultTy = ResultTy.getNonLValueExprType(Context); 10497 10498 // Build the actual expression node. 10499 DeclarationNameInfo OpLocInfo(OpName, LLoc); 10500 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 10501 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10502 HadMultipleCandidates, 10503 OpLocInfo.getLoc(), 10504 OpLocInfo.getInfo()); 10505 if (FnExpr.isInvalid()) 10506 return ExprError(); 10507 10508 CXXOperatorCallExpr *TheCall = 10509 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 10510 FnExpr.take(), Args, 10511 ResultTy, VK, RLoc, 10512 false); 10513 10514 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall, 10515 FnDecl)) 10516 return ExprError(); 10517 10518 return MaybeBindToTemporary(TheCall); 10519 } else { 10520 // We matched a built-in operator. Convert the arguments, then 10521 // break out so that we will build the appropriate built-in 10522 // operator node. 10523 ExprResult ArgsRes0 = 10524 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10525 Best->Conversions[0], AA_Passing); 10526 if (ArgsRes0.isInvalid()) 10527 return ExprError(); 10528 Args[0] = ArgsRes0.take(); 10529 10530 ExprResult ArgsRes1 = 10531 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10532 Best->Conversions[1], AA_Passing); 10533 if (ArgsRes1.isInvalid()) 10534 return ExprError(); 10535 Args[1] = ArgsRes1.take(); 10536 10537 break; 10538 } 10539 } 10540 10541 case OR_No_Viable_Function: { 10542 if (CandidateSet.empty()) 10543 Diag(LLoc, diag::err_ovl_no_oper) 10544 << Args[0]->getType() << /*subscript*/ 0 10545 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10546 else 10547 Diag(LLoc, diag::err_ovl_no_viable_subscript) 10548 << Args[0]->getType() 10549 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10550 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10551 "[]", LLoc); 10552 return ExprError(); 10553 } 10554 10555 case OR_Ambiguous: 10556 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 10557 << "[]" 10558 << Args[0]->getType() << Args[1]->getType() 10559 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10560 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 10561 "[]", LLoc); 10562 return ExprError(); 10563 10564 case OR_Deleted: 10565 Diag(LLoc, diag::err_ovl_deleted_oper) 10566 << Best->Function->isDeleted() << "[]" 10567 << getDeletedOrUnavailableSuffix(Best->Function) 10568 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 10569 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 10570 "[]", LLoc); 10571 return ExprError(); 10572 } 10573 10574 // We matched a built-in operator; build it. 10575 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 10576 } 10577 10578 /// BuildCallToMemberFunction - Build a call to a member 10579 /// function. MemExpr is the expression that refers to the member 10580 /// function (and includes the object parameter), Args/NumArgs are the 10581 /// arguments to the function call (not including the object 10582 /// parameter). The caller needs to validate that the member 10583 /// expression refers to a non-static member function or an overloaded 10584 /// member function. 10585 ExprResult 10586 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 10587 SourceLocation LParenLoc, Expr **Args, 10588 unsigned NumArgs, SourceLocation RParenLoc) { 10589 assert(MemExprE->getType() == Context.BoundMemberTy || 10590 MemExprE->getType() == Context.OverloadTy); 10591 10592 // Dig out the member expression. This holds both the object 10593 // argument and the member function we're referring to. 10594 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 10595 10596 // Determine whether this is a call to a pointer-to-member function. 10597 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 10598 assert(op->getType() == Context.BoundMemberTy); 10599 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 10600 10601 QualType fnType = 10602 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 10603 10604 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 10605 QualType resultType = proto->getCallResultType(Context); 10606 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType()); 10607 10608 // Check that the object type isn't more qualified than the 10609 // member function we're calling. 10610 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 10611 10612 QualType objectType = op->getLHS()->getType(); 10613 if (op->getOpcode() == BO_PtrMemI) 10614 objectType = objectType->castAs<PointerType>()->getPointeeType(); 10615 Qualifiers objectQuals = objectType.getQualifiers(); 10616 10617 Qualifiers difference = objectQuals - funcQuals; 10618 difference.removeObjCGCAttr(); 10619 difference.removeAddressSpace(); 10620 if (difference) { 10621 std::string qualsString = difference.getAsString(); 10622 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 10623 << fnType.getUnqualifiedType() 10624 << qualsString 10625 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 10626 } 10627 10628 CXXMemberCallExpr *call 10629 = new (Context) CXXMemberCallExpr(Context, MemExprE, 10630 llvm::makeArrayRef(Args, NumArgs), 10631 resultType, valueKind, RParenLoc); 10632 10633 if (CheckCallReturnType(proto->getResultType(), 10634 op->getRHS()->getLocStart(), 10635 call, 0)) 10636 return ExprError(); 10637 10638 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc)) 10639 return ExprError(); 10640 10641 return MaybeBindToTemporary(call); 10642 } 10643 10644 UnbridgedCastsSet UnbridgedCasts; 10645 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 10646 return ExprError(); 10647 10648 MemberExpr *MemExpr; 10649 CXXMethodDecl *Method = 0; 10650 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 10651 NestedNameSpecifier *Qualifier = 0; 10652 if (isa<MemberExpr>(NakedMemExpr)) { 10653 MemExpr = cast<MemberExpr>(NakedMemExpr); 10654 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 10655 FoundDecl = MemExpr->getFoundDecl(); 10656 Qualifier = MemExpr->getQualifier(); 10657 UnbridgedCasts.restore(); 10658 } else { 10659 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 10660 Qualifier = UnresExpr->getQualifier(); 10661 10662 QualType ObjectType = UnresExpr->getBaseType(); 10663 Expr::Classification ObjectClassification 10664 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 10665 : UnresExpr->getBase()->Classify(Context); 10666 10667 // Add overload candidates 10668 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 10669 10670 // FIXME: avoid copy. 10671 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 10672 if (UnresExpr->hasExplicitTemplateArgs()) { 10673 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 10674 TemplateArgs = &TemplateArgsBuffer; 10675 } 10676 10677 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 10678 E = UnresExpr->decls_end(); I != E; ++I) { 10679 10680 NamedDecl *Func = *I; 10681 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 10682 if (isa<UsingShadowDecl>(Func)) 10683 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 10684 10685 10686 // Microsoft supports direct constructor calls. 10687 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 10688 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 10689 llvm::makeArrayRef(Args, NumArgs), CandidateSet); 10690 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 10691 // If explicit template arguments were provided, we can't call a 10692 // non-template member function. 10693 if (TemplateArgs) 10694 continue; 10695 10696 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 10697 ObjectClassification, 10698 llvm::makeArrayRef(Args, NumArgs), CandidateSet, 10699 /*SuppressUserConversions=*/false); 10700 } else { 10701 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 10702 I.getPair(), ActingDC, TemplateArgs, 10703 ObjectType, ObjectClassification, 10704 llvm::makeArrayRef(Args, NumArgs), 10705 CandidateSet, 10706 /*SuppressUsedConversions=*/false); 10707 } 10708 } 10709 10710 DeclarationName DeclName = UnresExpr->getMemberName(); 10711 10712 UnbridgedCasts.restore(); 10713 10714 OverloadCandidateSet::iterator Best; 10715 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 10716 Best)) { 10717 case OR_Success: 10718 Method = cast<CXXMethodDecl>(Best->Function); 10719 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method); 10720 FoundDecl = Best->FoundDecl; 10721 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 10722 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()); 10723 break; 10724 10725 case OR_No_Viable_Function: 10726 Diag(UnresExpr->getMemberLoc(), 10727 diag::err_ovl_no_viable_member_function_in_call) 10728 << DeclName << MemExprE->getSourceRange(); 10729 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10730 llvm::makeArrayRef(Args, NumArgs)); 10731 // FIXME: Leaking incoming expressions! 10732 return ExprError(); 10733 10734 case OR_Ambiguous: 10735 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 10736 << DeclName << MemExprE->getSourceRange(); 10737 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10738 llvm::makeArrayRef(Args, NumArgs)); 10739 // FIXME: Leaking incoming expressions! 10740 return ExprError(); 10741 10742 case OR_Deleted: 10743 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 10744 << Best->Function->isDeleted() 10745 << DeclName 10746 << getDeletedOrUnavailableSuffix(Best->Function) 10747 << MemExprE->getSourceRange(); 10748 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10749 llvm::makeArrayRef(Args, NumArgs)); 10750 // FIXME: Leaking incoming expressions! 10751 return ExprError(); 10752 } 10753 10754 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 10755 10756 // If overload resolution picked a static member, build a 10757 // non-member call based on that function. 10758 if (Method->isStatic()) { 10759 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, 10760 Args, NumArgs, RParenLoc); 10761 } 10762 10763 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 10764 } 10765 10766 QualType ResultType = Method->getResultType(); 10767 ExprValueKind VK = Expr::getValueKindForType(ResultType); 10768 ResultType = ResultType.getNonLValueExprType(Context); 10769 10770 assert(Method && "Member call to something that isn't a method?"); 10771 CXXMemberCallExpr *TheCall = 10772 new (Context) CXXMemberCallExpr(Context, MemExprE, 10773 llvm::makeArrayRef(Args, NumArgs), 10774 ResultType, VK, RParenLoc); 10775 10776 // Check for a valid return type. 10777 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(), 10778 TheCall, Method)) 10779 return ExprError(); 10780 10781 // Convert the object argument (for a non-static member function call). 10782 // We only need to do this if there was actually an overload; otherwise 10783 // it was done at lookup. 10784 if (!Method->isStatic()) { 10785 ExprResult ObjectArg = 10786 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 10787 FoundDecl, Method); 10788 if (ObjectArg.isInvalid()) 10789 return ExprError(); 10790 MemExpr->setBase(ObjectArg.take()); 10791 } 10792 10793 // Convert the rest of the arguments 10794 const FunctionProtoType *Proto = 10795 Method->getType()->getAs<FunctionProtoType>(); 10796 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs, 10797 RParenLoc)) 10798 return ExprError(); 10799 10800 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs); 10801 10802 if (CheckFunctionCall(Method, TheCall, Proto)) 10803 return ExprError(); 10804 10805 if ((isa<CXXConstructorDecl>(CurContext) || 10806 isa<CXXDestructorDecl>(CurContext)) && 10807 TheCall->getMethodDecl()->isPure()) { 10808 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 10809 10810 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 10811 Diag(MemExpr->getLocStart(), 10812 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 10813 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 10814 << MD->getParent()->getDeclName(); 10815 10816 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 10817 } 10818 } 10819 return MaybeBindToTemporary(TheCall); 10820 } 10821 10822 /// BuildCallToObjectOfClassType - Build a call to an object of class 10823 /// type (C++ [over.call.object]), which can end up invoking an 10824 /// overloaded function call operator (@c operator()) or performing a 10825 /// user-defined conversion on the object argument. 10826 ExprResult 10827 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 10828 SourceLocation LParenLoc, 10829 Expr **Args, unsigned NumArgs, 10830 SourceLocation RParenLoc) { 10831 if (checkPlaceholderForOverload(*this, Obj)) 10832 return ExprError(); 10833 ExprResult Object = Owned(Obj); 10834 10835 UnbridgedCastsSet UnbridgedCasts; 10836 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) 10837 return ExprError(); 10838 10839 assert(Object.get()->getType()->isRecordType() && "Requires object type argument"); 10840 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 10841 10842 // C++ [over.call.object]p1: 10843 // If the primary-expression E in the function call syntax 10844 // evaluates to a class object of type "cv T", then the set of 10845 // candidate functions includes at least the function call 10846 // operators of T. The function call operators of T are obtained by 10847 // ordinary lookup of the name operator() in the context of 10848 // (E).operator(). 10849 OverloadCandidateSet CandidateSet(LParenLoc); 10850 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 10851 10852 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 10853 diag::err_incomplete_object_call, Object.get())) 10854 return true; 10855 10856 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 10857 LookupQualifiedName(R, Record->getDecl()); 10858 R.suppressDiagnostics(); 10859 10860 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 10861 Oper != OperEnd; ++Oper) { 10862 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 10863 Object.get()->Classify(Context), Args, NumArgs, CandidateSet, 10864 /*SuppressUserConversions=*/ false); 10865 } 10866 10867 // C++ [over.call.object]p2: 10868 // In addition, for each (non-explicit in C++0x) conversion function 10869 // declared in T of the form 10870 // 10871 // operator conversion-type-id () cv-qualifier; 10872 // 10873 // where cv-qualifier is the same cv-qualification as, or a 10874 // greater cv-qualification than, cv, and where conversion-type-id 10875 // denotes the type "pointer to function of (P1,...,Pn) returning 10876 // R", or the type "reference to pointer to function of 10877 // (P1,...,Pn) returning R", or the type "reference to function 10878 // of (P1,...,Pn) returning R", a surrogate call function [...] 10879 // is also considered as a candidate function. Similarly, 10880 // surrogate call functions are added to the set of candidate 10881 // functions for each conversion function declared in an 10882 // accessible base class provided the function is not hidden 10883 // within T by another intervening declaration. 10884 const UnresolvedSetImpl *Conversions 10885 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 10886 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 10887 E = Conversions->end(); I != E; ++I) { 10888 NamedDecl *D = *I; 10889 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 10890 if (isa<UsingShadowDecl>(D)) 10891 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 10892 10893 // Skip over templated conversion functions; they aren't 10894 // surrogates. 10895 if (isa<FunctionTemplateDecl>(D)) 10896 continue; 10897 10898 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 10899 if (!Conv->isExplicit()) { 10900 // Strip the reference type (if any) and then the pointer type (if 10901 // any) to get down to what might be a function type. 10902 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 10903 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10904 ConvType = ConvPtrType->getPointeeType(); 10905 10906 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 10907 { 10908 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 10909 Object.get(), llvm::makeArrayRef(Args, NumArgs), 10910 CandidateSet); 10911 } 10912 } 10913 } 10914 10915 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10916 10917 // Perform overload resolution. 10918 OverloadCandidateSet::iterator Best; 10919 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 10920 Best)) { 10921 case OR_Success: 10922 // Overload resolution succeeded; we'll build the appropriate call 10923 // below. 10924 break; 10925 10926 case OR_No_Viable_Function: 10927 if (CandidateSet.empty()) 10928 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 10929 << Object.get()->getType() << /*call*/ 1 10930 << Object.get()->getSourceRange(); 10931 else 10932 Diag(Object.get()->getLocStart(), 10933 diag::err_ovl_no_viable_object_call) 10934 << Object.get()->getType() << Object.get()->getSourceRange(); 10935 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10936 llvm::makeArrayRef(Args, NumArgs)); 10937 break; 10938 10939 case OR_Ambiguous: 10940 Diag(Object.get()->getLocStart(), 10941 diag::err_ovl_ambiguous_object_call) 10942 << Object.get()->getType() << Object.get()->getSourceRange(); 10943 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, 10944 llvm::makeArrayRef(Args, NumArgs)); 10945 break; 10946 10947 case OR_Deleted: 10948 Diag(Object.get()->getLocStart(), 10949 diag::err_ovl_deleted_object_call) 10950 << Best->Function->isDeleted() 10951 << Object.get()->getType() 10952 << getDeletedOrUnavailableSuffix(Best->Function) 10953 << Object.get()->getSourceRange(); 10954 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, 10955 llvm::makeArrayRef(Args, NumArgs)); 10956 break; 10957 } 10958 10959 if (Best == CandidateSet.end()) 10960 return true; 10961 10962 UnbridgedCasts.restore(); 10963 10964 if (Best->Function == 0) { 10965 // Since there is no function declaration, this is one of the 10966 // surrogate candidates. Dig out the conversion function. 10967 CXXConversionDecl *Conv 10968 = cast<CXXConversionDecl>( 10969 Best->Conversions[0].UserDefined.ConversionFunction); 10970 10971 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 10972 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 10973 10974 // We selected one of the surrogate functions that converts the 10975 // object parameter to a function pointer. Perform the conversion 10976 // on the object argument, then let ActOnCallExpr finish the job. 10977 10978 // Create an implicit member expr to refer to the conversion operator. 10979 // and then call it. 10980 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 10981 Conv, HadMultipleCandidates); 10982 if (Call.isInvalid()) 10983 return ExprError(); 10984 // Record usage of conversion in an implicit cast. 10985 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(), 10986 CK_UserDefinedConversion, 10987 Call.get(), 0, VK_RValue)); 10988 10989 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs), 10990 RParenLoc); 10991 } 10992 10993 MarkFunctionReferenced(LParenLoc, Best->Function); 10994 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 10995 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc); 10996 10997 // We found an overloaded operator(). Build a CXXOperatorCallExpr 10998 // that calls this method, using Object for the implicit object 10999 // parameter and passing along the remaining arguments. 11000 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11001 const FunctionProtoType *Proto = 11002 Method->getType()->getAs<FunctionProtoType>(); 11003 11004 unsigned NumArgsInProto = Proto->getNumArgs(); 11005 unsigned NumArgsToCheck = NumArgs; 11006 11007 // Build the full argument list for the method call (the 11008 // implicit object parameter is placed at the beginning of the 11009 // list). 11010 Expr **MethodArgs; 11011 if (NumArgs < NumArgsInProto) { 11012 NumArgsToCheck = NumArgsInProto; 11013 MethodArgs = new Expr*[NumArgsInProto + 1]; 11014 } else { 11015 MethodArgs = new Expr*[NumArgs + 1]; 11016 } 11017 MethodArgs[0] = Object.get(); 11018 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 11019 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 11020 11021 DeclarationNameInfo OpLocInfo( 11022 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 11023 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 11024 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, 11025 HadMultipleCandidates, 11026 OpLocInfo.getLoc(), 11027 OpLocInfo.getInfo()); 11028 if (NewFn.isInvalid()) 11029 return true; 11030 11031 // Once we've built TheCall, all of the expressions are properly 11032 // owned. 11033 QualType ResultTy = Method->getResultType(); 11034 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11035 ResultTy = ResultTy.getNonLValueExprType(Context); 11036 11037 CXXOperatorCallExpr *TheCall = 11038 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(), 11039 llvm::makeArrayRef(MethodArgs, NumArgs+1), 11040 ResultTy, VK, RParenLoc, false); 11041 delete [] MethodArgs; 11042 11043 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall, 11044 Method)) 11045 return true; 11046 11047 // We may have default arguments. If so, we need to allocate more 11048 // slots in the call for them. 11049 if (NumArgs < NumArgsInProto) 11050 TheCall->setNumArgs(Context, NumArgsInProto + 1); 11051 else if (NumArgs > NumArgsInProto) 11052 NumArgsToCheck = NumArgsInProto; 11053 11054 bool IsError = false; 11055 11056 // Initialize the implicit object parameter. 11057 ExprResult ObjRes = 11058 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0, 11059 Best->FoundDecl, Method); 11060 if (ObjRes.isInvalid()) 11061 IsError = true; 11062 else 11063 Object = ObjRes; 11064 TheCall->setArg(0, Object.take()); 11065 11066 // Check the argument types. 11067 for (unsigned i = 0; i != NumArgsToCheck; i++) { 11068 Expr *Arg; 11069 if (i < NumArgs) { 11070 Arg = Args[i]; 11071 11072 // Pass the argument. 11073 11074 ExprResult InputInit 11075 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11076 Context, 11077 Method->getParamDecl(i)), 11078 SourceLocation(), Arg); 11079 11080 IsError |= InputInit.isInvalid(); 11081 Arg = InputInit.takeAs<Expr>(); 11082 } else { 11083 ExprResult DefArg 11084 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 11085 if (DefArg.isInvalid()) { 11086 IsError = true; 11087 break; 11088 } 11089 11090 Arg = DefArg.takeAs<Expr>(); 11091 } 11092 11093 TheCall->setArg(i + 1, Arg); 11094 } 11095 11096 // If this is a variadic call, handle args passed through "...". 11097 if (Proto->isVariadic()) { 11098 // Promote the arguments (C99 6.5.2.2p7). 11099 for (unsigned i = NumArgsInProto; i < NumArgs; i++) { 11100 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); 11101 IsError |= Arg.isInvalid(); 11102 TheCall->setArg(i + 1, Arg.take()); 11103 } 11104 } 11105 11106 if (IsError) return true; 11107 11108 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs); 11109 11110 if (CheckFunctionCall(Method, TheCall, Proto)) 11111 return true; 11112 11113 return MaybeBindToTemporary(TheCall); 11114 } 11115 11116 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 11117 /// (if one exists), where @c Base is an expression of class type and 11118 /// @c Member is the name of the member we're trying to find. 11119 ExprResult 11120 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) { 11121 assert(Base->getType()->isRecordType() && 11122 "left-hand side must have class type"); 11123 11124 if (checkPlaceholderForOverload(*this, Base)) 11125 return ExprError(); 11126 11127 SourceLocation Loc = Base->getExprLoc(); 11128 11129 // C++ [over.ref]p1: 11130 // 11131 // [...] An expression x->m is interpreted as (x.operator->())->m 11132 // for a class object x of type T if T::operator->() exists and if 11133 // the operator is selected as the best match function by the 11134 // overload resolution mechanism (13.3). 11135 DeclarationName OpName = 11136 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 11137 OverloadCandidateSet CandidateSet(Loc); 11138 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 11139 11140 if (RequireCompleteType(Loc, Base->getType(), 11141 diag::err_typecheck_incomplete_tag, Base)) 11142 return ExprError(); 11143 11144 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 11145 LookupQualifiedName(R, BaseRecord->getDecl()); 11146 R.suppressDiagnostics(); 11147 11148 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11149 Oper != OperEnd; ++Oper) { 11150 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 11151 0, 0, CandidateSet, /*SuppressUserConversions=*/false); 11152 } 11153 11154 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11155 11156 // Perform overload resolution. 11157 OverloadCandidateSet::iterator Best; 11158 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11159 case OR_Success: 11160 // Overload resolution succeeded; we'll build the call below. 11161 break; 11162 11163 case OR_No_Viable_Function: 11164 if (CandidateSet.empty()) 11165 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 11166 << Base->getType() << Base->getSourceRange(); 11167 else 11168 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11169 << "operator->" << Base->getSourceRange(); 11170 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11171 return ExprError(); 11172 11173 case OR_Ambiguous: 11174 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11175 << "->" << Base->getType() << Base->getSourceRange(); 11176 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 11177 return ExprError(); 11178 11179 case OR_Deleted: 11180 Diag(OpLoc, diag::err_ovl_deleted_oper) 11181 << Best->Function->isDeleted() 11182 << "->" 11183 << getDeletedOrUnavailableSuffix(Best->Function) 11184 << Base->getSourceRange(); 11185 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11186 return ExprError(); 11187 } 11188 11189 MarkFunctionReferenced(OpLoc, Best->Function); 11190 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 11191 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc); 11192 11193 // Convert the object parameter. 11194 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11195 ExprResult BaseResult = 11196 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 11197 Best->FoundDecl, Method); 11198 if (BaseResult.isInvalid()) 11199 return ExprError(); 11200 Base = BaseResult.take(); 11201 11202 // Build the operator call. 11203 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, 11204 HadMultipleCandidates, OpLoc); 11205 if (FnExpr.isInvalid()) 11206 return ExprError(); 11207 11208 QualType ResultTy = Method->getResultType(); 11209 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11210 ResultTy = ResultTy.getNonLValueExprType(Context); 11211 CXXOperatorCallExpr *TheCall = 11212 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(), 11213 Base, ResultTy, VK, OpLoc, false); 11214 11215 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall, 11216 Method)) 11217 return ExprError(); 11218 11219 return MaybeBindToTemporary(TheCall); 11220 } 11221 11222 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 11223 /// a literal operator described by the provided lookup results. 11224 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 11225 DeclarationNameInfo &SuffixInfo, 11226 ArrayRef<Expr*> Args, 11227 SourceLocation LitEndLoc, 11228 TemplateArgumentListInfo *TemplateArgs) { 11229 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 11230 11231 OverloadCandidateSet CandidateSet(UDSuffixLoc); 11232 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true, 11233 TemplateArgs); 11234 11235 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11236 11237 // Perform overload resolution. This will usually be trivial, but might need 11238 // to perform substitutions for a literal operator template. 11239 OverloadCandidateSet::iterator Best; 11240 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 11241 case OR_Success: 11242 case OR_Deleted: 11243 break; 11244 11245 case OR_No_Viable_Function: 11246 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 11247 << R.getLookupName(); 11248 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11249 return ExprError(); 11250 11251 case OR_Ambiguous: 11252 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 11253 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11254 return ExprError(); 11255 } 11256 11257 FunctionDecl *FD = Best->Function; 11258 MarkFunctionReferenced(UDSuffixLoc, FD); 11259 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc); 11260 11261 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates, 11262 SuffixInfo.getLoc(), 11263 SuffixInfo.getInfo()); 11264 if (Fn.isInvalid()) 11265 return true; 11266 11267 // Check the argument types. This should almost always be a no-op, except 11268 // that array-to-pointer decay is applied to string literals. 11269 Expr *ConvArgs[2]; 11270 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { 11271 ExprResult InputInit = PerformCopyInitialization( 11272 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 11273 SourceLocation(), Args[ArgIdx]); 11274 if (InputInit.isInvalid()) 11275 return true; 11276 ConvArgs[ArgIdx] = InputInit.take(); 11277 } 11278 11279 QualType ResultTy = FD->getResultType(); 11280 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11281 ResultTy = ResultTy.getNonLValueExprType(Context); 11282 11283 UserDefinedLiteral *UDL = 11284 new (Context) UserDefinedLiteral(Context, Fn.take(), 11285 llvm::makeArrayRef(ConvArgs, Args.size()), 11286 ResultTy, VK, LitEndLoc, UDSuffixLoc); 11287 11288 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD)) 11289 return ExprError(); 11290 11291 if (CheckFunctionCall(FD, UDL, NULL)) 11292 return ExprError(); 11293 11294 return MaybeBindToTemporary(UDL); 11295 } 11296 11297 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 11298 /// given LookupResult is non-empty, it is assumed to describe a member which 11299 /// will be invoked. Otherwise, the function will be found via argument 11300 /// dependent lookup. 11301 /// CallExpr is set to a valid expression and FRS_Success returned on success, 11302 /// otherwise CallExpr is set to ExprError() and some non-success value 11303 /// is returned. 11304 Sema::ForRangeStatus 11305 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 11306 SourceLocation RangeLoc, VarDecl *Decl, 11307 BeginEndFunction BEF, 11308 const DeclarationNameInfo &NameInfo, 11309 LookupResult &MemberLookup, 11310 OverloadCandidateSet *CandidateSet, 11311 Expr *Range, ExprResult *CallExpr) { 11312 CandidateSet->clear(); 11313 if (!MemberLookup.empty()) { 11314 ExprResult MemberRef = 11315 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 11316 /*IsPtr=*/false, CXXScopeSpec(), 11317 /*TemplateKWLoc=*/SourceLocation(), 11318 /*FirstQualifierInScope=*/0, 11319 MemberLookup, 11320 /*TemplateArgs=*/0); 11321 if (MemberRef.isInvalid()) { 11322 *CallExpr = ExprError(); 11323 Diag(Range->getLocStart(), diag::note_in_for_range) 11324 << RangeLoc << BEF << Range->getType(); 11325 return FRS_DiagnosticIssued; 11326 } 11327 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0); 11328 if (CallExpr->isInvalid()) { 11329 *CallExpr = ExprError(); 11330 Diag(Range->getLocStart(), diag::note_in_for_range) 11331 << RangeLoc << BEF << Range->getType(); 11332 return FRS_DiagnosticIssued; 11333 } 11334 } else { 11335 UnresolvedSet<0> FoundNames; 11336 // C++11 [stmt.ranged]p1: For the purposes of this name lookup, namespace 11337 // std is an associated namespace. 11338 UnresolvedLookupExpr *Fn = 11339 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0, 11340 NestedNameSpecifierLoc(), NameInfo, 11341 /*NeedsADL=*/true, /*Overloaded=*/false, 11342 FoundNames.begin(), FoundNames.end(), 11343 /*LookInStdNamespace=*/true); 11344 11345 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc, 11346 CandidateSet, CallExpr); 11347 if (CandidateSet->empty() || CandidateSetError) { 11348 *CallExpr = ExprError(); 11349 return FRS_NoViableFunction; 11350 } 11351 OverloadCandidateSet::iterator Best; 11352 OverloadingResult OverloadResult = 11353 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 11354 11355 if (OverloadResult == OR_No_Viable_Function) { 11356 *CallExpr = ExprError(); 11357 return FRS_NoViableFunction; 11358 } 11359 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1, 11360 Loc, 0, CandidateSet, &Best, 11361 OverloadResult, 11362 /*AllowTypoCorrection=*/false); 11363 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 11364 *CallExpr = ExprError(); 11365 Diag(Range->getLocStart(), diag::note_in_for_range) 11366 << RangeLoc << BEF << Range->getType(); 11367 return FRS_DiagnosticIssued; 11368 } 11369 } 11370 return FRS_Success; 11371 } 11372 11373 11374 /// FixOverloadedFunctionReference - E is an expression that refers to 11375 /// a C++ overloaded function (possibly with some parentheses and 11376 /// perhaps a '&' around it). We have resolved the overloaded function 11377 /// to the function declaration Fn, so patch up the expression E to 11378 /// refer (possibly indirectly) to Fn. Returns the new expr. 11379 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 11380 FunctionDecl *Fn) { 11381 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 11382 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 11383 Found, Fn); 11384 if (SubExpr == PE->getSubExpr()) 11385 return PE; 11386 11387 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 11388 } 11389 11390 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11391 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 11392 Found, Fn); 11393 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 11394 SubExpr->getType()) && 11395 "Implicit cast type cannot be determined from overload"); 11396 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 11397 if (SubExpr == ICE->getSubExpr()) 11398 return ICE; 11399 11400 return ImplicitCastExpr::Create(Context, ICE->getType(), 11401 ICE->getCastKind(), 11402 SubExpr, 0, 11403 ICE->getValueKind()); 11404 } 11405 11406 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 11407 assert(UnOp->getOpcode() == UO_AddrOf && 11408 "Can only take the address of an overloaded function"); 11409 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11410 if (Method->isStatic()) { 11411 // Do nothing: static member functions aren't any different 11412 // from non-member functions. 11413 } else { 11414 // Fix the sub expression, which really has to be an 11415 // UnresolvedLookupExpr holding an overloaded member function 11416 // or template. 11417 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11418 Found, Fn); 11419 if (SubExpr == UnOp->getSubExpr()) 11420 return UnOp; 11421 11422 assert(isa<DeclRefExpr>(SubExpr) 11423 && "fixed to something other than a decl ref"); 11424 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 11425 && "fixed to a member ref with no nested name qualifier"); 11426 11427 // We have taken the address of a pointer to member 11428 // function. Perform the computation here so that we get the 11429 // appropriate pointer to member type. 11430 QualType ClassType 11431 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 11432 QualType MemPtrType 11433 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 11434 11435 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 11436 VK_RValue, OK_Ordinary, 11437 UnOp->getOperatorLoc()); 11438 } 11439 } 11440 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 11441 Found, Fn); 11442 if (SubExpr == UnOp->getSubExpr()) 11443 return UnOp; 11444 11445 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 11446 Context.getPointerType(SubExpr->getType()), 11447 VK_RValue, OK_Ordinary, 11448 UnOp->getOperatorLoc()); 11449 } 11450 11451 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 11452 // FIXME: avoid copy. 11453 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11454 if (ULE->hasExplicitTemplateArgs()) { 11455 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 11456 TemplateArgs = &TemplateArgsBuffer; 11457 } 11458 11459 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11460 ULE->getQualifierLoc(), 11461 ULE->getTemplateKeywordLoc(), 11462 Fn, 11463 /*enclosing*/ false, // FIXME? 11464 ULE->getNameLoc(), 11465 Fn->getType(), 11466 VK_LValue, 11467 Found.getDecl(), 11468 TemplateArgs); 11469 MarkDeclRefReferenced(DRE); 11470 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 11471 return DRE; 11472 } 11473 11474 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 11475 // FIXME: avoid copy. 11476 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11477 if (MemExpr->hasExplicitTemplateArgs()) { 11478 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11479 TemplateArgs = &TemplateArgsBuffer; 11480 } 11481 11482 Expr *Base; 11483 11484 // If we're filling in a static method where we used to have an 11485 // implicit member access, rewrite to a simple decl ref. 11486 if (MemExpr->isImplicitAccess()) { 11487 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11488 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 11489 MemExpr->getQualifierLoc(), 11490 MemExpr->getTemplateKeywordLoc(), 11491 Fn, 11492 /*enclosing*/ false, 11493 MemExpr->getMemberLoc(), 11494 Fn->getType(), 11495 VK_LValue, 11496 Found.getDecl(), 11497 TemplateArgs); 11498 MarkDeclRefReferenced(DRE); 11499 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 11500 return DRE; 11501 } else { 11502 SourceLocation Loc = MemExpr->getMemberLoc(); 11503 if (MemExpr->getQualifier()) 11504 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 11505 CheckCXXThisCapture(Loc); 11506 Base = new (Context) CXXThisExpr(Loc, 11507 MemExpr->getBaseType(), 11508 /*isImplicit=*/true); 11509 } 11510 } else 11511 Base = MemExpr->getBase(); 11512 11513 ExprValueKind valueKind; 11514 QualType type; 11515 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 11516 valueKind = VK_LValue; 11517 type = Fn->getType(); 11518 } else { 11519 valueKind = VK_RValue; 11520 type = Context.BoundMemberTy; 11521 } 11522 11523 MemberExpr *ME = MemberExpr::Create(Context, Base, 11524 MemExpr->isArrow(), 11525 MemExpr->getQualifierLoc(), 11526 MemExpr->getTemplateKeywordLoc(), 11527 Fn, 11528 Found, 11529 MemExpr->getMemberNameInfo(), 11530 TemplateArgs, 11531 type, valueKind, OK_Ordinary); 11532 ME->setHadMultipleCandidates(true); 11533 return ME; 11534 } 11535 11536 llvm_unreachable("Invalid reference to overloaded function"); 11537 } 11538 11539 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 11540 DeclAccessPair Found, 11541 FunctionDecl *Fn) { 11542 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 11543 } 11544 11545 } // end namespace clang 11546