1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file provides Sema routines for C++ overloading. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/Overload.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/CXXInheritance.h" 17 #include "clang/AST/DeclObjC.h" 18 #include "clang/AST/Expr.h" 19 #include "clang/AST/ExprCXX.h" 20 #include "clang/AST/ExprObjC.h" 21 #include "clang/AST/TypeOrdering.h" 22 #include "clang/Basic/Diagnostic.h" 23 #include "clang/Basic/PartialDiagnostic.h" 24 #include "clang/Basic/TargetInfo.h" 25 #include "clang/Lex/Preprocessor.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/SemaInternal.h" 29 #include "clang/Sema/Template.h" 30 #include "clang/Sema/TemplateDeduction.h" 31 #include "llvm/ADT/DenseSet.h" 32 #include "llvm/ADT/STLExtras.h" 33 #include "llvm/ADT/SmallPtrSet.h" 34 #include "llvm/ADT/SmallString.h" 35 #include <algorithm> 36 37 namespace clang { 38 using namespace sema; 39 40 /// A convenience routine for creating a decayed reference to a function. 41 static ExprResult 42 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 43 bool HadMultipleCandidates, 44 SourceLocation Loc = SourceLocation(), 45 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 46 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 47 return ExprError(); 48 // If FoundDecl is different from Fn (such as if one is a template 49 // and the other a specialization), make sure DiagnoseUseOfDecl is 50 // called on both. 51 // FIXME: This would be more comprehensively addressed by modifying 52 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 53 // being used. 54 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 55 return ExprError(); 56 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 57 VK_LValue, Loc, LocInfo); 58 if (HadMultipleCandidates) 59 DRE->setHadMultipleCandidates(true); 60 61 S.MarkDeclRefReferenced(DRE); 62 63 ExprResult E = S.Owned(DRE); 64 E = S.DefaultFunctionArrayConversion(E.take()); 65 if (E.isInvalid()) 66 return ExprError(); 67 return E; 68 } 69 70 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 71 bool InOverloadResolution, 72 StandardConversionSequence &SCS, 73 bool CStyle, 74 bool AllowObjCWritebackConversion); 75 76 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 77 QualType &ToType, 78 bool InOverloadResolution, 79 StandardConversionSequence &SCS, 80 bool CStyle); 81 static OverloadingResult 82 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 83 UserDefinedConversionSequence& User, 84 OverloadCandidateSet& Conversions, 85 bool AllowExplicit, 86 bool AllowObjCConversionOnExplicit); 87 88 89 static ImplicitConversionSequence::CompareKind 90 CompareStandardConversionSequences(Sema &S, 91 const StandardConversionSequence& SCS1, 92 const StandardConversionSequence& SCS2); 93 94 static ImplicitConversionSequence::CompareKind 95 CompareQualificationConversions(Sema &S, 96 const StandardConversionSequence& SCS1, 97 const StandardConversionSequence& SCS2); 98 99 static ImplicitConversionSequence::CompareKind 100 CompareDerivedToBaseConversions(Sema &S, 101 const StandardConversionSequence& SCS1, 102 const StandardConversionSequence& SCS2); 103 104 105 106 /// GetConversionCategory - Retrieve the implicit conversion 107 /// category corresponding to the given implicit conversion kind. 108 ImplicitConversionCategory 109 GetConversionCategory(ImplicitConversionKind Kind) { 110 static const ImplicitConversionCategory 111 Category[(int)ICK_Num_Conversion_Kinds] = { 112 ICC_Identity, 113 ICC_Lvalue_Transformation, 114 ICC_Lvalue_Transformation, 115 ICC_Lvalue_Transformation, 116 ICC_Identity, 117 ICC_Qualification_Adjustment, 118 ICC_Promotion, 119 ICC_Promotion, 120 ICC_Promotion, 121 ICC_Conversion, 122 ICC_Conversion, 123 ICC_Conversion, 124 ICC_Conversion, 125 ICC_Conversion, 126 ICC_Conversion, 127 ICC_Conversion, 128 ICC_Conversion, 129 ICC_Conversion, 130 ICC_Conversion, 131 ICC_Conversion, 132 ICC_Conversion, 133 ICC_Conversion 134 }; 135 return Category[(int)Kind]; 136 } 137 138 /// GetConversionRank - Retrieve the implicit conversion rank 139 /// corresponding to the given implicit conversion kind. 140 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 141 static const ImplicitConversionRank 142 Rank[(int)ICK_Num_Conversion_Kinds] = { 143 ICR_Exact_Match, 144 ICR_Exact_Match, 145 ICR_Exact_Match, 146 ICR_Exact_Match, 147 ICR_Exact_Match, 148 ICR_Exact_Match, 149 ICR_Promotion, 150 ICR_Promotion, 151 ICR_Promotion, 152 ICR_Conversion, 153 ICR_Conversion, 154 ICR_Conversion, 155 ICR_Conversion, 156 ICR_Conversion, 157 ICR_Conversion, 158 ICR_Conversion, 159 ICR_Conversion, 160 ICR_Conversion, 161 ICR_Conversion, 162 ICR_Conversion, 163 ICR_Complex_Real_Conversion, 164 ICR_Conversion, 165 ICR_Conversion, 166 ICR_Writeback_Conversion 167 }; 168 return Rank[(int)Kind]; 169 } 170 171 /// GetImplicitConversionName - Return the name of this kind of 172 /// implicit conversion. 173 const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 174 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 175 "No conversion", 176 "Lvalue-to-rvalue", 177 "Array-to-pointer", 178 "Function-to-pointer", 179 "Noreturn adjustment", 180 "Qualification", 181 "Integral promotion", 182 "Floating point promotion", 183 "Complex promotion", 184 "Integral conversion", 185 "Floating conversion", 186 "Complex conversion", 187 "Floating-integral conversion", 188 "Pointer conversion", 189 "Pointer-to-member conversion", 190 "Boolean conversion", 191 "Compatible-types conversion", 192 "Derived-to-base conversion", 193 "Vector conversion", 194 "Vector splat", 195 "Complex-real conversion", 196 "Block Pointer conversion", 197 "Transparent Union Conversion" 198 "Writeback conversion" 199 }; 200 return Name[Kind]; 201 } 202 203 /// StandardConversionSequence - Set the standard conversion 204 /// sequence to the identity conversion. 205 void StandardConversionSequence::setAsIdentityConversion() { 206 First = ICK_Identity; 207 Second = ICK_Identity; 208 Third = ICK_Identity; 209 DeprecatedStringLiteralToCharPtr = false; 210 QualificationIncludesObjCLifetime = false; 211 ReferenceBinding = false; 212 DirectBinding = false; 213 IsLvalueReference = true; 214 BindsToFunctionLvalue = false; 215 BindsToRvalue = false; 216 BindsImplicitObjectArgumentWithoutRefQualifier = false; 217 ObjCLifetimeConversionBinding = false; 218 CopyConstructor = 0; 219 } 220 221 /// getRank - Retrieve the rank of this standard conversion sequence 222 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 223 /// implicit conversions. 224 ImplicitConversionRank StandardConversionSequence::getRank() const { 225 ImplicitConversionRank Rank = ICR_Exact_Match; 226 if (GetConversionRank(First) > Rank) 227 Rank = GetConversionRank(First); 228 if (GetConversionRank(Second) > Rank) 229 Rank = GetConversionRank(Second); 230 if (GetConversionRank(Third) > Rank) 231 Rank = GetConversionRank(Third); 232 return Rank; 233 } 234 235 /// isPointerConversionToBool - Determines whether this conversion is 236 /// a conversion of a pointer or pointer-to-member to bool. This is 237 /// used as part of the ranking of standard conversion sequences 238 /// (C++ 13.3.3.2p4). 239 bool StandardConversionSequence::isPointerConversionToBool() const { 240 // Note that FromType has not necessarily been transformed by the 241 // array-to-pointer or function-to-pointer implicit conversions, so 242 // check for their presence as well as checking whether FromType is 243 // a pointer. 244 if (getToType(1)->isBooleanType() && 245 (getFromType()->isPointerType() || 246 getFromType()->isObjCObjectPointerType() || 247 getFromType()->isBlockPointerType() || 248 getFromType()->isNullPtrType() || 249 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 250 return true; 251 252 return false; 253 } 254 255 /// isPointerConversionToVoidPointer - Determines whether this 256 /// conversion is a conversion of a pointer to a void pointer. This is 257 /// used as part of the ranking of standard conversion sequences (C++ 258 /// 13.3.3.2p4). 259 bool 260 StandardConversionSequence:: 261 isPointerConversionToVoidPointer(ASTContext& Context) const { 262 QualType FromType = getFromType(); 263 QualType ToType = getToType(1); 264 265 // Note that FromType has not necessarily been transformed by the 266 // array-to-pointer implicit conversion, so check for its presence 267 // and redo the conversion to get a pointer. 268 if (First == ICK_Array_To_Pointer) 269 FromType = Context.getArrayDecayedType(FromType); 270 271 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 272 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 273 return ToPtrType->getPointeeType()->isVoidType(); 274 275 return false; 276 } 277 278 /// Skip any implicit casts which could be either part of a narrowing conversion 279 /// or after one in an implicit conversion. 280 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 281 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 282 switch (ICE->getCastKind()) { 283 case CK_NoOp: 284 case CK_IntegralCast: 285 case CK_IntegralToBoolean: 286 case CK_IntegralToFloating: 287 case CK_FloatingToIntegral: 288 case CK_FloatingToBoolean: 289 case CK_FloatingCast: 290 Converted = ICE->getSubExpr(); 291 continue; 292 293 default: 294 return Converted; 295 } 296 } 297 298 return Converted; 299 } 300 301 /// Check if this standard conversion sequence represents a narrowing 302 /// conversion, according to C++11 [dcl.init.list]p7. 303 /// 304 /// \param Ctx The AST context. 305 /// \param Converted The result of applying this standard conversion sequence. 306 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 307 /// value of the expression prior to the narrowing conversion. 308 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 309 /// type of the expression prior to the narrowing conversion. 310 NarrowingKind 311 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 312 const Expr *Converted, 313 APValue &ConstantValue, 314 QualType &ConstantType) const { 315 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 316 317 // C++11 [dcl.init.list]p7: 318 // A narrowing conversion is an implicit conversion ... 319 QualType FromType = getToType(0); 320 QualType ToType = getToType(1); 321 switch (Second) { 322 // -- from a floating-point type to an integer type, or 323 // 324 // -- from an integer type or unscoped enumeration type to a floating-point 325 // type, except where the source is a constant expression and the actual 326 // value after conversion will fit into the target type and will produce 327 // the original value when converted back to the original type, or 328 case ICK_Floating_Integral: 329 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 330 return NK_Type_Narrowing; 331 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 332 llvm::APSInt IntConstantValue; 333 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 334 if (Initializer && 335 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 336 // Convert the integer to the floating type. 337 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 338 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 339 llvm::APFloat::rmNearestTiesToEven); 340 // And back. 341 llvm::APSInt ConvertedValue = IntConstantValue; 342 bool ignored; 343 Result.convertToInteger(ConvertedValue, 344 llvm::APFloat::rmTowardZero, &ignored); 345 // If the resulting value is different, this was a narrowing conversion. 346 if (IntConstantValue != ConvertedValue) { 347 ConstantValue = APValue(IntConstantValue); 348 ConstantType = Initializer->getType(); 349 return NK_Constant_Narrowing; 350 } 351 } else { 352 // Variables are always narrowings. 353 return NK_Variable_Narrowing; 354 } 355 } 356 return NK_Not_Narrowing; 357 358 // -- from long double to double or float, or from double to float, except 359 // where the source is a constant expression and the actual value after 360 // conversion is within the range of values that can be represented (even 361 // if it cannot be represented exactly), or 362 case ICK_Floating_Conversion: 363 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 364 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 365 // FromType is larger than ToType. 366 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 367 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 368 // Constant! 369 assert(ConstantValue.isFloat()); 370 llvm::APFloat FloatVal = ConstantValue.getFloat(); 371 // Convert the source value into the target type. 372 bool ignored; 373 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 374 Ctx.getFloatTypeSemantics(ToType), 375 llvm::APFloat::rmNearestTiesToEven, &ignored); 376 // If there was no overflow, the source value is within the range of 377 // values that can be represented. 378 if (ConvertStatus & llvm::APFloat::opOverflow) { 379 ConstantType = Initializer->getType(); 380 return NK_Constant_Narrowing; 381 } 382 } else { 383 return NK_Variable_Narrowing; 384 } 385 } 386 return NK_Not_Narrowing; 387 388 // -- from an integer type or unscoped enumeration type to an integer type 389 // that cannot represent all the values of the original type, except where 390 // the source is a constant expression and the actual value after 391 // conversion will fit into the target type and will produce the original 392 // value when converted back to the original type. 393 case ICK_Boolean_Conversion: // Bools are integers too. 394 if (!FromType->isIntegralOrUnscopedEnumerationType()) { 395 // Boolean conversions can be from pointers and pointers to members 396 // [conv.bool], and those aren't considered narrowing conversions. 397 return NK_Not_Narrowing; 398 } // Otherwise, fall through to the integral case. 399 case ICK_Integral_Conversion: { 400 assert(FromType->isIntegralOrUnscopedEnumerationType()); 401 assert(ToType->isIntegralOrUnscopedEnumerationType()); 402 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 403 const unsigned FromWidth = Ctx.getIntWidth(FromType); 404 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 405 const unsigned ToWidth = Ctx.getIntWidth(ToType); 406 407 if (FromWidth > ToWidth || 408 (FromWidth == ToWidth && FromSigned != ToSigned) || 409 (FromSigned && !ToSigned)) { 410 // Not all values of FromType can be represented in ToType. 411 llvm::APSInt InitializerValue; 412 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 413 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 414 // Such conversions on variables are always narrowing. 415 return NK_Variable_Narrowing; 416 } 417 bool Narrowing = false; 418 if (FromWidth < ToWidth) { 419 // Negative -> unsigned is narrowing. Otherwise, more bits is never 420 // narrowing. 421 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 422 Narrowing = true; 423 } else { 424 // Add a bit to the InitializerValue so we don't have to worry about 425 // signed vs. unsigned comparisons. 426 InitializerValue = InitializerValue.extend( 427 InitializerValue.getBitWidth() + 1); 428 // Convert the initializer to and from the target width and signed-ness. 429 llvm::APSInt ConvertedValue = InitializerValue; 430 ConvertedValue = ConvertedValue.trunc(ToWidth); 431 ConvertedValue.setIsSigned(ToSigned); 432 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 433 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 434 // If the result is different, this was a narrowing conversion. 435 if (ConvertedValue != InitializerValue) 436 Narrowing = true; 437 } 438 if (Narrowing) { 439 ConstantType = Initializer->getType(); 440 ConstantValue = APValue(InitializerValue); 441 return NK_Constant_Narrowing; 442 } 443 } 444 return NK_Not_Narrowing; 445 } 446 447 default: 448 // Other kinds of conversions are not narrowings. 449 return NK_Not_Narrowing; 450 } 451 } 452 453 /// dump - Print this standard conversion sequence to standard 454 /// error. Useful for debugging overloading issues. 455 void StandardConversionSequence::dump() const { 456 raw_ostream &OS = llvm::errs(); 457 bool PrintedSomething = false; 458 if (First != ICK_Identity) { 459 OS << GetImplicitConversionName(First); 460 PrintedSomething = true; 461 } 462 463 if (Second != ICK_Identity) { 464 if (PrintedSomething) { 465 OS << " -> "; 466 } 467 OS << GetImplicitConversionName(Second); 468 469 if (CopyConstructor) { 470 OS << " (by copy constructor)"; 471 } else if (DirectBinding) { 472 OS << " (direct reference binding)"; 473 } else if (ReferenceBinding) { 474 OS << " (reference binding)"; 475 } 476 PrintedSomething = true; 477 } 478 479 if (Third != ICK_Identity) { 480 if (PrintedSomething) { 481 OS << " -> "; 482 } 483 OS << GetImplicitConversionName(Third); 484 PrintedSomething = true; 485 } 486 487 if (!PrintedSomething) { 488 OS << "No conversions required"; 489 } 490 } 491 492 /// dump - Print this user-defined conversion sequence to standard 493 /// error. Useful for debugging overloading issues. 494 void UserDefinedConversionSequence::dump() const { 495 raw_ostream &OS = llvm::errs(); 496 if (Before.First || Before.Second || Before.Third) { 497 Before.dump(); 498 OS << " -> "; 499 } 500 if (ConversionFunction) 501 OS << '\'' << *ConversionFunction << '\''; 502 else 503 OS << "aggregate initialization"; 504 if (After.First || After.Second || After.Third) { 505 OS << " -> "; 506 After.dump(); 507 } 508 } 509 510 /// dump - Print this implicit conversion sequence to standard 511 /// error. Useful for debugging overloading issues. 512 void ImplicitConversionSequence::dump() const { 513 raw_ostream &OS = llvm::errs(); 514 if (isStdInitializerListElement()) 515 OS << "Worst std::initializer_list element conversion: "; 516 switch (ConversionKind) { 517 case StandardConversion: 518 OS << "Standard conversion: "; 519 Standard.dump(); 520 break; 521 case UserDefinedConversion: 522 OS << "User-defined conversion: "; 523 UserDefined.dump(); 524 break; 525 case EllipsisConversion: 526 OS << "Ellipsis conversion"; 527 break; 528 case AmbiguousConversion: 529 OS << "Ambiguous conversion"; 530 break; 531 case BadConversion: 532 OS << "Bad conversion"; 533 break; 534 } 535 536 OS << "\n"; 537 } 538 539 void AmbiguousConversionSequence::construct() { 540 new (&conversions()) ConversionSet(); 541 } 542 543 void AmbiguousConversionSequence::destruct() { 544 conversions().~ConversionSet(); 545 } 546 547 void 548 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 549 FromTypePtr = O.FromTypePtr; 550 ToTypePtr = O.ToTypePtr; 551 new (&conversions()) ConversionSet(O.conversions()); 552 } 553 554 namespace { 555 // Structure used by DeductionFailureInfo to store 556 // template argument information. 557 struct DFIArguments { 558 TemplateArgument FirstArg; 559 TemplateArgument SecondArg; 560 }; 561 // Structure used by DeductionFailureInfo to store 562 // template parameter and template argument information. 563 struct DFIParamWithArguments : DFIArguments { 564 TemplateParameter Param; 565 }; 566 } 567 568 /// \brief Convert from Sema's representation of template deduction information 569 /// to the form used in overload-candidate information. 570 DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, 571 Sema::TemplateDeductionResult TDK, 572 TemplateDeductionInfo &Info) { 573 DeductionFailureInfo Result; 574 Result.Result = static_cast<unsigned>(TDK); 575 Result.HasDiagnostic = false; 576 Result.Data = 0; 577 switch (TDK) { 578 case Sema::TDK_Success: 579 case Sema::TDK_Invalid: 580 case Sema::TDK_InstantiationDepth: 581 case Sema::TDK_TooManyArguments: 582 case Sema::TDK_TooFewArguments: 583 break; 584 585 case Sema::TDK_Incomplete: 586 case Sema::TDK_InvalidExplicitArguments: 587 Result.Data = Info.Param.getOpaqueValue(); 588 break; 589 590 case Sema::TDK_NonDeducedMismatch: { 591 // FIXME: Should allocate from normal heap so that we can free this later. 592 DFIArguments *Saved = new (Context) DFIArguments; 593 Saved->FirstArg = Info.FirstArg; 594 Saved->SecondArg = Info.SecondArg; 595 Result.Data = Saved; 596 break; 597 } 598 599 case Sema::TDK_Inconsistent: 600 case Sema::TDK_Underqualified: { 601 // FIXME: Should allocate from normal heap so that we can free this later. 602 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 603 Saved->Param = Info.Param; 604 Saved->FirstArg = Info.FirstArg; 605 Saved->SecondArg = Info.SecondArg; 606 Result.Data = Saved; 607 break; 608 } 609 610 case Sema::TDK_SubstitutionFailure: 611 Result.Data = Info.take(); 612 if (Info.hasSFINAEDiagnostic()) { 613 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 614 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 615 Info.takeSFINAEDiagnostic(*Diag); 616 Result.HasDiagnostic = true; 617 } 618 break; 619 620 case Sema::TDK_FailedOverloadResolution: 621 Result.Data = Info.Expression; 622 break; 623 624 case Sema::TDK_MiscellaneousDeductionFailure: 625 break; 626 } 627 628 return Result; 629 } 630 631 void DeductionFailureInfo::Destroy() { 632 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 633 case Sema::TDK_Success: 634 case Sema::TDK_Invalid: 635 case Sema::TDK_InstantiationDepth: 636 case Sema::TDK_Incomplete: 637 case Sema::TDK_TooManyArguments: 638 case Sema::TDK_TooFewArguments: 639 case Sema::TDK_InvalidExplicitArguments: 640 case Sema::TDK_FailedOverloadResolution: 641 break; 642 643 case Sema::TDK_Inconsistent: 644 case Sema::TDK_Underqualified: 645 case Sema::TDK_NonDeducedMismatch: 646 // FIXME: Destroy the data? 647 Data = 0; 648 break; 649 650 case Sema::TDK_SubstitutionFailure: 651 // FIXME: Destroy the template argument list? 652 Data = 0; 653 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 654 Diag->~PartialDiagnosticAt(); 655 HasDiagnostic = false; 656 } 657 break; 658 659 // Unhandled 660 case Sema::TDK_MiscellaneousDeductionFailure: 661 break; 662 } 663 } 664 665 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 666 if (HasDiagnostic) 667 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 668 return 0; 669 } 670 671 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 672 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 673 case Sema::TDK_Success: 674 case Sema::TDK_Invalid: 675 case Sema::TDK_InstantiationDepth: 676 case Sema::TDK_TooManyArguments: 677 case Sema::TDK_TooFewArguments: 678 case Sema::TDK_SubstitutionFailure: 679 case Sema::TDK_NonDeducedMismatch: 680 case Sema::TDK_FailedOverloadResolution: 681 return TemplateParameter(); 682 683 case Sema::TDK_Incomplete: 684 case Sema::TDK_InvalidExplicitArguments: 685 return TemplateParameter::getFromOpaqueValue(Data); 686 687 case Sema::TDK_Inconsistent: 688 case Sema::TDK_Underqualified: 689 return static_cast<DFIParamWithArguments*>(Data)->Param; 690 691 // Unhandled 692 case Sema::TDK_MiscellaneousDeductionFailure: 693 break; 694 } 695 696 return TemplateParameter(); 697 } 698 699 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 700 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 701 case Sema::TDK_Success: 702 case Sema::TDK_Invalid: 703 case Sema::TDK_InstantiationDepth: 704 case Sema::TDK_TooManyArguments: 705 case Sema::TDK_TooFewArguments: 706 case Sema::TDK_Incomplete: 707 case Sema::TDK_InvalidExplicitArguments: 708 case Sema::TDK_Inconsistent: 709 case Sema::TDK_Underqualified: 710 case Sema::TDK_NonDeducedMismatch: 711 case Sema::TDK_FailedOverloadResolution: 712 return 0; 713 714 case Sema::TDK_SubstitutionFailure: 715 return static_cast<TemplateArgumentList*>(Data); 716 717 // Unhandled 718 case Sema::TDK_MiscellaneousDeductionFailure: 719 break; 720 } 721 722 return 0; 723 } 724 725 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 726 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 727 case Sema::TDK_Success: 728 case Sema::TDK_Invalid: 729 case Sema::TDK_InstantiationDepth: 730 case Sema::TDK_Incomplete: 731 case Sema::TDK_TooManyArguments: 732 case Sema::TDK_TooFewArguments: 733 case Sema::TDK_InvalidExplicitArguments: 734 case Sema::TDK_SubstitutionFailure: 735 case Sema::TDK_FailedOverloadResolution: 736 return 0; 737 738 case Sema::TDK_Inconsistent: 739 case Sema::TDK_Underqualified: 740 case Sema::TDK_NonDeducedMismatch: 741 return &static_cast<DFIArguments*>(Data)->FirstArg; 742 743 // Unhandled 744 case Sema::TDK_MiscellaneousDeductionFailure: 745 break; 746 } 747 748 return 0; 749 } 750 751 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 752 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 753 case Sema::TDK_Success: 754 case Sema::TDK_Invalid: 755 case Sema::TDK_InstantiationDepth: 756 case Sema::TDK_Incomplete: 757 case Sema::TDK_TooManyArguments: 758 case Sema::TDK_TooFewArguments: 759 case Sema::TDK_InvalidExplicitArguments: 760 case Sema::TDK_SubstitutionFailure: 761 case Sema::TDK_FailedOverloadResolution: 762 return 0; 763 764 case Sema::TDK_Inconsistent: 765 case Sema::TDK_Underqualified: 766 case Sema::TDK_NonDeducedMismatch: 767 return &static_cast<DFIArguments*>(Data)->SecondArg; 768 769 // Unhandled 770 case Sema::TDK_MiscellaneousDeductionFailure: 771 break; 772 } 773 774 return 0; 775 } 776 777 Expr *DeductionFailureInfo::getExpr() { 778 if (static_cast<Sema::TemplateDeductionResult>(Result) == 779 Sema::TDK_FailedOverloadResolution) 780 return static_cast<Expr*>(Data); 781 782 return 0; 783 } 784 785 void OverloadCandidateSet::destroyCandidates() { 786 for (iterator i = begin(), e = end(); i != e; ++i) { 787 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 788 i->Conversions[ii].~ImplicitConversionSequence(); 789 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 790 i->DeductionFailure.Destroy(); 791 } 792 } 793 794 void OverloadCandidateSet::clear() { 795 destroyCandidates(); 796 NumInlineSequences = 0; 797 Candidates.clear(); 798 Functions.clear(); 799 } 800 801 namespace { 802 class UnbridgedCastsSet { 803 struct Entry { 804 Expr **Addr; 805 Expr *Saved; 806 }; 807 SmallVector<Entry, 2> Entries; 808 809 public: 810 void save(Sema &S, Expr *&E) { 811 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 812 Entry entry = { &E, E }; 813 Entries.push_back(entry); 814 E = S.stripARCUnbridgedCast(E); 815 } 816 817 void restore() { 818 for (SmallVectorImpl<Entry>::iterator 819 i = Entries.begin(), e = Entries.end(); i != e; ++i) 820 *i->Addr = i->Saved; 821 } 822 }; 823 } 824 825 /// checkPlaceholderForOverload - Do any interesting placeholder-like 826 /// preprocessing on the given expression. 827 /// 828 /// \param unbridgedCasts a collection to which to add unbridged casts; 829 /// without this, they will be immediately diagnosed as errors 830 /// 831 /// Return true on unrecoverable error. 832 static bool checkPlaceholderForOverload(Sema &S, Expr *&E, 833 UnbridgedCastsSet *unbridgedCasts = 0) { 834 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 835 // We can't handle overloaded expressions here because overload 836 // resolution might reasonably tweak them. 837 if (placeholder->getKind() == BuiltinType::Overload) return false; 838 839 // If the context potentially accepts unbridged ARC casts, strip 840 // the unbridged cast and add it to the collection for later restoration. 841 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 842 unbridgedCasts) { 843 unbridgedCasts->save(S, E); 844 return false; 845 } 846 847 // Go ahead and check everything else. 848 ExprResult result = S.CheckPlaceholderExpr(E); 849 if (result.isInvalid()) 850 return true; 851 852 E = result.take(); 853 return false; 854 } 855 856 // Nothing to do. 857 return false; 858 } 859 860 /// checkArgPlaceholdersForOverload - Check a set of call operands for 861 /// placeholders. 862 static bool checkArgPlaceholdersForOverload(Sema &S, 863 MultiExprArg Args, 864 UnbridgedCastsSet &unbridged) { 865 for (unsigned i = 0, e = Args.size(); i != e; ++i) 866 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 867 return true; 868 869 return false; 870 } 871 872 // IsOverload - Determine whether the given New declaration is an 873 // overload of the declarations in Old. This routine returns false if 874 // New and Old cannot be overloaded, e.g., if New has the same 875 // signature as some function in Old (C++ 1.3.10) or if the Old 876 // declarations aren't functions (or function templates) at all. When 877 // it does return false, MatchedDecl will point to the decl that New 878 // cannot be overloaded with. This decl may be a UsingShadowDecl on 879 // top of the underlying declaration. 880 // 881 // Example: Given the following input: 882 // 883 // void f(int, float); // #1 884 // void f(int, int); // #2 885 // int f(int, int); // #3 886 // 887 // When we process #1, there is no previous declaration of "f", 888 // so IsOverload will not be used. 889 // 890 // When we process #2, Old contains only the FunctionDecl for #1. By 891 // comparing the parameter types, we see that #1 and #2 are overloaded 892 // (since they have different signatures), so this routine returns 893 // false; MatchedDecl is unchanged. 894 // 895 // When we process #3, Old is an overload set containing #1 and #2. We 896 // compare the signatures of #3 to #1 (they're overloaded, so we do 897 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 898 // identical (return types of functions are not part of the 899 // signature), IsOverload returns false and MatchedDecl will be set to 900 // point to the FunctionDecl for #2. 901 // 902 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 903 // into a class by a using declaration. The rules for whether to hide 904 // shadow declarations ignore some properties which otherwise figure 905 // into a function template's signature. 906 Sema::OverloadKind 907 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 908 NamedDecl *&Match, bool NewIsUsingDecl) { 909 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 910 I != E; ++I) { 911 NamedDecl *OldD = *I; 912 913 bool OldIsUsingDecl = false; 914 if (isa<UsingShadowDecl>(OldD)) { 915 OldIsUsingDecl = true; 916 917 // We can always introduce two using declarations into the same 918 // context, even if they have identical signatures. 919 if (NewIsUsingDecl) continue; 920 921 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 922 } 923 924 // If either declaration was introduced by a using declaration, 925 // we'll need to use slightly different rules for matching. 926 // Essentially, these rules are the normal rules, except that 927 // function templates hide function templates with different 928 // return types or template parameter lists. 929 bool UseMemberUsingDeclRules = 930 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 931 !New->getFriendObjectKind(); 932 933 if (FunctionDecl *OldF = OldD->getAsFunction()) { 934 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 935 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 936 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 937 continue; 938 } 939 940 if (!isa<FunctionTemplateDecl>(OldD) && 941 !shouldLinkPossiblyHiddenDecl(*I, New)) 942 continue; 943 944 Match = *I; 945 return Ovl_Match; 946 } 947 } else if (isa<UsingDecl>(OldD)) { 948 // We can overload with these, which can show up when doing 949 // redeclaration checks for UsingDecls. 950 assert(Old.getLookupKind() == LookupUsingDeclName); 951 } else if (isa<TagDecl>(OldD)) { 952 // We can always overload with tags by hiding them. 953 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 954 // Optimistically assume that an unresolved using decl will 955 // overload; if it doesn't, we'll have to diagnose during 956 // template instantiation. 957 } else { 958 // (C++ 13p1): 959 // Only function declarations can be overloaded; object and type 960 // declarations cannot be overloaded. 961 Match = *I; 962 return Ovl_NonFunction; 963 } 964 } 965 966 return Ovl_Overload; 967 } 968 969 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 970 bool UseUsingDeclRules) { 971 // C++ [basic.start.main]p2: This function shall not be overloaded. 972 if (New->isMain()) 973 return false; 974 975 // MSVCRT user defined entry points cannot be overloaded. 976 if (New->isMSVCRTEntryPoint()) 977 return false; 978 979 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 980 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 981 982 // C++ [temp.fct]p2: 983 // A function template can be overloaded with other function templates 984 // and with normal (non-template) functions. 985 if ((OldTemplate == 0) != (NewTemplate == 0)) 986 return true; 987 988 // Is the function New an overload of the function Old? 989 QualType OldQType = Context.getCanonicalType(Old->getType()); 990 QualType NewQType = Context.getCanonicalType(New->getType()); 991 992 // Compare the signatures (C++ 1.3.10) of the two functions to 993 // determine whether they are overloads. If we find any mismatch 994 // in the signature, they are overloads. 995 996 // If either of these functions is a K&R-style function (no 997 // prototype), then we consider them to have matching signatures. 998 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 999 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1000 return false; 1001 1002 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1003 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1004 1005 // The signature of a function includes the types of its 1006 // parameters (C++ 1.3.10), which includes the presence or absence 1007 // of the ellipsis; see C++ DR 357). 1008 if (OldQType != NewQType && 1009 (OldType->getNumParams() != NewType->getNumParams() || 1010 OldType->isVariadic() != NewType->isVariadic() || 1011 !FunctionParamTypesAreEqual(OldType, NewType))) 1012 return true; 1013 1014 // C++ [temp.over.link]p4: 1015 // The signature of a function template consists of its function 1016 // signature, its return type and its template parameter list. The names 1017 // of the template parameters are significant only for establishing the 1018 // relationship between the template parameters and the rest of the 1019 // signature. 1020 // 1021 // We check the return type and template parameter lists for function 1022 // templates first; the remaining checks follow. 1023 // 1024 // However, we don't consider either of these when deciding whether 1025 // a member introduced by a shadow declaration is hidden. 1026 if (!UseUsingDeclRules && NewTemplate && 1027 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1028 OldTemplate->getTemplateParameters(), 1029 false, TPL_TemplateMatch) || 1030 OldType->getReturnType() != NewType->getReturnType())) 1031 return true; 1032 1033 // If the function is a class member, its signature includes the 1034 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1035 // 1036 // As part of this, also check whether one of the member functions 1037 // is static, in which case they are not overloads (C++ 1038 // 13.1p2). While not part of the definition of the signature, 1039 // this check is important to determine whether these functions 1040 // can be overloaded. 1041 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1042 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1043 if (OldMethod && NewMethod && 1044 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1045 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1046 if (!UseUsingDeclRules && 1047 (OldMethod->getRefQualifier() == RQ_None || 1048 NewMethod->getRefQualifier() == RQ_None)) { 1049 // C++0x [over.load]p2: 1050 // - Member function declarations with the same name and the same 1051 // parameter-type-list as well as member function template 1052 // declarations with the same name, the same parameter-type-list, and 1053 // the same template parameter lists cannot be overloaded if any of 1054 // them, but not all, have a ref-qualifier (8.3.5). 1055 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1056 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1057 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1058 } 1059 return true; 1060 } 1061 1062 // We may not have applied the implicit const for a constexpr member 1063 // function yet (because we haven't yet resolved whether this is a static 1064 // or non-static member function). Add it now, on the assumption that this 1065 // is a redeclaration of OldMethod. 1066 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1067 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1068 if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() && 1069 !isa<CXXConstructorDecl>(NewMethod)) 1070 NewQuals |= Qualifiers::Const; 1071 1072 // We do not allow overloading based off of '__restrict'. 1073 OldQuals &= ~Qualifiers::Restrict; 1074 NewQuals &= ~Qualifiers::Restrict; 1075 if (OldQuals != NewQuals) 1076 return true; 1077 } 1078 1079 // enable_if attributes are an order-sensitive part of the signature. 1080 for (specific_attr_iterator<EnableIfAttr> 1081 NewI = New->specific_attr_begin<EnableIfAttr>(), 1082 NewE = New->specific_attr_end<EnableIfAttr>(), 1083 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1084 OldE = Old->specific_attr_end<EnableIfAttr>(); 1085 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1086 if (NewI == NewE || OldI == OldE) 1087 return true; 1088 llvm::FoldingSetNodeID NewID, OldID; 1089 NewI->getCond()->Profile(NewID, Context, true); 1090 OldI->getCond()->Profile(OldID, Context, true); 1091 if (NewID != OldID) 1092 return true; 1093 } 1094 1095 // The signatures match; this is not an overload. 1096 return false; 1097 } 1098 1099 /// \brief Checks availability of the function depending on the current 1100 /// function context. Inside an unavailable function, unavailability is ignored. 1101 /// 1102 /// \returns true if \arg FD is unavailable and current context is inside 1103 /// an available function, false otherwise. 1104 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1105 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1106 } 1107 1108 /// \brief Tries a user-defined conversion from From to ToType. 1109 /// 1110 /// Produces an implicit conversion sequence for when a standard conversion 1111 /// is not an option. See TryImplicitConversion for more information. 1112 static ImplicitConversionSequence 1113 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1114 bool SuppressUserConversions, 1115 bool AllowExplicit, 1116 bool InOverloadResolution, 1117 bool CStyle, 1118 bool AllowObjCWritebackConversion, 1119 bool AllowObjCConversionOnExplicit) { 1120 ImplicitConversionSequence ICS; 1121 1122 if (SuppressUserConversions) { 1123 // We're not in the case above, so there is no conversion that 1124 // we can perform. 1125 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1126 return ICS; 1127 } 1128 1129 // Attempt user-defined conversion. 1130 OverloadCandidateSet Conversions(From->getExprLoc()); 1131 OverloadingResult UserDefResult 1132 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 1133 AllowExplicit, AllowObjCConversionOnExplicit); 1134 1135 if (UserDefResult == OR_Success) { 1136 ICS.setUserDefined(); 1137 ICS.UserDefined.Before.setAsIdentityConversion(); 1138 // C++ [over.ics.user]p4: 1139 // A conversion of an expression of class type to the same class 1140 // type is given Exact Match rank, and a conversion of an 1141 // expression of class type to a base class of that type is 1142 // given Conversion rank, in spite of the fact that a copy 1143 // constructor (i.e., a user-defined conversion function) is 1144 // called for those cases. 1145 if (CXXConstructorDecl *Constructor 1146 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1147 QualType FromCanon 1148 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1149 QualType ToCanon 1150 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1151 if (Constructor->isCopyConstructor() && 1152 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1153 // Turn this into a "standard" conversion sequence, so that it 1154 // gets ranked with standard conversion sequences. 1155 ICS.setStandard(); 1156 ICS.Standard.setAsIdentityConversion(); 1157 ICS.Standard.setFromType(From->getType()); 1158 ICS.Standard.setAllToTypes(ToType); 1159 ICS.Standard.CopyConstructor = Constructor; 1160 if (ToCanon != FromCanon) 1161 ICS.Standard.Second = ICK_Derived_To_Base; 1162 } 1163 } 1164 1165 // C++ [over.best.ics]p4: 1166 // However, when considering the argument of a user-defined 1167 // conversion function that is a candidate by 13.3.1.3 when 1168 // invoked for the copying of the temporary in the second step 1169 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 1170 // 13.3.1.6 in all cases, only standard conversion sequences and 1171 // ellipsis conversion sequences are allowed. 1172 if (SuppressUserConversions && ICS.isUserDefined()) { 1173 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 1174 } 1175 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 1176 ICS.setAmbiguous(); 1177 ICS.Ambiguous.setFromType(From->getType()); 1178 ICS.Ambiguous.setToType(ToType); 1179 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1180 Cand != Conversions.end(); ++Cand) 1181 if (Cand->Viable) 1182 ICS.Ambiguous.addConversion(Cand->Function); 1183 } else { 1184 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1185 } 1186 1187 return ICS; 1188 } 1189 1190 /// TryImplicitConversion - Attempt to perform an implicit conversion 1191 /// from the given expression (Expr) to the given type (ToType). This 1192 /// function returns an implicit conversion sequence that can be used 1193 /// to perform the initialization. Given 1194 /// 1195 /// void f(float f); 1196 /// void g(int i) { f(i); } 1197 /// 1198 /// this routine would produce an implicit conversion sequence to 1199 /// describe the initialization of f from i, which will be a standard 1200 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1201 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1202 // 1203 /// Note that this routine only determines how the conversion can be 1204 /// performed; it does not actually perform the conversion. As such, 1205 /// it will not produce any diagnostics if no conversion is available, 1206 /// but will instead return an implicit conversion sequence of kind 1207 /// "BadConversion". 1208 /// 1209 /// If @p SuppressUserConversions, then user-defined conversions are 1210 /// not permitted. 1211 /// If @p AllowExplicit, then explicit user-defined conversions are 1212 /// permitted. 1213 /// 1214 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1215 /// writeback conversion, which allows __autoreleasing id* parameters to 1216 /// be initialized with __strong id* or __weak id* arguments. 1217 static ImplicitConversionSequence 1218 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1219 bool SuppressUserConversions, 1220 bool AllowExplicit, 1221 bool InOverloadResolution, 1222 bool CStyle, 1223 bool AllowObjCWritebackConversion, 1224 bool AllowObjCConversionOnExplicit) { 1225 ImplicitConversionSequence ICS; 1226 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1227 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1228 ICS.setStandard(); 1229 return ICS; 1230 } 1231 1232 if (!S.getLangOpts().CPlusPlus) { 1233 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1234 return ICS; 1235 } 1236 1237 // C++ [over.ics.user]p4: 1238 // A conversion of an expression of class type to the same class 1239 // type is given Exact Match rank, and a conversion of an 1240 // expression of class type to a base class of that type is 1241 // given Conversion rank, in spite of the fact that a copy/move 1242 // constructor (i.e., a user-defined conversion function) is 1243 // called for those cases. 1244 QualType FromType = From->getType(); 1245 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1246 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1247 S.IsDerivedFrom(FromType, ToType))) { 1248 ICS.setStandard(); 1249 ICS.Standard.setAsIdentityConversion(); 1250 ICS.Standard.setFromType(FromType); 1251 ICS.Standard.setAllToTypes(ToType); 1252 1253 // We don't actually check at this point whether there is a valid 1254 // copy/move constructor, since overloading just assumes that it 1255 // exists. When we actually perform initialization, we'll find the 1256 // appropriate constructor to copy the returned object, if needed. 1257 ICS.Standard.CopyConstructor = 0; 1258 1259 // Determine whether this is considered a derived-to-base conversion. 1260 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1261 ICS.Standard.Second = ICK_Derived_To_Base; 1262 1263 return ICS; 1264 } 1265 1266 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1267 AllowExplicit, InOverloadResolution, CStyle, 1268 AllowObjCWritebackConversion, 1269 AllowObjCConversionOnExplicit); 1270 } 1271 1272 ImplicitConversionSequence 1273 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1274 bool SuppressUserConversions, 1275 bool AllowExplicit, 1276 bool InOverloadResolution, 1277 bool CStyle, 1278 bool AllowObjCWritebackConversion) { 1279 return clang::TryImplicitConversion(*this, From, ToType, 1280 SuppressUserConversions, AllowExplicit, 1281 InOverloadResolution, CStyle, 1282 AllowObjCWritebackConversion, 1283 /*AllowObjCConversionOnExplicit=*/false); 1284 } 1285 1286 /// PerformImplicitConversion - Perform an implicit conversion of the 1287 /// expression From to the type ToType. Returns the 1288 /// converted expression. Flavor is the kind of conversion we're 1289 /// performing, used in the error message. If @p AllowExplicit, 1290 /// explicit user-defined conversions are permitted. 1291 ExprResult 1292 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1293 AssignmentAction Action, bool AllowExplicit) { 1294 ImplicitConversionSequence ICS; 1295 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1296 } 1297 1298 ExprResult 1299 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1300 AssignmentAction Action, bool AllowExplicit, 1301 ImplicitConversionSequence& ICS) { 1302 if (checkPlaceholderForOverload(*this, From)) 1303 return ExprError(); 1304 1305 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1306 bool AllowObjCWritebackConversion 1307 = getLangOpts().ObjCAutoRefCount && 1308 (Action == AA_Passing || Action == AA_Sending); 1309 if (getLangOpts().ObjC1) 1310 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1311 ToType, From->getType(), From); 1312 ICS = clang::TryImplicitConversion(*this, From, ToType, 1313 /*SuppressUserConversions=*/false, 1314 AllowExplicit, 1315 /*InOverloadResolution=*/false, 1316 /*CStyle=*/false, 1317 AllowObjCWritebackConversion, 1318 /*AllowObjCConversionOnExplicit=*/false); 1319 return PerformImplicitConversion(From, ToType, ICS, Action); 1320 } 1321 1322 /// \brief Determine whether the conversion from FromType to ToType is a valid 1323 /// conversion that strips "noreturn" off the nested function type. 1324 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1325 QualType &ResultTy) { 1326 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1327 return false; 1328 1329 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1330 // where F adds one of the following at most once: 1331 // - a pointer 1332 // - a member pointer 1333 // - a block pointer 1334 CanQualType CanTo = Context.getCanonicalType(ToType); 1335 CanQualType CanFrom = Context.getCanonicalType(FromType); 1336 Type::TypeClass TyClass = CanTo->getTypeClass(); 1337 if (TyClass != CanFrom->getTypeClass()) return false; 1338 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1339 if (TyClass == Type::Pointer) { 1340 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1341 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1342 } else if (TyClass == Type::BlockPointer) { 1343 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1344 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1345 } else if (TyClass == Type::MemberPointer) { 1346 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1347 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1348 } else { 1349 return false; 1350 } 1351 1352 TyClass = CanTo->getTypeClass(); 1353 if (TyClass != CanFrom->getTypeClass()) return false; 1354 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1355 return false; 1356 } 1357 1358 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1359 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1360 if (!EInfo.getNoReturn()) return false; 1361 1362 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1363 assert(QualType(FromFn, 0).isCanonical()); 1364 if (QualType(FromFn, 0) != CanTo) return false; 1365 1366 ResultTy = ToType; 1367 return true; 1368 } 1369 1370 /// \brief Determine whether the conversion from FromType to ToType is a valid 1371 /// vector conversion. 1372 /// 1373 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1374 /// conversion. 1375 static bool IsVectorConversion(ASTContext &Context, QualType FromType, 1376 QualType ToType, ImplicitConversionKind &ICK) { 1377 // We need at least one of these types to be a vector type to have a vector 1378 // conversion. 1379 if (!ToType->isVectorType() && !FromType->isVectorType()) 1380 return false; 1381 1382 // Identical types require no conversions. 1383 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1384 return false; 1385 1386 // There are no conversions between extended vector types, only identity. 1387 if (ToType->isExtVectorType()) { 1388 // There are no conversions between extended vector types other than the 1389 // identity conversion. 1390 if (FromType->isExtVectorType()) 1391 return false; 1392 1393 // Vector splat from any arithmetic type to a vector. 1394 if (FromType->isArithmeticType()) { 1395 ICK = ICK_Vector_Splat; 1396 return true; 1397 } 1398 } 1399 1400 // We can perform the conversion between vector types in the following cases: 1401 // 1)vector types are equivalent AltiVec and GCC vector types 1402 // 2)lax vector conversions are permitted and the vector types are of the 1403 // same size 1404 if (ToType->isVectorType() && FromType->isVectorType()) { 1405 if (Context.areCompatibleVectorTypes(FromType, ToType) || 1406 (Context.getLangOpts().LaxVectorConversions && 1407 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) { 1408 ICK = ICK_Vector_Conversion; 1409 return true; 1410 } 1411 } 1412 1413 return false; 1414 } 1415 1416 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1417 bool InOverloadResolution, 1418 StandardConversionSequence &SCS, 1419 bool CStyle); 1420 1421 /// IsStandardConversion - Determines whether there is a standard 1422 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1423 /// expression From to the type ToType. Standard conversion sequences 1424 /// only consider non-class types; for conversions that involve class 1425 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1426 /// contain the standard conversion sequence required to perform this 1427 /// conversion and this routine will return true. Otherwise, this 1428 /// routine will return false and the value of SCS is unspecified. 1429 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1430 bool InOverloadResolution, 1431 StandardConversionSequence &SCS, 1432 bool CStyle, 1433 bool AllowObjCWritebackConversion) { 1434 QualType FromType = From->getType(); 1435 1436 // Standard conversions (C++ [conv]) 1437 SCS.setAsIdentityConversion(); 1438 SCS.IncompatibleObjC = false; 1439 SCS.setFromType(FromType); 1440 SCS.CopyConstructor = 0; 1441 1442 // There are no standard conversions for class types in C++, so 1443 // abort early. When overloading in C, however, we do permit 1444 if (FromType->isRecordType() || ToType->isRecordType()) { 1445 if (S.getLangOpts().CPlusPlus) 1446 return false; 1447 1448 // When we're overloading in C, we allow, as standard conversions, 1449 } 1450 1451 // The first conversion can be an lvalue-to-rvalue conversion, 1452 // array-to-pointer conversion, or function-to-pointer conversion 1453 // (C++ 4p1). 1454 1455 if (FromType == S.Context.OverloadTy) { 1456 DeclAccessPair AccessPair; 1457 if (FunctionDecl *Fn 1458 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1459 AccessPair)) { 1460 // We were able to resolve the address of the overloaded function, 1461 // so we can convert to the type of that function. 1462 FromType = Fn->getType(); 1463 1464 // we can sometimes resolve &foo<int> regardless of ToType, so check 1465 // if the type matches (identity) or we are converting to bool 1466 if (!S.Context.hasSameUnqualifiedType( 1467 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1468 QualType resultTy; 1469 // if the function type matches except for [[noreturn]], it's ok 1470 if (!S.IsNoReturnConversion(FromType, 1471 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1472 // otherwise, only a boolean conversion is standard 1473 if (!ToType->isBooleanType()) 1474 return false; 1475 } 1476 1477 // Check if the "from" expression is taking the address of an overloaded 1478 // function and recompute the FromType accordingly. Take advantage of the 1479 // fact that non-static member functions *must* have such an address-of 1480 // expression. 1481 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1482 if (Method && !Method->isStatic()) { 1483 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1484 "Non-unary operator on non-static member address"); 1485 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1486 == UO_AddrOf && 1487 "Non-address-of operator on non-static member address"); 1488 const Type *ClassType 1489 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1490 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1491 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1492 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1493 UO_AddrOf && 1494 "Non-address-of operator for overloaded function expression"); 1495 FromType = S.Context.getPointerType(FromType); 1496 } 1497 1498 // Check that we've computed the proper type after overload resolution. 1499 assert(S.Context.hasSameType( 1500 FromType, 1501 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1502 } else { 1503 return false; 1504 } 1505 } 1506 // Lvalue-to-rvalue conversion (C++11 4.1): 1507 // A glvalue (3.10) of a non-function, non-array type T can 1508 // be converted to a prvalue. 1509 bool argIsLValue = From->isGLValue(); 1510 if (argIsLValue && 1511 !FromType->isFunctionType() && !FromType->isArrayType() && 1512 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1513 SCS.First = ICK_Lvalue_To_Rvalue; 1514 1515 // C11 6.3.2.1p2: 1516 // ... if the lvalue has atomic type, the value has the non-atomic version 1517 // of the type of the lvalue ... 1518 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1519 FromType = Atomic->getValueType(); 1520 1521 // If T is a non-class type, the type of the rvalue is the 1522 // cv-unqualified version of T. Otherwise, the type of the rvalue 1523 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1524 // just strip the qualifiers because they don't matter. 1525 FromType = FromType.getUnqualifiedType(); 1526 } else if (FromType->isArrayType()) { 1527 // Array-to-pointer conversion (C++ 4.2) 1528 SCS.First = ICK_Array_To_Pointer; 1529 1530 // An lvalue or rvalue of type "array of N T" or "array of unknown 1531 // bound of T" can be converted to an rvalue of type "pointer to 1532 // T" (C++ 4.2p1). 1533 FromType = S.Context.getArrayDecayedType(FromType); 1534 1535 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1536 // This conversion is deprecated in C++03 (D.4) 1537 SCS.DeprecatedStringLiteralToCharPtr = true; 1538 1539 // For the purpose of ranking in overload resolution 1540 // (13.3.3.1.1), this conversion is considered an 1541 // array-to-pointer conversion followed by a qualification 1542 // conversion (4.4). (C++ 4.2p2) 1543 SCS.Second = ICK_Identity; 1544 SCS.Third = ICK_Qualification; 1545 SCS.QualificationIncludesObjCLifetime = false; 1546 SCS.setAllToTypes(FromType); 1547 return true; 1548 } 1549 } else if (FromType->isFunctionType() && argIsLValue) { 1550 // Function-to-pointer conversion (C++ 4.3). 1551 SCS.First = ICK_Function_To_Pointer; 1552 1553 // An lvalue of function type T can be converted to an rvalue of 1554 // type "pointer to T." The result is a pointer to the 1555 // function. (C++ 4.3p1). 1556 FromType = S.Context.getPointerType(FromType); 1557 } else { 1558 // We don't require any conversions for the first step. 1559 SCS.First = ICK_Identity; 1560 } 1561 SCS.setToType(0, FromType); 1562 1563 // The second conversion can be an integral promotion, floating 1564 // point promotion, integral conversion, floating point conversion, 1565 // floating-integral conversion, pointer conversion, 1566 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1567 // For overloading in C, this can also be a "compatible-type" 1568 // conversion. 1569 bool IncompatibleObjC = false; 1570 ImplicitConversionKind SecondICK = ICK_Identity; 1571 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1572 // The unqualified versions of the types are the same: there's no 1573 // conversion to do. 1574 SCS.Second = ICK_Identity; 1575 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1576 // Integral promotion (C++ 4.5). 1577 SCS.Second = ICK_Integral_Promotion; 1578 FromType = ToType.getUnqualifiedType(); 1579 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1580 // Floating point promotion (C++ 4.6). 1581 SCS.Second = ICK_Floating_Promotion; 1582 FromType = ToType.getUnqualifiedType(); 1583 } else if (S.IsComplexPromotion(FromType, ToType)) { 1584 // Complex promotion (Clang extension) 1585 SCS.Second = ICK_Complex_Promotion; 1586 FromType = ToType.getUnqualifiedType(); 1587 } else if (ToType->isBooleanType() && 1588 (FromType->isArithmeticType() || 1589 FromType->isAnyPointerType() || 1590 FromType->isBlockPointerType() || 1591 FromType->isMemberPointerType() || 1592 FromType->isNullPtrType())) { 1593 // Boolean conversions (C++ 4.12). 1594 SCS.Second = ICK_Boolean_Conversion; 1595 FromType = S.Context.BoolTy; 1596 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1597 ToType->isIntegralType(S.Context)) { 1598 // Integral conversions (C++ 4.7). 1599 SCS.Second = ICK_Integral_Conversion; 1600 FromType = ToType.getUnqualifiedType(); 1601 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1602 // Complex conversions (C99 6.3.1.6) 1603 SCS.Second = ICK_Complex_Conversion; 1604 FromType = ToType.getUnqualifiedType(); 1605 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1606 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1607 // Complex-real conversions (C99 6.3.1.7) 1608 SCS.Second = ICK_Complex_Real; 1609 FromType = ToType.getUnqualifiedType(); 1610 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1611 // Floating point conversions (C++ 4.8). 1612 SCS.Second = ICK_Floating_Conversion; 1613 FromType = ToType.getUnqualifiedType(); 1614 } else if ((FromType->isRealFloatingType() && 1615 ToType->isIntegralType(S.Context)) || 1616 (FromType->isIntegralOrUnscopedEnumerationType() && 1617 ToType->isRealFloatingType())) { 1618 // Floating-integral conversions (C++ 4.9). 1619 SCS.Second = ICK_Floating_Integral; 1620 FromType = ToType.getUnqualifiedType(); 1621 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1622 SCS.Second = ICK_Block_Pointer_Conversion; 1623 } else if (AllowObjCWritebackConversion && 1624 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1625 SCS.Second = ICK_Writeback_Conversion; 1626 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1627 FromType, IncompatibleObjC)) { 1628 // Pointer conversions (C++ 4.10). 1629 SCS.Second = ICK_Pointer_Conversion; 1630 SCS.IncompatibleObjC = IncompatibleObjC; 1631 FromType = FromType.getUnqualifiedType(); 1632 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1633 InOverloadResolution, FromType)) { 1634 // Pointer to member conversions (4.11). 1635 SCS.Second = ICK_Pointer_Member; 1636 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) { 1637 SCS.Second = SecondICK; 1638 FromType = ToType.getUnqualifiedType(); 1639 } else if (!S.getLangOpts().CPlusPlus && 1640 S.Context.typesAreCompatible(ToType, FromType)) { 1641 // Compatible conversions (Clang extension for C function overloading) 1642 SCS.Second = ICK_Compatible_Conversion; 1643 FromType = ToType.getUnqualifiedType(); 1644 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1645 // Treat a conversion that strips "noreturn" as an identity conversion. 1646 SCS.Second = ICK_NoReturn_Adjustment; 1647 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1648 InOverloadResolution, 1649 SCS, CStyle)) { 1650 SCS.Second = ICK_TransparentUnionConversion; 1651 FromType = ToType; 1652 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1653 CStyle)) { 1654 // tryAtomicConversion has updated the standard conversion sequence 1655 // appropriately. 1656 return true; 1657 } else if (ToType->isEventT() && 1658 From->isIntegerConstantExpr(S.getASTContext()) && 1659 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1660 SCS.Second = ICK_Zero_Event_Conversion; 1661 FromType = ToType; 1662 } else { 1663 // No second conversion required. 1664 SCS.Second = ICK_Identity; 1665 } 1666 SCS.setToType(1, FromType); 1667 1668 QualType CanonFrom; 1669 QualType CanonTo; 1670 // The third conversion can be a qualification conversion (C++ 4p1). 1671 bool ObjCLifetimeConversion; 1672 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1673 ObjCLifetimeConversion)) { 1674 SCS.Third = ICK_Qualification; 1675 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1676 FromType = ToType; 1677 CanonFrom = S.Context.getCanonicalType(FromType); 1678 CanonTo = S.Context.getCanonicalType(ToType); 1679 } else { 1680 // No conversion required 1681 SCS.Third = ICK_Identity; 1682 1683 // C++ [over.best.ics]p6: 1684 // [...] Any difference in top-level cv-qualification is 1685 // subsumed by the initialization itself and does not constitute 1686 // a conversion. [...] 1687 CanonFrom = S.Context.getCanonicalType(FromType); 1688 CanonTo = S.Context.getCanonicalType(ToType); 1689 if (CanonFrom.getLocalUnqualifiedType() 1690 == CanonTo.getLocalUnqualifiedType() && 1691 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1692 FromType = ToType; 1693 CanonFrom = CanonTo; 1694 } 1695 } 1696 SCS.setToType(2, FromType); 1697 1698 // If we have not converted the argument type to the parameter type, 1699 // this is a bad conversion sequence. 1700 if (CanonFrom != CanonTo) 1701 return false; 1702 1703 return true; 1704 } 1705 1706 static bool 1707 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1708 QualType &ToType, 1709 bool InOverloadResolution, 1710 StandardConversionSequence &SCS, 1711 bool CStyle) { 1712 1713 const RecordType *UT = ToType->getAsUnionType(); 1714 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1715 return false; 1716 // The field to initialize within the transparent union. 1717 RecordDecl *UD = UT->getDecl(); 1718 // It's compatible if the expression matches any of the fields. 1719 for (RecordDecl::field_iterator it = UD->field_begin(), 1720 itend = UD->field_end(); 1721 it != itend; ++it) { 1722 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1723 CStyle, /*ObjCWritebackConversion=*/false)) { 1724 ToType = it->getType(); 1725 return true; 1726 } 1727 } 1728 return false; 1729 } 1730 1731 /// IsIntegralPromotion - Determines whether the conversion from the 1732 /// expression From (whose potentially-adjusted type is FromType) to 1733 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1734 /// sets PromotedType to the promoted type. 1735 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1736 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1737 // All integers are built-in. 1738 if (!To) { 1739 return false; 1740 } 1741 1742 // An rvalue of type char, signed char, unsigned char, short int, or 1743 // unsigned short int can be converted to an rvalue of type int if 1744 // int can represent all the values of the source type; otherwise, 1745 // the source rvalue can be converted to an rvalue of type unsigned 1746 // int (C++ 4.5p1). 1747 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1748 !FromType->isEnumeralType()) { 1749 if (// We can promote any signed, promotable integer type to an int 1750 (FromType->isSignedIntegerType() || 1751 // We can promote any unsigned integer type whose size is 1752 // less than int to an int. 1753 (!FromType->isSignedIntegerType() && 1754 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1755 return To->getKind() == BuiltinType::Int; 1756 } 1757 1758 return To->getKind() == BuiltinType::UInt; 1759 } 1760 1761 // C++11 [conv.prom]p3: 1762 // A prvalue of an unscoped enumeration type whose underlying type is not 1763 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1764 // following types that can represent all the values of the enumeration 1765 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1766 // unsigned int, long int, unsigned long int, long long int, or unsigned 1767 // long long int. If none of the types in that list can represent all the 1768 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1769 // type can be converted to an rvalue a prvalue of the extended integer type 1770 // with lowest integer conversion rank (4.13) greater than the rank of long 1771 // long in which all the values of the enumeration can be represented. If 1772 // there are two such extended types, the signed one is chosen. 1773 // C++11 [conv.prom]p4: 1774 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1775 // can be converted to a prvalue of its underlying type. Moreover, if 1776 // integral promotion can be applied to its underlying type, a prvalue of an 1777 // unscoped enumeration type whose underlying type is fixed can also be 1778 // converted to a prvalue of the promoted underlying type. 1779 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1780 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1781 // provided for a scoped enumeration. 1782 if (FromEnumType->getDecl()->isScoped()) 1783 return false; 1784 1785 // We can perform an integral promotion to the underlying type of the enum, 1786 // even if that's not the promoted type. 1787 if (FromEnumType->getDecl()->isFixed()) { 1788 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1789 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1790 IsIntegralPromotion(From, Underlying, ToType); 1791 } 1792 1793 // We have already pre-calculated the promotion type, so this is trivial. 1794 if (ToType->isIntegerType() && 1795 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1796 return Context.hasSameUnqualifiedType(ToType, 1797 FromEnumType->getDecl()->getPromotionType()); 1798 } 1799 1800 // C++0x [conv.prom]p2: 1801 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1802 // to an rvalue a prvalue of the first of the following types that can 1803 // represent all the values of its underlying type: int, unsigned int, 1804 // long int, unsigned long int, long long int, or unsigned long long int. 1805 // If none of the types in that list can represent all the values of its 1806 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1807 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1808 // type. 1809 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1810 ToType->isIntegerType()) { 1811 // Determine whether the type we're converting from is signed or 1812 // unsigned. 1813 bool FromIsSigned = FromType->isSignedIntegerType(); 1814 uint64_t FromSize = Context.getTypeSize(FromType); 1815 1816 // The types we'll try to promote to, in the appropriate 1817 // order. Try each of these types. 1818 QualType PromoteTypes[6] = { 1819 Context.IntTy, Context.UnsignedIntTy, 1820 Context.LongTy, Context.UnsignedLongTy , 1821 Context.LongLongTy, Context.UnsignedLongLongTy 1822 }; 1823 for (int Idx = 0; Idx < 6; ++Idx) { 1824 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1825 if (FromSize < ToSize || 1826 (FromSize == ToSize && 1827 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1828 // We found the type that we can promote to. If this is the 1829 // type we wanted, we have a promotion. Otherwise, no 1830 // promotion. 1831 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1832 } 1833 } 1834 } 1835 1836 // An rvalue for an integral bit-field (9.6) can be converted to an 1837 // rvalue of type int if int can represent all the values of the 1838 // bit-field; otherwise, it can be converted to unsigned int if 1839 // unsigned int can represent all the values of the bit-field. If 1840 // the bit-field is larger yet, no integral promotion applies to 1841 // it. If the bit-field has an enumerated type, it is treated as any 1842 // other value of that type for promotion purposes (C++ 4.5p3). 1843 // FIXME: We should delay checking of bit-fields until we actually perform the 1844 // conversion. 1845 using llvm::APSInt; 1846 if (From) 1847 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1848 APSInt BitWidth; 1849 if (FromType->isIntegralType(Context) && 1850 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1851 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1852 ToSize = Context.getTypeSize(ToType); 1853 1854 // Are we promoting to an int from a bitfield that fits in an int? 1855 if (BitWidth < ToSize || 1856 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1857 return To->getKind() == BuiltinType::Int; 1858 } 1859 1860 // Are we promoting to an unsigned int from an unsigned bitfield 1861 // that fits into an unsigned int? 1862 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1863 return To->getKind() == BuiltinType::UInt; 1864 } 1865 1866 return false; 1867 } 1868 } 1869 1870 // An rvalue of type bool can be converted to an rvalue of type int, 1871 // with false becoming zero and true becoming one (C++ 4.5p4). 1872 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1873 return true; 1874 } 1875 1876 return false; 1877 } 1878 1879 /// IsFloatingPointPromotion - Determines whether the conversion from 1880 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1881 /// returns true and sets PromotedType to the promoted type. 1882 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1883 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1884 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1885 /// An rvalue of type float can be converted to an rvalue of type 1886 /// double. (C++ 4.6p1). 1887 if (FromBuiltin->getKind() == BuiltinType::Float && 1888 ToBuiltin->getKind() == BuiltinType::Double) 1889 return true; 1890 1891 // C99 6.3.1.5p1: 1892 // When a float is promoted to double or long double, or a 1893 // double is promoted to long double [...]. 1894 if (!getLangOpts().CPlusPlus && 1895 (FromBuiltin->getKind() == BuiltinType::Float || 1896 FromBuiltin->getKind() == BuiltinType::Double) && 1897 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1898 return true; 1899 1900 // Half can be promoted to float. 1901 if (!getLangOpts().NativeHalfType && 1902 FromBuiltin->getKind() == BuiltinType::Half && 1903 ToBuiltin->getKind() == BuiltinType::Float) 1904 return true; 1905 } 1906 1907 return false; 1908 } 1909 1910 /// \brief Determine if a conversion is a complex promotion. 1911 /// 1912 /// A complex promotion is defined as a complex -> complex conversion 1913 /// where the conversion between the underlying real types is a 1914 /// floating-point or integral promotion. 1915 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1916 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1917 if (!FromComplex) 1918 return false; 1919 1920 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1921 if (!ToComplex) 1922 return false; 1923 1924 return IsFloatingPointPromotion(FromComplex->getElementType(), 1925 ToComplex->getElementType()) || 1926 IsIntegralPromotion(0, FromComplex->getElementType(), 1927 ToComplex->getElementType()); 1928 } 1929 1930 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1931 /// the pointer type FromPtr to a pointer to type ToPointee, with the 1932 /// same type qualifiers as FromPtr has on its pointee type. ToType, 1933 /// if non-empty, will be a pointer to ToType that may or may not have 1934 /// the right set of qualifiers on its pointee. 1935 /// 1936 static QualType 1937 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1938 QualType ToPointee, QualType ToType, 1939 ASTContext &Context, 1940 bool StripObjCLifetime = false) { 1941 assert((FromPtr->getTypeClass() == Type::Pointer || 1942 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1943 "Invalid similarly-qualified pointer type"); 1944 1945 /// Conversions to 'id' subsume cv-qualifier conversions. 1946 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1947 return ToType.getUnqualifiedType(); 1948 1949 QualType CanonFromPointee 1950 = Context.getCanonicalType(FromPtr->getPointeeType()); 1951 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1952 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1953 1954 if (StripObjCLifetime) 1955 Quals.removeObjCLifetime(); 1956 1957 // Exact qualifier match -> return the pointer type we're converting to. 1958 if (CanonToPointee.getLocalQualifiers() == Quals) { 1959 // ToType is exactly what we need. Return it. 1960 if (!ToType.isNull()) 1961 return ToType.getUnqualifiedType(); 1962 1963 // Build a pointer to ToPointee. It has the right qualifiers 1964 // already. 1965 if (isa<ObjCObjectPointerType>(ToType)) 1966 return Context.getObjCObjectPointerType(ToPointee); 1967 return Context.getPointerType(ToPointee); 1968 } 1969 1970 // Just build a canonical type that has the right qualifiers. 1971 QualType QualifiedCanonToPointee 1972 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1973 1974 if (isa<ObjCObjectPointerType>(ToType)) 1975 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1976 return Context.getPointerType(QualifiedCanonToPointee); 1977 } 1978 1979 static bool isNullPointerConstantForConversion(Expr *Expr, 1980 bool InOverloadResolution, 1981 ASTContext &Context) { 1982 // Handle value-dependent integral null pointer constants correctly. 1983 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1984 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1985 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1986 return !InOverloadResolution; 1987 1988 return Expr->isNullPointerConstant(Context, 1989 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1990 : Expr::NPC_ValueDependentIsNull); 1991 } 1992 1993 /// IsPointerConversion - Determines whether the conversion of the 1994 /// expression From, which has the (possibly adjusted) type FromType, 1995 /// can be converted to the type ToType via a pointer conversion (C++ 1996 /// 4.10). If so, returns true and places the converted type (that 1997 /// might differ from ToType in its cv-qualifiers at some level) into 1998 /// ConvertedType. 1999 /// 2000 /// This routine also supports conversions to and from block pointers 2001 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2002 /// pointers to interfaces. FIXME: Once we've determined the 2003 /// appropriate overloading rules for Objective-C, we may want to 2004 /// split the Objective-C checks into a different routine; however, 2005 /// GCC seems to consider all of these conversions to be pointer 2006 /// conversions, so for now they live here. IncompatibleObjC will be 2007 /// set if the conversion is an allowed Objective-C conversion that 2008 /// should result in a warning. 2009 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2010 bool InOverloadResolution, 2011 QualType& ConvertedType, 2012 bool &IncompatibleObjC) { 2013 IncompatibleObjC = false; 2014 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2015 IncompatibleObjC)) 2016 return true; 2017 2018 // Conversion from a null pointer constant to any Objective-C pointer type. 2019 if (ToType->isObjCObjectPointerType() && 2020 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2021 ConvertedType = ToType; 2022 return true; 2023 } 2024 2025 // Blocks: Block pointers can be converted to void*. 2026 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2027 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2028 ConvertedType = ToType; 2029 return true; 2030 } 2031 // Blocks: A null pointer constant can be converted to a block 2032 // pointer type. 2033 if (ToType->isBlockPointerType() && 2034 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2035 ConvertedType = ToType; 2036 return true; 2037 } 2038 2039 // If the left-hand-side is nullptr_t, the right side can be a null 2040 // pointer constant. 2041 if (ToType->isNullPtrType() && 2042 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2043 ConvertedType = ToType; 2044 return true; 2045 } 2046 2047 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2048 if (!ToTypePtr) 2049 return false; 2050 2051 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2052 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2053 ConvertedType = ToType; 2054 return true; 2055 } 2056 2057 // Beyond this point, both types need to be pointers 2058 // , including objective-c pointers. 2059 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2060 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2061 !getLangOpts().ObjCAutoRefCount) { 2062 ConvertedType = BuildSimilarlyQualifiedPointerType( 2063 FromType->getAs<ObjCObjectPointerType>(), 2064 ToPointeeType, 2065 ToType, Context); 2066 return true; 2067 } 2068 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2069 if (!FromTypePtr) 2070 return false; 2071 2072 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2073 2074 // If the unqualified pointee types are the same, this can't be a 2075 // pointer conversion, so don't do all of the work below. 2076 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2077 return false; 2078 2079 // An rvalue of type "pointer to cv T," where T is an object type, 2080 // can be converted to an rvalue of type "pointer to cv void" (C++ 2081 // 4.10p2). 2082 if (FromPointeeType->isIncompleteOrObjectType() && 2083 ToPointeeType->isVoidType()) { 2084 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2085 ToPointeeType, 2086 ToType, Context, 2087 /*StripObjCLifetime=*/true); 2088 return true; 2089 } 2090 2091 // MSVC allows implicit function to void* type conversion. 2092 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 2093 ToPointeeType->isVoidType()) { 2094 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2095 ToPointeeType, 2096 ToType, Context); 2097 return true; 2098 } 2099 2100 // When we're overloading in C, we allow a special kind of pointer 2101 // conversion for compatible-but-not-identical pointee types. 2102 if (!getLangOpts().CPlusPlus && 2103 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2104 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2105 ToPointeeType, 2106 ToType, Context); 2107 return true; 2108 } 2109 2110 // C++ [conv.ptr]p3: 2111 // 2112 // An rvalue of type "pointer to cv D," where D is a class type, 2113 // can be converted to an rvalue of type "pointer to cv B," where 2114 // B is a base class (clause 10) of D. If B is an inaccessible 2115 // (clause 11) or ambiguous (10.2) base class of D, a program that 2116 // necessitates this conversion is ill-formed. The result of the 2117 // conversion is a pointer to the base class sub-object of the 2118 // derived class object. The null pointer value is converted to 2119 // the null pointer value of the destination type. 2120 // 2121 // Note that we do not check for ambiguity or inaccessibility 2122 // here. That is handled by CheckPointerConversion. 2123 if (getLangOpts().CPlusPlus && 2124 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2125 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2126 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2127 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2128 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2129 ToPointeeType, 2130 ToType, Context); 2131 return true; 2132 } 2133 2134 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2135 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2136 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2137 ToPointeeType, 2138 ToType, Context); 2139 return true; 2140 } 2141 2142 return false; 2143 } 2144 2145 /// \brief Adopt the given qualifiers for the given type. 2146 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2147 Qualifiers TQs = T.getQualifiers(); 2148 2149 // Check whether qualifiers already match. 2150 if (TQs == Qs) 2151 return T; 2152 2153 if (Qs.compatiblyIncludes(TQs)) 2154 return Context.getQualifiedType(T, Qs); 2155 2156 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2157 } 2158 2159 /// isObjCPointerConversion - Determines whether this is an 2160 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2161 /// with the same arguments and return values. 2162 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2163 QualType& ConvertedType, 2164 bool &IncompatibleObjC) { 2165 if (!getLangOpts().ObjC1) 2166 return false; 2167 2168 // The set of qualifiers on the type we're converting from. 2169 Qualifiers FromQualifiers = FromType.getQualifiers(); 2170 2171 // First, we handle all conversions on ObjC object pointer types. 2172 const ObjCObjectPointerType* ToObjCPtr = 2173 ToType->getAs<ObjCObjectPointerType>(); 2174 const ObjCObjectPointerType *FromObjCPtr = 2175 FromType->getAs<ObjCObjectPointerType>(); 2176 2177 if (ToObjCPtr && FromObjCPtr) { 2178 // If the pointee types are the same (ignoring qualifications), 2179 // then this is not a pointer conversion. 2180 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2181 FromObjCPtr->getPointeeType())) 2182 return false; 2183 2184 // Check for compatible 2185 // Objective C++: We're able to convert between "id" or "Class" and a 2186 // pointer to any interface (in both directions). 2187 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2188 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2189 return true; 2190 } 2191 // Conversions with Objective-C's id<...>. 2192 if ((FromObjCPtr->isObjCQualifiedIdType() || 2193 ToObjCPtr->isObjCQualifiedIdType()) && 2194 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2195 /*compare=*/false)) { 2196 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2197 return true; 2198 } 2199 // Objective C++: We're able to convert from a pointer to an 2200 // interface to a pointer to a different interface. 2201 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2202 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2203 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2204 if (getLangOpts().CPlusPlus && LHS && RHS && 2205 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2206 FromObjCPtr->getPointeeType())) 2207 return false; 2208 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2209 ToObjCPtr->getPointeeType(), 2210 ToType, Context); 2211 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2212 return true; 2213 } 2214 2215 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2216 // Okay: this is some kind of implicit downcast of Objective-C 2217 // interfaces, which is permitted. However, we're going to 2218 // complain about it. 2219 IncompatibleObjC = true; 2220 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2221 ToObjCPtr->getPointeeType(), 2222 ToType, Context); 2223 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2224 return true; 2225 } 2226 } 2227 // Beyond this point, both types need to be C pointers or block pointers. 2228 QualType ToPointeeType; 2229 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2230 ToPointeeType = ToCPtr->getPointeeType(); 2231 else if (const BlockPointerType *ToBlockPtr = 2232 ToType->getAs<BlockPointerType>()) { 2233 // Objective C++: We're able to convert from a pointer to any object 2234 // to a block pointer type. 2235 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2236 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2237 return true; 2238 } 2239 ToPointeeType = ToBlockPtr->getPointeeType(); 2240 } 2241 else if (FromType->getAs<BlockPointerType>() && 2242 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2243 // Objective C++: We're able to convert from a block pointer type to a 2244 // pointer to any object. 2245 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2246 return true; 2247 } 2248 else 2249 return false; 2250 2251 QualType FromPointeeType; 2252 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2253 FromPointeeType = FromCPtr->getPointeeType(); 2254 else if (const BlockPointerType *FromBlockPtr = 2255 FromType->getAs<BlockPointerType>()) 2256 FromPointeeType = FromBlockPtr->getPointeeType(); 2257 else 2258 return false; 2259 2260 // If we have pointers to pointers, recursively check whether this 2261 // is an Objective-C conversion. 2262 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2263 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2264 IncompatibleObjC)) { 2265 // We always complain about this conversion. 2266 IncompatibleObjC = true; 2267 ConvertedType = Context.getPointerType(ConvertedType); 2268 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2269 return true; 2270 } 2271 // Allow conversion of pointee being objective-c pointer to another one; 2272 // as in I* to id. 2273 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2274 ToPointeeType->getAs<ObjCObjectPointerType>() && 2275 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2276 IncompatibleObjC)) { 2277 2278 ConvertedType = Context.getPointerType(ConvertedType); 2279 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2280 return true; 2281 } 2282 2283 // If we have pointers to functions or blocks, check whether the only 2284 // differences in the argument and result types are in Objective-C 2285 // pointer conversions. If so, we permit the conversion (but 2286 // complain about it). 2287 const FunctionProtoType *FromFunctionType 2288 = FromPointeeType->getAs<FunctionProtoType>(); 2289 const FunctionProtoType *ToFunctionType 2290 = ToPointeeType->getAs<FunctionProtoType>(); 2291 if (FromFunctionType && ToFunctionType) { 2292 // If the function types are exactly the same, this isn't an 2293 // Objective-C pointer conversion. 2294 if (Context.getCanonicalType(FromPointeeType) 2295 == Context.getCanonicalType(ToPointeeType)) 2296 return false; 2297 2298 // Perform the quick checks that will tell us whether these 2299 // function types are obviously different. 2300 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2301 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2302 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2303 return false; 2304 2305 bool HasObjCConversion = false; 2306 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2307 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2308 // Okay, the types match exactly. Nothing to do. 2309 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2310 ToFunctionType->getReturnType(), 2311 ConvertedType, IncompatibleObjC)) { 2312 // Okay, we have an Objective-C pointer conversion. 2313 HasObjCConversion = true; 2314 } else { 2315 // Function types are too different. Abort. 2316 return false; 2317 } 2318 2319 // Check argument types. 2320 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2321 ArgIdx != NumArgs; ++ArgIdx) { 2322 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2323 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2324 if (Context.getCanonicalType(FromArgType) 2325 == Context.getCanonicalType(ToArgType)) { 2326 // Okay, the types match exactly. Nothing to do. 2327 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2328 ConvertedType, IncompatibleObjC)) { 2329 // Okay, we have an Objective-C pointer conversion. 2330 HasObjCConversion = true; 2331 } else { 2332 // Argument types are too different. Abort. 2333 return false; 2334 } 2335 } 2336 2337 if (HasObjCConversion) { 2338 // We had an Objective-C conversion. Allow this pointer 2339 // conversion, but complain about it. 2340 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2341 IncompatibleObjC = true; 2342 return true; 2343 } 2344 } 2345 2346 return false; 2347 } 2348 2349 /// \brief Determine whether this is an Objective-C writeback conversion, 2350 /// used for parameter passing when performing automatic reference counting. 2351 /// 2352 /// \param FromType The type we're converting form. 2353 /// 2354 /// \param ToType The type we're converting to. 2355 /// 2356 /// \param ConvertedType The type that will be produced after applying 2357 /// this conversion. 2358 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2359 QualType &ConvertedType) { 2360 if (!getLangOpts().ObjCAutoRefCount || 2361 Context.hasSameUnqualifiedType(FromType, ToType)) 2362 return false; 2363 2364 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2365 QualType ToPointee; 2366 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2367 ToPointee = ToPointer->getPointeeType(); 2368 else 2369 return false; 2370 2371 Qualifiers ToQuals = ToPointee.getQualifiers(); 2372 if (!ToPointee->isObjCLifetimeType() || 2373 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2374 !ToQuals.withoutObjCLifetime().empty()) 2375 return false; 2376 2377 // Argument must be a pointer to __strong to __weak. 2378 QualType FromPointee; 2379 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2380 FromPointee = FromPointer->getPointeeType(); 2381 else 2382 return false; 2383 2384 Qualifiers FromQuals = FromPointee.getQualifiers(); 2385 if (!FromPointee->isObjCLifetimeType() || 2386 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2387 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2388 return false; 2389 2390 // Make sure that we have compatible qualifiers. 2391 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2392 if (!ToQuals.compatiblyIncludes(FromQuals)) 2393 return false; 2394 2395 // Remove qualifiers from the pointee type we're converting from; they 2396 // aren't used in the compatibility check belong, and we'll be adding back 2397 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2398 FromPointee = FromPointee.getUnqualifiedType(); 2399 2400 // The unqualified form of the pointee types must be compatible. 2401 ToPointee = ToPointee.getUnqualifiedType(); 2402 bool IncompatibleObjC; 2403 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2404 FromPointee = ToPointee; 2405 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2406 IncompatibleObjC)) 2407 return false; 2408 2409 /// \brief Construct the type we're converting to, which is a pointer to 2410 /// __autoreleasing pointee. 2411 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2412 ConvertedType = Context.getPointerType(FromPointee); 2413 return true; 2414 } 2415 2416 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2417 QualType& ConvertedType) { 2418 QualType ToPointeeType; 2419 if (const BlockPointerType *ToBlockPtr = 2420 ToType->getAs<BlockPointerType>()) 2421 ToPointeeType = ToBlockPtr->getPointeeType(); 2422 else 2423 return false; 2424 2425 QualType FromPointeeType; 2426 if (const BlockPointerType *FromBlockPtr = 2427 FromType->getAs<BlockPointerType>()) 2428 FromPointeeType = FromBlockPtr->getPointeeType(); 2429 else 2430 return false; 2431 // We have pointer to blocks, check whether the only 2432 // differences in the argument and result types are in Objective-C 2433 // pointer conversions. If so, we permit the conversion. 2434 2435 const FunctionProtoType *FromFunctionType 2436 = FromPointeeType->getAs<FunctionProtoType>(); 2437 const FunctionProtoType *ToFunctionType 2438 = ToPointeeType->getAs<FunctionProtoType>(); 2439 2440 if (!FromFunctionType || !ToFunctionType) 2441 return false; 2442 2443 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2444 return true; 2445 2446 // Perform the quick checks that will tell us whether these 2447 // function types are obviously different. 2448 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2449 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2450 return false; 2451 2452 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2453 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2454 if (FromEInfo != ToEInfo) 2455 return false; 2456 2457 bool IncompatibleObjC = false; 2458 if (Context.hasSameType(FromFunctionType->getReturnType(), 2459 ToFunctionType->getReturnType())) { 2460 // Okay, the types match exactly. Nothing to do. 2461 } else { 2462 QualType RHS = FromFunctionType->getReturnType(); 2463 QualType LHS = ToFunctionType->getReturnType(); 2464 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2465 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2466 LHS = LHS.getUnqualifiedType(); 2467 2468 if (Context.hasSameType(RHS,LHS)) { 2469 // OK exact match. 2470 } else if (isObjCPointerConversion(RHS, LHS, 2471 ConvertedType, IncompatibleObjC)) { 2472 if (IncompatibleObjC) 2473 return false; 2474 // Okay, we have an Objective-C pointer conversion. 2475 } 2476 else 2477 return false; 2478 } 2479 2480 // Check argument types. 2481 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2482 ArgIdx != NumArgs; ++ArgIdx) { 2483 IncompatibleObjC = false; 2484 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2485 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2486 if (Context.hasSameType(FromArgType, ToArgType)) { 2487 // Okay, the types match exactly. Nothing to do. 2488 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2489 ConvertedType, IncompatibleObjC)) { 2490 if (IncompatibleObjC) 2491 return false; 2492 // Okay, we have an Objective-C pointer conversion. 2493 } else 2494 // Argument types are too different. Abort. 2495 return false; 2496 } 2497 if (LangOpts.ObjCAutoRefCount && 2498 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2499 ToFunctionType)) 2500 return false; 2501 2502 ConvertedType = ToType; 2503 return true; 2504 } 2505 2506 enum { 2507 ft_default, 2508 ft_different_class, 2509 ft_parameter_arity, 2510 ft_parameter_mismatch, 2511 ft_return_type, 2512 ft_qualifer_mismatch 2513 }; 2514 2515 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2516 /// function types. Catches different number of parameter, mismatch in 2517 /// parameter types, and different return types. 2518 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2519 QualType FromType, QualType ToType) { 2520 // If either type is not valid, include no extra info. 2521 if (FromType.isNull() || ToType.isNull()) { 2522 PDiag << ft_default; 2523 return; 2524 } 2525 2526 // Get the function type from the pointers. 2527 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2528 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2529 *ToMember = ToType->getAs<MemberPointerType>(); 2530 if (FromMember->getClass() != ToMember->getClass()) { 2531 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2532 << QualType(FromMember->getClass(), 0); 2533 return; 2534 } 2535 FromType = FromMember->getPointeeType(); 2536 ToType = ToMember->getPointeeType(); 2537 } 2538 2539 if (FromType->isPointerType()) 2540 FromType = FromType->getPointeeType(); 2541 if (ToType->isPointerType()) 2542 ToType = ToType->getPointeeType(); 2543 2544 // Remove references. 2545 FromType = FromType.getNonReferenceType(); 2546 ToType = ToType.getNonReferenceType(); 2547 2548 // Don't print extra info for non-specialized template functions. 2549 if (FromType->isInstantiationDependentType() && 2550 !FromType->getAs<TemplateSpecializationType>()) { 2551 PDiag << ft_default; 2552 return; 2553 } 2554 2555 // No extra info for same types. 2556 if (Context.hasSameType(FromType, ToType)) { 2557 PDiag << ft_default; 2558 return; 2559 } 2560 2561 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2562 *ToFunction = ToType->getAs<FunctionProtoType>(); 2563 2564 // Both types need to be function types. 2565 if (!FromFunction || !ToFunction) { 2566 PDiag << ft_default; 2567 return; 2568 } 2569 2570 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2571 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2572 << FromFunction->getNumParams(); 2573 return; 2574 } 2575 2576 // Handle different parameter types. 2577 unsigned ArgPos; 2578 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2579 PDiag << ft_parameter_mismatch << ArgPos + 1 2580 << ToFunction->getParamType(ArgPos) 2581 << FromFunction->getParamType(ArgPos); 2582 return; 2583 } 2584 2585 // Handle different return type. 2586 if (!Context.hasSameType(FromFunction->getReturnType(), 2587 ToFunction->getReturnType())) { 2588 PDiag << ft_return_type << ToFunction->getReturnType() 2589 << FromFunction->getReturnType(); 2590 return; 2591 } 2592 2593 unsigned FromQuals = FromFunction->getTypeQuals(), 2594 ToQuals = ToFunction->getTypeQuals(); 2595 if (FromQuals != ToQuals) { 2596 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2597 return; 2598 } 2599 2600 // Unable to find a difference, so add no extra info. 2601 PDiag << ft_default; 2602 } 2603 2604 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2605 /// for equality of their argument types. Caller has already checked that 2606 /// they have same number of arguments. If the parameters are different, 2607 /// ArgPos will have the parameter index of the first different parameter. 2608 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2609 const FunctionProtoType *NewType, 2610 unsigned *ArgPos) { 2611 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2612 N = NewType->param_type_begin(), 2613 E = OldType->param_type_end(); 2614 O && (O != E); ++O, ++N) { 2615 if (!Context.hasSameType(O->getUnqualifiedType(), 2616 N->getUnqualifiedType())) { 2617 if (ArgPos) 2618 *ArgPos = O - OldType->param_type_begin(); 2619 return false; 2620 } 2621 } 2622 return true; 2623 } 2624 2625 /// CheckPointerConversion - Check the pointer conversion from the 2626 /// expression From to the type ToType. This routine checks for 2627 /// ambiguous or inaccessible derived-to-base pointer 2628 /// conversions for which IsPointerConversion has already returned 2629 /// true. It returns true and produces a diagnostic if there was an 2630 /// error, or returns false otherwise. 2631 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2632 CastKind &Kind, 2633 CXXCastPath& BasePath, 2634 bool IgnoreBaseAccess) { 2635 QualType FromType = From->getType(); 2636 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2637 2638 Kind = CK_BitCast; 2639 2640 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2641 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2642 Expr::NPCK_ZeroExpression) { 2643 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2644 DiagRuntimeBehavior(From->getExprLoc(), From, 2645 PDiag(diag::warn_impcast_bool_to_null_pointer) 2646 << ToType << From->getSourceRange()); 2647 else if (!isUnevaluatedContext()) 2648 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2649 << ToType << From->getSourceRange(); 2650 } 2651 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2652 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2653 QualType FromPointeeType = FromPtrType->getPointeeType(), 2654 ToPointeeType = ToPtrType->getPointeeType(); 2655 2656 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2657 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2658 // We must have a derived-to-base conversion. Check an 2659 // ambiguous or inaccessible conversion. 2660 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2661 From->getExprLoc(), 2662 From->getSourceRange(), &BasePath, 2663 IgnoreBaseAccess)) 2664 return true; 2665 2666 // The conversion was successful. 2667 Kind = CK_DerivedToBase; 2668 } 2669 } 2670 } else if (const ObjCObjectPointerType *ToPtrType = 2671 ToType->getAs<ObjCObjectPointerType>()) { 2672 if (const ObjCObjectPointerType *FromPtrType = 2673 FromType->getAs<ObjCObjectPointerType>()) { 2674 // Objective-C++ conversions are always okay. 2675 // FIXME: We should have a different class of conversions for the 2676 // Objective-C++ implicit conversions. 2677 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2678 return false; 2679 } else if (FromType->isBlockPointerType()) { 2680 Kind = CK_BlockPointerToObjCPointerCast; 2681 } else { 2682 Kind = CK_CPointerToObjCPointerCast; 2683 } 2684 } else if (ToType->isBlockPointerType()) { 2685 if (!FromType->isBlockPointerType()) 2686 Kind = CK_AnyPointerToBlockPointerCast; 2687 } 2688 2689 // We shouldn't fall into this case unless it's valid for other 2690 // reasons. 2691 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2692 Kind = CK_NullToPointer; 2693 2694 return false; 2695 } 2696 2697 /// IsMemberPointerConversion - Determines whether the conversion of the 2698 /// expression From, which has the (possibly adjusted) type FromType, can be 2699 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2700 /// If so, returns true and places the converted type (that might differ from 2701 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2702 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2703 QualType ToType, 2704 bool InOverloadResolution, 2705 QualType &ConvertedType) { 2706 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2707 if (!ToTypePtr) 2708 return false; 2709 2710 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2711 if (From->isNullPointerConstant(Context, 2712 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2713 : Expr::NPC_ValueDependentIsNull)) { 2714 ConvertedType = ToType; 2715 return true; 2716 } 2717 2718 // Otherwise, both types have to be member pointers. 2719 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2720 if (!FromTypePtr) 2721 return false; 2722 2723 // A pointer to member of B can be converted to a pointer to member of D, 2724 // where D is derived from B (C++ 4.11p2). 2725 QualType FromClass(FromTypePtr->getClass(), 0); 2726 QualType ToClass(ToTypePtr->getClass(), 0); 2727 2728 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2729 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2730 IsDerivedFrom(ToClass, FromClass)) { 2731 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2732 ToClass.getTypePtr()); 2733 return true; 2734 } 2735 2736 return false; 2737 } 2738 2739 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2740 /// expression From to the type ToType. This routine checks for ambiguous or 2741 /// virtual or inaccessible base-to-derived member pointer conversions 2742 /// for which IsMemberPointerConversion has already returned true. It returns 2743 /// true and produces a diagnostic if there was an error, or returns false 2744 /// otherwise. 2745 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2746 CastKind &Kind, 2747 CXXCastPath &BasePath, 2748 bool IgnoreBaseAccess) { 2749 QualType FromType = From->getType(); 2750 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2751 if (!FromPtrType) { 2752 // This must be a null pointer to member pointer conversion 2753 assert(From->isNullPointerConstant(Context, 2754 Expr::NPC_ValueDependentIsNull) && 2755 "Expr must be null pointer constant!"); 2756 Kind = CK_NullToMemberPointer; 2757 return false; 2758 } 2759 2760 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2761 assert(ToPtrType && "No member pointer cast has a target type " 2762 "that is not a member pointer."); 2763 2764 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2765 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2766 2767 // FIXME: What about dependent types? 2768 assert(FromClass->isRecordType() && "Pointer into non-class."); 2769 assert(ToClass->isRecordType() && "Pointer into non-class."); 2770 2771 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2772 /*DetectVirtual=*/true); 2773 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2774 assert(DerivationOkay && 2775 "Should not have been called if derivation isn't OK."); 2776 (void)DerivationOkay; 2777 2778 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2779 getUnqualifiedType())) { 2780 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2781 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2782 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2783 return true; 2784 } 2785 2786 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2787 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2788 << FromClass << ToClass << QualType(VBase, 0) 2789 << From->getSourceRange(); 2790 return true; 2791 } 2792 2793 if (!IgnoreBaseAccess) 2794 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2795 Paths.front(), 2796 diag::err_downcast_from_inaccessible_base); 2797 2798 // Must be a base to derived member conversion. 2799 BuildBasePathArray(Paths, BasePath); 2800 Kind = CK_BaseToDerivedMemberPointer; 2801 return false; 2802 } 2803 2804 /// Determine whether the lifetime conversion between the two given 2805 /// qualifiers sets is nontrivial. 2806 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 2807 Qualifiers ToQuals) { 2808 // Converting anything to const __unsafe_unretained is trivial. 2809 if (ToQuals.hasConst() && 2810 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 2811 return false; 2812 2813 return true; 2814 } 2815 2816 /// IsQualificationConversion - Determines whether the conversion from 2817 /// an rvalue of type FromType to ToType is a qualification conversion 2818 /// (C++ 4.4). 2819 /// 2820 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2821 /// when the qualification conversion involves a change in the Objective-C 2822 /// object lifetime. 2823 bool 2824 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2825 bool CStyle, bool &ObjCLifetimeConversion) { 2826 FromType = Context.getCanonicalType(FromType); 2827 ToType = Context.getCanonicalType(ToType); 2828 ObjCLifetimeConversion = false; 2829 2830 // If FromType and ToType are the same type, this is not a 2831 // qualification conversion. 2832 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2833 return false; 2834 2835 // (C++ 4.4p4): 2836 // A conversion can add cv-qualifiers at levels other than the first 2837 // in multi-level pointers, subject to the following rules: [...] 2838 bool PreviousToQualsIncludeConst = true; 2839 bool UnwrappedAnyPointer = false; 2840 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2841 // Within each iteration of the loop, we check the qualifiers to 2842 // determine if this still looks like a qualification 2843 // conversion. Then, if all is well, we unwrap one more level of 2844 // pointers or pointers-to-members and do it all again 2845 // until there are no more pointers or pointers-to-members left to 2846 // unwrap. 2847 UnwrappedAnyPointer = true; 2848 2849 Qualifiers FromQuals = FromType.getQualifiers(); 2850 Qualifiers ToQuals = ToType.getQualifiers(); 2851 2852 // Objective-C ARC: 2853 // Check Objective-C lifetime conversions. 2854 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2855 UnwrappedAnyPointer) { 2856 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2857 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 2858 ObjCLifetimeConversion = true; 2859 FromQuals.removeObjCLifetime(); 2860 ToQuals.removeObjCLifetime(); 2861 } else { 2862 // Qualification conversions cannot cast between different 2863 // Objective-C lifetime qualifiers. 2864 return false; 2865 } 2866 } 2867 2868 // Allow addition/removal of GC attributes but not changing GC attributes. 2869 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2870 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2871 FromQuals.removeObjCGCAttr(); 2872 ToQuals.removeObjCGCAttr(); 2873 } 2874 2875 // -- for every j > 0, if const is in cv 1,j then const is in cv 2876 // 2,j, and similarly for volatile. 2877 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2878 return false; 2879 2880 // -- if the cv 1,j and cv 2,j are different, then const is in 2881 // every cv for 0 < k < j. 2882 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2883 && !PreviousToQualsIncludeConst) 2884 return false; 2885 2886 // Keep track of whether all prior cv-qualifiers in the "to" type 2887 // include const. 2888 PreviousToQualsIncludeConst 2889 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2890 } 2891 2892 // We are left with FromType and ToType being the pointee types 2893 // after unwrapping the original FromType and ToType the same number 2894 // of types. If we unwrapped any pointers, and if FromType and 2895 // ToType have the same unqualified type (since we checked 2896 // qualifiers above), then this is a qualification conversion. 2897 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2898 } 2899 2900 /// \brief - Determine whether this is a conversion from a scalar type to an 2901 /// atomic type. 2902 /// 2903 /// If successful, updates \c SCS's second and third steps in the conversion 2904 /// sequence to finish the conversion. 2905 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2906 bool InOverloadResolution, 2907 StandardConversionSequence &SCS, 2908 bool CStyle) { 2909 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2910 if (!ToAtomic) 2911 return false; 2912 2913 StandardConversionSequence InnerSCS; 2914 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2915 InOverloadResolution, InnerSCS, 2916 CStyle, /*AllowObjCWritebackConversion=*/false)) 2917 return false; 2918 2919 SCS.Second = InnerSCS.Second; 2920 SCS.setToType(1, InnerSCS.getToType(1)); 2921 SCS.Third = InnerSCS.Third; 2922 SCS.QualificationIncludesObjCLifetime 2923 = InnerSCS.QualificationIncludesObjCLifetime; 2924 SCS.setToType(2, InnerSCS.getToType(2)); 2925 return true; 2926 } 2927 2928 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2929 CXXConstructorDecl *Constructor, 2930 QualType Type) { 2931 const FunctionProtoType *CtorType = 2932 Constructor->getType()->getAs<FunctionProtoType>(); 2933 if (CtorType->getNumParams() > 0) { 2934 QualType FirstArg = CtorType->getParamType(0); 2935 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2936 return true; 2937 } 2938 return false; 2939 } 2940 2941 static OverloadingResult 2942 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2943 CXXRecordDecl *To, 2944 UserDefinedConversionSequence &User, 2945 OverloadCandidateSet &CandidateSet, 2946 bool AllowExplicit) { 2947 DeclContext::lookup_result R = S.LookupConstructors(To); 2948 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 2949 Con != ConEnd; ++Con) { 2950 NamedDecl *D = *Con; 2951 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2952 2953 // Find the constructor (which may be a template). 2954 CXXConstructorDecl *Constructor = 0; 2955 FunctionTemplateDecl *ConstructorTmpl 2956 = dyn_cast<FunctionTemplateDecl>(D); 2957 if (ConstructorTmpl) 2958 Constructor 2959 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2960 else 2961 Constructor = cast<CXXConstructorDecl>(D); 2962 2963 bool Usable = !Constructor->isInvalidDecl() && 2964 S.isInitListConstructor(Constructor) && 2965 (AllowExplicit || !Constructor->isExplicit()); 2966 if (Usable) { 2967 // If the first argument is (a reference to) the target type, 2968 // suppress conversions. 2969 bool SuppressUserConversions = 2970 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2971 if (ConstructorTmpl) 2972 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2973 /*ExplicitArgs*/ 0, 2974 From, CandidateSet, 2975 SuppressUserConversions); 2976 else 2977 S.AddOverloadCandidate(Constructor, FoundDecl, 2978 From, CandidateSet, 2979 SuppressUserConversions); 2980 } 2981 } 2982 2983 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2984 2985 OverloadCandidateSet::iterator Best; 2986 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2987 case OR_Success: { 2988 // Record the standard conversion we used and the conversion function. 2989 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2990 QualType ThisType = Constructor->getThisType(S.Context); 2991 // Initializer lists don't have conversions as such. 2992 User.Before.setAsIdentityConversion(); 2993 User.HadMultipleCandidates = HadMultipleCandidates; 2994 User.ConversionFunction = Constructor; 2995 User.FoundConversionFunction = Best->FoundDecl; 2996 User.After.setAsIdentityConversion(); 2997 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2998 User.After.setAllToTypes(ToType); 2999 return OR_Success; 3000 } 3001 3002 case OR_No_Viable_Function: 3003 return OR_No_Viable_Function; 3004 case OR_Deleted: 3005 return OR_Deleted; 3006 case OR_Ambiguous: 3007 return OR_Ambiguous; 3008 } 3009 3010 llvm_unreachable("Invalid OverloadResult!"); 3011 } 3012 3013 /// Determines whether there is a user-defined conversion sequence 3014 /// (C++ [over.ics.user]) that converts expression From to the type 3015 /// ToType. If such a conversion exists, User will contain the 3016 /// user-defined conversion sequence that performs such a conversion 3017 /// and this routine will return true. Otherwise, this routine returns 3018 /// false and User is unspecified. 3019 /// 3020 /// \param AllowExplicit true if the conversion should consider C++0x 3021 /// "explicit" conversion functions as well as non-explicit conversion 3022 /// functions (C++0x [class.conv.fct]p2). 3023 /// 3024 /// \param AllowObjCConversionOnExplicit true if the conversion should 3025 /// allow an extra Objective-C pointer conversion on uses of explicit 3026 /// constructors. Requires \c AllowExplicit to also be set. 3027 static OverloadingResult 3028 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3029 UserDefinedConversionSequence &User, 3030 OverloadCandidateSet &CandidateSet, 3031 bool AllowExplicit, 3032 bool AllowObjCConversionOnExplicit) { 3033 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3034 3035 // Whether we will only visit constructors. 3036 bool ConstructorsOnly = false; 3037 3038 // If the type we are conversion to is a class type, enumerate its 3039 // constructors. 3040 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3041 // C++ [over.match.ctor]p1: 3042 // When objects of class type are direct-initialized (8.5), or 3043 // copy-initialized from an expression of the same or a 3044 // derived class type (8.5), overload resolution selects the 3045 // constructor. [...] For copy-initialization, the candidate 3046 // functions are all the converting constructors (12.3.1) of 3047 // that class. The argument list is the expression-list within 3048 // the parentheses of the initializer. 3049 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3050 (From->getType()->getAs<RecordType>() && 3051 S.IsDerivedFrom(From->getType(), ToType))) 3052 ConstructorsOnly = true; 3053 3054 S.RequireCompleteType(From->getExprLoc(), ToType, 0); 3055 // RequireCompleteType may have returned true due to some invalid decl 3056 // during template instantiation, but ToType may be complete enough now 3057 // to try to recover. 3058 if (ToType->isIncompleteType()) { 3059 // We're not going to find any constructors. 3060 } else if (CXXRecordDecl *ToRecordDecl 3061 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3062 3063 Expr **Args = &From; 3064 unsigned NumArgs = 1; 3065 bool ListInitializing = false; 3066 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3067 // But first, see if there is an init-list-constructor that will work. 3068 OverloadingResult Result = IsInitializerListConstructorConversion( 3069 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3070 if (Result != OR_No_Viable_Function) 3071 return Result; 3072 // Never mind. 3073 CandidateSet.clear(); 3074 3075 // If we're list-initializing, we pass the individual elements as 3076 // arguments, not the entire list. 3077 Args = InitList->getInits(); 3078 NumArgs = InitList->getNumInits(); 3079 ListInitializing = true; 3080 } 3081 3082 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3083 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3084 Con != ConEnd; ++Con) { 3085 NamedDecl *D = *Con; 3086 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3087 3088 // Find the constructor (which may be a template). 3089 CXXConstructorDecl *Constructor = 0; 3090 FunctionTemplateDecl *ConstructorTmpl 3091 = dyn_cast<FunctionTemplateDecl>(D); 3092 if (ConstructorTmpl) 3093 Constructor 3094 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3095 else 3096 Constructor = cast<CXXConstructorDecl>(D); 3097 3098 bool Usable = !Constructor->isInvalidDecl(); 3099 if (ListInitializing) 3100 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3101 else 3102 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3103 if (Usable) { 3104 bool SuppressUserConversions = !ConstructorsOnly; 3105 if (SuppressUserConversions && ListInitializing) { 3106 SuppressUserConversions = false; 3107 if (NumArgs == 1) { 3108 // If the first argument is (a reference to) the target type, 3109 // suppress conversions. 3110 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3111 S.Context, Constructor, ToType); 3112 } 3113 } 3114 if (ConstructorTmpl) 3115 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3116 /*ExplicitArgs*/ 0, 3117 llvm::makeArrayRef(Args, NumArgs), 3118 CandidateSet, SuppressUserConversions); 3119 else 3120 // Allow one user-defined conversion when user specifies a 3121 // From->ToType conversion via an static cast (c-style, etc). 3122 S.AddOverloadCandidate(Constructor, FoundDecl, 3123 llvm::makeArrayRef(Args, NumArgs), 3124 CandidateSet, SuppressUserConversions); 3125 } 3126 } 3127 } 3128 } 3129 3130 // Enumerate conversion functions, if we're allowed to. 3131 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3132 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3133 // No conversion functions from incomplete types. 3134 } else if (const RecordType *FromRecordType 3135 = From->getType()->getAs<RecordType>()) { 3136 if (CXXRecordDecl *FromRecordDecl 3137 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3138 // Add all of the conversion functions as candidates. 3139 std::pair<CXXRecordDecl::conversion_iterator, 3140 CXXRecordDecl::conversion_iterator> 3141 Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3142 for (CXXRecordDecl::conversion_iterator 3143 I = Conversions.first, E = Conversions.second; I != E; ++I) { 3144 DeclAccessPair FoundDecl = I.getPair(); 3145 NamedDecl *D = FoundDecl.getDecl(); 3146 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3147 if (isa<UsingShadowDecl>(D)) 3148 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3149 3150 CXXConversionDecl *Conv; 3151 FunctionTemplateDecl *ConvTemplate; 3152 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3153 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3154 else 3155 Conv = cast<CXXConversionDecl>(D); 3156 3157 if (AllowExplicit || !Conv->isExplicit()) { 3158 if (ConvTemplate) 3159 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3160 ActingContext, From, ToType, 3161 CandidateSet, 3162 AllowObjCConversionOnExplicit); 3163 else 3164 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3165 From, ToType, CandidateSet, 3166 AllowObjCConversionOnExplicit); 3167 } 3168 } 3169 } 3170 } 3171 3172 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3173 3174 OverloadCandidateSet::iterator Best; 3175 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3176 case OR_Success: 3177 // Record the standard conversion we used and the conversion function. 3178 if (CXXConstructorDecl *Constructor 3179 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3180 // C++ [over.ics.user]p1: 3181 // If the user-defined conversion is specified by a 3182 // constructor (12.3.1), the initial standard conversion 3183 // sequence converts the source type to the type required by 3184 // the argument of the constructor. 3185 // 3186 QualType ThisType = Constructor->getThisType(S.Context); 3187 if (isa<InitListExpr>(From)) { 3188 // Initializer lists don't have conversions as such. 3189 User.Before.setAsIdentityConversion(); 3190 } else { 3191 if (Best->Conversions[0].isEllipsis()) 3192 User.EllipsisConversion = true; 3193 else { 3194 User.Before = Best->Conversions[0].Standard; 3195 User.EllipsisConversion = false; 3196 } 3197 } 3198 User.HadMultipleCandidates = HadMultipleCandidates; 3199 User.ConversionFunction = Constructor; 3200 User.FoundConversionFunction = Best->FoundDecl; 3201 User.After.setAsIdentityConversion(); 3202 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3203 User.After.setAllToTypes(ToType); 3204 return OR_Success; 3205 } 3206 if (CXXConversionDecl *Conversion 3207 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3208 // C++ [over.ics.user]p1: 3209 // 3210 // [...] If the user-defined conversion is specified by a 3211 // conversion function (12.3.2), the initial standard 3212 // conversion sequence converts the source type to the 3213 // implicit object parameter of the conversion function. 3214 User.Before = Best->Conversions[0].Standard; 3215 User.HadMultipleCandidates = HadMultipleCandidates; 3216 User.ConversionFunction = Conversion; 3217 User.FoundConversionFunction = Best->FoundDecl; 3218 User.EllipsisConversion = false; 3219 3220 // C++ [over.ics.user]p2: 3221 // The second standard conversion sequence converts the 3222 // result of the user-defined conversion to the target type 3223 // for the sequence. Since an implicit conversion sequence 3224 // is an initialization, the special rules for 3225 // initialization by user-defined conversion apply when 3226 // selecting the best user-defined conversion for a 3227 // user-defined conversion sequence (see 13.3.3 and 3228 // 13.3.3.1). 3229 User.After = Best->FinalConversion; 3230 return OR_Success; 3231 } 3232 llvm_unreachable("Not a constructor or conversion function?"); 3233 3234 case OR_No_Viable_Function: 3235 return OR_No_Viable_Function; 3236 case OR_Deleted: 3237 // No conversion here! We're done. 3238 return OR_Deleted; 3239 3240 case OR_Ambiguous: 3241 return OR_Ambiguous; 3242 } 3243 3244 llvm_unreachable("Invalid OverloadResult!"); 3245 } 3246 3247 bool 3248 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3249 ImplicitConversionSequence ICS; 3250 OverloadCandidateSet CandidateSet(From->getExprLoc()); 3251 OverloadingResult OvResult = 3252 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3253 CandidateSet, false, false); 3254 if (OvResult == OR_Ambiguous) 3255 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3256 << From->getType() << ToType << From->getSourceRange(); 3257 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3258 if (!RequireCompleteType(From->getLocStart(), ToType, 3259 diag::err_typecheck_nonviable_condition_incomplete, 3260 From->getType(), From->getSourceRange())) 3261 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3262 << From->getType() << From->getSourceRange() << ToType; 3263 } else 3264 return false; 3265 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3266 return true; 3267 } 3268 3269 /// \brief Compare the user-defined conversion functions or constructors 3270 /// of two user-defined conversion sequences to determine whether any ordering 3271 /// is possible. 3272 static ImplicitConversionSequence::CompareKind 3273 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3274 FunctionDecl *Function2) { 3275 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3276 return ImplicitConversionSequence::Indistinguishable; 3277 3278 // Objective-C++: 3279 // If both conversion functions are implicitly-declared conversions from 3280 // a lambda closure type to a function pointer and a block pointer, 3281 // respectively, always prefer the conversion to a function pointer, 3282 // because the function pointer is more lightweight and is more likely 3283 // to keep code working. 3284 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1); 3285 if (!Conv1) 3286 return ImplicitConversionSequence::Indistinguishable; 3287 3288 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3289 if (!Conv2) 3290 return ImplicitConversionSequence::Indistinguishable; 3291 3292 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3293 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3294 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3295 if (Block1 != Block2) 3296 return Block1 ? ImplicitConversionSequence::Worse 3297 : ImplicitConversionSequence::Better; 3298 } 3299 3300 return ImplicitConversionSequence::Indistinguishable; 3301 } 3302 3303 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3304 const ImplicitConversionSequence &ICS) { 3305 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3306 (ICS.isUserDefined() && 3307 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3308 } 3309 3310 /// CompareImplicitConversionSequences - Compare two implicit 3311 /// conversion sequences to determine whether one is better than the 3312 /// other or if they are indistinguishable (C++ 13.3.3.2). 3313 static ImplicitConversionSequence::CompareKind 3314 CompareImplicitConversionSequences(Sema &S, 3315 const ImplicitConversionSequence& ICS1, 3316 const ImplicitConversionSequence& ICS2) 3317 { 3318 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3319 // conversion sequences (as defined in 13.3.3.1) 3320 // -- a standard conversion sequence (13.3.3.1.1) is a better 3321 // conversion sequence than a user-defined conversion sequence or 3322 // an ellipsis conversion sequence, and 3323 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3324 // conversion sequence than an ellipsis conversion sequence 3325 // (13.3.3.1.3). 3326 // 3327 // C++0x [over.best.ics]p10: 3328 // For the purpose of ranking implicit conversion sequences as 3329 // described in 13.3.3.2, the ambiguous conversion sequence is 3330 // treated as a user-defined sequence that is indistinguishable 3331 // from any other user-defined conversion sequence. 3332 3333 // String literal to 'char *' conversion has been deprecated in C++03. It has 3334 // been removed from C++11. We still accept this conversion, if it happens at 3335 // the best viable function. Otherwise, this conversion is considered worse 3336 // than ellipsis conversion. Consider this as an extension; this is not in the 3337 // standard. For example: 3338 // 3339 // int &f(...); // #1 3340 // void f(char*); // #2 3341 // void g() { int &r = f("foo"); } 3342 // 3343 // In C++03, we pick #2 as the best viable function. 3344 // In C++11, we pick #1 as the best viable function, because ellipsis 3345 // conversion is better than string-literal to char* conversion (since there 3346 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3347 // convert arguments, #2 would be the best viable function in C++11. 3348 // If the best viable function has this conversion, a warning will be issued 3349 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3350 3351 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3352 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3353 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3354 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3355 ? ImplicitConversionSequence::Worse 3356 : ImplicitConversionSequence::Better; 3357 3358 if (ICS1.getKindRank() < ICS2.getKindRank()) 3359 return ImplicitConversionSequence::Better; 3360 if (ICS2.getKindRank() < ICS1.getKindRank()) 3361 return ImplicitConversionSequence::Worse; 3362 3363 // The following checks require both conversion sequences to be of 3364 // the same kind. 3365 if (ICS1.getKind() != ICS2.getKind()) 3366 return ImplicitConversionSequence::Indistinguishable; 3367 3368 ImplicitConversionSequence::CompareKind Result = 3369 ImplicitConversionSequence::Indistinguishable; 3370 3371 // Two implicit conversion sequences of the same form are 3372 // indistinguishable conversion sequences unless one of the 3373 // following rules apply: (C++ 13.3.3.2p3): 3374 if (ICS1.isStandard()) 3375 Result = CompareStandardConversionSequences(S, 3376 ICS1.Standard, ICS2.Standard); 3377 else if (ICS1.isUserDefined()) { 3378 // User-defined conversion sequence U1 is a better conversion 3379 // sequence than another user-defined conversion sequence U2 if 3380 // they contain the same user-defined conversion function or 3381 // constructor and if the second standard conversion sequence of 3382 // U1 is better than the second standard conversion sequence of 3383 // U2 (C++ 13.3.3.2p3). 3384 if (ICS1.UserDefined.ConversionFunction == 3385 ICS2.UserDefined.ConversionFunction) 3386 Result = CompareStandardConversionSequences(S, 3387 ICS1.UserDefined.After, 3388 ICS2.UserDefined.After); 3389 else 3390 Result = compareConversionFunctions(S, 3391 ICS1.UserDefined.ConversionFunction, 3392 ICS2.UserDefined.ConversionFunction); 3393 } 3394 3395 // List-initialization sequence L1 is a better conversion sequence than 3396 // list-initialization sequence L2 if L1 converts to std::initializer_list<X> 3397 // for some X and L2 does not. 3398 if (Result == ImplicitConversionSequence::Indistinguishable && 3399 !ICS1.isBad()) { 3400 if (ICS1.isStdInitializerListElement() && 3401 !ICS2.isStdInitializerListElement()) 3402 return ImplicitConversionSequence::Better; 3403 if (!ICS1.isStdInitializerListElement() && 3404 ICS2.isStdInitializerListElement()) 3405 return ImplicitConversionSequence::Worse; 3406 } 3407 3408 return Result; 3409 } 3410 3411 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3412 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3413 Qualifiers Quals; 3414 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3415 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3416 } 3417 3418 return Context.hasSameUnqualifiedType(T1, T2); 3419 } 3420 3421 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3422 // determine if one is a proper subset of the other. 3423 static ImplicitConversionSequence::CompareKind 3424 compareStandardConversionSubsets(ASTContext &Context, 3425 const StandardConversionSequence& SCS1, 3426 const StandardConversionSequence& SCS2) { 3427 ImplicitConversionSequence::CompareKind Result 3428 = ImplicitConversionSequence::Indistinguishable; 3429 3430 // the identity conversion sequence is considered to be a subsequence of 3431 // any non-identity conversion sequence 3432 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3433 return ImplicitConversionSequence::Better; 3434 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3435 return ImplicitConversionSequence::Worse; 3436 3437 if (SCS1.Second != SCS2.Second) { 3438 if (SCS1.Second == ICK_Identity) 3439 Result = ImplicitConversionSequence::Better; 3440 else if (SCS2.Second == ICK_Identity) 3441 Result = ImplicitConversionSequence::Worse; 3442 else 3443 return ImplicitConversionSequence::Indistinguishable; 3444 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3445 return ImplicitConversionSequence::Indistinguishable; 3446 3447 if (SCS1.Third == SCS2.Third) { 3448 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3449 : ImplicitConversionSequence::Indistinguishable; 3450 } 3451 3452 if (SCS1.Third == ICK_Identity) 3453 return Result == ImplicitConversionSequence::Worse 3454 ? ImplicitConversionSequence::Indistinguishable 3455 : ImplicitConversionSequence::Better; 3456 3457 if (SCS2.Third == ICK_Identity) 3458 return Result == ImplicitConversionSequence::Better 3459 ? ImplicitConversionSequence::Indistinguishable 3460 : ImplicitConversionSequence::Worse; 3461 3462 return ImplicitConversionSequence::Indistinguishable; 3463 } 3464 3465 /// \brief Determine whether one of the given reference bindings is better 3466 /// than the other based on what kind of bindings they are. 3467 static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3468 const StandardConversionSequence &SCS2) { 3469 // C++0x [over.ics.rank]p3b4: 3470 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3471 // implicit object parameter of a non-static member function declared 3472 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3473 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3474 // lvalue reference to a function lvalue and S2 binds an rvalue 3475 // reference*. 3476 // 3477 // FIXME: Rvalue references. We're going rogue with the above edits, 3478 // because the semantics in the current C++0x working paper (N3225 at the 3479 // time of this writing) break the standard definition of std::forward 3480 // and std::reference_wrapper when dealing with references to functions. 3481 // Proposed wording changes submitted to CWG for consideration. 3482 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3483 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3484 return false; 3485 3486 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3487 SCS2.IsLvalueReference) || 3488 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3489 !SCS2.IsLvalueReference); 3490 } 3491 3492 /// CompareStandardConversionSequences - Compare two standard 3493 /// conversion sequences to determine whether one is better than the 3494 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3495 static ImplicitConversionSequence::CompareKind 3496 CompareStandardConversionSequences(Sema &S, 3497 const StandardConversionSequence& SCS1, 3498 const StandardConversionSequence& SCS2) 3499 { 3500 // Standard conversion sequence S1 is a better conversion sequence 3501 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3502 3503 // -- S1 is a proper subsequence of S2 (comparing the conversion 3504 // sequences in the canonical form defined by 13.3.3.1.1, 3505 // excluding any Lvalue Transformation; the identity conversion 3506 // sequence is considered to be a subsequence of any 3507 // non-identity conversion sequence) or, if not that, 3508 if (ImplicitConversionSequence::CompareKind CK 3509 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3510 return CK; 3511 3512 // -- the rank of S1 is better than the rank of S2 (by the rules 3513 // defined below), or, if not that, 3514 ImplicitConversionRank Rank1 = SCS1.getRank(); 3515 ImplicitConversionRank Rank2 = SCS2.getRank(); 3516 if (Rank1 < Rank2) 3517 return ImplicitConversionSequence::Better; 3518 else if (Rank2 < Rank1) 3519 return ImplicitConversionSequence::Worse; 3520 3521 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3522 // are indistinguishable unless one of the following rules 3523 // applies: 3524 3525 // A conversion that is not a conversion of a pointer, or 3526 // pointer to member, to bool is better than another conversion 3527 // that is such a conversion. 3528 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3529 return SCS2.isPointerConversionToBool() 3530 ? ImplicitConversionSequence::Better 3531 : ImplicitConversionSequence::Worse; 3532 3533 // C++ [over.ics.rank]p4b2: 3534 // 3535 // If class B is derived directly or indirectly from class A, 3536 // conversion of B* to A* is better than conversion of B* to 3537 // void*, and conversion of A* to void* is better than conversion 3538 // of B* to void*. 3539 bool SCS1ConvertsToVoid 3540 = SCS1.isPointerConversionToVoidPointer(S.Context); 3541 bool SCS2ConvertsToVoid 3542 = SCS2.isPointerConversionToVoidPointer(S.Context); 3543 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3544 // Exactly one of the conversion sequences is a conversion to 3545 // a void pointer; it's the worse conversion. 3546 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3547 : ImplicitConversionSequence::Worse; 3548 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3549 // Neither conversion sequence converts to a void pointer; compare 3550 // their derived-to-base conversions. 3551 if (ImplicitConversionSequence::CompareKind DerivedCK 3552 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3553 return DerivedCK; 3554 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3555 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3556 // Both conversion sequences are conversions to void 3557 // pointers. Compare the source types to determine if there's an 3558 // inheritance relationship in their sources. 3559 QualType FromType1 = SCS1.getFromType(); 3560 QualType FromType2 = SCS2.getFromType(); 3561 3562 // Adjust the types we're converting from via the array-to-pointer 3563 // conversion, if we need to. 3564 if (SCS1.First == ICK_Array_To_Pointer) 3565 FromType1 = S.Context.getArrayDecayedType(FromType1); 3566 if (SCS2.First == ICK_Array_To_Pointer) 3567 FromType2 = S.Context.getArrayDecayedType(FromType2); 3568 3569 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3570 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3571 3572 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3573 return ImplicitConversionSequence::Better; 3574 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3575 return ImplicitConversionSequence::Worse; 3576 3577 // Objective-C++: If one interface is more specific than the 3578 // other, it is the better one. 3579 const ObjCObjectPointerType* FromObjCPtr1 3580 = FromType1->getAs<ObjCObjectPointerType>(); 3581 const ObjCObjectPointerType* FromObjCPtr2 3582 = FromType2->getAs<ObjCObjectPointerType>(); 3583 if (FromObjCPtr1 && FromObjCPtr2) { 3584 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3585 FromObjCPtr2); 3586 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3587 FromObjCPtr1); 3588 if (AssignLeft != AssignRight) { 3589 return AssignLeft? ImplicitConversionSequence::Better 3590 : ImplicitConversionSequence::Worse; 3591 } 3592 } 3593 } 3594 3595 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3596 // bullet 3). 3597 if (ImplicitConversionSequence::CompareKind QualCK 3598 = CompareQualificationConversions(S, SCS1, SCS2)) 3599 return QualCK; 3600 3601 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3602 // Check for a better reference binding based on the kind of bindings. 3603 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3604 return ImplicitConversionSequence::Better; 3605 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3606 return ImplicitConversionSequence::Worse; 3607 3608 // C++ [over.ics.rank]p3b4: 3609 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3610 // which the references refer are the same type except for 3611 // top-level cv-qualifiers, and the type to which the reference 3612 // initialized by S2 refers is more cv-qualified than the type 3613 // to which the reference initialized by S1 refers. 3614 QualType T1 = SCS1.getToType(2); 3615 QualType T2 = SCS2.getToType(2); 3616 T1 = S.Context.getCanonicalType(T1); 3617 T2 = S.Context.getCanonicalType(T2); 3618 Qualifiers T1Quals, T2Quals; 3619 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3620 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3621 if (UnqualT1 == UnqualT2) { 3622 // Objective-C++ ARC: If the references refer to objects with different 3623 // lifetimes, prefer bindings that don't change lifetime. 3624 if (SCS1.ObjCLifetimeConversionBinding != 3625 SCS2.ObjCLifetimeConversionBinding) { 3626 return SCS1.ObjCLifetimeConversionBinding 3627 ? ImplicitConversionSequence::Worse 3628 : ImplicitConversionSequence::Better; 3629 } 3630 3631 // If the type is an array type, promote the element qualifiers to the 3632 // type for comparison. 3633 if (isa<ArrayType>(T1) && T1Quals) 3634 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3635 if (isa<ArrayType>(T2) && T2Quals) 3636 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3637 if (T2.isMoreQualifiedThan(T1)) 3638 return ImplicitConversionSequence::Better; 3639 else if (T1.isMoreQualifiedThan(T2)) 3640 return ImplicitConversionSequence::Worse; 3641 } 3642 } 3643 3644 // In Microsoft mode, prefer an integral conversion to a 3645 // floating-to-integral conversion if the integral conversion 3646 // is between types of the same size. 3647 // For example: 3648 // void f(float); 3649 // void f(int); 3650 // int main { 3651 // long a; 3652 // f(a); 3653 // } 3654 // Here, MSVC will call f(int) instead of generating a compile error 3655 // as clang will do in standard mode. 3656 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3657 SCS2.Second == ICK_Floating_Integral && 3658 S.Context.getTypeSize(SCS1.getFromType()) == 3659 S.Context.getTypeSize(SCS1.getToType(2))) 3660 return ImplicitConversionSequence::Better; 3661 3662 return ImplicitConversionSequence::Indistinguishable; 3663 } 3664 3665 /// CompareQualificationConversions - Compares two standard conversion 3666 /// sequences to determine whether they can be ranked based on their 3667 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3668 ImplicitConversionSequence::CompareKind 3669 CompareQualificationConversions(Sema &S, 3670 const StandardConversionSequence& SCS1, 3671 const StandardConversionSequence& SCS2) { 3672 // C++ 13.3.3.2p3: 3673 // -- S1 and S2 differ only in their qualification conversion and 3674 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3675 // cv-qualification signature of type T1 is a proper subset of 3676 // the cv-qualification signature of type T2, and S1 is not the 3677 // deprecated string literal array-to-pointer conversion (4.2). 3678 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3679 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3680 return ImplicitConversionSequence::Indistinguishable; 3681 3682 // FIXME: the example in the standard doesn't use a qualification 3683 // conversion (!) 3684 QualType T1 = SCS1.getToType(2); 3685 QualType T2 = SCS2.getToType(2); 3686 T1 = S.Context.getCanonicalType(T1); 3687 T2 = S.Context.getCanonicalType(T2); 3688 Qualifiers T1Quals, T2Quals; 3689 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3690 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3691 3692 // If the types are the same, we won't learn anything by unwrapped 3693 // them. 3694 if (UnqualT1 == UnqualT2) 3695 return ImplicitConversionSequence::Indistinguishable; 3696 3697 // If the type is an array type, promote the element qualifiers to the type 3698 // for comparison. 3699 if (isa<ArrayType>(T1) && T1Quals) 3700 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3701 if (isa<ArrayType>(T2) && T2Quals) 3702 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3703 3704 ImplicitConversionSequence::CompareKind Result 3705 = ImplicitConversionSequence::Indistinguishable; 3706 3707 // Objective-C++ ARC: 3708 // Prefer qualification conversions not involving a change in lifetime 3709 // to qualification conversions that do not change lifetime. 3710 if (SCS1.QualificationIncludesObjCLifetime != 3711 SCS2.QualificationIncludesObjCLifetime) { 3712 Result = SCS1.QualificationIncludesObjCLifetime 3713 ? ImplicitConversionSequence::Worse 3714 : ImplicitConversionSequence::Better; 3715 } 3716 3717 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3718 // Within each iteration of the loop, we check the qualifiers to 3719 // determine if this still looks like a qualification 3720 // conversion. Then, if all is well, we unwrap one more level of 3721 // pointers or pointers-to-members and do it all again 3722 // until there are no more pointers or pointers-to-members left 3723 // to unwrap. This essentially mimics what 3724 // IsQualificationConversion does, but here we're checking for a 3725 // strict subset of qualifiers. 3726 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3727 // The qualifiers are the same, so this doesn't tell us anything 3728 // about how the sequences rank. 3729 ; 3730 else if (T2.isMoreQualifiedThan(T1)) { 3731 // T1 has fewer qualifiers, so it could be the better sequence. 3732 if (Result == ImplicitConversionSequence::Worse) 3733 // Neither has qualifiers that are a subset of the other's 3734 // qualifiers. 3735 return ImplicitConversionSequence::Indistinguishable; 3736 3737 Result = ImplicitConversionSequence::Better; 3738 } else if (T1.isMoreQualifiedThan(T2)) { 3739 // T2 has fewer qualifiers, so it could be the better sequence. 3740 if (Result == ImplicitConversionSequence::Better) 3741 // Neither has qualifiers that are a subset of the other's 3742 // qualifiers. 3743 return ImplicitConversionSequence::Indistinguishable; 3744 3745 Result = ImplicitConversionSequence::Worse; 3746 } else { 3747 // Qualifiers are disjoint. 3748 return ImplicitConversionSequence::Indistinguishable; 3749 } 3750 3751 // If the types after this point are equivalent, we're done. 3752 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3753 break; 3754 } 3755 3756 // Check that the winning standard conversion sequence isn't using 3757 // the deprecated string literal array to pointer conversion. 3758 switch (Result) { 3759 case ImplicitConversionSequence::Better: 3760 if (SCS1.DeprecatedStringLiteralToCharPtr) 3761 Result = ImplicitConversionSequence::Indistinguishable; 3762 break; 3763 3764 case ImplicitConversionSequence::Indistinguishable: 3765 break; 3766 3767 case ImplicitConversionSequence::Worse: 3768 if (SCS2.DeprecatedStringLiteralToCharPtr) 3769 Result = ImplicitConversionSequence::Indistinguishable; 3770 break; 3771 } 3772 3773 return Result; 3774 } 3775 3776 /// CompareDerivedToBaseConversions - Compares two standard conversion 3777 /// sequences to determine whether they can be ranked based on their 3778 /// various kinds of derived-to-base conversions (C++ 3779 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3780 /// conversions between Objective-C interface types. 3781 ImplicitConversionSequence::CompareKind 3782 CompareDerivedToBaseConversions(Sema &S, 3783 const StandardConversionSequence& SCS1, 3784 const StandardConversionSequence& SCS2) { 3785 QualType FromType1 = SCS1.getFromType(); 3786 QualType ToType1 = SCS1.getToType(1); 3787 QualType FromType2 = SCS2.getFromType(); 3788 QualType ToType2 = SCS2.getToType(1); 3789 3790 // Adjust the types we're converting from via the array-to-pointer 3791 // conversion, if we need to. 3792 if (SCS1.First == ICK_Array_To_Pointer) 3793 FromType1 = S.Context.getArrayDecayedType(FromType1); 3794 if (SCS2.First == ICK_Array_To_Pointer) 3795 FromType2 = S.Context.getArrayDecayedType(FromType2); 3796 3797 // Canonicalize all of the types. 3798 FromType1 = S.Context.getCanonicalType(FromType1); 3799 ToType1 = S.Context.getCanonicalType(ToType1); 3800 FromType2 = S.Context.getCanonicalType(FromType2); 3801 ToType2 = S.Context.getCanonicalType(ToType2); 3802 3803 // C++ [over.ics.rank]p4b3: 3804 // 3805 // If class B is derived directly or indirectly from class A and 3806 // class C is derived directly or indirectly from B, 3807 // 3808 // Compare based on pointer conversions. 3809 if (SCS1.Second == ICK_Pointer_Conversion && 3810 SCS2.Second == ICK_Pointer_Conversion && 3811 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3812 FromType1->isPointerType() && FromType2->isPointerType() && 3813 ToType1->isPointerType() && ToType2->isPointerType()) { 3814 QualType FromPointee1 3815 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3816 QualType ToPointee1 3817 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3818 QualType FromPointee2 3819 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3820 QualType ToPointee2 3821 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3822 3823 // -- conversion of C* to B* is better than conversion of C* to A*, 3824 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3825 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3826 return ImplicitConversionSequence::Better; 3827 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3828 return ImplicitConversionSequence::Worse; 3829 } 3830 3831 // -- conversion of B* to A* is better than conversion of C* to A*, 3832 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3833 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3834 return ImplicitConversionSequence::Better; 3835 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3836 return ImplicitConversionSequence::Worse; 3837 } 3838 } else if (SCS1.Second == ICK_Pointer_Conversion && 3839 SCS2.Second == ICK_Pointer_Conversion) { 3840 const ObjCObjectPointerType *FromPtr1 3841 = FromType1->getAs<ObjCObjectPointerType>(); 3842 const ObjCObjectPointerType *FromPtr2 3843 = FromType2->getAs<ObjCObjectPointerType>(); 3844 const ObjCObjectPointerType *ToPtr1 3845 = ToType1->getAs<ObjCObjectPointerType>(); 3846 const ObjCObjectPointerType *ToPtr2 3847 = ToType2->getAs<ObjCObjectPointerType>(); 3848 3849 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3850 // Apply the same conversion ranking rules for Objective-C pointer types 3851 // that we do for C++ pointers to class types. However, we employ the 3852 // Objective-C pseudo-subtyping relationship used for assignment of 3853 // Objective-C pointer types. 3854 bool FromAssignLeft 3855 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3856 bool FromAssignRight 3857 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3858 bool ToAssignLeft 3859 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3860 bool ToAssignRight 3861 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3862 3863 // A conversion to an a non-id object pointer type or qualified 'id' 3864 // type is better than a conversion to 'id'. 3865 if (ToPtr1->isObjCIdType() && 3866 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3867 return ImplicitConversionSequence::Worse; 3868 if (ToPtr2->isObjCIdType() && 3869 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3870 return ImplicitConversionSequence::Better; 3871 3872 // A conversion to a non-id object pointer type is better than a 3873 // conversion to a qualified 'id' type 3874 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3875 return ImplicitConversionSequence::Worse; 3876 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3877 return ImplicitConversionSequence::Better; 3878 3879 // A conversion to an a non-Class object pointer type or qualified 'Class' 3880 // type is better than a conversion to 'Class'. 3881 if (ToPtr1->isObjCClassType() && 3882 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3883 return ImplicitConversionSequence::Worse; 3884 if (ToPtr2->isObjCClassType() && 3885 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3886 return ImplicitConversionSequence::Better; 3887 3888 // A conversion to a non-Class object pointer type is better than a 3889 // conversion to a qualified 'Class' type. 3890 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3891 return ImplicitConversionSequence::Worse; 3892 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3893 return ImplicitConversionSequence::Better; 3894 3895 // -- "conversion of C* to B* is better than conversion of C* to A*," 3896 if (S.Context.hasSameType(FromType1, FromType2) && 3897 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3898 (ToAssignLeft != ToAssignRight)) 3899 return ToAssignLeft? ImplicitConversionSequence::Worse 3900 : ImplicitConversionSequence::Better; 3901 3902 // -- "conversion of B* to A* is better than conversion of C* to A*," 3903 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3904 (FromAssignLeft != FromAssignRight)) 3905 return FromAssignLeft? ImplicitConversionSequence::Better 3906 : ImplicitConversionSequence::Worse; 3907 } 3908 } 3909 3910 // Ranking of member-pointer types. 3911 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3912 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3913 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3914 const MemberPointerType * FromMemPointer1 = 3915 FromType1->getAs<MemberPointerType>(); 3916 const MemberPointerType * ToMemPointer1 = 3917 ToType1->getAs<MemberPointerType>(); 3918 const MemberPointerType * FromMemPointer2 = 3919 FromType2->getAs<MemberPointerType>(); 3920 const MemberPointerType * ToMemPointer2 = 3921 ToType2->getAs<MemberPointerType>(); 3922 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3923 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3924 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3925 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3926 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3927 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3928 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3929 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3930 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3931 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3932 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3933 return ImplicitConversionSequence::Worse; 3934 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3935 return ImplicitConversionSequence::Better; 3936 } 3937 // conversion of B::* to C::* is better than conversion of A::* to C::* 3938 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3939 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3940 return ImplicitConversionSequence::Better; 3941 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3942 return ImplicitConversionSequence::Worse; 3943 } 3944 } 3945 3946 if (SCS1.Second == ICK_Derived_To_Base) { 3947 // -- conversion of C to B is better than conversion of C to A, 3948 // -- binding of an expression of type C to a reference of type 3949 // B& is better than binding an expression of type C to a 3950 // reference of type A&, 3951 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3952 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3953 if (S.IsDerivedFrom(ToType1, ToType2)) 3954 return ImplicitConversionSequence::Better; 3955 else if (S.IsDerivedFrom(ToType2, ToType1)) 3956 return ImplicitConversionSequence::Worse; 3957 } 3958 3959 // -- conversion of B to A is better than conversion of C to A. 3960 // -- binding of an expression of type B to a reference of type 3961 // A& is better than binding an expression of type C to a 3962 // reference of type A&, 3963 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3964 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3965 if (S.IsDerivedFrom(FromType2, FromType1)) 3966 return ImplicitConversionSequence::Better; 3967 else if (S.IsDerivedFrom(FromType1, FromType2)) 3968 return ImplicitConversionSequence::Worse; 3969 } 3970 } 3971 3972 return ImplicitConversionSequence::Indistinguishable; 3973 } 3974 3975 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 3976 /// C++ class. 3977 static bool isTypeValid(QualType T) { 3978 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 3979 return !Record->isInvalidDecl(); 3980 3981 return true; 3982 } 3983 3984 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 3985 /// determine whether they are reference-related, 3986 /// reference-compatible, reference-compatible with added 3987 /// qualification, or incompatible, for use in C++ initialization by 3988 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3989 /// type, and the first type (T1) is the pointee type of the reference 3990 /// type being initialized. 3991 Sema::ReferenceCompareResult 3992 Sema::CompareReferenceRelationship(SourceLocation Loc, 3993 QualType OrigT1, QualType OrigT2, 3994 bool &DerivedToBase, 3995 bool &ObjCConversion, 3996 bool &ObjCLifetimeConversion) { 3997 assert(!OrigT1->isReferenceType() && 3998 "T1 must be the pointee type of the reference type"); 3999 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4000 4001 QualType T1 = Context.getCanonicalType(OrigT1); 4002 QualType T2 = Context.getCanonicalType(OrigT2); 4003 Qualifiers T1Quals, T2Quals; 4004 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4005 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4006 4007 // C++ [dcl.init.ref]p4: 4008 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4009 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4010 // T1 is a base class of T2. 4011 DerivedToBase = false; 4012 ObjCConversion = false; 4013 ObjCLifetimeConversion = false; 4014 if (UnqualT1 == UnqualT2) { 4015 // Nothing to do. 4016 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 4017 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4018 IsDerivedFrom(UnqualT2, UnqualT1)) 4019 DerivedToBase = true; 4020 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4021 UnqualT2->isObjCObjectOrInterfaceType() && 4022 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4023 ObjCConversion = true; 4024 else 4025 return Ref_Incompatible; 4026 4027 // At this point, we know that T1 and T2 are reference-related (at 4028 // least). 4029 4030 // If the type is an array type, promote the element qualifiers to the type 4031 // for comparison. 4032 if (isa<ArrayType>(T1) && T1Quals) 4033 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4034 if (isa<ArrayType>(T2) && T2Quals) 4035 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4036 4037 // C++ [dcl.init.ref]p4: 4038 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4039 // reference-related to T2 and cv1 is the same cv-qualification 4040 // as, or greater cv-qualification than, cv2. For purposes of 4041 // overload resolution, cases for which cv1 is greater 4042 // cv-qualification than cv2 are identified as 4043 // reference-compatible with added qualification (see 13.3.3.2). 4044 // 4045 // Note that we also require equivalence of Objective-C GC and address-space 4046 // qualifiers when performing these computations, so that e.g., an int in 4047 // address space 1 is not reference-compatible with an int in address 4048 // space 2. 4049 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4050 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4051 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4052 ObjCLifetimeConversion = true; 4053 4054 T1Quals.removeObjCLifetime(); 4055 T2Quals.removeObjCLifetime(); 4056 } 4057 4058 if (T1Quals == T2Quals) 4059 return Ref_Compatible; 4060 else if (T1Quals.compatiblyIncludes(T2Quals)) 4061 return Ref_Compatible_With_Added_Qualification; 4062 else 4063 return Ref_Related; 4064 } 4065 4066 /// \brief Look for a user-defined conversion to an value reference-compatible 4067 /// with DeclType. Return true if something definite is found. 4068 static bool 4069 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4070 QualType DeclType, SourceLocation DeclLoc, 4071 Expr *Init, QualType T2, bool AllowRvalues, 4072 bool AllowExplicit) { 4073 assert(T2->isRecordType() && "Can only find conversions of record types."); 4074 CXXRecordDecl *T2RecordDecl 4075 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4076 4077 OverloadCandidateSet CandidateSet(DeclLoc); 4078 std::pair<CXXRecordDecl::conversion_iterator, 4079 CXXRecordDecl::conversion_iterator> 4080 Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4081 for (CXXRecordDecl::conversion_iterator 4082 I = Conversions.first, E = Conversions.second; I != E; ++I) { 4083 NamedDecl *D = *I; 4084 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4085 if (isa<UsingShadowDecl>(D)) 4086 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4087 4088 FunctionTemplateDecl *ConvTemplate 4089 = dyn_cast<FunctionTemplateDecl>(D); 4090 CXXConversionDecl *Conv; 4091 if (ConvTemplate) 4092 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4093 else 4094 Conv = cast<CXXConversionDecl>(D); 4095 4096 // If this is an explicit conversion, and we're not allowed to consider 4097 // explicit conversions, skip it. 4098 if (!AllowExplicit && Conv->isExplicit()) 4099 continue; 4100 4101 if (AllowRvalues) { 4102 bool DerivedToBase = false; 4103 bool ObjCConversion = false; 4104 bool ObjCLifetimeConversion = false; 4105 4106 // If we are initializing an rvalue reference, don't permit conversion 4107 // functions that return lvalues. 4108 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4109 const ReferenceType *RefType 4110 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4111 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4112 continue; 4113 } 4114 4115 if (!ConvTemplate && 4116 S.CompareReferenceRelationship( 4117 DeclLoc, 4118 Conv->getConversionType().getNonReferenceType() 4119 .getUnqualifiedType(), 4120 DeclType.getNonReferenceType().getUnqualifiedType(), 4121 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4122 Sema::Ref_Incompatible) 4123 continue; 4124 } else { 4125 // If the conversion function doesn't return a reference type, 4126 // it can't be considered for this conversion. An rvalue reference 4127 // is only acceptable if its referencee is a function type. 4128 4129 const ReferenceType *RefType = 4130 Conv->getConversionType()->getAs<ReferenceType>(); 4131 if (!RefType || 4132 (!RefType->isLValueReferenceType() && 4133 !RefType->getPointeeType()->isFunctionType())) 4134 continue; 4135 } 4136 4137 if (ConvTemplate) 4138 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4139 Init, DeclType, CandidateSet, 4140 /*AllowObjCConversionOnExplicit=*/false); 4141 else 4142 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4143 DeclType, CandidateSet, 4144 /*AllowObjCConversionOnExplicit=*/false); 4145 } 4146 4147 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4148 4149 OverloadCandidateSet::iterator Best; 4150 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4151 case OR_Success: 4152 // C++ [over.ics.ref]p1: 4153 // 4154 // [...] If the parameter binds directly to the result of 4155 // applying a conversion function to the argument 4156 // expression, the implicit conversion sequence is a 4157 // user-defined conversion sequence (13.3.3.1.2), with the 4158 // second standard conversion sequence either an identity 4159 // conversion or, if the conversion function returns an 4160 // entity of a type that is a derived class of the parameter 4161 // type, a derived-to-base Conversion. 4162 if (!Best->FinalConversion.DirectBinding) 4163 return false; 4164 4165 ICS.setUserDefined(); 4166 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4167 ICS.UserDefined.After = Best->FinalConversion; 4168 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4169 ICS.UserDefined.ConversionFunction = Best->Function; 4170 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4171 ICS.UserDefined.EllipsisConversion = false; 4172 assert(ICS.UserDefined.After.ReferenceBinding && 4173 ICS.UserDefined.After.DirectBinding && 4174 "Expected a direct reference binding!"); 4175 return true; 4176 4177 case OR_Ambiguous: 4178 ICS.setAmbiguous(); 4179 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4180 Cand != CandidateSet.end(); ++Cand) 4181 if (Cand->Viable) 4182 ICS.Ambiguous.addConversion(Cand->Function); 4183 return true; 4184 4185 case OR_No_Viable_Function: 4186 case OR_Deleted: 4187 // There was no suitable conversion, or we found a deleted 4188 // conversion; continue with other checks. 4189 return false; 4190 } 4191 4192 llvm_unreachable("Invalid OverloadResult!"); 4193 } 4194 4195 /// \brief Compute an implicit conversion sequence for reference 4196 /// initialization. 4197 static ImplicitConversionSequence 4198 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4199 SourceLocation DeclLoc, 4200 bool SuppressUserConversions, 4201 bool AllowExplicit) { 4202 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4203 4204 // Most paths end in a failed conversion. 4205 ImplicitConversionSequence ICS; 4206 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4207 4208 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4209 QualType T2 = Init->getType(); 4210 4211 // If the initializer is the address of an overloaded function, try 4212 // to resolve the overloaded function. If all goes well, T2 is the 4213 // type of the resulting function. 4214 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4215 DeclAccessPair Found; 4216 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4217 false, Found)) 4218 T2 = Fn->getType(); 4219 } 4220 4221 // Compute some basic properties of the types and the initializer. 4222 bool isRValRef = DeclType->isRValueReferenceType(); 4223 bool DerivedToBase = false; 4224 bool ObjCConversion = false; 4225 bool ObjCLifetimeConversion = false; 4226 Expr::Classification InitCategory = Init->Classify(S.Context); 4227 Sema::ReferenceCompareResult RefRelationship 4228 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4229 ObjCConversion, ObjCLifetimeConversion); 4230 4231 4232 // C++0x [dcl.init.ref]p5: 4233 // A reference to type "cv1 T1" is initialized by an expression 4234 // of type "cv2 T2" as follows: 4235 4236 // -- If reference is an lvalue reference and the initializer expression 4237 if (!isRValRef) { 4238 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4239 // reference-compatible with "cv2 T2," or 4240 // 4241 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4242 if (InitCategory.isLValue() && 4243 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4244 // C++ [over.ics.ref]p1: 4245 // When a parameter of reference type binds directly (8.5.3) 4246 // to an argument expression, the implicit conversion sequence 4247 // is the identity conversion, unless the argument expression 4248 // has a type that is a derived class of the parameter type, 4249 // in which case the implicit conversion sequence is a 4250 // derived-to-base Conversion (13.3.3.1). 4251 ICS.setStandard(); 4252 ICS.Standard.First = ICK_Identity; 4253 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4254 : ObjCConversion? ICK_Compatible_Conversion 4255 : ICK_Identity; 4256 ICS.Standard.Third = ICK_Identity; 4257 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4258 ICS.Standard.setToType(0, T2); 4259 ICS.Standard.setToType(1, T1); 4260 ICS.Standard.setToType(2, T1); 4261 ICS.Standard.ReferenceBinding = true; 4262 ICS.Standard.DirectBinding = true; 4263 ICS.Standard.IsLvalueReference = !isRValRef; 4264 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4265 ICS.Standard.BindsToRvalue = false; 4266 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4267 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4268 ICS.Standard.CopyConstructor = 0; 4269 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4270 4271 // Nothing more to do: the inaccessibility/ambiguity check for 4272 // derived-to-base conversions is suppressed when we're 4273 // computing the implicit conversion sequence (C++ 4274 // [over.best.ics]p2). 4275 return ICS; 4276 } 4277 4278 // -- has a class type (i.e., T2 is a class type), where T1 is 4279 // not reference-related to T2, and can be implicitly 4280 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4281 // is reference-compatible with "cv3 T3" 92) (this 4282 // conversion is selected by enumerating the applicable 4283 // conversion functions (13.3.1.6) and choosing the best 4284 // one through overload resolution (13.3)), 4285 if (!SuppressUserConversions && T2->isRecordType() && 4286 !S.RequireCompleteType(DeclLoc, T2, 0) && 4287 RefRelationship == Sema::Ref_Incompatible) { 4288 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4289 Init, T2, /*AllowRvalues=*/false, 4290 AllowExplicit)) 4291 return ICS; 4292 } 4293 } 4294 4295 // -- Otherwise, the reference shall be an lvalue reference to a 4296 // non-volatile const type (i.e., cv1 shall be const), or the reference 4297 // shall be an rvalue reference. 4298 // 4299 // We actually handle one oddity of C++ [over.ics.ref] at this 4300 // point, which is that, due to p2 (which short-circuits reference 4301 // binding by only attempting a simple conversion for non-direct 4302 // bindings) and p3's strange wording, we allow a const volatile 4303 // reference to bind to an rvalue. Hence the check for the presence 4304 // of "const" rather than checking for "const" being the only 4305 // qualifier. 4306 // This is also the point where rvalue references and lvalue inits no longer 4307 // go together. 4308 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4309 return ICS; 4310 4311 // -- If the initializer expression 4312 // 4313 // -- is an xvalue, class prvalue, array prvalue or function 4314 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4315 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4316 (InitCategory.isXValue() || 4317 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4318 (InitCategory.isLValue() && T2->isFunctionType()))) { 4319 ICS.setStandard(); 4320 ICS.Standard.First = ICK_Identity; 4321 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4322 : ObjCConversion? ICK_Compatible_Conversion 4323 : ICK_Identity; 4324 ICS.Standard.Third = ICK_Identity; 4325 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4326 ICS.Standard.setToType(0, T2); 4327 ICS.Standard.setToType(1, T1); 4328 ICS.Standard.setToType(2, T1); 4329 ICS.Standard.ReferenceBinding = true; 4330 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4331 // binding unless we're binding to a class prvalue. 4332 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4333 // allow the use of rvalue references in C++98/03 for the benefit of 4334 // standard library implementors; therefore, we need the xvalue check here. 4335 ICS.Standard.DirectBinding = 4336 S.getLangOpts().CPlusPlus11 || 4337 (InitCategory.isPRValue() && !T2->isRecordType()); 4338 ICS.Standard.IsLvalueReference = !isRValRef; 4339 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4340 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4341 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4342 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4343 ICS.Standard.CopyConstructor = 0; 4344 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4345 return ICS; 4346 } 4347 4348 // -- has a class type (i.e., T2 is a class type), where T1 is not 4349 // reference-related to T2, and can be implicitly converted to 4350 // an xvalue, class prvalue, or function lvalue of type 4351 // "cv3 T3", where "cv1 T1" is reference-compatible with 4352 // "cv3 T3", 4353 // 4354 // then the reference is bound to the value of the initializer 4355 // expression in the first case and to the result of the conversion 4356 // in the second case (or, in either case, to an appropriate base 4357 // class subobject). 4358 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4359 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4360 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4361 Init, T2, /*AllowRvalues=*/true, 4362 AllowExplicit)) { 4363 // In the second case, if the reference is an rvalue reference 4364 // and the second standard conversion sequence of the 4365 // user-defined conversion sequence includes an lvalue-to-rvalue 4366 // conversion, the program is ill-formed. 4367 if (ICS.isUserDefined() && isRValRef && 4368 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4369 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4370 4371 return ICS; 4372 } 4373 4374 // -- Otherwise, a temporary of type "cv1 T1" is created and 4375 // initialized from the initializer expression using the 4376 // rules for a non-reference copy initialization (8.5). The 4377 // reference is then bound to the temporary. If T1 is 4378 // reference-related to T2, cv1 must be the same 4379 // cv-qualification as, or greater cv-qualification than, 4380 // cv2; otherwise, the program is ill-formed. 4381 if (RefRelationship == Sema::Ref_Related) { 4382 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4383 // we would be reference-compatible or reference-compatible with 4384 // added qualification. But that wasn't the case, so the reference 4385 // initialization fails. 4386 // 4387 // Note that we only want to check address spaces and cvr-qualifiers here. 4388 // ObjC GC and lifetime qualifiers aren't important. 4389 Qualifiers T1Quals = T1.getQualifiers(); 4390 Qualifiers T2Quals = T2.getQualifiers(); 4391 T1Quals.removeObjCGCAttr(); 4392 T1Quals.removeObjCLifetime(); 4393 T2Quals.removeObjCGCAttr(); 4394 T2Quals.removeObjCLifetime(); 4395 if (!T1Quals.compatiblyIncludes(T2Quals)) 4396 return ICS; 4397 } 4398 4399 // If at least one of the types is a class type, the types are not 4400 // related, and we aren't allowed any user conversions, the 4401 // reference binding fails. This case is important for breaking 4402 // recursion, since TryImplicitConversion below will attempt to 4403 // create a temporary through the use of a copy constructor. 4404 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4405 (T1->isRecordType() || T2->isRecordType())) 4406 return ICS; 4407 4408 // If T1 is reference-related to T2 and the reference is an rvalue 4409 // reference, the initializer expression shall not be an lvalue. 4410 if (RefRelationship >= Sema::Ref_Related && 4411 isRValRef && Init->Classify(S.Context).isLValue()) 4412 return ICS; 4413 4414 // C++ [over.ics.ref]p2: 4415 // When a parameter of reference type is not bound directly to 4416 // an argument expression, the conversion sequence is the one 4417 // required to convert the argument expression to the 4418 // underlying type of the reference according to 4419 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4420 // to copy-initializing a temporary of the underlying type with 4421 // the argument expression. Any difference in top-level 4422 // cv-qualification is subsumed by the initialization itself 4423 // and does not constitute a conversion. 4424 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4425 /*AllowExplicit=*/false, 4426 /*InOverloadResolution=*/false, 4427 /*CStyle=*/false, 4428 /*AllowObjCWritebackConversion=*/false, 4429 /*AllowObjCConversionOnExplicit=*/false); 4430 4431 // Of course, that's still a reference binding. 4432 if (ICS.isStandard()) { 4433 ICS.Standard.ReferenceBinding = true; 4434 ICS.Standard.IsLvalueReference = !isRValRef; 4435 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4436 ICS.Standard.BindsToRvalue = true; 4437 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4438 ICS.Standard.ObjCLifetimeConversionBinding = false; 4439 } else if (ICS.isUserDefined()) { 4440 // Don't allow rvalue references to bind to lvalues. 4441 if (DeclType->isRValueReferenceType()) { 4442 if (const ReferenceType *RefType = 4443 ICS.UserDefined.ConversionFunction->getReturnType() 4444 ->getAs<LValueReferenceType>()) { 4445 if (!RefType->getPointeeType()->isFunctionType()) { 4446 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, 4447 DeclType); 4448 return ICS; 4449 } 4450 } 4451 } 4452 ICS.UserDefined.Before.setAsIdentityConversion(); 4453 ICS.UserDefined.After.ReferenceBinding = true; 4454 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4455 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType(); 4456 ICS.UserDefined.After.BindsToRvalue = true; 4457 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4458 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4459 } 4460 4461 return ICS; 4462 } 4463 4464 static ImplicitConversionSequence 4465 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4466 bool SuppressUserConversions, 4467 bool InOverloadResolution, 4468 bool AllowObjCWritebackConversion, 4469 bool AllowExplicit = false); 4470 4471 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4472 /// initializer list From. 4473 static ImplicitConversionSequence 4474 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4475 bool SuppressUserConversions, 4476 bool InOverloadResolution, 4477 bool AllowObjCWritebackConversion) { 4478 // C++11 [over.ics.list]p1: 4479 // When an argument is an initializer list, it is not an expression and 4480 // special rules apply for converting it to a parameter type. 4481 4482 ImplicitConversionSequence Result; 4483 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4484 4485 // We need a complete type for what follows. Incomplete types can never be 4486 // initialized from init lists. 4487 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4488 return Result; 4489 4490 // C++11 [over.ics.list]p2: 4491 // If the parameter type is std::initializer_list<X> or "array of X" and 4492 // all the elements can be implicitly converted to X, the implicit 4493 // conversion sequence is the worst conversion necessary to convert an 4494 // element of the list to X. 4495 bool toStdInitializerList = false; 4496 QualType X; 4497 if (ToType->isArrayType()) 4498 X = S.Context.getAsArrayType(ToType)->getElementType(); 4499 else 4500 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4501 if (!X.isNull()) { 4502 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4503 Expr *Init = From->getInit(i); 4504 ImplicitConversionSequence ICS = 4505 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4506 InOverloadResolution, 4507 AllowObjCWritebackConversion); 4508 // If a single element isn't convertible, fail. 4509 if (ICS.isBad()) { 4510 Result = ICS; 4511 break; 4512 } 4513 // Otherwise, look for the worst conversion. 4514 if (Result.isBad() || 4515 CompareImplicitConversionSequences(S, ICS, Result) == 4516 ImplicitConversionSequence::Worse) 4517 Result = ICS; 4518 } 4519 4520 // For an empty list, we won't have computed any conversion sequence. 4521 // Introduce the identity conversion sequence. 4522 if (From->getNumInits() == 0) { 4523 Result.setStandard(); 4524 Result.Standard.setAsIdentityConversion(); 4525 Result.Standard.setFromType(ToType); 4526 Result.Standard.setAllToTypes(ToType); 4527 } 4528 4529 Result.setStdInitializerListElement(toStdInitializerList); 4530 return Result; 4531 } 4532 4533 // C++11 [over.ics.list]p3: 4534 // Otherwise, if the parameter is a non-aggregate class X and overload 4535 // resolution chooses a single best constructor [...] the implicit 4536 // conversion sequence is a user-defined conversion sequence. If multiple 4537 // constructors are viable but none is better than the others, the 4538 // implicit conversion sequence is a user-defined conversion sequence. 4539 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4540 // This function can deal with initializer lists. 4541 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4542 /*AllowExplicit=*/false, 4543 InOverloadResolution, /*CStyle=*/false, 4544 AllowObjCWritebackConversion, 4545 /*AllowObjCConversionOnExplicit=*/false); 4546 } 4547 4548 // C++11 [over.ics.list]p4: 4549 // Otherwise, if the parameter has an aggregate type which can be 4550 // initialized from the initializer list [...] the implicit conversion 4551 // sequence is a user-defined conversion sequence. 4552 if (ToType->isAggregateType()) { 4553 // Type is an aggregate, argument is an init list. At this point it comes 4554 // down to checking whether the initialization works. 4555 // FIXME: Find out whether this parameter is consumed or not. 4556 InitializedEntity Entity = 4557 InitializedEntity::InitializeParameter(S.Context, ToType, 4558 /*Consumed=*/false); 4559 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) { 4560 Result.setUserDefined(); 4561 Result.UserDefined.Before.setAsIdentityConversion(); 4562 // Initializer lists don't have a type. 4563 Result.UserDefined.Before.setFromType(QualType()); 4564 Result.UserDefined.Before.setAllToTypes(QualType()); 4565 4566 Result.UserDefined.After.setAsIdentityConversion(); 4567 Result.UserDefined.After.setFromType(ToType); 4568 Result.UserDefined.After.setAllToTypes(ToType); 4569 Result.UserDefined.ConversionFunction = 0; 4570 } 4571 return Result; 4572 } 4573 4574 // C++11 [over.ics.list]p5: 4575 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4576 if (ToType->isReferenceType()) { 4577 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4578 // mention initializer lists in any way. So we go by what list- 4579 // initialization would do and try to extrapolate from that. 4580 4581 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4582 4583 // If the initializer list has a single element that is reference-related 4584 // to the parameter type, we initialize the reference from that. 4585 if (From->getNumInits() == 1) { 4586 Expr *Init = From->getInit(0); 4587 4588 QualType T2 = Init->getType(); 4589 4590 // If the initializer is the address of an overloaded function, try 4591 // to resolve the overloaded function. If all goes well, T2 is the 4592 // type of the resulting function. 4593 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4594 DeclAccessPair Found; 4595 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4596 Init, ToType, false, Found)) 4597 T2 = Fn->getType(); 4598 } 4599 4600 // Compute some basic properties of the types and the initializer. 4601 bool dummy1 = false; 4602 bool dummy2 = false; 4603 bool dummy3 = false; 4604 Sema::ReferenceCompareResult RefRelationship 4605 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4606 dummy2, dummy3); 4607 4608 if (RefRelationship >= Sema::Ref_Related) { 4609 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4610 SuppressUserConversions, 4611 /*AllowExplicit=*/false); 4612 } 4613 } 4614 4615 // Otherwise, we bind the reference to a temporary created from the 4616 // initializer list. 4617 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4618 InOverloadResolution, 4619 AllowObjCWritebackConversion); 4620 if (Result.isFailure()) 4621 return Result; 4622 assert(!Result.isEllipsis() && 4623 "Sub-initialization cannot result in ellipsis conversion."); 4624 4625 // Can we even bind to a temporary? 4626 if (ToType->isRValueReferenceType() || 4627 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4628 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4629 Result.UserDefined.After; 4630 SCS.ReferenceBinding = true; 4631 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4632 SCS.BindsToRvalue = true; 4633 SCS.BindsToFunctionLvalue = false; 4634 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4635 SCS.ObjCLifetimeConversionBinding = false; 4636 } else 4637 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4638 From, ToType); 4639 return Result; 4640 } 4641 4642 // C++11 [over.ics.list]p6: 4643 // Otherwise, if the parameter type is not a class: 4644 if (!ToType->isRecordType()) { 4645 // - if the initializer list has one element, the implicit conversion 4646 // sequence is the one required to convert the element to the 4647 // parameter type. 4648 unsigned NumInits = From->getNumInits(); 4649 if (NumInits == 1) 4650 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4651 SuppressUserConversions, 4652 InOverloadResolution, 4653 AllowObjCWritebackConversion); 4654 // - if the initializer list has no elements, the implicit conversion 4655 // sequence is the identity conversion. 4656 else if (NumInits == 0) { 4657 Result.setStandard(); 4658 Result.Standard.setAsIdentityConversion(); 4659 Result.Standard.setFromType(ToType); 4660 Result.Standard.setAllToTypes(ToType); 4661 } 4662 return Result; 4663 } 4664 4665 // C++11 [over.ics.list]p7: 4666 // In all cases other than those enumerated above, no conversion is possible 4667 return Result; 4668 } 4669 4670 /// TryCopyInitialization - Try to copy-initialize a value of type 4671 /// ToType from the expression From. Return the implicit conversion 4672 /// sequence required to pass this argument, which may be a bad 4673 /// conversion sequence (meaning that the argument cannot be passed to 4674 /// a parameter of this type). If @p SuppressUserConversions, then we 4675 /// do not permit any user-defined conversion sequences. 4676 static ImplicitConversionSequence 4677 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4678 bool SuppressUserConversions, 4679 bool InOverloadResolution, 4680 bool AllowObjCWritebackConversion, 4681 bool AllowExplicit) { 4682 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4683 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4684 InOverloadResolution,AllowObjCWritebackConversion); 4685 4686 if (ToType->isReferenceType()) 4687 return TryReferenceInit(S, From, ToType, 4688 /*FIXME:*/From->getLocStart(), 4689 SuppressUserConversions, 4690 AllowExplicit); 4691 4692 return TryImplicitConversion(S, From, ToType, 4693 SuppressUserConversions, 4694 /*AllowExplicit=*/false, 4695 InOverloadResolution, 4696 /*CStyle=*/false, 4697 AllowObjCWritebackConversion, 4698 /*AllowObjCConversionOnExplicit=*/false); 4699 } 4700 4701 static bool TryCopyInitialization(const CanQualType FromQTy, 4702 const CanQualType ToQTy, 4703 Sema &S, 4704 SourceLocation Loc, 4705 ExprValueKind FromVK) { 4706 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4707 ImplicitConversionSequence ICS = 4708 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4709 4710 return !ICS.isBad(); 4711 } 4712 4713 /// TryObjectArgumentInitialization - Try to initialize the object 4714 /// parameter of the given member function (@c Method) from the 4715 /// expression @p From. 4716 static ImplicitConversionSequence 4717 TryObjectArgumentInitialization(Sema &S, QualType FromType, 4718 Expr::Classification FromClassification, 4719 CXXMethodDecl *Method, 4720 CXXRecordDecl *ActingContext) { 4721 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4722 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4723 // const volatile object. 4724 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4725 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4726 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4727 4728 // Set up the conversion sequence as a "bad" conversion, to allow us 4729 // to exit early. 4730 ImplicitConversionSequence ICS; 4731 4732 // We need to have an object of class type. 4733 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4734 FromType = PT->getPointeeType(); 4735 4736 // When we had a pointer, it's implicitly dereferenced, so we 4737 // better have an lvalue. 4738 assert(FromClassification.isLValue()); 4739 } 4740 4741 assert(FromType->isRecordType()); 4742 4743 // C++0x [over.match.funcs]p4: 4744 // For non-static member functions, the type of the implicit object 4745 // parameter is 4746 // 4747 // - "lvalue reference to cv X" for functions declared without a 4748 // ref-qualifier or with the & ref-qualifier 4749 // - "rvalue reference to cv X" for functions declared with the && 4750 // ref-qualifier 4751 // 4752 // where X is the class of which the function is a member and cv is the 4753 // cv-qualification on the member function declaration. 4754 // 4755 // However, when finding an implicit conversion sequence for the argument, we 4756 // are not allowed to create temporaries or perform user-defined conversions 4757 // (C++ [over.match.funcs]p5). We perform a simplified version of 4758 // reference binding here, that allows class rvalues to bind to 4759 // non-constant references. 4760 4761 // First check the qualifiers. 4762 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4763 if (ImplicitParamType.getCVRQualifiers() 4764 != FromTypeCanon.getLocalCVRQualifiers() && 4765 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4766 ICS.setBad(BadConversionSequence::bad_qualifiers, 4767 FromType, ImplicitParamType); 4768 return ICS; 4769 } 4770 4771 // Check that we have either the same type or a derived type. It 4772 // affects the conversion rank. 4773 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4774 ImplicitConversionKind SecondKind; 4775 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4776 SecondKind = ICK_Identity; 4777 } else if (S.IsDerivedFrom(FromType, ClassType)) 4778 SecondKind = ICK_Derived_To_Base; 4779 else { 4780 ICS.setBad(BadConversionSequence::unrelated_class, 4781 FromType, ImplicitParamType); 4782 return ICS; 4783 } 4784 4785 // Check the ref-qualifier. 4786 switch (Method->getRefQualifier()) { 4787 case RQ_None: 4788 // Do nothing; we don't care about lvalueness or rvalueness. 4789 break; 4790 4791 case RQ_LValue: 4792 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4793 // non-const lvalue reference cannot bind to an rvalue 4794 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4795 ImplicitParamType); 4796 return ICS; 4797 } 4798 break; 4799 4800 case RQ_RValue: 4801 if (!FromClassification.isRValue()) { 4802 // rvalue reference cannot bind to an lvalue 4803 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4804 ImplicitParamType); 4805 return ICS; 4806 } 4807 break; 4808 } 4809 4810 // Success. Mark this as a reference binding. 4811 ICS.setStandard(); 4812 ICS.Standard.setAsIdentityConversion(); 4813 ICS.Standard.Second = SecondKind; 4814 ICS.Standard.setFromType(FromType); 4815 ICS.Standard.setAllToTypes(ImplicitParamType); 4816 ICS.Standard.ReferenceBinding = true; 4817 ICS.Standard.DirectBinding = true; 4818 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4819 ICS.Standard.BindsToFunctionLvalue = false; 4820 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4821 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4822 = (Method->getRefQualifier() == RQ_None); 4823 return ICS; 4824 } 4825 4826 /// PerformObjectArgumentInitialization - Perform initialization of 4827 /// the implicit object parameter for the given Method with the given 4828 /// expression. 4829 ExprResult 4830 Sema::PerformObjectArgumentInitialization(Expr *From, 4831 NestedNameSpecifier *Qualifier, 4832 NamedDecl *FoundDecl, 4833 CXXMethodDecl *Method) { 4834 QualType FromRecordType, DestType; 4835 QualType ImplicitParamRecordType = 4836 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4837 4838 Expr::Classification FromClassification; 4839 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4840 FromRecordType = PT->getPointeeType(); 4841 DestType = Method->getThisType(Context); 4842 FromClassification = Expr::Classification::makeSimpleLValue(); 4843 } else { 4844 FromRecordType = From->getType(); 4845 DestType = ImplicitParamRecordType; 4846 FromClassification = From->Classify(Context); 4847 } 4848 4849 // Note that we always use the true parent context when performing 4850 // the actual argument initialization. 4851 ImplicitConversionSequence ICS 4852 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification, 4853 Method, Method->getParent()); 4854 if (ICS.isBad()) { 4855 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4856 Qualifiers FromQs = FromRecordType.getQualifiers(); 4857 Qualifiers ToQs = DestType.getQualifiers(); 4858 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4859 if (CVR) { 4860 Diag(From->getLocStart(), 4861 diag::err_member_function_call_bad_cvr) 4862 << Method->getDeclName() << FromRecordType << (CVR - 1) 4863 << From->getSourceRange(); 4864 Diag(Method->getLocation(), diag::note_previous_decl) 4865 << Method->getDeclName(); 4866 return ExprError(); 4867 } 4868 } 4869 4870 return Diag(From->getLocStart(), 4871 diag::err_implicit_object_parameter_init) 4872 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4873 } 4874 4875 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4876 ExprResult FromRes = 4877 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4878 if (FromRes.isInvalid()) 4879 return ExprError(); 4880 From = FromRes.take(); 4881 } 4882 4883 if (!Context.hasSameType(From->getType(), DestType)) 4884 From = ImpCastExprToType(From, DestType, CK_NoOp, 4885 From->getValueKind()).take(); 4886 return Owned(From); 4887 } 4888 4889 /// TryContextuallyConvertToBool - Attempt to contextually convert the 4890 /// expression From to bool (C++0x [conv]p3). 4891 static ImplicitConversionSequence 4892 TryContextuallyConvertToBool(Sema &S, Expr *From) { 4893 return TryImplicitConversion(S, From, S.Context.BoolTy, 4894 /*SuppressUserConversions=*/false, 4895 /*AllowExplicit=*/true, 4896 /*InOverloadResolution=*/false, 4897 /*CStyle=*/false, 4898 /*AllowObjCWritebackConversion=*/false, 4899 /*AllowObjCConversionOnExplicit=*/false); 4900 } 4901 4902 /// PerformContextuallyConvertToBool - Perform a contextual conversion 4903 /// of the expression From to bool (C++0x [conv]p3). 4904 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4905 if (checkPlaceholderForOverload(*this, From)) 4906 return ExprError(); 4907 4908 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4909 if (!ICS.isBad()) 4910 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4911 4912 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4913 return Diag(From->getLocStart(), 4914 diag::err_typecheck_bool_condition) 4915 << From->getType() << From->getSourceRange(); 4916 return ExprError(); 4917 } 4918 4919 /// Check that the specified conversion is permitted in a converted constant 4920 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 4921 /// is acceptable. 4922 static bool CheckConvertedConstantConversions(Sema &S, 4923 StandardConversionSequence &SCS) { 4924 // Since we know that the target type is an integral or unscoped enumeration 4925 // type, most conversion kinds are impossible. All possible First and Third 4926 // conversions are fine. 4927 switch (SCS.Second) { 4928 case ICK_Identity: 4929 case ICK_Integral_Promotion: 4930 case ICK_Integral_Conversion: 4931 case ICK_Zero_Event_Conversion: 4932 return true; 4933 4934 case ICK_Boolean_Conversion: 4935 // Conversion from an integral or unscoped enumeration type to bool is 4936 // classified as ICK_Boolean_Conversion, but it's also an integral 4937 // conversion, so it's permitted in a converted constant expression. 4938 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4939 SCS.getToType(2)->isBooleanType(); 4940 4941 case ICK_Floating_Integral: 4942 case ICK_Complex_Real: 4943 return false; 4944 4945 case ICK_Lvalue_To_Rvalue: 4946 case ICK_Array_To_Pointer: 4947 case ICK_Function_To_Pointer: 4948 case ICK_NoReturn_Adjustment: 4949 case ICK_Qualification: 4950 case ICK_Compatible_Conversion: 4951 case ICK_Vector_Conversion: 4952 case ICK_Vector_Splat: 4953 case ICK_Derived_To_Base: 4954 case ICK_Pointer_Conversion: 4955 case ICK_Pointer_Member: 4956 case ICK_Block_Pointer_Conversion: 4957 case ICK_Writeback_Conversion: 4958 case ICK_Floating_Promotion: 4959 case ICK_Complex_Promotion: 4960 case ICK_Complex_Conversion: 4961 case ICK_Floating_Conversion: 4962 case ICK_TransparentUnionConversion: 4963 llvm_unreachable("unexpected second conversion kind"); 4964 4965 case ICK_Num_Conversion_Kinds: 4966 break; 4967 } 4968 4969 llvm_unreachable("unknown conversion kind"); 4970 } 4971 4972 /// CheckConvertedConstantExpression - Check that the expression From is a 4973 /// converted constant expression of type T, perform the conversion and produce 4974 /// the converted expression, per C++11 [expr.const]p3. 4975 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 4976 llvm::APSInt &Value, 4977 CCEKind CCE) { 4978 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11"); 4979 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 4980 4981 if (checkPlaceholderForOverload(*this, From)) 4982 return ExprError(); 4983 4984 // C++11 [expr.const]p3 with proposed wording fixes: 4985 // A converted constant expression of type T is a core constant expression, 4986 // implicitly converted to a prvalue of type T, where the converted 4987 // expression is a literal constant expression and the implicit conversion 4988 // sequence contains only user-defined conversions, lvalue-to-rvalue 4989 // conversions, integral promotions, and integral conversions other than 4990 // narrowing conversions. 4991 ImplicitConversionSequence ICS = 4992 TryImplicitConversion(From, T, 4993 /*SuppressUserConversions=*/false, 4994 /*AllowExplicit=*/false, 4995 /*InOverloadResolution=*/false, 4996 /*CStyle=*/false, 4997 /*AllowObjcWritebackConversion=*/false); 4998 StandardConversionSequence *SCS = 0; 4999 switch (ICS.getKind()) { 5000 case ImplicitConversionSequence::StandardConversion: 5001 if (!CheckConvertedConstantConversions(*this, ICS.Standard)) 5002 return Diag(From->getLocStart(), 5003 diag::err_typecheck_converted_constant_expression_disallowed) 5004 << From->getType() << From->getSourceRange() << T; 5005 SCS = &ICS.Standard; 5006 break; 5007 case ImplicitConversionSequence::UserDefinedConversion: 5008 // We are converting from class type to an integral or enumeration type, so 5009 // the Before sequence must be trivial. 5010 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After)) 5011 return Diag(From->getLocStart(), 5012 diag::err_typecheck_converted_constant_expression_disallowed) 5013 << From->getType() << From->getSourceRange() << T; 5014 SCS = &ICS.UserDefined.After; 5015 break; 5016 case ImplicitConversionSequence::AmbiguousConversion: 5017 case ImplicitConversionSequence::BadConversion: 5018 if (!DiagnoseMultipleUserDefinedConversion(From, T)) 5019 return Diag(From->getLocStart(), 5020 diag::err_typecheck_converted_constant_expression) 5021 << From->getType() << From->getSourceRange() << T; 5022 return ExprError(); 5023 5024 case ImplicitConversionSequence::EllipsisConversion: 5025 llvm_unreachable("ellipsis conversion in converted constant expression"); 5026 } 5027 5028 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting); 5029 if (Result.isInvalid()) 5030 return Result; 5031 5032 // Check for a narrowing implicit conversion. 5033 APValue PreNarrowingValue; 5034 QualType PreNarrowingType; 5035 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue, 5036 PreNarrowingType)) { 5037 case NK_Variable_Narrowing: 5038 // Implicit conversion to a narrower type, and the value is not a constant 5039 // expression. We'll diagnose this in a moment. 5040 case NK_Not_Narrowing: 5041 break; 5042 5043 case NK_Constant_Narrowing: 5044 Diag(From->getLocStart(), diag::ext_cce_narrowing) 5045 << CCE << /*Constant*/1 5046 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T; 5047 break; 5048 5049 case NK_Type_Narrowing: 5050 Diag(From->getLocStart(), diag::ext_cce_narrowing) 5051 << CCE << /*Constant*/0 << From->getType() << T; 5052 break; 5053 } 5054 5055 // Check the expression is a constant expression. 5056 SmallVector<PartialDiagnosticAt, 8> Notes; 5057 Expr::EvalResult Eval; 5058 Eval.Diag = &Notes; 5059 5060 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) { 5061 // The expression can't be folded, so we can't keep it at this position in 5062 // the AST. 5063 Result = ExprError(); 5064 } else { 5065 Value = Eval.Val.getInt(); 5066 5067 if (Notes.empty()) { 5068 // It's a constant expression. 5069 return Result; 5070 } 5071 } 5072 5073 // It's not a constant expression. Produce an appropriate diagnostic. 5074 if (Notes.size() == 1 && 5075 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5076 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5077 else { 5078 Diag(From->getLocStart(), diag::err_expr_not_cce) 5079 << CCE << From->getSourceRange(); 5080 for (unsigned I = 0; I < Notes.size(); ++I) 5081 Diag(Notes[I].first, Notes[I].second); 5082 } 5083 return Result; 5084 } 5085 5086 /// dropPointerConversions - If the given standard conversion sequence 5087 /// involves any pointer conversions, remove them. This may change 5088 /// the result type of the conversion sequence. 5089 static void dropPointerConversion(StandardConversionSequence &SCS) { 5090 if (SCS.Second == ICK_Pointer_Conversion) { 5091 SCS.Second = ICK_Identity; 5092 SCS.Third = ICK_Identity; 5093 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5094 } 5095 } 5096 5097 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5098 /// convert the expression From to an Objective-C pointer type. 5099 static ImplicitConversionSequence 5100 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5101 // Do an implicit conversion to 'id'. 5102 QualType Ty = S.Context.getObjCIdType(); 5103 ImplicitConversionSequence ICS 5104 = TryImplicitConversion(S, From, Ty, 5105 // FIXME: Are these flags correct? 5106 /*SuppressUserConversions=*/false, 5107 /*AllowExplicit=*/true, 5108 /*InOverloadResolution=*/false, 5109 /*CStyle=*/false, 5110 /*AllowObjCWritebackConversion=*/false, 5111 /*AllowObjCConversionOnExplicit=*/true); 5112 5113 // Strip off any final conversions to 'id'. 5114 switch (ICS.getKind()) { 5115 case ImplicitConversionSequence::BadConversion: 5116 case ImplicitConversionSequence::AmbiguousConversion: 5117 case ImplicitConversionSequence::EllipsisConversion: 5118 break; 5119 5120 case ImplicitConversionSequence::UserDefinedConversion: 5121 dropPointerConversion(ICS.UserDefined.After); 5122 break; 5123 5124 case ImplicitConversionSequence::StandardConversion: 5125 dropPointerConversion(ICS.Standard); 5126 break; 5127 } 5128 5129 return ICS; 5130 } 5131 5132 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5133 /// conversion of the expression From to an Objective-C pointer type. 5134 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5135 if (checkPlaceholderForOverload(*this, From)) 5136 return ExprError(); 5137 5138 QualType Ty = Context.getObjCIdType(); 5139 ImplicitConversionSequence ICS = 5140 TryContextuallyConvertToObjCPointer(*this, From); 5141 if (!ICS.isBad()) 5142 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5143 return ExprError(); 5144 } 5145 5146 /// Determine whether the provided type is an integral type, or an enumeration 5147 /// type of a permitted flavor. 5148 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5149 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5150 : T->isIntegralOrUnscopedEnumerationType(); 5151 } 5152 5153 static ExprResult 5154 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5155 Sema::ContextualImplicitConverter &Converter, 5156 QualType T, UnresolvedSetImpl &ViableConversions) { 5157 5158 if (Converter.Suppress) 5159 return ExprError(); 5160 5161 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5162 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5163 CXXConversionDecl *Conv = 5164 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5165 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5166 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5167 } 5168 return SemaRef.Owned(From); 5169 } 5170 5171 static bool 5172 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5173 Sema::ContextualImplicitConverter &Converter, 5174 QualType T, bool HadMultipleCandidates, 5175 UnresolvedSetImpl &ExplicitConversions) { 5176 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5177 DeclAccessPair Found = ExplicitConversions[0]; 5178 CXXConversionDecl *Conversion = 5179 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5180 5181 // The user probably meant to invoke the given explicit 5182 // conversion; use it. 5183 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5184 std::string TypeStr; 5185 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5186 5187 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5188 << FixItHint::CreateInsertion(From->getLocStart(), 5189 "static_cast<" + TypeStr + ">(") 5190 << FixItHint::CreateInsertion( 5191 SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")"); 5192 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5193 5194 // If we aren't in a SFINAE context, build a call to the 5195 // explicit conversion function. 5196 if (SemaRef.isSFINAEContext()) 5197 return true; 5198 5199 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5200 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5201 HadMultipleCandidates); 5202 if (Result.isInvalid()) 5203 return true; 5204 // Record usage of conversion in an implicit cast. 5205 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5206 CK_UserDefinedConversion, Result.get(), 0, 5207 Result.get()->getValueKind()); 5208 } 5209 return false; 5210 } 5211 5212 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5213 Sema::ContextualImplicitConverter &Converter, 5214 QualType T, bool HadMultipleCandidates, 5215 DeclAccessPair &Found) { 5216 CXXConversionDecl *Conversion = 5217 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5218 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5219 5220 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5221 if (!Converter.SuppressConversion) { 5222 if (SemaRef.isSFINAEContext()) 5223 return true; 5224 5225 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5226 << From->getSourceRange(); 5227 } 5228 5229 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5230 HadMultipleCandidates); 5231 if (Result.isInvalid()) 5232 return true; 5233 // Record usage of conversion in an implicit cast. 5234 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5235 CK_UserDefinedConversion, Result.get(), 0, 5236 Result.get()->getValueKind()); 5237 return false; 5238 } 5239 5240 static ExprResult finishContextualImplicitConversion( 5241 Sema &SemaRef, SourceLocation Loc, Expr *From, 5242 Sema::ContextualImplicitConverter &Converter) { 5243 if (!Converter.match(From->getType()) && !Converter.Suppress) 5244 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5245 << From->getSourceRange(); 5246 5247 return SemaRef.DefaultLvalueConversion(From); 5248 } 5249 5250 static void 5251 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5252 UnresolvedSetImpl &ViableConversions, 5253 OverloadCandidateSet &CandidateSet) { 5254 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5255 DeclAccessPair FoundDecl = ViableConversions[I]; 5256 NamedDecl *D = FoundDecl.getDecl(); 5257 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5258 if (isa<UsingShadowDecl>(D)) 5259 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5260 5261 CXXConversionDecl *Conv; 5262 FunctionTemplateDecl *ConvTemplate; 5263 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5264 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5265 else 5266 Conv = cast<CXXConversionDecl>(D); 5267 5268 if (ConvTemplate) 5269 SemaRef.AddTemplateConversionCandidate( 5270 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5271 /*AllowObjCConversionOnExplicit=*/false); 5272 else 5273 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5274 ToType, CandidateSet, 5275 /*AllowObjCConversionOnExplicit=*/false); 5276 } 5277 } 5278 5279 /// \brief Attempt to convert the given expression to a type which is accepted 5280 /// by the given converter. 5281 /// 5282 /// This routine will attempt to convert an expression of class type to a 5283 /// type accepted by the specified converter. In C++11 and before, the class 5284 /// must have a single non-explicit conversion function converting to a matching 5285 /// type. In C++1y, there can be multiple such conversion functions, but only 5286 /// one target type. 5287 /// 5288 /// \param Loc The source location of the construct that requires the 5289 /// conversion. 5290 /// 5291 /// \param From The expression we're converting from. 5292 /// 5293 /// \param Converter Used to control and diagnose the conversion process. 5294 /// 5295 /// \returns The expression, converted to an integral or enumeration type if 5296 /// successful. 5297 ExprResult Sema::PerformContextualImplicitConversion( 5298 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5299 // We can't perform any more checking for type-dependent expressions. 5300 if (From->isTypeDependent()) 5301 return Owned(From); 5302 5303 // Process placeholders immediately. 5304 if (From->hasPlaceholderType()) { 5305 ExprResult result = CheckPlaceholderExpr(From); 5306 if (result.isInvalid()) 5307 return result; 5308 From = result.take(); 5309 } 5310 5311 // If the expression already has a matching type, we're golden. 5312 QualType T = From->getType(); 5313 if (Converter.match(T)) 5314 return DefaultLvalueConversion(From); 5315 5316 // FIXME: Check for missing '()' if T is a function type? 5317 5318 // We can only perform contextual implicit conversions on objects of class 5319 // type. 5320 const RecordType *RecordTy = T->getAs<RecordType>(); 5321 if (!RecordTy || !getLangOpts().CPlusPlus) { 5322 if (!Converter.Suppress) 5323 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5324 return Owned(From); 5325 } 5326 5327 // We must have a complete class type. 5328 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5329 ContextualImplicitConverter &Converter; 5330 Expr *From; 5331 5332 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5333 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {} 5334 5335 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) { 5336 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5337 } 5338 } IncompleteDiagnoser(Converter, From); 5339 5340 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5341 return Owned(From); 5342 5343 // Look for a conversion to an integral or enumeration type. 5344 UnresolvedSet<4> 5345 ViableConversions; // These are *potentially* viable in C++1y. 5346 UnresolvedSet<4> ExplicitConversions; 5347 std::pair<CXXRecordDecl::conversion_iterator, 5348 CXXRecordDecl::conversion_iterator> Conversions = 5349 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5350 5351 bool HadMultipleCandidates = 5352 (std::distance(Conversions.first, Conversions.second) > 1); 5353 5354 // To check that there is only one target type, in C++1y: 5355 QualType ToType; 5356 bool HasUniqueTargetType = true; 5357 5358 // Collect explicit or viable (potentially in C++1y) conversions. 5359 for (CXXRecordDecl::conversion_iterator I = Conversions.first, 5360 E = Conversions.second; 5361 I != E; ++I) { 5362 NamedDecl *D = (*I)->getUnderlyingDecl(); 5363 CXXConversionDecl *Conversion; 5364 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5365 if (ConvTemplate) { 5366 if (getLangOpts().CPlusPlus1y) 5367 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5368 else 5369 continue; // C++11 does not consider conversion operator templates(?). 5370 } else 5371 Conversion = cast<CXXConversionDecl>(D); 5372 5373 assert((!ConvTemplate || getLangOpts().CPlusPlus1y) && 5374 "Conversion operator templates are considered potentially " 5375 "viable in C++1y"); 5376 5377 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5378 if (Converter.match(CurToType) || ConvTemplate) { 5379 5380 if (Conversion->isExplicit()) { 5381 // FIXME: For C++1y, do we need this restriction? 5382 // cf. diagnoseNoViableConversion() 5383 if (!ConvTemplate) 5384 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5385 } else { 5386 if (!ConvTemplate && getLangOpts().CPlusPlus1y) { 5387 if (ToType.isNull()) 5388 ToType = CurToType.getUnqualifiedType(); 5389 else if (HasUniqueTargetType && 5390 (CurToType.getUnqualifiedType() != ToType)) 5391 HasUniqueTargetType = false; 5392 } 5393 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5394 } 5395 } 5396 } 5397 5398 if (getLangOpts().CPlusPlus1y) { 5399 // C++1y [conv]p6: 5400 // ... An expression e of class type E appearing in such a context 5401 // is said to be contextually implicitly converted to a specified 5402 // type T and is well-formed if and only if e can be implicitly 5403 // converted to a type T that is determined as follows: E is searched 5404 // for conversion functions whose return type is cv T or reference to 5405 // cv T such that T is allowed by the context. There shall be 5406 // exactly one such T. 5407 5408 // If no unique T is found: 5409 if (ToType.isNull()) { 5410 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5411 HadMultipleCandidates, 5412 ExplicitConversions)) 5413 return ExprError(); 5414 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5415 } 5416 5417 // If more than one unique Ts are found: 5418 if (!HasUniqueTargetType) 5419 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5420 ViableConversions); 5421 5422 // If one unique T is found: 5423 // First, build a candidate set from the previously recorded 5424 // potentially viable conversions. 5425 OverloadCandidateSet CandidateSet(Loc); 5426 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5427 CandidateSet); 5428 5429 // Then, perform overload resolution over the candidate set. 5430 OverloadCandidateSet::iterator Best; 5431 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5432 case OR_Success: { 5433 // Apply this conversion. 5434 DeclAccessPair Found = 5435 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5436 if (recordConversion(*this, Loc, From, Converter, T, 5437 HadMultipleCandidates, Found)) 5438 return ExprError(); 5439 break; 5440 } 5441 case OR_Ambiguous: 5442 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5443 ViableConversions); 5444 case OR_No_Viable_Function: 5445 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5446 HadMultipleCandidates, 5447 ExplicitConversions)) 5448 return ExprError(); 5449 // fall through 'OR_Deleted' case. 5450 case OR_Deleted: 5451 // We'll complain below about a non-integral condition type. 5452 break; 5453 } 5454 } else { 5455 switch (ViableConversions.size()) { 5456 case 0: { 5457 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5458 HadMultipleCandidates, 5459 ExplicitConversions)) 5460 return ExprError(); 5461 5462 // We'll complain below about a non-integral condition type. 5463 break; 5464 } 5465 case 1: { 5466 // Apply this conversion. 5467 DeclAccessPair Found = ViableConversions[0]; 5468 if (recordConversion(*this, Loc, From, Converter, T, 5469 HadMultipleCandidates, Found)) 5470 return ExprError(); 5471 break; 5472 } 5473 default: 5474 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5475 ViableConversions); 5476 } 5477 } 5478 5479 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5480 } 5481 5482 /// AddOverloadCandidate - Adds the given function to the set of 5483 /// candidate functions, using the given function call arguments. If 5484 /// @p SuppressUserConversions, then don't allow user-defined 5485 /// conversions via constructors or conversion operators. 5486 /// 5487 /// \param PartialOverloading true if we are performing "partial" overloading 5488 /// based on an incomplete set of function arguments. This feature is used by 5489 /// code completion. 5490 void 5491 Sema::AddOverloadCandidate(FunctionDecl *Function, 5492 DeclAccessPair FoundDecl, 5493 ArrayRef<Expr *> Args, 5494 OverloadCandidateSet &CandidateSet, 5495 bool SuppressUserConversions, 5496 bool PartialOverloading, 5497 bool AllowExplicit) { 5498 const FunctionProtoType *Proto 5499 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5500 assert(Proto && "Functions without a prototype cannot be overloaded"); 5501 assert(!Function->getDescribedFunctionTemplate() && 5502 "Use AddTemplateOverloadCandidate for function templates"); 5503 5504 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5505 if (!isa<CXXConstructorDecl>(Method)) { 5506 // If we get here, it's because we're calling a member function 5507 // that is named without a member access expression (e.g., 5508 // "this->f") that was either written explicitly or created 5509 // implicitly. This can happen with a qualified call to a member 5510 // function, e.g., X::f(). We use an empty type for the implied 5511 // object argument (C++ [over.call.func]p3), and the acting context 5512 // is irrelevant. 5513 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5514 QualType(), Expr::Classification::makeSimpleLValue(), 5515 Args, CandidateSet, SuppressUserConversions); 5516 return; 5517 } 5518 // We treat a constructor like a non-member function, since its object 5519 // argument doesn't participate in overload resolution. 5520 } 5521 5522 if (!CandidateSet.isNewCandidate(Function)) 5523 return; 5524 5525 // C++11 [class.copy]p11: [DR1402] 5526 // A defaulted move constructor that is defined as deleted is ignored by 5527 // overload resolution. 5528 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5529 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5530 Constructor->isMoveConstructor()) 5531 return; 5532 5533 // Overload resolution is always an unevaluated context. 5534 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5535 5536 if (Constructor) { 5537 // C++ [class.copy]p3: 5538 // A member function template is never instantiated to perform the copy 5539 // of a class object to an object of its class type. 5540 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5541 if (Args.size() == 1 && 5542 Constructor->isSpecializationCopyingObject() && 5543 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5544 IsDerivedFrom(Args[0]->getType(), ClassType))) 5545 return; 5546 } 5547 5548 // Add this candidate 5549 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5550 Candidate.FoundDecl = FoundDecl; 5551 Candidate.Function = Function; 5552 Candidate.Viable = true; 5553 Candidate.IsSurrogate = false; 5554 Candidate.IgnoreObjectArgument = false; 5555 Candidate.ExplicitCallArguments = Args.size(); 5556 5557 unsigned NumParams = Proto->getNumParams(); 5558 5559 // (C++ 13.3.2p2): A candidate function having fewer than m 5560 // parameters is viable only if it has an ellipsis in its parameter 5561 // list (8.3.5). 5562 if ((Args.size() + (PartialOverloading && Args.size())) > NumParams && 5563 !Proto->isVariadic()) { 5564 Candidate.Viable = false; 5565 Candidate.FailureKind = ovl_fail_too_many_arguments; 5566 return; 5567 } 5568 5569 // (C++ 13.3.2p2): A candidate function having more than m parameters 5570 // is viable only if the (m+1)st parameter has a default argument 5571 // (8.3.6). For the purposes of overload resolution, the 5572 // parameter list is truncated on the right, so that there are 5573 // exactly m parameters. 5574 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5575 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5576 // Not enough arguments. 5577 Candidate.Viable = false; 5578 Candidate.FailureKind = ovl_fail_too_few_arguments; 5579 return; 5580 } 5581 5582 // (CUDA B.1): Check for invalid calls between targets. 5583 if (getLangOpts().CUDA) 5584 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5585 if (CheckCUDATarget(Caller, Function)) { 5586 Candidate.Viable = false; 5587 Candidate.FailureKind = ovl_fail_bad_target; 5588 return; 5589 } 5590 5591 // Determine the implicit conversion sequences for each of the 5592 // arguments. 5593 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5594 if (ArgIdx < NumParams) { 5595 // (C++ 13.3.2p3): for F to be a viable function, there shall 5596 // exist for each argument an implicit conversion sequence 5597 // (13.3.3.1) that converts that argument to the corresponding 5598 // parameter of F. 5599 QualType ParamType = Proto->getParamType(ArgIdx); 5600 Candidate.Conversions[ArgIdx] 5601 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5602 SuppressUserConversions, 5603 /*InOverloadResolution=*/true, 5604 /*AllowObjCWritebackConversion=*/ 5605 getLangOpts().ObjCAutoRefCount, 5606 AllowExplicit); 5607 if (Candidate.Conversions[ArgIdx].isBad()) { 5608 Candidate.Viable = false; 5609 Candidate.FailureKind = ovl_fail_bad_conversion; 5610 return; 5611 } 5612 } else { 5613 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5614 // argument for which there is no corresponding parameter is 5615 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5616 Candidate.Conversions[ArgIdx].setEllipsis(); 5617 } 5618 } 5619 5620 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5621 Candidate.Viable = false; 5622 Candidate.FailureKind = ovl_fail_enable_if; 5623 Candidate.DeductionFailure.Data = FailedAttr; 5624 return; 5625 } 5626 } 5627 5628 static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); } 5629 5630 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 5631 bool MissingImplicitThis) { 5632 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but 5633 // we need to find the first failing one. 5634 if (!Function->hasAttrs()) 5635 return 0; 5636 AttrVec Attrs = Function->getAttrs(); 5637 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(), 5638 IsNotEnableIfAttr); 5639 if (Attrs.begin() == E) 5640 return 0; 5641 std::reverse(Attrs.begin(), E); 5642 5643 SFINAETrap Trap(*this); 5644 5645 // Convert the arguments. 5646 SmallVector<Expr *, 16> ConvertedArgs; 5647 bool InitializationFailed = false; 5648 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 5649 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 5650 !cast<CXXMethodDecl>(Function)->isStatic()) { 5651 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 5652 ExprResult R = 5653 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 5654 Method, Method); 5655 if (R.isInvalid()) { 5656 InitializationFailed = true; 5657 break; 5658 } 5659 ConvertedArgs.push_back(R.take()); 5660 } else { 5661 ExprResult R = 5662 PerformCopyInitialization(InitializedEntity::InitializeParameter( 5663 Context, 5664 Function->getParamDecl(i)), 5665 SourceLocation(), 5666 Args[i]); 5667 if (R.isInvalid()) { 5668 InitializationFailed = true; 5669 break; 5670 } 5671 ConvertedArgs.push_back(R.take()); 5672 } 5673 } 5674 5675 if (InitializationFailed || Trap.hasErrorOccurred()) 5676 return cast<EnableIfAttr>(Attrs[0]); 5677 5678 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) { 5679 APValue Result; 5680 EnableIfAttr *EIA = cast<EnableIfAttr>(*I); 5681 if (!EIA->getCond()->EvaluateWithSubstitution( 5682 Result, Context, Function, 5683 llvm::ArrayRef<const Expr*>(ConvertedArgs.data(), 5684 ConvertedArgs.size())) || 5685 !Result.isInt() || !Result.getInt().getBoolValue()) { 5686 return EIA; 5687 } 5688 } 5689 return 0; 5690 } 5691 5692 /// \brief Add all of the function declarations in the given function set to 5693 /// the overload candidate set. 5694 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5695 ArrayRef<Expr *> Args, 5696 OverloadCandidateSet& CandidateSet, 5697 bool SuppressUserConversions, 5698 TemplateArgumentListInfo *ExplicitTemplateArgs) { 5699 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5700 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5701 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5702 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5703 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5704 cast<CXXMethodDecl>(FD)->getParent(), 5705 Args[0]->getType(), Args[0]->Classify(Context), 5706 Args.slice(1), CandidateSet, 5707 SuppressUserConversions); 5708 else 5709 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5710 SuppressUserConversions); 5711 } else { 5712 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5713 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5714 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5715 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5716 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5717 ExplicitTemplateArgs, 5718 Args[0]->getType(), 5719 Args[0]->Classify(Context), Args.slice(1), 5720 CandidateSet, SuppressUserConversions); 5721 else 5722 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5723 ExplicitTemplateArgs, Args, 5724 CandidateSet, SuppressUserConversions); 5725 } 5726 } 5727 } 5728 5729 /// AddMethodCandidate - Adds a named decl (which is some kind of 5730 /// method) as a method candidate to the given overload set. 5731 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5732 QualType ObjectType, 5733 Expr::Classification ObjectClassification, 5734 ArrayRef<Expr *> Args, 5735 OverloadCandidateSet& CandidateSet, 5736 bool SuppressUserConversions) { 5737 NamedDecl *Decl = FoundDecl.getDecl(); 5738 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5739 5740 if (isa<UsingShadowDecl>(Decl)) 5741 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5742 5743 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5744 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5745 "Expected a member function template"); 5746 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5747 /*ExplicitArgs*/ 0, 5748 ObjectType, ObjectClassification, 5749 Args, CandidateSet, 5750 SuppressUserConversions); 5751 } else { 5752 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5753 ObjectType, ObjectClassification, 5754 Args, 5755 CandidateSet, SuppressUserConversions); 5756 } 5757 } 5758 5759 /// AddMethodCandidate - Adds the given C++ member function to the set 5760 /// of candidate functions, using the given function call arguments 5761 /// and the object argument (@c Object). For example, in a call 5762 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5763 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5764 /// allow user-defined conversions via constructors or conversion 5765 /// operators. 5766 void 5767 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5768 CXXRecordDecl *ActingContext, QualType ObjectType, 5769 Expr::Classification ObjectClassification, 5770 ArrayRef<Expr *> Args, 5771 OverloadCandidateSet &CandidateSet, 5772 bool SuppressUserConversions) { 5773 const FunctionProtoType *Proto 5774 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5775 assert(Proto && "Methods without a prototype cannot be overloaded"); 5776 assert(!isa<CXXConstructorDecl>(Method) && 5777 "Use AddOverloadCandidate for constructors"); 5778 5779 if (!CandidateSet.isNewCandidate(Method)) 5780 return; 5781 5782 // C++11 [class.copy]p23: [DR1402] 5783 // A defaulted move assignment operator that is defined as deleted is 5784 // ignored by overload resolution. 5785 if (Method->isDefaulted() && Method->isDeleted() && 5786 Method->isMoveAssignmentOperator()) 5787 return; 5788 5789 // Overload resolution is always an unevaluated context. 5790 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5791 5792 // Add this candidate 5793 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5794 Candidate.FoundDecl = FoundDecl; 5795 Candidate.Function = Method; 5796 Candidate.IsSurrogate = false; 5797 Candidate.IgnoreObjectArgument = false; 5798 Candidate.ExplicitCallArguments = Args.size(); 5799 5800 unsigned NumParams = Proto->getNumParams(); 5801 5802 // (C++ 13.3.2p2): A candidate function having fewer than m 5803 // parameters is viable only if it has an ellipsis in its parameter 5804 // list (8.3.5). 5805 if (Args.size() > NumParams && !Proto->isVariadic()) { 5806 Candidate.Viable = false; 5807 Candidate.FailureKind = ovl_fail_too_many_arguments; 5808 return; 5809 } 5810 5811 // (C++ 13.3.2p2): A candidate function having more than m parameters 5812 // is viable only if the (m+1)st parameter has a default argument 5813 // (8.3.6). For the purposes of overload resolution, the 5814 // parameter list is truncated on the right, so that there are 5815 // exactly m parameters. 5816 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 5817 if (Args.size() < MinRequiredArgs) { 5818 // Not enough arguments. 5819 Candidate.Viable = false; 5820 Candidate.FailureKind = ovl_fail_too_few_arguments; 5821 return; 5822 } 5823 5824 Candidate.Viable = true; 5825 5826 if (Method->isStatic() || ObjectType.isNull()) 5827 // The implicit object argument is ignored. 5828 Candidate.IgnoreObjectArgument = true; 5829 else { 5830 // Determine the implicit conversion sequence for the object 5831 // parameter. 5832 Candidate.Conversions[0] 5833 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 5834 Method, ActingContext); 5835 if (Candidate.Conversions[0].isBad()) { 5836 Candidate.Viable = false; 5837 Candidate.FailureKind = ovl_fail_bad_conversion; 5838 return; 5839 } 5840 } 5841 5842 // Determine the implicit conversion sequences for each of the 5843 // arguments. 5844 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5845 if (ArgIdx < NumParams) { 5846 // (C++ 13.3.2p3): for F to be a viable function, there shall 5847 // exist for each argument an implicit conversion sequence 5848 // (13.3.3.1) that converts that argument to the corresponding 5849 // parameter of F. 5850 QualType ParamType = Proto->getParamType(ArgIdx); 5851 Candidate.Conversions[ArgIdx + 1] 5852 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5853 SuppressUserConversions, 5854 /*InOverloadResolution=*/true, 5855 /*AllowObjCWritebackConversion=*/ 5856 getLangOpts().ObjCAutoRefCount); 5857 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5858 Candidate.Viable = false; 5859 Candidate.FailureKind = ovl_fail_bad_conversion; 5860 return; 5861 } 5862 } else { 5863 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5864 // argument for which there is no corresponding parameter is 5865 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 5866 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5867 } 5868 } 5869 5870 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 5871 Candidate.Viable = false; 5872 Candidate.FailureKind = ovl_fail_enable_if; 5873 Candidate.DeductionFailure.Data = FailedAttr; 5874 return; 5875 } 5876 } 5877 5878 /// \brief Add a C++ member function template as a candidate to the candidate 5879 /// set, using template argument deduction to produce an appropriate member 5880 /// function template specialization. 5881 void 5882 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 5883 DeclAccessPair FoundDecl, 5884 CXXRecordDecl *ActingContext, 5885 TemplateArgumentListInfo *ExplicitTemplateArgs, 5886 QualType ObjectType, 5887 Expr::Classification ObjectClassification, 5888 ArrayRef<Expr *> Args, 5889 OverloadCandidateSet& CandidateSet, 5890 bool SuppressUserConversions) { 5891 if (!CandidateSet.isNewCandidate(MethodTmpl)) 5892 return; 5893 5894 // C++ [over.match.funcs]p7: 5895 // In each case where a candidate is a function template, candidate 5896 // function template specializations are generated using template argument 5897 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5898 // candidate functions in the usual way.113) A given name can refer to one 5899 // or more function templates and also to a set of overloaded non-template 5900 // functions. In such a case, the candidate functions generated from each 5901 // function template are combined with the set of non-template candidate 5902 // functions. 5903 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5904 FunctionDecl *Specialization = 0; 5905 if (TemplateDeductionResult Result 5906 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 5907 Specialization, Info)) { 5908 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5909 Candidate.FoundDecl = FoundDecl; 5910 Candidate.Function = MethodTmpl->getTemplatedDecl(); 5911 Candidate.Viable = false; 5912 Candidate.FailureKind = ovl_fail_bad_deduction; 5913 Candidate.IsSurrogate = false; 5914 Candidate.IgnoreObjectArgument = false; 5915 Candidate.ExplicitCallArguments = Args.size(); 5916 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5917 Info); 5918 return; 5919 } 5920 5921 // Add the function template specialization produced by template argument 5922 // deduction as a candidate. 5923 assert(Specialization && "Missing member function template specialization?"); 5924 assert(isa<CXXMethodDecl>(Specialization) && 5925 "Specialization is not a member function?"); 5926 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 5927 ActingContext, ObjectType, ObjectClassification, Args, 5928 CandidateSet, SuppressUserConversions); 5929 } 5930 5931 /// \brief Add a C++ function template specialization as a candidate 5932 /// in the candidate set, using template argument deduction to produce 5933 /// an appropriate function template specialization. 5934 void 5935 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 5936 DeclAccessPair FoundDecl, 5937 TemplateArgumentListInfo *ExplicitTemplateArgs, 5938 ArrayRef<Expr *> Args, 5939 OverloadCandidateSet& CandidateSet, 5940 bool SuppressUserConversions) { 5941 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5942 return; 5943 5944 // C++ [over.match.funcs]p7: 5945 // In each case where a candidate is a function template, candidate 5946 // function template specializations are generated using template argument 5947 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5948 // candidate functions in the usual way.113) A given name can refer to one 5949 // or more function templates and also to a set of overloaded non-template 5950 // functions. In such a case, the candidate functions generated from each 5951 // function template are combined with the set of non-template candidate 5952 // functions. 5953 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5954 FunctionDecl *Specialization = 0; 5955 if (TemplateDeductionResult Result 5956 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 5957 Specialization, Info)) { 5958 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5959 Candidate.FoundDecl = FoundDecl; 5960 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5961 Candidate.Viable = false; 5962 Candidate.FailureKind = ovl_fail_bad_deduction; 5963 Candidate.IsSurrogate = false; 5964 Candidate.IgnoreObjectArgument = false; 5965 Candidate.ExplicitCallArguments = Args.size(); 5966 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5967 Info); 5968 return; 5969 } 5970 5971 // Add the function template specialization produced by template argument 5972 // deduction as a candidate. 5973 assert(Specialization && "Missing function template specialization?"); 5974 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 5975 SuppressUserConversions); 5976 } 5977 5978 /// Determine whether this is an allowable conversion from the result 5979 /// of an explicit conversion operator to the expected type, per C++ 5980 /// [over.match.conv]p1 and [over.match.ref]p1. 5981 /// 5982 /// \param ConvType The return type of the conversion function. 5983 /// 5984 /// \param ToType The type we are converting to. 5985 /// 5986 /// \param AllowObjCPointerConversion Allow a conversion from one 5987 /// Objective-C pointer to another. 5988 /// 5989 /// \returns true if the conversion is allowable, false otherwise. 5990 static bool isAllowableExplicitConversion(Sema &S, 5991 QualType ConvType, QualType ToType, 5992 bool AllowObjCPointerConversion) { 5993 QualType ToNonRefType = ToType.getNonReferenceType(); 5994 5995 // Easy case: the types are the same. 5996 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 5997 return true; 5998 5999 // Allow qualification conversions. 6000 bool ObjCLifetimeConversion; 6001 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6002 ObjCLifetimeConversion)) 6003 return true; 6004 6005 // If we're not allowed to consider Objective-C pointer conversions, 6006 // we're done. 6007 if (!AllowObjCPointerConversion) 6008 return false; 6009 6010 // Is this an Objective-C pointer conversion? 6011 bool IncompatibleObjC = false; 6012 QualType ConvertedType; 6013 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6014 IncompatibleObjC); 6015 } 6016 6017 /// AddConversionCandidate - Add a C++ conversion function as a 6018 /// candidate in the candidate set (C++ [over.match.conv], 6019 /// C++ [over.match.copy]). From is the expression we're converting from, 6020 /// and ToType is the type that we're eventually trying to convert to 6021 /// (which may or may not be the same type as the type that the 6022 /// conversion function produces). 6023 void 6024 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6025 DeclAccessPair FoundDecl, 6026 CXXRecordDecl *ActingContext, 6027 Expr *From, QualType ToType, 6028 OverloadCandidateSet& CandidateSet, 6029 bool AllowObjCConversionOnExplicit) { 6030 assert(!Conversion->getDescribedFunctionTemplate() && 6031 "Conversion function templates use AddTemplateConversionCandidate"); 6032 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6033 if (!CandidateSet.isNewCandidate(Conversion)) 6034 return; 6035 6036 // If the conversion function has an undeduced return type, trigger its 6037 // deduction now. 6038 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) { 6039 if (DeduceReturnType(Conversion, From->getExprLoc())) 6040 return; 6041 ConvType = Conversion->getConversionType().getNonReferenceType(); 6042 } 6043 6044 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6045 // operator is only a candidate if its return type is the target type or 6046 // can be converted to the target type with a qualification conversion. 6047 if (Conversion->isExplicit() && 6048 !isAllowableExplicitConversion(*this, ConvType, ToType, 6049 AllowObjCConversionOnExplicit)) 6050 return; 6051 6052 // Overload resolution is always an unevaluated context. 6053 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6054 6055 // Add this candidate 6056 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6057 Candidate.FoundDecl = FoundDecl; 6058 Candidate.Function = Conversion; 6059 Candidate.IsSurrogate = false; 6060 Candidate.IgnoreObjectArgument = false; 6061 Candidate.FinalConversion.setAsIdentityConversion(); 6062 Candidate.FinalConversion.setFromType(ConvType); 6063 Candidate.FinalConversion.setAllToTypes(ToType); 6064 Candidate.Viable = true; 6065 Candidate.ExplicitCallArguments = 1; 6066 6067 // C++ [over.match.funcs]p4: 6068 // For conversion functions, the function is considered to be a member of 6069 // the class of the implicit implied object argument for the purpose of 6070 // defining the type of the implicit object parameter. 6071 // 6072 // Determine the implicit conversion sequence for the implicit 6073 // object parameter. 6074 QualType ImplicitParamType = From->getType(); 6075 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6076 ImplicitParamType = FromPtrType->getPointeeType(); 6077 CXXRecordDecl *ConversionContext 6078 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6079 6080 Candidate.Conversions[0] 6081 = TryObjectArgumentInitialization(*this, From->getType(), 6082 From->Classify(Context), 6083 Conversion, ConversionContext); 6084 6085 if (Candidate.Conversions[0].isBad()) { 6086 Candidate.Viable = false; 6087 Candidate.FailureKind = ovl_fail_bad_conversion; 6088 return; 6089 } 6090 6091 // We won't go through a user-defined type conversion function to convert a 6092 // derived to base as such conversions are given Conversion Rank. They only 6093 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6094 QualType FromCanon 6095 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6096 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6097 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 6098 Candidate.Viable = false; 6099 Candidate.FailureKind = ovl_fail_trivial_conversion; 6100 return; 6101 } 6102 6103 // To determine what the conversion from the result of calling the 6104 // conversion function to the type we're eventually trying to 6105 // convert to (ToType), we need to synthesize a call to the 6106 // conversion function and attempt copy initialization from it. This 6107 // makes sure that we get the right semantics with respect to 6108 // lvalues/rvalues and the type. Fortunately, we can allocate this 6109 // call on the stack and we don't need its arguments to be 6110 // well-formed. 6111 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6112 VK_LValue, From->getLocStart()); 6113 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6114 Context.getPointerType(Conversion->getType()), 6115 CK_FunctionToPointerDecay, 6116 &ConversionRef, VK_RValue); 6117 6118 QualType ConversionType = Conversion->getConversionType(); 6119 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 6120 Candidate.Viable = false; 6121 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6122 return; 6123 } 6124 6125 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6126 6127 // Note that it is safe to allocate CallExpr on the stack here because 6128 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6129 // allocator). 6130 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6131 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6132 From->getLocStart()); 6133 ImplicitConversionSequence ICS = 6134 TryCopyInitialization(*this, &Call, ToType, 6135 /*SuppressUserConversions=*/true, 6136 /*InOverloadResolution=*/false, 6137 /*AllowObjCWritebackConversion=*/false); 6138 6139 switch (ICS.getKind()) { 6140 case ImplicitConversionSequence::StandardConversion: 6141 Candidate.FinalConversion = ICS.Standard; 6142 6143 // C++ [over.ics.user]p3: 6144 // If the user-defined conversion is specified by a specialization of a 6145 // conversion function template, the second standard conversion sequence 6146 // shall have exact match rank. 6147 if (Conversion->getPrimaryTemplate() && 6148 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6149 Candidate.Viable = false; 6150 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6151 return; 6152 } 6153 6154 // C++0x [dcl.init.ref]p5: 6155 // In the second case, if the reference is an rvalue reference and 6156 // the second standard conversion sequence of the user-defined 6157 // conversion sequence includes an lvalue-to-rvalue conversion, the 6158 // program is ill-formed. 6159 if (ToType->isRValueReferenceType() && 6160 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6161 Candidate.Viable = false; 6162 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6163 return; 6164 } 6165 break; 6166 6167 case ImplicitConversionSequence::BadConversion: 6168 Candidate.Viable = false; 6169 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6170 return; 6171 6172 default: 6173 llvm_unreachable( 6174 "Can only end up with a standard conversion sequence or failure"); 6175 } 6176 6177 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) { 6178 Candidate.Viable = false; 6179 Candidate.FailureKind = ovl_fail_enable_if; 6180 Candidate.DeductionFailure.Data = FailedAttr; 6181 return; 6182 } 6183 } 6184 6185 /// \brief Adds a conversion function template specialization 6186 /// candidate to the overload set, using template argument deduction 6187 /// to deduce the template arguments of the conversion function 6188 /// template from the type that we are converting to (C++ 6189 /// [temp.deduct.conv]). 6190 void 6191 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6192 DeclAccessPair FoundDecl, 6193 CXXRecordDecl *ActingDC, 6194 Expr *From, QualType ToType, 6195 OverloadCandidateSet &CandidateSet, 6196 bool AllowObjCConversionOnExplicit) { 6197 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6198 "Only conversion function templates permitted here"); 6199 6200 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6201 return; 6202 6203 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6204 CXXConversionDecl *Specialization = 0; 6205 if (TemplateDeductionResult Result 6206 = DeduceTemplateArguments(FunctionTemplate, ToType, 6207 Specialization, Info)) { 6208 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6209 Candidate.FoundDecl = FoundDecl; 6210 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6211 Candidate.Viable = false; 6212 Candidate.FailureKind = ovl_fail_bad_deduction; 6213 Candidate.IsSurrogate = false; 6214 Candidate.IgnoreObjectArgument = false; 6215 Candidate.ExplicitCallArguments = 1; 6216 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6217 Info); 6218 return; 6219 } 6220 6221 // Add the conversion function template specialization produced by 6222 // template argument deduction as a candidate. 6223 assert(Specialization && "Missing function template specialization?"); 6224 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6225 CandidateSet, AllowObjCConversionOnExplicit); 6226 } 6227 6228 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6229 /// converts the given @c Object to a function pointer via the 6230 /// conversion function @c Conversion, and then attempts to call it 6231 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6232 /// the type of function that we'll eventually be calling. 6233 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6234 DeclAccessPair FoundDecl, 6235 CXXRecordDecl *ActingContext, 6236 const FunctionProtoType *Proto, 6237 Expr *Object, 6238 ArrayRef<Expr *> Args, 6239 OverloadCandidateSet& CandidateSet) { 6240 if (!CandidateSet.isNewCandidate(Conversion)) 6241 return; 6242 6243 // Overload resolution is always an unevaluated context. 6244 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6245 6246 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6247 Candidate.FoundDecl = FoundDecl; 6248 Candidate.Function = 0; 6249 Candidate.Surrogate = Conversion; 6250 Candidate.Viable = true; 6251 Candidate.IsSurrogate = true; 6252 Candidate.IgnoreObjectArgument = false; 6253 Candidate.ExplicitCallArguments = Args.size(); 6254 6255 // Determine the implicit conversion sequence for the implicit 6256 // object parameter. 6257 ImplicitConversionSequence ObjectInit 6258 = TryObjectArgumentInitialization(*this, Object->getType(), 6259 Object->Classify(Context), 6260 Conversion, ActingContext); 6261 if (ObjectInit.isBad()) { 6262 Candidate.Viable = false; 6263 Candidate.FailureKind = ovl_fail_bad_conversion; 6264 Candidate.Conversions[0] = ObjectInit; 6265 return; 6266 } 6267 6268 // The first conversion is actually a user-defined conversion whose 6269 // first conversion is ObjectInit's standard conversion (which is 6270 // effectively a reference binding). Record it as such. 6271 Candidate.Conversions[0].setUserDefined(); 6272 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6273 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6274 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6275 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6276 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6277 Candidate.Conversions[0].UserDefined.After 6278 = Candidate.Conversions[0].UserDefined.Before; 6279 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6280 6281 // Find the 6282 unsigned NumParams = Proto->getNumParams(); 6283 6284 // (C++ 13.3.2p2): A candidate function having fewer than m 6285 // parameters is viable only if it has an ellipsis in its parameter 6286 // list (8.3.5). 6287 if (Args.size() > NumParams && !Proto->isVariadic()) { 6288 Candidate.Viable = false; 6289 Candidate.FailureKind = ovl_fail_too_many_arguments; 6290 return; 6291 } 6292 6293 // Function types don't have any default arguments, so just check if 6294 // we have enough arguments. 6295 if (Args.size() < NumParams) { 6296 // Not enough arguments. 6297 Candidate.Viable = false; 6298 Candidate.FailureKind = ovl_fail_too_few_arguments; 6299 return; 6300 } 6301 6302 // Determine the implicit conversion sequences for each of the 6303 // arguments. 6304 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6305 if (ArgIdx < NumParams) { 6306 // (C++ 13.3.2p3): for F to be a viable function, there shall 6307 // exist for each argument an implicit conversion sequence 6308 // (13.3.3.1) that converts that argument to the corresponding 6309 // parameter of F. 6310 QualType ParamType = Proto->getParamType(ArgIdx); 6311 Candidate.Conversions[ArgIdx + 1] 6312 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6313 /*SuppressUserConversions=*/false, 6314 /*InOverloadResolution=*/false, 6315 /*AllowObjCWritebackConversion=*/ 6316 getLangOpts().ObjCAutoRefCount); 6317 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6318 Candidate.Viable = false; 6319 Candidate.FailureKind = ovl_fail_bad_conversion; 6320 return; 6321 } 6322 } else { 6323 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6324 // argument for which there is no corresponding parameter is 6325 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6326 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6327 } 6328 } 6329 6330 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) { 6331 Candidate.Viable = false; 6332 Candidate.FailureKind = ovl_fail_enable_if; 6333 Candidate.DeductionFailure.Data = FailedAttr; 6334 return; 6335 } 6336 } 6337 6338 /// \brief Add overload candidates for overloaded operators that are 6339 /// member functions. 6340 /// 6341 /// Add the overloaded operator candidates that are member functions 6342 /// for the operator Op that was used in an operator expression such 6343 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6344 /// CandidateSet will store the added overload candidates. (C++ 6345 /// [over.match.oper]). 6346 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6347 SourceLocation OpLoc, 6348 ArrayRef<Expr *> Args, 6349 OverloadCandidateSet& CandidateSet, 6350 SourceRange OpRange) { 6351 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6352 6353 // C++ [over.match.oper]p3: 6354 // For a unary operator @ with an operand of a type whose 6355 // cv-unqualified version is T1, and for a binary operator @ with 6356 // a left operand of a type whose cv-unqualified version is T1 and 6357 // a right operand of a type whose cv-unqualified version is T2, 6358 // three sets of candidate functions, designated member 6359 // candidates, non-member candidates and built-in candidates, are 6360 // constructed as follows: 6361 QualType T1 = Args[0]->getType(); 6362 6363 // -- If T1 is a complete class type or a class currently being 6364 // defined, the set of member candidates is the result of the 6365 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6366 // the set of member candidates is empty. 6367 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6368 // Complete the type if it can be completed. 6369 RequireCompleteType(OpLoc, T1, 0); 6370 // If the type is neither complete nor being defined, bail out now. 6371 if (!T1Rec->getDecl()->getDefinition()) 6372 return; 6373 6374 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6375 LookupQualifiedName(Operators, T1Rec->getDecl()); 6376 Operators.suppressDiagnostics(); 6377 6378 for (LookupResult::iterator Oper = Operators.begin(), 6379 OperEnd = Operators.end(); 6380 Oper != OperEnd; 6381 ++Oper) 6382 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6383 Args[0]->Classify(Context), 6384 Args.slice(1), 6385 CandidateSet, 6386 /* SuppressUserConversions = */ false); 6387 } 6388 } 6389 6390 /// AddBuiltinCandidate - Add a candidate for a built-in 6391 /// operator. ResultTy and ParamTys are the result and parameter types 6392 /// of the built-in candidate, respectively. Args and NumArgs are the 6393 /// arguments being passed to the candidate. IsAssignmentOperator 6394 /// should be true when this built-in candidate is an assignment 6395 /// operator. NumContextualBoolArguments is the number of arguments 6396 /// (at the beginning of the argument list) that will be contextually 6397 /// converted to bool. 6398 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6399 ArrayRef<Expr *> Args, 6400 OverloadCandidateSet& CandidateSet, 6401 bool IsAssignmentOperator, 6402 unsigned NumContextualBoolArguments) { 6403 // Overload resolution is always an unevaluated context. 6404 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6405 6406 // Add this candidate 6407 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6408 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 6409 Candidate.Function = 0; 6410 Candidate.IsSurrogate = false; 6411 Candidate.IgnoreObjectArgument = false; 6412 Candidate.BuiltinTypes.ResultTy = ResultTy; 6413 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6414 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6415 6416 // Determine the implicit conversion sequences for each of the 6417 // arguments. 6418 Candidate.Viable = true; 6419 Candidate.ExplicitCallArguments = Args.size(); 6420 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6421 // C++ [over.match.oper]p4: 6422 // For the built-in assignment operators, conversions of the 6423 // left operand are restricted as follows: 6424 // -- no temporaries are introduced to hold the left operand, and 6425 // -- no user-defined conversions are applied to the left 6426 // operand to achieve a type match with the left-most 6427 // parameter of a built-in candidate. 6428 // 6429 // We block these conversions by turning off user-defined 6430 // conversions, since that is the only way that initialization of 6431 // a reference to a non-class type can occur from something that 6432 // is not of the same type. 6433 if (ArgIdx < NumContextualBoolArguments) { 6434 assert(ParamTys[ArgIdx] == Context.BoolTy && 6435 "Contextual conversion to bool requires bool type"); 6436 Candidate.Conversions[ArgIdx] 6437 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6438 } else { 6439 Candidate.Conversions[ArgIdx] 6440 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6441 ArgIdx == 0 && IsAssignmentOperator, 6442 /*InOverloadResolution=*/false, 6443 /*AllowObjCWritebackConversion=*/ 6444 getLangOpts().ObjCAutoRefCount); 6445 } 6446 if (Candidate.Conversions[ArgIdx].isBad()) { 6447 Candidate.Viable = false; 6448 Candidate.FailureKind = ovl_fail_bad_conversion; 6449 break; 6450 } 6451 } 6452 } 6453 6454 namespace { 6455 6456 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6457 /// candidate operator functions for built-in operators (C++ 6458 /// [over.built]). The types are separated into pointer types and 6459 /// enumeration types. 6460 class BuiltinCandidateTypeSet { 6461 /// TypeSet - A set of types. 6462 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6463 6464 /// PointerTypes - The set of pointer types that will be used in the 6465 /// built-in candidates. 6466 TypeSet PointerTypes; 6467 6468 /// MemberPointerTypes - The set of member pointer types that will be 6469 /// used in the built-in candidates. 6470 TypeSet MemberPointerTypes; 6471 6472 /// EnumerationTypes - The set of enumeration types that will be 6473 /// used in the built-in candidates. 6474 TypeSet EnumerationTypes; 6475 6476 /// \brief The set of vector types that will be used in the built-in 6477 /// candidates. 6478 TypeSet VectorTypes; 6479 6480 /// \brief A flag indicating non-record types are viable candidates 6481 bool HasNonRecordTypes; 6482 6483 /// \brief A flag indicating whether either arithmetic or enumeration types 6484 /// were present in the candidate set. 6485 bool HasArithmeticOrEnumeralTypes; 6486 6487 /// \brief A flag indicating whether the nullptr type was present in the 6488 /// candidate set. 6489 bool HasNullPtrType; 6490 6491 /// Sema - The semantic analysis instance where we are building the 6492 /// candidate type set. 6493 Sema &SemaRef; 6494 6495 /// Context - The AST context in which we will build the type sets. 6496 ASTContext &Context; 6497 6498 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6499 const Qualifiers &VisibleQuals); 6500 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6501 6502 public: 6503 /// iterator - Iterates through the types that are part of the set. 6504 typedef TypeSet::iterator iterator; 6505 6506 BuiltinCandidateTypeSet(Sema &SemaRef) 6507 : HasNonRecordTypes(false), 6508 HasArithmeticOrEnumeralTypes(false), 6509 HasNullPtrType(false), 6510 SemaRef(SemaRef), 6511 Context(SemaRef.Context) { } 6512 6513 void AddTypesConvertedFrom(QualType Ty, 6514 SourceLocation Loc, 6515 bool AllowUserConversions, 6516 bool AllowExplicitConversions, 6517 const Qualifiers &VisibleTypeConversionsQuals); 6518 6519 /// pointer_begin - First pointer type found; 6520 iterator pointer_begin() { return PointerTypes.begin(); } 6521 6522 /// pointer_end - Past the last pointer type found; 6523 iterator pointer_end() { return PointerTypes.end(); } 6524 6525 /// member_pointer_begin - First member pointer type found; 6526 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6527 6528 /// member_pointer_end - Past the last member pointer type found; 6529 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6530 6531 /// enumeration_begin - First enumeration type found; 6532 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6533 6534 /// enumeration_end - Past the last enumeration type found; 6535 iterator enumeration_end() { return EnumerationTypes.end(); } 6536 6537 iterator vector_begin() { return VectorTypes.begin(); } 6538 iterator vector_end() { return VectorTypes.end(); } 6539 6540 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6541 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6542 bool hasNullPtrType() const { return HasNullPtrType; } 6543 }; 6544 6545 } // end anonymous namespace 6546 6547 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6548 /// the set of pointer types along with any more-qualified variants of 6549 /// that type. For example, if @p Ty is "int const *", this routine 6550 /// will add "int const *", "int const volatile *", "int const 6551 /// restrict *", and "int const volatile restrict *" to the set of 6552 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6553 /// false otherwise. 6554 /// 6555 /// FIXME: what to do about extended qualifiers? 6556 bool 6557 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6558 const Qualifiers &VisibleQuals) { 6559 6560 // Insert this type. 6561 if (!PointerTypes.insert(Ty)) 6562 return false; 6563 6564 QualType PointeeTy; 6565 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6566 bool buildObjCPtr = false; 6567 if (!PointerTy) { 6568 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6569 PointeeTy = PTy->getPointeeType(); 6570 buildObjCPtr = true; 6571 } else { 6572 PointeeTy = PointerTy->getPointeeType(); 6573 } 6574 6575 // Don't add qualified variants of arrays. For one, they're not allowed 6576 // (the qualifier would sink to the element type), and for another, the 6577 // only overload situation where it matters is subscript or pointer +- int, 6578 // and those shouldn't have qualifier variants anyway. 6579 if (PointeeTy->isArrayType()) 6580 return true; 6581 6582 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6583 bool hasVolatile = VisibleQuals.hasVolatile(); 6584 bool hasRestrict = VisibleQuals.hasRestrict(); 6585 6586 // Iterate through all strict supersets of BaseCVR. 6587 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6588 if ((CVR | BaseCVR) != CVR) continue; 6589 // Skip over volatile if no volatile found anywhere in the types. 6590 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6591 6592 // Skip over restrict if no restrict found anywhere in the types, or if 6593 // the type cannot be restrict-qualified. 6594 if ((CVR & Qualifiers::Restrict) && 6595 (!hasRestrict || 6596 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6597 continue; 6598 6599 // Build qualified pointee type. 6600 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6601 6602 // Build qualified pointer type. 6603 QualType QPointerTy; 6604 if (!buildObjCPtr) 6605 QPointerTy = Context.getPointerType(QPointeeTy); 6606 else 6607 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6608 6609 // Insert qualified pointer type. 6610 PointerTypes.insert(QPointerTy); 6611 } 6612 6613 return true; 6614 } 6615 6616 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6617 /// to the set of pointer types along with any more-qualified variants of 6618 /// that type. For example, if @p Ty is "int const *", this routine 6619 /// will add "int const *", "int const volatile *", "int const 6620 /// restrict *", and "int const volatile restrict *" to the set of 6621 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6622 /// false otherwise. 6623 /// 6624 /// FIXME: what to do about extended qualifiers? 6625 bool 6626 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6627 QualType Ty) { 6628 // Insert this type. 6629 if (!MemberPointerTypes.insert(Ty)) 6630 return false; 6631 6632 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6633 assert(PointerTy && "type was not a member pointer type!"); 6634 6635 QualType PointeeTy = PointerTy->getPointeeType(); 6636 // Don't add qualified variants of arrays. For one, they're not allowed 6637 // (the qualifier would sink to the element type), and for another, the 6638 // only overload situation where it matters is subscript or pointer +- int, 6639 // and those shouldn't have qualifier variants anyway. 6640 if (PointeeTy->isArrayType()) 6641 return true; 6642 const Type *ClassTy = PointerTy->getClass(); 6643 6644 // Iterate through all strict supersets of the pointee type's CVR 6645 // qualifiers. 6646 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6647 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6648 if ((CVR | BaseCVR) != CVR) continue; 6649 6650 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6651 MemberPointerTypes.insert( 6652 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6653 } 6654 6655 return true; 6656 } 6657 6658 /// AddTypesConvertedFrom - Add each of the types to which the type @p 6659 /// Ty can be implicit converted to the given set of @p Types. We're 6660 /// primarily interested in pointer types and enumeration types. We also 6661 /// take member pointer types, for the conditional operator. 6662 /// AllowUserConversions is true if we should look at the conversion 6663 /// functions of a class type, and AllowExplicitConversions if we 6664 /// should also include the explicit conversion functions of a class 6665 /// type. 6666 void 6667 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6668 SourceLocation Loc, 6669 bool AllowUserConversions, 6670 bool AllowExplicitConversions, 6671 const Qualifiers &VisibleQuals) { 6672 // Only deal with canonical types. 6673 Ty = Context.getCanonicalType(Ty); 6674 6675 // Look through reference types; they aren't part of the type of an 6676 // expression for the purposes of conversions. 6677 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6678 Ty = RefTy->getPointeeType(); 6679 6680 // If we're dealing with an array type, decay to the pointer. 6681 if (Ty->isArrayType()) 6682 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6683 6684 // Otherwise, we don't care about qualifiers on the type. 6685 Ty = Ty.getLocalUnqualifiedType(); 6686 6687 // Flag if we ever add a non-record type. 6688 const RecordType *TyRec = Ty->getAs<RecordType>(); 6689 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6690 6691 // Flag if we encounter an arithmetic type. 6692 HasArithmeticOrEnumeralTypes = 6693 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6694 6695 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6696 PointerTypes.insert(Ty); 6697 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6698 // Insert our type, and its more-qualified variants, into the set 6699 // of types. 6700 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6701 return; 6702 } else if (Ty->isMemberPointerType()) { 6703 // Member pointers are far easier, since the pointee can't be converted. 6704 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6705 return; 6706 } else if (Ty->isEnumeralType()) { 6707 HasArithmeticOrEnumeralTypes = true; 6708 EnumerationTypes.insert(Ty); 6709 } else if (Ty->isVectorType()) { 6710 // We treat vector types as arithmetic types in many contexts as an 6711 // extension. 6712 HasArithmeticOrEnumeralTypes = true; 6713 VectorTypes.insert(Ty); 6714 } else if (Ty->isNullPtrType()) { 6715 HasNullPtrType = true; 6716 } else if (AllowUserConversions && TyRec) { 6717 // No conversion functions in incomplete types. 6718 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6719 return; 6720 6721 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6722 std::pair<CXXRecordDecl::conversion_iterator, 6723 CXXRecordDecl::conversion_iterator> 6724 Conversions = ClassDecl->getVisibleConversionFunctions(); 6725 for (CXXRecordDecl::conversion_iterator 6726 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6727 NamedDecl *D = I.getDecl(); 6728 if (isa<UsingShadowDecl>(D)) 6729 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6730 6731 // Skip conversion function templates; they don't tell us anything 6732 // about which builtin types we can convert to. 6733 if (isa<FunctionTemplateDecl>(D)) 6734 continue; 6735 6736 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6737 if (AllowExplicitConversions || !Conv->isExplicit()) { 6738 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6739 VisibleQuals); 6740 } 6741 } 6742 } 6743 } 6744 6745 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6746 /// the volatile- and non-volatile-qualified assignment operators for the 6747 /// given type to the candidate set. 6748 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6749 QualType T, 6750 ArrayRef<Expr *> Args, 6751 OverloadCandidateSet &CandidateSet) { 6752 QualType ParamTypes[2]; 6753 6754 // T& operator=(T&, T) 6755 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6756 ParamTypes[1] = T; 6757 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6758 /*IsAssignmentOperator=*/true); 6759 6760 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6761 // volatile T& operator=(volatile T&, T) 6762 ParamTypes[0] 6763 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6764 ParamTypes[1] = T; 6765 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6766 /*IsAssignmentOperator=*/true); 6767 } 6768 } 6769 6770 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6771 /// if any, found in visible type conversion functions found in ArgExpr's type. 6772 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6773 Qualifiers VRQuals; 6774 const RecordType *TyRec; 6775 if (const MemberPointerType *RHSMPType = 6776 ArgExpr->getType()->getAs<MemberPointerType>()) 6777 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6778 else 6779 TyRec = ArgExpr->getType()->getAs<RecordType>(); 6780 if (!TyRec) { 6781 // Just to be safe, assume the worst case. 6782 VRQuals.addVolatile(); 6783 VRQuals.addRestrict(); 6784 return VRQuals; 6785 } 6786 6787 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6788 if (!ClassDecl->hasDefinition()) 6789 return VRQuals; 6790 6791 std::pair<CXXRecordDecl::conversion_iterator, 6792 CXXRecordDecl::conversion_iterator> 6793 Conversions = ClassDecl->getVisibleConversionFunctions(); 6794 6795 for (CXXRecordDecl::conversion_iterator 6796 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6797 NamedDecl *D = I.getDecl(); 6798 if (isa<UsingShadowDecl>(D)) 6799 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6800 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6801 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 6802 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 6803 CanTy = ResTypeRef->getPointeeType(); 6804 // Need to go down the pointer/mempointer chain and add qualifiers 6805 // as see them. 6806 bool done = false; 6807 while (!done) { 6808 if (CanTy.isRestrictQualified()) 6809 VRQuals.addRestrict(); 6810 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 6811 CanTy = ResTypePtr->getPointeeType(); 6812 else if (const MemberPointerType *ResTypeMPtr = 6813 CanTy->getAs<MemberPointerType>()) 6814 CanTy = ResTypeMPtr->getPointeeType(); 6815 else 6816 done = true; 6817 if (CanTy.isVolatileQualified()) 6818 VRQuals.addVolatile(); 6819 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 6820 return VRQuals; 6821 } 6822 } 6823 } 6824 return VRQuals; 6825 } 6826 6827 namespace { 6828 6829 /// \brief Helper class to manage the addition of builtin operator overload 6830 /// candidates. It provides shared state and utility methods used throughout 6831 /// the process, as well as a helper method to add each group of builtin 6832 /// operator overloads from the standard to a candidate set. 6833 class BuiltinOperatorOverloadBuilder { 6834 // Common instance state available to all overload candidate addition methods. 6835 Sema &S; 6836 ArrayRef<Expr *> Args; 6837 Qualifiers VisibleTypeConversionsQuals; 6838 bool HasArithmeticOrEnumeralCandidateType; 6839 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 6840 OverloadCandidateSet &CandidateSet; 6841 6842 // Define some constants used to index and iterate over the arithemetic types 6843 // provided via the getArithmeticType() method below. 6844 // The "promoted arithmetic types" are the arithmetic 6845 // types are that preserved by promotion (C++ [over.built]p2). 6846 static const unsigned FirstIntegralType = 3; 6847 static const unsigned LastIntegralType = 20; 6848 static const unsigned FirstPromotedIntegralType = 3, 6849 LastPromotedIntegralType = 11; 6850 static const unsigned FirstPromotedArithmeticType = 0, 6851 LastPromotedArithmeticType = 11; 6852 static const unsigned NumArithmeticTypes = 20; 6853 6854 /// \brief Get the canonical type for a given arithmetic type index. 6855 CanQualType getArithmeticType(unsigned index) { 6856 assert(index < NumArithmeticTypes); 6857 static CanQualType ASTContext::* const 6858 ArithmeticTypes[NumArithmeticTypes] = { 6859 // Start of promoted types. 6860 &ASTContext::FloatTy, 6861 &ASTContext::DoubleTy, 6862 &ASTContext::LongDoubleTy, 6863 6864 // Start of integral types. 6865 &ASTContext::IntTy, 6866 &ASTContext::LongTy, 6867 &ASTContext::LongLongTy, 6868 &ASTContext::Int128Ty, 6869 &ASTContext::UnsignedIntTy, 6870 &ASTContext::UnsignedLongTy, 6871 &ASTContext::UnsignedLongLongTy, 6872 &ASTContext::UnsignedInt128Ty, 6873 // End of promoted types. 6874 6875 &ASTContext::BoolTy, 6876 &ASTContext::CharTy, 6877 &ASTContext::WCharTy, 6878 &ASTContext::Char16Ty, 6879 &ASTContext::Char32Ty, 6880 &ASTContext::SignedCharTy, 6881 &ASTContext::ShortTy, 6882 &ASTContext::UnsignedCharTy, 6883 &ASTContext::UnsignedShortTy, 6884 // End of integral types. 6885 // FIXME: What about complex? What about half? 6886 }; 6887 return S.Context.*ArithmeticTypes[index]; 6888 } 6889 6890 /// \brief Gets the canonical type resulting from the usual arithemetic 6891 /// converions for the given arithmetic types. 6892 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 6893 // Accelerator table for performing the usual arithmetic conversions. 6894 // The rules are basically: 6895 // - if either is floating-point, use the wider floating-point 6896 // - if same signedness, use the higher rank 6897 // - if same size, use unsigned of the higher rank 6898 // - use the larger type 6899 // These rules, together with the axiom that higher ranks are 6900 // never smaller, are sufficient to precompute all of these results 6901 // *except* when dealing with signed types of higher rank. 6902 // (we could precompute SLL x UI for all known platforms, but it's 6903 // better not to make any assumptions). 6904 // We assume that int128 has a higher rank than long long on all platforms. 6905 enum PromotedType { 6906 Dep=-1, 6907 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 6908 }; 6909 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 6910 [LastPromotedArithmeticType] = { 6911 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 6912 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 6913 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 6914 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 6915 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 6916 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 6917 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 6918 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 6919 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 6920 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 6921 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 6922 }; 6923 6924 assert(L < LastPromotedArithmeticType); 6925 assert(R < LastPromotedArithmeticType); 6926 int Idx = ConversionsTable[L][R]; 6927 6928 // Fast path: the table gives us a concrete answer. 6929 if (Idx != Dep) return getArithmeticType(Idx); 6930 6931 // Slow path: we need to compare widths. 6932 // An invariant is that the signed type has higher rank. 6933 CanQualType LT = getArithmeticType(L), 6934 RT = getArithmeticType(R); 6935 unsigned LW = S.Context.getIntWidth(LT), 6936 RW = S.Context.getIntWidth(RT); 6937 6938 // If they're different widths, use the signed type. 6939 if (LW > RW) return LT; 6940 else if (LW < RW) return RT; 6941 6942 // Otherwise, use the unsigned type of the signed type's rank. 6943 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 6944 assert(L == SLL || R == SLL); 6945 return S.Context.UnsignedLongLongTy; 6946 } 6947 6948 /// \brief Helper method to factor out the common pattern of adding overloads 6949 /// for '++' and '--' builtin operators. 6950 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 6951 bool HasVolatile, 6952 bool HasRestrict) { 6953 QualType ParamTypes[2] = { 6954 S.Context.getLValueReferenceType(CandidateTy), 6955 S.Context.IntTy 6956 }; 6957 6958 // Non-volatile version. 6959 if (Args.size() == 1) 6960 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6961 else 6962 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6963 6964 // Use a heuristic to reduce number of builtin candidates in the set: 6965 // add volatile version only if there are conversions to a volatile type. 6966 if (HasVolatile) { 6967 ParamTypes[0] = 6968 S.Context.getLValueReferenceType( 6969 S.Context.getVolatileType(CandidateTy)); 6970 if (Args.size() == 1) 6971 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6972 else 6973 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6974 } 6975 6976 // Add restrict version only if there are conversions to a restrict type 6977 // and our candidate type is a non-restrict-qualified pointer. 6978 if (HasRestrict && CandidateTy->isAnyPointerType() && 6979 !CandidateTy.isRestrictQualified()) { 6980 ParamTypes[0] 6981 = S.Context.getLValueReferenceType( 6982 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 6983 if (Args.size() == 1) 6984 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6985 else 6986 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6987 6988 if (HasVolatile) { 6989 ParamTypes[0] 6990 = S.Context.getLValueReferenceType( 6991 S.Context.getCVRQualifiedType(CandidateTy, 6992 (Qualifiers::Volatile | 6993 Qualifiers::Restrict))); 6994 if (Args.size() == 1) 6995 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6996 else 6997 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6998 } 6999 } 7000 7001 } 7002 7003 public: 7004 BuiltinOperatorOverloadBuilder( 7005 Sema &S, ArrayRef<Expr *> Args, 7006 Qualifiers VisibleTypeConversionsQuals, 7007 bool HasArithmeticOrEnumeralCandidateType, 7008 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7009 OverloadCandidateSet &CandidateSet) 7010 : S(S), Args(Args), 7011 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7012 HasArithmeticOrEnumeralCandidateType( 7013 HasArithmeticOrEnumeralCandidateType), 7014 CandidateTypes(CandidateTypes), 7015 CandidateSet(CandidateSet) { 7016 // Validate some of our static helper constants in debug builds. 7017 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7018 "Invalid first promoted integral type"); 7019 assert(getArithmeticType(LastPromotedIntegralType - 1) 7020 == S.Context.UnsignedInt128Ty && 7021 "Invalid last promoted integral type"); 7022 assert(getArithmeticType(FirstPromotedArithmeticType) 7023 == S.Context.FloatTy && 7024 "Invalid first promoted arithmetic type"); 7025 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7026 == S.Context.UnsignedInt128Ty && 7027 "Invalid last promoted arithmetic type"); 7028 } 7029 7030 // C++ [over.built]p3: 7031 // 7032 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7033 // is either volatile or empty, there exist candidate operator 7034 // functions of the form 7035 // 7036 // VQ T& operator++(VQ T&); 7037 // T operator++(VQ T&, int); 7038 // 7039 // C++ [over.built]p4: 7040 // 7041 // For every pair (T, VQ), where T is an arithmetic type other 7042 // than bool, and VQ is either volatile or empty, there exist 7043 // candidate operator functions of the form 7044 // 7045 // VQ T& operator--(VQ T&); 7046 // T operator--(VQ T&, int); 7047 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7048 if (!HasArithmeticOrEnumeralCandidateType) 7049 return; 7050 7051 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7052 Arith < NumArithmeticTypes; ++Arith) { 7053 addPlusPlusMinusMinusStyleOverloads( 7054 getArithmeticType(Arith), 7055 VisibleTypeConversionsQuals.hasVolatile(), 7056 VisibleTypeConversionsQuals.hasRestrict()); 7057 } 7058 } 7059 7060 // C++ [over.built]p5: 7061 // 7062 // For every pair (T, VQ), where T is a cv-qualified or 7063 // cv-unqualified object type, and VQ is either volatile or 7064 // empty, there exist candidate operator functions of the form 7065 // 7066 // T*VQ& operator++(T*VQ&); 7067 // T*VQ& operator--(T*VQ&); 7068 // T* operator++(T*VQ&, int); 7069 // T* operator--(T*VQ&, int); 7070 void addPlusPlusMinusMinusPointerOverloads() { 7071 for (BuiltinCandidateTypeSet::iterator 7072 Ptr = CandidateTypes[0].pointer_begin(), 7073 PtrEnd = CandidateTypes[0].pointer_end(); 7074 Ptr != PtrEnd; ++Ptr) { 7075 // Skip pointer types that aren't pointers to object types. 7076 if (!(*Ptr)->getPointeeType()->isObjectType()) 7077 continue; 7078 7079 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7080 (!(*Ptr).isVolatileQualified() && 7081 VisibleTypeConversionsQuals.hasVolatile()), 7082 (!(*Ptr).isRestrictQualified() && 7083 VisibleTypeConversionsQuals.hasRestrict())); 7084 } 7085 } 7086 7087 // C++ [over.built]p6: 7088 // For every cv-qualified or cv-unqualified object type T, there 7089 // exist candidate operator functions of the form 7090 // 7091 // T& operator*(T*); 7092 // 7093 // C++ [over.built]p7: 7094 // For every function type T that does not have cv-qualifiers or a 7095 // ref-qualifier, there exist candidate operator functions of the form 7096 // T& operator*(T*); 7097 void addUnaryStarPointerOverloads() { 7098 for (BuiltinCandidateTypeSet::iterator 7099 Ptr = CandidateTypes[0].pointer_begin(), 7100 PtrEnd = CandidateTypes[0].pointer_end(); 7101 Ptr != PtrEnd; ++Ptr) { 7102 QualType ParamTy = *Ptr; 7103 QualType PointeeTy = ParamTy->getPointeeType(); 7104 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7105 continue; 7106 7107 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7108 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7109 continue; 7110 7111 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7112 &ParamTy, Args, CandidateSet); 7113 } 7114 } 7115 7116 // C++ [over.built]p9: 7117 // For every promoted arithmetic type T, there exist candidate 7118 // operator functions of the form 7119 // 7120 // T operator+(T); 7121 // T operator-(T); 7122 void addUnaryPlusOrMinusArithmeticOverloads() { 7123 if (!HasArithmeticOrEnumeralCandidateType) 7124 return; 7125 7126 for (unsigned Arith = FirstPromotedArithmeticType; 7127 Arith < LastPromotedArithmeticType; ++Arith) { 7128 QualType ArithTy = getArithmeticType(Arith); 7129 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7130 } 7131 7132 // Extension: We also add these operators for vector types. 7133 for (BuiltinCandidateTypeSet::iterator 7134 Vec = CandidateTypes[0].vector_begin(), 7135 VecEnd = CandidateTypes[0].vector_end(); 7136 Vec != VecEnd; ++Vec) { 7137 QualType VecTy = *Vec; 7138 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7139 } 7140 } 7141 7142 // C++ [over.built]p8: 7143 // For every type T, there exist candidate operator functions of 7144 // the form 7145 // 7146 // T* operator+(T*); 7147 void addUnaryPlusPointerOverloads() { 7148 for (BuiltinCandidateTypeSet::iterator 7149 Ptr = CandidateTypes[0].pointer_begin(), 7150 PtrEnd = CandidateTypes[0].pointer_end(); 7151 Ptr != PtrEnd; ++Ptr) { 7152 QualType ParamTy = *Ptr; 7153 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7154 } 7155 } 7156 7157 // C++ [over.built]p10: 7158 // For every promoted integral type T, there exist candidate 7159 // operator functions of the form 7160 // 7161 // T operator~(T); 7162 void addUnaryTildePromotedIntegralOverloads() { 7163 if (!HasArithmeticOrEnumeralCandidateType) 7164 return; 7165 7166 for (unsigned Int = FirstPromotedIntegralType; 7167 Int < LastPromotedIntegralType; ++Int) { 7168 QualType IntTy = getArithmeticType(Int); 7169 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7170 } 7171 7172 // Extension: We also add this operator for vector types. 7173 for (BuiltinCandidateTypeSet::iterator 7174 Vec = CandidateTypes[0].vector_begin(), 7175 VecEnd = CandidateTypes[0].vector_end(); 7176 Vec != VecEnd; ++Vec) { 7177 QualType VecTy = *Vec; 7178 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7179 } 7180 } 7181 7182 // C++ [over.match.oper]p16: 7183 // For every pointer to member type T, there exist candidate operator 7184 // functions of the form 7185 // 7186 // bool operator==(T,T); 7187 // bool operator!=(T,T); 7188 void addEqualEqualOrNotEqualMemberPointerOverloads() { 7189 /// Set of (canonical) types that we've already handled. 7190 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7191 7192 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7193 for (BuiltinCandidateTypeSet::iterator 7194 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7195 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7196 MemPtr != MemPtrEnd; 7197 ++MemPtr) { 7198 // Don't add the same builtin candidate twice. 7199 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7200 continue; 7201 7202 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7203 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7204 } 7205 } 7206 } 7207 7208 // C++ [over.built]p15: 7209 // 7210 // For every T, where T is an enumeration type, a pointer type, or 7211 // std::nullptr_t, there exist candidate operator functions of the form 7212 // 7213 // bool operator<(T, T); 7214 // bool operator>(T, T); 7215 // bool operator<=(T, T); 7216 // bool operator>=(T, T); 7217 // bool operator==(T, T); 7218 // bool operator!=(T, T); 7219 void addRelationalPointerOrEnumeralOverloads() { 7220 // C++ [over.match.oper]p3: 7221 // [...]the built-in candidates include all of the candidate operator 7222 // functions defined in 13.6 that, compared to the given operator, [...] 7223 // do not have the same parameter-type-list as any non-template non-member 7224 // candidate. 7225 // 7226 // Note that in practice, this only affects enumeration types because there 7227 // aren't any built-in candidates of record type, and a user-defined operator 7228 // must have an operand of record or enumeration type. Also, the only other 7229 // overloaded operator with enumeration arguments, operator=, 7230 // cannot be overloaded for enumeration types, so this is the only place 7231 // where we must suppress candidates like this. 7232 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7233 UserDefinedBinaryOperators; 7234 7235 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7236 if (CandidateTypes[ArgIdx].enumeration_begin() != 7237 CandidateTypes[ArgIdx].enumeration_end()) { 7238 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7239 CEnd = CandidateSet.end(); 7240 C != CEnd; ++C) { 7241 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7242 continue; 7243 7244 if (C->Function->isFunctionTemplateSpecialization()) 7245 continue; 7246 7247 QualType FirstParamType = 7248 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7249 QualType SecondParamType = 7250 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7251 7252 // Skip if either parameter isn't of enumeral type. 7253 if (!FirstParamType->isEnumeralType() || 7254 !SecondParamType->isEnumeralType()) 7255 continue; 7256 7257 // Add this operator to the set of known user-defined operators. 7258 UserDefinedBinaryOperators.insert( 7259 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7260 S.Context.getCanonicalType(SecondParamType))); 7261 } 7262 } 7263 } 7264 7265 /// Set of (canonical) types that we've already handled. 7266 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7267 7268 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7269 for (BuiltinCandidateTypeSet::iterator 7270 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7271 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7272 Ptr != PtrEnd; ++Ptr) { 7273 // Don't add the same builtin candidate twice. 7274 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7275 continue; 7276 7277 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7278 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7279 } 7280 for (BuiltinCandidateTypeSet::iterator 7281 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7282 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7283 Enum != EnumEnd; ++Enum) { 7284 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7285 7286 // Don't add the same builtin candidate twice, or if a user defined 7287 // candidate exists. 7288 if (!AddedTypes.insert(CanonType) || 7289 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7290 CanonType))) 7291 continue; 7292 7293 QualType ParamTypes[2] = { *Enum, *Enum }; 7294 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7295 } 7296 7297 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7298 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7299 if (AddedTypes.insert(NullPtrTy) && 7300 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7301 NullPtrTy))) { 7302 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7303 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7304 CandidateSet); 7305 } 7306 } 7307 } 7308 } 7309 7310 // C++ [over.built]p13: 7311 // 7312 // For every cv-qualified or cv-unqualified object type T 7313 // there exist candidate operator functions of the form 7314 // 7315 // T* operator+(T*, ptrdiff_t); 7316 // T& operator[](T*, ptrdiff_t); [BELOW] 7317 // T* operator-(T*, ptrdiff_t); 7318 // T* operator+(ptrdiff_t, T*); 7319 // T& operator[](ptrdiff_t, T*); [BELOW] 7320 // 7321 // C++ [over.built]p14: 7322 // 7323 // For every T, where T is a pointer to object type, there 7324 // exist candidate operator functions of the form 7325 // 7326 // ptrdiff_t operator-(T, T); 7327 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7328 /// Set of (canonical) types that we've already handled. 7329 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7330 7331 for (int Arg = 0; Arg < 2; ++Arg) { 7332 QualType AsymetricParamTypes[2] = { 7333 S.Context.getPointerDiffType(), 7334 S.Context.getPointerDiffType(), 7335 }; 7336 for (BuiltinCandidateTypeSet::iterator 7337 Ptr = CandidateTypes[Arg].pointer_begin(), 7338 PtrEnd = CandidateTypes[Arg].pointer_end(); 7339 Ptr != PtrEnd; ++Ptr) { 7340 QualType PointeeTy = (*Ptr)->getPointeeType(); 7341 if (!PointeeTy->isObjectType()) 7342 continue; 7343 7344 AsymetricParamTypes[Arg] = *Ptr; 7345 if (Arg == 0 || Op == OO_Plus) { 7346 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7347 // T* operator+(ptrdiff_t, T*); 7348 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet); 7349 } 7350 if (Op == OO_Minus) { 7351 // ptrdiff_t operator-(T, T); 7352 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7353 continue; 7354 7355 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7356 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7357 Args, CandidateSet); 7358 } 7359 } 7360 } 7361 } 7362 7363 // C++ [over.built]p12: 7364 // 7365 // For every pair of promoted arithmetic types L and R, there 7366 // exist candidate operator functions of the form 7367 // 7368 // LR operator*(L, R); 7369 // LR operator/(L, R); 7370 // LR operator+(L, R); 7371 // LR operator-(L, R); 7372 // bool operator<(L, R); 7373 // bool operator>(L, R); 7374 // bool operator<=(L, R); 7375 // bool operator>=(L, R); 7376 // bool operator==(L, R); 7377 // bool operator!=(L, R); 7378 // 7379 // where LR is the result of the usual arithmetic conversions 7380 // between types L and R. 7381 // 7382 // C++ [over.built]p24: 7383 // 7384 // For every pair of promoted arithmetic types L and R, there exist 7385 // candidate operator functions of the form 7386 // 7387 // LR operator?(bool, L, R); 7388 // 7389 // where LR is the result of the usual arithmetic conversions 7390 // between types L and R. 7391 // Our candidates ignore the first parameter. 7392 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7393 if (!HasArithmeticOrEnumeralCandidateType) 7394 return; 7395 7396 for (unsigned Left = FirstPromotedArithmeticType; 7397 Left < LastPromotedArithmeticType; ++Left) { 7398 for (unsigned Right = FirstPromotedArithmeticType; 7399 Right < LastPromotedArithmeticType; ++Right) { 7400 QualType LandR[2] = { getArithmeticType(Left), 7401 getArithmeticType(Right) }; 7402 QualType Result = 7403 isComparison ? S.Context.BoolTy 7404 : getUsualArithmeticConversions(Left, Right); 7405 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7406 } 7407 } 7408 7409 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7410 // conditional operator for vector types. 7411 for (BuiltinCandidateTypeSet::iterator 7412 Vec1 = CandidateTypes[0].vector_begin(), 7413 Vec1End = CandidateTypes[0].vector_end(); 7414 Vec1 != Vec1End; ++Vec1) { 7415 for (BuiltinCandidateTypeSet::iterator 7416 Vec2 = CandidateTypes[1].vector_begin(), 7417 Vec2End = CandidateTypes[1].vector_end(); 7418 Vec2 != Vec2End; ++Vec2) { 7419 QualType LandR[2] = { *Vec1, *Vec2 }; 7420 QualType Result = S.Context.BoolTy; 7421 if (!isComparison) { 7422 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7423 Result = *Vec1; 7424 else 7425 Result = *Vec2; 7426 } 7427 7428 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7429 } 7430 } 7431 } 7432 7433 // C++ [over.built]p17: 7434 // 7435 // For every pair of promoted integral types L and R, there 7436 // exist candidate operator functions of the form 7437 // 7438 // LR operator%(L, R); 7439 // LR operator&(L, R); 7440 // LR operator^(L, R); 7441 // LR operator|(L, R); 7442 // L operator<<(L, R); 7443 // L operator>>(L, R); 7444 // 7445 // where LR is the result of the usual arithmetic conversions 7446 // between types L and R. 7447 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7448 if (!HasArithmeticOrEnumeralCandidateType) 7449 return; 7450 7451 for (unsigned Left = FirstPromotedIntegralType; 7452 Left < LastPromotedIntegralType; ++Left) { 7453 for (unsigned Right = FirstPromotedIntegralType; 7454 Right < LastPromotedIntegralType; ++Right) { 7455 QualType LandR[2] = { getArithmeticType(Left), 7456 getArithmeticType(Right) }; 7457 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7458 ? LandR[0] 7459 : getUsualArithmeticConversions(Left, Right); 7460 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7461 } 7462 } 7463 } 7464 7465 // C++ [over.built]p20: 7466 // 7467 // For every pair (T, VQ), where T is an enumeration or 7468 // pointer to member type and VQ is either volatile or 7469 // empty, there exist candidate operator functions of the form 7470 // 7471 // VQ T& operator=(VQ T&, T); 7472 void addAssignmentMemberPointerOrEnumeralOverloads() { 7473 /// Set of (canonical) types that we've already handled. 7474 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7475 7476 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7477 for (BuiltinCandidateTypeSet::iterator 7478 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7479 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7480 Enum != EnumEnd; ++Enum) { 7481 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7482 continue; 7483 7484 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7485 } 7486 7487 for (BuiltinCandidateTypeSet::iterator 7488 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7489 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7490 MemPtr != MemPtrEnd; ++MemPtr) { 7491 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7492 continue; 7493 7494 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7495 } 7496 } 7497 } 7498 7499 // C++ [over.built]p19: 7500 // 7501 // For every pair (T, VQ), where T is any type and VQ is either 7502 // volatile or empty, there exist candidate operator functions 7503 // of the form 7504 // 7505 // T*VQ& operator=(T*VQ&, T*); 7506 // 7507 // C++ [over.built]p21: 7508 // 7509 // For every pair (T, VQ), where T is a cv-qualified or 7510 // cv-unqualified object type and VQ is either volatile or 7511 // empty, there exist candidate operator functions of the form 7512 // 7513 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7514 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7515 void addAssignmentPointerOverloads(bool isEqualOp) { 7516 /// Set of (canonical) types that we've already handled. 7517 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7518 7519 for (BuiltinCandidateTypeSet::iterator 7520 Ptr = CandidateTypes[0].pointer_begin(), 7521 PtrEnd = CandidateTypes[0].pointer_end(); 7522 Ptr != PtrEnd; ++Ptr) { 7523 // If this is operator=, keep track of the builtin candidates we added. 7524 if (isEqualOp) 7525 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7526 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7527 continue; 7528 7529 // non-volatile version 7530 QualType ParamTypes[2] = { 7531 S.Context.getLValueReferenceType(*Ptr), 7532 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7533 }; 7534 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7535 /*IsAssigmentOperator=*/ isEqualOp); 7536 7537 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7538 VisibleTypeConversionsQuals.hasVolatile(); 7539 if (NeedVolatile) { 7540 // volatile version 7541 ParamTypes[0] = 7542 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7543 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7544 /*IsAssigmentOperator=*/isEqualOp); 7545 } 7546 7547 if (!(*Ptr).isRestrictQualified() && 7548 VisibleTypeConversionsQuals.hasRestrict()) { 7549 // restrict version 7550 ParamTypes[0] 7551 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7552 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7553 /*IsAssigmentOperator=*/isEqualOp); 7554 7555 if (NeedVolatile) { 7556 // volatile restrict version 7557 ParamTypes[0] 7558 = S.Context.getLValueReferenceType( 7559 S.Context.getCVRQualifiedType(*Ptr, 7560 (Qualifiers::Volatile | 7561 Qualifiers::Restrict))); 7562 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7563 /*IsAssigmentOperator=*/isEqualOp); 7564 } 7565 } 7566 } 7567 7568 if (isEqualOp) { 7569 for (BuiltinCandidateTypeSet::iterator 7570 Ptr = CandidateTypes[1].pointer_begin(), 7571 PtrEnd = CandidateTypes[1].pointer_end(); 7572 Ptr != PtrEnd; ++Ptr) { 7573 // Make sure we don't add the same candidate twice. 7574 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7575 continue; 7576 7577 QualType ParamTypes[2] = { 7578 S.Context.getLValueReferenceType(*Ptr), 7579 *Ptr, 7580 }; 7581 7582 // non-volatile version 7583 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7584 /*IsAssigmentOperator=*/true); 7585 7586 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7587 VisibleTypeConversionsQuals.hasVolatile(); 7588 if (NeedVolatile) { 7589 // volatile version 7590 ParamTypes[0] = 7591 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7592 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7593 /*IsAssigmentOperator=*/true); 7594 } 7595 7596 if (!(*Ptr).isRestrictQualified() && 7597 VisibleTypeConversionsQuals.hasRestrict()) { 7598 // restrict version 7599 ParamTypes[0] 7600 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7601 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7602 /*IsAssigmentOperator=*/true); 7603 7604 if (NeedVolatile) { 7605 // volatile restrict version 7606 ParamTypes[0] 7607 = S.Context.getLValueReferenceType( 7608 S.Context.getCVRQualifiedType(*Ptr, 7609 (Qualifiers::Volatile | 7610 Qualifiers::Restrict))); 7611 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7612 /*IsAssigmentOperator=*/true); 7613 } 7614 } 7615 } 7616 } 7617 } 7618 7619 // C++ [over.built]p18: 7620 // 7621 // For every triple (L, VQ, R), where L is an arithmetic type, 7622 // VQ is either volatile or empty, and R is a promoted 7623 // arithmetic type, there exist candidate operator functions of 7624 // the form 7625 // 7626 // VQ L& operator=(VQ L&, R); 7627 // VQ L& operator*=(VQ L&, R); 7628 // VQ L& operator/=(VQ L&, R); 7629 // VQ L& operator+=(VQ L&, R); 7630 // VQ L& operator-=(VQ L&, R); 7631 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7632 if (!HasArithmeticOrEnumeralCandidateType) 7633 return; 7634 7635 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7636 for (unsigned Right = FirstPromotedArithmeticType; 7637 Right < LastPromotedArithmeticType; ++Right) { 7638 QualType ParamTypes[2]; 7639 ParamTypes[1] = getArithmeticType(Right); 7640 7641 // Add this built-in operator as a candidate (VQ is empty). 7642 ParamTypes[0] = 7643 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7644 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7645 /*IsAssigmentOperator=*/isEqualOp); 7646 7647 // Add this built-in operator as a candidate (VQ is 'volatile'). 7648 if (VisibleTypeConversionsQuals.hasVolatile()) { 7649 ParamTypes[0] = 7650 S.Context.getVolatileType(getArithmeticType(Left)); 7651 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7652 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7653 /*IsAssigmentOperator=*/isEqualOp); 7654 } 7655 } 7656 } 7657 7658 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7659 for (BuiltinCandidateTypeSet::iterator 7660 Vec1 = CandidateTypes[0].vector_begin(), 7661 Vec1End = CandidateTypes[0].vector_end(); 7662 Vec1 != Vec1End; ++Vec1) { 7663 for (BuiltinCandidateTypeSet::iterator 7664 Vec2 = CandidateTypes[1].vector_begin(), 7665 Vec2End = CandidateTypes[1].vector_end(); 7666 Vec2 != Vec2End; ++Vec2) { 7667 QualType ParamTypes[2]; 7668 ParamTypes[1] = *Vec2; 7669 // Add this built-in operator as a candidate (VQ is empty). 7670 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7671 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7672 /*IsAssigmentOperator=*/isEqualOp); 7673 7674 // Add this built-in operator as a candidate (VQ is 'volatile'). 7675 if (VisibleTypeConversionsQuals.hasVolatile()) { 7676 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7677 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7678 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7679 /*IsAssigmentOperator=*/isEqualOp); 7680 } 7681 } 7682 } 7683 } 7684 7685 // C++ [over.built]p22: 7686 // 7687 // For every triple (L, VQ, R), where L is an integral type, VQ 7688 // is either volatile or empty, and R is a promoted integral 7689 // type, there exist candidate operator functions of the form 7690 // 7691 // VQ L& operator%=(VQ L&, R); 7692 // VQ L& operator<<=(VQ L&, R); 7693 // VQ L& operator>>=(VQ L&, R); 7694 // VQ L& operator&=(VQ L&, R); 7695 // VQ L& operator^=(VQ L&, R); 7696 // VQ L& operator|=(VQ L&, R); 7697 void addAssignmentIntegralOverloads() { 7698 if (!HasArithmeticOrEnumeralCandidateType) 7699 return; 7700 7701 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7702 for (unsigned Right = FirstPromotedIntegralType; 7703 Right < LastPromotedIntegralType; ++Right) { 7704 QualType ParamTypes[2]; 7705 ParamTypes[1] = getArithmeticType(Right); 7706 7707 // Add this built-in operator as a candidate (VQ is empty). 7708 ParamTypes[0] = 7709 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7710 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7711 if (VisibleTypeConversionsQuals.hasVolatile()) { 7712 // Add this built-in operator as a candidate (VQ is 'volatile'). 7713 ParamTypes[0] = getArithmeticType(Left); 7714 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7715 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7716 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7717 } 7718 } 7719 } 7720 } 7721 7722 // C++ [over.operator]p23: 7723 // 7724 // There also exist candidate operator functions of the form 7725 // 7726 // bool operator!(bool); 7727 // bool operator&&(bool, bool); 7728 // bool operator||(bool, bool); 7729 void addExclaimOverload() { 7730 QualType ParamTy = S.Context.BoolTy; 7731 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 7732 /*IsAssignmentOperator=*/false, 7733 /*NumContextualBoolArguments=*/1); 7734 } 7735 void addAmpAmpOrPipePipeOverload() { 7736 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7737 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 7738 /*IsAssignmentOperator=*/false, 7739 /*NumContextualBoolArguments=*/2); 7740 } 7741 7742 // C++ [over.built]p13: 7743 // 7744 // For every cv-qualified or cv-unqualified object type T there 7745 // exist candidate operator functions of the form 7746 // 7747 // T* operator+(T*, ptrdiff_t); [ABOVE] 7748 // T& operator[](T*, ptrdiff_t); 7749 // T* operator-(T*, ptrdiff_t); [ABOVE] 7750 // T* operator+(ptrdiff_t, T*); [ABOVE] 7751 // T& operator[](ptrdiff_t, T*); 7752 void addSubscriptOverloads() { 7753 for (BuiltinCandidateTypeSet::iterator 7754 Ptr = CandidateTypes[0].pointer_begin(), 7755 PtrEnd = CandidateTypes[0].pointer_end(); 7756 Ptr != PtrEnd; ++Ptr) { 7757 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7758 QualType PointeeType = (*Ptr)->getPointeeType(); 7759 if (!PointeeType->isObjectType()) 7760 continue; 7761 7762 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7763 7764 // T& operator[](T*, ptrdiff_t) 7765 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7766 } 7767 7768 for (BuiltinCandidateTypeSet::iterator 7769 Ptr = CandidateTypes[1].pointer_begin(), 7770 PtrEnd = CandidateTypes[1].pointer_end(); 7771 Ptr != PtrEnd; ++Ptr) { 7772 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7773 QualType PointeeType = (*Ptr)->getPointeeType(); 7774 if (!PointeeType->isObjectType()) 7775 continue; 7776 7777 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7778 7779 // T& operator[](ptrdiff_t, T*) 7780 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7781 } 7782 } 7783 7784 // C++ [over.built]p11: 7785 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7786 // C1 is the same type as C2 or is a derived class of C2, T is an object 7787 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7788 // there exist candidate operator functions of the form 7789 // 7790 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7791 // 7792 // where CV12 is the union of CV1 and CV2. 7793 void addArrowStarOverloads() { 7794 for (BuiltinCandidateTypeSet::iterator 7795 Ptr = CandidateTypes[0].pointer_begin(), 7796 PtrEnd = CandidateTypes[0].pointer_end(); 7797 Ptr != PtrEnd; ++Ptr) { 7798 QualType C1Ty = (*Ptr); 7799 QualType C1; 7800 QualifierCollector Q1; 7801 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 7802 if (!isa<RecordType>(C1)) 7803 continue; 7804 // heuristic to reduce number of builtin candidates in the set. 7805 // Add volatile/restrict version only if there are conversions to a 7806 // volatile/restrict type. 7807 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 7808 continue; 7809 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 7810 continue; 7811 for (BuiltinCandidateTypeSet::iterator 7812 MemPtr = CandidateTypes[1].member_pointer_begin(), 7813 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 7814 MemPtr != MemPtrEnd; ++MemPtr) { 7815 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 7816 QualType C2 = QualType(mptr->getClass(), 0); 7817 C2 = C2.getUnqualifiedType(); 7818 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 7819 break; 7820 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 7821 // build CV12 T& 7822 QualType T = mptr->getPointeeType(); 7823 if (!VisibleTypeConversionsQuals.hasVolatile() && 7824 T.isVolatileQualified()) 7825 continue; 7826 if (!VisibleTypeConversionsQuals.hasRestrict() && 7827 T.isRestrictQualified()) 7828 continue; 7829 T = Q1.apply(S.Context, T); 7830 QualType ResultTy = S.Context.getLValueReferenceType(T); 7831 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7832 } 7833 } 7834 } 7835 7836 // Note that we don't consider the first argument, since it has been 7837 // contextually converted to bool long ago. The candidates below are 7838 // therefore added as binary. 7839 // 7840 // C++ [over.built]p25: 7841 // For every type T, where T is a pointer, pointer-to-member, or scoped 7842 // enumeration type, there exist candidate operator functions of the form 7843 // 7844 // T operator?(bool, T, T); 7845 // 7846 void addConditionalOperatorOverloads() { 7847 /// Set of (canonical) types that we've already handled. 7848 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7849 7850 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7851 for (BuiltinCandidateTypeSet::iterator 7852 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7853 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7854 Ptr != PtrEnd; ++Ptr) { 7855 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7856 continue; 7857 7858 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7859 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 7860 } 7861 7862 for (BuiltinCandidateTypeSet::iterator 7863 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7864 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7865 MemPtr != MemPtrEnd; ++MemPtr) { 7866 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7867 continue; 7868 7869 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7870 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 7871 } 7872 7873 if (S.getLangOpts().CPlusPlus11) { 7874 for (BuiltinCandidateTypeSet::iterator 7875 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7876 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7877 Enum != EnumEnd; ++Enum) { 7878 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 7879 continue; 7880 7881 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7882 continue; 7883 7884 QualType ParamTypes[2] = { *Enum, *Enum }; 7885 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 7886 } 7887 } 7888 } 7889 } 7890 }; 7891 7892 } // end anonymous namespace 7893 7894 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 7895 /// operator overloads to the candidate set (C++ [over.built]), based 7896 /// on the operator @p Op and the arguments given. For example, if the 7897 /// operator is a binary '+', this routine might add "int 7898 /// operator+(int, int)" to cover integer addition. 7899 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 7900 SourceLocation OpLoc, 7901 ArrayRef<Expr *> Args, 7902 OverloadCandidateSet &CandidateSet) { 7903 // Find all of the types that the arguments can convert to, but only 7904 // if the operator we're looking at has built-in operator candidates 7905 // that make use of these types. Also record whether we encounter non-record 7906 // candidate types or either arithmetic or enumeral candidate types. 7907 Qualifiers VisibleTypeConversionsQuals; 7908 VisibleTypeConversionsQuals.addConst(); 7909 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 7910 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 7911 7912 bool HasNonRecordCandidateType = false; 7913 bool HasArithmeticOrEnumeralCandidateType = false; 7914 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 7915 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7916 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 7917 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 7918 OpLoc, 7919 true, 7920 (Op == OO_Exclaim || 7921 Op == OO_AmpAmp || 7922 Op == OO_PipePipe), 7923 VisibleTypeConversionsQuals); 7924 HasNonRecordCandidateType = HasNonRecordCandidateType || 7925 CandidateTypes[ArgIdx].hasNonRecordTypes(); 7926 HasArithmeticOrEnumeralCandidateType = 7927 HasArithmeticOrEnumeralCandidateType || 7928 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 7929 } 7930 7931 // Exit early when no non-record types have been added to the candidate set 7932 // for any of the arguments to the operator. 7933 // 7934 // We can't exit early for !, ||, or &&, since there we have always have 7935 // 'bool' overloads. 7936 if (!HasNonRecordCandidateType && 7937 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 7938 return; 7939 7940 // Setup an object to manage the common state for building overloads. 7941 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 7942 VisibleTypeConversionsQuals, 7943 HasArithmeticOrEnumeralCandidateType, 7944 CandidateTypes, CandidateSet); 7945 7946 // Dispatch over the operation to add in only those overloads which apply. 7947 switch (Op) { 7948 case OO_None: 7949 case NUM_OVERLOADED_OPERATORS: 7950 llvm_unreachable("Expected an overloaded operator"); 7951 7952 case OO_New: 7953 case OO_Delete: 7954 case OO_Array_New: 7955 case OO_Array_Delete: 7956 case OO_Call: 7957 llvm_unreachable( 7958 "Special operators don't use AddBuiltinOperatorCandidates"); 7959 7960 case OO_Comma: 7961 case OO_Arrow: 7962 // C++ [over.match.oper]p3: 7963 // -- For the operator ',', the unary operator '&', or the 7964 // operator '->', the built-in candidates set is empty. 7965 break; 7966 7967 case OO_Plus: // '+' is either unary or binary 7968 if (Args.size() == 1) 7969 OpBuilder.addUnaryPlusPointerOverloads(); 7970 // Fall through. 7971 7972 case OO_Minus: // '-' is either unary or binary 7973 if (Args.size() == 1) { 7974 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 7975 } else { 7976 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 7977 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7978 } 7979 break; 7980 7981 case OO_Star: // '*' is either unary or binary 7982 if (Args.size() == 1) 7983 OpBuilder.addUnaryStarPointerOverloads(); 7984 else 7985 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7986 break; 7987 7988 case OO_Slash: 7989 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7990 break; 7991 7992 case OO_PlusPlus: 7993 case OO_MinusMinus: 7994 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 7995 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 7996 break; 7997 7998 case OO_EqualEqual: 7999 case OO_ExclaimEqual: 8000 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 8001 // Fall through. 8002 8003 case OO_Less: 8004 case OO_Greater: 8005 case OO_LessEqual: 8006 case OO_GreaterEqual: 8007 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8008 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8009 break; 8010 8011 case OO_Percent: 8012 case OO_Caret: 8013 case OO_Pipe: 8014 case OO_LessLess: 8015 case OO_GreaterGreater: 8016 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8017 break; 8018 8019 case OO_Amp: // '&' is either unary or binary 8020 if (Args.size() == 1) 8021 // C++ [over.match.oper]p3: 8022 // -- For the operator ',', the unary operator '&', or the 8023 // operator '->', the built-in candidates set is empty. 8024 break; 8025 8026 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8027 break; 8028 8029 case OO_Tilde: 8030 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8031 break; 8032 8033 case OO_Equal: 8034 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8035 // Fall through. 8036 8037 case OO_PlusEqual: 8038 case OO_MinusEqual: 8039 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8040 // Fall through. 8041 8042 case OO_StarEqual: 8043 case OO_SlashEqual: 8044 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8045 break; 8046 8047 case OO_PercentEqual: 8048 case OO_LessLessEqual: 8049 case OO_GreaterGreaterEqual: 8050 case OO_AmpEqual: 8051 case OO_CaretEqual: 8052 case OO_PipeEqual: 8053 OpBuilder.addAssignmentIntegralOverloads(); 8054 break; 8055 8056 case OO_Exclaim: 8057 OpBuilder.addExclaimOverload(); 8058 break; 8059 8060 case OO_AmpAmp: 8061 case OO_PipePipe: 8062 OpBuilder.addAmpAmpOrPipePipeOverload(); 8063 break; 8064 8065 case OO_Subscript: 8066 OpBuilder.addSubscriptOverloads(); 8067 break; 8068 8069 case OO_ArrowStar: 8070 OpBuilder.addArrowStarOverloads(); 8071 break; 8072 8073 case OO_Conditional: 8074 OpBuilder.addConditionalOperatorOverloads(); 8075 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8076 break; 8077 } 8078 } 8079 8080 /// \brief Add function candidates found via argument-dependent lookup 8081 /// to the set of overloading candidates. 8082 /// 8083 /// This routine performs argument-dependent name lookup based on the 8084 /// given function name (which may also be an operator name) and adds 8085 /// all of the overload candidates found by ADL to the overload 8086 /// candidate set (C++ [basic.lookup.argdep]). 8087 void 8088 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8089 bool Operator, SourceLocation Loc, 8090 ArrayRef<Expr *> Args, 8091 TemplateArgumentListInfo *ExplicitTemplateArgs, 8092 OverloadCandidateSet& CandidateSet, 8093 bool PartialOverloading) { 8094 ADLResult Fns; 8095 8096 // FIXME: This approach for uniquing ADL results (and removing 8097 // redundant candidates from the set) relies on pointer-equality, 8098 // which means we need to key off the canonical decl. However, 8099 // always going back to the canonical decl might not get us the 8100 // right set of default arguments. What default arguments are 8101 // we supposed to consider on ADL candidates, anyway? 8102 8103 // FIXME: Pass in the explicit template arguments? 8104 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns); 8105 8106 // Erase all of the candidates we already knew about. 8107 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8108 CandEnd = CandidateSet.end(); 8109 Cand != CandEnd; ++Cand) 8110 if (Cand->Function) { 8111 Fns.erase(Cand->Function); 8112 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8113 Fns.erase(FunTmpl); 8114 } 8115 8116 // For each of the ADL candidates we found, add it to the overload 8117 // set. 8118 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8119 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8120 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8121 if (ExplicitTemplateArgs) 8122 continue; 8123 8124 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8125 PartialOverloading); 8126 } else 8127 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8128 FoundDecl, ExplicitTemplateArgs, 8129 Args, CandidateSet); 8130 } 8131 } 8132 8133 /// isBetterOverloadCandidate - Determines whether the first overload 8134 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8135 bool 8136 isBetterOverloadCandidate(Sema &S, 8137 const OverloadCandidate &Cand1, 8138 const OverloadCandidate &Cand2, 8139 SourceLocation Loc, 8140 bool UserDefinedConversion) { 8141 // Define viable functions to be better candidates than non-viable 8142 // functions. 8143 if (!Cand2.Viable) 8144 return Cand1.Viable; 8145 else if (!Cand1.Viable) 8146 return false; 8147 8148 // C++ [over.match.best]p1: 8149 // 8150 // -- if F is a static member function, ICS1(F) is defined such 8151 // that ICS1(F) is neither better nor worse than ICS1(G) for 8152 // any function G, and, symmetrically, ICS1(G) is neither 8153 // better nor worse than ICS1(F). 8154 unsigned StartArg = 0; 8155 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8156 StartArg = 1; 8157 8158 // C++ [over.match.best]p1: 8159 // A viable function F1 is defined to be a better function than another 8160 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8161 // conversion sequence than ICSi(F2), and then... 8162 unsigned NumArgs = Cand1.NumConversions; 8163 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8164 bool HasBetterConversion = false; 8165 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8166 switch (CompareImplicitConversionSequences(S, 8167 Cand1.Conversions[ArgIdx], 8168 Cand2.Conversions[ArgIdx])) { 8169 case ImplicitConversionSequence::Better: 8170 // Cand1 has a better conversion sequence. 8171 HasBetterConversion = true; 8172 break; 8173 8174 case ImplicitConversionSequence::Worse: 8175 // Cand1 can't be better than Cand2. 8176 return false; 8177 8178 case ImplicitConversionSequence::Indistinguishable: 8179 // Do nothing. 8180 break; 8181 } 8182 } 8183 8184 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8185 // ICSj(F2), or, if not that, 8186 if (HasBetterConversion) 8187 return true; 8188 8189 // - F1 is a non-template function and F2 is a function template 8190 // specialization, or, if not that, 8191 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 8192 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 8193 return true; 8194 8195 // -- F1 and F2 are function template specializations, and the function 8196 // template for F1 is more specialized than the template for F2 8197 // according to the partial ordering rules described in 14.5.5.2, or, 8198 // if not that, 8199 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 8200 Cand2.Function && Cand2.Function->getPrimaryTemplate()) { 8201 if (FunctionTemplateDecl *BetterTemplate 8202 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8203 Cand2.Function->getPrimaryTemplate(), 8204 Loc, 8205 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8206 : TPOC_Call, 8207 Cand1.ExplicitCallArguments, 8208 Cand2.ExplicitCallArguments)) 8209 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8210 } 8211 8212 // -- the context is an initialization by user-defined conversion 8213 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8214 // from the return type of F1 to the destination type (i.e., 8215 // the type of the entity being initialized) is a better 8216 // conversion sequence than the standard conversion sequence 8217 // from the return type of F2 to the destination type. 8218 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8219 isa<CXXConversionDecl>(Cand1.Function) && 8220 isa<CXXConversionDecl>(Cand2.Function)) { 8221 // First check whether we prefer one of the conversion functions over the 8222 // other. This only distinguishes the results in non-standard, extension 8223 // cases such as the conversion from a lambda closure type to a function 8224 // pointer or block. 8225 ImplicitConversionSequence::CompareKind FuncResult 8226 = compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8227 if (FuncResult != ImplicitConversionSequence::Indistinguishable) 8228 return FuncResult; 8229 8230 switch (CompareStandardConversionSequences(S, 8231 Cand1.FinalConversion, 8232 Cand2.FinalConversion)) { 8233 case ImplicitConversionSequence::Better: 8234 // Cand1 has a better conversion sequence. 8235 return true; 8236 8237 case ImplicitConversionSequence::Worse: 8238 // Cand1 can't be better than Cand2. 8239 return false; 8240 8241 case ImplicitConversionSequence::Indistinguishable: 8242 // Do nothing 8243 break; 8244 } 8245 } 8246 8247 // Check for enable_if value-based overload resolution. 8248 if (Cand1.Function && Cand2.Function && 8249 (Cand1.Function->hasAttr<EnableIfAttr>() || 8250 Cand2.Function->hasAttr<EnableIfAttr>())) { 8251 // FIXME: The next several lines are just 8252 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8253 // instead of reverse order which is how they're stored in the AST. 8254 AttrVec Cand1Attrs; 8255 AttrVec::iterator Cand1E = Cand1Attrs.end(); 8256 if (Cand1.Function->hasAttrs()) { 8257 Cand1Attrs = Cand1.Function->getAttrs(); 8258 Cand1E = std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(), 8259 IsNotEnableIfAttr); 8260 std::reverse(Cand1Attrs.begin(), Cand1E); 8261 } 8262 8263 AttrVec Cand2Attrs; 8264 AttrVec::iterator Cand2E = Cand2Attrs.end(); 8265 if (Cand2.Function->hasAttrs()) { 8266 Cand2Attrs = Cand2.Function->getAttrs(); 8267 Cand2E = std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(), 8268 IsNotEnableIfAttr); 8269 std::reverse(Cand2Attrs.begin(), Cand2E); 8270 } 8271 for (AttrVec::iterator 8272 Cand1I = Cand1Attrs.begin(), Cand2I = Cand2Attrs.begin(); 8273 Cand1I != Cand1E || Cand2I != Cand2E; ++Cand1I, ++Cand2I) { 8274 if (Cand1I == Cand1E) 8275 return false; 8276 if (Cand2I == Cand2E) 8277 return true; 8278 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8279 cast<EnableIfAttr>(*Cand1I)->getCond()->Profile(Cand1ID, 8280 S.getASTContext(), true); 8281 cast<EnableIfAttr>(*Cand2I)->getCond()->Profile(Cand2ID, 8282 S.getASTContext(), true); 8283 if (Cand1ID != Cand2ID) 8284 return false; 8285 } 8286 } 8287 8288 return false; 8289 } 8290 8291 /// \brief Computes the best viable function (C++ 13.3.3) 8292 /// within an overload candidate set. 8293 /// 8294 /// \param Loc The location of the function name (or operator symbol) for 8295 /// which overload resolution occurs. 8296 /// 8297 /// \param Best If overload resolution was successful or found a deleted 8298 /// function, \p Best points to the candidate function found. 8299 /// 8300 /// \returns The result of overload resolution. 8301 OverloadingResult 8302 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8303 iterator &Best, 8304 bool UserDefinedConversion) { 8305 // Find the best viable function. 8306 Best = end(); 8307 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8308 if (Cand->Viable) 8309 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8310 UserDefinedConversion)) 8311 Best = Cand; 8312 } 8313 8314 // If we didn't find any viable functions, abort. 8315 if (Best == end()) 8316 return OR_No_Viable_Function; 8317 8318 // Make sure that this function is better than every other viable 8319 // function. If not, we have an ambiguity. 8320 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8321 if (Cand->Viable && 8322 Cand != Best && 8323 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8324 UserDefinedConversion)) { 8325 Best = end(); 8326 return OR_Ambiguous; 8327 } 8328 } 8329 8330 // Best is the best viable function. 8331 if (Best->Function && 8332 (Best->Function->isDeleted() || 8333 S.isFunctionConsideredUnavailable(Best->Function))) 8334 return OR_Deleted; 8335 8336 return OR_Success; 8337 } 8338 8339 namespace { 8340 8341 enum OverloadCandidateKind { 8342 oc_function, 8343 oc_method, 8344 oc_constructor, 8345 oc_function_template, 8346 oc_method_template, 8347 oc_constructor_template, 8348 oc_implicit_default_constructor, 8349 oc_implicit_copy_constructor, 8350 oc_implicit_move_constructor, 8351 oc_implicit_copy_assignment, 8352 oc_implicit_move_assignment, 8353 oc_implicit_inherited_constructor 8354 }; 8355 8356 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8357 FunctionDecl *Fn, 8358 std::string &Description) { 8359 bool isTemplate = false; 8360 8361 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8362 isTemplate = true; 8363 Description = S.getTemplateArgumentBindingsText( 8364 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8365 } 8366 8367 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8368 if (!Ctor->isImplicit()) 8369 return isTemplate ? oc_constructor_template : oc_constructor; 8370 8371 if (Ctor->getInheritedConstructor()) 8372 return oc_implicit_inherited_constructor; 8373 8374 if (Ctor->isDefaultConstructor()) 8375 return oc_implicit_default_constructor; 8376 8377 if (Ctor->isMoveConstructor()) 8378 return oc_implicit_move_constructor; 8379 8380 assert(Ctor->isCopyConstructor() && 8381 "unexpected sort of implicit constructor"); 8382 return oc_implicit_copy_constructor; 8383 } 8384 8385 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8386 // This actually gets spelled 'candidate function' for now, but 8387 // it doesn't hurt to split it out. 8388 if (!Meth->isImplicit()) 8389 return isTemplate ? oc_method_template : oc_method; 8390 8391 if (Meth->isMoveAssignmentOperator()) 8392 return oc_implicit_move_assignment; 8393 8394 if (Meth->isCopyAssignmentOperator()) 8395 return oc_implicit_copy_assignment; 8396 8397 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8398 return oc_method; 8399 } 8400 8401 return isTemplate ? oc_function_template : oc_function; 8402 } 8403 8404 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) { 8405 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8406 if (!Ctor) return; 8407 8408 Ctor = Ctor->getInheritedConstructor(); 8409 if (!Ctor) return; 8410 8411 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8412 } 8413 8414 } // end anonymous namespace 8415 8416 // Notes the location of an overload candidate. 8417 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 8418 std::string FnDesc; 8419 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8420 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8421 << (unsigned) K << FnDesc; 8422 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8423 Diag(Fn->getLocation(), PD); 8424 MaybeEmitInheritedConstructorNote(*this, Fn); 8425 } 8426 8427 // Notes the location of all overload candidates designated through 8428 // OverloadedExpr 8429 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 8430 assert(OverloadedExpr->getType() == Context.OverloadTy); 8431 8432 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8433 OverloadExpr *OvlExpr = Ovl.Expression; 8434 8435 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8436 IEnd = OvlExpr->decls_end(); 8437 I != IEnd; ++I) { 8438 if (FunctionTemplateDecl *FunTmpl = 8439 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8440 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 8441 } else if (FunctionDecl *Fun 8442 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8443 NoteOverloadCandidate(Fun, DestType); 8444 } 8445 } 8446 } 8447 8448 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 8449 /// "lead" diagnostic; it will be given two arguments, the source and 8450 /// target types of the conversion. 8451 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8452 Sema &S, 8453 SourceLocation CaretLoc, 8454 const PartialDiagnostic &PDiag) const { 8455 S.Diag(CaretLoc, PDiag) 8456 << Ambiguous.getFromType() << Ambiguous.getToType(); 8457 // FIXME: The note limiting machinery is borrowed from 8458 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8459 // refactoring here. 8460 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8461 unsigned CandsShown = 0; 8462 AmbiguousConversionSequence::const_iterator I, E; 8463 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8464 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8465 break; 8466 ++CandsShown; 8467 S.NoteOverloadCandidate(*I); 8468 } 8469 if (I != E) 8470 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8471 } 8472 8473 namespace { 8474 8475 void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 8476 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8477 assert(Conv.isBad()); 8478 assert(Cand->Function && "for now, candidate must be a function"); 8479 FunctionDecl *Fn = Cand->Function; 8480 8481 // There's a conversion slot for the object argument if this is a 8482 // non-constructor method. Note that 'I' corresponds the 8483 // conversion-slot index. 8484 bool isObjectArgument = false; 8485 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8486 if (I == 0) 8487 isObjectArgument = true; 8488 else 8489 I--; 8490 } 8491 8492 std::string FnDesc; 8493 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8494 8495 Expr *FromExpr = Conv.Bad.FromExpr; 8496 QualType FromTy = Conv.Bad.getFromType(); 8497 QualType ToTy = Conv.Bad.getToType(); 8498 8499 if (FromTy == S.Context.OverloadTy) { 8500 assert(FromExpr && "overload set argument came from implicit argument?"); 8501 Expr *E = FromExpr->IgnoreParens(); 8502 if (isa<UnaryOperator>(E)) 8503 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8504 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8505 8506 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8507 << (unsigned) FnKind << FnDesc 8508 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8509 << ToTy << Name << I+1; 8510 MaybeEmitInheritedConstructorNote(S, Fn); 8511 return; 8512 } 8513 8514 // Do some hand-waving analysis to see if the non-viability is due 8515 // to a qualifier mismatch. 8516 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8517 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8518 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8519 CToTy = RT->getPointeeType(); 8520 else { 8521 // TODO: detect and diagnose the full richness of const mismatches. 8522 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8523 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8524 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8525 } 8526 8527 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8528 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8529 Qualifiers FromQs = CFromTy.getQualifiers(); 8530 Qualifiers ToQs = CToTy.getQualifiers(); 8531 8532 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8533 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8534 << (unsigned) FnKind << FnDesc 8535 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8536 << FromTy 8537 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8538 << (unsigned) isObjectArgument << I+1; 8539 MaybeEmitInheritedConstructorNote(S, Fn); 8540 return; 8541 } 8542 8543 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8544 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8545 << (unsigned) FnKind << FnDesc 8546 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8547 << FromTy 8548 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8549 << (unsigned) isObjectArgument << I+1; 8550 MaybeEmitInheritedConstructorNote(S, Fn); 8551 return; 8552 } 8553 8554 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8555 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8556 << (unsigned) FnKind << FnDesc 8557 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8558 << FromTy 8559 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8560 << (unsigned) isObjectArgument << I+1; 8561 MaybeEmitInheritedConstructorNote(S, Fn); 8562 return; 8563 } 8564 8565 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8566 assert(CVR && "unexpected qualifiers mismatch"); 8567 8568 if (isObjectArgument) { 8569 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8570 << (unsigned) FnKind << FnDesc 8571 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8572 << FromTy << (CVR - 1); 8573 } else { 8574 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8575 << (unsigned) FnKind << FnDesc 8576 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8577 << FromTy << (CVR - 1) << I+1; 8578 } 8579 MaybeEmitInheritedConstructorNote(S, Fn); 8580 return; 8581 } 8582 8583 // Special diagnostic for failure to convert an initializer list, since 8584 // telling the user that it has type void is not useful. 8585 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8586 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8587 << (unsigned) FnKind << FnDesc 8588 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8589 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8590 MaybeEmitInheritedConstructorNote(S, Fn); 8591 return; 8592 } 8593 8594 // Diagnose references or pointers to incomplete types differently, 8595 // since it's far from impossible that the incompleteness triggered 8596 // the failure. 8597 QualType TempFromTy = FromTy.getNonReferenceType(); 8598 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8599 TempFromTy = PTy->getPointeeType(); 8600 if (TempFromTy->isIncompleteType()) { 8601 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8602 << (unsigned) FnKind << FnDesc 8603 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8604 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8605 MaybeEmitInheritedConstructorNote(S, Fn); 8606 return; 8607 } 8608 8609 // Diagnose base -> derived pointer conversions. 8610 unsigned BaseToDerivedConversion = 0; 8611 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8612 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8613 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8614 FromPtrTy->getPointeeType()) && 8615 !FromPtrTy->getPointeeType()->isIncompleteType() && 8616 !ToPtrTy->getPointeeType()->isIncompleteType() && 8617 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8618 FromPtrTy->getPointeeType())) 8619 BaseToDerivedConversion = 1; 8620 } 8621 } else if (const ObjCObjectPointerType *FromPtrTy 8622 = FromTy->getAs<ObjCObjectPointerType>()) { 8623 if (const ObjCObjectPointerType *ToPtrTy 8624 = ToTy->getAs<ObjCObjectPointerType>()) 8625 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8626 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8627 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8628 FromPtrTy->getPointeeType()) && 8629 FromIface->isSuperClassOf(ToIface)) 8630 BaseToDerivedConversion = 2; 8631 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8632 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8633 !FromTy->isIncompleteType() && 8634 !ToRefTy->getPointeeType()->isIncompleteType() && 8635 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8636 BaseToDerivedConversion = 3; 8637 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8638 ToTy.getNonReferenceType().getCanonicalType() == 8639 FromTy.getNonReferenceType().getCanonicalType()) { 8640 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8641 << (unsigned) FnKind << FnDesc 8642 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8643 << (unsigned) isObjectArgument << I + 1; 8644 MaybeEmitInheritedConstructorNote(S, Fn); 8645 return; 8646 } 8647 } 8648 8649 if (BaseToDerivedConversion) { 8650 S.Diag(Fn->getLocation(), 8651 diag::note_ovl_candidate_bad_base_to_derived_conv) 8652 << (unsigned) FnKind << FnDesc 8653 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8654 << (BaseToDerivedConversion - 1) 8655 << FromTy << ToTy << I+1; 8656 MaybeEmitInheritedConstructorNote(S, Fn); 8657 return; 8658 } 8659 8660 if (isa<ObjCObjectPointerType>(CFromTy) && 8661 isa<PointerType>(CToTy)) { 8662 Qualifiers FromQs = CFromTy.getQualifiers(); 8663 Qualifiers ToQs = CToTy.getQualifiers(); 8664 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8665 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8666 << (unsigned) FnKind << FnDesc 8667 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8668 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8669 MaybeEmitInheritedConstructorNote(S, Fn); 8670 return; 8671 } 8672 } 8673 8674 // Emit the generic diagnostic and, optionally, add the hints to it. 8675 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8676 FDiag << (unsigned) FnKind << FnDesc 8677 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8678 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8679 << (unsigned) (Cand->Fix.Kind); 8680 8681 // If we can fix the conversion, suggest the FixIts. 8682 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8683 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8684 FDiag << *HI; 8685 S.Diag(Fn->getLocation(), FDiag); 8686 8687 MaybeEmitInheritedConstructorNote(S, Fn); 8688 } 8689 8690 /// Additional arity mismatch diagnosis specific to a function overload 8691 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 8692 /// over a candidate in any candidate set. 8693 bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 8694 unsigned NumArgs) { 8695 FunctionDecl *Fn = Cand->Function; 8696 unsigned MinParams = Fn->getMinRequiredArguments(); 8697 8698 // With invalid overloaded operators, it's possible that we think we 8699 // have an arity mismatch when in fact it looks like we have the 8700 // right number of arguments, because only overloaded operators have 8701 // the weird behavior of overloading member and non-member functions. 8702 // Just don't report anything. 8703 if (Fn->isInvalidDecl() && 8704 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8705 return true; 8706 8707 if (NumArgs < MinParams) { 8708 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8709 (Cand->FailureKind == ovl_fail_bad_deduction && 8710 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8711 } else { 8712 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8713 (Cand->FailureKind == ovl_fail_bad_deduction && 8714 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8715 } 8716 8717 return false; 8718 } 8719 8720 /// General arity mismatch diagnosis over a candidate in a candidate set. 8721 void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) { 8722 assert(isa<FunctionDecl>(D) && 8723 "The templated declaration should at least be a function" 8724 " when diagnosing bad template argument deduction due to too many" 8725 " or too few arguments"); 8726 8727 FunctionDecl *Fn = cast<FunctionDecl>(D); 8728 8729 // TODO: treat calls to a missing default constructor as a special case 8730 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8731 unsigned MinParams = Fn->getMinRequiredArguments(); 8732 8733 // at least / at most / exactly 8734 unsigned mode, modeCount; 8735 if (NumFormalArgs < MinParams) { 8736 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 8737 FnTy->isTemplateVariadic()) 8738 mode = 0; // "at least" 8739 else 8740 mode = 2; // "exactly" 8741 modeCount = MinParams; 8742 } else { 8743 if (MinParams != FnTy->getNumParams()) 8744 mode = 1; // "at most" 8745 else 8746 mode = 2; // "exactly" 8747 modeCount = FnTy->getNumParams(); 8748 } 8749 8750 std::string Description; 8751 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8752 8753 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8754 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8755 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8756 << Fn->getParamDecl(0) << NumFormalArgs; 8757 else 8758 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8759 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8760 << modeCount << NumFormalArgs; 8761 MaybeEmitInheritedConstructorNote(S, Fn); 8762 } 8763 8764 /// Arity mismatch diagnosis specific to a function overload candidate. 8765 void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8766 unsigned NumFormalArgs) { 8767 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 8768 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs); 8769 } 8770 8771 TemplateDecl *getDescribedTemplate(Decl *Templated) { 8772 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated)) 8773 return FD->getDescribedFunctionTemplate(); 8774 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated)) 8775 return RD->getDescribedClassTemplate(); 8776 8777 llvm_unreachable("Unsupported: Getting the described template declaration" 8778 " for bad deduction diagnosis"); 8779 } 8780 8781 /// Diagnose a failed template-argument deduction. 8782 void DiagnoseBadDeduction(Sema &S, Decl *Templated, 8783 DeductionFailureInfo &DeductionFailure, 8784 unsigned NumArgs) { 8785 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 8786 NamedDecl *ParamD; 8787 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8788 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8789 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8790 switch (DeductionFailure.Result) { 8791 case Sema::TDK_Success: 8792 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8793 8794 case Sema::TDK_Incomplete: { 8795 assert(ParamD && "no parameter found for incomplete deduction result"); 8796 S.Diag(Templated->getLocation(), 8797 diag::note_ovl_candidate_incomplete_deduction) 8798 << ParamD->getDeclName(); 8799 MaybeEmitInheritedConstructorNote(S, Templated); 8800 return; 8801 } 8802 8803 case Sema::TDK_Underqualified: { 8804 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8805 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 8806 8807 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 8808 8809 // Param will have been canonicalized, but it should just be a 8810 // qualified version of ParamD, so move the qualifiers to that. 8811 QualifierCollector Qs; 8812 Qs.strip(Param); 8813 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 8814 assert(S.Context.hasSameType(Param, NonCanonParam)); 8815 8816 // Arg has also been canonicalized, but there's nothing we can do 8817 // about that. It also doesn't matter as much, because it won't 8818 // have any template parameters in it (because deduction isn't 8819 // done on dependent types). 8820 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 8821 8822 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 8823 << ParamD->getDeclName() << Arg << NonCanonParam; 8824 MaybeEmitInheritedConstructorNote(S, Templated); 8825 return; 8826 } 8827 8828 case Sema::TDK_Inconsistent: { 8829 assert(ParamD && "no parameter found for inconsistent deduction result"); 8830 int which = 0; 8831 if (isa<TemplateTypeParmDecl>(ParamD)) 8832 which = 0; 8833 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 8834 which = 1; 8835 else { 8836 which = 2; 8837 } 8838 8839 S.Diag(Templated->getLocation(), 8840 diag::note_ovl_candidate_inconsistent_deduction) 8841 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 8842 << *DeductionFailure.getSecondArg(); 8843 MaybeEmitInheritedConstructorNote(S, Templated); 8844 return; 8845 } 8846 8847 case Sema::TDK_InvalidExplicitArguments: 8848 assert(ParamD && "no parameter found for invalid explicit arguments"); 8849 if (ParamD->getDeclName()) 8850 S.Diag(Templated->getLocation(), 8851 diag::note_ovl_candidate_explicit_arg_mismatch_named) 8852 << ParamD->getDeclName(); 8853 else { 8854 int index = 0; 8855 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 8856 index = TTP->getIndex(); 8857 else if (NonTypeTemplateParmDecl *NTTP 8858 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 8859 index = NTTP->getIndex(); 8860 else 8861 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 8862 S.Diag(Templated->getLocation(), 8863 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 8864 << (index + 1); 8865 } 8866 MaybeEmitInheritedConstructorNote(S, Templated); 8867 return; 8868 8869 case Sema::TDK_TooManyArguments: 8870 case Sema::TDK_TooFewArguments: 8871 DiagnoseArityMismatch(S, Templated, NumArgs); 8872 return; 8873 8874 case Sema::TDK_InstantiationDepth: 8875 S.Diag(Templated->getLocation(), 8876 diag::note_ovl_candidate_instantiation_depth); 8877 MaybeEmitInheritedConstructorNote(S, Templated); 8878 return; 8879 8880 case Sema::TDK_SubstitutionFailure: { 8881 // Format the template argument list into the argument string. 8882 SmallString<128> TemplateArgString; 8883 if (TemplateArgumentList *Args = 8884 DeductionFailure.getTemplateArgumentList()) { 8885 TemplateArgString = " "; 8886 TemplateArgString += S.getTemplateArgumentBindingsText( 8887 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 8888 } 8889 8890 // If this candidate was disabled by enable_if, say so. 8891 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 8892 if (PDiag && PDiag->second.getDiagID() == 8893 diag::err_typename_nested_not_found_enable_if) { 8894 // FIXME: Use the source range of the condition, and the fully-qualified 8895 // name of the enable_if template. These are both present in PDiag. 8896 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 8897 << "'enable_if'" << TemplateArgString; 8898 return; 8899 } 8900 8901 // Format the SFINAE diagnostic into the argument string. 8902 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 8903 // formatted message in another diagnostic. 8904 SmallString<128> SFINAEArgString; 8905 SourceRange R; 8906 if (PDiag) { 8907 SFINAEArgString = ": "; 8908 R = SourceRange(PDiag->first, PDiag->first); 8909 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 8910 } 8911 8912 S.Diag(Templated->getLocation(), 8913 diag::note_ovl_candidate_substitution_failure) 8914 << TemplateArgString << SFINAEArgString << R; 8915 MaybeEmitInheritedConstructorNote(S, Templated); 8916 return; 8917 } 8918 8919 case Sema::TDK_FailedOverloadResolution: { 8920 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 8921 S.Diag(Templated->getLocation(), 8922 diag::note_ovl_candidate_failed_overload_resolution) 8923 << R.Expression->getName(); 8924 return; 8925 } 8926 8927 case Sema::TDK_NonDeducedMismatch: { 8928 // FIXME: Provide a source location to indicate what we couldn't match. 8929 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 8930 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 8931 if (FirstTA.getKind() == TemplateArgument::Template && 8932 SecondTA.getKind() == TemplateArgument::Template) { 8933 TemplateName FirstTN = FirstTA.getAsTemplate(); 8934 TemplateName SecondTN = SecondTA.getAsTemplate(); 8935 if (FirstTN.getKind() == TemplateName::Template && 8936 SecondTN.getKind() == TemplateName::Template) { 8937 if (FirstTN.getAsTemplateDecl()->getName() == 8938 SecondTN.getAsTemplateDecl()->getName()) { 8939 // FIXME: This fixes a bad diagnostic where both templates are named 8940 // the same. This particular case is a bit difficult since: 8941 // 1) It is passed as a string to the diagnostic printer. 8942 // 2) The diagnostic printer only attempts to find a better 8943 // name for types, not decls. 8944 // Ideally, this should folded into the diagnostic printer. 8945 S.Diag(Templated->getLocation(), 8946 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 8947 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 8948 return; 8949 } 8950 } 8951 } 8952 // FIXME: For generic lambda parameters, check if the function is a lambda 8953 // call operator, and if so, emit a prettier and more informative 8954 // diagnostic that mentions 'auto' and lambda in addition to 8955 // (or instead of?) the canonical template type parameters. 8956 S.Diag(Templated->getLocation(), 8957 diag::note_ovl_candidate_non_deduced_mismatch) 8958 << FirstTA << SecondTA; 8959 return; 8960 } 8961 // TODO: diagnose these individually, then kill off 8962 // note_ovl_candidate_bad_deduction, which is uselessly vague. 8963 case Sema::TDK_MiscellaneousDeductionFailure: 8964 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 8965 MaybeEmitInheritedConstructorNote(S, Templated); 8966 return; 8967 } 8968 } 8969 8970 /// Diagnose a failed template-argument deduction, for function calls. 8971 void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) { 8972 unsigned TDK = Cand->DeductionFailure.Result; 8973 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 8974 if (CheckArityMismatch(S, Cand, NumArgs)) 8975 return; 8976 } 8977 DiagnoseBadDeduction(S, Cand->Function, // pattern 8978 Cand->DeductionFailure, NumArgs); 8979 } 8980 8981 /// CUDA: diagnose an invalid call across targets. 8982 void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 8983 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 8984 FunctionDecl *Callee = Cand->Function; 8985 8986 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 8987 CalleeTarget = S.IdentifyCUDATarget(Callee); 8988 8989 std::string FnDesc; 8990 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 8991 8992 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 8993 << (unsigned) FnKind << CalleeTarget << CallerTarget; 8994 } 8995 8996 void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 8997 FunctionDecl *Callee = Cand->Function; 8998 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 8999 9000 S.Diag(Callee->getLocation(), 9001 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9002 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9003 } 9004 9005 /// Generates a 'note' diagnostic for an overload candidate. We've 9006 /// already generated a primary error at the call site. 9007 /// 9008 /// It really does need to be a single diagnostic with its caret 9009 /// pointed at the candidate declaration. Yes, this creates some 9010 /// major challenges of technical writing. Yes, this makes pointing 9011 /// out problems with specific arguments quite awkward. It's still 9012 /// better than generating twenty screens of text for every failed 9013 /// overload. 9014 /// 9015 /// It would be great to be able to express per-candidate problems 9016 /// more richly for those diagnostic clients that cared, but we'd 9017 /// still have to be just as careful with the default diagnostics. 9018 void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9019 unsigned NumArgs) { 9020 FunctionDecl *Fn = Cand->Function; 9021 9022 // Note deleted candidates, but only if they're viable. 9023 if (Cand->Viable && (Fn->isDeleted() || 9024 S.isFunctionConsideredUnavailable(Fn))) { 9025 std::string FnDesc; 9026 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 9027 9028 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9029 << FnKind << FnDesc 9030 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9031 MaybeEmitInheritedConstructorNote(S, Fn); 9032 return; 9033 } 9034 9035 // We don't really have anything else to say about viable candidates. 9036 if (Cand->Viable) { 9037 S.NoteOverloadCandidate(Fn); 9038 return; 9039 } 9040 9041 switch (Cand->FailureKind) { 9042 case ovl_fail_too_many_arguments: 9043 case ovl_fail_too_few_arguments: 9044 return DiagnoseArityMismatch(S, Cand, NumArgs); 9045 9046 case ovl_fail_bad_deduction: 9047 return DiagnoseBadDeduction(S, Cand, NumArgs); 9048 9049 case ovl_fail_trivial_conversion: 9050 case ovl_fail_bad_final_conversion: 9051 case ovl_fail_final_conversion_not_exact: 9052 return S.NoteOverloadCandidate(Fn); 9053 9054 case ovl_fail_bad_conversion: { 9055 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9056 for (unsigned N = Cand->NumConversions; I != N; ++I) 9057 if (Cand->Conversions[I].isBad()) 9058 return DiagnoseBadConversion(S, Cand, I); 9059 9060 // FIXME: this currently happens when we're called from SemaInit 9061 // when user-conversion overload fails. Figure out how to handle 9062 // those conditions and diagnose them well. 9063 return S.NoteOverloadCandidate(Fn); 9064 } 9065 9066 case ovl_fail_bad_target: 9067 return DiagnoseBadTarget(S, Cand); 9068 9069 case ovl_fail_enable_if: 9070 return DiagnoseFailedEnableIfAttr(S, Cand); 9071 } 9072 } 9073 9074 void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9075 // Desugar the type of the surrogate down to a function type, 9076 // retaining as many typedefs as possible while still showing 9077 // the function type (and, therefore, its parameter types). 9078 QualType FnType = Cand->Surrogate->getConversionType(); 9079 bool isLValueReference = false; 9080 bool isRValueReference = false; 9081 bool isPointer = false; 9082 if (const LValueReferenceType *FnTypeRef = 9083 FnType->getAs<LValueReferenceType>()) { 9084 FnType = FnTypeRef->getPointeeType(); 9085 isLValueReference = true; 9086 } else if (const RValueReferenceType *FnTypeRef = 9087 FnType->getAs<RValueReferenceType>()) { 9088 FnType = FnTypeRef->getPointeeType(); 9089 isRValueReference = true; 9090 } 9091 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9092 FnType = FnTypePtr->getPointeeType(); 9093 isPointer = true; 9094 } 9095 // Desugar down to a function type. 9096 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9097 // Reconstruct the pointer/reference as appropriate. 9098 if (isPointer) FnType = S.Context.getPointerType(FnType); 9099 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9100 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9101 9102 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9103 << FnType; 9104 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 9105 } 9106 9107 void NoteBuiltinOperatorCandidate(Sema &S, 9108 StringRef Opc, 9109 SourceLocation OpLoc, 9110 OverloadCandidate *Cand) { 9111 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9112 std::string TypeStr("operator"); 9113 TypeStr += Opc; 9114 TypeStr += "("; 9115 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9116 if (Cand->NumConversions == 1) { 9117 TypeStr += ")"; 9118 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9119 } else { 9120 TypeStr += ", "; 9121 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9122 TypeStr += ")"; 9123 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9124 } 9125 } 9126 9127 void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9128 OverloadCandidate *Cand) { 9129 unsigned NoOperands = Cand->NumConversions; 9130 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9131 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9132 if (ICS.isBad()) break; // all meaningless after first invalid 9133 if (!ICS.isAmbiguous()) continue; 9134 9135 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 9136 S.PDiag(diag::note_ambiguous_type_conversion)); 9137 } 9138 } 9139 9140 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9141 if (Cand->Function) 9142 return Cand->Function->getLocation(); 9143 if (Cand->IsSurrogate) 9144 return Cand->Surrogate->getLocation(); 9145 return SourceLocation(); 9146 } 9147 9148 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 9149 switch ((Sema::TemplateDeductionResult)DFI.Result) { 9150 case Sema::TDK_Success: 9151 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9152 9153 case Sema::TDK_Invalid: 9154 case Sema::TDK_Incomplete: 9155 return 1; 9156 9157 case Sema::TDK_Underqualified: 9158 case Sema::TDK_Inconsistent: 9159 return 2; 9160 9161 case Sema::TDK_SubstitutionFailure: 9162 case Sema::TDK_NonDeducedMismatch: 9163 case Sema::TDK_MiscellaneousDeductionFailure: 9164 return 3; 9165 9166 case Sema::TDK_InstantiationDepth: 9167 case Sema::TDK_FailedOverloadResolution: 9168 return 4; 9169 9170 case Sema::TDK_InvalidExplicitArguments: 9171 return 5; 9172 9173 case Sema::TDK_TooManyArguments: 9174 case Sema::TDK_TooFewArguments: 9175 return 6; 9176 } 9177 llvm_unreachable("Unhandled deduction result"); 9178 } 9179 9180 struct CompareOverloadCandidatesForDisplay { 9181 Sema &S; 9182 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 9183 9184 bool operator()(const OverloadCandidate *L, 9185 const OverloadCandidate *R) { 9186 // Fast-path this check. 9187 if (L == R) return false; 9188 9189 // Order first by viability. 9190 if (L->Viable) { 9191 if (!R->Viable) return true; 9192 9193 // TODO: introduce a tri-valued comparison for overload 9194 // candidates. Would be more worthwhile if we had a sort 9195 // that could exploit it. 9196 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 9197 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 9198 } else if (R->Viable) 9199 return false; 9200 9201 assert(L->Viable == R->Viable); 9202 9203 // Criteria by which we can sort non-viable candidates: 9204 if (!L->Viable) { 9205 // 1. Arity mismatches come after other candidates. 9206 if (L->FailureKind == ovl_fail_too_many_arguments || 9207 L->FailureKind == ovl_fail_too_few_arguments) 9208 return false; 9209 if (R->FailureKind == ovl_fail_too_many_arguments || 9210 R->FailureKind == ovl_fail_too_few_arguments) 9211 return true; 9212 9213 // 2. Bad conversions come first and are ordered by the number 9214 // of bad conversions and quality of good conversions. 9215 if (L->FailureKind == ovl_fail_bad_conversion) { 9216 if (R->FailureKind != ovl_fail_bad_conversion) 9217 return true; 9218 9219 // The conversion that can be fixed with a smaller number of changes, 9220 // comes first. 9221 unsigned numLFixes = L->Fix.NumConversionsFixed; 9222 unsigned numRFixes = R->Fix.NumConversionsFixed; 9223 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 9224 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 9225 if (numLFixes != numRFixes) { 9226 if (numLFixes < numRFixes) 9227 return true; 9228 else 9229 return false; 9230 } 9231 9232 // If there's any ordering between the defined conversions... 9233 // FIXME: this might not be transitive. 9234 assert(L->NumConversions == R->NumConversions); 9235 9236 int leftBetter = 0; 9237 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 9238 for (unsigned E = L->NumConversions; I != E; ++I) { 9239 switch (CompareImplicitConversionSequences(S, 9240 L->Conversions[I], 9241 R->Conversions[I])) { 9242 case ImplicitConversionSequence::Better: 9243 leftBetter++; 9244 break; 9245 9246 case ImplicitConversionSequence::Worse: 9247 leftBetter--; 9248 break; 9249 9250 case ImplicitConversionSequence::Indistinguishable: 9251 break; 9252 } 9253 } 9254 if (leftBetter > 0) return true; 9255 if (leftBetter < 0) return false; 9256 9257 } else if (R->FailureKind == ovl_fail_bad_conversion) 9258 return false; 9259 9260 if (L->FailureKind == ovl_fail_bad_deduction) { 9261 if (R->FailureKind != ovl_fail_bad_deduction) 9262 return true; 9263 9264 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9265 return RankDeductionFailure(L->DeductionFailure) 9266 < RankDeductionFailure(R->DeductionFailure); 9267 } else if (R->FailureKind == ovl_fail_bad_deduction) 9268 return false; 9269 9270 // TODO: others? 9271 } 9272 9273 // Sort everything else by location. 9274 SourceLocation LLoc = GetLocationForCandidate(L); 9275 SourceLocation RLoc = GetLocationForCandidate(R); 9276 9277 // Put candidates without locations (e.g. builtins) at the end. 9278 if (LLoc.isInvalid()) return false; 9279 if (RLoc.isInvalid()) return true; 9280 9281 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9282 } 9283 }; 9284 9285 /// CompleteNonViableCandidate - Normally, overload resolution only 9286 /// computes up to the first. Produces the FixIt set if possible. 9287 void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 9288 ArrayRef<Expr *> Args) { 9289 assert(!Cand->Viable); 9290 9291 // Don't do anything on failures other than bad conversion. 9292 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 9293 9294 // We only want the FixIts if all the arguments can be corrected. 9295 bool Unfixable = false; 9296 // Use a implicit copy initialization to check conversion fixes. 9297 Cand->Fix.setConversionChecker(TryCopyInitialization); 9298 9299 // Skip forward to the first bad conversion. 9300 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 9301 unsigned ConvCount = Cand->NumConversions; 9302 while (true) { 9303 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 9304 ConvIdx++; 9305 if (Cand->Conversions[ConvIdx - 1].isBad()) { 9306 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 9307 break; 9308 } 9309 } 9310 9311 if (ConvIdx == ConvCount) 9312 return; 9313 9314 assert(!Cand->Conversions[ConvIdx].isInitialized() && 9315 "remaining conversion is initialized?"); 9316 9317 // FIXME: this should probably be preserved from the overload 9318 // operation somehow. 9319 bool SuppressUserConversions = false; 9320 9321 const FunctionProtoType* Proto; 9322 unsigned ArgIdx = ConvIdx; 9323 9324 if (Cand->IsSurrogate) { 9325 QualType ConvType 9326 = Cand->Surrogate->getConversionType().getNonReferenceType(); 9327 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9328 ConvType = ConvPtrType->getPointeeType(); 9329 Proto = ConvType->getAs<FunctionProtoType>(); 9330 ArgIdx--; 9331 } else if (Cand->Function) { 9332 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 9333 if (isa<CXXMethodDecl>(Cand->Function) && 9334 !isa<CXXConstructorDecl>(Cand->Function)) 9335 ArgIdx--; 9336 } else { 9337 // Builtin binary operator with a bad first conversion. 9338 assert(ConvCount <= 3); 9339 for (; ConvIdx != ConvCount; ++ConvIdx) 9340 Cand->Conversions[ConvIdx] 9341 = TryCopyInitialization(S, Args[ConvIdx], 9342 Cand->BuiltinTypes.ParamTypes[ConvIdx], 9343 SuppressUserConversions, 9344 /*InOverloadResolution*/ true, 9345 /*AllowObjCWritebackConversion=*/ 9346 S.getLangOpts().ObjCAutoRefCount); 9347 return; 9348 } 9349 9350 // Fill in the rest of the conversions. 9351 unsigned NumParams = Proto->getNumParams(); 9352 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 9353 if (ArgIdx < NumParams) { 9354 Cand->Conversions[ConvIdx] = TryCopyInitialization( 9355 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 9356 /*InOverloadResolution=*/true, 9357 /*AllowObjCWritebackConversion=*/ 9358 S.getLangOpts().ObjCAutoRefCount); 9359 // Store the FixIt in the candidate if it exists. 9360 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 9361 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 9362 } 9363 else 9364 Cand->Conversions[ConvIdx].setEllipsis(); 9365 } 9366 } 9367 9368 } // end anonymous namespace 9369 9370 /// PrintOverloadCandidates - When overload resolution fails, prints 9371 /// diagnostic messages containing the candidates in the candidate 9372 /// set. 9373 void OverloadCandidateSet::NoteCandidates(Sema &S, 9374 OverloadCandidateDisplayKind OCD, 9375 ArrayRef<Expr *> Args, 9376 StringRef Opc, 9377 SourceLocation OpLoc) { 9378 // Sort the candidates by viability and position. Sorting directly would 9379 // be prohibitive, so we make a set of pointers and sort those. 9380 SmallVector<OverloadCandidate*, 32> Cands; 9381 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 9382 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9383 if (Cand->Viable) 9384 Cands.push_back(Cand); 9385 else if (OCD == OCD_AllCandidates) { 9386 CompleteNonViableCandidate(S, Cand, Args); 9387 if (Cand->Function || Cand->IsSurrogate) 9388 Cands.push_back(Cand); 9389 // Otherwise, this a non-viable builtin candidate. We do not, in general, 9390 // want to list every possible builtin candidate. 9391 } 9392 } 9393 9394 std::sort(Cands.begin(), Cands.end(), 9395 CompareOverloadCandidatesForDisplay(S)); 9396 9397 bool ReportedAmbiguousConversions = false; 9398 9399 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 9400 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9401 unsigned CandsShown = 0; 9402 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9403 OverloadCandidate *Cand = *I; 9404 9405 // Set an arbitrary limit on the number of candidate functions we'll spam 9406 // the user with. FIXME: This limit should depend on details of the 9407 // candidate list. 9408 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 9409 break; 9410 } 9411 ++CandsShown; 9412 9413 if (Cand->Function) 9414 NoteFunctionCandidate(S, Cand, Args.size()); 9415 else if (Cand->IsSurrogate) 9416 NoteSurrogateCandidate(S, Cand); 9417 else { 9418 assert(Cand->Viable && 9419 "Non-viable built-in candidates are not added to Cands."); 9420 // Generally we only see ambiguities including viable builtin 9421 // operators if overload resolution got screwed up by an 9422 // ambiguous user-defined conversion. 9423 // 9424 // FIXME: It's quite possible for different conversions to see 9425 // different ambiguities, though. 9426 if (!ReportedAmbiguousConversions) { 9427 NoteAmbiguousUserConversions(S, OpLoc, Cand); 9428 ReportedAmbiguousConversions = true; 9429 } 9430 9431 // If this is a viable builtin, print it. 9432 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 9433 } 9434 } 9435 9436 if (I != E) 9437 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 9438 } 9439 9440 static SourceLocation 9441 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 9442 return Cand->Specialization ? Cand->Specialization->getLocation() 9443 : SourceLocation(); 9444 } 9445 9446 struct CompareTemplateSpecCandidatesForDisplay { 9447 Sema &S; 9448 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 9449 9450 bool operator()(const TemplateSpecCandidate *L, 9451 const TemplateSpecCandidate *R) { 9452 // Fast-path this check. 9453 if (L == R) 9454 return false; 9455 9456 // Assuming that both candidates are not matches... 9457 9458 // Sort by the ranking of deduction failures. 9459 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9460 return RankDeductionFailure(L->DeductionFailure) < 9461 RankDeductionFailure(R->DeductionFailure); 9462 9463 // Sort everything else by location. 9464 SourceLocation LLoc = GetLocationForCandidate(L); 9465 SourceLocation RLoc = GetLocationForCandidate(R); 9466 9467 // Put candidates without locations (e.g. builtins) at the end. 9468 if (LLoc.isInvalid()) 9469 return false; 9470 if (RLoc.isInvalid()) 9471 return true; 9472 9473 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9474 } 9475 }; 9476 9477 /// Diagnose a template argument deduction failure. 9478 /// We are treating these failures as overload failures due to bad 9479 /// deductions. 9480 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) { 9481 DiagnoseBadDeduction(S, Specialization, // pattern 9482 DeductionFailure, /*NumArgs=*/0); 9483 } 9484 9485 void TemplateSpecCandidateSet::destroyCandidates() { 9486 for (iterator i = begin(), e = end(); i != e; ++i) { 9487 i->DeductionFailure.Destroy(); 9488 } 9489 } 9490 9491 void TemplateSpecCandidateSet::clear() { 9492 destroyCandidates(); 9493 Candidates.clear(); 9494 } 9495 9496 /// NoteCandidates - When no template specialization match is found, prints 9497 /// diagnostic messages containing the non-matching specializations that form 9498 /// the candidate set. 9499 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 9500 /// OCD == OCD_AllCandidates and Cand->Viable == false. 9501 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 9502 // Sort the candidates by position (assuming no candidate is a match). 9503 // Sorting directly would be prohibitive, so we make a set of pointers 9504 // and sort those. 9505 SmallVector<TemplateSpecCandidate *, 32> Cands; 9506 Cands.reserve(size()); 9507 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9508 if (Cand->Specialization) 9509 Cands.push_back(Cand); 9510 // Otherwise, this is a non-matching builtin candidate. We do not, 9511 // in general, want to list every possible builtin candidate. 9512 } 9513 9514 std::sort(Cands.begin(), Cands.end(), 9515 CompareTemplateSpecCandidatesForDisplay(S)); 9516 9517 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 9518 // for generalization purposes (?). 9519 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9520 9521 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 9522 unsigned CandsShown = 0; 9523 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9524 TemplateSpecCandidate *Cand = *I; 9525 9526 // Set an arbitrary limit on the number of candidates we'll spam 9527 // the user with. FIXME: This limit should depend on details of the 9528 // candidate list. 9529 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9530 break; 9531 ++CandsShown; 9532 9533 assert(Cand->Specialization && 9534 "Non-matching built-in candidates are not added to Cands."); 9535 Cand->NoteDeductionFailure(S); 9536 } 9537 9538 if (I != E) 9539 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 9540 } 9541 9542 // [PossiblyAFunctionType] --> [Return] 9543 // NonFunctionType --> NonFunctionType 9544 // R (A) --> R(A) 9545 // R (*)(A) --> R (A) 9546 // R (&)(A) --> R (A) 9547 // R (S::*)(A) --> R (A) 9548 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 9549 QualType Ret = PossiblyAFunctionType; 9550 if (const PointerType *ToTypePtr = 9551 PossiblyAFunctionType->getAs<PointerType>()) 9552 Ret = ToTypePtr->getPointeeType(); 9553 else if (const ReferenceType *ToTypeRef = 9554 PossiblyAFunctionType->getAs<ReferenceType>()) 9555 Ret = ToTypeRef->getPointeeType(); 9556 else if (const MemberPointerType *MemTypePtr = 9557 PossiblyAFunctionType->getAs<MemberPointerType>()) 9558 Ret = MemTypePtr->getPointeeType(); 9559 Ret = 9560 Context.getCanonicalType(Ret).getUnqualifiedType(); 9561 return Ret; 9562 } 9563 9564 // A helper class to help with address of function resolution 9565 // - allows us to avoid passing around all those ugly parameters 9566 class AddressOfFunctionResolver 9567 { 9568 Sema& S; 9569 Expr* SourceExpr; 9570 const QualType& TargetType; 9571 QualType TargetFunctionType; // Extracted function type from target type 9572 9573 bool Complain; 9574 //DeclAccessPair& ResultFunctionAccessPair; 9575 ASTContext& Context; 9576 9577 bool TargetTypeIsNonStaticMemberFunction; 9578 bool FoundNonTemplateFunction; 9579 bool StaticMemberFunctionFromBoundPointer; 9580 9581 OverloadExpr::FindResult OvlExprInfo; 9582 OverloadExpr *OvlExpr; 9583 TemplateArgumentListInfo OvlExplicitTemplateArgs; 9584 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 9585 TemplateSpecCandidateSet FailedCandidates; 9586 9587 public: 9588 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 9589 const QualType &TargetType, bool Complain) 9590 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 9591 Complain(Complain), Context(S.getASTContext()), 9592 TargetTypeIsNonStaticMemberFunction( 9593 !!TargetType->getAs<MemberPointerType>()), 9594 FoundNonTemplateFunction(false), 9595 StaticMemberFunctionFromBoundPointer(false), 9596 OvlExprInfo(OverloadExpr::find(SourceExpr)), 9597 OvlExpr(OvlExprInfo.Expression), 9598 FailedCandidates(OvlExpr->getNameLoc()) { 9599 ExtractUnqualifiedFunctionTypeFromTargetType(); 9600 9601 if (TargetFunctionType->isFunctionType()) { 9602 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 9603 if (!UME->isImplicitAccess() && 9604 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 9605 StaticMemberFunctionFromBoundPointer = true; 9606 } else if (OvlExpr->hasExplicitTemplateArgs()) { 9607 DeclAccessPair dap; 9608 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 9609 OvlExpr, false, &dap)) { 9610 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 9611 if (!Method->isStatic()) { 9612 // If the target type is a non-function type and the function found 9613 // is a non-static member function, pretend as if that was the 9614 // target, it's the only possible type to end up with. 9615 TargetTypeIsNonStaticMemberFunction = true; 9616 9617 // And skip adding the function if its not in the proper form. 9618 // We'll diagnose this due to an empty set of functions. 9619 if (!OvlExprInfo.HasFormOfMemberPointer) 9620 return; 9621 } 9622 9623 Matches.push_back(std::make_pair(dap, Fn)); 9624 } 9625 return; 9626 } 9627 9628 if (OvlExpr->hasExplicitTemplateArgs()) 9629 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 9630 9631 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 9632 // C++ [over.over]p4: 9633 // If more than one function is selected, [...] 9634 if (Matches.size() > 1) { 9635 if (FoundNonTemplateFunction) 9636 EliminateAllTemplateMatches(); 9637 else 9638 EliminateAllExceptMostSpecializedTemplate(); 9639 } 9640 } 9641 } 9642 9643 private: 9644 bool isTargetTypeAFunction() const { 9645 return TargetFunctionType->isFunctionType(); 9646 } 9647 9648 // [ToType] [Return] 9649 9650 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 9651 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 9652 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 9653 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 9654 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 9655 } 9656 9657 // return true if any matching specializations were found 9658 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 9659 const DeclAccessPair& CurAccessFunPair) { 9660 if (CXXMethodDecl *Method 9661 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 9662 // Skip non-static function templates when converting to pointer, and 9663 // static when converting to member pointer. 9664 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9665 return false; 9666 } 9667 else if (TargetTypeIsNonStaticMemberFunction) 9668 return false; 9669 9670 // C++ [over.over]p2: 9671 // If the name is a function template, template argument deduction is 9672 // done (14.8.2.2), and if the argument deduction succeeds, the 9673 // resulting template argument list is used to generate a single 9674 // function template specialization, which is added to the set of 9675 // overloaded functions considered. 9676 FunctionDecl *Specialization = 0; 9677 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 9678 if (Sema::TemplateDeductionResult Result 9679 = S.DeduceTemplateArguments(FunctionTemplate, 9680 &OvlExplicitTemplateArgs, 9681 TargetFunctionType, Specialization, 9682 Info, /*InOverloadResolution=*/true)) { 9683 // Make a note of the failed deduction for diagnostics. 9684 FailedCandidates.addCandidate() 9685 .set(FunctionTemplate->getTemplatedDecl(), 9686 MakeDeductionFailureInfo(Context, Result, Info)); 9687 return false; 9688 } 9689 9690 // Template argument deduction ensures that we have an exact match or 9691 // compatible pointer-to-function arguments that would be adjusted by ICS. 9692 // This function template specicalization works. 9693 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 9694 assert(S.isSameOrCompatibleFunctionType( 9695 Context.getCanonicalType(Specialization->getType()), 9696 Context.getCanonicalType(TargetFunctionType))); 9697 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 9698 return true; 9699 } 9700 9701 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9702 const DeclAccessPair& CurAccessFunPair) { 9703 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9704 // Skip non-static functions when converting to pointer, and static 9705 // when converting to member pointer. 9706 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9707 return false; 9708 } 9709 else if (TargetTypeIsNonStaticMemberFunction) 9710 return false; 9711 9712 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9713 if (S.getLangOpts().CUDA) 9714 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9715 if (S.CheckCUDATarget(Caller, FunDecl)) 9716 return false; 9717 9718 // If any candidate has a placeholder return type, trigger its deduction 9719 // now. 9720 if (S.getLangOpts().CPlusPlus1y && 9721 FunDecl->getReturnType()->isUndeducedType() && 9722 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) 9723 return false; 9724 9725 QualType ResultTy; 9726 if (Context.hasSameUnqualifiedType(TargetFunctionType, 9727 FunDecl->getType()) || 9728 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9729 ResultTy)) { 9730 Matches.push_back(std::make_pair(CurAccessFunPair, 9731 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9732 FoundNonTemplateFunction = true; 9733 return true; 9734 } 9735 } 9736 9737 return false; 9738 } 9739 9740 bool FindAllFunctionsThatMatchTargetTypeExactly() { 9741 bool Ret = false; 9742 9743 // If the overload expression doesn't have the form of a pointer to 9744 // member, don't try to convert it to a pointer-to-member type. 9745 if (IsInvalidFormOfPointerToMemberFunction()) 9746 return false; 9747 9748 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9749 E = OvlExpr->decls_end(); 9750 I != E; ++I) { 9751 // Look through any using declarations to find the underlying function. 9752 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 9753 9754 // C++ [over.over]p3: 9755 // Non-member functions and static member functions match 9756 // targets of type "pointer-to-function" or "reference-to-function." 9757 // Nonstatic member functions match targets of 9758 // type "pointer-to-member-function." 9759 // Note that according to DR 247, the containing class does not matter. 9760 if (FunctionTemplateDecl *FunctionTemplate 9761 = dyn_cast<FunctionTemplateDecl>(Fn)) { 9762 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 9763 Ret = true; 9764 } 9765 // If we have explicit template arguments supplied, skip non-templates. 9766 else if (!OvlExpr->hasExplicitTemplateArgs() && 9767 AddMatchingNonTemplateFunction(Fn, I.getPair())) 9768 Ret = true; 9769 } 9770 assert(Ret || Matches.empty()); 9771 return Ret; 9772 } 9773 9774 void EliminateAllExceptMostSpecializedTemplate() { 9775 // [...] and any given function template specialization F1 is 9776 // eliminated if the set contains a second function template 9777 // specialization whose function template is more specialized 9778 // than the function template of F1 according to the partial 9779 // ordering rules of 14.5.5.2. 9780 9781 // The algorithm specified above is quadratic. We instead use a 9782 // two-pass algorithm (similar to the one used to identify the 9783 // best viable function in an overload set) that identifies the 9784 // best function template (if it exists). 9785 9786 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 9787 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 9788 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 9789 9790 // TODO: It looks like FailedCandidates does not serve much purpose 9791 // here, since the no_viable diagnostic has index 0. 9792 UnresolvedSetIterator Result = S.getMostSpecialized( 9793 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 9794 SourceExpr->getLocStart(), S.PDiag(), 9795 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0] 9796 .second->getDeclName(), 9797 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template, 9798 Complain, TargetFunctionType); 9799 9800 if (Result != MatchesCopy.end()) { 9801 // Make it the first and only element 9802 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 9803 Matches[0].second = cast<FunctionDecl>(*Result); 9804 Matches.resize(1); 9805 } 9806 } 9807 9808 void EliminateAllTemplateMatches() { 9809 // [...] any function template specializations in the set are 9810 // eliminated if the set also contains a non-template function, [...] 9811 for (unsigned I = 0, N = Matches.size(); I != N; ) { 9812 if (Matches[I].second->getPrimaryTemplate() == 0) 9813 ++I; 9814 else { 9815 Matches[I] = Matches[--N]; 9816 Matches.set_size(N); 9817 } 9818 } 9819 } 9820 9821 public: 9822 void ComplainNoMatchesFound() const { 9823 assert(Matches.empty()); 9824 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 9825 << OvlExpr->getName() << TargetFunctionType 9826 << OvlExpr->getSourceRange(); 9827 if (FailedCandidates.empty()) 9828 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9829 else { 9830 // We have some deduction failure messages. Use them to diagnose 9831 // the function templates, and diagnose the non-template candidates 9832 // normally. 9833 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9834 IEnd = OvlExpr->decls_end(); 9835 I != IEnd; ++I) 9836 if (FunctionDecl *Fun = 9837 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 9838 S.NoteOverloadCandidate(Fun, TargetFunctionType); 9839 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 9840 } 9841 } 9842 9843 bool IsInvalidFormOfPointerToMemberFunction() const { 9844 return TargetTypeIsNonStaticMemberFunction && 9845 !OvlExprInfo.HasFormOfMemberPointer; 9846 } 9847 9848 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 9849 // TODO: Should we condition this on whether any functions might 9850 // have matched, or is it more appropriate to do that in callers? 9851 // TODO: a fixit wouldn't hurt. 9852 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 9853 << TargetType << OvlExpr->getSourceRange(); 9854 } 9855 9856 bool IsStaticMemberFunctionFromBoundPointer() const { 9857 return StaticMemberFunctionFromBoundPointer; 9858 } 9859 9860 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 9861 S.Diag(OvlExpr->getLocStart(), 9862 diag::err_invalid_form_pointer_member_function) 9863 << OvlExpr->getSourceRange(); 9864 } 9865 9866 void ComplainOfInvalidConversion() const { 9867 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 9868 << OvlExpr->getName() << TargetType; 9869 } 9870 9871 void ComplainMultipleMatchesFound() const { 9872 assert(Matches.size() > 1); 9873 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 9874 << OvlExpr->getName() 9875 << OvlExpr->getSourceRange(); 9876 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9877 } 9878 9879 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 9880 9881 int getNumMatches() const { return Matches.size(); } 9882 9883 FunctionDecl* getMatchingFunctionDecl() const { 9884 if (Matches.size() != 1) return 0; 9885 return Matches[0].second; 9886 } 9887 9888 const DeclAccessPair* getMatchingFunctionAccessPair() const { 9889 if (Matches.size() != 1) return 0; 9890 return &Matches[0].first; 9891 } 9892 }; 9893 9894 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 9895 /// an overloaded function (C++ [over.over]), where @p From is an 9896 /// expression with overloaded function type and @p ToType is the type 9897 /// we're trying to resolve to. For example: 9898 /// 9899 /// @code 9900 /// int f(double); 9901 /// int f(int); 9902 /// 9903 /// int (*pfd)(double) = f; // selects f(double) 9904 /// @endcode 9905 /// 9906 /// This routine returns the resulting FunctionDecl if it could be 9907 /// resolved, and NULL otherwise. When @p Complain is true, this 9908 /// routine will emit diagnostics if there is an error. 9909 FunctionDecl * 9910 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 9911 QualType TargetType, 9912 bool Complain, 9913 DeclAccessPair &FoundResult, 9914 bool *pHadMultipleCandidates) { 9915 assert(AddressOfExpr->getType() == Context.OverloadTy); 9916 9917 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 9918 Complain); 9919 int NumMatches = Resolver.getNumMatches(); 9920 FunctionDecl* Fn = 0; 9921 if (NumMatches == 0 && Complain) { 9922 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 9923 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 9924 else 9925 Resolver.ComplainNoMatchesFound(); 9926 } 9927 else if (NumMatches > 1 && Complain) 9928 Resolver.ComplainMultipleMatchesFound(); 9929 else if (NumMatches == 1) { 9930 Fn = Resolver.getMatchingFunctionDecl(); 9931 assert(Fn); 9932 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 9933 if (Complain) { 9934 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 9935 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 9936 else 9937 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 9938 } 9939 } 9940 9941 if (pHadMultipleCandidates) 9942 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 9943 return Fn; 9944 } 9945 9946 /// \brief Given an expression that refers to an overloaded function, try to 9947 /// resolve that overloaded function expression down to a single function. 9948 /// 9949 /// This routine can only resolve template-ids that refer to a single function 9950 /// template, where that template-id refers to a single template whose template 9951 /// arguments are either provided by the template-id or have defaults, 9952 /// as described in C++0x [temp.arg.explicit]p3. 9953 /// 9954 /// If no template-ids are found, no diagnostics are emitted and NULL is 9955 /// returned. 9956 FunctionDecl * 9957 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 9958 bool Complain, 9959 DeclAccessPair *FoundResult) { 9960 // C++ [over.over]p1: 9961 // [...] [Note: any redundant set of parentheses surrounding the 9962 // overloaded function name is ignored (5.1). ] 9963 // C++ [over.over]p1: 9964 // [...] The overloaded function name can be preceded by the & 9965 // operator. 9966 9967 // If we didn't actually find any template-ids, we're done. 9968 if (!ovl->hasExplicitTemplateArgs()) 9969 return 0; 9970 9971 TemplateArgumentListInfo ExplicitTemplateArgs; 9972 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 9973 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 9974 9975 // Look through all of the overloaded functions, searching for one 9976 // whose type matches exactly. 9977 FunctionDecl *Matched = 0; 9978 for (UnresolvedSetIterator I = ovl->decls_begin(), 9979 E = ovl->decls_end(); I != E; ++I) { 9980 // C++0x [temp.arg.explicit]p3: 9981 // [...] In contexts where deduction is done and fails, or in contexts 9982 // where deduction is not done, if a template argument list is 9983 // specified and it, along with any default template arguments, 9984 // identifies a single function template specialization, then the 9985 // template-id is an lvalue for the function template specialization. 9986 FunctionTemplateDecl *FunctionTemplate 9987 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 9988 9989 // C++ [over.over]p2: 9990 // If the name is a function template, template argument deduction is 9991 // done (14.8.2.2), and if the argument deduction succeeds, the 9992 // resulting template argument list is used to generate a single 9993 // function template specialization, which is added to the set of 9994 // overloaded functions considered. 9995 FunctionDecl *Specialization = 0; 9996 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 9997 if (TemplateDeductionResult Result 9998 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 9999 Specialization, Info, 10000 /*InOverloadResolution=*/true)) { 10001 // Make a note of the failed deduction for diagnostics. 10002 // TODO: Actually use the failed-deduction info? 10003 FailedCandidates.addCandidate() 10004 .set(FunctionTemplate->getTemplatedDecl(), 10005 MakeDeductionFailureInfo(Context, Result, Info)); 10006 continue; 10007 } 10008 10009 assert(Specialization && "no specialization and no error?"); 10010 10011 // Multiple matches; we can't resolve to a single declaration. 10012 if (Matched) { 10013 if (Complain) { 10014 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 10015 << ovl->getName(); 10016 NoteAllOverloadCandidates(ovl); 10017 } 10018 return 0; 10019 } 10020 10021 Matched = Specialization; 10022 if (FoundResult) *FoundResult = I.getPair(); 10023 } 10024 10025 if (Matched && getLangOpts().CPlusPlus1y && 10026 Matched->getReturnType()->isUndeducedType() && 10027 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 10028 return 0; 10029 10030 return Matched; 10031 } 10032 10033 10034 10035 10036 // Resolve and fix an overloaded expression that can be resolved 10037 // because it identifies a single function template specialization. 10038 // 10039 // Last three arguments should only be supplied if Complain = true 10040 // 10041 // Return true if it was logically possible to so resolve the 10042 // expression, regardless of whether or not it succeeded. Always 10043 // returns true if 'complain' is set. 10044 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 10045 ExprResult &SrcExpr, bool doFunctionPointerConverion, 10046 bool complain, const SourceRange& OpRangeForComplaining, 10047 QualType DestTypeForComplaining, 10048 unsigned DiagIDForComplaining) { 10049 assert(SrcExpr.get()->getType() == Context.OverloadTy); 10050 10051 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 10052 10053 DeclAccessPair found; 10054 ExprResult SingleFunctionExpression; 10055 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 10056 ovl.Expression, /*complain*/ false, &found)) { 10057 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 10058 SrcExpr = ExprError(); 10059 return true; 10060 } 10061 10062 // It is only correct to resolve to an instance method if we're 10063 // resolving a form that's permitted to be a pointer to member. 10064 // Otherwise we'll end up making a bound member expression, which 10065 // is illegal in all the contexts we resolve like this. 10066 if (!ovl.HasFormOfMemberPointer && 10067 isa<CXXMethodDecl>(fn) && 10068 cast<CXXMethodDecl>(fn)->isInstance()) { 10069 if (!complain) return false; 10070 10071 Diag(ovl.Expression->getExprLoc(), 10072 diag::err_bound_member_function) 10073 << 0 << ovl.Expression->getSourceRange(); 10074 10075 // TODO: I believe we only end up here if there's a mix of 10076 // static and non-static candidates (otherwise the expression 10077 // would have 'bound member' type, not 'overload' type). 10078 // Ideally we would note which candidate was chosen and why 10079 // the static candidates were rejected. 10080 SrcExpr = ExprError(); 10081 return true; 10082 } 10083 10084 // Fix the expression to refer to 'fn'. 10085 SingleFunctionExpression = 10086 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn)); 10087 10088 // If desired, do function-to-pointer decay. 10089 if (doFunctionPointerConverion) { 10090 SingleFunctionExpression = 10091 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take()); 10092 if (SingleFunctionExpression.isInvalid()) { 10093 SrcExpr = ExprError(); 10094 return true; 10095 } 10096 } 10097 } 10098 10099 if (!SingleFunctionExpression.isUsable()) { 10100 if (complain) { 10101 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 10102 << ovl.Expression->getName() 10103 << DestTypeForComplaining 10104 << OpRangeForComplaining 10105 << ovl.Expression->getQualifierLoc().getSourceRange(); 10106 NoteAllOverloadCandidates(SrcExpr.get()); 10107 10108 SrcExpr = ExprError(); 10109 return true; 10110 } 10111 10112 return false; 10113 } 10114 10115 SrcExpr = SingleFunctionExpression; 10116 return true; 10117 } 10118 10119 /// \brief Add a single candidate to the overload set. 10120 static void AddOverloadedCallCandidate(Sema &S, 10121 DeclAccessPair FoundDecl, 10122 TemplateArgumentListInfo *ExplicitTemplateArgs, 10123 ArrayRef<Expr *> Args, 10124 OverloadCandidateSet &CandidateSet, 10125 bool PartialOverloading, 10126 bool KnownValid) { 10127 NamedDecl *Callee = FoundDecl.getDecl(); 10128 if (isa<UsingShadowDecl>(Callee)) 10129 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 10130 10131 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 10132 if (ExplicitTemplateArgs) { 10133 assert(!KnownValid && "Explicit template arguments?"); 10134 return; 10135 } 10136 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false, 10137 PartialOverloading); 10138 return; 10139 } 10140 10141 if (FunctionTemplateDecl *FuncTemplate 10142 = dyn_cast<FunctionTemplateDecl>(Callee)) { 10143 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 10144 ExplicitTemplateArgs, Args, CandidateSet); 10145 return; 10146 } 10147 10148 assert(!KnownValid && "unhandled case in overloaded call candidate"); 10149 } 10150 10151 /// \brief Add the overload candidates named by callee and/or found by argument 10152 /// dependent lookup to the given overload set. 10153 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 10154 ArrayRef<Expr *> Args, 10155 OverloadCandidateSet &CandidateSet, 10156 bool PartialOverloading) { 10157 10158 #ifndef NDEBUG 10159 // Verify that ArgumentDependentLookup is consistent with the rules 10160 // in C++0x [basic.lookup.argdep]p3: 10161 // 10162 // Let X be the lookup set produced by unqualified lookup (3.4.1) 10163 // and let Y be the lookup set produced by argument dependent 10164 // lookup (defined as follows). If X contains 10165 // 10166 // -- a declaration of a class member, or 10167 // 10168 // -- a block-scope function declaration that is not a 10169 // using-declaration, or 10170 // 10171 // -- a declaration that is neither a function or a function 10172 // template 10173 // 10174 // then Y is empty. 10175 10176 if (ULE->requiresADL()) { 10177 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10178 E = ULE->decls_end(); I != E; ++I) { 10179 assert(!(*I)->getDeclContext()->isRecord()); 10180 assert(isa<UsingShadowDecl>(*I) || 10181 !(*I)->getDeclContext()->isFunctionOrMethod()); 10182 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 10183 } 10184 } 10185 #endif 10186 10187 // It would be nice to avoid this copy. 10188 TemplateArgumentListInfo TABuffer; 10189 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 10190 if (ULE->hasExplicitTemplateArgs()) { 10191 ULE->copyTemplateArgumentsInto(TABuffer); 10192 ExplicitTemplateArgs = &TABuffer; 10193 } 10194 10195 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10196 E = ULE->decls_end(); I != E; ++I) 10197 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 10198 CandidateSet, PartialOverloading, 10199 /*KnownValid*/ true); 10200 10201 if (ULE->requiresADL()) 10202 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 10203 ULE->getExprLoc(), 10204 Args, ExplicitTemplateArgs, 10205 CandidateSet, PartialOverloading); 10206 } 10207 10208 /// Determine whether a declaration with the specified name could be moved into 10209 /// a different namespace. 10210 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 10211 switch (Name.getCXXOverloadedOperator()) { 10212 case OO_New: case OO_Array_New: 10213 case OO_Delete: case OO_Array_Delete: 10214 return false; 10215 10216 default: 10217 return true; 10218 } 10219 } 10220 10221 /// Attempt to recover from an ill-formed use of a non-dependent name in a 10222 /// template, where the non-dependent name was declared after the template 10223 /// was defined. This is common in code written for a compilers which do not 10224 /// correctly implement two-stage name lookup. 10225 /// 10226 /// Returns true if a viable candidate was found and a diagnostic was issued. 10227 static bool 10228 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 10229 const CXXScopeSpec &SS, LookupResult &R, 10230 TemplateArgumentListInfo *ExplicitTemplateArgs, 10231 ArrayRef<Expr *> Args) { 10232 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 10233 return false; 10234 10235 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 10236 if (DC->isTransparentContext()) 10237 continue; 10238 10239 SemaRef.LookupQualifiedName(R, DC); 10240 10241 if (!R.empty()) { 10242 R.suppressDiagnostics(); 10243 10244 if (isa<CXXRecordDecl>(DC)) { 10245 // Don't diagnose names we find in classes; we get much better 10246 // diagnostics for these from DiagnoseEmptyLookup. 10247 R.clear(); 10248 return false; 10249 } 10250 10251 OverloadCandidateSet Candidates(FnLoc); 10252 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10253 AddOverloadedCallCandidate(SemaRef, I.getPair(), 10254 ExplicitTemplateArgs, Args, 10255 Candidates, false, /*KnownValid*/ false); 10256 10257 OverloadCandidateSet::iterator Best; 10258 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 10259 // No viable functions. Don't bother the user with notes for functions 10260 // which don't work and shouldn't be found anyway. 10261 R.clear(); 10262 return false; 10263 } 10264 10265 // Find the namespaces where ADL would have looked, and suggest 10266 // declaring the function there instead. 10267 Sema::AssociatedNamespaceSet AssociatedNamespaces; 10268 Sema::AssociatedClassSet AssociatedClasses; 10269 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 10270 AssociatedNamespaces, 10271 AssociatedClasses); 10272 Sema::AssociatedNamespaceSet SuggestedNamespaces; 10273 if (canBeDeclaredInNamespace(R.getLookupName())) { 10274 DeclContext *Std = SemaRef.getStdNamespace(); 10275 for (Sema::AssociatedNamespaceSet::iterator 10276 it = AssociatedNamespaces.begin(), 10277 end = AssociatedNamespaces.end(); it != end; ++it) { 10278 // Never suggest declaring a function within namespace 'std'. 10279 if (Std && Std->Encloses(*it)) 10280 continue; 10281 10282 // Never suggest declaring a function within a namespace with a 10283 // reserved name, like __gnu_cxx. 10284 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 10285 if (NS && 10286 NS->getQualifiedNameAsString().find("__") != std::string::npos) 10287 continue; 10288 10289 SuggestedNamespaces.insert(*it); 10290 } 10291 } 10292 10293 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 10294 << R.getLookupName(); 10295 if (SuggestedNamespaces.empty()) { 10296 SemaRef.Diag(Best->Function->getLocation(), 10297 diag::note_not_found_by_two_phase_lookup) 10298 << R.getLookupName() << 0; 10299 } else if (SuggestedNamespaces.size() == 1) { 10300 SemaRef.Diag(Best->Function->getLocation(), 10301 diag::note_not_found_by_two_phase_lookup) 10302 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 10303 } else { 10304 // FIXME: It would be useful to list the associated namespaces here, 10305 // but the diagnostics infrastructure doesn't provide a way to produce 10306 // a localized representation of a list of items. 10307 SemaRef.Diag(Best->Function->getLocation(), 10308 diag::note_not_found_by_two_phase_lookup) 10309 << R.getLookupName() << 2; 10310 } 10311 10312 // Try to recover by calling this function. 10313 return true; 10314 } 10315 10316 R.clear(); 10317 } 10318 10319 return false; 10320 } 10321 10322 /// Attempt to recover from ill-formed use of a non-dependent operator in a 10323 /// template, where the non-dependent operator was declared after the template 10324 /// was defined. 10325 /// 10326 /// Returns true if a viable candidate was found and a diagnostic was issued. 10327 static bool 10328 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 10329 SourceLocation OpLoc, 10330 ArrayRef<Expr *> Args) { 10331 DeclarationName OpName = 10332 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 10333 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 10334 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 10335 /*ExplicitTemplateArgs=*/0, Args); 10336 } 10337 10338 namespace { 10339 class BuildRecoveryCallExprRAII { 10340 Sema &SemaRef; 10341 public: 10342 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 10343 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 10344 SemaRef.IsBuildingRecoveryCallExpr = true; 10345 } 10346 10347 ~BuildRecoveryCallExprRAII() { 10348 SemaRef.IsBuildingRecoveryCallExpr = false; 10349 } 10350 }; 10351 10352 } 10353 10354 /// Attempts to recover from a call where no functions were found. 10355 /// 10356 /// Returns true if new candidates were found. 10357 static ExprResult 10358 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10359 UnresolvedLookupExpr *ULE, 10360 SourceLocation LParenLoc, 10361 llvm::MutableArrayRef<Expr *> Args, 10362 SourceLocation RParenLoc, 10363 bool EmptyLookup, bool AllowTypoCorrection) { 10364 // Do not try to recover if it is already building a recovery call. 10365 // This stops infinite loops for template instantiations like 10366 // 10367 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 10368 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 10369 // 10370 if (SemaRef.IsBuildingRecoveryCallExpr) 10371 return ExprError(); 10372 BuildRecoveryCallExprRAII RCE(SemaRef); 10373 10374 CXXScopeSpec SS; 10375 SS.Adopt(ULE->getQualifierLoc()); 10376 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 10377 10378 TemplateArgumentListInfo TABuffer; 10379 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 10380 if (ULE->hasExplicitTemplateArgs()) { 10381 ULE->copyTemplateArgumentsInto(TABuffer); 10382 ExplicitTemplateArgs = &TABuffer; 10383 } 10384 10385 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 10386 Sema::LookupOrdinaryName); 10387 FunctionCallFilterCCC Validator(SemaRef, Args.size(), 10388 ExplicitTemplateArgs != 0); 10389 NoTypoCorrectionCCC RejectAll; 10390 CorrectionCandidateCallback *CCC = AllowTypoCorrection ? 10391 (CorrectionCandidateCallback*)&Validator : 10392 (CorrectionCandidateCallback*)&RejectAll; 10393 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 10394 ExplicitTemplateArgs, Args) && 10395 (!EmptyLookup || 10396 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC, 10397 ExplicitTemplateArgs, Args))) 10398 return ExprError(); 10399 10400 assert(!R.empty() && "lookup results empty despite recovery"); 10401 10402 // Build an implicit member call if appropriate. Just drop the 10403 // casts and such from the call, we don't really care. 10404 ExprResult NewFn = ExprError(); 10405 if ((*R.begin())->isCXXClassMember()) 10406 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 10407 R, ExplicitTemplateArgs); 10408 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 10409 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 10410 ExplicitTemplateArgs); 10411 else 10412 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 10413 10414 if (NewFn.isInvalid()) 10415 return ExprError(); 10416 10417 // This shouldn't cause an infinite loop because we're giving it 10418 // an expression with viable lookup results, which should never 10419 // end up here. 10420 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 10421 MultiExprArg(Args.data(), Args.size()), 10422 RParenLoc); 10423 } 10424 10425 /// \brief Constructs and populates an OverloadedCandidateSet from 10426 /// the given function. 10427 /// \returns true when an the ExprResult output parameter has been set. 10428 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 10429 UnresolvedLookupExpr *ULE, 10430 MultiExprArg Args, 10431 SourceLocation RParenLoc, 10432 OverloadCandidateSet *CandidateSet, 10433 ExprResult *Result) { 10434 #ifndef NDEBUG 10435 if (ULE->requiresADL()) { 10436 // To do ADL, we must have found an unqualified name. 10437 assert(!ULE->getQualifier() && "qualified name with ADL"); 10438 10439 // We don't perform ADL for implicit declarations of builtins. 10440 // Verify that this was correctly set up. 10441 FunctionDecl *F; 10442 if (ULE->decls_begin() + 1 == ULE->decls_end() && 10443 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 10444 F->getBuiltinID() && F->isImplicit()) 10445 llvm_unreachable("performing ADL for builtin"); 10446 10447 // We don't perform ADL in C. 10448 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 10449 } 10450 #endif 10451 10452 UnbridgedCastsSet UnbridgedCasts; 10453 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 10454 *Result = ExprError(); 10455 return true; 10456 } 10457 10458 // Add the functions denoted by the callee to the set of candidate 10459 // functions, including those from argument-dependent lookup. 10460 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 10461 10462 // If we found nothing, try to recover. 10463 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 10464 // out if it fails. 10465 if (CandidateSet->empty()) { 10466 // In Microsoft mode, if we are inside a template class member function then 10467 // create a type dependent CallExpr. The goal is to postpone name lookup 10468 // to instantiation time to be able to search into type dependent base 10469 // classes. 10470 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() && 10471 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 10472 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, 10473 Context.DependentTy, VK_RValue, 10474 RParenLoc); 10475 CE->setTypeDependent(true); 10476 *Result = Owned(CE); 10477 return true; 10478 } 10479 return false; 10480 } 10481 10482 UnbridgedCasts.restore(); 10483 return false; 10484 } 10485 10486 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 10487 /// the completed call expression. If overload resolution fails, emits 10488 /// diagnostics and returns ExprError() 10489 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10490 UnresolvedLookupExpr *ULE, 10491 SourceLocation LParenLoc, 10492 MultiExprArg Args, 10493 SourceLocation RParenLoc, 10494 Expr *ExecConfig, 10495 OverloadCandidateSet *CandidateSet, 10496 OverloadCandidateSet::iterator *Best, 10497 OverloadingResult OverloadResult, 10498 bool AllowTypoCorrection) { 10499 if (CandidateSet->empty()) 10500 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 10501 RParenLoc, /*EmptyLookup=*/true, 10502 AllowTypoCorrection); 10503 10504 switch (OverloadResult) { 10505 case OR_Success: { 10506 FunctionDecl *FDecl = (*Best)->Function; 10507 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 10508 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 10509 return ExprError(); 10510 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10511 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10512 ExecConfig); 10513 } 10514 10515 case OR_No_Viable_Function: { 10516 // Try to recover by looking for viable functions which the user might 10517 // have meant to call. 10518 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 10519 Args, RParenLoc, 10520 /*EmptyLookup=*/false, 10521 AllowTypoCorrection); 10522 if (!Recovery.isInvalid()) 10523 return Recovery; 10524 10525 SemaRef.Diag(Fn->getLocStart(), 10526 diag::err_ovl_no_viable_function_in_call) 10527 << ULE->getName() << Fn->getSourceRange(); 10528 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10529 break; 10530 } 10531 10532 case OR_Ambiguous: 10533 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 10534 << ULE->getName() << Fn->getSourceRange(); 10535 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 10536 break; 10537 10538 case OR_Deleted: { 10539 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 10540 << (*Best)->Function->isDeleted() 10541 << ULE->getName() 10542 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 10543 << Fn->getSourceRange(); 10544 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10545 10546 // We emitted an error for the unvailable/deleted function call but keep 10547 // the call in the AST. 10548 FunctionDecl *FDecl = (*Best)->Function; 10549 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10550 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10551 ExecConfig); 10552 } 10553 } 10554 10555 // Overload resolution failed. 10556 return ExprError(); 10557 } 10558 10559 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 10560 /// (which eventually refers to the declaration Func) and the call 10561 /// arguments Args/NumArgs, attempt to resolve the function call down 10562 /// to a specific function. If overload resolution succeeds, returns 10563 /// the call expression produced by overload resolution. 10564 /// Otherwise, emits diagnostics and returns ExprError. 10565 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 10566 UnresolvedLookupExpr *ULE, 10567 SourceLocation LParenLoc, 10568 MultiExprArg Args, 10569 SourceLocation RParenLoc, 10570 Expr *ExecConfig, 10571 bool AllowTypoCorrection) { 10572 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 10573 ExprResult result; 10574 10575 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 10576 &result)) 10577 return result; 10578 10579 OverloadCandidateSet::iterator Best; 10580 OverloadingResult OverloadResult = 10581 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 10582 10583 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 10584 RParenLoc, ExecConfig, &CandidateSet, 10585 &Best, OverloadResult, 10586 AllowTypoCorrection); 10587 } 10588 10589 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 10590 return Functions.size() > 1 || 10591 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 10592 } 10593 10594 /// \brief Create a unary operation that may resolve to an overloaded 10595 /// operator. 10596 /// 10597 /// \param OpLoc The location of the operator itself (e.g., '*'). 10598 /// 10599 /// \param OpcIn The UnaryOperator::Opcode that describes this 10600 /// operator. 10601 /// 10602 /// \param Fns The set of non-member functions that will be 10603 /// considered by overload resolution. The caller needs to build this 10604 /// set based on the context using, e.g., 10605 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10606 /// set should not contain any member functions; those will be added 10607 /// by CreateOverloadedUnaryOp(). 10608 /// 10609 /// \param Input The input argument. 10610 ExprResult 10611 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 10612 const UnresolvedSetImpl &Fns, 10613 Expr *Input) { 10614 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 10615 10616 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 10617 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 10618 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10619 // TODO: provide better source location info. 10620 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10621 10622 if (checkPlaceholderForOverload(*this, Input)) 10623 return ExprError(); 10624 10625 Expr *Args[2] = { Input, 0 }; 10626 unsigned NumArgs = 1; 10627 10628 // For post-increment and post-decrement, add the implicit '0' as 10629 // the second argument, so that we know this is a post-increment or 10630 // post-decrement. 10631 if (Opc == UO_PostInc || Opc == UO_PostDec) { 10632 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 10633 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 10634 SourceLocation()); 10635 NumArgs = 2; 10636 } 10637 10638 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 10639 10640 if (Input->isTypeDependent()) { 10641 if (Fns.empty()) 10642 return Owned(new (Context) UnaryOperator(Input, 10643 Opc, 10644 Context.DependentTy, 10645 VK_RValue, OK_Ordinary, 10646 OpLoc)); 10647 10648 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10649 UnresolvedLookupExpr *Fn 10650 = UnresolvedLookupExpr::Create(Context, NamingClass, 10651 NestedNameSpecifierLoc(), OpNameInfo, 10652 /*ADL*/ true, IsOverloaded(Fns), 10653 Fns.begin(), Fns.end()); 10654 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, 10655 Context.DependentTy, 10656 VK_RValue, 10657 OpLoc, false)); 10658 } 10659 10660 // Build an empty overload set. 10661 OverloadCandidateSet CandidateSet(OpLoc); 10662 10663 // Add the candidates from the given function set. 10664 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false); 10665 10666 // Add operator candidates that are member functions. 10667 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10668 10669 // Add candidates from ADL. 10670 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc, 10671 ArgsArray, /*ExplicitTemplateArgs*/ 0, 10672 CandidateSet); 10673 10674 // Add builtin operator candidates. 10675 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10676 10677 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10678 10679 // Perform overload resolution. 10680 OverloadCandidateSet::iterator Best; 10681 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10682 case OR_Success: { 10683 // We found a built-in operator or an overloaded operator. 10684 FunctionDecl *FnDecl = Best->Function; 10685 10686 if (FnDecl) { 10687 // We matched an overloaded operator. Build a call to that 10688 // operator. 10689 10690 // Convert the arguments. 10691 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10692 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 10693 10694 ExprResult InputRes = 10695 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 10696 Best->FoundDecl, Method); 10697 if (InputRes.isInvalid()) 10698 return ExprError(); 10699 Input = InputRes.take(); 10700 } else { 10701 // Convert the arguments. 10702 ExprResult InputInit 10703 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10704 Context, 10705 FnDecl->getParamDecl(0)), 10706 SourceLocation(), 10707 Input); 10708 if (InputInit.isInvalid()) 10709 return ExprError(); 10710 Input = InputInit.take(); 10711 } 10712 10713 // Build the actual expression node. 10714 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 10715 HadMultipleCandidates, OpLoc); 10716 if (FnExpr.isInvalid()) 10717 return ExprError(); 10718 10719 // Determine the result type. 10720 QualType ResultTy = FnDecl->getReturnType(); 10721 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10722 ResultTy = ResultTy.getNonLValueExprType(Context); 10723 10724 Args[0] = Input; 10725 CallExpr *TheCall = 10726 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray, 10727 ResultTy, VK, OpLoc, false); 10728 10729 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 10730 return ExprError(); 10731 10732 return MaybeBindToTemporary(TheCall); 10733 } else { 10734 // We matched a built-in operator. Convert the arguments, then 10735 // break out so that we will build the appropriate built-in 10736 // operator node. 10737 ExprResult InputRes = 10738 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 10739 Best->Conversions[0], AA_Passing); 10740 if (InputRes.isInvalid()) 10741 return ExprError(); 10742 Input = InputRes.take(); 10743 break; 10744 } 10745 } 10746 10747 case OR_No_Viable_Function: 10748 // This is an erroneous use of an operator which can be overloaded by 10749 // a non-member function. Check for non-member operators which were 10750 // defined too late to be candidates. 10751 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 10752 // FIXME: Recover by calling the found function. 10753 return ExprError(); 10754 10755 // No viable function; fall through to handling this as a 10756 // built-in operator, which will produce an error message for us. 10757 break; 10758 10759 case OR_Ambiguous: 10760 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 10761 << UnaryOperator::getOpcodeStr(Opc) 10762 << Input->getType() 10763 << Input->getSourceRange(); 10764 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 10765 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10766 return ExprError(); 10767 10768 case OR_Deleted: 10769 Diag(OpLoc, diag::err_ovl_deleted_oper) 10770 << Best->Function->isDeleted() 10771 << UnaryOperator::getOpcodeStr(Opc) 10772 << getDeletedOrUnavailableSuffix(Best->Function) 10773 << Input->getSourceRange(); 10774 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 10775 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10776 return ExprError(); 10777 } 10778 10779 // Either we found no viable overloaded operator or we matched a 10780 // built-in operator. In either case, fall through to trying to 10781 // build a built-in operation. 10782 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10783 } 10784 10785 /// \brief Create a binary operation that may resolve to an overloaded 10786 /// operator. 10787 /// 10788 /// \param OpLoc The location of the operator itself (e.g., '+'). 10789 /// 10790 /// \param OpcIn The BinaryOperator::Opcode that describes this 10791 /// operator. 10792 /// 10793 /// \param Fns The set of non-member functions that will be 10794 /// considered by overload resolution. The caller needs to build this 10795 /// set based on the context using, e.g., 10796 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10797 /// set should not contain any member functions; those will be added 10798 /// by CreateOverloadedBinOp(). 10799 /// 10800 /// \param LHS Left-hand argument. 10801 /// \param RHS Right-hand argument. 10802 ExprResult 10803 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 10804 unsigned OpcIn, 10805 const UnresolvedSetImpl &Fns, 10806 Expr *LHS, Expr *RHS) { 10807 Expr *Args[2] = { LHS, RHS }; 10808 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 10809 10810 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 10811 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 10812 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10813 10814 // If either side is type-dependent, create an appropriate dependent 10815 // expression. 10816 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10817 if (Fns.empty()) { 10818 // If there are no functions to store, just build a dependent 10819 // BinaryOperator or CompoundAssignment. 10820 if (Opc <= BO_Assign || Opc > BO_OrAssign) 10821 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 10822 Context.DependentTy, 10823 VK_RValue, OK_Ordinary, 10824 OpLoc, 10825 FPFeatures.fp_contract)); 10826 10827 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 10828 Context.DependentTy, 10829 VK_LValue, 10830 OK_Ordinary, 10831 Context.DependentTy, 10832 Context.DependentTy, 10833 OpLoc, 10834 FPFeatures.fp_contract)); 10835 } 10836 10837 // FIXME: save results of ADL from here? 10838 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10839 // TODO: provide better source location info in DNLoc component. 10840 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10841 UnresolvedLookupExpr *Fn 10842 = UnresolvedLookupExpr::Create(Context, NamingClass, 10843 NestedNameSpecifierLoc(), OpNameInfo, 10844 /*ADL*/ true, IsOverloaded(Fns), 10845 Fns.begin(), Fns.end()); 10846 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args, 10847 Context.DependentTy, VK_RValue, 10848 OpLoc, FPFeatures.fp_contract)); 10849 } 10850 10851 // Always do placeholder-like conversions on the RHS. 10852 if (checkPlaceholderForOverload(*this, Args[1])) 10853 return ExprError(); 10854 10855 // Do placeholder-like conversion on the LHS; note that we should 10856 // not get here with a PseudoObject LHS. 10857 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 10858 if (checkPlaceholderForOverload(*this, Args[0])) 10859 return ExprError(); 10860 10861 // If this is the assignment operator, we only perform overload resolution 10862 // if the left-hand side is a class or enumeration type. This is actually 10863 // a hack. The standard requires that we do overload resolution between the 10864 // various built-in candidates, but as DR507 points out, this can lead to 10865 // problems. So we do it this way, which pretty much follows what GCC does. 10866 // Note that we go the traditional code path for compound assignment forms. 10867 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 10868 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10869 10870 // If this is the .* operator, which is not overloadable, just 10871 // create a built-in binary operator. 10872 if (Opc == BO_PtrMemD) 10873 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10874 10875 // Build an empty overload set. 10876 OverloadCandidateSet CandidateSet(OpLoc); 10877 10878 // Add the candidates from the given function set. 10879 AddFunctionCandidates(Fns, Args, CandidateSet, false); 10880 10881 // Add operator candidates that are member functions. 10882 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 10883 10884 // Add candidates from ADL. 10885 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10886 OpLoc, Args, 10887 /*ExplicitTemplateArgs*/ 0, 10888 CandidateSet); 10889 10890 // Add builtin operator candidates. 10891 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 10892 10893 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10894 10895 // Perform overload resolution. 10896 OverloadCandidateSet::iterator Best; 10897 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10898 case OR_Success: { 10899 // We found a built-in operator or an overloaded operator. 10900 FunctionDecl *FnDecl = Best->Function; 10901 10902 if (FnDecl) { 10903 // We matched an overloaded operator. Build a call to that 10904 // operator. 10905 10906 // Convert the arguments. 10907 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10908 // Best->Access is only meaningful for class members. 10909 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 10910 10911 ExprResult Arg1 = 10912 PerformCopyInitialization( 10913 InitializedEntity::InitializeParameter(Context, 10914 FnDecl->getParamDecl(0)), 10915 SourceLocation(), Owned(Args[1])); 10916 if (Arg1.isInvalid()) 10917 return ExprError(); 10918 10919 ExprResult Arg0 = 10920 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10921 Best->FoundDecl, Method); 10922 if (Arg0.isInvalid()) 10923 return ExprError(); 10924 Args[0] = Arg0.takeAs<Expr>(); 10925 Args[1] = RHS = Arg1.takeAs<Expr>(); 10926 } else { 10927 // Convert the arguments. 10928 ExprResult Arg0 = PerformCopyInitialization( 10929 InitializedEntity::InitializeParameter(Context, 10930 FnDecl->getParamDecl(0)), 10931 SourceLocation(), Owned(Args[0])); 10932 if (Arg0.isInvalid()) 10933 return ExprError(); 10934 10935 ExprResult Arg1 = 10936 PerformCopyInitialization( 10937 InitializedEntity::InitializeParameter(Context, 10938 FnDecl->getParamDecl(1)), 10939 SourceLocation(), Owned(Args[1])); 10940 if (Arg1.isInvalid()) 10941 return ExprError(); 10942 Args[0] = LHS = Arg0.takeAs<Expr>(); 10943 Args[1] = RHS = Arg1.takeAs<Expr>(); 10944 } 10945 10946 // Build the actual expression node. 10947 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10948 Best->FoundDecl, 10949 HadMultipleCandidates, OpLoc); 10950 if (FnExpr.isInvalid()) 10951 return ExprError(); 10952 10953 // Determine the result type. 10954 QualType ResultTy = FnDecl->getReturnType(); 10955 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10956 ResultTy = ResultTy.getNonLValueExprType(Context); 10957 10958 CXXOperatorCallExpr *TheCall = 10959 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10960 Args, ResultTy, VK, OpLoc, 10961 FPFeatures.fp_contract); 10962 10963 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 10964 FnDecl)) 10965 return ExprError(); 10966 10967 ArrayRef<const Expr *> ArgsArray(Args, 2); 10968 // Cut off the implicit 'this'. 10969 if (isa<CXXMethodDecl>(FnDecl)) 10970 ArgsArray = ArgsArray.slice(1); 10971 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc, 10972 TheCall->getSourceRange(), VariadicDoesNotApply); 10973 10974 return MaybeBindToTemporary(TheCall); 10975 } else { 10976 // We matched a built-in operator. Convert the arguments, then 10977 // break out so that we will build the appropriate built-in 10978 // operator node. 10979 ExprResult ArgsRes0 = 10980 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10981 Best->Conversions[0], AA_Passing); 10982 if (ArgsRes0.isInvalid()) 10983 return ExprError(); 10984 Args[0] = ArgsRes0.take(); 10985 10986 ExprResult ArgsRes1 = 10987 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10988 Best->Conversions[1], AA_Passing); 10989 if (ArgsRes1.isInvalid()) 10990 return ExprError(); 10991 Args[1] = ArgsRes1.take(); 10992 break; 10993 } 10994 } 10995 10996 case OR_No_Viable_Function: { 10997 // C++ [over.match.oper]p9: 10998 // If the operator is the operator , [...] and there are no 10999 // viable functions, then the operator is assumed to be the 11000 // built-in operator and interpreted according to clause 5. 11001 if (Opc == BO_Comma) 11002 break; 11003 11004 // For class as left operand for assignment or compound assigment 11005 // operator do not fall through to handling in built-in, but report that 11006 // no overloaded assignment operator found 11007 ExprResult Result = ExprError(); 11008 if (Args[0]->getType()->isRecordType() && 11009 Opc >= BO_Assign && Opc <= BO_OrAssign) { 11010 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11011 << BinaryOperator::getOpcodeStr(Opc) 11012 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11013 if (Args[0]->getType()->isIncompleteType()) { 11014 Diag(OpLoc, diag::note_assign_lhs_incomplete) 11015 << Args[0]->getType() 11016 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11017 } 11018 } else { 11019 // This is an erroneous use of an operator which can be overloaded by 11020 // a non-member function. Check for non-member operators which were 11021 // defined too late to be candidates. 11022 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 11023 // FIXME: Recover by calling the found function. 11024 return ExprError(); 11025 11026 // No viable function; try to create a built-in operation, which will 11027 // produce an error. Then, show the non-viable candidates. 11028 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11029 } 11030 assert(Result.isInvalid() && 11031 "C++ binary operator overloading is missing candidates!"); 11032 if (Result.isInvalid()) 11033 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11034 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11035 return Result; 11036 } 11037 11038 case OR_Ambiguous: 11039 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 11040 << BinaryOperator::getOpcodeStr(Opc) 11041 << Args[0]->getType() << Args[1]->getType() 11042 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11043 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11044 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11045 return ExprError(); 11046 11047 case OR_Deleted: 11048 if (isImplicitlyDeleted(Best->Function)) { 11049 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11050 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 11051 << Context.getRecordType(Method->getParent()) 11052 << getSpecialMember(Method); 11053 11054 // The user probably meant to call this special member. Just 11055 // explain why it's deleted. 11056 NoteDeletedFunction(Method); 11057 return ExprError(); 11058 } else { 11059 Diag(OpLoc, diag::err_ovl_deleted_oper) 11060 << Best->Function->isDeleted() 11061 << BinaryOperator::getOpcodeStr(Opc) 11062 << getDeletedOrUnavailableSuffix(Best->Function) 11063 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11064 } 11065 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11066 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11067 return ExprError(); 11068 } 11069 11070 // We matched a built-in operator; build it. 11071 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11072 } 11073 11074 ExprResult 11075 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 11076 SourceLocation RLoc, 11077 Expr *Base, Expr *Idx) { 11078 Expr *Args[2] = { Base, Idx }; 11079 DeclarationName OpName = 11080 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 11081 11082 // If either side is type-dependent, create an appropriate dependent 11083 // expression. 11084 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11085 11086 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 11087 // CHECKME: no 'operator' keyword? 11088 DeclarationNameInfo OpNameInfo(OpName, LLoc); 11089 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11090 UnresolvedLookupExpr *Fn 11091 = UnresolvedLookupExpr::Create(Context, NamingClass, 11092 NestedNameSpecifierLoc(), OpNameInfo, 11093 /*ADL*/ true, /*Overloaded*/ false, 11094 UnresolvedSetIterator(), 11095 UnresolvedSetIterator()); 11096 // Can't add any actual overloads yet 11097 11098 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 11099 Args, 11100 Context.DependentTy, 11101 VK_RValue, 11102 RLoc, false)); 11103 } 11104 11105 // Handle placeholders on both operands. 11106 if (checkPlaceholderForOverload(*this, Args[0])) 11107 return ExprError(); 11108 if (checkPlaceholderForOverload(*this, Args[1])) 11109 return ExprError(); 11110 11111 // Build an empty overload set. 11112 OverloadCandidateSet CandidateSet(LLoc); 11113 11114 // Subscript can only be overloaded as a member function. 11115 11116 // Add operator candidates that are member functions. 11117 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11118 11119 // Add builtin operator candidates. 11120 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11121 11122 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11123 11124 // Perform overload resolution. 11125 OverloadCandidateSet::iterator Best; 11126 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 11127 case OR_Success: { 11128 // We found a built-in operator or an overloaded operator. 11129 FunctionDecl *FnDecl = Best->Function; 11130 11131 if (FnDecl) { 11132 // We matched an overloaded operator. Build a call to that 11133 // operator. 11134 11135 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 11136 11137 // Convert the arguments. 11138 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 11139 ExprResult Arg0 = 11140 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 11141 Best->FoundDecl, Method); 11142 if (Arg0.isInvalid()) 11143 return ExprError(); 11144 Args[0] = Arg0.take(); 11145 11146 // Convert the arguments. 11147 ExprResult InputInit 11148 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11149 Context, 11150 FnDecl->getParamDecl(0)), 11151 SourceLocation(), 11152 Owned(Args[1])); 11153 if (InputInit.isInvalid()) 11154 return ExprError(); 11155 11156 Args[1] = InputInit.takeAs<Expr>(); 11157 11158 // Build the actual expression node. 11159 DeclarationNameInfo OpLocInfo(OpName, LLoc); 11160 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11161 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11162 Best->FoundDecl, 11163 HadMultipleCandidates, 11164 OpLocInfo.getLoc(), 11165 OpLocInfo.getInfo()); 11166 if (FnExpr.isInvalid()) 11167 return ExprError(); 11168 11169 // Determine the result type 11170 QualType ResultTy = FnDecl->getReturnType(); 11171 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11172 ResultTy = ResultTy.getNonLValueExprType(Context); 11173 11174 CXXOperatorCallExpr *TheCall = 11175 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 11176 FnExpr.take(), Args, 11177 ResultTy, VK, RLoc, 11178 false); 11179 11180 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 11181 return ExprError(); 11182 11183 return MaybeBindToTemporary(TheCall); 11184 } else { 11185 // We matched a built-in operator. Convert the arguments, then 11186 // break out so that we will build the appropriate built-in 11187 // operator node. 11188 ExprResult ArgsRes0 = 11189 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11190 Best->Conversions[0], AA_Passing); 11191 if (ArgsRes0.isInvalid()) 11192 return ExprError(); 11193 Args[0] = ArgsRes0.take(); 11194 11195 ExprResult ArgsRes1 = 11196 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11197 Best->Conversions[1], AA_Passing); 11198 if (ArgsRes1.isInvalid()) 11199 return ExprError(); 11200 Args[1] = ArgsRes1.take(); 11201 11202 break; 11203 } 11204 } 11205 11206 case OR_No_Viable_Function: { 11207 if (CandidateSet.empty()) 11208 Diag(LLoc, diag::err_ovl_no_oper) 11209 << Args[0]->getType() << /*subscript*/ 0 11210 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11211 else 11212 Diag(LLoc, diag::err_ovl_no_viable_subscript) 11213 << Args[0]->getType() 11214 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11215 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11216 "[]", LLoc); 11217 return ExprError(); 11218 } 11219 11220 case OR_Ambiguous: 11221 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 11222 << "[]" 11223 << Args[0]->getType() << Args[1]->getType() 11224 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11225 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11226 "[]", LLoc); 11227 return ExprError(); 11228 11229 case OR_Deleted: 11230 Diag(LLoc, diag::err_ovl_deleted_oper) 11231 << Best->Function->isDeleted() << "[]" 11232 << getDeletedOrUnavailableSuffix(Best->Function) 11233 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11234 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11235 "[]", LLoc); 11236 return ExprError(); 11237 } 11238 11239 // We matched a built-in operator; build it. 11240 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 11241 } 11242 11243 /// BuildCallToMemberFunction - Build a call to a member 11244 /// function. MemExpr is the expression that refers to the member 11245 /// function (and includes the object parameter), Args/NumArgs are the 11246 /// arguments to the function call (not including the object 11247 /// parameter). The caller needs to validate that the member 11248 /// expression refers to a non-static member function or an overloaded 11249 /// member function. 11250 ExprResult 11251 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 11252 SourceLocation LParenLoc, 11253 MultiExprArg Args, 11254 SourceLocation RParenLoc) { 11255 assert(MemExprE->getType() == Context.BoundMemberTy || 11256 MemExprE->getType() == Context.OverloadTy); 11257 11258 // Dig out the member expression. This holds both the object 11259 // argument and the member function we're referring to. 11260 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 11261 11262 // Determine whether this is a call to a pointer-to-member function. 11263 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 11264 assert(op->getType() == Context.BoundMemberTy); 11265 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 11266 11267 QualType fnType = 11268 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 11269 11270 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 11271 QualType resultType = proto->getCallResultType(Context); 11272 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 11273 11274 // Check that the object type isn't more qualified than the 11275 // member function we're calling. 11276 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 11277 11278 QualType objectType = op->getLHS()->getType(); 11279 if (op->getOpcode() == BO_PtrMemI) 11280 objectType = objectType->castAs<PointerType>()->getPointeeType(); 11281 Qualifiers objectQuals = objectType.getQualifiers(); 11282 11283 Qualifiers difference = objectQuals - funcQuals; 11284 difference.removeObjCGCAttr(); 11285 difference.removeAddressSpace(); 11286 if (difference) { 11287 std::string qualsString = difference.getAsString(); 11288 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 11289 << fnType.getUnqualifiedType() 11290 << qualsString 11291 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 11292 } 11293 11294 CXXMemberCallExpr *call 11295 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11296 resultType, valueKind, RParenLoc); 11297 11298 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 11299 call, 0)) 11300 return ExprError(); 11301 11302 if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc)) 11303 return ExprError(); 11304 11305 if (CheckOtherCall(call, proto)) 11306 return ExprError(); 11307 11308 return MaybeBindToTemporary(call); 11309 } 11310 11311 UnbridgedCastsSet UnbridgedCasts; 11312 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11313 return ExprError(); 11314 11315 MemberExpr *MemExpr; 11316 CXXMethodDecl *Method = 0; 11317 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 11318 NestedNameSpecifier *Qualifier = 0; 11319 if (isa<MemberExpr>(NakedMemExpr)) { 11320 MemExpr = cast<MemberExpr>(NakedMemExpr); 11321 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 11322 FoundDecl = MemExpr->getFoundDecl(); 11323 Qualifier = MemExpr->getQualifier(); 11324 UnbridgedCasts.restore(); 11325 } else { 11326 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 11327 Qualifier = UnresExpr->getQualifier(); 11328 11329 QualType ObjectType = UnresExpr->getBaseType(); 11330 Expr::Classification ObjectClassification 11331 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 11332 : UnresExpr->getBase()->Classify(Context); 11333 11334 // Add overload candidates 11335 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 11336 11337 // FIXME: avoid copy. 11338 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11339 if (UnresExpr->hasExplicitTemplateArgs()) { 11340 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11341 TemplateArgs = &TemplateArgsBuffer; 11342 } 11343 11344 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 11345 E = UnresExpr->decls_end(); I != E; ++I) { 11346 11347 NamedDecl *Func = *I; 11348 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 11349 if (isa<UsingShadowDecl>(Func)) 11350 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 11351 11352 11353 // Microsoft supports direct constructor calls. 11354 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 11355 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 11356 Args, CandidateSet); 11357 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 11358 // If explicit template arguments were provided, we can't call a 11359 // non-template member function. 11360 if (TemplateArgs) 11361 continue; 11362 11363 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 11364 ObjectClassification, Args, CandidateSet, 11365 /*SuppressUserConversions=*/false); 11366 } else { 11367 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 11368 I.getPair(), ActingDC, TemplateArgs, 11369 ObjectType, ObjectClassification, 11370 Args, CandidateSet, 11371 /*SuppressUsedConversions=*/false); 11372 } 11373 } 11374 11375 DeclarationName DeclName = UnresExpr->getMemberName(); 11376 11377 UnbridgedCasts.restore(); 11378 11379 OverloadCandidateSet::iterator Best; 11380 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 11381 Best)) { 11382 case OR_Success: 11383 Method = cast<CXXMethodDecl>(Best->Function); 11384 FoundDecl = Best->FoundDecl; 11385 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 11386 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 11387 return ExprError(); 11388 // If FoundDecl is different from Method (such as if one is a template 11389 // and the other a specialization), make sure DiagnoseUseOfDecl is 11390 // called on both. 11391 // FIXME: This would be more comprehensively addressed by modifying 11392 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 11393 // being used. 11394 if (Method != FoundDecl.getDecl() && 11395 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 11396 return ExprError(); 11397 break; 11398 11399 case OR_No_Viable_Function: 11400 Diag(UnresExpr->getMemberLoc(), 11401 diag::err_ovl_no_viable_member_function_in_call) 11402 << DeclName << MemExprE->getSourceRange(); 11403 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11404 // FIXME: Leaking incoming expressions! 11405 return ExprError(); 11406 11407 case OR_Ambiguous: 11408 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 11409 << DeclName << MemExprE->getSourceRange(); 11410 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11411 // FIXME: Leaking incoming expressions! 11412 return ExprError(); 11413 11414 case OR_Deleted: 11415 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 11416 << Best->Function->isDeleted() 11417 << DeclName 11418 << getDeletedOrUnavailableSuffix(Best->Function) 11419 << MemExprE->getSourceRange(); 11420 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11421 // FIXME: Leaking incoming expressions! 11422 return ExprError(); 11423 } 11424 11425 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 11426 11427 // If overload resolution picked a static member, build a 11428 // non-member call based on that function. 11429 if (Method->isStatic()) { 11430 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 11431 RParenLoc); 11432 } 11433 11434 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 11435 } 11436 11437 QualType ResultType = Method->getReturnType(); 11438 ExprValueKind VK = Expr::getValueKindForType(ResultType); 11439 ResultType = ResultType.getNonLValueExprType(Context); 11440 11441 assert(Method && "Member call to something that isn't a method?"); 11442 CXXMemberCallExpr *TheCall = 11443 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11444 ResultType, VK, RParenLoc); 11445 11446 // Check for a valid return type. 11447 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 11448 TheCall, Method)) 11449 return ExprError(); 11450 11451 // Convert the object argument (for a non-static member function call). 11452 // We only need to do this if there was actually an overload; otherwise 11453 // it was done at lookup. 11454 if (!Method->isStatic()) { 11455 ExprResult ObjectArg = 11456 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 11457 FoundDecl, Method); 11458 if (ObjectArg.isInvalid()) 11459 return ExprError(); 11460 MemExpr->setBase(ObjectArg.take()); 11461 } 11462 11463 // Convert the rest of the arguments 11464 const FunctionProtoType *Proto = 11465 Method->getType()->getAs<FunctionProtoType>(); 11466 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 11467 RParenLoc)) 11468 return ExprError(); 11469 11470 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11471 11472 if (CheckFunctionCall(Method, TheCall, Proto)) 11473 return ExprError(); 11474 11475 if ((isa<CXXConstructorDecl>(CurContext) || 11476 isa<CXXDestructorDecl>(CurContext)) && 11477 TheCall->getMethodDecl()->isPure()) { 11478 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 11479 11480 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 11481 Diag(MemExpr->getLocStart(), 11482 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 11483 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 11484 << MD->getParent()->getDeclName(); 11485 11486 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 11487 } 11488 } 11489 return MaybeBindToTemporary(TheCall); 11490 } 11491 11492 /// BuildCallToObjectOfClassType - Build a call to an object of class 11493 /// type (C++ [over.call.object]), which can end up invoking an 11494 /// overloaded function call operator (@c operator()) or performing a 11495 /// user-defined conversion on the object argument. 11496 ExprResult 11497 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 11498 SourceLocation LParenLoc, 11499 MultiExprArg Args, 11500 SourceLocation RParenLoc) { 11501 if (checkPlaceholderForOverload(*this, Obj)) 11502 return ExprError(); 11503 ExprResult Object = Owned(Obj); 11504 11505 UnbridgedCastsSet UnbridgedCasts; 11506 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11507 return ExprError(); 11508 11509 assert(Object.get()->getType()->isRecordType() && "Requires object type argument"); 11510 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 11511 11512 // C++ [over.call.object]p1: 11513 // If the primary-expression E in the function call syntax 11514 // evaluates to a class object of type "cv T", then the set of 11515 // candidate functions includes at least the function call 11516 // operators of T. The function call operators of T are obtained by 11517 // ordinary lookup of the name operator() in the context of 11518 // (E).operator(). 11519 OverloadCandidateSet CandidateSet(LParenLoc); 11520 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 11521 11522 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 11523 diag::err_incomplete_object_call, Object.get())) 11524 return true; 11525 11526 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 11527 LookupQualifiedName(R, Record->getDecl()); 11528 R.suppressDiagnostics(); 11529 11530 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11531 Oper != OperEnd; ++Oper) { 11532 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 11533 Object.get()->Classify(Context), 11534 Args, CandidateSet, 11535 /*SuppressUserConversions=*/ false); 11536 } 11537 11538 // C++ [over.call.object]p2: 11539 // In addition, for each (non-explicit in C++0x) conversion function 11540 // declared in T of the form 11541 // 11542 // operator conversion-type-id () cv-qualifier; 11543 // 11544 // where cv-qualifier is the same cv-qualification as, or a 11545 // greater cv-qualification than, cv, and where conversion-type-id 11546 // denotes the type "pointer to function of (P1,...,Pn) returning 11547 // R", or the type "reference to pointer to function of 11548 // (P1,...,Pn) returning R", or the type "reference to function 11549 // of (P1,...,Pn) returning R", a surrogate call function [...] 11550 // is also considered as a candidate function. Similarly, 11551 // surrogate call functions are added to the set of candidate 11552 // functions for each conversion function declared in an 11553 // accessible base class provided the function is not hidden 11554 // within T by another intervening declaration. 11555 std::pair<CXXRecordDecl::conversion_iterator, 11556 CXXRecordDecl::conversion_iterator> Conversions 11557 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 11558 for (CXXRecordDecl::conversion_iterator 11559 I = Conversions.first, E = Conversions.second; I != E; ++I) { 11560 NamedDecl *D = *I; 11561 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 11562 if (isa<UsingShadowDecl>(D)) 11563 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 11564 11565 // Skip over templated conversion functions; they aren't 11566 // surrogates. 11567 if (isa<FunctionTemplateDecl>(D)) 11568 continue; 11569 11570 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 11571 if (!Conv->isExplicit()) { 11572 // Strip the reference type (if any) and then the pointer type (if 11573 // any) to get down to what might be a function type. 11574 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 11575 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11576 ConvType = ConvPtrType->getPointeeType(); 11577 11578 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 11579 { 11580 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 11581 Object.get(), Args, CandidateSet); 11582 } 11583 } 11584 } 11585 11586 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11587 11588 // Perform overload resolution. 11589 OverloadCandidateSet::iterator Best; 11590 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 11591 Best)) { 11592 case OR_Success: 11593 // Overload resolution succeeded; we'll build the appropriate call 11594 // below. 11595 break; 11596 11597 case OR_No_Viable_Function: 11598 if (CandidateSet.empty()) 11599 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 11600 << Object.get()->getType() << /*call*/ 1 11601 << Object.get()->getSourceRange(); 11602 else 11603 Diag(Object.get()->getLocStart(), 11604 diag::err_ovl_no_viable_object_call) 11605 << Object.get()->getType() << Object.get()->getSourceRange(); 11606 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11607 break; 11608 11609 case OR_Ambiguous: 11610 Diag(Object.get()->getLocStart(), 11611 diag::err_ovl_ambiguous_object_call) 11612 << Object.get()->getType() << Object.get()->getSourceRange(); 11613 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11614 break; 11615 11616 case OR_Deleted: 11617 Diag(Object.get()->getLocStart(), 11618 diag::err_ovl_deleted_object_call) 11619 << Best->Function->isDeleted() 11620 << Object.get()->getType() 11621 << getDeletedOrUnavailableSuffix(Best->Function) 11622 << Object.get()->getSourceRange(); 11623 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11624 break; 11625 } 11626 11627 if (Best == CandidateSet.end()) 11628 return true; 11629 11630 UnbridgedCasts.restore(); 11631 11632 if (Best->Function == 0) { 11633 // Since there is no function declaration, this is one of the 11634 // surrogate candidates. Dig out the conversion function. 11635 CXXConversionDecl *Conv 11636 = cast<CXXConversionDecl>( 11637 Best->Conversions[0].UserDefined.ConversionFunction); 11638 11639 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11640 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 11641 return ExprError(); 11642 assert(Conv == Best->FoundDecl.getDecl() && 11643 "Found Decl & conversion-to-functionptr should be same, right?!"); 11644 // We selected one of the surrogate functions that converts the 11645 // object parameter to a function pointer. Perform the conversion 11646 // on the object argument, then let ActOnCallExpr finish the job. 11647 11648 // Create an implicit member expr to refer to the conversion operator. 11649 // and then call it. 11650 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 11651 Conv, HadMultipleCandidates); 11652 if (Call.isInvalid()) 11653 return ExprError(); 11654 // Record usage of conversion in an implicit cast. 11655 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(), 11656 CK_UserDefinedConversion, 11657 Call.get(), 0, VK_RValue)); 11658 11659 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 11660 } 11661 11662 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11663 11664 // We found an overloaded operator(). Build a CXXOperatorCallExpr 11665 // that calls this method, using Object for the implicit object 11666 // parameter and passing along the remaining arguments. 11667 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11668 11669 // An error diagnostic has already been printed when parsing the declaration. 11670 if (Method->isInvalidDecl()) 11671 return ExprError(); 11672 11673 const FunctionProtoType *Proto = 11674 Method->getType()->getAs<FunctionProtoType>(); 11675 11676 unsigned NumParams = Proto->getNumParams(); 11677 11678 DeclarationNameInfo OpLocInfo( 11679 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 11680 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 11681 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11682 HadMultipleCandidates, 11683 OpLocInfo.getLoc(), 11684 OpLocInfo.getInfo()); 11685 if (NewFn.isInvalid()) 11686 return true; 11687 11688 // Build the full argument list for the method call (the implicit object 11689 // parameter is placed at the beginning of the list). 11690 llvm::OwningArrayPtr<Expr *> MethodArgs(new Expr*[Args.size() + 1]); 11691 MethodArgs[0] = Object.get(); 11692 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 11693 11694 // Once we've built TheCall, all of the expressions are properly 11695 // owned. 11696 QualType ResultTy = Method->getReturnType(); 11697 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11698 ResultTy = ResultTy.getNonLValueExprType(Context); 11699 11700 CXXOperatorCallExpr *TheCall = new (Context) 11701 CXXOperatorCallExpr(Context, OO_Call, NewFn.take(), 11702 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 11703 ResultTy, VK, RParenLoc, false); 11704 MethodArgs.reset(); 11705 11706 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 11707 return true; 11708 11709 // We may have default arguments. If so, we need to allocate more 11710 // slots in the call for them. 11711 if (Args.size() < NumParams) 11712 TheCall->setNumArgs(Context, NumParams + 1); 11713 11714 bool IsError = false; 11715 11716 // Initialize the implicit object parameter. 11717 ExprResult ObjRes = 11718 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0, 11719 Best->FoundDecl, Method); 11720 if (ObjRes.isInvalid()) 11721 IsError = true; 11722 else 11723 Object = ObjRes; 11724 TheCall->setArg(0, Object.take()); 11725 11726 // Check the argument types. 11727 for (unsigned i = 0; i != NumParams; i++) { 11728 Expr *Arg; 11729 if (i < Args.size()) { 11730 Arg = Args[i]; 11731 11732 // Pass the argument. 11733 11734 ExprResult InputInit 11735 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11736 Context, 11737 Method->getParamDecl(i)), 11738 SourceLocation(), Arg); 11739 11740 IsError |= InputInit.isInvalid(); 11741 Arg = InputInit.takeAs<Expr>(); 11742 } else { 11743 ExprResult DefArg 11744 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 11745 if (DefArg.isInvalid()) { 11746 IsError = true; 11747 break; 11748 } 11749 11750 Arg = DefArg.takeAs<Expr>(); 11751 } 11752 11753 TheCall->setArg(i + 1, Arg); 11754 } 11755 11756 // If this is a variadic call, handle args passed through "...". 11757 if (Proto->isVariadic()) { 11758 // Promote the arguments (C99 6.5.2.2p7). 11759 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 11760 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); 11761 IsError |= Arg.isInvalid(); 11762 TheCall->setArg(i + 1, Arg.take()); 11763 } 11764 } 11765 11766 if (IsError) return true; 11767 11768 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11769 11770 if (CheckFunctionCall(Method, TheCall, Proto)) 11771 return true; 11772 11773 return MaybeBindToTemporary(TheCall); 11774 } 11775 11776 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 11777 /// (if one exists), where @c Base is an expression of class type and 11778 /// @c Member is the name of the member we're trying to find. 11779 ExprResult 11780 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 11781 bool *NoArrowOperatorFound) { 11782 assert(Base->getType()->isRecordType() && 11783 "left-hand side must have class type"); 11784 11785 if (checkPlaceholderForOverload(*this, Base)) 11786 return ExprError(); 11787 11788 SourceLocation Loc = Base->getExprLoc(); 11789 11790 // C++ [over.ref]p1: 11791 // 11792 // [...] An expression x->m is interpreted as (x.operator->())->m 11793 // for a class object x of type T if T::operator->() exists and if 11794 // the operator is selected as the best match function by the 11795 // overload resolution mechanism (13.3). 11796 DeclarationName OpName = 11797 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 11798 OverloadCandidateSet CandidateSet(Loc); 11799 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 11800 11801 if (RequireCompleteType(Loc, Base->getType(), 11802 diag::err_typecheck_incomplete_tag, Base)) 11803 return ExprError(); 11804 11805 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 11806 LookupQualifiedName(R, BaseRecord->getDecl()); 11807 R.suppressDiagnostics(); 11808 11809 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11810 Oper != OperEnd; ++Oper) { 11811 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 11812 None, CandidateSet, /*SuppressUserConversions=*/false); 11813 } 11814 11815 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11816 11817 // Perform overload resolution. 11818 OverloadCandidateSet::iterator Best; 11819 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11820 case OR_Success: 11821 // Overload resolution succeeded; we'll build the call below. 11822 break; 11823 11824 case OR_No_Viable_Function: 11825 if (CandidateSet.empty()) { 11826 QualType BaseType = Base->getType(); 11827 if (NoArrowOperatorFound) { 11828 // Report this specific error to the caller instead of emitting a 11829 // diagnostic, as requested. 11830 *NoArrowOperatorFound = true; 11831 return ExprError(); 11832 } 11833 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 11834 << BaseType << Base->getSourceRange(); 11835 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 11836 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 11837 << FixItHint::CreateReplacement(OpLoc, "."); 11838 } 11839 } else 11840 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11841 << "operator->" << Base->getSourceRange(); 11842 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11843 return ExprError(); 11844 11845 case OR_Ambiguous: 11846 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11847 << "->" << Base->getType() << Base->getSourceRange(); 11848 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 11849 return ExprError(); 11850 11851 case OR_Deleted: 11852 Diag(OpLoc, diag::err_ovl_deleted_oper) 11853 << Best->Function->isDeleted() 11854 << "->" 11855 << getDeletedOrUnavailableSuffix(Best->Function) 11856 << Base->getSourceRange(); 11857 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11858 return ExprError(); 11859 } 11860 11861 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 11862 11863 // Convert the object parameter. 11864 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11865 ExprResult BaseResult = 11866 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 11867 Best->FoundDecl, Method); 11868 if (BaseResult.isInvalid()) 11869 return ExprError(); 11870 Base = BaseResult.take(); 11871 11872 // Build the operator call. 11873 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11874 HadMultipleCandidates, OpLoc); 11875 if (FnExpr.isInvalid()) 11876 return ExprError(); 11877 11878 QualType ResultTy = Method->getReturnType(); 11879 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11880 ResultTy = ResultTy.getNonLValueExprType(Context); 11881 CXXOperatorCallExpr *TheCall = 11882 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(), 11883 Base, ResultTy, VK, OpLoc, false); 11884 11885 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 11886 return ExprError(); 11887 11888 return MaybeBindToTemporary(TheCall); 11889 } 11890 11891 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 11892 /// a literal operator described by the provided lookup results. 11893 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 11894 DeclarationNameInfo &SuffixInfo, 11895 ArrayRef<Expr*> Args, 11896 SourceLocation LitEndLoc, 11897 TemplateArgumentListInfo *TemplateArgs) { 11898 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 11899 11900 OverloadCandidateSet CandidateSet(UDSuffixLoc); 11901 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true, 11902 TemplateArgs); 11903 11904 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11905 11906 // Perform overload resolution. This will usually be trivial, but might need 11907 // to perform substitutions for a literal operator template. 11908 OverloadCandidateSet::iterator Best; 11909 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 11910 case OR_Success: 11911 case OR_Deleted: 11912 break; 11913 11914 case OR_No_Viable_Function: 11915 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 11916 << R.getLookupName(); 11917 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11918 return ExprError(); 11919 11920 case OR_Ambiguous: 11921 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 11922 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11923 return ExprError(); 11924 } 11925 11926 FunctionDecl *FD = Best->Function; 11927 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 11928 HadMultipleCandidates, 11929 SuffixInfo.getLoc(), 11930 SuffixInfo.getInfo()); 11931 if (Fn.isInvalid()) 11932 return true; 11933 11934 // Check the argument types. This should almost always be a no-op, except 11935 // that array-to-pointer decay is applied to string literals. 11936 Expr *ConvArgs[2]; 11937 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 11938 ExprResult InputInit = PerformCopyInitialization( 11939 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 11940 SourceLocation(), Args[ArgIdx]); 11941 if (InputInit.isInvalid()) 11942 return true; 11943 ConvArgs[ArgIdx] = InputInit.take(); 11944 } 11945 11946 QualType ResultTy = FD->getReturnType(); 11947 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11948 ResultTy = ResultTy.getNonLValueExprType(Context); 11949 11950 UserDefinedLiteral *UDL = 11951 new (Context) UserDefinedLiteral(Context, Fn.take(), 11952 llvm::makeArrayRef(ConvArgs, Args.size()), 11953 ResultTy, VK, LitEndLoc, UDSuffixLoc); 11954 11955 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 11956 return ExprError(); 11957 11958 if (CheckFunctionCall(FD, UDL, NULL)) 11959 return ExprError(); 11960 11961 return MaybeBindToTemporary(UDL); 11962 } 11963 11964 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 11965 /// given LookupResult is non-empty, it is assumed to describe a member which 11966 /// will be invoked. Otherwise, the function will be found via argument 11967 /// dependent lookup. 11968 /// CallExpr is set to a valid expression and FRS_Success returned on success, 11969 /// otherwise CallExpr is set to ExprError() and some non-success value 11970 /// is returned. 11971 Sema::ForRangeStatus 11972 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 11973 SourceLocation RangeLoc, VarDecl *Decl, 11974 BeginEndFunction BEF, 11975 const DeclarationNameInfo &NameInfo, 11976 LookupResult &MemberLookup, 11977 OverloadCandidateSet *CandidateSet, 11978 Expr *Range, ExprResult *CallExpr) { 11979 CandidateSet->clear(); 11980 if (!MemberLookup.empty()) { 11981 ExprResult MemberRef = 11982 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 11983 /*IsPtr=*/false, CXXScopeSpec(), 11984 /*TemplateKWLoc=*/SourceLocation(), 11985 /*FirstQualifierInScope=*/0, 11986 MemberLookup, 11987 /*TemplateArgs=*/0); 11988 if (MemberRef.isInvalid()) { 11989 *CallExpr = ExprError(); 11990 Diag(Range->getLocStart(), diag::note_in_for_range) 11991 << RangeLoc << BEF << Range->getType(); 11992 return FRS_DiagnosticIssued; 11993 } 11994 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0); 11995 if (CallExpr->isInvalid()) { 11996 *CallExpr = ExprError(); 11997 Diag(Range->getLocStart(), diag::note_in_for_range) 11998 << RangeLoc << BEF << Range->getType(); 11999 return FRS_DiagnosticIssued; 12000 } 12001 } else { 12002 UnresolvedSet<0> FoundNames; 12003 UnresolvedLookupExpr *Fn = 12004 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0, 12005 NestedNameSpecifierLoc(), NameInfo, 12006 /*NeedsADL=*/true, /*Overloaded=*/false, 12007 FoundNames.begin(), FoundNames.end()); 12008 12009 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 12010 CandidateSet, CallExpr); 12011 if (CandidateSet->empty() || CandidateSetError) { 12012 *CallExpr = ExprError(); 12013 return FRS_NoViableFunction; 12014 } 12015 OverloadCandidateSet::iterator Best; 12016 OverloadingResult OverloadResult = 12017 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 12018 12019 if (OverloadResult == OR_No_Viable_Function) { 12020 *CallExpr = ExprError(); 12021 return FRS_NoViableFunction; 12022 } 12023 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 12024 Loc, 0, CandidateSet, &Best, 12025 OverloadResult, 12026 /*AllowTypoCorrection=*/false); 12027 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 12028 *CallExpr = ExprError(); 12029 Diag(Range->getLocStart(), diag::note_in_for_range) 12030 << RangeLoc << BEF << Range->getType(); 12031 return FRS_DiagnosticIssued; 12032 } 12033 } 12034 return FRS_Success; 12035 } 12036 12037 12038 /// FixOverloadedFunctionReference - E is an expression that refers to 12039 /// a C++ overloaded function (possibly with some parentheses and 12040 /// perhaps a '&' around it). We have resolved the overloaded function 12041 /// to the function declaration Fn, so patch up the expression E to 12042 /// refer (possibly indirectly) to Fn. Returns the new expr. 12043 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 12044 FunctionDecl *Fn) { 12045 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 12046 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 12047 Found, Fn); 12048 if (SubExpr == PE->getSubExpr()) 12049 return PE; 12050 12051 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 12052 } 12053 12054 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 12055 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 12056 Found, Fn); 12057 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 12058 SubExpr->getType()) && 12059 "Implicit cast type cannot be determined from overload"); 12060 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 12061 if (SubExpr == ICE->getSubExpr()) 12062 return ICE; 12063 12064 return ImplicitCastExpr::Create(Context, ICE->getType(), 12065 ICE->getCastKind(), 12066 SubExpr, 0, 12067 ICE->getValueKind()); 12068 } 12069 12070 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 12071 assert(UnOp->getOpcode() == UO_AddrOf && 12072 "Can only take the address of an overloaded function"); 12073 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12074 if (Method->isStatic()) { 12075 // Do nothing: static member functions aren't any different 12076 // from non-member functions. 12077 } else { 12078 // Fix the subexpression, which really has to be an 12079 // UnresolvedLookupExpr holding an overloaded member function 12080 // or template. 12081 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12082 Found, Fn); 12083 if (SubExpr == UnOp->getSubExpr()) 12084 return UnOp; 12085 12086 assert(isa<DeclRefExpr>(SubExpr) 12087 && "fixed to something other than a decl ref"); 12088 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 12089 && "fixed to a member ref with no nested name qualifier"); 12090 12091 // We have taken the address of a pointer to member 12092 // function. Perform the computation here so that we get the 12093 // appropriate pointer to member type. 12094 QualType ClassType 12095 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 12096 QualType MemPtrType 12097 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 12098 12099 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 12100 VK_RValue, OK_Ordinary, 12101 UnOp->getOperatorLoc()); 12102 } 12103 } 12104 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12105 Found, Fn); 12106 if (SubExpr == UnOp->getSubExpr()) 12107 return UnOp; 12108 12109 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 12110 Context.getPointerType(SubExpr->getType()), 12111 VK_RValue, OK_Ordinary, 12112 UnOp->getOperatorLoc()); 12113 } 12114 12115 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12116 // FIXME: avoid copy. 12117 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 12118 if (ULE->hasExplicitTemplateArgs()) { 12119 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 12120 TemplateArgs = &TemplateArgsBuffer; 12121 } 12122 12123 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12124 ULE->getQualifierLoc(), 12125 ULE->getTemplateKeywordLoc(), 12126 Fn, 12127 /*enclosing*/ false, // FIXME? 12128 ULE->getNameLoc(), 12129 Fn->getType(), 12130 VK_LValue, 12131 Found.getDecl(), 12132 TemplateArgs); 12133 MarkDeclRefReferenced(DRE); 12134 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 12135 return DRE; 12136 } 12137 12138 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 12139 // FIXME: avoid copy. 12140 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 12141 if (MemExpr->hasExplicitTemplateArgs()) { 12142 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12143 TemplateArgs = &TemplateArgsBuffer; 12144 } 12145 12146 Expr *Base; 12147 12148 // If we're filling in a static method where we used to have an 12149 // implicit member access, rewrite to a simple decl ref. 12150 if (MemExpr->isImplicitAccess()) { 12151 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12152 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12153 MemExpr->getQualifierLoc(), 12154 MemExpr->getTemplateKeywordLoc(), 12155 Fn, 12156 /*enclosing*/ false, 12157 MemExpr->getMemberLoc(), 12158 Fn->getType(), 12159 VK_LValue, 12160 Found.getDecl(), 12161 TemplateArgs); 12162 MarkDeclRefReferenced(DRE); 12163 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 12164 return DRE; 12165 } else { 12166 SourceLocation Loc = MemExpr->getMemberLoc(); 12167 if (MemExpr->getQualifier()) 12168 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 12169 CheckCXXThisCapture(Loc); 12170 Base = new (Context) CXXThisExpr(Loc, 12171 MemExpr->getBaseType(), 12172 /*isImplicit=*/true); 12173 } 12174 } else 12175 Base = MemExpr->getBase(); 12176 12177 ExprValueKind valueKind; 12178 QualType type; 12179 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12180 valueKind = VK_LValue; 12181 type = Fn->getType(); 12182 } else { 12183 valueKind = VK_RValue; 12184 type = Context.BoundMemberTy; 12185 } 12186 12187 MemberExpr *ME = MemberExpr::Create(Context, Base, 12188 MemExpr->isArrow(), 12189 MemExpr->getQualifierLoc(), 12190 MemExpr->getTemplateKeywordLoc(), 12191 Fn, 12192 Found, 12193 MemExpr->getMemberNameInfo(), 12194 TemplateArgs, 12195 type, valueKind, OK_Ordinary); 12196 ME->setHadMultipleCandidates(true); 12197 MarkMemberReferenced(ME); 12198 return ME; 12199 } 12200 12201 llvm_unreachable("Invalid reference to overloaded function"); 12202 } 12203 12204 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 12205 DeclAccessPair Found, 12206 FunctionDecl *Fn) { 12207 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 12208 } 12209 12210 } // end namespace clang 12211