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(Sema &S, 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 (S.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 (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1406 S.isLaxVectorConversion(FromType, ToType)) { 1407 ICK = ICK_Vector_Conversion; 1408 return true; 1409 } 1410 } 1411 1412 return false; 1413 } 1414 1415 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1416 bool InOverloadResolution, 1417 StandardConversionSequence &SCS, 1418 bool CStyle); 1419 1420 /// IsStandardConversion - Determines whether there is a standard 1421 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1422 /// expression From to the type ToType. Standard conversion sequences 1423 /// only consider non-class types; for conversions that involve class 1424 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1425 /// contain the standard conversion sequence required to perform this 1426 /// conversion and this routine will return true. Otherwise, this 1427 /// routine will return false and the value of SCS is unspecified. 1428 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1429 bool InOverloadResolution, 1430 StandardConversionSequence &SCS, 1431 bool CStyle, 1432 bool AllowObjCWritebackConversion) { 1433 QualType FromType = From->getType(); 1434 1435 // Standard conversions (C++ [conv]) 1436 SCS.setAsIdentityConversion(); 1437 SCS.IncompatibleObjC = false; 1438 SCS.setFromType(FromType); 1439 SCS.CopyConstructor = 0; 1440 1441 // There are no standard conversions for class types in C++, so 1442 // abort early. When overloading in C, however, we do permit 1443 if (FromType->isRecordType() || ToType->isRecordType()) { 1444 if (S.getLangOpts().CPlusPlus) 1445 return false; 1446 1447 // When we're overloading in C, we allow, as standard conversions, 1448 } 1449 1450 // The first conversion can be an lvalue-to-rvalue conversion, 1451 // array-to-pointer conversion, or function-to-pointer conversion 1452 // (C++ 4p1). 1453 1454 if (FromType == S.Context.OverloadTy) { 1455 DeclAccessPair AccessPair; 1456 if (FunctionDecl *Fn 1457 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1458 AccessPair)) { 1459 // We were able to resolve the address of the overloaded function, 1460 // so we can convert to the type of that function. 1461 FromType = Fn->getType(); 1462 1463 // we can sometimes resolve &foo<int> regardless of ToType, so check 1464 // if the type matches (identity) or we are converting to bool 1465 if (!S.Context.hasSameUnqualifiedType( 1466 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1467 QualType resultTy; 1468 // if the function type matches except for [[noreturn]], it's ok 1469 if (!S.IsNoReturnConversion(FromType, 1470 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1471 // otherwise, only a boolean conversion is standard 1472 if (!ToType->isBooleanType()) 1473 return false; 1474 } 1475 1476 // Check if the "from" expression is taking the address of an overloaded 1477 // function and recompute the FromType accordingly. Take advantage of the 1478 // fact that non-static member functions *must* have such an address-of 1479 // expression. 1480 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1481 if (Method && !Method->isStatic()) { 1482 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1483 "Non-unary operator on non-static member address"); 1484 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1485 == UO_AddrOf && 1486 "Non-address-of operator on non-static member address"); 1487 const Type *ClassType 1488 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1489 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1490 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1491 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1492 UO_AddrOf && 1493 "Non-address-of operator for overloaded function expression"); 1494 FromType = S.Context.getPointerType(FromType); 1495 } 1496 1497 // Check that we've computed the proper type after overload resolution. 1498 assert(S.Context.hasSameType( 1499 FromType, 1500 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1501 } else { 1502 return false; 1503 } 1504 } 1505 // Lvalue-to-rvalue conversion (C++11 4.1): 1506 // A glvalue (3.10) of a non-function, non-array type T can 1507 // be converted to a prvalue. 1508 bool argIsLValue = From->isGLValue(); 1509 if (argIsLValue && 1510 !FromType->isFunctionType() && !FromType->isArrayType() && 1511 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1512 SCS.First = ICK_Lvalue_To_Rvalue; 1513 1514 // C11 6.3.2.1p2: 1515 // ... if the lvalue has atomic type, the value has the non-atomic version 1516 // of the type of the lvalue ... 1517 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1518 FromType = Atomic->getValueType(); 1519 1520 // If T is a non-class type, the type of the rvalue is the 1521 // cv-unqualified version of T. Otherwise, the type of the rvalue 1522 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1523 // just strip the qualifiers because they don't matter. 1524 FromType = FromType.getUnqualifiedType(); 1525 } else if (FromType->isArrayType()) { 1526 // Array-to-pointer conversion (C++ 4.2) 1527 SCS.First = ICK_Array_To_Pointer; 1528 1529 // An lvalue or rvalue of type "array of N T" or "array of unknown 1530 // bound of T" can be converted to an rvalue of type "pointer to 1531 // T" (C++ 4.2p1). 1532 FromType = S.Context.getArrayDecayedType(FromType); 1533 1534 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1535 // This conversion is deprecated in C++03 (D.4) 1536 SCS.DeprecatedStringLiteralToCharPtr = true; 1537 1538 // For the purpose of ranking in overload resolution 1539 // (13.3.3.1.1), this conversion is considered an 1540 // array-to-pointer conversion followed by a qualification 1541 // conversion (4.4). (C++ 4.2p2) 1542 SCS.Second = ICK_Identity; 1543 SCS.Third = ICK_Qualification; 1544 SCS.QualificationIncludesObjCLifetime = false; 1545 SCS.setAllToTypes(FromType); 1546 return true; 1547 } 1548 } else if (FromType->isFunctionType() && argIsLValue) { 1549 // Function-to-pointer conversion (C++ 4.3). 1550 SCS.First = ICK_Function_To_Pointer; 1551 1552 // An lvalue of function type T can be converted to an rvalue of 1553 // type "pointer to T." The result is a pointer to the 1554 // function. (C++ 4.3p1). 1555 FromType = S.Context.getPointerType(FromType); 1556 } else { 1557 // We don't require any conversions for the first step. 1558 SCS.First = ICK_Identity; 1559 } 1560 SCS.setToType(0, FromType); 1561 1562 // The second conversion can be an integral promotion, floating 1563 // point promotion, integral conversion, floating point conversion, 1564 // floating-integral conversion, pointer conversion, 1565 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1566 // For overloading in C, this can also be a "compatible-type" 1567 // conversion. 1568 bool IncompatibleObjC = false; 1569 ImplicitConversionKind SecondICK = ICK_Identity; 1570 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1571 // The unqualified versions of the types are the same: there's no 1572 // conversion to do. 1573 SCS.Second = ICK_Identity; 1574 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1575 // Integral promotion (C++ 4.5). 1576 SCS.Second = ICK_Integral_Promotion; 1577 FromType = ToType.getUnqualifiedType(); 1578 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1579 // Floating point promotion (C++ 4.6). 1580 SCS.Second = ICK_Floating_Promotion; 1581 FromType = ToType.getUnqualifiedType(); 1582 } else if (S.IsComplexPromotion(FromType, ToType)) { 1583 // Complex promotion (Clang extension) 1584 SCS.Second = ICK_Complex_Promotion; 1585 FromType = ToType.getUnqualifiedType(); 1586 } else if (ToType->isBooleanType() && 1587 (FromType->isArithmeticType() || 1588 FromType->isAnyPointerType() || 1589 FromType->isBlockPointerType() || 1590 FromType->isMemberPointerType() || 1591 FromType->isNullPtrType())) { 1592 // Boolean conversions (C++ 4.12). 1593 SCS.Second = ICK_Boolean_Conversion; 1594 FromType = S.Context.BoolTy; 1595 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1596 ToType->isIntegralType(S.Context)) { 1597 // Integral conversions (C++ 4.7). 1598 SCS.Second = ICK_Integral_Conversion; 1599 FromType = ToType.getUnqualifiedType(); 1600 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1601 // Complex conversions (C99 6.3.1.6) 1602 SCS.Second = ICK_Complex_Conversion; 1603 FromType = ToType.getUnqualifiedType(); 1604 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1605 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1606 // Complex-real conversions (C99 6.3.1.7) 1607 SCS.Second = ICK_Complex_Real; 1608 FromType = ToType.getUnqualifiedType(); 1609 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1610 // Floating point conversions (C++ 4.8). 1611 SCS.Second = ICK_Floating_Conversion; 1612 FromType = ToType.getUnqualifiedType(); 1613 } else if ((FromType->isRealFloatingType() && 1614 ToType->isIntegralType(S.Context)) || 1615 (FromType->isIntegralOrUnscopedEnumerationType() && 1616 ToType->isRealFloatingType())) { 1617 // Floating-integral conversions (C++ 4.9). 1618 SCS.Second = ICK_Floating_Integral; 1619 FromType = ToType.getUnqualifiedType(); 1620 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1621 SCS.Second = ICK_Block_Pointer_Conversion; 1622 } else if (AllowObjCWritebackConversion && 1623 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1624 SCS.Second = ICK_Writeback_Conversion; 1625 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1626 FromType, IncompatibleObjC)) { 1627 // Pointer conversions (C++ 4.10). 1628 SCS.Second = ICK_Pointer_Conversion; 1629 SCS.IncompatibleObjC = IncompatibleObjC; 1630 FromType = FromType.getUnqualifiedType(); 1631 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1632 InOverloadResolution, FromType)) { 1633 // Pointer to member conversions (4.11). 1634 SCS.Second = ICK_Pointer_Member; 1635 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1636 SCS.Second = SecondICK; 1637 FromType = ToType.getUnqualifiedType(); 1638 } else if (!S.getLangOpts().CPlusPlus && 1639 S.Context.typesAreCompatible(ToType, FromType)) { 1640 // Compatible conversions (Clang extension for C function overloading) 1641 SCS.Second = ICK_Compatible_Conversion; 1642 FromType = ToType.getUnqualifiedType(); 1643 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1644 // Treat a conversion that strips "noreturn" as an identity conversion. 1645 SCS.Second = ICK_NoReturn_Adjustment; 1646 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1647 InOverloadResolution, 1648 SCS, CStyle)) { 1649 SCS.Second = ICK_TransparentUnionConversion; 1650 FromType = ToType; 1651 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1652 CStyle)) { 1653 // tryAtomicConversion has updated the standard conversion sequence 1654 // appropriately. 1655 return true; 1656 } else if (ToType->isEventT() && 1657 From->isIntegerConstantExpr(S.getASTContext()) && 1658 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1659 SCS.Second = ICK_Zero_Event_Conversion; 1660 FromType = ToType; 1661 } else { 1662 // No second conversion required. 1663 SCS.Second = ICK_Identity; 1664 } 1665 SCS.setToType(1, FromType); 1666 1667 QualType CanonFrom; 1668 QualType CanonTo; 1669 // The third conversion can be a qualification conversion (C++ 4p1). 1670 bool ObjCLifetimeConversion; 1671 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1672 ObjCLifetimeConversion)) { 1673 SCS.Third = ICK_Qualification; 1674 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1675 FromType = ToType; 1676 CanonFrom = S.Context.getCanonicalType(FromType); 1677 CanonTo = S.Context.getCanonicalType(ToType); 1678 } else { 1679 // No conversion required 1680 SCS.Third = ICK_Identity; 1681 1682 // C++ [over.best.ics]p6: 1683 // [...] Any difference in top-level cv-qualification is 1684 // subsumed by the initialization itself and does not constitute 1685 // a conversion. [...] 1686 CanonFrom = S.Context.getCanonicalType(FromType); 1687 CanonTo = S.Context.getCanonicalType(ToType); 1688 if (CanonFrom.getLocalUnqualifiedType() 1689 == CanonTo.getLocalUnqualifiedType() && 1690 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1691 FromType = ToType; 1692 CanonFrom = CanonTo; 1693 } 1694 } 1695 SCS.setToType(2, FromType); 1696 1697 // If we have not converted the argument type to the parameter type, 1698 // this is a bad conversion sequence. 1699 if (CanonFrom != CanonTo) 1700 return false; 1701 1702 return true; 1703 } 1704 1705 static bool 1706 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1707 QualType &ToType, 1708 bool InOverloadResolution, 1709 StandardConversionSequence &SCS, 1710 bool CStyle) { 1711 1712 const RecordType *UT = ToType->getAsUnionType(); 1713 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1714 return false; 1715 // The field to initialize within the transparent union. 1716 RecordDecl *UD = UT->getDecl(); 1717 // It's compatible if the expression matches any of the fields. 1718 for (const auto *it : UD->fields()) { 1719 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1720 CStyle, /*ObjCWritebackConversion=*/false)) { 1721 ToType = it->getType(); 1722 return true; 1723 } 1724 } 1725 return false; 1726 } 1727 1728 /// IsIntegralPromotion - Determines whether the conversion from the 1729 /// expression From (whose potentially-adjusted type is FromType) to 1730 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1731 /// sets PromotedType to the promoted type. 1732 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1733 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1734 // All integers are built-in. 1735 if (!To) { 1736 return false; 1737 } 1738 1739 // An rvalue of type char, signed char, unsigned char, short int, or 1740 // unsigned short int can be converted to an rvalue of type int if 1741 // int can represent all the values of the source type; otherwise, 1742 // the source rvalue can be converted to an rvalue of type unsigned 1743 // int (C++ 4.5p1). 1744 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1745 !FromType->isEnumeralType()) { 1746 if (// We can promote any signed, promotable integer type to an int 1747 (FromType->isSignedIntegerType() || 1748 // We can promote any unsigned integer type whose size is 1749 // less than int to an int. 1750 (!FromType->isSignedIntegerType() && 1751 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1752 return To->getKind() == BuiltinType::Int; 1753 } 1754 1755 return To->getKind() == BuiltinType::UInt; 1756 } 1757 1758 // C++11 [conv.prom]p3: 1759 // A prvalue of an unscoped enumeration type whose underlying type is not 1760 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1761 // following types that can represent all the values of the enumeration 1762 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1763 // unsigned int, long int, unsigned long int, long long int, or unsigned 1764 // long long int. If none of the types in that list can represent all the 1765 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1766 // type can be converted to an rvalue a prvalue of the extended integer type 1767 // with lowest integer conversion rank (4.13) greater than the rank of long 1768 // long in which all the values of the enumeration can be represented. If 1769 // there are two such extended types, the signed one is chosen. 1770 // C++11 [conv.prom]p4: 1771 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1772 // can be converted to a prvalue of its underlying type. Moreover, if 1773 // integral promotion can be applied to its underlying type, a prvalue of an 1774 // unscoped enumeration type whose underlying type is fixed can also be 1775 // converted to a prvalue of the promoted underlying type. 1776 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1777 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1778 // provided for a scoped enumeration. 1779 if (FromEnumType->getDecl()->isScoped()) 1780 return false; 1781 1782 // We can perform an integral promotion to the underlying type of the enum, 1783 // even if that's not the promoted type. 1784 if (FromEnumType->getDecl()->isFixed()) { 1785 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1786 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1787 IsIntegralPromotion(From, Underlying, ToType); 1788 } 1789 1790 // We have already pre-calculated the promotion type, so this is trivial. 1791 if (ToType->isIntegerType() && 1792 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1793 return Context.hasSameUnqualifiedType(ToType, 1794 FromEnumType->getDecl()->getPromotionType()); 1795 } 1796 1797 // C++0x [conv.prom]p2: 1798 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1799 // to an rvalue a prvalue of the first of the following types that can 1800 // represent all the values of its underlying type: int, unsigned int, 1801 // long int, unsigned long int, long long int, or unsigned long long int. 1802 // If none of the types in that list can represent all the values of its 1803 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1804 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1805 // type. 1806 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1807 ToType->isIntegerType()) { 1808 // Determine whether the type we're converting from is signed or 1809 // unsigned. 1810 bool FromIsSigned = FromType->isSignedIntegerType(); 1811 uint64_t FromSize = Context.getTypeSize(FromType); 1812 1813 // The types we'll try to promote to, in the appropriate 1814 // order. Try each of these types. 1815 QualType PromoteTypes[6] = { 1816 Context.IntTy, Context.UnsignedIntTy, 1817 Context.LongTy, Context.UnsignedLongTy , 1818 Context.LongLongTy, Context.UnsignedLongLongTy 1819 }; 1820 for (int Idx = 0; Idx < 6; ++Idx) { 1821 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1822 if (FromSize < ToSize || 1823 (FromSize == ToSize && 1824 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1825 // We found the type that we can promote to. If this is the 1826 // type we wanted, we have a promotion. Otherwise, no 1827 // promotion. 1828 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1829 } 1830 } 1831 } 1832 1833 // An rvalue for an integral bit-field (9.6) can be converted to an 1834 // rvalue of type int if int can represent all the values of the 1835 // bit-field; otherwise, it can be converted to unsigned int if 1836 // unsigned int can represent all the values of the bit-field. If 1837 // the bit-field is larger yet, no integral promotion applies to 1838 // it. If the bit-field has an enumerated type, it is treated as any 1839 // other value of that type for promotion purposes (C++ 4.5p3). 1840 // FIXME: We should delay checking of bit-fields until we actually perform the 1841 // conversion. 1842 using llvm::APSInt; 1843 if (From) 1844 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1845 APSInt BitWidth; 1846 if (FromType->isIntegralType(Context) && 1847 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1848 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1849 ToSize = Context.getTypeSize(ToType); 1850 1851 // Are we promoting to an int from a bitfield that fits in an int? 1852 if (BitWidth < ToSize || 1853 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1854 return To->getKind() == BuiltinType::Int; 1855 } 1856 1857 // Are we promoting to an unsigned int from an unsigned bitfield 1858 // that fits into an unsigned int? 1859 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1860 return To->getKind() == BuiltinType::UInt; 1861 } 1862 1863 return false; 1864 } 1865 } 1866 1867 // An rvalue of type bool can be converted to an rvalue of type int, 1868 // with false becoming zero and true becoming one (C++ 4.5p4). 1869 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1870 return true; 1871 } 1872 1873 return false; 1874 } 1875 1876 /// IsFloatingPointPromotion - Determines whether the conversion from 1877 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1878 /// returns true and sets PromotedType to the promoted type. 1879 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1880 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1881 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1882 /// An rvalue of type float can be converted to an rvalue of type 1883 /// double. (C++ 4.6p1). 1884 if (FromBuiltin->getKind() == BuiltinType::Float && 1885 ToBuiltin->getKind() == BuiltinType::Double) 1886 return true; 1887 1888 // C99 6.3.1.5p1: 1889 // When a float is promoted to double or long double, or a 1890 // double is promoted to long double [...]. 1891 if (!getLangOpts().CPlusPlus && 1892 (FromBuiltin->getKind() == BuiltinType::Float || 1893 FromBuiltin->getKind() == BuiltinType::Double) && 1894 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1895 return true; 1896 1897 // Half can be promoted to float. 1898 if (!getLangOpts().NativeHalfType && 1899 FromBuiltin->getKind() == BuiltinType::Half && 1900 ToBuiltin->getKind() == BuiltinType::Float) 1901 return true; 1902 } 1903 1904 return false; 1905 } 1906 1907 /// \brief Determine if a conversion is a complex promotion. 1908 /// 1909 /// A complex promotion is defined as a complex -> complex conversion 1910 /// where the conversion between the underlying real types is a 1911 /// floating-point or integral promotion. 1912 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1913 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1914 if (!FromComplex) 1915 return false; 1916 1917 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1918 if (!ToComplex) 1919 return false; 1920 1921 return IsFloatingPointPromotion(FromComplex->getElementType(), 1922 ToComplex->getElementType()) || 1923 IsIntegralPromotion(0, FromComplex->getElementType(), 1924 ToComplex->getElementType()); 1925 } 1926 1927 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1928 /// the pointer type FromPtr to a pointer to type ToPointee, with the 1929 /// same type qualifiers as FromPtr has on its pointee type. ToType, 1930 /// if non-empty, will be a pointer to ToType that may or may not have 1931 /// the right set of qualifiers on its pointee. 1932 /// 1933 static QualType 1934 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1935 QualType ToPointee, QualType ToType, 1936 ASTContext &Context, 1937 bool StripObjCLifetime = false) { 1938 assert((FromPtr->getTypeClass() == Type::Pointer || 1939 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1940 "Invalid similarly-qualified pointer type"); 1941 1942 /// Conversions to 'id' subsume cv-qualifier conversions. 1943 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1944 return ToType.getUnqualifiedType(); 1945 1946 QualType CanonFromPointee 1947 = Context.getCanonicalType(FromPtr->getPointeeType()); 1948 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1949 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1950 1951 if (StripObjCLifetime) 1952 Quals.removeObjCLifetime(); 1953 1954 // Exact qualifier match -> return the pointer type we're converting to. 1955 if (CanonToPointee.getLocalQualifiers() == Quals) { 1956 // ToType is exactly what we need. Return it. 1957 if (!ToType.isNull()) 1958 return ToType.getUnqualifiedType(); 1959 1960 // Build a pointer to ToPointee. It has the right qualifiers 1961 // already. 1962 if (isa<ObjCObjectPointerType>(ToType)) 1963 return Context.getObjCObjectPointerType(ToPointee); 1964 return Context.getPointerType(ToPointee); 1965 } 1966 1967 // Just build a canonical type that has the right qualifiers. 1968 QualType QualifiedCanonToPointee 1969 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1970 1971 if (isa<ObjCObjectPointerType>(ToType)) 1972 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1973 return Context.getPointerType(QualifiedCanonToPointee); 1974 } 1975 1976 static bool isNullPointerConstantForConversion(Expr *Expr, 1977 bool InOverloadResolution, 1978 ASTContext &Context) { 1979 // Handle value-dependent integral null pointer constants correctly. 1980 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1981 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1982 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1983 return !InOverloadResolution; 1984 1985 return Expr->isNullPointerConstant(Context, 1986 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1987 : Expr::NPC_ValueDependentIsNull); 1988 } 1989 1990 /// IsPointerConversion - Determines whether the conversion of the 1991 /// expression From, which has the (possibly adjusted) type FromType, 1992 /// can be converted to the type ToType via a pointer conversion (C++ 1993 /// 4.10). If so, returns true and places the converted type (that 1994 /// might differ from ToType in its cv-qualifiers at some level) into 1995 /// ConvertedType. 1996 /// 1997 /// This routine also supports conversions to and from block pointers 1998 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 1999 /// pointers to interfaces. FIXME: Once we've determined the 2000 /// appropriate overloading rules for Objective-C, we may want to 2001 /// split the Objective-C checks into a different routine; however, 2002 /// GCC seems to consider all of these conversions to be pointer 2003 /// conversions, so for now they live here. IncompatibleObjC will be 2004 /// set if the conversion is an allowed Objective-C conversion that 2005 /// should result in a warning. 2006 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2007 bool InOverloadResolution, 2008 QualType& ConvertedType, 2009 bool &IncompatibleObjC) { 2010 IncompatibleObjC = false; 2011 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2012 IncompatibleObjC)) 2013 return true; 2014 2015 // Conversion from a null pointer constant to any Objective-C pointer type. 2016 if (ToType->isObjCObjectPointerType() && 2017 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2018 ConvertedType = ToType; 2019 return true; 2020 } 2021 2022 // Blocks: Block pointers can be converted to void*. 2023 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2024 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2025 ConvertedType = ToType; 2026 return true; 2027 } 2028 // Blocks: A null pointer constant can be converted to a block 2029 // pointer type. 2030 if (ToType->isBlockPointerType() && 2031 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2032 ConvertedType = ToType; 2033 return true; 2034 } 2035 2036 // If the left-hand-side is nullptr_t, the right side can be a null 2037 // pointer constant. 2038 if (ToType->isNullPtrType() && 2039 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2040 ConvertedType = ToType; 2041 return true; 2042 } 2043 2044 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2045 if (!ToTypePtr) 2046 return false; 2047 2048 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2049 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2050 ConvertedType = ToType; 2051 return true; 2052 } 2053 2054 // Beyond this point, both types need to be pointers 2055 // , including objective-c pointers. 2056 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2057 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2058 !getLangOpts().ObjCAutoRefCount) { 2059 ConvertedType = BuildSimilarlyQualifiedPointerType( 2060 FromType->getAs<ObjCObjectPointerType>(), 2061 ToPointeeType, 2062 ToType, Context); 2063 return true; 2064 } 2065 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2066 if (!FromTypePtr) 2067 return false; 2068 2069 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2070 2071 // If the unqualified pointee types are the same, this can't be a 2072 // pointer conversion, so don't do all of the work below. 2073 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2074 return false; 2075 2076 // An rvalue of type "pointer to cv T," where T is an object type, 2077 // can be converted to an rvalue of type "pointer to cv void" (C++ 2078 // 4.10p2). 2079 if (FromPointeeType->isIncompleteOrObjectType() && 2080 ToPointeeType->isVoidType()) { 2081 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2082 ToPointeeType, 2083 ToType, Context, 2084 /*StripObjCLifetime=*/true); 2085 return true; 2086 } 2087 2088 // MSVC allows implicit function to void* type conversion. 2089 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 2090 ToPointeeType->isVoidType()) { 2091 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2092 ToPointeeType, 2093 ToType, Context); 2094 return true; 2095 } 2096 2097 // When we're overloading in C, we allow a special kind of pointer 2098 // conversion for compatible-but-not-identical pointee types. 2099 if (!getLangOpts().CPlusPlus && 2100 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2101 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2102 ToPointeeType, 2103 ToType, Context); 2104 return true; 2105 } 2106 2107 // C++ [conv.ptr]p3: 2108 // 2109 // An rvalue of type "pointer to cv D," where D is a class type, 2110 // can be converted to an rvalue of type "pointer to cv B," where 2111 // B is a base class (clause 10) of D. If B is an inaccessible 2112 // (clause 11) or ambiguous (10.2) base class of D, a program that 2113 // necessitates this conversion is ill-formed. The result of the 2114 // conversion is a pointer to the base class sub-object of the 2115 // derived class object. The null pointer value is converted to 2116 // the null pointer value of the destination type. 2117 // 2118 // Note that we do not check for ambiguity or inaccessibility 2119 // here. That is handled by CheckPointerConversion. 2120 if (getLangOpts().CPlusPlus && 2121 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2122 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2123 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2124 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2125 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2126 ToPointeeType, 2127 ToType, Context); 2128 return true; 2129 } 2130 2131 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2132 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2133 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2134 ToPointeeType, 2135 ToType, Context); 2136 return true; 2137 } 2138 2139 return false; 2140 } 2141 2142 /// \brief Adopt the given qualifiers for the given type. 2143 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2144 Qualifiers TQs = T.getQualifiers(); 2145 2146 // Check whether qualifiers already match. 2147 if (TQs == Qs) 2148 return T; 2149 2150 if (Qs.compatiblyIncludes(TQs)) 2151 return Context.getQualifiedType(T, Qs); 2152 2153 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2154 } 2155 2156 /// isObjCPointerConversion - Determines whether this is an 2157 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2158 /// with the same arguments and return values. 2159 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2160 QualType& ConvertedType, 2161 bool &IncompatibleObjC) { 2162 if (!getLangOpts().ObjC1) 2163 return false; 2164 2165 // The set of qualifiers on the type we're converting from. 2166 Qualifiers FromQualifiers = FromType.getQualifiers(); 2167 2168 // First, we handle all conversions on ObjC object pointer types. 2169 const ObjCObjectPointerType* ToObjCPtr = 2170 ToType->getAs<ObjCObjectPointerType>(); 2171 const ObjCObjectPointerType *FromObjCPtr = 2172 FromType->getAs<ObjCObjectPointerType>(); 2173 2174 if (ToObjCPtr && FromObjCPtr) { 2175 // If the pointee types are the same (ignoring qualifications), 2176 // then this is not a pointer conversion. 2177 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2178 FromObjCPtr->getPointeeType())) 2179 return false; 2180 2181 // Check for compatible 2182 // Objective C++: We're able to convert between "id" or "Class" and a 2183 // pointer to any interface (in both directions). 2184 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2185 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2186 return true; 2187 } 2188 // Conversions with Objective-C's id<...>. 2189 if ((FromObjCPtr->isObjCQualifiedIdType() || 2190 ToObjCPtr->isObjCQualifiedIdType()) && 2191 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2192 /*compare=*/false)) { 2193 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2194 return true; 2195 } 2196 // Objective C++: We're able to convert from a pointer to an 2197 // interface to a pointer to a different interface. 2198 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2199 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2200 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2201 if (getLangOpts().CPlusPlus && LHS && RHS && 2202 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2203 FromObjCPtr->getPointeeType())) 2204 return false; 2205 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2206 ToObjCPtr->getPointeeType(), 2207 ToType, Context); 2208 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2209 return true; 2210 } 2211 2212 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2213 // Okay: this is some kind of implicit downcast of Objective-C 2214 // interfaces, which is permitted. However, we're going to 2215 // complain about it. 2216 IncompatibleObjC = true; 2217 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2218 ToObjCPtr->getPointeeType(), 2219 ToType, Context); 2220 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2221 return true; 2222 } 2223 } 2224 // Beyond this point, both types need to be C pointers or block pointers. 2225 QualType ToPointeeType; 2226 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2227 ToPointeeType = ToCPtr->getPointeeType(); 2228 else if (const BlockPointerType *ToBlockPtr = 2229 ToType->getAs<BlockPointerType>()) { 2230 // Objective C++: We're able to convert from a pointer to any object 2231 // to a block pointer type. 2232 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2233 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2234 return true; 2235 } 2236 ToPointeeType = ToBlockPtr->getPointeeType(); 2237 } 2238 else if (FromType->getAs<BlockPointerType>() && 2239 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2240 // Objective C++: We're able to convert from a block pointer type to a 2241 // pointer to any object. 2242 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2243 return true; 2244 } 2245 else 2246 return false; 2247 2248 QualType FromPointeeType; 2249 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2250 FromPointeeType = FromCPtr->getPointeeType(); 2251 else if (const BlockPointerType *FromBlockPtr = 2252 FromType->getAs<BlockPointerType>()) 2253 FromPointeeType = FromBlockPtr->getPointeeType(); 2254 else 2255 return false; 2256 2257 // If we have pointers to pointers, recursively check whether this 2258 // is an Objective-C conversion. 2259 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2260 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2261 IncompatibleObjC)) { 2262 // We always complain about this conversion. 2263 IncompatibleObjC = true; 2264 ConvertedType = Context.getPointerType(ConvertedType); 2265 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2266 return true; 2267 } 2268 // Allow conversion of pointee being objective-c pointer to another one; 2269 // as in I* to id. 2270 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2271 ToPointeeType->getAs<ObjCObjectPointerType>() && 2272 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2273 IncompatibleObjC)) { 2274 2275 ConvertedType = Context.getPointerType(ConvertedType); 2276 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2277 return true; 2278 } 2279 2280 // If we have pointers to functions or blocks, check whether the only 2281 // differences in the argument and result types are in Objective-C 2282 // pointer conversions. If so, we permit the conversion (but 2283 // complain about it). 2284 const FunctionProtoType *FromFunctionType 2285 = FromPointeeType->getAs<FunctionProtoType>(); 2286 const FunctionProtoType *ToFunctionType 2287 = ToPointeeType->getAs<FunctionProtoType>(); 2288 if (FromFunctionType && ToFunctionType) { 2289 // If the function types are exactly the same, this isn't an 2290 // Objective-C pointer conversion. 2291 if (Context.getCanonicalType(FromPointeeType) 2292 == Context.getCanonicalType(ToPointeeType)) 2293 return false; 2294 2295 // Perform the quick checks that will tell us whether these 2296 // function types are obviously different. 2297 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2298 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2299 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2300 return false; 2301 2302 bool HasObjCConversion = false; 2303 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2304 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2305 // Okay, the types match exactly. Nothing to do. 2306 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2307 ToFunctionType->getReturnType(), 2308 ConvertedType, IncompatibleObjC)) { 2309 // Okay, we have an Objective-C pointer conversion. 2310 HasObjCConversion = true; 2311 } else { 2312 // Function types are too different. Abort. 2313 return false; 2314 } 2315 2316 // Check argument types. 2317 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2318 ArgIdx != NumArgs; ++ArgIdx) { 2319 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2320 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2321 if (Context.getCanonicalType(FromArgType) 2322 == Context.getCanonicalType(ToArgType)) { 2323 // Okay, the types match exactly. Nothing to do. 2324 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2325 ConvertedType, IncompatibleObjC)) { 2326 // Okay, we have an Objective-C pointer conversion. 2327 HasObjCConversion = true; 2328 } else { 2329 // Argument types are too different. Abort. 2330 return false; 2331 } 2332 } 2333 2334 if (HasObjCConversion) { 2335 // We had an Objective-C conversion. Allow this pointer 2336 // conversion, but complain about it. 2337 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2338 IncompatibleObjC = true; 2339 return true; 2340 } 2341 } 2342 2343 return false; 2344 } 2345 2346 /// \brief Determine whether this is an Objective-C writeback conversion, 2347 /// used for parameter passing when performing automatic reference counting. 2348 /// 2349 /// \param FromType The type we're converting form. 2350 /// 2351 /// \param ToType The type we're converting to. 2352 /// 2353 /// \param ConvertedType The type that will be produced after applying 2354 /// this conversion. 2355 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2356 QualType &ConvertedType) { 2357 if (!getLangOpts().ObjCAutoRefCount || 2358 Context.hasSameUnqualifiedType(FromType, ToType)) 2359 return false; 2360 2361 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2362 QualType ToPointee; 2363 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2364 ToPointee = ToPointer->getPointeeType(); 2365 else 2366 return false; 2367 2368 Qualifiers ToQuals = ToPointee.getQualifiers(); 2369 if (!ToPointee->isObjCLifetimeType() || 2370 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2371 !ToQuals.withoutObjCLifetime().empty()) 2372 return false; 2373 2374 // Argument must be a pointer to __strong to __weak. 2375 QualType FromPointee; 2376 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2377 FromPointee = FromPointer->getPointeeType(); 2378 else 2379 return false; 2380 2381 Qualifiers FromQuals = FromPointee.getQualifiers(); 2382 if (!FromPointee->isObjCLifetimeType() || 2383 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2384 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2385 return false; 2386 2387 // Make sure that we have compatible qualifiers. 2388 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2389 if (!ToQuals.compatiblyIncludes(FromQuals)) 2390 return false; 2391 2392 // Remove qualifiers from the pointee type we're converting from; they 2393 // aren't used in the compatibility check belong, and we'll be adding back 2394 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2395 FromPointee = FromPointee.getUnqualifiedType(); 2396 2397 // The unqualified form of the pointee types must be compatible. 2398 ToPointee = ToPointee.getUnqualifiedType(); 2399 bool IncompatibleObjC; 2400 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2401 FromPointee = ToPointee; 2402 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2403 IncompatibleObjC)) 2404 return false; 2405 2406 /// \brief Construct the type we're converting to, which is a pointer to 2407 /// __autoreleasing pointee. 2408 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2409 ConvertedType = Context.getPointerType(FromPointee); 2410 return true; 2411 } 2412 2413 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2414 QualType& ConvertedType) { 2415 QualType ToPointeeType; 2416 if (const BlockPointerType *ToBlockPtr = 2417 ToType->getAs<BlockPointerType>()) 2418 ToPointeeType = ToBlockPtr->getPointeeType(); 2419 else 2420 return false; 2421 2422 QualType FromPointeeType; 2423 if (const BlockPointerType *FromBlockPtr = 2424 FromType->getAs<BlockPointerType>()) 2425 FromPointeeType = FromBlockPtr->getPointeeType(); 2426 else 2427 return false; 2428 // We have pointer to blocks, check whether the only 2429 // differences in the argument and result types are in Objective-C 2430 // pointer conversions. If so, we permit the conversion. 2431 2432 const FunctionProtoType *FromFunctionType 2433 = FromPointeeType->getAs<FunctionProtoType>(); 2434 const FunctionProtoType *ToFunctionType 2435 = ToPointeeType->getAs<FunctionProtoType>(); 2436 2437 if (!FromFunctionType || !ToFunctionType) 2438 return false; 2439 2440 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2441 return true; 2442 2443 // Perform the quick checks that will tell us whether these 2444 // function types are obviously different. 2445 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2446 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2447 return false; 2448 2449 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2450 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2451 if (FromEInfo != ToEInfo) 2452 return false; 2453 2454 bool IncompatibleObjC = false; 2455 if (Context.hasSameType(FromFunctionType->getReturnType(), 2456 ToFunctionType->getReturnType())) { 2457 // Okay, the types match exactly. Nothing to do. 2458 } else { 2459 QualType RHS = FromFunctionType->getReturnType(); 2460 QualType LHS = ToFunctionType->getReturnType(); 2461 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2462 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2463 LHS = LHS.getUnqualifiedType(); 2464 2465 if (Context.hasSameType(RHS,LHS)) { 2466 // OK exact match. 2467 } else if (isObjCPointerConversion(RHS, LHS, 2468 ConvertedType, IncompatibleObjC)) { 2469 if (IncompatibleObjC) 2470 return false; 2471 // Okay, we have an Objective-C pointer conversion. 2472 } 2473 else 2474 return false; 2475 } 2476 2477 // Check argument types. 2478 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2479 ArgIdx != NumArgs; ++ArgIdx) { 2480 IncompatibleObjC = false; 2481 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2482 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2483 if (Context.hasSameType(FromArgType, ToArgType)) { 2484 // Okay, the types match exactly. Nothing to do. 2485 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2486 ConvertedType, IncompatibleObjC)) { 2487 if (IncompatibleObjC) 2488 return false; 2489 // Okay, we have an Objective-C pointer conversion. 2490 } else 2491 // Argument types are too different. Abort. 2492 return false; 2493 } 2494 if (LangOpts.ObjCAutoRefCount && 2495 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2496 ToFunctionType)) 2497 return false; 2498 2499 ConvertedType = ToType; 2500 return true; 2501 } 2502 2503 enum { 2504 ft_default, 2505 ft_different_class, 2506 ft_parameter_arity, 2507 ft_parameter_mismatch, 2508 ft_return_type, 2509 ft_qualifer_mismatch 2510 }; 2511 2512 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2513 /// function types. Catches different number of parameter, mismatch in 2514 /// parameter types, and different return types. 2515 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2516 QualType FromType, QualType ToType) { 2517 // If either type is not valid, include no extra info. 2518 if (FromType.isNull() || ToType.isNull()) { 2519 PDiag << ft_default; 2520 return; 2521 } 2522 2523 // Get the function type from the pointers. 2524 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2525 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2526 *ToMember = ToType->getAs<MemberPointerType>(); 2527 if (FromMember->getClass() != ToMember->getClass()) { 2528 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2529 << QualType(FromMember->getClass(), 0); 2530 return; 2531 } 2532 FromType = FromMember->getPointeeType(); 2533 ToType = ToMember->getPointeeType(); 2534 } 2535 2536 if (FromType->isPointerType()) 2537 FromType = FromType->getPointeeType(); 2538 if (ToType->isPointerType()) 2539 ToType = ToType->getPointeeType(); 2540 2541 // Remove references. 2542 FromType = FromType.getNonReferenceType(); 2543 ToType = ToType.getNonReferenceType(); 2544 2545 // Don't print extra info for non-specialized template functions. 2546 if (FromType->isInstantiationDependentType() && 2547 !FromType->getAs<TemplateSpecializationType>()) { 2548 PDiag << ft_default; 2549 return; 2550 } 2551 2552 // No extra info for same types. 2553 if (Context.hasSameType(FromType, ToType)) { 2554 PDiag << ft_default; 2555 return; 2556 } 2557 2558 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2559 *ToFunction = ToType->getAs<FunctionProtoType>(); 2560 2561 // Both types need to be function types. 2562 if (!FromFunction || !ToFunction) { 2563 PDiag << ft_default; 2564 return; 2565 } 2566 2567 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2568 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2569 << FromFunction->getNumParams(); 2570 return; 2571 } 2572 2573 // Handle different parameter types. 2574 unsigned ArgPos; 2575 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2576 PDiag << ft_parameter_mismatch << ArgPos + 1 2577 << ToFunction->getParamType(ArgPos) 2578 << FromFunction->getParamType(ArgPos); 2579 return; 2580 } 2581 2582 // Handle different return type. 2583 if (!Context.hasSameType(FromFunction->getReturnType(), 2584 ToFunction->getReturnType())) { 2585 PDiag << ft_return_type << ToFunction->getReturnType() 2586 << FromFunction->getReturnType(); 2587 return; 2588 } 2589 2590 unsigned FromQuals = FromFunction->getTypeQuals(), 2591 ToQuals = ToFunction->getTypeQuals(); 2592 if (FromQuals != ToQuals) { 2593 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2594 return; 2595 } 2596 2597 // Unable to find a difference, so add no extra info. 2598 PDiag << ft_default; 2599 } 2600 2601 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2602 /// for equality of their argument types. Caller has already checked that 2603 /// they have same number of arguments. If the parameters are different, 2604 /// ArgPos will have the parameter index of the first different parameter. 2605 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2606 const FunctionProtoType *NewType, 2607 unsigned *ArgPos) { 2608 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2609 N = NewType->param_type_begin(), 2610 E = OldType->param_type_end(); 2611 O && (O != E); ++O, ++N) { 2612 if (!Context.hasSameType(O->getUnqualifiedType(), 2613 N->getUnqualifiedType())) { 2614 if (ArgPos) 2615 *ArgPos = O - OldType->param_type_begin(); 2616 return false; 2617 } 2618 } 2619 return true; 2620 } 2621 2622 /// CheckPointerConversion - Check the pointer conversion from the 2623 /// expression From to the type ToType. This routine checks for 2624 /// ambiguous or inaccessible derived-to-base pointer 2625 /// conversions for which IsPointerConversion has already returned 2626 /// true. It returns true and produces a diagnostic if there was an 2627 /// error, or returns false otherwise. 2628 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2629 CastKind &Kind, 2630 CXXCastPath& BasePath, 2631 bool IgnoreBaseAccess) { 2632 QualType FromType = From->getType(); 2633 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2634 2635 Kind = CK_BitCast; 2636 2637 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2638 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2639 Expr::NPCK_ZeroExpression) { 2640 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2641 DiagRuntimeBehavior(From->getExprLoc(), From, 2642 PDiag(diag::warn_impcast_bool_to_null_pointer) 2643 << ToType << From->getSourceRange()); 2644 else if (!isUnevaluatedContext()) 2645 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2646 << ToType << From->getSourceRange(); 2647 } 2648 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2649 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2650 QualType FromPointeeType = FromPtrType->getPointeeType(), 2651 ToPointeeType = ToPtrType->getPointeeType(); 2652 2653 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2654 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2655 // We must have a derived-to-base conversion. Check an 2656 // ambiguous or inaccessible conversion. 2657 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2658 From->getExprLoc(), 2659 From->getSourceRange(), &BasePath, 2660 IgnoreBaseAccess)) 2661 return true; 2662 2663 // The conversion was successful. 2664 Kind = CK_DerivedToBase; 2665 } 2666 } 2667 } else if (const ObjCObjectPointerType *ToPtrType = 2668 ToType->getAs<ObjCObjectPointerType>()) { 2669 if (const ObjCObjectPointerType *FromPtrType = 2670 FromType->getAs<ObjCObjectPointerType>()) { 2671 // Objective-C++ conversions are always okay. 2672 // FIXME: We should have a different class of conversions for the 2673 // Objective-C++ implicit conversions. 2674 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2675 return false; 2676 } else if (FromType->isBlockPointerType()) { 2677 Kind = CK_BlockPointerToObjCPointerCast; 2678 } else { 2679 Kind = CK_CPointerToObjCPointerCast; 2680 } 2681 } else if (ToType->isBlockPointerType()) { 2682 if (!FromType->isBlockPointerType()) 2683 Kind = CK_AnyPointerToBlockPointerCast; 2684 } 2685 2686 // We shouldn't fall into this case unless it's valid for other 2687 // reasons. 2688 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2689 Kind = CK_NullToPointer; 2690 2691 return false; 2692 } 2693 2694 /// IsMemberPointerConversion - Determines whether the conversion of the 2695 /// expression From, which has the (possibly adjusted) type FromType, can be 2696 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2697 /// If so, returns true and places the converted type (that might differ from 2698 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2699 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2700 QualType ToType, 2701 bool InOverloadResolution, 2702 QualType &ConvertedType) { 2703 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2704 if (!ToTypePtr) 2705 return false; 2706 2707 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2708 if (From->isNullPointerConstant(Context, 2709 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2710 : Expr::NPC_ValueDependentIsNull)) { 2711 ConvertedType = ToType; 2712 return true; 2713 } 2714 2715 // Otherwise, both types have to be member pointers. 2716 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2717 if (!FromTypePtr) 2718 return false; 2719 2720 // A pointer to member of B can be converted to a pointer to member of D, 2721 // where D is derived from B (C++ 4.11p2). 2722 QualType FromClass(FromTypePtr->getClass(), 0); 2723 QualType ToClass(ToTypePtr->getClass(), 0); 2724 2725 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2726 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2727 IsDerivedFrom(ToClass, FromClass)) { 2728 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2729 ToClass.getTypePtr()); 2730 return true; 2731 } 2732 2733 return false; 2734 } 2735 2736 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2737 /// expression From to the type ToType. This routine checks for ambiguous or 2738 /// virtual or inaccessible base-to-derived member pointer conversions 2739 /// for which IsMemberPointerConversion has already returned true. It returns 2740 /// true and produces a diagnostic if there was an error, or returns false 2741 /// otherwise. 2742 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2743 CastKind &Kind, 2744 CXXCastPath &BasePath, 2745 bool IgnoreBaseAccess) { 2746 QualType FromType = From->getType(); 2747 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2748 if (!FromPtrType) { 2749 // This must be a null pointer to member pointer conversion 2750 assert(From->isNullPointerConstant(Context, 2751 Expr::NPC_ValueDependentIsNull) && 2752 "Expr must be null pointer constant!"); 2753 Kind = CK_NullToMemberPointer; 2754 return false; 2755 } 2756 2757 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2758 assert(ToPtrType && "No member pointer cast has a target type " 2759 "that is not a member pointer."); 2760 2761 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2762 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2763 2764 // FIXME: What about dependent types? 2765 assert(FromClass->isRecordType() && "Pointer into non-class."); 2766 assert(ToClass->isRecordType() && "Pointer into non-class."); 2767 2768 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2769 /*DetectVirtual=*/true); 2770 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2771 assert(DerivationOkay && 2772 "Should not have been called if derivation isn't OK."); 2773 (void)DerivationOkay; 2774 2775 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2776 getUnqualifiedType())) { 2777 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2778 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2779 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2780 return true; 2781 } 2782 2783 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2784 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2785 << FromClass << ToClass << QualType(VBase, 0) 2786 << From->getSourceRange(); 2787 return true; 2788 } 2789 2790 if (!IgnoreBaseAccess) 2791 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2792 Paths.front(), 2793 diag::err_downcast_from_inaccessible_base); 2794 2795 // Must be a base to derived member conversion. 2796 BuildBasePathArray(Paths, BasePath); 2797 Kind = CK_BaseToDerivedMemberPointer; 2798 return false; 2799 } 2800 2801 /// Determine whether the lifetime conversion between the two given 2802 /// qualifiers sets is nontrivial. 2803 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 2804 Qualifiers ToQuals) { 2805 // Converting anything to const __unsafe_unretained is trivial. 2806 if (ToQuals.hasConst() && 2807 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 2808 return false; 2809 2810 return true; 2811 } 2812 2813 /// IsQualificationConversion - Determines whether the conversion from 2814 /// an rvalue of type FromType to ToType is a qualification conversion 2815 /// (C++ 4.4). 2816 /// 2817 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2818 /// when the qualification conversion involves a change in the Objective-C 2819 /// object lifetime. 2820 bool 2821 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2822 bool CStyle, bool &ObjCLifetimeConversion) { 2823 FromType = Context.getCanonicalType(FromType); 2824 ToType = Context.getCanonicalType(ToType); 2825 ObjCLifetimeConversion = false; 2826 2827 // If FromType and ToType are the same type, this is not a 2828 // qualification conversion. 2829 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2830 return false; 2831 2832 // (C++ 4.4p4): 2833 // A conversion can add cv-qualifiers at levels other than the first 2834 // in multi-level pointers, subject to the following rules: [...] 2835 bool PreviousToQualsIncludeConst = true; 2836 bool UnwrappedAnyPointer = false; 2837 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2838 // Within each iteration of the loop, we check the qualifiers to 2839 // determine if this still looks like a qualification 2840 // conversion. Then, if all is well, we unwrap one more level of 2841 // pointers or pointers-to-members and do it all again 2842 // until there are no more pointers or pointers-to-members left to 2843 // unwrap. 2844 UnwrappedAnyPointer = true; 2845 2846 Qualifiers FromQuals = FromType.getQualifiers(); 2847 Qualifiers ToQuals = ToType.getQualifiers(); 2848 2849 // Objective-C ARC: 2850 // Check Objective-C lifetime conversions. 2851 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2852 UnwrappedAnyPointer) { 2853 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2854 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 2855 ObjCLifetimeConversion = true; 2856 FromQuals.removeObjCLifetime(); 2857 ToQuals.removeObjCLifetime(); 2858 } else { 2859 // Qualification conversions cannot cast between different 2860 // Objective-C lifetime qualifiers. 2861 return false; 2862 } 2863 } 2864 2865 // Allow addition/removal of GC attributes but not changing GC attributes. 2866 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2867 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2868 FromQuals.removeObjCGCAttr(); 2869 ToQuals.removeObjCGCAttr(); 2870 } 2871 2872 // -- for every j > 0, if const is in cv 1,j then const is in cv 2873 // 2,j, and similarly for volatile. 2874 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2875 return false; 2876 2877 // -- if the cv 1,j and cv 2,j are different, then const is in 2878 // every cv for 0 < k < j. 2879 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2880 && !PreviousToQualsIncludeConst) 2881 return false; 2882 2883 // Keep track of whether all prior cv-qualifiers in the "to" type 2884 // include const. 2885 PreviousToQualsIncludeConst 2886 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2887 } 2888 2889 // We are left with FromType and ToType being the pointee types 2890 // after unwrapping the original FromType and ToType the same number 2891 // of types. If we unwrapped any pointers, and if FromType and 2892 // ToType have the same unqualified type (since we checked 2893 // qualifiers above), then this is a qualification conversion. 2894 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2895 } 2896 2897 /// \brief - Determine whether this is a conversion from a scalar type to an 2898 /// atomic type. 2899 /// 2900 /// If successful, updates \c SCS's second and third steps in the conversion 2901 /// sequence to finish the conversion. 2902 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2903 bool InOverloadResolution, 2904 StandardConversionSequence &SCS, 2905 bool CStyle) { 2906 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2907 if (!ToAtomic) 2908 return false; 2909 2910 StandardConversionSequence InnerSCS; 2911 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2912 InOverloadResolution, InnerSCS, 2913 CStyle, /*AllowObjCWritebackConversion=*/false)) 2914 return false; 2915 2916 SCS.Second = InnerSCS.Second; 2917 SCS.setToType(1, InnerSCS.getToType(1)); 2918 SCS.Third = InnerSCS.Third; 2919 SCS.QualificationIncludesObjCLifetime 2920 = InnerSCS.QualificationIncludesObjCLifetime; 2921 SCS.setToType(2, InnerSCS.getToType(2)); 2922 return true; 2923 } 2924 2925 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2926 CXXConstructorDecl *Constructor, 2927 QualType Type) { 2928 const FunctionProtoType *CtorType = 2929 Constructor->getType()->getAs<FunctionProtoType>(); 2930 if (CtorType->getNumParams() > 0) { 2931 QualType FirstArg = CtorType->getParamType(0); 2932 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2933 return true; 2934 } 2935 return false; 2936 } 2937 2938 static OverloadingResult 2939 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2940 CXXRecordDecl *To, 2941 UserDefinedConversionSequence &User, 2942 OverloadCandidateSet &CandidateSet, 2943 bool AllowExplicit) { 2944 DeclContext::lookup_result R = S.LookupConstructors(To); 2945 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 2946 Con != ConEnd; ++Con) { 2947 NamedDecl *D = *Con; 2948 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2949 2950 // Find the constructor (which may be a template). 2951 CXXConstructorDecl *Constructor = 0; 2952 FunctionTemplateDecl *ConstructorTmpl 2953 = dyn_cast<FunctionTemplateDecl>(D); 2954 if (ConstructorTmpl) 2955 Constructor 2956 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2957 else 2958 Constructor = cast<CXXConstructorDecl>(D); 2959 2960 bool Usable = !Constructor->isInvalidDecl() && 2961 S.isInitListConstructor(Constructor) && 2962 (AllowExplicit || !Constructor->isExplicit()); 2963 if (Usable) { 2964 // If the first argument is (a reference to) the target type, 2965 // suppress conversions. 2966 bool SuppressUserConversions = 2967 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2968 if (ConstructorTmpl) 2969 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2970 /*ExplicitArgs*/ 0, 2971 From, CandidateSet, 2972 SuppressUserConversions); 2973 else 2974 S.AddOverloadCandidate(Constructor, FoundDecl, 2975 From, CandidateSet, 2976 SuppressUserConversions); 2977 } 2978 } 2979 2980 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2981 2982 OverloadCandidateSet::iterator Best; 2983 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2984 case OR_Success: { 2985 // Record the standard conversion we used and the conversion function. 2986 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2987 QualType ThisType = Constructor->getThisType(S.Context); 2988 // Initializer lists don't have conversions as such. 2989 User.Before.setAsIdentityConversion(); 2990 User.HadMultipleCandidates = HadMultipleCandidates; 2991 User.ConversionFunction = Constructor; 2992 User.FoundConversionFunction = Best->FoundDecl; 2993 User.After.setAsIdentityConversion(); 2994 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2995 User.After.setAllToTypes(ToType); 2996 return OR_Success; 2997 } 2998 2999 case OR_No_Viable_Function: 3000 return OR_No_Viable_Function; 3001 case OR_Deleted: 3002 return OR_Deleted; 3003 case OR_Ambiguous: 3004 return OR_Ambiguous; 3005 } 3006 3007 llvm_unreachable("Invalid OverloadResult!"); 3008 } 3009 3010 /// Determines whether there is a user-defined conversion sequence 3011 /// (C++ [over.ics.user]) that converts expression From to the type 3012 /// ToType. If such a conversion exists, User will contain the 3013 /// user-defined conversion sequence that performs such a conversion 3014 /// and this routine will return true. Otherwise, this routine returns 3015 /// false and User is unspecified. 3016 /// 3017 /// \param AllowExplicit true if the conversion should consider C++0x 3018 /// "explicit" conversion functions as well as non-explicit conversion 3019 /// functions (C++0x [class.conv.fct]p2). 3020 /// 3021 /// \param AllowObjCConversionOnExplicit true if the conversion should 3022 /// allow an extra Objective-C pointer conversion on uses of explicit 3023 /// constructors. Requires \c AllowExplicit to also be set. 3024 static OverloadingResult 3025 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3026 UserDefinedConversionSequence &User, 3027 OverloadCandidateSet &CandidateSet, 3028 bool AllowExplicit, 3029 bool AllowObjCConversionOnExplicit) { 3030 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3031 3032 // Whether we will only visit constructors. 3033 bool ConstructorsOnly = false; 3034 3035 // If the type we are conversion to is a class type, enumerate its 3036 // constructors. 3037 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3038 // C++ [over.match.ctor]p1: 3039 // When objects of class type are direct-initialized (8.5), or 3040 // copy-initialized from an expression of the same or a 3041 // derived class type (8.5), overload resolution selects the 3042 // constructor. [...] For copy-initialization, the candidate 3043 // functions are all the converting constructors (12.3.1) of 3044 // that class. The argument list is the expression-list within 3045 // the parentheses of the initializer. 3046 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3047 (From->getType()->getAs<RecordType>() && 3048 S.IsDerivedFrom(From->getType(), ToType))) 3049 ConstructorsOnly = true; 3050 3051 S.RequireCompleteType(From->getExprLoc(), ToType, 0); 3052 // RequireCompleteType may have returned true due to some invalid decl 3053 // during template instantiation, but ToType may be complete enough now 3054 // to try to recover. 3055 if (ToType->isIncompleteType()) { 3056 // We're not going to find any constructors. 3057 } else if (CXXRecordDecl *ToRecordDecl 3058 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3059 3060 Expr **Args = &From; 3061 unsigned NumArgs = 1; 3062 bool ListInitializing = false; 3063 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3064 // But first, see if there is an init-list-constructor that will work. 3065 OverloadingResult Result = IsInitializerListConstructorConversion( 3066 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3067 if (Result != OR_No_Viable_Function) 3068 return Result; 3069 // Never mind. 3070 CandidateSet.clear(); 3071 3072 // If we're list-initializing, we pass the individual elements as 3073 // arguments, not the entire list. 3074 Args = InitList->getInits(); 3075 NumArgs = InitList->getNumInits(); 3076 ListInitializing = true; 3077 } 3078 3079 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3080 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3081 Con != ConEnd; ++Con) { 3082 NamedDecl *D = *Con; 3083 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3084 3085 // Find the constructor (which may be a template). 3086 CXXConstructorDecl *Constructor = 0; 3087 FunctionTemplateDecl *ConstructorTmpl 3088 = dyn_cast<FunctionTemplateDecl>(D); 3089 if (ConstructorTmpl) 3090 Constructor 3091 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3092 else 3093 Constructor = cast<CXXConstructorDecl>(D); 3094 3095 bool Usable = !Constructor->isInvalidDecl(); 3096 if (ListInitializing) 3097 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3098 else 3099 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3100 if (Usable) { 3101 bool SuppressUserConversions = !ConstructorsOnly; 3102 if (SuppressUserConversions && ListInitializing) { 3103 SuppressUserConversions = false; 3104 if (NumArgs == 1) { 3105 // If the first argument is (a reference to) the target type, 3106 // suppress conversions. 3107 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3108 S.Context, Constructor, ToType); 3109 } 3110 } 3111 if (ConstructorTmpl) 3112 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3113 /*ExplicitArgs*/ 0, 3114 llvm::makeArrayRef(Args, NumArgs), 3115 CandidateSet, SuppressUserConversions); 3116 else 3117 // Allow one user-defined conversion when user specifies a 3118 // From->ToType conversion via an static cast (c-style, etc). 3119 S.AddOverloadCandidate(Constructor, FoundDecl, 3120 llvm::makeArrayRef(Args, NumArgs), 3121 CandidateSet, SuppressUserConversions); 3122 } 3123 } 3124 } 3125 } 3126 3127 // Enumerate conversion functions, if we're allowed to. 3128 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3129 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3130 // No conversion functions from incomplete types. 3131 } else if (const RecordType *FromRecordType 3132 = From->getType()->getAs<RecordType>()) { 3133 if (CXXRecordDecl *FromRecordDecl 3134 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3135 // Add all of the conversion functions as candidates. 3136 std::pair<CXXRecordDecl::conversion_iterator, 3137 CXXRecordDecl::conversion_iterator> 3138 Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3139 for (CXXRecordDecl::conversion_iterator 3140 I = Conversions.first, E = Conversions.second; I != E; ++I) { 3141 DeclAccessPair FoundDecl = I.getPair(); 3142 NamedDecl *D = FoundDecl.getDecl(); 3143 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3144 if (isa<UsingShadowDecl>(D)) 3145 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3146 3147 CXXConversionDecl *Conv; 3148 FunctionTemplateDecl *ConvTemplate; 3149 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3150 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3151 else 3152 Conv = cast<CXXConversionDecl>(D); 3153 3154 if (AllowExplicit || !Conv->isExplicit()) { 3155 if (ConvTemplate) 3156 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3157 ActingContext, From, ToType, 3158 CandidateSet, 3159 AllowObjCConversionOnExplicit); 3160 else 3161 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3162 From, ToType, CandidateSet, 3163 AllowObjCConversionOnExplicit); 3164 } 3165 } 3166 } 3167 } 3168 3169 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3170 3171 OverloadCandidateSet::iterator Best; 3172 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3173 case OR_Success: 3174 // Record the standard conversion we used and the conversion function. 3175 if (CXXConstructorDecl *Constructor 3176 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3177 // C++ [over.ics.user]p1: 3178 // If the user-defined conversion is specified by a 3179 // constructor (12.3.1), the initial standard conversion 3180 // sequence converts the source type to the type required by 3181 // the argument of the constructor. 3182 // 3183 QualType ThisType = Constructor->getThisType(S.Context); 3184 if (isa<InitListExpr>(From)) { 3185 // Initializer lists don't have conversions as such. 3186 User.Before.setAsIdentityConversion(); 3187 } else { 3188 if (Best->Conversions[0].isEllipsis()) 3189 User.EllipsisConversion = true; 3190 else { 3191 User.Before = Best->Conversions[0].Standard; 3192 User.EllipsisConversion = false; 3193 } 3194 } 3195 User.HadMultipleCandidates = HadMultipleCandidates; 3196 User.ConversionFunction = Constructor; 3197 User.FoundConversionFunction = Best->FoundDecl; 3198 User.After.setAsIdentityConversion(); 3199 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3200 User.After.setAllToTypes(ToType); 3201 return OR_Success; 3202 } 3203 if (CXXConversionDecl *Conversion 3204 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3205 // C++ [over.ics.user]p1: 3206 // 3207 // [...] If the user-defined conversion is specified by a 3208 // conversion function (12.3.2), the initial standard 3209 // conversion sequence converts the source type to the 3210 // implicit object parameter of the conversion function. 3211 User.Before = Best->Conversions[0].Standard; 3212 User.HadMultipleCandidates = HadMultipleCandidates; 3213 User.ConversionFunction = Conversion; 3214 User.FoundConversionFunction = Best->FoundDecl; 3215 User.EllipsisConversion = false; 3216 3217 // C++ [over.ics.user]p2: 3218 // The second standard conversion sequence converts the 3219 // result of the user-defined conversion to the target type 3220 // for the sequence. Since an implicit conversion sequence 3221 // is an initialization, the special rules for 3222 // initialization by user-defined conversion apply when 3223 // selecting the best user-defined conversion for a 3224 // user-defined conversion sequence (see 13.3.3 and 3225 // 13.3.3.1). 3226 User.After = Best->FinalConversion; 3227 return OR_Success; 3228 } 3229 llvm_unreachable("Not a constructor or conversion function?"); 3230 3231 case OR_No_Viable_Function: 3232 return OR_No_Viable_Function; 3233 case OR_Deleted: 3234 // No conversion here! We're done. 3235 return OR_Deleted; 3236 3237 case OR_Ambiguous: 3238 return OR_Ambiguous; 3239 } 3240 3241 llvm_unreachable("Invalid OverloadResult!"); 3242 } 3243 3244 bool 3245 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3246 ImplicitConversionSequence ICS; 3247 OverloadCandidateSet CandidateSet(From->getExprLoc()); 3248 OverloadingResult OvResult = 3249 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3250 CandidateSet, false, false); 3251 if (OvResult == OR_Ambiguous) 3252 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3253 << From->getType() << ToType << From->getSourceRange(); 3254 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3255 if (!RequireCompleteType(From->getLocStart(), ToType, 3256 diag::err_typecheck_nonviable_condition_incomplete, 3257 From->getType(), From->getSourceRange())) 3258 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3259 << From->getType() << From->getSourceRange() << ToType; 3260 } else 3261 return false; 3262 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3263 return true; 3264 } 3265 3266 /// \brief Compare the user-defined conversion functions or constructors 3267 /// of two user-defined conversion sequences to determine whether any ordering 3268 /// is possible. 3269 static ImplicitConversionSequence::CompareKind 3270 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3271 FunctionDecl *Function2) { 3272 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3273 return ImplicitConversionSequence::Indistinguishable; 3274 3275 // Objective-C++: 3276 // If both conversion functions are implicitly-declared conversions from 3277 // a lambda closure type to a function pointer and a block pointer, 3278 // respectively, always prefer the conversion to a function pointer, 3279 // because the function pointer is more lightweight and is more likely 3280 // to keep code working. 3281 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3282 if (!Conv1) 3283 return ImplicitConversionSequence::Indistinguishable; 3284 3285 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3286 if (!Conv2) 3287 return ImplicitConversionSequence::Indistinguishable; 3288 3289 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3290 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3291 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3292 if (Block1 != Block2) 3293 return Block1 ? ImplicitConversionSequence::Worse 3294 : ImplicitConversionSequence::Better; 3295 } 3296 3297 return ImplicitConversionSequence::Indistinguishable; 3298 } 3299 3300 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3301 const ImplicitConversionSequence &ICS) { 3302 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3303 (ICS.isUserDefined() && 3304 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3305 } 3306 3307 /// CompareImplicitConversionSequences - Compare two implicit 3308 /// conversion sequences to determine whether one is better than the 3309 /// other or if they are indistinguishable (C++ 13.3.3.2). 3310 static ImplicitConversionSequence::CompareKind 3311 CompareImplicitConversionSequences(Sema &S, 3312 const ImplicitConversionSequence& ICS1, 3313 const ImplicitConversionSequence& ICS2) 3314 { 3315 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3316 // conversion sequences (as defined in 13.3.3.1) 3317 // -- a standard conversion sequence (13.3.3.1.1) is a better 3318 // conversion sequence than a user-defined conversion sequence or 3319 // an ellipsis conversion sequence, and 3320 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3321 // conversion sequence than an ellipsis conversion sequence 3322 // (13.3.3.1.3). 3323 // 3324 // C++0x [over.best.ics]p10: 3325 // For the purpose of ranking implicit conversion sequences as 3326 // described in 13.3.3.2, the ambiguous conversion sequence is 3327 // treated as a user-defined sequence that is indistinguishable 3328 // from any other user-defined conversion sequence. 3329 3330 // String literal to 'char *' conversion has been deprecated in C++03. It has 3331 // been removed from C++11. We still accept this conversion, if it happens at 3332 // the best viable function. Otherwise, this conversion is considered worse 3333 // than ellipsis conversion. Consider this as an extension; this is not in the 3334 // standard. For example: 3335 // 3336 // int &f(...); // #1 3337 // void f(char*); // #2 3338 // void g() { int &r = f("foo"); } 3339 // 3340 // In C++03, we pick #2 as the best viable function. 3341 // In C++11, we pick #1 as the best viable function, because ellipsis 3342 // conversion is better than string-literal to char* conversion (since there 3343 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3344 // convert arguments, #2 would be the best viable function in C++11. 3345 // If the best viable function has this conversion, a warning will be issued 3346 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3347 3348 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3349 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3350 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3351 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3352 ? ImplicitConversionSequence::Worse 3353 : ImplicitConversionSequence::Better; 3354 3355 if (ICS1.getKindRank() < ICS2.getKindRank()) 3356 return ImplicitConversionSequence::Better; 3357 if (ICS2.getKindRank() < ICS1.getKindRank()) 3358 return ImplicitConversionSequence::Worse; 3359 3360 // The following checks require both conversion sequences to be of 3361 // the same kind. 3362 if (ICS1.getKind() != ICS2.getKind()) 3363 return ImplicitConversionSequence::Indistinguishable; 3364 3365 ImplicitConversionSequence::CompareKind Result = 3366 ImplicitConversionSequence::Indistinguishable; 3367 3368 // Two implicit conversion sequences of the same form are 3369 // indistinguishable conversion sequences unless one of the 3370 // following rules apply: (C++ 13.3.3.2p3): 3371 if (ICS1.isStandard()) 3372 Result = CompareStandardConversionSequences(S, 3373 ICS1.Standard, ICS2.Standard); 3374 else if (ICS1.isUserDefined()) { 3375 // User-defined conversion sequence U1 is a better conversion 3376 // sequence than another user-defined conversion sequence U2 if 3377 // they contain the same user-defined conversion function or 3378 // constructor and if the second standard conversion sequence of 3379 // U1 is better than the second standard conversion sequence of 3380 // U2 (C++ 13.3.3.2p3). 3381 if (ICS1.UserDefined.ConversionFunction == 3382 ICS2.UserDefined.ConversionFunction) 3383 Result = CompareStandardConversionSequences(S, 3384 ICS1.UserDefined.After, 3385 ICS2.UserDefined.After); 3386 else 3387 Result = compareConversionFunctions(S, 3388 ICS1.UserDefined.ConversionFunction, 3389 ICS2.UserDefined.ConversionFunction); 3390 } 3391 3392 // List-initialization sequence L1 is a better conversion sequence than 3393 // list-initialization sequence L2 if L1 converts to std::initializer_list<X> 3394 // for some X and L2 does not. 3395 if (Result == ImplicitConversionSequence::Indistinguishable && 3396 !ICS1.isBad()) { 3397 if (ICS1.isStdInitializerListElement() && 3398 !ICS2.isStdInitializerListElement()) 3399 return ImplicitConversionSequence::Better; 3400 if (!ICS1.isStdInitializerListElement() && 3401 ICS2.isStdInitializerListElement()) 3402 return ImplicitConversionSequence::Worse; 3403 } 3404 3405 return Result; 3406 } 3407 3408 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3409 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3410 Qualifiers Quals; 3411 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3412 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3413 } 3414 3415 return Context.hasSameUnqualifiedType(T1, T2); 3416 } 3417 3418 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3419 // determine if one is a proper subset of the other. 3420 static ImplicitConversionSequence::CompareKind 3421 compareStandardConversionSubsets(ASTContext &Context, 3422 const StandardConversionSequence& SCS1, 3423 const StandardConversionSequence& SCS2) { 3424 ImplicitConversionSequence::CompareKind Result 3425 = ImplicitConversionSequence::Indistinguishable; 3426 3427 // the identity conversion sequence is considered to be a subsequence of 3428 // any non-identity conversion sequence 3429 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3430 return ImplicitConversionSequence::Better; 3431 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3432 return ImplicitConversionSequence::Worse; 3433 3434 if (SCS1.Second != SCS2.Second) { 3435 if (SCS1.Second == ICK_Identity) 3436 Result = ImplicitConversionSequence::Better; 3437 else if (SCS2.Second == ICK_Identity) 3438 Result = ImplicitConversionSequence::Worse; 3439 else 3440 return ImplicitConversionSequence::Indistinguishable; 3441 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3442 return ImplicitConversionSequence::Indistinguishable; 3443 3444 if (SCS1.Third == SCS2.Third) { 3445 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3446 : ImplicitConversionSequence::Indistinguishable; 3447 } 3448 3449 if (SCS1.Third == ICK_Identity) 3450 return Result == ImplicitConversionSequence::Worse 3451 ? ImplicitConversionSequence::Indistinguishable 3452 : ImplicitConversionSequence::Better; 3453 3454 if (SCS2.Third == ICK_Identity) 3455 return Result == ImplicitConversionSequence::Better 3456 ? ImplicitConversionSequence::Indistinguishable 3457 : ImplicitConversionSequence::Worse; 3458 3459 return ImplicitConversionSequence::Indistinguishable; 3460 } 3461 3462 /// \brief Determine whether one of the given reference bindings is better 3463 /// than the other based on what kind of bindings they are. 3464 static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3465 const StandardConversionSequence &SCS2) { 3466 // C++0x [over.ics.rank]p3b4: 3467 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3468 // implicit object parameter of a non-static member function declared 3469 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3470 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3471 // lvalue reference to a function lvalue and S2 binds an rvalue 3472 // reference*. 3473 // 3474 // FIXME: Rvalue references. We're going rogue with the above edits, 3475 // because the semantics in the current C++0x working paper (N3225 at the 3476 // time of this writing) break the standard definition of std::forward 3477 // and std::reference_wrapper when dealing with references to functions. 3478 // Proposed wording changes submitted to CWG for consideration. 3479 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3480 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3481 return false; 3482 3483 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3484 SCS2.IsLvalueReference) || 3485 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3486 !SCS2.IsLvalueReference); 3487 } 3488 3489 /// CompareStandardConversionSequences - Compare two standard 3490 /// conversion sequences to determine whether one is better than the 3491 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3492 static ImplicitConversionSequence::CompareKind 3493 CompareStandardConversionSequences(Sema &S, 3494 const StandardConversionSequence& SCS1, 3495 const StandardConversionSequence& SCS2) 3496 { 3497 // Standard conversion sequence S1 is a better conversion sequence 3498 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3499 3500 // -- S1 is a proper subsequence of S2 (comparing the conversion 3501 // sequences in the canonical form defined by 13.3.3.1.1, 3502 // excluding any Lvalue Transformation; the identity conversion 3503 // sequence is considered to be a subsequence of any 3504 // non-identity conversion sequence) or, if not that, 3505 if (ImplicitConversionSequence::CompareKind CK 3506 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3507 return CK; 3508 3509 // -- the rank of S1 is better than the rank of S2 (by the rules 3510 // defined below), or, if not that, 3511 ImplicitConversionRank Rank1 = SCS1.getRank(); 3512 ImplicitConversionRank Rank2 = SCS2.getRank(); 3513 if (Rank1 < Rank2) 3514 return ImplicitConversionSequence::Better; 3515 else if (Rank2 < Rank1) 3516 return ImplicitConversionSequence::Worse; 3517 3518 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3519 // are indistinguishable unless one of the following rules 3520 // applies: 3521 3522 // A conversion that is not a conversion of a pointer, or 3523 // pointer to member, to bool is better than another conversion 3524 // that is such a conversion. 3525 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3526 return SCS2.isPointerConversionToBool() 3527 ? ImplicitConversionSequence::Better 3528 : ImplicitConversionSequence::Worse; 3529 3530 // C++ [over.ics.rank]p4b2: 3531 // 3532 // If class B is derived directly or indirectly from class A, 3533 // conversion of B* to A* is better than conversion of B* to 3534 // void*, and conversion of A* to void* is better than conversion 3535 // of B* to void*. 3536 bool SCS1ConvertsToVoid 3537 = SCS1.isPointerConversionToVoidPointer(S.Context); 3538 bool SCS2ConvertsToVoid 3539 = SCS2.isPointerConversionToVoidPointer(S.Context); 3540 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3541 // Exactly one of the conversion sequences is a conversion to 3542 // a void pointer; it's the worse conversion. 3543 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3544 : ImplicitConversionSequence::Worse; 3545 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3546 // Neither conversion sequence converts to a void pointer; compare 3547 // their derived-to-base conversions. 3548 if (ImplicitConversionSequence::CompareKind DerivedCK 3549 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3550 return DerivedCK; 3551 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3552 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3553 // Both conversion sequences are conversions to void 3554 // pointers. Compare the source types to determine if there's an 3555 // inheritance relationship in their sources. 3556 QualType FromType1 = SCS1.getFromType(); 3557 QualType FromType2 = SCS2.getFromType(); 3558 3559 // Adjust the types we're converting from via the array-to-pointer 3560 // conversion, if we need to. 3561 if (SCS1.First == ICK_Array_To_Pointer) 3562 FromType1 = S.Context.getArrayDecayedType(FromType1); 3563 if (SCS2.First == ICK_Array_To_Pointer) 3564 FromType2 = S.Context.getArrayDecayedType(FromType2); 3565 3566 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3567 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3568 3569 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3570 return ImplicitConversionSequence::Better; 3571 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3572 return ImplicitConversionSequence::Worse; 3573 3574 // Objective-C++: If one interface is more specific than the 3575 // other, it is the better one. 3576 const ObjCObjectPointerType* FromObjCPtr1 3577 = FromType1->getAs<ObjCObjectPointerType>(); 3578 const ObjCObjectPointerType* FromObjCPtr2 3579 = FromType2->getAs<ObjCObjectPointerType>(); 3580 if (FromObjCPtr1 && FromObjCPtr2) { 3581 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3582 FromObjCPtr2); 3583 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3584 FromObjCPtr1); 3585 if (AssignLeft != AssignRight) { 3586 return AssignLeft? ImplicitConversionSequence::Better 3587 : ImplicitConversionSequence::Worse; 3588 } 3589 } 3590 } 3591 3592 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3593 // bullet 3). 3594 if (ImplicitConversionSequence::CompareKind QualCK 3595 = CompareQualificationConversions(S, SCS1, SCS2)) 3596 return QualCK; 3597 3598 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3599 // Check for a better reference binding based on the kind of bindings. 3600 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3601 return ImplicitConversionSequence::Better; 3602 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3603 return ImplicitConversionSequence::Worse; 3604 3605 // C++ [over.ics.rank]p3b4: 3606 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3607 // which the references refer are the same type except for 3608 // top-level cv-qualifiers, and the type to which the reference 3609 // initialized by S2 refers is more cv-qualified than the type 3610 // to which the reference initialized by S1 refers. 3611 QualType T1 = SCS1.getToType(2); 3612 QualType T2 = SCS2.getToType(2); 3613 T1 = S.Context.getCanonicalType(T1); 3614 T2 = S.Context.getCanonicalType(T2); 3615 Qualifiers T1Quals, T2Quals; 3616 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3617 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3618 if (UnqualT1 == UnqualT2) { 3619 // Objective-C++ ARC: If the references refer to objects with different 3620 // lifetimes, prefer bindings that don't change lifetime. 3621 if (SCS1.ObjCLifetimeConversionBinding != 3622 SCS2.ObjCLifetimeConversionBinding) { 3623 return SCS1.ObjCLifetimeConversionBinding 3624 ? ImplicitConversionSequence::Worse 3625 : ImplicitConversionSequence::Better; 3626 } 3627 3628 // If the type is an array type, promote the element qualifiers to the 3629 // type for comparison. 3630 if (isa<ArrayType>(T1) && T1Quals) 3631 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3632 if (isa<ArrayType>(T2) && T2Quals) 3633 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3634 if (T2.isMoreQualifiedThan(T1)) 3635 return ImplicitConversionSequence::Better; 3636 else if (T1.isMoreQualifiedThan(T2)) 3637 return ImplicitConversionSequence::Worse; 3638 } 3639 } 3640 3641 // In Microsoft mode, prefer an integral conversion to a 3642 // floating-to-integral conversion if the integral conversion 3643 // is between types of the same size. 3644 // For example: 3645 // void f(float); 3646 // void f(int); 3647 // int main { 3648 // long a; 3649 // f(a); 3650 // } 3651 // Here, MSVC will call f(int) instead of generating a compile error 3652 // as clang will do in standard mode. 3653 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3654 SCS2.Second == ICK_Floating_Integral && 3655 S.Context.getTypeSize(SCS1.getFromType()) == 3656 S.Context.getTypeSize(SCS1.getToType(2))) 3657 return ImplicitConversionSequence::Better; 3658 3659 return ImplicitConversionSequence::Indistinguishable; 3660 } 3661 3662 /// CompareQualificationConversions - Compares two standard conversion 3663 /// sequences to determine whether they can be ranked based on their 3664 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3665 ImplicitConversionSequence::CompareKind 3666 CompareQualificationConversions(Sema &S, 3667 const StandardConversionSequence& SCS1, 3668 const StandardConversionSequence& SCS2) { 3669 // C++ 13.3.3.2p3: 3670 // -- S1 and S2 differ only in their qualification conversion and 3671 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3672 // cv-qualification signature of type T1 is a proper subset of 3673 // the cv-qualification signature of type T2, and S1 is not the 3674 // deprecated string literal array-to-pointer conversion (4.2). 3675 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3676 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3677 return ImplicitConversionSequence::Indistinguishable; 3678 3679 // FIXME: the example in the standard doesn't use a qualification 3680 // conversion (!) 3681 QualType T1 = SCS1.getToType(2); 3682 QualType T2 = SCS2.getToType(2); 3683 T1 = S.Context.getCanonicalType(T1); 3684 T2 = S.Context.getCanonicalType(T2); 3685 Qualifiers T1Quals, T2Quals; 3686 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3687 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3688 3689 // If the types are the same, we won't learn anything by unwrapped 3690 // them. 3691 if (UnqualT1 == UnqualT2) 3692 return ImplicitConversionSequence::Indistinguishable; 3693 3694 // If the type is an array type, promote the element qualifiers to the type 3695 // for comparison. 3696 if (isa<ArrayType>(T1) && T1Quals) 3697 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3698 if (isa<ArrayType>(T2) && T2Quals) 3699 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3700 3701 ImplicitConversionSequence::CompareKind Result 3702 = ImplicitConversionSequence::Indistinguishable; 3703 3704 // Objective-C++ ARC: 3705 // Prefer qualification conversions not involving a change in lifetime 3706 // to qualification conversions that do not change lifetime. 3707 if (SCS1.QualificationIncludesObjCLifetime != 3708 SCS2.QualificationIncludesObjCLifetime) { 3709 Result = SCS1.QualificationIncludesObjCLifetime 3710 ? ImplicitConversionSequence::Worse 3711 : ImplicitConversionSequence::Better; 3712 } 3713 3714 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3715 // Within each iteration of the loop, we check the qualifiers to 3716 // determine if this still looks like a qualification 3717 // conversion. Then, if all is well, we unwrap one more level of 3718 // pointers or pointers-to-members and do it all again 3719 // until there are no more pointers or pointers-to-members left 3720 // to unwrap. This essentially mimics what 3721 // IsQualificationConversion does, but here we're checking for a 3722 // strict subset of qualifiers. 3723 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3724 // The qualifiers are the same, so this doesn't tell us anything 3725 // about how the sequences rank. 3726 ; 3727 else if (T2.isMoreQualifiedThan(T1)) { 3728 // T1 has fewer qualifiers, so it could be the better sequence. 3729 if (Result == ImplicitConversionSequence::Worse) 3730 // Neither has qualifiers that are a subset of the other's 3731 // qualifiers. 3732 return ImplicitConversionSequence::Indistinguishable; 3733 3734 Result = ImplicitConversionSequence::Better; 3735 } else if (T1.isMoreQualifiedThan(T2)) { 3736 // T2 has fewer qualifiers, so it could be the better sequence. 3737 if (Result == ImplicitConversionSequence::Better) 3738 // Neither has qualifiers that are a subset of the other's 3739 // qualifiers. 3740 return ImplicitConversionSequence::Indistinguishable; 3741 3742 Result = ImplicitConversionSequence::Worse; 3743 } else { 3744 // Qualifiers are disjoint. 3745 return ImplicitConversionSequence::Indistinguishable; 3746 } 3747 3748 // If the types after this point are equivalent, we're done. 3749 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3750 break; 3751 } 3752 3753 // Check that the winning standard conversion sequence isn't using 3754 // the deprecated string literal array to pointer conversion. 3755 switch (Result) { 3756 case ImplicitConversionSequence::Better: 3757 if (SCS1.DeprecatedStringLiteralToCharPtr) 3758 Result = ImplicitConversionSequence::Indistinguishable; 3759 break; 3760 3761 case ImplicitConversionSequence::Indistinguishable: 3762 break; 3763 3764 case ImplicitConversionSequence::Worse: 3765 if (SCS2.DeprecatedStringLiteralToCharPtr) 3766 Result = ImplicitConversionSequence::Indistinguishable; 3767 break; 3768 } 3769 3770 return Result; 3771 } 3772 3773 /// CompareDerivedToBaseConversions - Compares two standard conversion 3774 /// sequences to determine whether they can be ranked based on their 3775 /// various kinds of derived-to-base conversions (C++ 3776 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3777 /// conversions between Objective-C interface types. 3778 ImplicitConversionSequence::CompareKind 3779 CompareDerivedToBaseConversions(Sema &S, 3780 const StandardConversionSequence& SCS1, 3781 const StandardConversionSequence& SCS2) { 3782 QualType FromType1 = SCS1.getFromType(); 3783 QualType ToType1 = SCS1.getToType(1); 3784 QualType FromType2 = SCS2.getFromType(); 3785 QualType ToType2 = SCS2.getToType(1); 3786 3787 // Adjust the types we're converting from via the array-to-pointer 3788 // conversion, if we need to. 3789 if (SCS1.First == ICK_Array_To_Pointer) 3790 FromType1 = S.Context.getArrayDecayedType(FromType1); 3791 if (SCS2.First == ICK_Array_To_Pointer) 3792 FromType2 = S.Context.getArrayDecayedType(FromType2); 3793 3794 // Canonicalize all of the types. 3795 FromType1 = S.Context.getCanonicalType(FromType1); 3796 ToType1 = S.Context.getCanonicalType(ToType1); 3797 FromType2 = S.Context.getCanonicalType(FromType2); 3798 ToType2 = S.Context.getCanonicalType(ToType2); 3799 3800 // C++ [over.ics.rank]p4b3: 3801 // 3802 // If class B is derived directly or indirectly from class A and 3803 // class C is derived directly or indirectly from B, 3804 // 3805 // Compare based on pointer conversions. 3806 if (SCS1.Second == ICK_Pointer_Conversion && 3807 SCS2.Second == ICK_Pointer_Conversion && 3808 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3809 FromType1->isPointerType() && FromType2->isPointerType() && 3810 ToType1->isPointerType() && ToType2->isPointerType()) { 3811 QualType FromPointee1 3812 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3813 QualType ToPointee1 3814 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3815 QualType FromPointee2 3816 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3817 QualType ToPointee2 3818 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3819 3820 // -- conversion of C* to B* is better than conversion of C* to A*, 3821 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3822 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3823 return ImplicitConversionSequence::Better; 3824 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3825 return ImplicitConversionSequence::Worse; 3826 } 3827 3828 // -- conversion of B* to A* is better than conversion of C* to A*, 3829 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3830 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3831 return ImplicitConversionSequence::Better; 3832 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3833 return ImplicitConversionSequence::Worse; 3834 } 3835 } else if (SCS1.Second == ICK_Pointer_Conversion && 3836 SCS2.Second == ICK_Pointer_Conversion) { 3837 const ObjCObjectPointerType *FromPtr1 3838 = FromType1->getAs<ObjCObjectPointerType>(); 3839 const ObjCObjectPointerType *FromPtr2 3840 = FromType2->getAs<ObjCObjectPointerType>(); 3841 const ObjCObjectPointerType *ToPtr1 3842 = ToType1->getAs<ObjCObjectPointerType>(); 3843 const ObjCObjectPointerType *ToPtr2 3844 = ToType2->getAs<ObjCObjectPointerType>(); 3845 3846 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3847 // Apply the same conversion ranking rules for Objective-C pointer types 3848 // that we do for C++ pointers to class types. However, we employ the 3849 // Objective-C pseudo-subtyping relationship used for assignment of 3850 // Objective-C pointer types. 3851 bool FromAssignLeft 3852 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3853 bool FromAssignRight 3854 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3855 bool ToAssignLeft 3856 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3857 bool ToAssignRight 3858 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3859 3860 // A conversion to an a non-id object pointer type or qualified 'id' 3861 // type is better than a conversion to 'id'. 3862 if (ToPtr1->isObjCIdType() && 3863 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3864 return ImplicitConversionSequence::Worse; 3865 if (ToPtr2->isObjCIdType() && 3866 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3867 return ImplicitConversionSequence::Better; 3868 3869 // A conversion to a non-id object pointer type is better than a 3870 // conversion to a qualified 'id' type 3871 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3872 return ImplicitConversionSequence::Worse; 3873 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3874 return ImplicitConversionSequence::Better; 3875 3876 // A conversion to an a non-Class object pointer type or qualified 'Class' 3877 // type is better than a conversion to 'Class'. 3878 if (ToPtr1->isObjCClassType() && 3879 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3880 return ImplicitConversionSequence::Worse; 3881 if (ToPtr2->isObjCClassType() && 3882 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3883 return ImplicitConversionSequence::Better; 3884 3885 // A conversion to a non-Class object pointer type is better than a 3886 // conversion to a qualified 'Class' type. 3887 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3888 return ImplicitConversionSequence::Worse; 3889 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3890 return ImplicitConversionSequence::Better; 3891 3892 // -- "conversion of C* to B* is better than conversion of C* to A*," 3893 if (S.Context.hasSameType(FromType1, FromType2) && 3894 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3895 (ToAssignLeft != ToAssignRight)) 3896 return ToAssignLeft? ImplicitConversionSequence::Worse 3897 : ImplicitConversionSequence::Better; 3898 3899 // -- "conversion of B* to A* is better than conversion of C* to A*," 3900 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3901 (FromAssignLeft != FromAssignRight)) 3902 return FromAssignLeft? ImplicitConversionSequence::Better 3903 : ImplicitConversionSequence::Worse; 3904 } 3905 } 3906 3907 // Ranking of member-pointer types. 3908 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3909 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3910 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3911 const MemberPointerType * FromMemPointer1 = 3912 FromType1->getAs<MemberPointerType>(); 3913 const MemberPointerType * ToMemPointer1 = 3914 ToType1->getAs<MemberPointerType>(); 3915 const MemberPointerType * FromMemPointer2 = 3916 FromType2->getAs<MemberPointerType>(); 3917 const MemberPointerType * ToMemPointer2 = 3918 ToType2->getAs<MemberPointerType>(); 3919 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3920 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3921 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3922 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3923 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3924 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3925 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3926 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3927 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3928 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3929 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3930 return ImplicitConversionSequence::Worse; 3931 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3932 return ImplicitConversionSequence::Better; 3933 } 3934 // conversion of B::* to C::* is better than conversion of A::* to C::* 3935 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3936 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3937 return ImplicitConversionSequence::Better; 3938 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3939 return ImplicitConversionSequence::Worse; 3940 } 3941 } 3942 3943 if (SCS1.Second == ICK_Derived_To_Base) { 3944 // -- conversion of C to B is better than conversion of C to A, 3945 // -- binding of an expression of type C to a reference of type 3946 // B& is better than binding an expression of type C to a 3947 // reference of type A&, 3948 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3949 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3950 if (S.IsDerivedFrom(ToType1, ToType2)) 3951 return ImplicitConversionSequence::Better; 3952 else if (S.IsDerivedFrom(ToType2, ToType1)) 3953 return ImplicitConversionSequence::Worse; 3954 } 3955 3956 // -- conversion of B to A is better than conversion of C to A. 3957 // -- binding of an expression of type B to a reference of type 3958 // A& is better than binding an expression of type C to a 3959 // reference of type A&, 3960 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3961 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3962 if (S.IsDerivedFrom(FromType2, FromType1)) 3963 return ImplicitConversionSequence::Better; 3964 else if (S.IsDerivedFrom(FromType1, FromType2)) 3965 return ImplicitConversionSequence::Worse; 3966 } 3967 } 3968 3969 return ImplicitConversionSequence::Indistinguishable; 3970 } 3971 3972 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 3973 /// C++ class. 3974 static bool isTypeValid(QualType T) { 3975 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 3976 return !Record->isInvalidDecl(); 3977 3978 return true; 3979 } 3980 3981 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 3982 /// determine whether they are reference-related, 3983 /// reference-compatible, reference-compatible with added 3984 /// qualification, or incompatible, for use in C++ initialization by 3985 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3986 /// type, and the first type (T1) is the pointee type of the reference 3987 /// type being initialized. 3988 Sema::ReferenceCompareResult 3989 Sema::CompareReferenceRelationship(SourceLocation Loc, 3990 QualType OrigT1, QualType OrigT2, 3991 bool &DerivedToBase, 3992 bool &ObjCConversion, 3993 bool &ObjCLifetimeConversion) { 3994 assert(!OrigT1->isReferenceType() && 3995 "T1 must be the pointee type of the reference type"); 3996 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3997 3998 QualType T1 = Context.getCanonicalType(OrigT1); 3999 QualType T2 = Context.getCanonicalType(OrigT2); 4000 Qualifiers T1Quals, T2Quals; 4001 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4002 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4003 4004 // C++ [dcl.init.ref]p4: 4005 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4006 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4007 // T1 is a base class of T2. 4008 DerivedToBase = false; 4009 ObjCConversion = false; 4010 ObjCLifetimeConversion = false; 4011 if (UnqualT1 == UnqualT2) { 4012 // Nothing to do. 4013 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 4014 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4015 IsDerivedFrom(UnqualT2, UnqualT1)) 4016 DerivedToBase = true; 4017 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4018 UnqualT2->isObjCObjectOrInterfaceType() && 4019 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4020 ObjCConversion = true; 4021 else 4022 return Ref_Incompatible; 4023 4024 // At this point, we know that T1 and T2 are reference-related (at 4025 // least). 4026 4027 // If the type is an array type, promote the element qualifiers to the type 4028 // for comparison. 4029 if (isa<ArrayType>(T1) && T1Quals) 4030 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4031 if (isa<ArrayType>(T2) && T2Quals) 4032 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4033 4034 // C++ [dcl.init.ref]p4: 4035 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4036 // reference-related to T2 and cv1 is the same cv-qualification 4037 // as, or greater cv-qualification than, cv2. For purposes of 4038 // overload resolution, cases for which cv1 is greater 4039 // cv-qualification than cv2 are identified as 4040 // reference-compatible with added qualification (see 13.3.3.2). 4041 // 4042 // Note that we also require equivalence of Objective-C GC and address-space 4043 // qualifiers when performing these computations, so that e.g., an int in 4044 // address space 1 is not reference-compatible with an int in address 4045 // space 2. 4046 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4047 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4048 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4049 ObjCLifetimeConversion = true; 4050 4051 T1Quals.removeObjCLifetime(); 4052 T2Quals.removeObjCLifetime(); 4053 } 4054 4055 if (T1Quals == T2Quals) 4056 return Ref_Compatible; 4057 else if (T1Quals.compatiblyIncludes(T2Quals)) 4058 return Ref_Compatible_With_Added_Qualification; 4059 else 4060 return Ref_Related; 4061 } 4062 4063 /// \brief Look for a user-defined conversion to an value reference-compatible 4064 /// with DeclType. Return true if something definite is found. 4065 static bool 4066 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4067 QualType DeclType, SourceLocation DeclLoc, 4068 Expr *Init, QualType T2, bool AllowRvalues, 4069 bool AllowExplicit) { 4070 assert(T2->isRecordType() && "Can only find conversions of record types."); 4071 CXXRecordDecl *T2RecordDecl 4072 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4073 4074 OverloadCandidateSet CandidateSet(DeclLoc); 4075 std::pair<CXXRecordDecl::conversion_iterator, 4076 CXXRecordDecl::conversion_iterator> 4077 Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4078 for (CXXRecordDecl::conversion_iterator 4079 I = Conversions.first, E = Conversions.second; I != E; ++I) { 4080 NamedDecl *D = *I; 4081 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4082 if (isa<UsingShadowDecl>(D)) 4083 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4084 4085 FunctionTemplateDecl *ConvTemplate 4086 = dyn_cast<FunctionTemplateDecl>(D); 4087 CXXConversionDecl *Conv; 4088 if (ConvTemplate) 4089 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4090 else 4091 Conv = cast<CXXConversionDecl>(D); 4092 4093 // If this is an explicit conversion, and we're not allowed to consider 4094 // explicit conversions, skip it. 4095 if (!AllowExplicit && Conv->isExplicit()) 4096 continue; 4097 4098 if (AllowRvalues) { 4099 bool DerivedToBase = false; 4100 bool ObjCConversion = false; 4101 bool ObjCLifetimeConversion = false; 4102 4103 // If we are initializing an rvalue reference, don't permit conversion 4104 // functions that return lvalues. 4105 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4106 const ReferenceType *RefType 4107 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4108 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4109 continue; 4110 } 4111 4112 if (!ConvTemplate && 4113 S.CompareReferenceRelationship( 4114 DeclLoc, 4115 Conv->getConversionType().getNonReferenceType() 4116 .getUnqualifiedType(), 4117 DeclType.getNonReferenceType().getUnqualifiedType(), 4118 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4119 Sema::Ref_Incompatible) 4120 continue; 4121 } else { 4122 // If the conversion function doesn't return a reference type, 4123 // it can't be considered for this conversion. An rvalue reference 4124 // is only acceptable if its referencee is a function type. 4125 4126 const ReferenceType *RefType = 4127 Conv->getConversionType()->getAs<ReferenceType>(); 4128 if (!RefType || 4129 (!RefType->isLValueReferenceType() && 4130 !RefType->getPointeeType()->isFunctionType())) 4131 continue; 4132 } 4133 4134 if (ConvTemplate) 4135 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4136 Init, DeclType, CandidateSet, 4137 /*AllowObjCConversionOnExplicit=*/false); 4138 else 4139 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4140 DeclType, CandidateSet, 4141 /*AllowObjCConversionOnExplicit=*/false); 4142 } 4143 4144 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4145 4146 OverloadCandidateSet::iterator Best; 4147 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4148 case OR_Success: 4149 // C++ [over.ics.ref]p1: 4150 // 4151 // [...] If the parameter binds directly to the result of 4152 // applying a conversion function to the argument 4153 // expression, the implicit conversion sequence is a 4154 // user-defined conversion sequence (13.3.3.1.2), with the 4155 // second standard conversion sequence either an identity 4156 // conversion or, if the conversion function returns an 4157 // entity of a type that is a derived class of the parameter 4158 // type, a derived-to-base Conversion. 4159 if (!Best->FinalConversion.DirectBinding) 4160 return false; 4161 4162 ICS.setUserDefined(); 4163 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4164 ICS.UserDefined.After = Best->FinalConversion; 4165 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4166 ICS.UserDefined.ConversionFunction = Best->Function; 4167 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4168 ICS.UserDefined.EllipsisConversion = false; 4169 assert(ICS.UserDefined.After.ReferenceBinding && 4170 ICS.UserDefined.After.DirectBinding && 4171 "Expected a direct reference binding!"); 4172 return true; 4173 4174 case OR_Ambiguous: 4175 ICS.setAmbiguous(); 4176 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4177 Cand != CandidateSet.end(); ++Cand) 4178 if (Cand->Viable) 4179 ICS.Ambiguous.addConversion(Cand->Function); 4180 return true; 4181 4182 case OR_No_Viable_Function: 4183 case OR_Deleted: 4184 // There was no suitable conversion, or we found a deleted 4185 // conversion; continue with other checks. 4186 return false; 4187 } 4188 4189 llvm_unreachable("Invalid OverloadResult!"); 4190 } 4191 4192 /// \brief Compute an implicit conversion sequence for reference 4193 /// initialization. 4194 static ImplicitConversionSequence 4195 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4196 SourceLocation DeclLoc, 4197 bool SuppressUserConversions, 4198 bool AllowExplicit) { 4199 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4200 4201 // Most paths end in a failed conversion. 4202 ImplicitConversionSequence ICS; 4203 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4204 4205 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4206 QualType T2 = Init->getType(); 4207 4208 // If the initializer is the address of an overloaded function, try 4209 // to resolve the overloaded function. If all goes well, T2 is the 4210 // type of the resulting function. 4211 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4212 DeclAccessPair Found; 4213 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4214 false, Found)) 4215 T2 = Fn->getType(); 4216 } 4217 4218 // Compute some basic properties of the types and the initializer. 4219 bool isRValRef = DeclType->isRValueReferenceType(); 4220 bool DerivedToBase = false; 4221 bool ObjCConversion = false; 4222 bool ObjCLifetimeConversion = false; 4223 Expr::Classification InitCategory = Init->Classify(S.Context); 4224 Sema::ReferenceCompareResult RefRelationship 4225 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4226 ObjCConversion, ObjCLifetimeConversion); 4227 4228 4229 // C++0x [dcl.init.ref]p5: 4230 // A reference to type "cv1 T1" is initialized by an expression 4231 // of type "cv2 T2" as follows: 4232 4233 // -- If reference is an lvalue reference and the initializer expression 4234 if (!isRValRef) { 4235 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4236 // reference-compatible with "cv2 T2," or 4237 // 4238 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4239 if (InitCategory.isLValue() && 4240 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4241 // C++ [over.ics.ref]p1: 4242 // When a parameter of reference type binds directly (8.5.3) 4243 // to an argument expression, the implicit conversion sequence 4244 // is the identity conversion, unless the argument expression 4245 // has a type that is a derived class of the parameter type, 4246 // in which case the implicit conversion sequence is a 4247 // derived-to-base Conversion (13.3.3.1). 4248 ICS.setStandard(); 4249 ICS.Standard.First = ICK_Identity; 4250 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4251 : ObjCConversion? ICK_Compatible_Conversion 4252 : ICK_Identity; 4253 ICS.Standard.Third = ICK_Identity; 4254 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4255 ICS.Standard.setToType(0, T2); 4256 ICS.Standard.setToType(1, T1); 4257 ICS.Standard.setToType(2, T1); 4258 ICS.Standard.ReferenceBinding = true; 4259 ICS.Standard.DirectBinding = true; 4260 ICS.Standard.IsLvalueReference = !isRValRef; 4261 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4262 ICS.Standard.BindsToRvalue = false; 4263 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4264 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4265 ICS.Standard.CopyConstructor = 0; 4266 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4267 4268 // Nothing more to do: the inaccessibility/ambiguity check for 4269 // derived-to-base conversions is suppressed when we're 4270 // computing the implicit conversion sequence (C++ 4271 // [over.best.ics]p2). 4272 return ICS; 4273 } 4274 4275 // -- has a class type (i.e., T2 is a class type), where T1 is 4276 // not reference-related to T2, and can be implicitly 4277 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4278 // is reference-compatible with "cv3 T3" 92) (this 4279 // conversion is selected by enumerating the applicable 4280 // conversion functions (13.3.1.6) and choosing the best 4281 // one through overload resolution (13.3)), 4282 if (!SuppressUserConversions && T2->isRecordType() && 4283 !S.RequireCompleteType(DeclLoc, T2, 0) && 4284 RefRelationship == Sema::Ref_Incompatible) { 4285 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4286 Init, T2, /*AllowRvalues=*/false, 4287 AllowExplicit)) 4288 return ICS; 4289 } 4290 } 4291 4292 // -- Otherwise, the reference shall be an lvalue reference to a 4293 // non-volatile const type (i.e., cv1 shall be const), or the reference 4294 // shall be an rvalue reference. 4295 // 4296 // We actually handle one oddity of C++ [over.ics.ref] at this 4297 // point, which is that, due to p2 (which short-circuits reference 4298 // binding by only attempting a simple conversion for non-direct 4299 // bindings) and p3's strange wording, we allow a const volatile 4300 // reference to bind to an rvalue. Hence the check for the presence 4301 // of "const" rather than checking for "const" being the only 4302 // qualifier. 4303 // This is also the point where rvalue references and lvalue inits no longer 4304 // go together. 4305 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4306 return ICS; 4307 4308 // -- If the initializer expression 4309 // 4310 // -- is an xvalue, class prvalue, array prvalue or function 4311 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4312 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4313 (InitCategory.isXValue() || 4314 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4315 (InitCategory.isLValue() && T2->isFunctionType()))) { 4316 ICS.setStandard(); 4317 ICS.Standard.First = ICK_Identity; 4318 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4319 : ObjCConversion? ICK_Compatible_Conversion 4320 : ICK_Identity; 4321 ICS.Standard.Third = ICK_Identity; 4322 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4323 ICS.Standard.setToType(0, T2); 4324 ICS.Standard.setToType(1, T1); 4325 ICS.Standard.setToType(2, T1); 4326 ICS.Standard.ReferenceBinding = true; 4327 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4328 // binding unless we're binding to a class prvalue. 4329 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4330 // allow the use of rvalue references in C++98/03 for the benefit of 4331 // standard library implementors; therefore, we need the xvalue check here. 4332 ICS.Standard.DirectBinding = 4333 S.getLangOpts().CPlusPlus11 || 4334 (InitCategory.isPRValue() && !T2->isRecordType()); 4335 ICS.Standard.IsLvalueReference = !isRValRef; 4336 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4337 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4338 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4339 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4340 ICS.Standard.CopyConstructor = 0; 4341 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4342 return ICS; 4343 } 4344 4345 // -- has a class type (i.e., T2 is a class type), where T1 is not 4346 // reference-related to T2, and can be implicitly converted to 4347 // an xvalue, class prvalue, or function lvalue of type 4348 // "cv3 T3", where "cv1 T1" is reference-compatible with 4349 // "cv3 T3", 4350 // 4351 // then the reference is bound to the value of the initializer 4352 // expression in the first case and to the result of the conversion 4353 // in the second case (or, in either case, to an appropriate base 4354 // class subobject). 4355 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4356 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4357 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4358 Init, T2, /*AllowRvalues=*/true, 4359 AllowExplicit)) { 4360 // In the second case, if the reference is an rvalue reference 4361 // and the second standard conversion sequence of the 4362 // user-defined conversion sequence includes an lvalue-to-rvalue 4363 // conversion, the program is ill-formed. 4364 if (ICS.isUserDefined() && isRValRef && 4365 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4366 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4367 4368 return ICS; 4369 } 4370 4371 // -- Otherwise, a temporary of type "cv1 T1" is created and 4372 // initialized from the initializer expression using the 4373 // rules for a non-reference copy initialization (8.5). The 4374 // reference is then bound to the temporary. If T1 is 4375 // reference-related to T2, cv1 must be the same 4376 // cv-qualification as, or greater cv-qualification than, 4377 // cv2; otherwise, the program is ill-formed. 4378 if (RefRelationship == Sema::Ref_Related) { 4379 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4380 // we would be reference-compatible or reference-compatible with 4381 // added qualification. But that wasn't the case, so the reference 4382 // initialization fails. 4383 // 4384 // Note that we only want to check address spaces and cvr-qualifiers here. 4385 // ObjC GC and lifetime qualifiers aren't important. 4386 Qualifiers T1Quals = T1.getQualifiers(); 4387 Qualifiers T2Quals = T2.getQualifiers(); 4388 T1Quals.removeObjCGCAttr(); 4389 T1Quals.removeObjCLifetime(); 4390 T2Quals.removeObjCGCAttr(); 4391 T2Quals.removeObjCLifetime(); 4392 if (!T1Quals.compatiblyIncludes(T2Quals)) 4393 return ICS; 4394 } 4395 4396 // If at least one of the types is a class type, the types are not 4397 // related, and we aren't allowed any user conversions, the 4398 // reference binding fails. This case is important for breaking 4399 // recursion, since TryImplicitConversion below will attempt to 4400 // create a temporary through the use of a copy constructor. 4401 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4402 (T1->isRecordType() || T2->isRecordType())) 4403 return ICS; 4404 4405 // If T1 is reference-related to T2 and the reference is an rvalue 4406 // reference, the initializer expression shall not be an lvalue. 4407 if (RefRelationship >= Sema::Ref_Related && 4408 isRValRef && Init->Classify(S.Context).isLValue()) 4409 return ICS; 4410 4411 // C++ [over.ics.ref]p2: 4412 // When a parameter of reference type is not bound directly to 4413 // an argument expression, the conversion sequence is the one 4414 // required to convert the argument expression to the 4415 // underlying type of the reference according to 4416 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4417 // to copy-initializing a temporary of the underlying type with 4418 // the argument expression. Any difference in top-level 4419 // cv-qualification is subsumed by the initialization itself 4420 // and does not constitute a conversion. 4421 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4422 /*AllowExplicit=*/false, 4423 /*InOverloadResolution=*/false, 4424 /*CStyle=*/false, 4425 /*AllowObjCWritebackConversion=*/false, 4426 /*AllowObjCConversionOnExplicit=*/false); 4427 4428 // Of course, that's still a reference binding. 4429 if (ICS.isStandard()) { 4430 ICS.Standard.ReferenceBinding = true; 4431 ICS.Standard.IsLvalueReference = !isRValRef; 4432 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4433 ICS.Standard.BindsToRvalue = true; 4434 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4435 ICS.Standard.ObjCLifetimeConversionBinding = false; 4436 } else if (ICS.isUserDefined()) { 4437 // Don't allow rvalue references to bind to lvalues. 4438 if (DeclType->isRValueReferenceType()) { 4439 if (const ReferenceType *RefType = 4440 ICS.UserDefined.ConversionFunction->getReturnType() 4441 ->getAs<LValueReferenceType>()) { 4442 if (!RefType->getPointeeType()->isFunctionType()) { 4443 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, 4444 DeclType); 4445 return ICS; 4446 } 4447 } 4448 } 4449 ICS.UserDefined.Before.setAsIdentityConversion(); 4450 ICS.UserDefined.After.ReferenceBinding = true; 4451 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4452 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType(); 4453 ICS.UserDefined.After.BindsToRvalue = true; 4454 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4455 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4456 } 4457 4458 return ICS; 4459 } 4460 4461 static ImplicitConversionSequence 4462 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4463 bool SuppressUserConversions, 4464 bool InOverloadResolution, 4465 bool AllowObjCWritebackConversion, 4466 bool AllowExplicit = false); 4467 4468 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4469 /// initializer list From. 4470 static ImplicitConversionSequence 4471 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4472 bool SuppressUserConversions, 4473 bool InOverloadResolution, 4474 bool AllowObjCWritebackConversion) { 4475 // C++11 [over.ics.list]p1: 4476 // When an argument is an initializer list, it is not an expression and 4477 // special rules apply for converting it to a parameter type. 4478 4479 ImplicitConversionSequence Result; 4480 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4481 4482 // We need a complete type for what follows. Incomplete types can never be 4483 // initialized from init lists. 4484 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4485 return Result; 4486 4487 // C++11 [over.ics.list]p2: 4488 // If the parameter type is std::initializer_list<X> or "array of X" and 4489 // all the elements can be implicitly converted to X, the implicit 4490 // conversion sequence is the worst conversion necessary to convert an 4491 // element of the list to X. 4492 bool toStdInitializerList = false; 4493 QualType X; 4494 if (ToType->isArrayType()) 4495 X = S.Context.getAsArrayType(ToType)->getElementType(); 4496 else 4497 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4498 if (!X.isNull()) { 4499 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4500 Expr *Init = From->getInit(i); 4501 ImplicitConversionSequence ICS = 4502 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4503 InOverloadResolution, 4504 AllowObjCWritebackConversion); 4505 // If a single element isn't convertible, fail. 4506 if (ICS.isBad()) { 4507 Result = ICS; 4508 break; 4509 } 4510 // Otherwise, look for the worst conversion. 4511 if (Result.isBad() || 4512 CompareImplicitConversionSequences(S, ICS, Result) == 4513 ImplicitConversionSequence::Worse) 4514 Result = ICS; 4515 } 4516 4517 // For an empty list, we won't have computed any conversion sequence. 4518 // Introduce the identity conversion sequence. 4519 if (From->getNumInits() == 0) { 4520 Result.setStandard(); 4521 Result.Standard.setAsIdentityConversion(); 4522 Result.Standard.setFromType(ToType); 4523 Result.Standard.setAllToTypes(ToType); 4524 } 4525 4526 Result.setStdInitializerListElement(toStdInitializerList); 4527 return Result; 4528 } 4529 4530 // C++11 [over.ics.list]p3: 4531 // Otherwise, if the parameter is a non-aggregate class X and overload 4532 // resolution chooses a single best constructor [...] the implicit 4533 // conversion sequence is a user-defined conversion sequence. If multiple 4534 // constructors are viable but none is better than the others, the 4535 // implicit conversion sequence is a user-defined conversion sequence. 4536 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4537 // This function can deal with initializer lists. 4538 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4539 /*AllowExplicit=*/false, 4540 InOverloadResolution, /*CStyle=*/false, 4541 AllowObjCWritebackConversion, 4542 /*AllowObjCConversionOnExplicit=*/false); 4543 } 4544 4545 // C++11 [over.ics.list]p4: 4546 // Otherwise, if the parameter has an aggregate type which can be 4547 // initialized from the initializer list [...] the implicit conversion 4548 // sequence is a user-defined conversion sequence. 4549 if (ToType->isAggregateType()) { 4550 // Type is an aggregate, argument is an init list. At this point it comes 4551 // down to checking whether the initialization works. 4552 // FIXME: Find out whether this parameter is consumed or not. 4553 InitializedEntity Entity = 4554 InitializedEntity::InitializeParameter(S.Context, ToType, 4555 /*Consumed=*/false); 4556 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) { 4557 Result.setUserDefined(); 4558 Result.UserDefined.Before.setAsIdentityConversion(); 4559 // Initializer lists don't have a type. 4560 Result.UserDefined.Before.setFromType(QualType()); 4561 Result.UserDefined.Before.setAllToTypes(QualType()); 4562 4563 Result.UserDefined.After.setAsIdentityConversion(); 4564 Result.UserDefined.After.setFromType(ToType); 4565 Result.UserDefined.After.setAllToTypes(ToType); 4566 Result.UserDefined.ConversionFunction = 0; 4567 } 4568 return Result; 4569 } 4570 4571 // C++11 [over.ics.list]p5: 4572 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4573 if (ToType->isReferenceType()) { 4574 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4575 // mention initializer lists in any way. So we go by what list- 4576 // initialization would do and try to extrapolate from that. 4577 4578 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4579 4580 // If the initializer list has a single element that is reference-related 4581 // to the parameter type, we initialize the reference from that. 4582 if (From->getNumInits() == 1) { 4583 Expr *Init = From->getInit(0); 4584 4585 QualType T2 = Init->getType(); 4586 4587 // If the initializer is the address of an overloaded function, try 4588 // to resolve the overloaded function. If all goes well, T2 is the 4589 // type of the resulting function. 4590 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4591 DeclAccessPair Found; 4592 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4593 Init, ToType, false, Found)) 4594 T2 = Fn->getType(); 4595 } 4596 4597 // Compute some basic properties of the types and the initializer. 4598 bool dummy1 = false; 4599 bool dummy2 = false; 4600 bool dummy3 = false; 4601 Sema::ReferenceCompareResult RefRelationship 4602 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4603 dummy2, dummy3); 4604 4605 if (RefRelationship >= Sema::Ref_Related) { 4606 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4607 SuppressUserConversions, 4608 /*AllowExplicit=*/false); 4609 } 4610 } 4611 4612 // Otherwise, we bind the reference to a temporary created from the 4613 // initializer list. 4614 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4615 InOverloadResolution, 4616 AllowObjCWritebackConversion); 4617 if (Result.isFailure()) 4618 return Result; 4619 assert(!Result.isEllipsis() && 4620 "Sub-initialization cannot result in ellipsis conversion."); 4621 4622 // Can we even bind to a temporary? 4623 if (ToType->isRValueReferenceType() || 4624 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4625 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4626 Result.UserDefined.After; 4627 SCS.ReferenceBinding = true; 4628 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4629 SCS.BindsToRvalue = true; 4630 SCS.BindsToFunctionLvalue = false; 4631 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4632 SCS.ObjCLifetimeConversionBinding = false; 4633 } else 4634 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4635 From, ToType); 4636 return Result; 4637 } 4638 4639 // C++11 [over.ics.list]p6: 4640 // Otherwise, if the parameter type is not a class: 4641 if (!ToType->isRecordType()) { 4642 // - if the initializer list has one element, the implicit conversion 4643 // sequence is the one required to convert the element to the 4644 // parameter type. 4645 unsigned NumInits = From->getNumInits(); 4646 if (NumInits == 1) 4647 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4648 SuppressUserConversions, 4649 InOverloadResolution, 4650 AllowObjCWritebackConversion); 4651 // - if the initializer list has no elements, the implicit conversion 4652 // sequence is the identity conversion. 4653 else if (NumInits == 0) { 4654 Result.setStandard(); 4655 Result.Standard.setAsIdentityConversion(); 4656 Result.Standard.setFromType(ToType); 4657 Result.Standard.setAllToTypes(ToType); 4658 } 4659 return Result; 4660 } 4661 4662 // C++11 [over.ics.list]p7: 4663 // In all cases other than those enumerated above, no conversion is possible 4664 return Result; 4665 } 4666 4667 /// TryCopyInitialization - Try to copy-initialize a value of type 4668 /// ToType from the expression From. Return the implicit conversion 4669 /// sequence required to pass this argument, which may be a bad 4670 /// conversion sequence (meaning that the argument cannot be passed to 4671 /// a parameter of this type). If @p SuppressUserConversions, then we 4672 /// do not permit any user-defined conversion sequences. 4673 static ImplicitConversionSequence 4674 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4675 bool SuppressUserConversions, 4676 bool InOverloadResolution, 4677 bool AllowObjCWritebackConversion, 4678 bool AllowExplicit) { 4679 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4680 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4681 InOverloadResolution,AllowObjCWritebackConversion); 4682 4683 if (ToType->isReferenceType()) 4684 return TryReferenceInit(S, From, ToType, 4685 /*FIXME:*/From->getLocStart(), 4686 SuppressUserConversions, 4687 AllowExplicit); 4688 4689 return TryImplicitConversion(S, From, ToType, 4690 SuppressUserConversions, 4691 /*AllowExplicit=*/false, 4692 InOverloadResolution, 4693 /*CStyle=*/false, 4694 AllowObjCWritebackConversion, 4695 /*AllowObjCConversionOnExplicit=*/false); 4696 } 4697 4698 static bool TryCopyInitialization(const CanQualType FromQTy, 4699 const CanQualType ToQTy, 4700 Sema &S, 4701 SourceLocation Loc, 4702 ExprValueKind FromVK) { 4703 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4704 ImplicitConversionSequence ICS = 4705 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4706 4707 return !ICS.isBad(); 4708 } 4709 4710 /// TryObjectArgumentInitialization - Try to initialize the object 4711 /// parameter of the given member function (@c Method) from the 4712 /// expression @p From. 4713 static ImplicitConversionSequence 4714 TryObjectArgumentInitialization(Sema &S, QualType FromType, 4715 Expr::Classification FromClassification, 4716 CXXMethodDecl *Method, 4717 CXXRecordDecl *ActingContext) { 4718 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4719 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4720 // const volatile object. 4721 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4722 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4723 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4724 4725 // Set up the conversion sequence as a "bad" conversion, to allow us 4726 // to exit early. 4727 ImplicitConversionSequence ICS; 4728 4729 // We need to have an object of class type. 4730 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4731 FromType = PT->getPointeeType(); 4732 4733 // When we had a pointer, it's implicitly dereferenced, so we 4734 // better have an lvalue. 4735 assert(FromClassification.isLValue()); 4736 } 4737 4738 assert(FromType->isRecordType()); 4739 4740 // C++0x [over.match.funcs]p4: 4741 // For non-static member functions, the type of the implicit object 4742 // parameter is 4743 // 4744 // - "lvalue reference to cv X" for functions declared without a 4745 // ref-qualifier or with the & ref-qualifier 4746 // - "rvalue reference to cv X" for functions declared with the && 4747 // ref-qualifier 4748 // 4749 // where X is the class of which the function is a member and cv is the 4750 // cv-qualification on the member function declaration. 4751 // 4752 // However, when finding an implicit conversion sequence for the argument, we 4753 // are not allowed to create temporaries or perform user-defined conversions 4754 // (C++ [over.match.funcs]p5). We perform a simplified version of 4755 // reference binding here, that allows class rvalues to bind to 4756 // non-constant references. 4757 4758 // First check the qualifiers. 4759 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4760 if (ImplicitParamType.getCVRQualifiers() 4761 != FromTypeCanon.getLocalCVRQualifiers() && 4762 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4763 ICS.setBad(BadConversionSequence::bad_qualifiers, 4764 FromType, ImplicitParamType); 4765 return ICS; 4766 } 4767 4768 // Check that we have either the same type or a derived type. It 4769 // affects the conversion rank. 4770 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4771 ImplicitConversionKind SecondKind; 4772 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4773 SecondKind = ICK_Identity; 4774 } else if (S.IsDerivedFrom(FromType, ClassType)) 4775 SecondKind = ICK_Derived_To_Base; 4776 else { 4777 ICS.setBad(BadConversionSequence::unrelated_class, 4778 FromType, ImplicitParamType); 4779 return ICS; 4780 } 4781 4782 // Check the ref-qualifier. 4783 switch (Method->getRefQualifier()) { 4784 case RQ_None: 4785 // Do nothing; we don't care about lvalueness or rvalueness. 4786 break; 4787 4788 case RQ_LValue: 4789 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4790 // non-const lvalue reference cannot bind to an rvalue 4791 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4792 ImplicitParamType); 4793 return ICS; 4794 } 4795 break; 4796 4797 case RQ_RValue: 4798 if (!FromClassification.isRValue()) { 4799 // rvalue reference cannot bind to an lvalue 4800 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4801 ImplicitParamType); 4802 return ICS; 4803 } 4804 break; 4805 } 4806 4807 // Success. Mark this as a reference binding. 4808 ICS.setStandard(); 4809 ICS.Standard.setAsIdentityConversion(); 4810 ICS.Standard.Second = SecondKind; 4811 ICS.Standard.setFromType(FromType); 4812 ICS.Standard.setAllToTypes(ImplicitParamType); 4813 ICS.Standard.ReferenceBinding = true; 4814 ICS.Standard.DirectBinding = true; 4815 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4816 ICS.Standard.BindsToFunctionLvalue = false; 4817 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4818 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4819 = (Method->getRefQualifier() == RQ_None); 4820 return ICS; 4821 } 4822 4823 /// PerformObjectArgumentInitialization - Perform initialization of 4824 /// the implicit object parameter for the given Method with the given 4825 /// expression. 4826 ExprResult 4827 Sema::PerformObjectArgumentInitialization(Expr *From, 4828 NestedNameSpecifier *Qualifier, 4829 NamedDecl *FoundDecl, 4830 CXXMethodDecl *Method) { 4831 QualType FromRecordType, DestType; 4832 QualType ImplicitParamRecordType = 4833 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4834 4835 Expr::Classification FromClassification; 4836 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4837 FromRecordType = PT->getPointeeType(); 4838 DestType = Method->getThisType(Context); 4839 FromClassification = Expr::Classification::makeSimpleLValue(); 4840 } else { 4841 FromRecordType = From->getType(); 4842 DestType = ImplicitParamRecordType; 4843 FromClassification = From->Classify(Context); 4844 } 4845 4846 // Note that we always use the true parent context when performing 4847 // the actual argument initialization. 4848 ImplicitConversionSequence ICS 4849 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification, 4850 Method, Method->getParent()); 4851 if (ICS.isBad()) { 4852 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4853 Qualifiers FromQs = FromRecordType.getQualifiers(); 4854 Qualifiers ToQs = DestType.getQualifiers(); 4855 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4856 if (CVR) { 4857 Diag(From->getLocStart(), 4858 diag::err_member_function_call_bad_cvr) 4859 << Method->getDeclName() << FromRecordType << (CVR - 1) 4860 << From->getSourceRange(); 4861 Diag(Method->getLocation(), diag::note_previous_decl) 4862 << Method->getDeclName(); 4863 return ExprError(); 4864 } 4865 } 4866 4867 return Diag(From->getLocStart(), 4868 diag::err_implicit_object_parameter_init) 4869 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4870 } 4871 4872 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4873 ExprResult FromRes = 4874 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4875 if (FromRes.isInvalid()) 4876 return ExprError(); 4877 From = FromRes.take(); 4878 } 4879 4880 if (!Context.hasSameType(From->getType(), DestType)) 4881 From = ImpCastExprToType(From, DestType, CK_NoOp, 4882 From->getValueKind()).take(); 4883 return Owned(From); 4884 } 4885 4886 /// TryContextuallyConvertToBool - Attempt to contextually convert the 4887 /// expression From to bool (C++0x [conv]p3). 4888 static ImplicitConversionSequence 4889 TryContextuallyConvertToBool(Sema &S, Expr *From) { 4890 return TryImplicitConversion(S, From, S.Context.BoolTy, 4891 /*SuppressUserConversions=*/false, 4892 /*AllowExplicit=*/true, 4893 /*InOverloadResolution=*/false, 4894 /*CStyle=*/false, 4895 /*AllowObjCWritebackConversion=*/false, 4896 /*AllowObjCConversionOnExplicit=*/false); 4897 } 4898 4899 /// PerformContextuallyConvertToBool - Perform a contextual conversion 4900 /// of the expression From to bool (C++0x [conv]p3). 4901 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4902 if (checkPlaceholderForOverload(*this, From)) 4903 return ExprError(); 4904 4905 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4906 if (!ICS.isBad()) 4907 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4908 4909 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4910 return Diag(From->getLocStart(), 4911 diag::err_typecheck_bool_condition) 4912 << From->getType() << From->getSourceRange(); 4913 return ExprError(); 4914 } 4915 4916 /// Check that the specified conversion is permitted in a converted constant 4917 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 4918 /// is acceptable. 4919 static bool CheckConvertedConstantConversions(Sema &S, 4920 StandardConversionSequence &SCS) { 4921 // Since we know that the target type is an integral or unscoped enumeration 4922 // type, most conversion kinds are impossible. All possible First and Third 4923 // conversions are fine. 4924 switch (SCS.Second) { 4925 case ICK_Identity: 4926 case ICK_Integral_Promotion: 4927 case ICK_Integral_Conversion: 4928 case ICK_Zero_Event_Conversion: 4929 return true; 4930 4931 case ICK_Boolean_Conversion: 4932 // Conversion from an integral or unscoped enumeration type to bool is 4933 // classified as ICK_Boolean_Conversion, but it's also an integral 4934 // conversion, so it's permitted in a converted constant expression. 4935 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 4936 SCS.getToType(2)->isBooleanType(); 4937 4938 case ICK_Floating_Integral: 4939 case ICK_Complex_Real: 4940 return false; 4941 4942 case ICK_Lvalue_To_Rvalue: 4943 case ICK_Array_To_Pointer: 4944 case ICK_Function_To_Pointer: 4945 case ICK_NoReturn_Adjustment: 4946 case ICK_Qualification: 4947 case ICK_Compatible_Conversion: 4948 case ICK_Vector_Conversion: 4949 case ICK_Vector_Splat: 4950 case ICK_Derived_To_Base: 4951 case ICK_Pointer_Conversion: 4952 case ICK_Pointer_Member: 4953 case ICK_Block_Pointer_Conversion: 4954 case ICK_Writeback_Conversion: 4955 case ICK_Floating_Promotion: 4956 case ICK_Complex_Promotion: 4957 case ICK_Complex_Conversion: 4958 case ICK_Floating_Conversion: 4959 case ICK_TransparentUnionConversion: 4960 llvm_unreachable("unexpected second conversion kind"); 4961 4962 case ICK_Num_Conversion_Kinds: 4963 break; 4964 } 4965 4966 llvm_unreachable("unknown conversion kind"); 4967 } 4968 4969 /// CheckConvertedConstantExpression - Check that the expression From is a 4970 /// converted constant expression of type T, perform the conversion and produce 4971 /// the converted expression, per C++11 [expr.const]p3. 4972 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 4973 llvm::APSInt &Value, 4974 CCEKind CCE) { 4975 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11"); 4976 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 4977 4978 if (checkPlaceholderForOverload(*this, From)) 4979 return ExprError(); 4980 4981 // C++11 [expr.const]p3 with proposed wording fixes: 4982 // A converted constant expression of type T is a core constant expression, 4983 // implicitly converted to a prvalue of type T, where the converted 4984 // expression is a literal constant expression and the implicit conversion 4985 // sequence contains only user-defined conversions, lvalue-to-rvalue 4986 // conversions, integral promotions, and integral conversions other than 4987 // narrowing conversions. 4988 ImplicitConversionSequence ICS = 4989 TryImplicitConversion(From, T, 4990 /*SuppressUserConversions=*/false, 4991 /*AllowExplicit=*/false, 4992 /*InOverloadResolution=*/false, 4993 /*CStyle=*/false, 4994 /*AllowObjcWritebackConversion=*/false); 4995 StandardConversionSequence *SCS = 0; 4996 switch (ICS.getKind()) { 4997 case ImplicitConversionSequence::StandardConversion: 4998 if (!CheckConvertedConstantConversions(*this, ICS.Standard)) 4999 return Diag(From->getLocStart(), 5000 diag::err_typecheck_converted_constant_expression_disallowed) 5001 << From->getType() << From->getSourceRange() << T; 5002 SCS = &ICS.Standard; 5003 break; 5004 case ImplicitConversionSequence::UserDefinedConversion: 5005 // We are converting from class type to an integral or enumeration type, so 5006 // the Before sequence must be trivial. 5007 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After)) 5008 return Diag(From->getLocStart(), 5009 diag::err_typecheck_converted_constant_expression_disallowed) 5010 << From->getType() << From->getSourceRange() << T; 5011 SCS = &ICS.UserDefined.After; 5012 break; 5013 case ImplicitConversionSequence::AmbiguousConversion: 5014 case ImplicitConversionSequence::BadConversion: 5015 if (!DiagnoseMultipleUserDefinedConversion(From, T)) 5016 return Diag(From->getLocStart(), 5017 diag::err_typecheck_converted_constant_expression) 5018 << From->getType() << From->getSourceRange() << T; 5019 return ExprError(); 5020 5021 case ImplicitConversionSequence::EllipsisConversion: 5022 llvm_unreachable("ellipsis conversion in converted constant expression"); 5023 } 5024 5025 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting); 5026 if (Result.isInvalid()) 5027 return Result; 5028 5029 // Check for a narrowing implicit conversion. 5030 APValue PreNarrowingValue; 5031 QualType PreNarrowingType; 5032 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue, 5033 PreNarrowingType)) { 5034 case NK_Variable_Narrowing: 5035 // Implicit conversion to a narrower type, and the value is not a constant 5036 // expression. We'll diagnose this in a moment. 5037 case NK_Not_Narrowing: 5038 break; 5039 5040 case NK_Constant_Narrowing: 5041 Diag(From->getLocStart(), diag::ext_cce_narrowing) 5042 << CCE << /*Constant*/1 5043 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T; 5044 break; 5045 5046 case NK_Type_Narrowing: 5047 Diag(From->getLocStart(), diag::ext_cce_narrowing) 5048 << CCE << /*Constant*/0 << From->getType() << T; 5049 break; 5050 } 5051 5052 // Check the expression is a constant expression. 5053 SmallVector<PartialDiagnosticAt, 8> Notes; 5054 Expr::EvalResult Eval; 5055 Eval.Diag = &Notes; 5056 5057 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) { 5058 // The expression can't be folded, so we can't keep it at this position in 5059 // the AST. 5060 Result = ExprError(); 5061 } else { 5062 Value = Eval.Val.getInt(); 5063 5064 if (Notes.empty()) { 5065 // It's a constant expression. 5066 return Result; 5067 } 5068 } 5069 5070 // It's not a constant expression. Produce an appropriate diagnostic. 5071 if (Notes.size() == 1 && 5072 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5073 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5074 else { 5075 Diag(From->getLocStart(), diag::err_expr_not_cce) 5076 << CCE << From->getSourceRange(); 5077 for (unsigned I = 0; I < Notes.size(); ++I) 5078 Diag(Notes[I].first, Notes[I].second); 5079 } 5080 return Result; 5081 } 5082 5083 /// dropPointerConversions - If the given standard conversion sequence 5084 /// involves any pointer conversions, remove them. This may change 5085 /// the result type of the conversion sequence. 5086 static void dropPointerConversion(StandardConversionSequence &SCS) { 5087 if (SCS.Second == ICK_Pointer_Conversion) { 5088 SCS.Second = ICK_Identity; 5089 SCS.Third = ICK_Identity; 5090 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5091 } 5092 } 5093 5094 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5095 /// convert the expression From to an Objective-C pointer type. 5096 static ImplicitConversionSequence 5097 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5098 // Do an implicit conversion to 'id'. 5099 QualType Ty = S.Context.getObjCIdType(); 5100 ImplicitConversionSequence ICS 5101 = TryImplicitConversion(S, From, Ty, 5102 // FIXME: Are these flags correct? 5103 /*SuppressUserConversions=*/false, 5104 /*AllowExplicit=*/true, 5105 /*InOverloadResolution=*/false, 5106 /*CStyle=*/false, 5107 /*AllowObjCWritebackConversion=*/false, 5108 /*AllowObjCConversionOnExplicit=*/true); 5109 5110 // Strip off any final conversions to 'id'. 5111 switch (ICS.getKind()) { 5112 case ImplicitConversionSequence::BadConversion: 5113 case ImplicitConversionSequence::AmbiguousConversion: 5114 case ImplicitConversionSequence::EllipsisConversion: 5115 break; 5116 5117 case ImplicitConversionSequence::UserDefinedConversion: 5118 dropPointerConversion(ICS.UserDefined.After); 5119 break; 5120 5121 case ImplicitConversionSequence::StandardConversion: 5122 dropPointerConversion(ICS.Standard); 5123 break; 5124 } 5125 5126 return ICS; 5127 } 5128 5129 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5130 /// conversion of the expression From to an Objective-C pointer type. 5131 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5132 if (checkPlaceholderForOverload(*this, From)) 5133 return ExprError(); 5134 5135 QualType Ty = Context.getObjCIdType(); 5136 ImplicitConversionSequence ICS = 5137 TryContextuallyConvertToObjCPointer(*this, From); 5138 if (!ICS.isBad()) 5139 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5140 return ExprError(); 5141 } 5142 5143 /// Determine whether the provided type is an integral type, or an enumeration 5144 /// type of a permitted flavor. 5145 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5146 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5147 : T->isIntegralOrUnscopedEnumerationType(); 5148 } 5149 5150 static ExprResult 5151 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5152 Sema::ContextualImplicitConverter &Converter, 5153 QualType T, UnresolvedSetImpl &ViableConversions) { 5154 5155 if (Converter.Suppress) 5156 return ExprError(); 5157 5158 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5159 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5160 CXXConversionDecl *Conv = 5161 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5162 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5163 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5164 } 5165 return SemaRef.Owned(From); 5166 } 5167 5168 static bool 5169 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5170 Sema::ContextualImplicitConverter &Converter, 5171 QualType T, bool HadMultipleCandidates, 5172 UnresolvedSetImpl &ExplicitConversions) { 5173 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5174 DeclAccessPair Found = ExplicitConversions[0]; 5175 CXXConversionDecl *Conversion = 5176 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5177 5178 // The user probably meant to invoke the given explicit 5179 // conversion; use it. 5180 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5181 std::string TypeStr; 5182 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5183 5184 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5185 << FixItHint::CreateInsertion(From->getLocStart(), 5186 "static_cast<" + TypeStr + ">(") 5187 << FixItHint::CreateInsertion( 5188 SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")"); 5189 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5190 5191 // If we aren't in a SFINAE context, build a call to the 5192 // explicit conversion function. 5193 if (SemaRef.isSFINAEContext()) 5194 return true; 5195 5196 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5197 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5198 HadMultipleCandidates); 5199 if (Result.isInvalid()) 5200 return true; 5201 // Record usage of conversion in an implicit cast. 5202 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5203 CK_UserDefinedConversion, Result.get(), 0, 5204 Result.get()->getValueKind()); 5205 } 5206 return false; 5207 } 5208 5209 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5210 Sema::ContextualImplicitConverter &Converter, 5211 QualType T, bool HadMultipleCandidates, 5212 DeclAccessPair &Found) { 5213 CXXConversionDecl *Conversion = 5214 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5215 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found); 5216 5217 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5218 if (!Converter.SuppressConversion) { 5219 if (SemaRef.isSFINAEContext()) 5220 return true; 5221 5222 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5223 << From->getSourceRange(); 5224 } 5225 5226 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5227 HadMultipleCandidates); 5228 if (Result.isInvalid()) 5229 return true; 5230 // Record usage of conversion in an implicit cast. 5231 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5232 CK_UserDefinedConversion, Result.get(), 0, 5233 Result.get()->getValueKind()); 5234 return false; 5235 } 5236 5237 static ExprResult finishContextualImplicitConversion( 5238 Sema &SemaRef, SourceLocation Loc, Expr *From, 5239 Sema::ContextualImplicitConverter &Converter) { 5240 if (!Converter.match(From->getType()) && !Converter.Suppress) 5241 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5242 << From->getSourceRange(); 5243 5244 return SemaRef.DefaultLvalueConversion(From); 5245 } 5246 5247 static void 5248 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5249 UnresolvedSetImpl &ViableConversions, 5250 OverloadCandidateSet &CandidateSet) { 5251 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5252 DeclAccessPair FoundDecl = ViableConversions[I]; 5253 NamedDecl *D = FoundDecl.getDecl(); 5254 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5255 if (isa<UsingShadowDecl>(D)) 5256 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5257 5258 CXXConversionDecl *Conv; 5259 FunctionTemplateDecl *ConvTemplate; 5260 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5261 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5262 else 5263 Conv = cast<CXXConversionDecl>(D); 5264 5265 if (ConvTemplate) 5266 SemaRef.AddTemplateConversionCandidate( 5267 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5268 /*AllowObjCConversionOnExplicit=*/false); 5269 else 5270 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5271 ToType, CandidateSet, 5272 /*AllowObjCConversionOnExplicit=*/false); 5273 } 5274 } 5275 5276 /// \brief Attempt to convert the given expression to a type which is accepted 5277 /// by the given converter. 5278 /// 5279 /// This routine will attempt to convert an expression of class type to a 5280 /// type accepted by the specified converter. In C++11 and before, the class 5281 /// must have a single non-explicit conversion function converting to a matching 5282 /// type. In C++1y, there can be multiple such conversion functions, but only 5283 /// one target type. 5284 /// 5285 /// \param Loc The source location of the construct that requires the 5286 /// conversion. 5287 /// 5288 /// \param From The expression we're converting from. 5289 /// 5290 /// \param Converter Used to control and diagnose the conversion process. 5291 /// 5292 /// \returns The expression, converted to an integral or enumeration type if 5293 /// successful. 5294 ExprResult Sema::PerformContextualImplicitConversion( 5295 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5296 // We can't perform any more checking for type-dependent expressions. 5297 if (From->isTypeDependent()) 5298 return Owned(From); 5299 5300 // Process placeholders immediately. 5301 if (From->hasPlaceholderType()) { 5302 ExprResult result = CheckPlaceholderExpr(From); 5303 if (result.isInvalid()) 5304 return result; 5305 From = result.take(); 5306 } 5307 5308 // If the expression already has a matching type, we're golden. 5309 QualType T = From->getType(); 5310 if (Converter.match(T)) 5311 return DefaultLvalueConversion(From); 5312 5313 // FIXME: Check for missing '()' if T is a function type? 5314 5315 // We can only perform contextual implicit conversions on objects of class 5316 // type. 5317 const RecordType *RecordTy = T->getAs<RecordType>(); 5318 if (!RecordTy || !getLangOpts().CPlusPlus) { 5319 if (!Converter.Suppress) 5320 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5321 return Owned(From); 5322 } 5323 5324 // We must have a complete class type. 5325 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5326 ContextualImplicitConverter &Converter; 5327 Expr *From; 5328 5329 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5330 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {} 5331 5332 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5333 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5334 } 5335 } IncompleteDiagnoser(Converter, From); 5336 5337 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5338 return Owned(From); 5339 5340 // Look for a conversion to an integral or enumeration type. 5341 UnresolvedSet<4> 5342 ViableConversions; // These are *potentially* viable in C++1y. 5343 UnresolvedSet<4> ExplicitConversions; 5344 std::pair<CXXRecordDecl::conversion_iterator, 5345 CXXRecordDecl::conversion_iterator> Conversions = 5346 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5347 5348 bool HadMultipleCandidates = 5349 (std::distance(Conversions.first, Conversions.second) > 1); 5350 5351 // To check that there is only one target type, in C++1y: 5352 QualType ToType; 5353 bool HasUniqueTargetType = true; 5354 5355 // Collect explicit or viable (potentially in C++1y) conversions. 5356 for (CXXRecordDecl::conversion_iterator I = Conversions.first, 5357 E = Conversions.second; 5358 I != E; ++I) { 5359 NamedDecl *D = (*I)->getUnderlyingDecl(); 5360 CXXConversionDecl *Conversion; 5361 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5362 if (ConvTemplate) { 5363 if (getLangOpts().CPlusPlus1y) 5364 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5365 else 5366 continue; // C++11 does not consider conversion operator templates(?). 5367 } else 5368 Conversion = cast<CXXConversionDecl>(D); 5369 5370 assert((!ConvTemplate || getLangOpts().CPlusPlus1y) && 5371 "Conversion operator templates are considered potentially " 5372 "viable in C++1y"); 5373 5374 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5375 if (Converter.match(CurToType) || ConvTemplate) { 5376 5377 if (Conversion->isExplicit()) { 5378 // FIXME: For C++1y, do we need this restriction? 5379 // cf. diagnoseNoViableConversion() 5380 if (!ConvTemplate) 5381 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5382 } else { 5383 if (!ConvTemplate && getLangOpts().CPlusPlus1y) { 5384 if (ToType.isNull()) 5385 ToType = CurToType.getUnqualifiedType(); 5386 else if (HasUniqueTargetType && 5387 (CurToType.getUnqualifiedType() != ToType)) 5388 HasUniqueTargetType = false; 5389 } 5390 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5391 } 5392 } 5393 } 5394 5395 if (getLangOpts().CPlusPlus1y) { 5396 // C++1y [conv]p6: 5397 // ... An expression e of class type E appearing in such a context 5398 // is said to be contextually implicitly converted to a specified 5399 // type T and is well-formed if and only if e can be implicitly 5400 // converted to a type T that is determined as follows: E is searched 5401 // for conversion functions whose return type is cv T or reference to 5402 // cv T such that T is allowed by the context. There shall be 5403 // exactly one such T. 5404 5405 // If no unique T is found: 5406 if (ToType.isNull()) { 5407 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5408 HadMultipleCandidates, 5409 ExplicitConversions)) 5410 return ExprError(); 5411 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5412 } 5413 5414 // If more than one unique Ts are found: 5415 if (!HasUniqueTargetType) 5416 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5417 ViableConversions); 5418 5419 // If one unique T is found: 5420 // First, build a candidate set from the previously recorded 5421 // potentially viable conversions. 5422 OverloadCandidateSet CandidateSet(Loc); 5423 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5424 CandidateSet); 5425 5426 // Then, perform overload resolution over the candidate set. 5427 OverloadCandidateSet::iterator Best; 5428 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5429 case OR_Success: { 5430 // Apply this conversion. 5431 DeclAccessPair Found = 5432 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5433 if (recordConversion(*this, Loc, From, Converter, T, 5434 HadMultipleCandidates, Found)) 5435 return ExprError(); 5436 break; 5437 } 5438 case OR_Ambiguous: 5439 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5440 ViableConversions); 5441 case OR_No_Viable_Function: 5442 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5443 HadMultipleCandidates, 5444 ExplicitConversions)) 5445 return ExprError(); 5446 // fall through 'OR_Deleted' case. 5447 case OR_Deleted: 5448 // We'll complain below about a non-integral condition type. 5449 break; 5450 } 5451 } else { 5452 switch (ViableConversions.size()) { 5453 case 0: { 5454 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5455 HadMultipleCandidates, 5456 ExplicitConversions)) 5457 return ExprError(); 5458 5459 // We'll complain below about a non-integral condition type. 5460 break; 5461 } 5462 case 1: { 5463 // Apply this conversion. 5464 DeclAccessPair Found = ViableConversions[0]; 5465 if (recordConversion(*this, Loc, From, Converter, T, 5466 HadMultipleCandidates, Found)) 5467 return ExprError(); 5468 break; 5469 } 5470 default: 5471 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5472 ViableConversions); 5473 } 5474 } 5475 5476 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5477 } 5478 5479 /// AddOverloadCandidate - Adds the given function to the set of 5480 /// candidate functions, using the given function call arguments. If 5481 /// @p SuppressUserConversions, then don't allow user-defined 5482 /// conversions via constructors or conversion operators. 5483 /// 5484 /// \param PartialOverloading true if we are performing "partial" overloading 5485 /// based on an incomplete set of function arguments. This feature is used by 5486 /// code completion. 5487 void 5488 Sema::AddOverloadCandidate(FunctionDecl *Function, 5489 DeclAccessPair FoundDecl, 5490 ArrayRef<Expr *> Args, 5491 OverloadCandidateSet &CandidateSet, 5492 bool SuppressUserConversions, 5493 bool PartialOverloading, 5494 bool AllowExplicit) { 5495 const FunctionProtoType *Proto 5496 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5497 assert(Proto && "Functions without a prototype cannot be overloaded"); 5498 assert(!Function->getDescribedFunctionTemplate() && 5499 "Use AddTemplateOverloadCandidate for function templates"); 5500 5501 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5502 if (!isa<CXXConstructorDecl>(Method)) { 5503 // If we get here, it's because we're calling a member function 5504 // that is named without a member access expression (e.g., 5505 // "this->f") that was either written explicitly or created 5506 // implicitly. This can happen with a qualified call to a member 5507 // function, e.g., X::f(). We use an empty type for the implied 5508 // object argument (C++ [over.call.func]p3), and the acting context 5509 // is irrelevant. 5510 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5511 QualType(), Expr::Classification::makeSimpleLValue(), 5512 Args, CandidateSet, SuppressUserConversions); 5513 return; 5514 } 5515 // We treat a constructor like a non-member function, since its object 5516 // argument doesn't participate in overload resolution. 5517 } 5518 5519 if (!CandidateSet.isNewCandidate(Function)) 5520 return; 5521 5522 // C++11 [class.copy]p11: [DR1402] 5523 // A defaulted move constructor that is defined as deleted is ignored by 5524 // overload resolution. 5525 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5526 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5527 Constructor->isMoveConstructor()) 5528 return; 5529 5530 // Overload resolution is always an unevaluated context. 5531 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5532 5533 if (Constructor) { 5534 // C++ [class.copy]p3: 5535 // A member function template is never instantiated to perform the copy 5536 // of a class object to an object of its class type. 5537 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5538 if (Args.size() == 1 && 5539 Constructor->isSpecializationCopyingObject() && 5540 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5541 IsDerivedFrom(Args[0]->getType(), ClassType))) 5542 return; 5543 } 5544 5545 // Add this candidate 5546 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5547 Candidate.FoundDecl = FoundDecl; 5548 Candidate.Function = Function; 5549 Candidate.Viable = true; 5550 Candidate.IsSurrogate = false; 5551 Candidate.IgnoreObjectArgument = false; 5552 Candidate.ExplicitCallArguments = Args.size(); 5553 5554 unsigned NumParams = Proto->getNumParams(); 5555 5556 // (C++ 13.3.2p2): A candidate function having fewer than m 5557 // parameters is viable only if it has an ellipsis in its parameter 5558 // list (8.3.5). 5559 if ((Args.size() + (PartialOverloading && Args.size())) > NumParams && 5560 !Proto->isVariadic()) { 5561 Candidate.Viable = false; 5562 Candidate.FailureKind = ovl_fail_too_many_arguments; 5563 return; 5564 } 5565 5566 // (C++ 13.3.2p2): A candidate function having more than m parameters 5567 // is viable only if the (m+1)st parameter has a default argument 5568 // (8.3.6). For the purposes of overload resolution, the 5569 // parameter list is truncated on the right, so that there are 5570 // exactly m parameters. 5571 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5572 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5573 // Not enough arguments. 5574 Candidate.Viable = false; 5575 Candidate.FailureKind = ovl_fail_too_few_arguments; 5576 return; 5577 } 5578 5579 // (CUDA B.1): Check for invalid calls between targets. 5580 if (getLangOpts().CUDA) 5581 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5582 if (CheckCUDATarget(Caller, Function)) { 5583 Candidate.Viable = false; 5584 Candidate.FailureKind = ovl_fail_bad_target; 5585 return; 5586 } 5587 5588 // Determine the implicit conversion sequences for each of the 5589 // arguments. 5590 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5591 if (ArgIdx < NumParams) { 5592 // (C++ 13.3.2p3): for F to be a viable function, there shall 5593 // exist for each argument an implicit conversion sequence 5594 // (13.3.3.1) that converts that argument to the corresponding 5595 // parameter of F. 5596 QualType ParamType = Proto->getParamType(ArgIdx); 5597 Candidate.Conversions[ArgIdx] 5598 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5599 SuppressUserConversions, 5600 /*InOverloadResolution=*/true, 5601 /*AllowObjCWritebackConversion=*/ 5602 getLangOpts().ObjCAutoRefCount, 5603 AllowExplicit); 5604 if (Candidate.Conversions[ArgIdx].isBad()) { 5605 Candidate.Viable = false; 5606 Candidate.FailureKind = ovl_fail_bad_conversion; 5607 return; 5608 } 5609 } else { 5610 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5611 // argument for which there is no corresponding parameter is 5612 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5613 Candidate.Conversions[ArgIdx].setEllipsis(); 5614 } 5615 } 5616 5617 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5618 Candidate.Viable = false; 5619 Candidate.FailureKind = ovl_fail_enable_if; 5620 Candidate.DeductionFailure.Data = FailedAttr; 5621 return; 5622 } 5623 } 5624 5625 static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); } 5626 5627 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 5628 bool MissingImplicitThis) { 5629 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but 5630 // we need to find the first failing one. 5631 if (!Function->hasAttrs()) 5632 return 0; 5633 AttrVec Attrs = Function->getAttrs(); 5634 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(), 5635 IsNotEnableIfAttr); 5636 if (Attrs.begin() == E) 5637 return 0; 5638 std::reverse(Attrs.begin(), E); 5639 5640 SFINAETrap Trap(*this); 5641 5642 // Convert the arguments. 5643 SmallVector<Expr *, 16> ConvertedArgs; 5644 bool InitializationFailed = false; 5645 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 5646 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 5647 !cast<CXXMethodDecl>(Function)->isStatic() && 5648 !isa<CXXConstructorDecl>(Function)) { 5649 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 5650 ExprResult R = 5651 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 5652 Method, Method); 5653 if (R.isInvalid()) { 5654 InitializationFailed = true; 5655 break; 5656 } 5657 ConvertedArgs.push_back(R.take()); 5658 } else { 5659 ExprResult R = 5660 PerformCopyInitialization(InitializedEntity::InitializeParameter( 5661 Context, 5662 Function->getParamDecl(i)), 5663 SourceLocation(), 5664 Args[i]); 5665 if (R.isInvalid()) { 5666 InitializationFailed = true; 5667 break; 5668 } 5669 ConvertedArgs.push_back(R.take()); 5670 } 5671 } 5672 5673 if (InitializationFailed || Trap.hasErrorOccurred()) 5674 return cast<EnableIfAttr>(Attrs[0]); 5675 5676 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) { 5677 APValue Result; 5678 EnableIfAttr *EIA = cast<EnableIfAttr>(*I); 5679 if (!EIA->getCond()->EvaluateWithSubstitution( 5680 Result, Context, Function, 5681 llvm::ArrayRef<const Expr*>(ConvertedArgs.data(), 5682 ConvertedArgs.size())) || 5683 !Result.isInt() || !Result.getInt().getBoolValue()) { 5684 return EIA; 5685 } 5686 } 5687 return 0; 5688 } 5689 5690 /// \brief Add all of the function declarations in the given function set to 5691 /// the overload candidate set. 5692 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5693 ArrayRef<Expr *> Args, 5694 OverloadCandidateSet& CandidateSet, 5695 bool SuppressUserConversions, 5696 TemplateArgumentListInfo *ExplicitTemplateArgs) { 5697 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 5698 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 5699 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5700 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 5701 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 5702 cast<CXXMethodDecl>(FD)->getParent(), 5703 Args[0]->getType(), Args[0]->Classify(Context), 5704 Args.slice(1), CandidateSet, 5705 SuppressUserConversions); 5706 else 5707 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 5708 SuppressUserConversions); 5709 } else { 5710 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 5711 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 5712 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 5713 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 5714 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 5715 ExplicitTemplateArgs, 5716 Args[0]->getType(), 5717 Args[0]->Classify(Context), Args.slice(1), 5718 CandidateSet, SuppressUserConversions); 5719 else 5720 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 5721 ExplicitTemplateArgs, Args, 5722 CandidateSet, SuppressUserConversions); 5723 } 5724 } 5725 } 5726 5727 /// AddMethodCandidate - Adds a named decl (which is some kind of 5728 /// method) as a method candidate to the given overload set. 5729 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 5730 QualType ObjectType, 5731 Expr::Classification ObjectClassification, 5732 ArrayRef<Expr *> Args, 5733 OverloadCandidateSet& CandidateSet, 5734 bool SuppressUserConversions) { 5735 NamedDecl *Decl = FoundDecl.getDecl(); 5736 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 5737 5738 if (isa<UsingShadowDecl>(Decl)) 5739 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 5740 5741 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 5742 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 5743 "Expected a member function template"); 5744 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 5745 /*ExplicitArgs*/ 0, 5746 ObjectType, ObjectClassification, 5747 Args, CandidateSet, 5748 SuppressUserConversions); 5749 } else { 5750 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 5751 ObjectType, ObjectClassification, 5752 Args, 5753 CandidateSet, SuppressUserConversions); 5754 } 5755 } 5756 5757 /// AddMethodCandidate - Adds the given C++ member function to the set 5758 /// of candidate functions, using the given function call arguments 5759 /// and the object argument (@c Object). For example, in a call 5760 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 5761 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 5762 /// allow user-defined conversions via constructors or conversion 5763 /// operators. 5764 void 5765 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 5766 CXXRecordDecl *ActingContext, QualType ObjectType, 5767 Expr::Classification ObjectClassification, 5768 ArrayRef<Expr *> Args, 5769 OverloadCandidateSet &CandidateSet, 5770 bool SuppressUserConversions) { 5771 const FunctionProtoType *Proto 5772 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 5773 assert(Proto && "Methods without a prototype cannot be overloaded"); 5774 assert(!isa<CXXConstructorDecl>(Method) && 5775 "Use AddOverloadCandidate for constructors"); 5776 5777 if (!CandidateSet.isNewCandidate(Method)) 5778 return; 5779 5780 // C++11 [class.copy]p23: [DR1402] 5781 // A defaulted move assignment operator that is defined as deleted is 5782 // ignored by overload resolution. 5783 if (Method->isDefaulted() && Method->isDeleted() && 5784 Method->isMoveAssignmentOperator()) 5785 return; 5786 5787 // Overload resolution is always an unevaluated context. 5788 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5789 5790 // Add this candidate 5791 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 5792 Candidate.FoundDecl = FoundDecl; 5793 Candidate.Function = Method; 5794 Candidate.IsSurrogate = false; 5795 Candidate.IgnoreObjectArgument = false; 5796 Candidate.ExplicitCallArguments = Args.size(); 5797 5798 unsigned NumParams = Proto->getNumParams(); 5799 5800 // (C++ 13.3.2p2): A candidate function having fewer than m 5801 // parameters is viable only if it has an ellipsis in its parameter 5802 // list (8.3.5). 5803 if (Args.size() > NumParams && !Proto->isVariadic()) { 5804 Candidate.Viable = false; 5805 Candidate.FailureKind = ovl_fail_too_many_arguments; 5806 return; 5807 } 5808 5809 // (C++ 13.3.2p2): A candidate function having more than m parameters 5810 // is viable only if the (m+1)st parameter has a default argument 5811 // (8.3.6). For the purposes of overload resolution, the 5812 // parameter list is truncated on the right, so that there are 5813 // exactly m parameters. 5814 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 5815 if (Args.size() < MinRequiredArgs) { 5816 // Not enough arguments. 5817 Candidate.Viable = false; 5818 Candidate.FailureKind = ovl_fail_too_few_arguments; 5819 return; 5820 } 5821 5822 Candidate.Viable = true; 5823 5824 if (Method->isStatic() || ObjectType.isNull()) 5825 // The implicit object argument is ignored. 5826 Candidate.IgnoreObjectArgument = true; 5827 else { 5828 // Determine the implicit conversion sequence for the object 5829 // parameter. 5830 Candidate.Conversions[0] 5831 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 5832 Method, ActingContext); 5833 if (Candidate.Conversions[0].isBad()) { 5834 Candidate.Viable = false; 5835 Candidate.FailureKind = ovl_fail_bad_conversion; 5836 return; 5837 } 5838 } 5839 5840 // Determine the implicit conversion sequences for each of the 5841 // arguments. 5842 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5843 if (ArgIdx < NumParams) { 5844 // (C++ 13.3.2p3): for F to be a viable function, there shall 5845 // exist for each argument an implicit conversion sequence 5846 // (13.3.3.1) that converts that argument to the corresponding 5847 // parameter of F. 5848 QualType ParamType = Proto->getParamType(ArgIdx); 5849 Candidate.Conversions[ArgIdx + 1] 5850 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5851 SuppressUserConversions, 5852 /*InOverloadResolution=*/true, 5853 /*AllowObjCWritebackConversion=*/ 5854 getLangOpts().ObjCAutoRefCount); 5855 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 5856 Candidate.Viable = false; 5857 Candidate.FailureKind = ovl_fail_bad_conversion; 5858 return; 5859 } 5860 } else { 5861 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5862 // argument for which there is no corresponding parameter is 5863 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 5864 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 5865 } 5866 } 5867 5868 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 5869 Candidate.Viable = false; 5870 Candidate.FailureKind = ovl_fail_enable_if; 5871 Candidate.DeductionFailure.Data = FailedAttr; 5872 return; 5873 } 5874 } 5875 5876 /// \brief Add a C++ member function template as a candidate to the candidate 5877 /// set, using template argument deduction to produce an appropriate member 5878 /// function template specialization. 5879 void 5880 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 5881 DeclAccessPair FoundDecl, 5882 CXXRecordDecl *ActingContext, 5883 TemplateArgumentListInfo *ExplicitTemplateArgs, 5884 QualType ObjectType, 5885 Expr::Classification ObjectClassification, 5886 ArrayRef<Expr *> Args, 5887 OverloadCandidateSet& CandidateSet, 5888 bool SuppressUserConversions) { 5889 if (!CandidateSet.isNewCandidate(MethodTmpl)) 5890 return; 5891 5892 // C++ [over.match.funcs]p7: 5893 // In each case where a candidate is a function template, candidate 5894 // function template specializations are generated using template argument 5895 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5896 // candidate functions in the usual way.113) A given name can refer to one 5897 // or more function templates and also to a set of overloaded non-template 5898 // functions. In such a case, the candidate functions generated from each 5899 // function template are combined with the set of non-template candidate 5900 // functions. 5901 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5902 FunctionDecl *Specialization = 0; 5903 if (TemplateDeductionResult Result 5904 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 5905 Specialization, Info)) { 5906 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5907 Candidate.FoundDecl = FoundDecl; 5908 Candidate.Function = MethodTmpl->getTemplatedDecl(); 5909 Candidate.Viable = false; 5910 Candidate.FailureKind = ovl_fail_bad_deduction; 5911 Candidate.IsSurrogate = false; 5912 Candidate.IgnoreObjectArgument = false; 5913 Candidate.ExplicitCallArguments = Args.size(); 5914 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5915 Info); 5916 return; 5917 } 5918 5919 // Add the function template specialization produced by template argument 5920 // deduction as a candidate. 5921 assert(Specialization && "Missing member function template specialization?"); 5922 assert(isa<CXXMethodDecl>(Specialization) && 5923 "Specialization is not a member function?"); 5924 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 5925 ActingContext, ObjectType, ObjectClassification, Args, 5926 CandidateSet, SuppressUserConversions); 5927 } 5928 5929 /// \brief Add a C++ function template specialization as a candidate 5930 /// in the candidate set, using template argument deduction to produce 5931 /// an appropriate function template specialization. 5932 void 5933 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 5934 DeclAccessPair FoundDecl, 5935 TemplateArgumentListInfo *ExplicitTemplateArgs, 5936 ArrayRef<Expr *> Args, 5937 OverloadCandidateSet& CandidateSet, 5938 bool SuppressUserConversions) { 5939 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 5940 return; 5941 5942 // C++ [over.match.funcs]p7: 5943 // In each case where a candidate is a function template, candidate 5944 // function template specializations are generated using template argument 5945 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 5946 // candidate functions in the usual way.113) A given name can refer to one 5947 // or more function templates and also to a set of overloaded non-template 5948 // functions. In such a case, the candidate functions generated from each 5949 // function template are combined with the set of non-template candidate 5950 // functions. 5951 TemplateDeductionInfo Info(CandidateSet.getLocation()); 5952 FunctionDecl *Specialization = 0; 5953 if (TemplateDeductionResult Result 5954 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 5955 Specialization, Info)) { 5956 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 5957 Candidate.FoundDecl = FoundDecl; 5958 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 5959 Candidate.Viable = false; 5960 Candidate.FailureKind = ovl_fail_bad_deduction; 5961 Candidate.IsSurrogate = false; 5962 Candidate.IgnoreObjectArgument = false; 5963 Candidate.ExplicitCallArguments = Args.size(); 5964 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 5965 Info); 5966 return; 5967 } 5968 5969 // Add the function template specialization produced by template argument 5970 // deduction as a candidate. 5971 assert(Specialization && "Missing function template specialization?"); 5972 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 5973 SuppressUserConversions); 5974 } 5975 5976 /// Determine whether this is an allowable conversion from the result 5977 /// of an explicit conversion operator to the expected type, per C++ 5978 /// [over.match.conv]p1 and [over.match.ref]p1. 5979 /// 5980 /// \param ConvType The return type of the conversion function. 5981 /// 5982 /// \param ToType The type we are converting to. 5983 /// 5984 /// \param AllowObjCPointerConversion Allow a conversion from one 5985 /// Objective-C pointer to another. 5986 /// 5987 /// \returns true if the conversion is allowable, false otherwise. 5988 static bool isAllowableExplicitConversion(Sema &S, 5989 QualType ConvType, QualType ToType, 5990 bool AllowObjCPointerConversion) { 5991 QualType ToNonRefType = ToType.getNonReferenceType(); 5992 5993 // Easy case: the types are the same. 5994 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 5995 return true; 5996 5997 // Allow qualification conversions. 5998 bool ObjCLifetimeConversion; 5999 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6000 ObjCLifetimeConversion)) 6001 return true; 6002 6003 // If we're not allowed to consider Objective-C pointer conversions, 6004 // we're done. 6005 if (!AllowObjCPointerConversion) 6006 return false; 6007 6008 // Is this an Objective-C pointer conversion? 6009 bool IncompatibleObjC = false; 6010 QualType ConvertedType; 6011 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6012 IncompatibleObjC); 6013 } 6014 6015 /// AddConversionCandidate - Add a C++ conversion function as a 6016 /// candidate in the candidate set (C++ [over.match.conv], 6017 /// C++ [over.match.copy]). From is the expression we're converting from, 6018 /// and ToType is the type that we're eventually trying to convert to 6019 /// (which may or may not be the same type as the type that the 6020 /// conversion function produces). 6021 void 6022 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6023 DeclAccessPair FoundDecl, 6024 CXXRecordDecl *ActingContext, 6025 Expr *From, QualType ToType, 6026 OverloadCandidateSet& CandidateSet, 6027 bool AllowObjCConversionOnExplicit) { 6028 assert(!Conversion->getDescribedFunctionTemplate() && 6029 "Conversion function templates use AddTemplateConversionCandidate"); 6030 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6031 if (!CandidateSet.isNewCandidate(Conversion)) 6032 return; 6033 6034 // If the conversion function has an undeduced return type, trigger its 6035 // deduction now. 6036 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) { 6037 if (DeduceReturnType(Conversion, From->getExprLoc())) 6038 return; 6039 ConvType = Conversion->getConversionType().getNonReferenceType(); 6040 } 6041 6042 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6043 // operator is only a candidate if its return type is the target type or 6044 // can be converted to the target type with a qualification conversion. 6045 if (Conversion->isExplicit() && 6046 !isAllowableExplicitConversion(*this, ConvType, ToType, 6047 AllowObjCConversionOnExplicit)) 6048 return; 6049 6050 // Overload resolution is always an unevaluated context. 6051 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6052 6053 // Add this candidate 6054 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6055 Candidate.FoundDecl = FoundDecl; 6056 Candidate.Function = Conversion; 6057 Candidate.IsSurrogate = false; 6058 Candidate.IgnoreObjectArgument = false; 6059 Candidate.FinalConversion.setAsIdentityConversion(); 6060 Candidate.FinalConversion.setFromType(ConvType); 6061 Candidate.FinalConversion.setAllToTypes(ToType); 6062 Candidate.Viable = true; 6063 Candidate.ExplicitCallArguments = 1; 6064 6065 // C++ [over.match.funcs]p4: 6066 // For conversion functions, the function is considered to be a member of 6067 // the class of the implicit implied object argument for the purpose of 6068 // defining the type of the implicit object parameter. 6069 // 6070 // Determine the implicit conversion sequence for the implicit 6071 // object parameter. 6072 QualType ImplicitParamType = From->getType(); 6073 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6074 ImplicitParamType = FromPtrType->getPointeeType(); 6075 CXXRecordDecl *ConversionContext 6076 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6077 6078 Candidate.Conversions[0] 6079 = TryObjectArgumentInitialization(*this, From->getType(), 6080 From->Classify(Context), 6081 Conversion, ConversionContext); 6082 6083 if (Candidate.Conversions[0].isBad()) { 6084 Candidate.Viable = false; 6085 Candidate.FailureKind = ovl_fail_bad_conversion; 6086 return; 6087 } 6088 6089 // We won't go through a user-defined type conversion function to convert a 6090 // derived to base as such conversions are given Conversion Rank. They only 6091 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6092 QualType FromCanon 6093 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6094 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6095 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 6096 Candidate.Viable = false; 6097 Candidate.FailureKind = ovl_fail_trivial_conversion; 6098 return; 6099 } 6100 6101 // To determine what the conversion from the result of calling the 6102 // conversion function to the type we're eventually trying to 6103 // convert to (ToType), we need to synthesize a call to the 6104 // conversion function and attempt copy initialization from it. This 6105 // makes sure that we get the right semantics with respect to 6106 // lvalues/rvalues and the type. Fortunately, we can allocate this 6107 // call on the stack and we don't need its arguments to be 6108 // well-formed. 6109 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6110 VK_LValue, From->getLocStart()); 6111 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6112 Context.getPointerType(Conversion->getType()), 6113 CK_FunctionToPointerDecay, 6114 &ConversionRef, VK_RValue); 6115 6116 QualType ConversionType = Conversion->getConversionType(); 6117 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 6118 Candidate.Viable = false; 6119 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6120 return; 6121 } 6122 6123 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6124 6125 // Note that it is safe to allocate CallExpr on the stack here because 6126 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6127 // allocator). 6128 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6129 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6130 From->getLocStart()); 6131 ImplicitConversionSequence ICS = 6132 TryCopyInitialization(*this, &Call, ToType, 6133 /*SuppressUserConversions=*/true, 6134 /*InOverloadResolution=*/false, 6135 /*AllowObjCWritebackConversion=*/false); 6136 6137 switch (ICS.getKind()) { 6138 case ImplicitConversionSequence::StandardConversion: 6139 Candidate.FinalConversion = ICS.Standard; 6140 6141 // C++ [over.ics.user]p3: 6142 // If the user-defined conversion is specified by a specialization of a 6143 // conversion function template, the second standard conversion sequence 6144 // shall have exact match rank. 6145 if (Conversion->getPrimaryTemplate() && 6146 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6147 Candidate.Viable = false; 6148 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6149 return; 6150 } 6151 6152 // C++0x [dcl.init.ref]p5: 6153 // In the second case, if the reference is an rvalue reference and 6154 // the second standard conversion sequence of the user-defined 6155 // conversion sequence includes an lvalue-to-rvalue conversion, the 6156 // program is ill-formed. 6157 if (ToType->isRValueReferenceType() && 6158 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6159 Candidate.Viable = false; 6160 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6161 return; 6162 } 6163 break; 6164 6165 case ImplicitConversionSequence::BadConversion: 6166 Candidate.Viable = false; 6167 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6168 return; 6169 6170 default: 6171 llvm_unreachable( 6172 "Can only end up with a standard conversion sequence or failure"); 6173 } 6174 6175 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) { 6176 Candidate.Viable = false; 6177 Candidate.FailureKind = ovl_fail_enable_if; 6178 Candidate.DeductionFailure.Data = FailedAttr; 6179 return; 6180 } 6181 } 6182 6183 /// \brief Adds a conversion function template specialization 6184 /// candidate to the overload set, using template argument deduction 6185 /// to deduce the template arguments of the conversion function 6186 /// template from the type that we are converting to (C++ 6187 /// [temp.deduct.conv]). 6188 void 6189 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6190 DeclAccessPair FoundDecl, 6191 CXXRecordDecl *ActingDC, 6192 Expr *From, QualType ToType, 6193 OverloadCandidateSet &CandidateSet, 6194 bool AllowObjCConversionOnExplicit) { 6195 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6196 "Only conversion function templates permitted here"); 6197 6198 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6199 return; 6200 6201 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6202 CXXConversionDecl *Specialization = 0; 6203 if (TemplateDeductionResult Result 6204 = DeduceTemplateArguments(FunctionTemplate, ToType, 6205 Specialization, Info)) { 6206 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6207 Candidate.FoundDecl = FoundDecl; 6208 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6209 Candidate.Viable = false; 6210 Candidate.FailureKind = ovl_fail_bad_deduction; 6211 Candidate.IsSurrogate = false; 6212 Candidate.IgnoreObjectArgument = false; 6213 Candidate.ExplicitCallArguments = 1; 6214 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6215 Info); 6216 return; 6217 } 6218 6219 // Add the conversion function template specialization produced by 6220 // template argument deduction as a candidate. 6221 assert(Specialization && "Missing function template specialization?"); 6222 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6223 CandidateSet, AllowObjCConversionOnExplicit); 6224 } 6225 6226 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6227 /// converts the given @c Object to a function pointer via the 6228 /// conversion function @c Conversion, and then attempts to call it 6229 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6230 /// the type of function that we'll eventually be calling. 6231 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6232 DeclAccessPair FoundDecl, 6233 CXXRecordDecl *ActingContext, 6234 const FunctionProtoType *Proto, 6235 Expr *Object, 6236 ArrayRef<Expr *> Args, 6237 OverloadCandidateSet& CandidateSet) { 6238 if (!CandidateSet.isNewCandidate(Conversion)) 6239 return; 6240 6241 // Overload resolution is always an unevaluated context. 6242 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6243 6244 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6245 Candidate.FoundDecl = FoundDecl; 6246 Candidate.Function = 0; 6247 Candidate.Surrogate = Conversion; 6248 Candidate.Viable = true; 6249 Candidate.IsSurrogate = true; 6250 Candidate.IgnoreObjectArgument = false; 6251 Candidate.ExplicitCallArguments = Args.size(); 6252 6253 // Determine the implicit conversion sequence for the implicit 6254 // object parameter. 6255 ImplicitConversionSequence ObjectInit 6256 = TryObjectArgumentInitialization(*this, Object->getType(), 6257 Object->Classify(Context), 6258 Conversion, ActingContext); 6259 if (ObjectInit.isBad()) { 6260 Candidate.Viable = false; 6261 Candidate.FailureKind = ovl_fail_bad_conversion; 6262 Candidate.Conversions[0] = ObjectInit; 6263 return; 6264 } 6265 6266 // The first conversion is actually a user-defined conversion whose 6267 // first conversion is ObjectInit's standard conversion (which is 6268 // effectively a reference binding). Record it as such. 6269 Candidate.Conversions[0].setUserDefined(); 6270 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6271 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6272 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6273 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6274 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6275 Candidate.Conversions[0].UserDefined.After 6276 = Candidate.Conversions[0].UserDefined.Before; 6277 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6278 6279 // Find the 6280 unsigned NumParams = Proto->getNumParams(); 6281 6282 // (C++ 13.3.2p2): A candidate function having fewer than m 6283 // parameters is viable only if it has an ellipsis in its parameter 6284 // list (8.3.5). 6285 if (Args.size() > NumParams && !Proto->isVariadic()) { 6286 Candidate.Viable = false; 6287 Candidate.FailureKind = ovl_fail_too_many_arguments; 6288 return; 6289 } 6290 6291 // Function types don't have any default arguments, so just check if 6292 // we have enough arguments. 6293 if (Args.size() < NumParams) { 6294 // Not enough arguments. 6295 Candidate.Viable = false; 6296 Candidate.FailureKind = ovl_fail_too_few_arguments; 6297 return; 6298 } 6299 6300 // Determine the implicit conversion sequences for each of the 6301 // arguments. 6302 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6303 if (ArgIdx < NumParams) { 6304 // (C++ 13.3.2p3): for F to be a viable function, there shall 6305 // exist for each argument an implicit conversion sequence 6306 // (13.3.3.1) that converts that argument to the corresponding 6307 // parameter of F. 6308 QualType ParamType = Proto->getParamType(ArgIdx); 6309 Candidate.Conversions[ArgIdx + 1] 6310 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6311 /*SuppressUserConversions=*/false, 6312 /*InOverloadResolution=*/false, 6313 /*AllowObjCWritebackConversion=*/ 6314 getLangOpts().ObjCAutoRefCount); 6315 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6316 Candidate.Viable = false; 6317 Candidate.FailureKind = ovl_fail_bad_conversion; 6318 return; 6319 } 6320 } else { 6321 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6322 // argument for which there is no corresponding parameter is 6323 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6324 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6325 } 6326 } 6327 6328 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) { 6329 Candidate.Viable = false; 6330 Candidate.FailureKind = ovl_fail_enable_if; 6331 Candidate.DeductionFailure.Data = FailedAttr; 6332 return; 6333 } 6334 } 6335 6336 /// \brief Add overload candidates for overloaded operators that are 6337 /// member functions. 6338 /// 6339 /// Add the overloaded operator candidates that are member functions 6340 /// for the operator Op that was used in an operator expression such 6341 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6342 /// CandidateSet will store the added overload candidates. (C++ 6343 /// [over.match.oper]). 6344 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6345 SourceLocation OpLoc, 6346 ArrayRef<Expr *> Args, 6347 OverloadCandidateSet& CandidateSet, 6348 SourceRange OpRange) { 6349 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6350 6351 // C++ [over.match.oper]p3: 6352 // For a unary operator @ with an operand of a type whose 6353 // cv-unqualified version is T1, and for a binary operator @ with 6354 // a left operand of a type whose cv-unqualified version is T1 and 6355 // a right operand of a type whose cv-unqualified version is T2, 6356 // three sets of candidate functions, designated member 6357 // candidates, non-member candidates and built-in candidates, are 6358 // constructed as follows: 6359 QualType T1 = Args[0]->getType(); 6360 6361 // -- If T1 is a complete class type or a class currently being 6362 // defined, the set of member candidates is the result of the 6363 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6364 // the set of member candidates is empty. 6365 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6366 // Complete the type if it can be completed. 6367 RequireCompleteType(OpLoc, T1, 0); 6368 // If the type is neither complete nor being defined, bail out now. 6369 if (!T1Rec->getDecl()->getDefinition()) 6370 return; 6371 6372 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6373 LookupQualifiedName(Operators, T1Rec->getDecl()); 6374 Operators.suppressDiagnostics(); 6375 6376 for (LookupResult::iterator Oper = Operators.begin(), 6377 OperEnd = Operators.end(); 6378 Oper != OperEnd; 6379 ++Oper) 6380 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6381 Args[0]->Classify(Context), 6382 Args.slice(1), 6383 CandidateSet, 6384 /* SuppressUserConversions = */ false); 6385 } 6386 } 6387 6388 /// AddBuiltinCandidate - Add a candidate for a built-in 6389 /// operator. ResultTy and ParamTys are the result and parameter types 6390 /// of the built-in candidate, respectively. Args and NumArgs are the 6391 /// arguments being passed to the candidate. IsAssignmentOperator 6392 /// should be true when this built-in candidate is an assignment 6393 /// operator. NumContextualBoolArguments is the number of arguments 6394 /// (at the beginning of the argument list) that will be contextually 6395 /// converted to bool. 6396 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6397 ArrayRef<Expr *> Args, 6398 OverloadCandidateSet& CandidateSet, 6399 bool IsAssignmentOperator, 6400 unsigned NumContextualBoolArguments) { 6401 // Overload resolution is always an unevaluated context. 6402 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6403 6404 // Add this candidate 6405 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6406 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none); 6407 Candidate.Function = 0; 6408 Candidate.IsSurrogate = false; 6409 Candidate.IgnoreObjectArgument = false; 6410 Candidate.BuiltinTypes.ResultTy = ResultTy; 6411 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6412 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6413 6414 // Determine the implicit conversion sequences for each of the 6415 // arguments. 6416 Candidate.Viable = true; 6417 Candidate.ExplicitCallArguments = Args.size(); 6418 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6419 // C++ [over.match.oper]p4: 6420 // For the built-in assignment operators, conversions of the 6421 // left operand are restricted as follows: 6422 // -- no temporaries are introduced to hold the left operand, and 6423 // -- no user-defined conversions are applied to the left 6424 // operand to achieve a type match with the left-most 6425 // parameter of a built-in candidate. 6426 // 6427 // We block these conversions by turning off user-defined 6428 // conversions, since that is the only way that initialization of 6429 // a reference to a non-class type can occur from something that 6430 // is not of the same type. 6431 if (ArgIdx < NumContextualBoolArguments) { 6432 assert(ParamTys[ArgIdx] == Context.BoolTy && 6433 "Contextual conversion to bool requires bool type"); 6434 Candidate.Conversions[ArgIdx] 6435 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6436 } else { 6437 Candidate.Conversions[ArgIdx] 6438 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6439 ArgIdx == 0 && IsAssignmentOperator, 6440 /*InOverloadResolution=*/false, 6441 /*AllowObjCWritebackConversion=*/ 6442 getLangOpts().ObjCAutoRefCount); 6443 } 6444 if (Candidate.Conversions[ArgIdx].isBad()) { 6445 Candidate.Viable = false; 6446 Candidate.FailureKind = ovl_fail_bad_conversion; 6447 break; 6448 } 6449 } 6450 } 6451 6452 namespace { 6453 6454 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6455 /// candidate operator functions for built-in operators (C++ 6456 /// [over.built]). The types are separated into pointer types and 6457 /// enumeration types. 6458 class BuiltinCandidateTypeSet { 6459 /// TypeSet - A set of types. 6460 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6461 6462 /// PointerTypes - The set of pointer types that will be used in the 6463 /// built-in candidates. 6464 TypeSet PointerTypes; 6465 6466 /// MemberPointerTypes - The set of member pointer types that will be 6467 /// used in the built-in candidates. 6468 TypeSet MemberPointerTypes; 6469 6470 /// EnumerationTypes - The set of enumeration types that will be 6471 /// used in the built-in candidates. 6472 TypeSet EnumerationTypes; 6473 6474 /// \brief The set of vector types that will be used in the built-in 6475 /// candidates. 6476 TypeSet VectorTypes; 6477 6478 /// \brief A flag indicating non-record types are viable candidates 6479 bool HasNonRecordTypes; 6480 6481 /// \brief A flag indicating whether either arithmetic or enumeration types 6482 /// were present in the candidate set. 6483 bool HasArithmeticOrEnumeralTypes; 6484 6485 /// \brief A flag indicating whether the nullptr type was present in the 6486 /// candidate set. 6487 bool HasNullPtrType; 6488 6489 /// Sema - The semantic analysis instance where we are building the 6490 /// candidate type set. 6491 Sema &SemaRef; 6492 6493 /// Context - The AST context in which we will build the type sets. 6494 ASTContext &Context; 6495 6496 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6497 const Qualifiers &VisibleQuals); 6498 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6499 6500 public: 6501 /// iterator - Iterates through the types that are part of the set. 6502 typedef TypeSet::iterator iterator; 6503 6504 BuiltinCandidateTypeSet(Sema &SemaRef) 6505 : HasNonRecordTypes(false), 6506 HasArithmeticOrEnumeralTypes(false), 6507 HasNullPtrType(false), 6508 SemaRef(SemaRef), 6509 Context(SemaRef.Context) { } 6510 6511 void AddTypesConvertedFrom(QualType Ty, 6512 SourceLocation Loc, 6513 bool AllowUserConversions, 6514 bool AllowExplicitConversions, 6515 const Qualifiers &VisibleTypeConversionsQuals); 6516 6517 /// pointer_begin - First pointer type found; 6518 iterator pointer_begin() { return PointerTypes.begin(); } 6519 6520 /// pointer_end - Past the last pointer type found; 6521 iterator pointer_end() { return PointerTypes.end(); } 6522 6523 /// member_pointer_begin - First member pointer type found; 6524 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6525 6526 /// member_pointer_end - Past the last member pointer type found; 6527 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6528 6529 /// enumeration_begin - First enumeration type found; 6530 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6531 6532 /// enumeration_end - Past the last enumeration type found; 6533 iterator enumeration_end() { return EnumerationTypes.end(); } 6534 6535 iterator vector_begin() { return VectorTypes.begin(); } 6536 iterator vector_end() { return VectorTypes.end(); } 6537 6538 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6539 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6540 bool hasNullPtrType() const { return HasNullPtrType; } 6541 }; 6542 6543 } // end anonymous namespace 6544 6545 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6546 /// the set of pointer types along with any more-qualified variants of 6547 /// that type. For example, if @p Ty is "int const *", this routine 6548 /// will add "int const *", "int const volatile *", "int const 6549 /// restrict *", and "int const volatile restrict *" to the set of 6550 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6551 /// false otherwise. 6552 /// 6553 /// FIXME: what to do about extended qualifiers? 6554 bool 6555 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6556 const Qualifiers &VisibleQuals) { 6557 6558 // Insert this type. 6559 if (!PointerTypes.insert(Ty)) 6560 return false; 6561 6562 QualType PointeeTy; 6563 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6564 bool buildObjCPtr = false; 6565 if (!PointerTy) { 6566 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6567 PointeeTy = PTy->getPointeeType(); 6568 buildObjCPtr = true; 6569 } else { 6570 PointeeTy = PointerTy->getPointeeType(); 6571 } 6572 6573 // Don't add qualified variants of arrays. For one, they're not allowed 6574 // (the qualifier would sink to the element type), and for another, the 6575 // only overload situation where it matters is subscript or pointer +- int, 6576 // and those shouldn't have qualifier variants anyway. 6577 if (PointeeTy->isArrayType()) 6578 return true; 6579 6580 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6581 bool hasVolatile = VisibleQuals.hasVolatile(); 6582 bool hasRestrict = VisibleQuals.hasRestrict(); 6583 6584 // Iterate through all strict supersets of BaseCVR. 6585 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6586 if ((CVR | BaseCVR) != CVR) continue; 6587 // Skip over volatile if no volatile found anywhere in the types. 6588 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6589 6590 // Skip over restrict if no restrict found anywhere in the types, or if 6591 // the type cannot be restrict-qualified. 6592 if ((CVR & Qualifiers::Restrict) && 6593 (!hasRestrict || 6594 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6595 continue; 6596 6597 // Build qualified pointee type. 6598 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6599 6600 // Build qualified pointer type. 6601 QualType QPointerTy; 6602 if (!buildObjCPtr) 6603 QPointerTy = Context.getPointerType(QPointeeTy); 6604 else 6605 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6606 6607 // Insert qualified pointer type. 6608 PointerTypes.insert(QPointerTy); 6609 } 6610 6611 return true; 6612 } 6613 6614 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6615 /// to the set of pointer types along with any more-qualified variants of 6616 /// that type. For example, if @p Ty is "int const *", this routine 6617 /// will add "int const *", "int const volatile *", "int const 6618 /// restrict *", and "int const volatile restrict *" to the set of 6619 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6620 /// false otherwise. 6621 /// 6622 /// FIXME: what to do about extended qualifiers? 6623 bool 6624 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6625 QualType Ty) { 6626 // Insert this type. 6627 if (!MemberPointerTypes.insert(Ty)) 6628 return false; 6629 6630 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6631 assert(PointerTy && "type was not a member pointer type!"); 6632 6633 QualType PointeeTy = PointerTy->getPointeeType(); 6634 // Don't add qualified variants of arrays. For one, they're not allowed 6635 // (the qualifier would sink to the element type), and for another, the 6636 // only overload situation where it matters is subscript or pointer +- int, 6637 // and those shouldn't have qualifier variants anyway. 6638 if (PointeeTy->isArrayType()) 6639 return true; 6640 const Type *ClassTy = PointerTy->getClass(); 6641 6642 // Iterate through all strict supersets of the pointee type's CVR 6643 // qualifiers. 6644 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6645 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6646 if ((CVR | BaseCVR) != CVR) continue; 6647 6648 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6649 MemberPointerTypes.insert( 6650 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6651 } 6652 6653 return true; 6654 } 6655 6656 /// AddTypesConvertedFrom - Add each of the types to which the type @p 6657 /// Ty can be implicit converted to the given set of @p Types. We're 6658 /// primarily interested in pointer types and enumeration types. We also 6659 /// take member pointer types, for the conditional operator. 6660 /// AllowUserConversions is true if we should look at the conversion 6661 /// functions of a class type, and AllowExplicitConversions if we 6662 /// should also include the explicit conversion functions of a class 6663 /// type. 6664 void 6665 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6666 SourceLocation Loc, 6667 bool AllowUserConversions, 6668 bool AllowExplicitConversions, 6669 const Qualifiers &VisibleQuals) { 6670 // Only deal with canonical types. 6671 Ty = Context.getCanonicalType(Ty); 6672 6673 // Look through reference types; they aren't part of the type of an 6674 // expression for the purposes of conversions. 6675 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6676 Ty = RefTy->getPointeeType(); 6677 6678 // If we're dealing with an array type, decay to the pointer. 6679 if (Ty->isArrayType()) 6680 Ty = SemaRef.Context.getArrayDecayedType(Ty); 6681 6682 // Otherwise, we don't care about qualifiers on the type. 6683 Ty = Ty.getLocalUnqualifiedType(); 6684 6685 // Flag if we ever add a non-record type. 6686 const RecordType *TyRec = Ty->getAs<RecordType>(); 6687 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 6688 6689 // Flag if we encounter an arithmetic type. 6690 HasArithmeticOrEnumeralTypes = 6691 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 6692 6693 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 6694 PointerTypes.insert(Ty); 6695 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 6696 // Insert our type, and its more-qualified variants, into the set 6697 // of types. 6698 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 6699 return; 6700 } else if (Ty->isMemberPointerType()) { 6701 // Member pointers are far easier, since the pointee can't be converted. 6702 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 6703 return; 6704 } else if (Ty->isEnumeralType()) { 6705 HasArithmeticOrEnumeralTypes = true; 6706 EnumerationTypes.insert(Ty); 6707 } else if (Ty->isVectorType()) { 6708 // We treat vector types as arithmetic types in many contexts as an 6709 // extension. 6710 HasArithmeticOrEnumeralTypes = true; 6711 VectorTypes.insert(Ty); 6712 } else if (Ty->isNullPtrType()) { 6713 HasNullPtrType = true; 6714 } else if (AllowUserConversions && TyRec) { 6715 // No conversion functions in incomplete types. 6716 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 6717 return; 6718 6719 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6720 std::pair<CXXRecordDecl::conversion_iterator, 6721 CXXRecordDecl::conversion_iterator> 6722 Conversions = ClassDecl->getVisibleConversionFunctions(); 6723 for (CXXRecordDecl::conversion_iterator 6724 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6725 NamedDecl *D = I.getDecl(); 6726 if (isa<UsingShadowDecl>(D)) 6727 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6728 6729 // Skip conversion function templates; they don't tell us anything 6730 // about which builtin types we can convert to. 6731 if (isa<FunctionTemplateDecl>(D)) 6732 continue; 6733 6734 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 6735 if (AllowExplicitConversions || !Conv->isExplicit()) { 6736 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 6737 VisibleQuals); 6738 } 6739 } 6740 } 6741 } 6742 6743 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 6744 /// the volatile- and non-volatile-qualified assignment operators for the 6745 /// given type to the candidate set. 6746 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 6747 QualType T, 6748 ArrayRef<Expr *> Args, 6749 OverloadCandidateSet &CandidateSet) { 6750 QualType ParamTypes[2]; 6751 6752 // T& operator=(T&, T) 6753 ParamTypes[0] = S.Context.getLValueReferenceType(T); 6754 ParamTypes[1] = T; 6755 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6756 /*IsAssignmentOperator=*/true); 6757 6758 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 6759 // volatile T& operator=(volatile T&, T) 6760 ParamTypes[0] 6761 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 6762 ParamTypes[1] = T; 6763 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 6764 /*IsAssignmentOperator=*/true); 6765 } 6766 } 6767 6768 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 6769 /// if any, found in visible type conversion functions found in ArgExpr's type. 6770 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 6771 Qualifiers VRQuals; 6772 const RecordType *TyRec; 6773 if (const MemberPointerType *RHSMPType = 6774 ArgExpr->getType()->getAs<MemberPointerType>()) 6775 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 6776 else 6777 TyRec = ArgExpr->getType()->getAs<RecordType>(); 6778 if (!TyRec) { 6779 // Just to be safe, assume the worst case. 6780 VRQuals.addVolatile(); 6781 VRQuals.addRestrict(); 6782 return VRQuals; 6783 } 6784 6785 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 6786 if (!ClassDecl->hasDefinition()) 6787 return VRQuals; 6788 6789 std::pair<CXXRecordDecl::conversion_iterator, 6790 CXXRecordDecl::conversion_iterator> 6791 Conversions = ClassDecl->getVisibleConversionFunctions(); 6792 6793 for (CXXRecordDecl::conversion_iterator 6794 I = Conversions.first, E = Conversions.second; I != E; ++I) { 6795 NamedDecl *D = I.getDecl(); 6796 if (isa<UsingShadowDecl>(D)) 6797 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 6798 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 6799 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 6800 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 6801 CanTy = ResTypeRef->getPointeeType(); 6802 // Need to go down the pointer/mempointer chain and add qualifiers 6803 // as see them. 6804 bool done = false; 6805 while (!done) { 6806 if (CanTy.isRestrictQualified()) 6807 VRQuals.addRestrict(); 6808 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 6809 CanTy = ResTypePtr->getPointeeType(); 6810 else if (const MemberPointerType *ResTypeMPtr = 6811 CanTy->getAs<MemberPointerType>()) 6812 CanTy = ResTypeMPtr->getPointeeType(); 6813 else 6814 done = true; 6815 if (CanTy.isVolatileQualified()) 6816 VRQuals.addVolatile(); 6817 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 6818 return VRQuals; 6819 } 6820 } 6821 } 6822 return VRQuals; 6823 } 6824 6825 namespace { 6826 6827 /// \brief Helper class to manage the addition of builtin operator overload 6828 /// candidates. It provides shared state and utility methods used throughout 6829 /// the process, as well as a helper method to add each group of builtin 6830 /// operator overloads from the standard to a candidate set. 6831 class BuiltinOperatorOverloadBuilder { 6832 // Common instance state available to all overload candidate addition methods. 6833 Sema &S; 6834 ArrayRef<Expr *> Args; 6835 Qualifiers VisibleTypeConversionsQuals; 6836 bool HasArithmeticOrEnumeralCandidateType; 6837 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 6838 OverloadCandidateSet &CandidateSet; 6839 6840 // Define some constants used to index and iterate over the arithemetic types 6841 // provided via the getArithmeticType() method below. 6842 // The "promoted arithmetic types" are the arithmetic 6843 // types are that preserved by promotion (C++ [over.built]p2). 6844 static const unsigned FirstIntegralType = 3; 6845 static const unsigned LastIntegralType = 20; 6846 static const unsigned FirstPromotedIntegralType = 3, 6847 LastPromotedIntegralType = 11; 6848 static const unsigned FirstPromotedArithmeticType = 0, 6849 LastPromotedArithmeticType = 11; 6850 static const unsigned NumArithmeticTypes = 20; 6851 6852 /// \brief Get the canonical type for a given arithmetic type index. 6853 CanQualType getArithmeticType(unsigned index) { 6854 assert(index < NumArithmeticTypes); 6855 static CanQualType ASTContext::* const 6856 ArithmeticTypes[NumArithmeticTypes] = { 6857 // Start of promoted types. 6858 &ASTContext::FloatTy, 6859 &ASTContext::DoubleTy, 6860 &ASTContext::LongDoubleTy, 6861 6862 // Start of integral types. 6863 &ASTContext::IntTy, 6864 &ASTContext::LongTy, 6865 &ASTContext::LongLongTy, 6866 &ASTContext::Int128Ty, 6867 &ASTContext::UnsignedIntTy, 6868 &ASTContext::UnsignedLongTy, 6869 &ASTContext::UnsignedLongLongTy, 6870 &ASTContext::UnsignedInt128Ty, 6871 // End of promoted types. 6872 6873 &ASTContext::BoolTy, 6874 &ASTContext::CharTy, 6875 &ASTContext::WCharTy, 6876 &ASTContext::Char16Ty, 6877 &ASTContext::Char32Ty, 6878 &ASTContext::SignedCharTy, 6879 &ASTContext::ShortTy, 6880 &ASTContext::UnsignedCharTy, 6881 &ASTContext::UnsignedShortTy, 6882 // End of integral types. 6883 // FIXME: What about complex? What about half? 6884 }; 6885 return S.Context.*ArithmeticTypes[index]; 6886 } 6887 6888 /// \brief Gets the canonical type resulting from the usual arithemetic 6889 /// converions for the given arithmetic types. 6890 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 6891 // Accelerator table for performing the usual arithmetic conversions. 6892 // The rules are basically: 6893 // - if either is floating-point, use the wider floating-point 6894 // - if same signedness, use the higher rank 6895 // - if same size, use unsigned of the higher rank 6896 // - use the larger type 6897 // These rules, together with the axiom that higher ranks are 6898 // never smaller, are sufficient to precompute all of these results 6899 // *except* when dealing with signed types of higher rank. 6900 // (we could precompute SLL x UI for all known platforms, but it's 6901 // better not to make any assumptions). 6902 // We assume that int128 has a higher rank than long long on all platforms. 6903 enum PromotedType { 6904 Dep=-1, 6905 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 6906 }; 6907 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 6908 [LastPromotedArithmeticType] = { 6909 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 6910 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 6911 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 6912 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 6913 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 6914 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 6915 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 6916 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 6917 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 6918 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 6919 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 6920 }; 6921 6922 assert(L < LastPromotedArithmeticType); 6923 assert(R < LastPromotedArithmeticType); 6924 int Idx = ConversionsTable[L][R]; 6925 6926 // Fast path: the table gives us a concrete answer. 6927 if (Idx != Dep) return getArithmeticType(Idx); 6928 6929 // Slow path: we need to compare widths. 6930 // An invariant is that the signed type has higher rank. 6931 CanQualType LT = getArithmeticType(L), 6932 RT = getArithmeticType(R); 6933 unsigned LW = S.Context.getIntWidth(LT), 6934 RW = S.Context.getIntWidth(RT); 6935 6936 // If they're different widths, use the signed type. 6937 if (LW > RW) return LT; 6938 else if (LW < RW) return RT; 6939 6940 // Otherwise, use the unsigned type of the signed type's rank. 6941 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 6942 assert(L == SLL || R == SLL); 6943 return S.Context.UnsignedLongLongTy; 6944 } 6945 6946 /// \brief Helper method to factor out the common pattern of adding overloads 6947 /// for '++' and '--' builtin operators. 6948 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 6949 bool HasVolatile, 6950 bool HasRestrict) { 6951 QualType ParamTypes[2] = { 6952 S.Context.getLValueReferenceType(CandidateTy), 6953 S.Context.IntTy 6954 }; 6955 6956 // Non-volatile version. 6957 if (Args.size() == 1) 6958 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6959 else 6960 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6961 6962 // Use a heuristic to reduce number of builtin candidates in the set: 6963 // add volatile version only if there are conversions to a volatile type. 6964 if (HasVolatile) { 6965 ParamTypes[0] = 6966 S.Context.getLValueReferenceType( 6967 S.Context.getVolatileType(CandidateTy)); 6968 if (Args.size() == 1) 6969 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6970 else 6971 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6972 } 6973 6974 // Add restrict version only if there are conversions to a restrict type 6975 // and our candidate type is a non-restrict-qualified pointer. 6976 if (HasRestrict && CandidateTy->isAnyPointerType() && 6977 !CandidateTy.isRestrictQualified()) { 6978 ParamTypes[0] 6979 = S.Context.getLValueReferenceType( 6980 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 6981 if (Args.size() == 1) 6982 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6983 else 6984 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6985 6986 if (HasVolatile) { 6987 ParamTypes[0] 6988 = S.Context.getLValueReferenceType( 6989 S.Context.getCVRQualifiedType(CandidateTy, 6990 (Qualifiers::Volatile | 6991 Qualifiers::Restrict))); 6992 if (Args.size() == 1) 6993 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 6994 else 6995 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 6996 } 6997 } 6998 6999 } 7000 7001 public: 7002 BuiltinOperatorOverloadBuilder( 7003 Sema &S, ArrayRef<Expr *> Args, 7004 Qualifiers VisibleTypeConversionsQuals, 7005 bool HasArithmeticOrEnumeralCandidateType, 7006 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7007 OverloadCandidateSet &CandidateSet) 7008 : S(S), Args(Args), 7009 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7010 HasArithmeticOrEnumeralCandidateType( 7011 HasArithmeticOrEnumeralCandidateType), 7012 CandidateTypes(CandidateTypes), 7013 CandidateSet(CandidateSet) { 7014 // Validate some of our static helper constants in debug builds. 7015 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7016 "Invalid first promoted integral type"); 7017 assert(getArithmeticType(LastPromotedIntegralType - 1) 7018 == S.Context.UnsignedInt128Ty && 7019 "Invalid last promoted integral type"); 7020 assert(getArithmeticType(FirstPromotedArithmeticType) 7021 == S.Context.FloatTy && 7022 "Invalid first promoted arithmetic type"); 7023 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7024 == S.Context.UnsignedInt128Ty && 7025 "Invalid last promoted arithmetic type"); 7026 } 7027 7028 // C++ [over.built]p3: 7029 // 7030 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7031 // is either volatile or empty, there exist candidate operator 7032 // functions of the form 7033 // 7034 // VQ T& operator++(VQ T&); 7035 // T operator++(VQ T&, int); 7036 // 7037 // C++ [over.built]p4: 7038 // 7039 // For every pair (T, VQ), where T is an arithmetic type other 7040 // than bool, and VQ is either volatile or empty, there exist 7041 // candidate operator functions of the form 7042 // 7043 // VQ T& operator--(VQ T&); 7044 // T operator--(VQ T&, int); 7045 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7046 if (!HasArithmeticOrEnumeralCandidateType) 7047 return; 7048 7049 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7050 Arith < NumArithmeticTypes; ++Arith) { 7051 addPlusPlusMinusMinusStyleOverloads( 7052 getArithmeticType(Arith), 7053 VisibleTypeConversionsQuals.hasVolatile(), 7054 VisibleTypeConversionsQuals.hasRestrict()); 7055 } 7056 } 7057 7058 // C++ [over.built]p5: 7059 // 7060 // For every pair (T, VQ), where T is a cv-qualified or 7061 // cv-unqualified object type, and VQ is either volatile or 7062 // empty, there exist candidate operator functions of the form 7063 // 7064 // T*VQ& operator++(T*VQ&); 7065 // T*VQ& operator--(T*VQ&); 7066 // T* operator++(T*VQ&, int); 7067 // T* operator--(T*VQ&, int); 7068 void addPlusPlusMinusMinusPointerOverloads() { 7069 for (BuiltinCandidateTypeSet::iterator 7070 Ptr = CandidateTypes[0].pointer_begin(), 7071 PtrEnd = CandidateTypes[0].pointer_end(); 7072 Ptr != PtrEnd; ++Ptr) { 7073 // Skip pointer types that aren't pointers to object types. 7074 if (!(*Ptr)->getPointeeType()->isObjectType()) 7075 continue; 7076 7077 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7078 (!(*Ptr).isVolatileQualified() && 7079 VisibleTypeConversionsQuals.hasVolatile()), 7080 (!(*Ptr).isRestrictQualified() && 7081 VisibleTypeConversionsQuals.hasRestrict())); 7082 } 7083 } 7084 7085 // C++ [over.built]p6: 7086 // For every cv-qualified or cv-unqualified object type T, there 7087 // exist candidate operator functions of the form 7088 // 7089 // T& operator*(T*); 7090 // 7091 // C++ [over.built]p7: 7092 // For every function type T that does not have cv-qualifiers or a 7093 // ref-qualifier, there exist candidate operator functions of the form 7094 // T& operator*(T*); 7095 void addUnaryStarPointerOverloads() { 7096 for (BuiltinCandidateTypeSet::iterator 7097 Ptr = CandidateTypes[0].pointer_begin(), 7098 PtrEnd = CandidateTypes[0].pointer_end(); 7099 Ptr != PtrEnd; ++Ptr) { 7100 QualType ParamTy = *Ptr; 7101 QualType PointeeTy = ParamTy->getPointeeType(); 7102 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7103 continue; 7104 7105 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7106 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7107 continue; 7108 7109 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7110 &ParamTy, Args, CandidateSet); 7111 } 7112 } 7113 7114 // C++ [over.built]p9: 7115 // For every promoted arithmetic type T, there exist candidate 7116 // operator functions of the form 7117 // 7118 // T operator+(T); 7119 // T operator-(T); 7120 void addUnaryPlusOrMinusArithmeticOverloads() { 7121 if (!HasArithmeticOrEnumeralCandidateType) 7122 return; 7123 7124 for (unsigned Arith = FirstPromotedArithmeticType; 7125 Arith < LastPromotedArithmeticType; ++Arith) { 7126 QualType ArithTy = getArithmeticType(Arith); 7127 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7128 } 7129 7130 // Extension: We also add these operators for vector types. 7131 for (BuiltinCandidateTypeSet::iterator 7132 Vec = CandidateTypes[0].vector_begin(), 7133 VecEnd = CandidateTypes[0].vector_end(); 7134 Vec != VecEnd; ++Vec) { 7135 QualType VecTy = *Vec; 7136 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7137 } 7138 } 7139 7140 // C++ [over.built]p8: 7141 // For every type T, there exist candidate operator functions of 7142 // the form 7143 // 7144 // T* operator+(T*); 7145 void addUnaryPlusPointerOverloads() { 7146 for (BuiltinCandidateTypeSet::iterator 7147 Ptr = CandidateTypes[0].pointer_begin(), 7148 PtrEnd = CandidateTypes[0].pointer_end(); 7149 Ptr != PtrEnd; ++Ptr) { 7150 QualType ParamTy = *Ptr; 7151 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7152 } 7153 } 7154 7155 // C++ [over.built]p10: 7156 // For every promoted integral type T, there exist candidate 7157 // operator functions of the form 7158 // 7159 // T operator~(T); 7160 void addUnaryTildePromotedIntegralOverloads() { 7161 if (!HasArithmeticOrEnumeralCandidateType) 7162 return; 7163 7164 for (unsigned Int = FirstPromotedIntegralType; 7165 Int < LastPromotedIntegralType; ++Int) { 7166 QualType IntTy = getArithmeticType(Int); 7167 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7168 } 7169 7170 // Extension: We also add this operator for vector types. 7171 for (BuiltinCandidateTypeSet::iterator 7172 Vec = CandidateTypes[0].vector_begin(), 7173 VecEnd = CandidateTypes[0].vector_end(); 7174 Vec != VecEnd; ++Vec) { 7175 QualType VecTy = *Vec; 7176 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7177 } 7178 } 7179 7180 // C++ [over.match.oper]p16: 7181 // For every pointer to member type T, there exist candidate operator 7182 // functions of the form 7183 // 7184 // bool operator==(T,T); 7185 // bool operator!=(T,T); 7186 void addEqualEqualOrNotEqualMemberPointerOverloads() { 7187 /// Set of (canonical) types that we've already handled. 7188 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7189 7190 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7191 for (BuiltinCandidateTypeSet::iterator 7192 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7193 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7194 MemPtr != MemPtrEnd; 7195 ++MemPtr) { 7196 // Don't add the same builtin candidate twice. 7197 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7198 continue; 7199 7200 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7201 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7202 } 7203 } 7204 } 7205 7206 // C++ [over.built]p15: 7207 // 7208 // For every T, where T is an enumeration type, a pointer type, or 7209 // std::nullptr_t, there exist candidate operator functions of the form 7210 // 7211 // bool operator<(T, T); 7212 // bool operator>(T, T); 7213 // bool operator<=(T, T); 7214 // bool operator>=(T, T); 7215 // bool operator==(T, T); 7216 // bool operator!=(T, T); 7217 void addRelationalPointerOrEnumeralOverloads() { 7218 // C++ [over.match.oper]p3: 7219 // [...]the built-in candidates include all of the candidate operator 7220 // functions defined in 13.6 that, compared to the given operator, [...] 7221 // do not have the same parameter-type-list as any non-template non-member 7222 // candidate. 7223 // 7224 // Note that in practice, this only affects enumeration types because there 7225 // aren't any built-in candidates of record type, and a user-defined operator 7226 // must have an operand of record or enumeration type. Also, the only other 7227 // overloaded operator with enumeration arguments, operator=, 7228 // cannot be overloaded for enumeration types, so this is the only place 7229 // where we must suppress candidates like this. 7230 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7231 UserDefinedBinaryOperators; 7232 7233 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7234 if (CandidateTypes[ArgIdx].enumeration_begin() != 7235 CandidateTypes[ArgIdx].enumeration_end()) { 7236 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7237 CEnd = CandidateSet.end(); 7238 C != CEnd; ++C) { 7239 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7240 continue; 7241 7242 if (C->Function->isFunctionTemplateSpecialization()) 7243 continue; 7244 7245 QualType FirstParamType = 7246 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7247 QualType SecondParamType = 7248 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7249 7250 // Skip if either parameter isn't of enumeral type. 7251 if (!FirstParamType->isEnumeralType() || 7252 !SecondParamType->isEnumeralType()) 7253 continue; 7254 7255 // Add this operator to the set of known user-defined operators. 7256 UserDefinedBinaryOperators.insert( 7257 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7258 S.Context.getCanonicalType(SecondParamType))); 7259 } 7260 } 7261 } 7262 7263 /// Set of (canonical) types that we've already handled. 7264 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7265 7266 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7267 for (BuiltinCandidateTypeSet::iterator 7268 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7269 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7270 Ptr != PtrEnd; ++Ptr) { 7271 // Don't add the same builtin candidate twice. 7272 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7273 continue; 7274 7275 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7276 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7277 } 7278 for (BuiltinCandidateTypeSet::iterator 7279 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7280 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7281 Enum != EnumEnd; ++Enum) { 7282 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7283 7284 // Don't add the same builtin candidate twice, or if a user defined 7285 // candidate exists. 7286 if (!AddedTypes.insert(CanonType) || 7287 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7288 CanonType))) 7289 continue; 7290 7291 QualType ParamTypes[2] = { *Enum, *Enum }; 7292 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7293 } 7294 7295 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7296 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7297 if (AddedTypes.insert(NullPtrTy) && 7298 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7299 NullPtrTy))) { 7300 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7301 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7302 CandidateSet); 7303 } 7304 } 7305 } 7306 } 7307 7308 // C++ [over.built]p13: 7309 // 7310 // For every cv-qualified or cv-unqualified object type T 7311 // there exist candidate operator functions of the form 7312 // 7313 // T* operator+(T*, ptrdiff_t); 7314 // T& operator[](T*, ptrdiff_t); [BELOW] 7315 // T* operator-(T*, ptrdiff_t); 7316 // T* operator+(ptrdiff_t, T*); 7317 // T& operator[](ptrdiff_t, T*); [BELOW] 7318 // 7319 // C++ [over.built]p14: 7320 // 7321 // For every T, where T is a pointer to object type, there 7322 // exist candidate operator functions of the form 7323 // 7324 // ptrdiff_t operator-(T, T); 7325 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7326 /// Set of (canonical) types that we've already handled. 7327 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7328 7329 for (int Arg = 0; Arg < 2; ++Arg) { 7330 QualType AsymetricParamTypes[2] = { 7331 S.Context.getPointerDiffType(), 7332 S.Context.getPointerDiffType(), 7333 }; 7334 for (BuiltinCandidateTypeSet::iterator 7335 Ptr = CandidateTypes[Arg].pointer_begin(), 7336 PtrEnd = CandidateTypes[Arg].pointer_end(); 7337 Ptr != PtrEnd; ++Ptr) { 7338 QualType PointeeTy = (*Ptr)->getPointeeType(); 7339 if (!PointeeTy->isObjectType()) 7340 continue; 7341 7342 AsymetricParamTypes[Arg] = *Ptr; 7343 if (Arg == 0 || Op == OO_Plus) { 7344 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7345 // T* operator+(ptrdiff_t, T*); 7346 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet); 7347 } 7348 if (Op == OO_Minus) { 7349 // ptrdiff_t operator-(T, T); 7350 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7351 continue; 7352 7353 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7354 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7355 Args, CandidateSet); 7356 } 7357 } 7358 } 7359 } 7360 7361 // C++ [over.built]p12: 7362 // 7363 // For every pair of promoted arithmetic types L and R, there 7364 // exist candidate operator functions of the form 7365 // 7366 // LR operator*(L, R); 7367 // LR operator/(L, R); 7368 // LR operator+(L, R); 7369 // LR operator-(L, R); 7370 // bool operator<(L, R); 7371 // bool operator>(L, R); 7372 // bool operator<=(L, R); 7373 // bool operator>=(L, R); 7374 // bool operator==(L, R); 7375 // bool operator!=(L, R); 7376 // 7377 // where LR is the result of the usual arithmetic conversions 7378 // between types L and R. 7379 // 7380 // C++ [over.built]p24: 7381 // 7382 // For every pair of promoted arithmetic types L and R, there exist 7383 // candidate operator functions of the form 7384 // 7385 // LR operator?(bool, L, R); 7386 // 7387 // where LR is the result of the usual arithmetic conversions 7388 // between types L and R. 7389 // Our candidates ignore the first parameter. 7390 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7391 if (!HasArithmeticOrEnumeralCandidateType) 7392 return; 7393 7394 for (unsigned Left = FirstPromotedArithmeticType; 7395 Left < LastPromotedArithmeticType; ++Left) { 7396 for (unsigned Right = FirstPromotedArithmeticType; 7397 Right < LastPromotedArithmeticType; ++Right) { 7398 QualType LandR[2] = { getArithmeticType(Left), 7399 getArithmeticType(Right) }; 7400 QualType Result = 7401 isComparison ? S.Context.BoolTy 7402 : getUsualArithmeticConversions(Left, Right); 7403 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7404 } 7405 } 7406 7407 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7408 // conditional operator for vector types. 7409 for (BuiltinCandidateTypeSet::iterator 7410 Vec1 = CandidateTypes[0].vector_begin(), 7411 Vec1End = CandidateTypes[0].vector_end(); 7412 Vec1 != Vec1End; ++Vec1) { 7413 for (BuiltinCandidateTypeSet::iterator 7414 Vec2 = CandidateTypes[1].vector_begin(), 7415 Vec2End = CandidateTypes[1].vector_end(); 7416 Vec2 != Vec2End; ++Vec2) { 7417 QualType LandR[2] = { *Vec1, *Vec2 }; 7418 QualType Result = S.Context.BoolTy; 7419 if (!isComparison) { 7420 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7421 Result = *Vec1; 7422 else 7423 Result = *Vec2; 7424 } 7425 7426 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7427 } 7428 } 7429 } 7430 7431 // C++ [over.built]p17: 7432 // 7433 // For every pair of promoted integral types L and R, there 7434 // exist candidate operator functions of the form 7435 // 7436 // LR operator%(L, R); 7437 // LR operator&(L, R); 7438 // LR operator^(L, R); 7439 // LR operator|(L, R); 7440 // L operator<<(L, R); 7441 // L operator>>(L, R); 7442 // 7443 // where LR is the result of the usual arithmetic conversions 7444 // between types L and R. 7445 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7446 if (!HasArithmeticOrEnumeralCandidateType) 7447 return; 7448 7449 for (unsigned Left = FirstPromotedIntegralType; 7450 Left < LastPromotedIntegralType; ++Left) { 7451 for (unsigned Right = FirstPromotedIntegralType; 7452 Right < LastPromotedIntegralType; ++Right) { 7453 QualType LandR[2] = { getArithmeticType(Left), 7454 getArithmeticType(Right) }; 7455 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7456 ? LandR[0] 7457 : getUsualArithmeticConversions(Left, Right); 7458 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7459 } 7460 } 7461 } 7462 7463 // C++ [over.built]p20: 7464 // 7465 // For every pair (T, VQ), where T is an enumeration or 7466 // pointer to member type and VQ is either volatile or 7467 // empty, there exist candidate operator functions of the form 7468 // 7469 // VQ T& operator=(VQ T&, T); 7470 void addAssignmentMemberPointerOrEnumeralOverloads() { 7471 /// Set of (canonical) types that we've already handled. 7472 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7473 7474 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7475 for (BuiltinCandidateTypeSet::iterator 7476 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7477 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7478 Enum != EnumEnd; ++Enum) { 7479 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7480 continue; 7481 7482 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7483 } 7484 7485 for (BuiltinCandidateTypeSet::iterator 7486 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7487 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7488 MemPtr != MemPtrEnd; ++MemPtr) { 7489 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7490 continue; 7491 7492 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7493 } 7494 } 7495 } 7496 7497 // C++ [over.built]p19: 7498 // 7499 // For every pair (T, VQ), where T is any type and VQ is either 7500 // volatile or empty, there exist candidate operator functions 7501 // of the form 7502 // 7503 // T*VQ& operator=(T*VQ&, T*); 7504 // 7505 // C++ [over.built]p21: 7506 // 7507 // For every pair (T, VQ), where T is a cv-qualified or 7508 // cv-unqualified object type and VQ is either volatile or 7509 // empty, there exist candidate operator functions of the form 7510 // 7511 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7512 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7513 void addAssignmentPointerOverloads(bool isEqualOp) { 7514 /// Set of (canonical) types that we've already handled. 7515 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7516 7517 for (BuiltinCandidateTypeSet::iterator 7518 Ptr = CandidateTypes[0].pointer_begin(), 7519 PtrEnd = CandidateTypes[0].pointer_end(); 7520 Ptr != PtrEnd; ++Ptr) { 7521 // If this is operator=, keep track of the builtin candidates we added. 7522 if (isEqualOp) 7523 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7524 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7525 continue; 7526 7527 // non-volatile version 7528 QualType ParamTypes[2] = { 7529 S.Context.getLValueReferenceType(*Ptr), 7530 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7531 }; 7532 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7533 /*IsAssigmentOperator=*/ isEqualOp); 7534 7535 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7536 VisibleTypeConversionsQuals.hasVolatile(); 7537 if (NeedVolatile) { 7538 // volatile version 7539 ParamTypes[0] = 7540 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7541 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7542 /*IsAssigmentOperator=*/isEqualOp); 7543 } 7544 7545 if (!(*Ptr).isRestrictQualified() && 7546 VisibleTypeConversionsQuals.hasRestrict()) { 7547 // restrict version 7548 ParamTypes[0] 7549 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7550 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7551 /*IsAssigmentOperator=*/isEqualOp); 7552 7553 if (NeedVolatile) { 7554 // volatile restrict version 7555 ParamTypes[0] 7556 = S.Context.getLValueReferenceType( 7557 S.Context.getCVRQualifiedType(*Ptr, 7558 (Qualifiers::Volatile | 7559 Qualifiers::Restrict))); 7560 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7561 /*IsAssigmentOperator=*/isEqualOp); 7562 } 7563 } 7564 } 7565 7566 if (isEqualOp) { 7567 for (BuiltinCandidateTypeSet::iterator 7568 Ptr = CandidateTypes[1].pointer_begin(), 7569 PtrEnd = CandidateTypes[1].pointer_end(); 7570 Ptr != PtrEnd; ++Ptr) { 7571 // Make sure we don't add the same candidate twice. 7572 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7573 continue; 7574 7575 QualType ParamTypes[2] = { 7576 S.Context.getLValueReferenceType(*Ptr), 7577 *Ptr, 7578 }; 7579 7580 // non-volatile version 7581 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7582 /*IsAssigmentOperator=*/true); 7583 7584 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7585 VisibleTypeConversionsQuals.hasVolatile(); 7586 if (NeedVolatile) { 7587 // volatile version 7588 ParamTypes[0] = 7589 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7590 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7591 /*IsAssigmentOperator=*/true); 7592 } 7593 7594 if (!(*Ptr).isRestrictQualified() && 7595 VisibleTypeConversionsQuals.hasRestrict()) { 7596 // restrict version 7597 ParamTypes[0] 7598 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7599 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7600 /*IsAssigmentOperator=*/true); 7601 7602 if (NeedVolatile) { 7603 // volatile restrict version 7604 ParamTypes[0] 7605 = S.Context.getLValueReferenceType( 7606 S.Context.getCVRQualifiedType(*Ptr, 7607 (Qualifiers::Volatile | 7608 Qualifiers::Restrict))); 7609 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7610 /*IsAssigmentOperator=*/true); 7611 } 7612 } 7613 } 7614 } 7615 } 7616 7617 // C++ [over.built]p18: 7618 // 7619 // For every triple (L, VQ, R), where L is an arithmetic type, 7620 // VQ is either volatile or empty, and R is a promoted 7621 // arithmetic type, there exist candidate operator functions of 7622 // the form 7623 // 7624 // VQ L& operator=(VQ L&, R); 7625 // VQ L& operator*=(VQ L&, R); 7626 // VQ L& operator/=(VQ L&, R); 7627 // VQ L& operator+=(VQ L&, R); 7628 // VQ L& operator-=(VQ L&, R); 7629 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7630 if (!HasArithmeticOrEnumeralCandidateType) 7631 return; 7632 7633 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7634 for (unsigned Right = FirstPromotedArithmeticType; 7635 Right < LastPromotedArithmeticType; ++Right) { 7636 QualType ParamTypes[2]; 7637 ParamTypes[1] = getArithmeticType(Right); 7638 7639 // Add this built-in operator as a candidate (VQ is empty). 7640 ParamTypes[0] = 7641 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7642 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7643 /*IsAssigmentOperator=*/isEqualOp); 7644 7645 // Add this built-in operator as a candidate (VQ is 'volatile'). 7646 if (VisibleTypeConversionsQuals.hasVolatile()) { 7647 ParamTypes[0] = 7648 S.Context.getVolatileType(getArithmeticType(Left)); 7649 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7650 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7651 /*IsAssigmentOperator=*/isEqualOp); 7652 } 7653 } 7654 } 7655 7656 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7657 for (BuiltinCandidateTypeSet::iterator 7658 Vec1 = CandidateTypes[0].vector_begin(), 7659 Vec1End = CandidateTypes[0].vector_end(); 7660 Vec1 != Vec1End; ++Vec1) { 7661 for (BuiltinCandidateTypeSet::iterator 7662 Vec2 = CandidateTypes[1].vector_begin(), 7663 Vec2End = CandidateTypes[1].vector_end(); 7664 Vec2 != Vec2End; ++Vec2) { 7665 QualType ParamTypes[2]; 7666 ParamTypes[1] = *Vec2; 7667 // Add this built-in operator as a candidate (VQ is empty). 7668 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7669 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7670 /*IsAssigmentOperator=*/isEqualOp); 7671 7672 // Add this built-in operator as a candidate (VQ is 'volatile'). 7673 if (VisibleTypeConversionsQuals.hasVolatile()) { 7674 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7675 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7676 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7677 /*IsAssigmentOperator=*/isEqualOp); 7678 } 7679 } 7680 } 7681 } 7682 7683 // C++ [over.built]p22: 7684 // 7685 // For every triple (L, VQ, R), where L is an integral type, VQ 7686 // is either volatile or empty, and R is a promoted integral 7687 // type, there exist candidate operator functions of the form 7688 // 7689 // VQ L& operator%=(VQ L&, R); 7690 // VQ L& operator<<=(VQ L&, R); 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 void addAssignmentIntegralOverloads() { 7696 if (!HasArithmeticOrEnumeralCandidateType) 7697 return; 7698 7699 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 7700 for (unsigned Right = FirstPromotedIntegralType; 7701 Right < LastPromotedIntegralType; ++Right) { 7702 QualType ParamTypes[2]; 7703 ParamTypes[1] = getArithmeticType(Right); 7704 7705 // Add this built-in operator as a candidate (VQ is empty). 7706 ParamTypes[0] = 7707 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7708 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7709 if (VisibleTypeConversionsQuals.hasVolatile()) { 7710 // Add this built-in operator as a candidate (VQ is 'volatile'). 7711 ParamTypes[0] = getArithmeticType(Left); 7712 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 7713 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7714 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7715 } 7716 } 7717 } 7718 } 7719 7720 // C++ [over.operator]p23: 7721 // 7722 // There also exist candidate operator functions of the form 7723 // 7724 // bool operator!(bool); 7725 // bool operator&&(bool, bool); 7726 // bool operator||(bool, bool); 7727 void addExclaimOverload() { 7728 QualType ParamTy = S.Context.BoolTy; 7729 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 7730 /*IsAssignmentOperator=*/false, 7731 /*NumContextualBoolArguments=*/1); 7732 } 7733 void addAmpAmpOrPipePipeOverload() { 7734 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 7735 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 7736 /*IsAssignmentOperator=*/false, 7737 /*NumContextualBoolArguments=*/2); 7738 } 7739 7740 // C++ [over.built]p13: 7741 // 7742 // For every cv-qualified or cv-unqualified object type T there 7743 // exist candidate operator functions of the form 7744 // 7745 // T* operator+(T*, ptrdiff_t); [ABOVE] 7746 // T& operator[](T*, ptrdiff_t); 7747 // T* operator-(T*, ptrdiff_t); [ABOVE] 7748 // T* operator+(ptrdiff_t, T*); [ABOVE] 7749 // T& operator[](ptrdiff_t, T*); 7750 void addSubscriptOverloads() { 7751 for (BuiltinCandidateTypeSet::iterator 7752 Ptr = CandidateTypes[0].pointer_begin(), 7753 PtrEnd = CandidateTypes[0].pointer_end(); 7754 Ptr != PtrEnd; ++Ptr) { 7755 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 7756 QualType PointeeType = (*Ptr)->getPointeeType(); 7757 if (!PointeeType->isObjectType()) 7758 continue; 7759 7760 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7761 7762 // T& operator[](T*, ptrdiff_t) 7763 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7764 } 7765 7766 for (BuiltinCandidateTypeSet::iterator 7767 Ptr = CandidateTypes[1].pointer_begin(), 7768 PtrEnd = CandidateTypes[1].pointer_end(); 7769 Ptr != PtrEnd; ++Ptr) { 7770 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 7771 QualType PointeeType = (*Ptr)->getPointeeType(); 7772 if (!PointeeType->isObjectType()) 7773 continue; 7774 7775 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 7776 7777 // T& operator[](ptrdiff_t, T*) 7778 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7779 } 7780 } 7781 7782 // C++ [over.built]p11: 7783 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 7784 // C1 is the same type as C2 or is a derived class of C2, T is an object 7785 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 7786 // there exist candidate operator functions of the form 7787 // 7788 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 7789 // 7790 // where CV12 is the union of CV1 and CV2. 7791 void addArrowStarOverloads() { 7792 for (BuiltinCandidateTypeSet::iterator 7793 Ptr = CandidateTypes[0].pointer_begin(), 7794 PtrEnd = CandidateTypes[0].pointer_end(); 7795 Ptr != PtrEnd; ++Ptr) { 7796 QualType C1Ty = (*Ptr); 7797 QualType C1; 7798 QualifierCollector Q1; 7799 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 7800 if (!isa<RecordType>(C1)) 7801 continue; 7802 // heuristic to reduce number of builtin candidates in the set. 7803 // Add volatile/restrict version only if there are conversions to a 7804 // volatile/restrict type. 7805 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 7806 continue; 7807 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 7808 continue; 7809 for (BuiltinCandidateTypeSet::iterator 7810 MemPtr = CandidateTypes[1].member_pointer_begin(), 7811 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 7812 MemPtr != MemPtrEnd; ++MemPtr) { 7813 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 7814 QualType C2 = QualType(mptr->getClass(), 0); 7815 C2 = C2.getUnqualifiedType(); 7816 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 7817 break; 7818 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 7819 // build CV12 T& 7820 QualType T = mptr->getPointeeType(); 7821 if (!VisibleTypeConversionsQuals.hasVolatile() && 7822 T.isVolatileQualified()) 7823 continue; 7824 if (!VisibleTypeConversionsQuals.hasRestrict() && 7825 T.isRestrictQualified()) 7826 continue; 7827 T = Q1.apply(S.Context, T); 7828 QualType ResultTy = S.Context.getLValueReferenceType(T); 7829 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 7830 } 7831 } 7832 } 7833 7834 // Note that we don't consider the first argument, since it has been 7835 // contextually converted to bool long ago. The candidates below are 7836 // therefore added as binary. 7837 // 7838 // C++ [over.built]p25: 7839 // For every type T, where T is a pointer, pointer-to-member, or scoped 7840 // enumeration type, there exist candidate operator functions of the form 7841 // 7842 // T operator?(bool, T, T); 7843 // 7844 void addConditionalOperatorOverloads() { 7845 /// Set of (canonical) types that we've already handled. 7846 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7847 7848 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7849 for (BuiltinCandidateTypeSet::iterator 7850 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7851 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7852 Ptr != PtrEnd; ++Ptr) { 7853 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr))) 7854 continue; 7855 7856 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7857 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 7858 } 7859 7860 for (BuiltinCandidateTypeSet::iterator 7861 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7862 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7863 MemPtr != MemPtrEnd; ++MemPtr) { 7864 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr))) 7865 continue; 7866 7867 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7868 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 7869 } 7870 7871 if (S.getLangOpts().CPlusPlus11) { 7872 for (BuiltinCandidateTypeSet::iterator 7873 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7874 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7875 Enum != EnumEnd; ++Enum) { 7876 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 7877 continue; 7878 7879 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum))) 7880 continue; 7881 7882 QualType ParamTypes[2] = { *Enum, *Enum }; 7883 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 7884 } 7885 } 7886 } 7887 } 7888 }; 7889 7890 } // end anonymous namespace 7891 7892 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 7893 /// operator overloads to the candidate set (C++ [over.built]), based 7894 /// on the operator @p Op and the arguments given. For example, if the 7895 /// operator is a binary '+', this routine might add "int 7896 /// operator+(int, int)" to cover integer addition. 7897 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 7898 SourceLocation OpLoc, 7899 ArrayRef<Expr *> Args, 7900 OverloadCandidateSet &CandidateSet) { 7901 // Find all of the types that the arguments can convert to, but only 7902 // if the operator we're looking at has built-in operator candidates 7903 // that make use of these types. Also record whether we encounter non-record 7904 // candidate types or either arithmetic or enumeral candidate types. 7905 Qualifiers VisibleTypeConversionsQuals; 7906 VisibleTypeConversionsQuals.addConst(); 7907 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 7908 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 7909 7910 bool HasNonRecordCandidateType = false; 7911 bool HasArithmeticOrEnumeralCandidateType = false; 7912 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 7913 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7914 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this)); 7915 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 7916 OpLoc, 7917 true, 7918 (Op == OO_Exclaim || 7919 Op == OO_AmpAmp || 7920 Op == OO_PipePipe), 7921 VisibleTypeConversionsQuals); 7922 HasNonRecordCandidateType = HasNonRecordCandidateType || 7923 CandidateTypes[ArgIdx].hasNonRecordTypes(); 7924 HasArithmeticOrEnumeralCandidateType = 7925 HasArithmeticOrEnumeralCandidateType || 7926 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 7927 } 7928 7929 // Exit early when no non-record types have been added to the candidate set 7930 // for any of the arguments to the operator. 7931 // 7932 // We can't exit early for !, ||, or &&, since there we have always have 7933 // 'bool' overloads. 7934 if (!HasNonRecordCandidateType && 7935 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 7936 return; 7937 7938 // Setup an object to manage the common state for building overloads. 7939 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 7940 VisibleTypeConversionsQuals, 7941 HasArithmeticOrEnumeralCandidateType, 7942 CandidateTypes, CandidateSet); 7943 7944 // Dispatch over the operation to add in only those overloads which apply. 7945 switch (Op) { 7946 case OO_None: 7947 case NUM_OVERLOADED_OPERATORS: 7948 llvm_unreachable("Expected an overloaded operator"); 7949 7950 case OO_New: 7951 case OO_Delete: 7952 case OO_Array_New: 7953 case OO_Array_Delete: 7954 case OO_Call: 7955 llvm_unreachable( 7956 "Special operators don't use AddBuiltinOperatorCandidates"); 7957 7958 case OO_Comma: 7959 case OO_Arrow: 7960 // C++ [over.match.oper]p3: 7961 // -- For the operator ',', the unary operator '&', or the 7962 // operator '->', the built-in candidates set is empty. 7963 break; 7964 7965 case OO_Plus: // '+' is either unary or binary 7966 if (Args.size() == 1) 7967 OpBuilder.addUnaryPlusPointerOverloads(); 7968 // Fall through. 7969 7970 case OO_Minus: // '-' is either unary or binary 7971 if (Args.size() == 1) { 7972 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 7973 } else { 7974 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 7975 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7976 } 7977 break; 7978 7979 case OO_Star: // '*' is either unary or binary 7980 if (Args.size() == 1) 7981 OpBuilder.addUnaryStarPointerOverloads(); 7982 else 7983 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7984 break; 7985 7986 case OO_Slash: 7987 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 7988 break; 7989 7990 case OO_PlusPlus: 7991 case OO_MinusMinus: 7992 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 7993 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 7994 break; 7995 7996 case OO_EqualEqual: 7997 case OO_ExclaimEqual: 7998 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 7999 // Fall through. 8000 8001 case OO_Less: 8002 case OO_Greater: 8003 case OO_LessEqual: 8004 case OO_GreaterEqual: 8005 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8006 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8007 break; 8008 8009 case OO_Percent: 8010 case OO_Caret: 8011 case OO_Pipe: 8012 case OO_LessLess: 8013 case OO_GreaterGreater: 8014 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8015 break; 8016 8017 case OO_Amp: // '&' is either unary or binary 8018 if (Args.size() == 1) 8019 // C++ [over.match.oper]p3: 8020 // -- For the operator ',', the unary operator '&', or the 8021 // operator '->', the built-in candidates set is empty. 8022 break; 8023 8024 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8025 break; 8026 8027 case OO_Tilde: 8028 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8029 break; 8030 8031 case OO_Equal: 8032 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8033 // Fall through. 8034 8035 case OO_PlusEqual: 8036 case OO_MinusEqual: 8037 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8038 // Fall through. 8039 8040 case OO_StarEqual: 8041 case OO_SlashEqual: 8042 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8043 break; 8044 8045 case OO_PercentEqual: 8046 case OO_LessLessEqual: 8047 case OO_GreaterGreaterEqual: 8048 case OO_AmpEqual: 8049 case OO_CaretEqual: 8050 case OO_PipeEqual: 8051 OpBuilder.addAssignmentIntegralOverloads(); 8052 break; 8053 8054 case OO_Exclaim: 8055 OpBuilder.addExclaimOverload(); 8056 break; 8057 8058 case OO_AmpAmp: 8059 case OO_PipePipe: 8060 OpBuilder.addAmpAmpOrPipePipeOverload(); 8061 break; 8062 8063 case OO_Subscript: 8064 OpBuilder.addSubscriptOverloads(); 8065 break; 8066 8067 case OO_ArrowStar: 8068 OpBuilder.addArrowStarOverloads(); 8069 break; 8070 8071 case OO_Conditional: 8072 OpBuilder.addConditionalOperatorOverloads(); 8073 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8074 break; 8075 } 8076 } 8077 8078 /// \brief Add function candidates found via argument-dependent lookup 8079 /// to the set of overloading candidates. 8080 /// 8081 /// This routine performs argument-dependent name lookup based on the 8082 /// given function name (which may also be an operator name) and adds 8083 /// all of the overload candidates found by ADL to the overload 8084 /// candidate set (C++ [basic.lookup.argdep]). 8085 void 8086 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8087 bool Operator, SourceLocation Loc, 8088 ArrayRef<Expr *> Args, 8089 TemplateArgumentListInfo *ExplicitTemplateArgs, 8090 OverloadCandidateSet& CandidateSet, 8091 bool PartialOverloading) { 8092 ADLResult Fns; 8093 8094 // FIXME: This approach for uniquing ADL results (and removing 8095 // redundant candidates from the set) relies on pointer-equality, 8096 // which means we need to key off the canonical decl. However, 8097 // always going back to the canonical decl might not get us the 8098 // right set of default arguments. What default arguments are 8099 // we supposed to consider on ADL candidates, anyway? 8100 8101 // FIXME: Pass in the explicit template arguments? 8102 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns); 8103 8104 // Erase all of the candidates we already knew about. 8105 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8106 CandEnd = CandidateSet.end(); 8107 Cand != CandEnd; ++Cand) 8108 if (Cand->Function) { 8109 Fns.erase(Cand->Function); 8110 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8111 Fns.erase(FunTmpl); 8112 } 8113 8114 // For each of the ADL candidates we found, add it to the overload 8115 // set. 8116 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8117 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8118 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8119 if (ExplicitTemplateArgs) 8120 continue; 8121 8122 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8123 PartialOverloading); 8124 } else 8125 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8126 FoundDecl, ExplicitTemplateArgs, 8127 Args, CandidateSet); 8128 } 8129 } 8130 8131 /// isBetterOverloadCandidate - Determines whether the first overload 8132 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8133 bool 8134 isBetterOverloadCandidate(Sema &S, 8135 const OverloadCandidate &Cand1, 8136 const OverloadCandidate &Cand2, 8137 SourceLocation Loc, 8138 bool UserDefinedConversion) { 8139 // Define viable functions to be better candidates than non-viable 8140 // functions. 8141 if (!Cand2.Viable) 8142 return Cand1.Viable; 8143 else if (!Cand1.Viable) 8144 return false; 8145 8146 // C++ [over.match.best]p1: 8147 // 8148 // -- if F is a static member function, ICS1(F) is defined such 8149 // that ICS1(F) is neither better nor worse than ICS1(G) for 8150 // any function G, and, symmetrically, ICS1(G) is neither 8151 // better nor worse than ICS1(F). 8152 unsigned StartArg = 0; 8153 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8154 StartArg = 1; 8155 8156 // C++ [over.match.best]p1: 8157 // A viable function F1 is defined to be a better function than another 8158 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8159 // conversion sequence than ICSi(F2), and then... 8160 unsigned NumArgs = Cand1.NumConversions; 8161 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8162 bool HasBetterConversion = false; 8163 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8164 switch (CompareImplicitConversionSequences(S, 8165 Cand1.Conversions[ArgIdx], 8166 Cand2.Conversions[ArgIdx])) { 8167 case ImplicitConversionSequence::Better: 8168 // Cand1 has a better conversion sequence. 8169 HasBetterConversion = true; 8170 break; 8171 8172 case ImplicitConversionSequence::Worse: 8173 // Cand1 can't be better than Cand2. 8174 return false; 8175 8176 case ImplicitConversionSequence::Indistinguishable: 8177 // Do nothing. 8178 break; 8179 } 8180 } 8181 8182 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8183 // ICSj(F2), or, if not that, 8184 if (HasBetterConversion) 8185 return true; 8186 8187 // - F1 is a non-template function and F2 is a function template 8188 // specialization, or, if not that, 8189 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) && 8190 Cand2.Function && Cand2.Function->getPrimaryTemplate()) 8191 return true; 8192 8193 // -- F1 and F2 are function template specializations, and the function 8194 // template for F1 is more specialized than the template for F2 8195 // according to the partial ordering rules described in 14.5.5.2, or, 8196 // if not that, 8197 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() && 8198 Cand2.Function && Cand2.Function->getPrimaryTemplate()) { 8199 if (FunctionTemplateDecl *BetterTemplate 8200 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8201 Cand2.Function->getPrimaryTemplate(), 8202 Loc, 8203 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8204 : TPOC_Call, 8205 Cand1.ExplicitCallArguments, 8206 Cand2.ExplicitCallArguments)) 8207 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8208 } 8209 8210 // -- the context is an initialization by user-defined conversion 8211 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8212 // from the return type of F1 to the destination type (i.e., 8213 // the type of the entity being initialized) is a better 8214 // conversion sequence than the standard conversion sequence 8215 // from the return type of F2 to the destination type. 8216 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8217 isa<CXXConversionDecl>(Cand1.Function) && 8218 isa<CXXConversionDecl>(Cand2.Function)) { 8219 // First check whether we prefer one of the conversion functions over the 8220 // other. This only distinguishes the results in non-standard, extension 8221 // cases such as the conversion from a lambda closure type to a function 8222 // pointer or block. 8223 ImplicitConversionSequence::CompareKind FuncResult 8224 = compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8225 if (FuncResult != ImplicitConversionSequence::Indistinguishable) 8226 return FuncResult; 8227 8228 switch (CompareStandardConversionSequences(S, 8229 Cand1.FinalConversion, 8230 Cand2.FinalConversion)) { 8231 case ImplicitConversionSequence::Better: 8232 // Cand1 has a better conversion sequence. 8233 return true; 8234 8235 case ImplicitConversionSequence::Worse: 8236 // Cand1 can't be better than Cand2. 8237 return false; 8238 8239 case ImplicitConversionSequence::Indistinguishable: 8240 // Do nothing 8241 break; 8242 } 8243 } 8244 8245 // Check for enable_if value-based overload resolution. 8246 if (Cand1.Function && Cand2.Function && 8247 (Cand1.Function->hasAttr<EnableIfAttr>() || 8248 Cand2.Function->hasAttr<EnableIfAttr>())) { 8249 // FIXME: The next several lines are just 8250 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8251 // instead of reverse order which is how they're stored in the AST. 8252 AttrVec Cand1Attrs; 8253 AttrVec::iterator Cand1E = Cand1Attrs.end(); 8254 if (Cand1.Function->hasAttrs()) { 8255 Cand1Attrs = Cand1.Function->getAttrs(); 8256 Cand1E = std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(), 8257 IsNotEnableIfAttr); 8258 std::reverse(Cand1Attrs.begin(), Cand1E); 8259 } 8260 8261 AttrVec Cand2Attrs; 8262 AttrVec::iterator Cand2E = Cand2Attrs.end(); 8263 if (Cand2.Function->hasAttrs()) { 8264 Cand2Attrs = Cand2.Function->getAttrs(); 8265 Cand2E = std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(), 8266 IsNotEnableIfAttr); 8267 std::reverse(Cand2Attrs.begin(), Cand2E); 8268 } 8269 for (AttrVec::iterator 8270 Cand1I = Cand1Attrs.begin(), Cand2I = Cand2Attrs.begin(); 8271 Cand1I != Cand1E || Cand2I != Cand2E; ++Cand1I, ++Cand2I) { 8272 if (Cand1I == Cand1E) 8273 return false; 8274 if (Cand2I == Cand2E) 8275 return true; 8276 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8277 cast<EnableIfAttr>(*Cand1I)->getCond()->Profile(Cand1ID, 8278 S.getASTContext(), true); 8279 cast<EnableIfAttr>(*Cand2I)->getCond()->Profile(Cand2ID, 8280 S.getASTContext(), true); 8281 if (Cand1ID != Cand2ID) 8282 return false; 8283 } 8284 } 8285 8286 return false; 8287 } 8288 8289 /// \brief Computes the best viable function (C++ 13.3.3) 8290 /// within an overload candidate set. 8291 /// 8292 /// \param Loc The location of the function name (or operator symbol) for 8293 /// which overload resolution occurs. 8294 /// 8295 /// \param Best If overload resolution was successful or found a deleted 8296 /// function, \p Best points to the candidate function found. 8297 /// 8298 /// \returns The result of overload resolution. 8299 OverloadingResult 8300 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8301 iterator &Best, 8302 bool UserDefinedConversion) { 8303 // Find the best viable function. 8304 Best = end(); 8305 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8306 if (Cand->Viable) 8307 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8308 UserDefinedConversion)) 8309 Best = Cand; 8310 } 8311 8312 // If we didn't find any viable functions, abort. 8313 if (Best == end()) 8314 return OR_No_Viable_Function; 8315 8316 // Make sure that this function is better than every other viable 8317 // function. If not, we have an ambiguity. 8318 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8319 if (Cand->Viable && 8320 Cand != Best && 8321 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8322 UserDefinedConversion)) { 8323 Best = end(); 8324 return OR_Ambiguous; 8325 } 8326 } 8327 8328 // Best is the best viable function. 8329 if (Best->Function && 8330 (Best->Function->isDeleted() || 8331 S.isFunctionConsideredUnavailable(Best->Function))) 8332 return OR_Deleted; 8333 8334 return OR_Success; 8335 } 8336 8337 namespace { 8338 8339 enum OverloadCandidateKind { 8340 oc_function, 8341 oc_method, 8342 oc_constructor, 8343 oc_function_template, 8344 oc_method_template, 8345 oc_constructor_template, 8346 oc_implicit_default_constructor, 8347 oc_implicit_copy_constructor, 8348 oc_implicit_move_constructor, 8349 oc_implicit_copy_assignment, 8350 oc_implicit_move_assignment, 8351 oc_implicit_inherited_constructor 8352 }; 8353 8354 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8355 FunctionDecl *Fn, 8356 std::string &Description) { 8357 bool isTemplate = false; 8358 8359 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8360 isTemplate = true; 8361 Description = S.getTemplateArgumentBindingsText( 8362 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8363 } 8364 8365 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8366 if (!Ctor->isImplicit()) 8367 return isTemplate ? oc_constructor_template : oc_constructor; 8368 8369 if (Ctor->getInheritedConstructor()) 8370 return oc_implicit_inherited_constructor; 8371 8372 if (Ctor->isDefaultConstructor()) 8373 return oc_implicit_default_constructor; 8374 8375 if (Ctor->isMoveConstructor()) 8376 return oc_implicit_move_constructor; 8377 8378 assert(Ctor->isCopyConstructor() && 8379 "unexpected sort of implicit constructor"); 8380 return oc_implicit_copy_constructor; 8381 } 8382 8383 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8384 // This actually gets spelled 'candidate function' for now, but 8385 // it doesn't hurt to split it out. 8386 if (!Meth->isImplicit()) 8387 return isTemplate ? oc_method_template : oc_method; 8388 8389 if (Meth->isMoveAssignmentOperator()) 8390 return oc_implicit_move_assignment; 8391 8392 if (Meth->isCopyAssignmentOperator()) 8393 return oc_implicit_copy_assignment; 8394 8395 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8396 return oc_method; 8397 } 8398 8399 return isTemplate ? oc_function_template : oc_function; 8400 } 8401 8402 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) { 8403 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8404 if (!Ctor) return; 8405 8406 Ctor = Ctor->getInheritedConstructor(); 8407 if (!Ctor) return; 8408 8409 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8410 } 8411 8412 } // end anonymous namespace 8413 8414 // Notes the location of an overload candidate. 8415 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) { 8416 std::string FnDesc; 8417 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8418 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8419 << (unsigned) K << FnDesc; 8420 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8421 Diag(Fn->getLocation(), PD); 8422 MaybeEmitInheritedConstructorNote(*this, Fn); 8423 } 8424 8425 // Notes the location of all overload candidates designated through 8426 // OverloadedExpr 8427 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) { 8428 assert(OverloadedExpr->getType() == Context.OverloadTy); 8429 8430 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8431 OverloadExpr *OvlExpr = Ovl.Expression; 8432 8433 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8434 IEnd = OvlExpr->decls_end(); 8435 I != IEnd; ++I) { 8436 if (FunctionTemplateDecl *FunTmpl = 8437 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8438 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType); 8439 } else if (FunctionDecl *Fun 8440 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8441 NoteOverloadCandidate(Fun, DestType); 8442 } 8443 } 8444 } 8445 8446 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 8447 /// "lead" diagnostic; it will be given two arguments, the source and 8448 /// target types of the conversion. 8449 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8450 Sema &S, 8451 SourceLocation CaretLoc, 8452 const PartialDiagnostic &PDiag) const { 8453 S.Diag(CaretLoc, PDiag) 8454 << Ambiguous.getFromType() << Ambiguous.getToType(); 8455 // FIXME: The note limiting machinery is borrowed from 8456 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8457 // refactoring here. 8458 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8459 unsigned CandsShown = 0; 8460 AmbiguousConversionSequence::const_iterator I, E; 8461 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8462 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8463 break; 8464 ++CandsShown; 8465 S.NoteOverloadCandidate(*I); 8466 } 8467 if (I != E) 8468 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8469 } 8470 8471 namespace { 8472 8473 void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) { 8474 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8475 assert(Conv.isBad()); 8476 assert(Cand->Function && "for now, candidate must be a function"); 8477 FunctionDecl *Fn = Cand->Function; 8478 8479 // There's a conversion slot for the object argument if this is a 8480 // non-constructor method. Note that 'I' corresponds the 8481 // conversion-slot index. 8482 bool isObjectArgument = false; 8483 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8484 if (I == 0) 8485 isObjectArgument = true; 8486 else 8487 I--; 8488 } 8489 8490 std::string FnDesc; 8491 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8492 8493 Expr *FromExpr = Conv.Bad.FromExpr; 8494 QualType FromTy = Conv.Bad.getFromType(); 8495 QualType ToTy = Conv.Bad.getToType(); 8496 8497 if (FromTy == S.Context.OverloadTy) { 8498 assert(FromExpr && "overload set argument came from implicit argument?"); 8499 Expr *E = FromExpr->IgnoreParens(); 8500 if (isa<UnaryOperator>(E)) 8501 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8502 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8503 8504 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8505 << (unsigned) FnKind << FnDesc 8506 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8507 << ToTy << Name << I+1; 8508 MaybeEmitInheritedConstructorNote(S, Fn); 8509 return; 8510 } 8511 8512 // Do some hand-waving analysis to see if the non-viability is due 8513 // to a qualifier mismatch. 8514 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8515 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8516 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8517 CToTy = RT->getPointeeType(); 8518 else { 8519 // TODO: detect and diagnose the full richness of const mismatches. 8520 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8521 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8522 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8523 } 8524 8525 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8526 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8527 Qualifiers FromQs = CFromTy.getQualifiers(); 8528 Qualifiers ToQs = CToTy.getQualifiers(); 8529 8530 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 8531 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 8532 << (unsigned) FnKind << FnDesc 8533 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8534 << FromTy 8535 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 8536 << (unsigned) isObjectArgument << I+1; 8537 MaybeEmitInheritedConstructorNote(S, Fn); 8538 return; 8539 } 8540 8541 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8542 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 8543 << (unsigned) FnKind << FnDesc 8544 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8545 << FromTy 8546 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 8547 << (unsigned) isObjectArgument << I+1; 8548 MaybeEmitInheritedConstructorNote(S, Fn); 8549 return; 8550 } 8551 8552 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 8553 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 8554 << (unsigned) FnKind << FnDesc 8555 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8556 << FromTy 8557 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 8558 << (unsigned) isObjectArgument << I+1; 8559 MaybeEmitInheritedConstructorNote(S, Fn); 8560 return; 8561 } 8562 8563 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 8564 assert(CVR && "unexpected qualifiers mismatch"); 8565 8566 if (isObjectArgument) { 8567 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 8568 << (unsigned) FnKind << FnDesc 8569 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8570 << FromTy << (CVR - 1); 8571 } else { 8572 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 8573 << (unsigned) FnKind << FnDesc 8574 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8575 << FromTy << (CVR - 1) << I+1; 8576 } 8577 MaybeEmitInheritedConstructorNote(S, Fn); 8578 return; 8579 } 8580 8581 // Special diagnostic for failure to convert an initializer list, since 8582 // telling the user that it has type void is not useful. 8583 if (FromExpr && isa<InitListExpr>(FromExpr)) { 8584 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 8585 << (unsigned) FnKind << FnDesc 8586 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8587 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8588 MaybeEmitInheritedConstructorNote(S, Fn); 8589 return; 8590 } 8591 8592 // Diagnose references or pointers to incomplete types differently, 8593 // since it's far from impossible that the incompleteness triggered 8594 // the failure. 8595 QualType TempFromTy = FromTy.getNonReferenceType(); 8596 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 8597 TempFromTy = PTy->getPointeeType(); 8598 if (TempFromTy->isIncompleteType()) { 8599 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 8600 << (unsigned) FnKind << FnDesc 8601 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8602 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8603 MaybeEmitInheritedConstructorNote(S, Fn); 8604 return; 8605 } 8606 8607 // Diagnose base -> derived pointer conversions. 8608 unsigned BaseToDerivedConversion = 0; 8609 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 8610 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 8611 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8612 FromPtrTy->getPointeeType()) && 8613 !FromPtrTy->getPointeeType()->isIncompleteType() && 8614 !ToPtrTy->getPointeeType()->isIncompleteType() && 8615 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 8616 FromPtrTy->getPointeeType())) 8617 BaseToDerivedConversion = 1; 8618 } 8619 } else if (const ObjCObjectPointerType *FromPtrTy 8620 = FromTy->getAs<ObjCObjectPointerType>()) { 8621 if (const ObjCObjectPointerType *ToPtrTy 8622 = ToTy->getAs<ObjCObjectPointerType>()) 8623 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 8624 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 8625 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 8626 FromPtrTy->getPointeeType()) && 8627 FromIface->isSuperClassOf(ToIface)) 8628 BaseToDerivedConversion = 2; 8629 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 8630 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 8631 !FromTy->isIncompleteType() && 8632 !ToRefTy->getPointeeType()->isIncompleteType() && 8633 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 8634 BaseToDerivedConversion = 3; 8635 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 8636 ToTy.getNonReferenceType().getCanonicalType() == 8637 FromTy.getNonReferenceType().getCanonicalType()) { 8638 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 8639 << (unsigned) FnKind << FnDesc 8640 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8641 << (unsigned) isObjectArgument << I + 1; 8642 MaybeEmitInheritedConstructorNote(S, Fn); 8643 return; 8644 } 8645 } 8646 8647 if (BaseToDerivedConversion) { 8648 S.Diag(Fn->getLocation(), 8649 diag::note_ovl_candidate_bad_base_to_derived_conv) 8650 << (unsigned) FnKind << FnDesc 8651 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8652 << (BaseToDerivedConversion - 1) 8653 << FromTy << ToTy << I+1; 8654 MaybeEmitInheritedConstructorNote(S, Fn); 8655 return; 8656 } 8657 8658 if (isa<ObjCObjectPointerType>(CFromTy) && 8659 isa<PointerType>(CToTy)) { 8660 Qualifiers FromQs = CFromTy.getQualifiers(); 8661 Qualifiers ToQs = CToTy.getQualifiers(); 8662 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 8663 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 8664 << (unsigned) FnKind << FnDesc 8665 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8666 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 8667 MaybeEmitInheritedConstructorNote(S, Fn); 8668 return; 8669 } 8670 } 8671 8672 // Emit the generic diagnostic and, optionally, add the hints to it. 8673 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 8674 FDiag << (unsigned) FnKind << FnDesc 8675 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8676 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 8677 << (unsigned) (Cand->Fix.Kind); 8678 8679 // If we can fix the conversion, suggest the FixIts. 8680 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 8681 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 8682 FDiag << *HI; 8683 S.Diag(Fn->getLocation(), FDiag); 8684 8685 MaybeEmitInheritedConstructorNote(S, Fn); 8686 } 8687 8688 /// Additional arity mismatch diagnosis specific to a function overload 8689 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 8690 /// over a candidate in any candidate set. 8691 bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 8692 unsigned NumArgs) { 8693 FunctionDecl *Fn = Cand->Function; 8694 unsigned MinParams = Fn->getMinRequiredArguments(); 8695 8696 // With invalid overloaded operators, it's possible that we think we 8697 // have an arity mismatch when in fact it looks like we have the 8698 // right number of arguments, because only overloaded operators have 8699 // the weird behavior of overloading member and non-member functions. 8700 // Just don't report anything. 8701 if (Fn->isInvalidDecl() && 8702 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 8703 return true; 8704 8705 if (NumArgs < MinParams) { 8706 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 8707 (Cand->FailureKind == ovl_fail_bad_deduction && 8708 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 8709 } else { 8710 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 8711 (Cand->FailureKind == ovl_fail_bad_deduction && 8712 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 8713 } 8714 8715 return false; 8716 } 8717 8718 /// General arity mismatch diagnosis over a candidate in a candidate set. 8719 void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) { 8720 assert(isa<FunctionDecl>(D) && 8721 "The templated declaration should at least be a function" 8722 " when diagnosing bad template argument deduction due to too many" 8723 " or too few arguments"); 8724 8725 FunctionDecl *Fn = cast<FunctionDecl>(D); 8726 8727 // TODO: treat calls to a missing default constructor as a special case 8728 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 8729 unsigned MinParams = Fn->getMinRequiredArguments(); 8730 8731 // at least / at most / exactly 8732 unsigned mode, modeCount; 8733 if (NumFormalArgs < MinParams) { 8734 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 8735 FnTy->isTemplateVariadic()) 8736 mode = 0; // "at least" 8737 else 8738 mode = 2; // "exactly" 8739 modeCount = MinParams; 8740 } else { 8741 if (MinParams != FnTy->getNumParams()) 8742 mode = 1; // "at most" 8743 else 8744 mode = 2; // "exactly" 8745 modeCount = FnTy->getNumParams(); 8746 } 8747 8748 std::string Description; 8749 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 8750 8751 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 8752 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 8753 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8754 << Fn->getParamDecl(0) << NumFormalArgs; 8755 else 8756 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 8757 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode 8758 << modeCount << NumFormalArgs; 8759 MaybeEmitInheritedConstructorNote(S, Fn); 8760 } 8761 8762 /// Arity mismatch diagnosis specific to a function overload candidate. 8763 void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 8764 unsigned NumFormalArgs) { 8765 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 8766 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs); 8767 } 8768 8769 TemplateDecl *getDescribedTemplate(Decl *Templated) { 8770 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated)) 8771 return FD->getDescribedFunctionTemplate(); 8772 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated)) 8773 return RD->getDescribedClassTemplate(); 8774 8775 llvm_unreachable("Unsupported: Getting the described template declaration" 8776 " for bad deduction diagnosis"); 8777 } 8778 8779 /// Diagnose a failed template-argument deduction. 8780 void DiagnoseBadDeduction(Sema &S, Decl *Templated, 8781 DeductionFailureInfo &DeductionFailure, 8782 unsigned NumArgs) { 8783 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 8784 NamedDecl *ParamD; 8785 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 8786 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 8787 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 8788 switch (DeductionFailure.Result) { 8789 case Sema::TDK_Success: 8790 llvm_unreachable("TDK_success while diagnosing bad deduction"); 8791 8792 case Sema::TDK_Incomplete: { 8793 assert(ParamD && "no parameter found for incomplete deduction result"); 8794 S.Diag(Templated->getLocation(), 8795 diag::note_ovl_candidate_incomplete_deduction) 8796 << ParamD->getDeclName(); 8797 MaybeEmitInheritedConstructorNote(S, Templated); 8798 return; 8799 } 8800 8801 case Sema::TDK_Underqualified: { 8802 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 8803 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 8804 8805 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 8806 8807 // Param will have been canonicalized, but it should just be a 8808 // qualified version of ParamD, so move the qualifiers to that. 8809 QualifierCollector Qs; 8810 Qs.strip(Param); 8811 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 8812 assert(S.Context.hasSameType(Param, NonCanonParam)); 8813 8814 // Arg has also been canonicalized, but there's nothing we can do 8815 // about that. It also doesn't matter as much, because it won't 8816 // have any template parameters in it (because deduction isn't 8817 // done on dependent types). 8818 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 8819 8820 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 8821 << ParamD->getDeclName() << Arg << NonCanonParam; 8822 MaybeEmitInheritedConstructorNote(S, Templated); 8823 return; 8824 } 8825 8826 case Sema::TDK_Inconsistent: { 8827 assert(ParamD && "no parameter found for inconsistent deduction result"); 8828 int which = 0; 8829 if (isa<TemplateTypeParmDecl>(ParamD)) 8830 which = 0; 8831 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 8832 which = 1; 8833 else { 8834 which = 2; 8835 } 8836 8837 S.Diag(Templated->getLocation(), 8838 diag::note_ovl_candidate_inconsistent_deduction) 8839 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 8840 << *DeductionFailure.getSecondArg(); 8841 MaybeEmitInheritedConstructorNote(S, Templated); 8842 return; 8843 } 8844 8845 case Sema::TDK_InvalidExplicitArguments: 8846 assert(ParamD && "no parameter found for invalid explicit arguments"); 8847 if (ParamD->getDeclName()) 8848 S.Diag(Templated->getLocation(), 8849 diag::note_ovl_candidate_explicit_arg_mismatch_named) 8850 << ParamD->getDeclName(); 8851 else { 8852 int index = 0; 8853 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 8854 index = TTP->getIndex(); 8855 else if (NonTypeTemplateParmDecl *NTTP 8856 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 8857 index = NTTP->getIndex(); 8858 else 8859 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 8860 S.Diag(Templated->getLocation(), 8861 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 8862 << (index + 1); 8863 } 8864 MaybeEmitInheritedConstructorNote(S, Templated); 8865 return; 8866 8867 case Sema::TDK_TooManyArguments: 8868 case Sema::TDK_TooFewArguments: 8869 DiagnoseArityMismatch(S, Templated, NumArgs); 8870 return; 8871 8872 case Sema::TDK_InstantiationDepth: 8873 S.Diag(Templated->getLocation(), 8874 diag::note_ovl_candidate_instantiation_depth); 8875 MaybeEmitInheritedConstructorNote(S, Templated); 8876 return; 8877 8878 case Sema::TDK_SubstitutionFailure: { 8879 // Format the template argument list into the argument string. 8880 SmallString<128> TemplateArgString; 8881 if (TemplateArgumentList *Args = 8882 DeductionFailure.getTemplateArgumentList()) { 8883 TemplateArgString = " "; 8884 TemplateArgString += S.getTemplateArgumentBindingsText( 8885 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 8886 } 8887 8888 // If this candidate was disabled by enable_if, say so. 8889 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 8890 if (PDiag && PDiag->second.getDiagID() == 8891 diag::err_typename_nested_not_found_enable_if) { 8892 // FIXME: Use the source range of the condition, and the fully-qualified 8893 // name of the enable_if template. These are both present in PDiag. 8894 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 8895 << "'enable_if'" << TemplateArgString; 8896 return; 8897 } 8898 8899 // Format the SFINAE diagnostic into the argument string. 8900 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 8901 // formatted message in another diagnostic. 8902 SmallString<128> SFINAEArgString; 8903 SourceRange R; 8904 if (PDiag) { 8905 SFINAEArgString = ": "; 8906 R = SourceRange(PDiag->first, PDiag->first); 8907 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 8908 } 8909 8910 S.Diag(Templated->getLocation(), 8911 diag::note_ovl_candidate_substitution_failure) 8912 << TemplateArgString << SFINAEArgString << R; 8913 MaybeEmitInheritedConstructorNote(S, Templated); 8914 return; 8915 } 8916 8917 case Sema::TDK_FailedOverloadResolution: { 8918 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 8919 S.Diag(Templated->getLocation(), 8920 diag::note_ovl_candidate_failed_overload_resolution) 8921 << R.Expression->getName(); 8922 return; 8923 } 8924 8925 case Sema::TDK_NonDeducedMismatch: { 8926 // FIXME: Provide a source location to indicate what we couldn't match. 8927 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 8928 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 8929 if (FirstTA.getKind() == TemplateArgument::Template && 8930 SecondTA.getKind() == TemplateArgument::Template) { 8931 TemplateName FirstTN = FirstTA.getAsTemplate(); 8932 TemplateName SecondTN = SecondTA.getAsTemplate(); 8933 if (FirstTN.getKind() == TemplateName::Template && 8934 SecondTN.getKind() == TemplateName::Template) { 8935 if (FirstTN.getAsTemplateDecl()->getName() == 8936 SecondTN.getAsTemplateDecl()->getName()) { 8937 // FIXME: This fixes a bad diagnostic where both templates are named 8938 // the same. This particular case is a bit difficult since: 8939 // 1) It is passed as a string to the diagnostic printer. 8940 // 2) The diagnostic printer only attempts to find a better 8941 // name for types, not decls. 8942 // Ideally, this should folded into the diagnostic printer. 8943 S.Diag(Templated->getLocation(), 8944 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 8945 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 8946 return; 8947 } 8948 } 8949 } 8950 // FIXME: For generic lambda parameters, check if the function is a lambda 8951 // call operator, and if so, emit a prettier and more informative 8952 // diagnostic that mentions 'auto' and lambda in addition to 8953 // (or instead of?) the canonical template type parameters. 8954 S.Diag(Templated->getLocation(), 8955 diag::note_ovl_candidate_non_deduced_mismatch) 8956 << FirstTA << SecondTA; 8957 return; 8958 } 8959 // TODO: diagnose these individually, then kill off 8960 // note_ovl_candidate_bad_deduction, which is uselessly vague. 8961 case Sema::TDK_MiscellaneousDeductionFailure: 8962 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 8963 MaybeEmitInheritedConstructorNote(S, Templated); 8964 return; 8965 } 8966 } 8967 8968 /// Diagnose a failed template-argument deduction, for function calls. 8969 void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) { 8970 unsigned TDK = Cand->DeductionFailure.Result; 8971 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 8972 if (CheckArityMismatch(S, Cand, NumArgs)) 8973 return; 8974 } 8975 DiagnoseBadDeduction(S, Cand->Function, // pattern 8976 Cand->DeductionFailure, NumArgs); 8977 } 8978 8979 /// CUDA: diagnose an invalid call across targets. 8980 void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 8981 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 8982 FunctionDecl *Callee = Cand->Function; 8983 8984 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 8985 CalleeTarget = S.IdentifyCUDATarget(Callee); 8986 8987 std::string FnDesc; 8988 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 8989 8990 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 8991 << (unsigned) FnKind << CalleeTarget << CallerTarget; 8992 } 8993 8994 void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 8995 FunctionDecl *Callee = Cand->Function; 8996 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 8997 8998 S.Diag(Callee->getLocation(), 8999 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9000 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9001 } 9002 9003 /// Generates a 'note' diagnostic for an overload candidate. We've 9004 /// already generated a primary error at the call site. 9005 /// 9006 /// It really does need to be a single diagnostic with its caret 9007 /// pointed at the candidate declaration. Yes, this creates some 9008 /// major challenges of technical writing. Yes, this makes pointing 9009 /// out problems with specific arguments quite awkward. It's still 9010 /// better than generating twenty screens of text for every failed 9011 /// overload. 9012 /// 9013 /// It would be great to be able to express per-candidate problems 9014 /// more richly for those diagnostic clients that cared, but we'd 9015 /// still have to be just as careful with the default diagnostics. 9016 void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9017 unsigned NumArgs) { 9018 FunctionDecl *Fn = Cand->Function; 9019 9020 // Note deleted candidates, but only if they're viable. 9021 if (Cand->Viable && (Fn->isDeleted() || 9022 S.isFunctionConsideredUnavailable(Fn))) { 9023 std::string FnDesc; 9024 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 9025 9026 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9027 << FnKind << FnDesc 9028 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9029 MaybeEmitInheritedConstructorNote(S, Fn); 9030 return; 9031 } 9032 9033 // We don't really have anything else to say about viable candidates. 9034 if (Cand->Viable) { 9035 S.NoteOverloadCandidate(Fn); 9036 return; 9037 } 9038 9039 switch (Cand->FailureKind) { 9040 case ovl_fail_too_many_arguments: 9041 case ovl_fail_too_few_arguments: 9042 return DiagnoseArityMismatch(S, Cand, NumArgs); 9043 9044 case ovl_fail_bad_deduction: 9045 return DiagnoseBadDeduction(S, Cand, NumArgs); 9046 9047 case ovl_fail_trivial_conversion: 9048 case ovl_fail_bad_final_conversion: 9049 case ovl_fail_final_conversion_not_exact: 9050 return S.NoteOverloadCandidate(Fn); 9051 9052 case ovl_fail_bad_conversion: { 9053 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9054 for (unsigned N = Cand->NumConversions; I != N; ++I) 9055 if (Cand->Conversions[I].isBad()) 9056 return DiagnoseBadConversion(S, Cand, I); 9057 9058 // FIXME: this currently happens when we're called from SemaInit 9059 // when user-conversion overload fails. Figure out how to handle 9060 // those conditions and diagnose them well. 9061 return S.NoteOverloadCandidate(Fn); 9062 } 9063 9064 case ovl_fail_bad_target: 9065 return DiagnoseBadTarget(S, Cand); 9066 9067 case ovl_fail_enable_if: 9068 return DiagnoseFailedEnableIfAttr(S, Cand); 9069 } 9070 } 9071 9072 void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9073 // Desugar the type of the surrogate down to a function type, 9074 // retaining as many typedefs as possible while still showing 9075 // the function type (and, therefore, its parameter types). 9076 QualType FnType = Cand->Surrogate->getConversionType(); 9077 bool isLValueReference = false; 9078 bool isRValueReference = false; 9079 bool isPointer = false; 9080 if (const LValueReferenceType *FnTypeRef = 9081 FnType->getAs<LValueReferenceType>()) { 9082 FnType = FnTypeRef->getPointeeType(); 9083 isLValueReference = true; 9084 } else if (const RValueReferenceType *FnTypeRef = 9085 FnType->getAs<RValueReferenceType>()) { 9086 FnType = FnTypeRef->getPointeeType(); 9087 isRValueReference = true; 9088 } 9089 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9090 FnType = FnTypePtr->getPointeeType(); 9091 isPointer = true; 9092 } 9093 // Desugar down to a function type. 9094 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9095 // Reconstruct the pointer/reference as appropriate. 9096 if (isPointer) FnType = S.Context.getPointerType(FnType); 9097 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9098 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9099 9100 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9101 << FnType; 9102 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 9103 } 9104 9105 void NoteBuiltinOperatorCandidate(Sema &S, 9106 StringRef Opc, 9107 SourceLocation OpLoc, 9108 OverloadCandidate *Cand) { 9109 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9110 std::string TypeStr("operator"); 9111 TypeStr += Opc; 9112 TypeStr += "("; 9113 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9114 if (Cand->NumConversions == 1) { 9115 TypeStr += ")"; 9116 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9117 } else { 9118 TypeStr += ", "; 9119 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9120 TypeStr += ")"; 9121 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9122 } 9123 } 9124 9125 void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9126 OverloadCandidate *Cand) { 9127 unsigned NoOperands = Cand->NumConversions; 9128 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9129 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9130 if (ICS.isBad()) break; // all meaningless after first invalid 9131 if (!ICS.isAmbiguous()) continue; 9132 9133 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 9134 S.PDiag(diag::note_ambiguous_type_conversion)); 9135 } 9136 } 9137 9138 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9139 if (Cand->Function) 9140 return Cand->Function->getLocation(); 9141 if (Cand->IsSurrogate) 9142 return Cand->Surrogate->getLocation(); 9143 return SourceLocation(); 9144 } 9145 9146 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 9147 switch ((Sema::TemplateDeductionResult)DFI.Result) { 9148 case Sema::TDK_Success: 9149 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9150 9151 case Sema::TDK_Invalid: 9152 case Sema::TDK_Incomplete: 9153 return 1; 9154 9155 case Sema::TDK_Underqualified: 9156 case Sema::TDK_Inconsistent: 9157 return 2; 9158 9159 case Sema::TDK_SubstitutionFailure: 9160 case Sema::TDK_NonDeducedMismatch: 9161 case Sema::TDK_MiscellaneousDeductionFailure: 9162 return 3; 9163 9164 case Sema::TDK_InstantiationDepth: 9165 case Sema::TDK_FailedOverloadResolution: 9166 return 4; 9167 9168 case Sema::TDK_InvalidExplicitArguments: 9169 return 5; 9170 9171 case Sema::TDK_TooManyArguments: 9172 case Sema::TDK_TooFewArguments: 9173 return 6; 9174 } 9175 llvm_unreachable("Unhandled deduction result"); 9176 } 9177 9178 struct CompareOverloadCandidatesForDisplay { 9179 Sema &S; 9180 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {} 9181 9182 bool operator()(const OverloadCandidate *L, 9183 const OverloadCandidate *R) { 9184 // Fast-path this check. 9185 if (L == R) return false; 9186 9187 // Order first by viability. 9188 if (L->Viable) { 9189 if (!R->Viable) return true; 9190 9191 // TODO: introduce a tri-valued comparison for overload 9192 // candidates. Would be more worthwhile if we had a sort 9193 // that could exploit it. 9194 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 9195 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 9196 } else if (R->Viable) 9197 return false; 9198 9199 assert(L->Viable == R->Viable); 9200 9201 // Criteria by which we can sort non-viable candidates: 9202 if (!L->Viable) { 9203 // 1. Arity mismatches come after other candidates. 9204 if (L->FailureKind == ovl_fail_too_many_arguments || 9205 L->FailureKind == ovl_fail_too_few_arguments) 9206 return false; 9207 if (R->FailureKind == ovl_fail_too_many_arguments || 9208 R->FailureKind == ovl_fail_too_few_arguments) 9209 return true; 9210 9211 // 2. Bad conversions come first and are ordered by the number 9212 // of bad conversions and quality of good conversions. 9213 if (L->FailureKind == ovl_fail_bad_conversion) { 9214 if (R->FailureKind != ovl_fail_bad_conversion) 9215 return true; 9216 9217 // The conversion that can be fixed with a smaller number of changes, 9218 // comes first. 9219 unsigned numLFixes = L->Fix.NumConversionsFixed; 9220 unsigned numRFixes = R->Fix.NumConversionsFixed; 9221 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 9222 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 9223 if (numLFixes != numRFixes) { 9224 if (numLFixes < numRFixes) 9225 return true; 9226 else 9227 return false; 9228 } 9229 9230 // If there's any ordering between the defined conversions... 9231 // FIXME: this might not be transitive. 9232 assert(L->NumConversions == R->NumConversions); 9233 9234 int leftBetter = 0; 9235 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 9236 for (unsigned E = L->NumConversions; I != E; ++I) { 9237 switch (CompareImplicitConversionSequences(S, 9238 L->Conversions[I], 9239 R->Conversions[I])) { 9240 case ImplicitConversionSequence::Better: 9241 leftBetter++; 9242 break; 9243 9244 case ImplicitConversionSequence::Worse: 9245 leftBetter--; 9246 break; 9247 9248 case ImplicitConversionSequence::Indistinguishable: 9249 break; 9250 } 9251 } 9252 if (leftBetter > 0) return true; 9253 if (leftBetter < 0) return false; 9254 9255 } else if (R->FailureKind == ovl_fail_bad_conversion) 9256 return false; 9257 9258 if (L->FailureKind == ovl_fail_bad_deduction) { 9259 if (R->FailureKind != ovl_fail_bad_deduction) 9260 return true; 9261 9262 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9263 return RankDeductionFailure(L->DeductionFailure) 9264 < RankDeductionFailure(R->DeductionFailure); 9265 } else if (R->FailureKind == ovl_fail_bad_deduction) 9266 return false; 9267 9268 // TODO: others? 9269 } 9270 9271 // Sort everything else by location. 9272 SourceLocation LLoc = GetLocationForCandidate(L); 9273 SourceLocation RLoc = GetLocationForCandidate(R); 9274 9275 // Put candidates without locations (e.g. builtins) at the end. 9276 if (LLoc.isInvalid()) return false; 9277 if (RLoc.isInvalid()) return true; 9278 9279 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9280 } 9281 }; 9282 9283 /// CompleteNonViableCandidate - Normally, overload resolution only 9284 /// computes up to the first. Produces the FixIt set if possible. 9285 void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 9286 ArrayRef<Expr *> Args) { 9287 assert(!Cand->Viable); 9288 9289 // Don't do anything on failures other than bad conversion. 9290 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 9291 9292 // We only want the FixIts if all the arguments can be corrected. 9293 bool Unfixable = false; 9294 // Use a implicit copy initialization to check conversion fixes. 9295 Cand->Fix.setConversionChecker(TryCopyInitialization); 9296 9297 // Skip forward to the first bad conversion. 9298 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 9299 unsigned ConvCount = Cand->NumConversions; 9300 while (true) { 9301 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 9302 ConvIdx++; 9303 if (Cand->Conversions[ConvIdx - 1].isBad()) { 9304 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 9305 break; 9306 } 9307 } 9308 9309 if (ConvIdx == ConvCount) 9310 return; 9311 9312 assert(!Cand->Conversions[ConvIdx].isInitialized() && 9313 "remaining conversion is initialized?"); 9314 9315 // FIXME: this should probably be preserved from the overload 9316 // operation somehow. 9317 bool SuppressUserConversions = false; 9318 9319 const FunctionProtoType* Proto; 9320 unsigned ArgIdx = ConvIdx; 9321 9322 if (Cand->IsSurrogate) { 9323 QualType ConvType 9324 = Cand->Surrogate->getConversionType().getNonReferenceType(); 9325 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9326 ConvType = ConvPtrType->getPointeeType(); 9327 Proto = ConvType->getAs<FunctionProtoType>(); 9328 ArgIdx--; 9329 } else if (Cand->Function) { 9330 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 9331 if (isa<CXXMethodDecl>(Cand->Function) && 9332 !isa<CXXConstructorDecl>(Cand->Function)) 9333 ArgIdx--; 9334 } else { 9335 // Builtin binary operator with a bad first conversion. 9336 assert(ConvCount <= 3); 9337 for (; ConvIdx != ConvCount; ++ConvIdx) 9338 Cand->Conversions[ConvIdx] 9339 = TryCopyInitialization(S, Args[ConvIdx], 9340 Cand->BuiltinTypes.ParamTypes[ConvIdx], 9341 SuppressUserConversions, 9342 /*InOverloadResolution*/ true, 9343 /*AllowObjCWritebackConversion=*/ 9344 S.getLangOpts().ObjCAutoRefCount); 9345 return; 9346 } 9347 9348 // Fill in the rest of the conversions. 9349 unsigned NumParams = Proto->getNumParams(); 9350 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 9351 if (ArgIdx < NumParams) { 9352 Cand->Conversions[ConvIdx] = TryCopyInitialization( 9353 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 9354 /*InOverloadResolution=*/true, 9355 /*AllowObjCWritebackConversion=*/ 9356 S.getLangOpts().ObjCAutoRefCount); 9357 // Store the FixIt in the candidate if it exists. 9358 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 9359 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 9360 } 9361 else 9362 Cand->Conversions[ConvIdx].setEllipsis(); 9363 } 9364 } 9365 9366 } // end anonymous namespace 9367 9368 /// PrintOverloadCandidates - When overload resolution fails, prints 9369 /// diagnostic messages containing the candidates in the candidate 9370 /// set. 9371 void OverloadCandidateSet::NoteCandidates(Sema &S, 9372 OverloadCandidateDisplayKind OCD, 9373 ArrayRef<Expr *> Args, 9374 StringRef Opc, 9375 SourceLocation OpLoc) { 9376 // Sort the candidates by viability and position. Sorting directly would 9377 // be prohibitive, so we make a set of pointers and sort those. 9378 SmallVector<OverloadCandidate*, 32> Cands; 9379 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 9380 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9381 if (Cand->Viable) 9382 Cands.push_back(Cand); 9383 else if (OCD == OCD_AllCandidates) { 9384 CompleteNonViableCandidate(S, Cand, Args); 9385 if (Cand->Function || Cand->IsSurrogate) 9386 Cands.push_back(Cand); 9387 // Otherwise, this a non-viable builtin candidate. We do not, in general, 9388 // want to list every possible builtin candidate. 9389 } 9390 } 9391 9392 std::sort(Cands.begin(), Cands.end(), 9393 CompareOverloadCandidatesForDisplay(S)); 9394 9395 bool ReportedAmbiguousConversions = false; 9396 9397 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 9398 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9399 unsigned CandsShown = 0; 9400 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9401 OverloadCandidate *Cand = *I; 9402 9403 // Set an arbitrary limit on the number of candidate functions we'll spam 9404 // the user with. FIXME: This limit should depend on details of the 9405 // candidate list. 9406 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 9407 break; 9408 } 9409 ++CandsShown; 9410 9411 if (Cand->Function) 9412 NoteFunctionCandidate(S, Cand, Args.size()); 9413 else if (Cand->IsSurrogate) 9414 NoteSurrogateCandidate(S, Cand); 9415 else { 9416 assert(Cand->Viable && 9417 "Non-viable built-in candidates are not added to Cands."); 9418 // Generally we only see ambiguities including viable builtin 9419 // operators if overload resolution got screwed up by an 9420 // ambiguous user-defined conversion. 9421 // 9422 // FIXME: It's quite possible for different conversions to see 9423 // different ambiguities, though. 9424 if (!ReportedAmbiguousConversions) { 9425 NoteAmbiguousUserConversions(S, OpLoc, Cand); 9426 ReportedAmbiguousConversions = true; 9427 } 9428 9429 // If this is a viable builtin, print it. 9430 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 9431 } 9432 } 9433 9434 if (I != E) 9435 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 9436 } 9437 9438 static SourceLocation 9439 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 9440 return Cand->Specialization ? Cand->Specialization->getLocation() 9441 : SourceLocation(); 9442 } 9443 9444 struct CompareTemplateSpecCandidatesForDisplay { 9445 Sema &S; 9446 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 9447 9448 bool operator()(const TemplateSpecCandidate *L, 9449 const TemplateSpecCandidate *R) { 9450 // Fast-path this check. 9451 if (L == R) 9452 return false; 9453 9454 // Assuming that both candidates are not matches... 9455 9456 // Sort by the ranking of deduction failures. 9457 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9458 return RankDeductionFailure(L->DeductionFailure) < 9459 RankDeductionFailure(R->DeductionFailure); 9460 9461 // Sort everything else by location. 9462 SourceLocation LLoc = GetLocationForCandidate(L); 9463 SourceLocation RLoc = GetLocationForCandidate(R); 9464 9465 // Put candidates without locations (e.g. builtins) at the end. 9466 if (LLoc.isInvalid()) 9467 return false; 9468 if (RLoc.isInvalid()) 9469 return true; 9470 9471 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9472 } 9473 }; 9474 9475 /// Diagnose a template argument deduction failure. 9476 /// We are treating these failures as overload failures due to bad 9477 /// deductions. 9478 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) { 9479 DiagnoseBadDeduction(S, Specialization, // pattern 9480 DeductionFailure, /*NumArgs=*/0); 9481 } 9482 9483 void TemplateSpecCandidateSet::destroyCandidates() { 9484 for (iterator i = begin(), e = end(); i != e; ++i) { 9485 i->DeductionFailure.Destroy(); 9486 } 9487 } 9488 9489 void TemplateSpecCandidateSet::clear() { 9490 destroyCandidates(); 9491 Candidates.clear(); 9492 } 9493 9494 /// NoteCandidates - When no template specialization match is found, prints 9495 /// diagnostic messages containing the non-matching specializations that form 9496 /// the candidate set. 9497 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 9498 /// OCD == OCD_AllCandidates and Cand->Viable == false. 9499 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 9500 // Sort the candidates by position (assuming no candidate is a match). 9501 // Sorting directly would be prohibitive, so we make a set of pointers 9502 // and sort those. 9503 SmallVector<TemplateSpecCandidate *, 32> Cands; 9504 Cands.reserve(size()); 9505 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9506 if (Cand->Specialization) 9507 Cands.push_back(Cand); 9508 // Otherwise, this is a non-matching builtin candidate. We do not, 9509 // in general, want to list every possible builtin candidate. 9510 } 9511 9512 std::sort(Cands.begin(), Cands.end(), 9513 CompareTemplateSpecCandidatesForDisplay(S)); 9514 9515 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 9516 // for generalization purposes (?). 9517 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9518 9519 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 9520 unsigned CandsShown = 0; 9521 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9522 TemplateSpecCandidate *Cand = *I; 9523 9524 // Set an arbitrary limit on the number of candidates we'll spam 9525 // the user with. FIXME: This limit should depend on details of the 9526 // candidate list. 9527 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9528 break; 9529 ++CandsShown; 9530 9531 assert(Cand->Specialization && 9532 "Non-matching built-in candidates are not added to Cands."); 9533 Cand->NoteDeductionFailure(S); 9534 } 9535 9536 if (I != E) 9537 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 9538 } 9539 9540 // [PossiblyAFunctionType] --> [Return] 9541 // NonFunctionType --> NonFunctionType 9542 // R (A) --> R(A) 9543 // R (*)(A) --> R (A) 9544 // R (&)(A) --> R (A) 9545 // R (S::*)(A) --> R (A) 9546 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 9547 QualType Ret = PossiblyAFunctionType; 9548 if (const PointerType *ToTypePtr = 9549 PossiblyAFunctionType->getAs<PointerType>()) 9550 Ret = ToTypePtr->getPointeeType(); 9551 else if (const ReferenceType *ToTypeRef = 9552 PossiblyAFunctionType->getAs<ReferenceType>()) 9553 Ret = ToTypeRef->getPointeeType(); 9554 else if (const MemberPointerType *MemTypePtr = 9555 PossiblyAFunctionType->getAs<MemberPointerType>()) 9556 Ret = MemTypePtr->getPointeeType(); 9557 Ret = 9558 Context.getCanonicalType(Ret).getUnqualifiedType(); 9559 return Ret; 9560 } 9561 9562 // A helper class to help with address of function resolution 9563 // - allows us to avoid passing around all those ugly parameters 9564 class AddressOfFunctionResolver 9565 { 9566 Sema& S; 9567 Expr* SourceExpr; 9568 const QualType& TargetType; 9569 QualType TargetFunctionType; // Extracted function type from target type 9570 9571 bool Complain; 9572 //DeclAccessPair& ResultFunctionAccessPair; 9573 ASTContext& Context; 9574 9575 bool TargetTypeIsNonStaticMemberFunction; 9576 bool FoundNonTemplateFunction; 9577 bool StaticMemberFunctionFromBoundPointer; 9578 9579 OverloadExpr::FindResult OvlExprInfo; 9580 OverloadExpr *OvlExpr; 9581 TemplateArgumentListInfo OvlExplicitTemplateArgs; 9582 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 9583 TemplateSpecCandidateSet FailedCandidates; 9584 9585 public: 9586 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 9587 const QualType &TargetType, bool Complain) 9588 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 9589 Complain(Complain), Context(S.getASTContext()), 9590 TargetTypeIsNonStaticMemberFunction( 9591 !!TargetType->getAs<MemberPointerType>()), 9592 FoundNonTemplateFunction(false), 9593 StaticMemberFunctionFromBoundPointer(false), 9594 OvlExprInfo(OverloadExpr::find(SourceExpr)), 9595 OvlExpr(OvlExprInfo.Expression), 9596 FailedCandidates(OvlExpr->getNameLoc()) { 9597 ExtractUnqualifiedFunctionTypeFromTargetType(); 9598 9599 if (TargetFunctionType->isFunctionType()) { 9600 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 9601 if (!UME->isImplicitAccess() && 9602 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 9603 StaticMemberFunctionFromBoundPointer = true; 9604 } else if (OvlExpr->hasExplicitTemplateArgs()) { 9605 DeclAccessPair dap; 9606 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 9607 OvlExpr, false, &dap)) { 9608 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 9609 if (!Method->isStatic()) { 9610 // If the target type is a non-function type and the function found 9611 // is a non-static member function, pretend as if that was the 9612 // target, it's the only possible type to end up with. 9613 TargetTypeIsNonStaticMemberFunction = true; 9614 9615 // And skip adding the function if its not in the proper form. 9616 // We'll diagnose this due to an empty set of functions. 9617 if (!OvlExprInfo.HasFormOfMemberPointer) 9618 return; 9619 } 9620 9621 Matches.push_back(std::make_pair(dap, Fn)); 9622 } 9623 return; 9624 } 9625 9626 if (OvlExpr->hasExplicitTemplateArgs()) 9627 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 9628 9629 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 9630 // C++ [over.over]p4: 9631 // If more than one function is selected, [...] 9632 if (Matches.size() > 1) { 9633 if (FoundNonTemplateFunction) 9634 EliminateAllTemplateMatches(); 9635 else 9636 EliminateAllExceptMostSpecializedTemplate(); 9637 } 9638 } 9639 } 9640 9641 private: 9642 bool isTargetTypeAFunction() const { 9643 return TargetFunctionType->isFunctionType(); 9644 } 9645 9646 // [ToType] [Return] 9647 9648 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 9649 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 9650 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 9651 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 9652 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 9653 } 9654 9655 // return true if any matching specializations were found 9656 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 9657 const DeclAccessPair& CurAccessFunPair) { 9658 if (CXXMethodDecl *Method 9659 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 9660 // Skip non-static function templates when converting to pointer, and 9661 // static when converting to member pointer. 9662 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9663 return false; 9664 } 9665 else if (TargetTypeIsNonStaticMemberFunction) 9666 return false; 9667 9668 // C++ [over.over]p2: 9669 // If the name is a function template, template argument deduction is 9670 // done (14.8.2.2), and if the argument deduction succeeds, the 9671 // resulting template argument list is used to generate a single 9672 // function template specialization, which is added to the set of 9673 // overloaded functions considered. 9674 FunctionDecl *Specialization = 0; 9675 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 9676 if (Sema::TemplateDeductionResult Result 9677 = S.DeduceTemplateArguments(FunctionTemplate, 9678 &OvlExplicitTemplateArgs, 9679 TargetFunctionType, Specialization, 9680 Info, /*InOverloadResolution=*/true)) { 9681 // Make a note of the failed deduction for diagnostics. 9682 FailedCandidates.addCandidate() 9683 .set(FunctionTemplate->getTemplatedDecl(), 9684 MakeDeductionFailureInfo(Context, Result, Info)); 9685 return false; 9686 } 9687 9688 // Template argument deduction ensures that we have an exact match or 9689 // compatible pointer-to-function arguments that would be adjusted by ICS. 9690 // This function template specicalization works. 9691 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 9692 assert(S.isSameOrCompatibleFunctionType( 9693 Context.getCanonicalType(Specialization->getType()), 9694 Context.getCanonicalType(TargetFunctionType))); 9695 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 9696 return true; 9697 } 9698 9699 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 9700 const DeclAccessPair& CurAccessFunPair) { 9701 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 9702 // Skip non-static functions when converting to pointer, and static 9703 // when converting to member pointer. 9704 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 9705 return false; 9706 } 9707 else if (TargetTypeIsNonStaticMemberFunction) 9708 return false; 9709 9710 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 9711 if (S.getLangOpts().CUDA) 9712 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 9713 if (S.CheckCUDATarget(Caller, FunDecl)) 9714 return false; 9715 9716 // If any candidate has a placeholder return type, trigger its deduction 9717 // now. 9718 if (S.getLangOpts().CPlusPlus1y && 9719 FunDecl->getReturnType()->isUndeducedType() && 9720 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) 9721 return false; 9722 9723 QualType ResultTy; 9724 if (Context.hasSameUnqualifiedType(TargetFunctionType, 9725 FunDecl->getType()) || 9726 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 9727 ResultTy)) { 9728 Matches.push_back(std::make_pair(CurAccessFunPair, 9729 cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 9730 FoundNonTemplateFunction = true; 9731 return true; 9732 } 9733 } 9734 9735 return false; 9736 } 9737 9738 bool FindAllFunctionsThatMatchTargetTypeExactly() { 9739 bool Ret = false; 9740 9741 // If the overload expression doesn't have the form of a pointer to 9742 // member, don't try to convert it to a pointer-to-member type. 9743 if (IsInvalidFormOfPointerToMemberFunction()) 9744 return false; 9745 9746 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9747 E = OvlExpr->decls_end(); 9748 I != E; ++I) { 9749 // Look through any using declarations to find the underlying function. 9750 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 9751 9752 // C++ [over.over]p3: 9753 // Non-member functions and static member functions match 9754 // targets of type "pointer-to-function" or "reference-to-function." 9755 // Nonstatic member functions match targets of 9756 // type "pointer-to-member-function." 9757 // Note that according to DR 247, the containing class does not matter. 9758 if (FunctionTemplateDecl *FunctionTemplate 9759 = dyn_cast<FunctionTemplateDecl>(Fn)) { 9760 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 9761 Ret = true; 9762 } 9763 // If we have explicit template arguments supplied, skip non-templates. 9764 else if (!OvlExpr->hasExplicitTemplateArgs() && 9765 AddMatchingNonTemplateFunction(Fn, I.getPair())) 9766 Ret = true; 9767 } 9768 assert(Ret || Matches.empty()); 9769 return Ret; 9770 } 9771 9772 void EliminateAllExceptMostSpecializedTemplate() { 9773 // [...] and any given function template specialization F1 is 9774 // eliminated if the set contains a second function template 9775 // specialization whose function template is more specialized 9776 // than the function template of F1 according to the partial 9777 // ordering rules of 14.5.5.2. 9778 9779 // The algorithm specified above is quadratic. We instead use a 9780 // two-pass algorithm (similar to the one used to identify the 9781 // best viable function in an overload set) that identifies the 9782 // best function template (if it exists). 9783 9784 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 9785 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 9786 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 9787 9788 // TODO: It looks like FailedCandidates does not serve much purpose 9789 // here, since the no_viable diagnostic has index 0. 9790 UnresolvedSetIterator Result = S.getMostSpecialized( 9791 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 9792 SourceExpr->getLocStart(), S.PDiag(), 9793 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0] 9794 .second->getDeclName(), 9795 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template, 9796 Complain, TargetFunctionType); 9797 9798 if (Result != MatchesCopy.end()) { 9799 // Make it the first and only element 9800 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 9801 Matches[0].second = cast<FunctionDecl>(*Result); 9802 Matches.resize(1); 9803 } 9804 } 9805 9806 void EliminateAllTemplateMatches() { 9807 // [...] any function template specializations in the set are 9808 // eliminated if the set also contains a non-template function, [...] 9809 for (unsigned I = 0, N = Matches.size(); I != N; ) { 9810 if (Matches[I].second->getPrimaryTemplate() == 0) 9811 ++I; 9812 else { 9813 Matches[I] = Matches[--N]; 9814 Matches.set_size(N); 9815 } 9816 } 9817 } 9818 9819 public: 9820 void ComplainNoMatchesFound() const { 9821 assert(Matches.empty()); 9822 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 9823 << OvlExpr->getName() << TargetFunctionType 9824 << OvlExpr->getSourceRange(); 9825 if (FailedCandidates.empty()) 9826 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9827 else { 9828 // We have some deduction failure messages. Use them to diagnose 9829 // the function templates, and diagnose the non-template candidates 9830 // normally. 9831 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9832 IEnd = OvlExpr->decls_end(); 9833 I != IEnd; ++I) 9834 if (FunctionDecl *Fun = 9835 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 9836 S.NoteOverloadCandidate(Fun, TargetFunctionType); 9837 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 9838 } 9839 } 9840 9841 bool IsInvalidFormOfPointerToMemberFunction() const { 9842 return TargetTypeIsNonStaticMemberFunction && 9843 !OvlExprInfo.HasFormOfMemberPointer; 9844 } 9845 9846 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 9847 // TODO: Should we condition this on whether any functions might 9848 // have matched, or is it more appropriate to do that in callers? 9849 // TODO: a fixit wouldn't hurt. 9850 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 9851 << TargetType << OvlExpr->getSourceRange(); 9852 } 9853 9854 bool IsStaticMemberFunctionFromBoundPointer() const { 9855 return StaticMemberFunctionFromBoundPointer; 9856 } 9857 9858 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 9859 S.Diag(OvlExpr->getLocStart(), 9860 diag::err_invalid_form_pointer_member_function) 9861 << OvlExpr->getSourceRange(); 9862 } 9863 9864 void ComplainOfInvalidConversion() const { 9865 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 9866 << OvlExpr->getName() << TargetType; 9867 } 9868 9869 void ComplainMultipleMatchesFound() const { 9870 assert(Matches.size() > 1); 9871 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 9872 << OvlExpr->getName() 9873 << OvlExpr->getSourceRange(); 9874 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType); 9875 } 9876 9877 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 9878 9879 int getNumMatches() const { return Matches.size(); } 9880 9881 FunctionDecl* getMatchingFunctionDecl() const { 9882 if (Matches.size() != 1) return 0; 9883 return Matches[0].second; 9884 } 9885 9886 const DeclAccessPair* getMatchingFunctionAccessPair() const { 9887 if (Matches.size() != 1) return 0; 9888 return &Matches[0].first; 9889 } 9890 }; 9891 9892 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 9893 /// an overloaded function (C++ [over.over]), where @p From is an 9894 /// expression with overloaded function type and @p ToType is the type 9895 /// we're trying to resolve to. For example: 9896 /// 9897 /// @code 9898 /// int f(double); 9899 /// int f(int); 9900 /// 9901 /// int (*pfd)(double) = f; // selects f(double) 9902 /// @endcode 9903 /// 9904 /// This routine returns the resulting FunctionDecl if it could be 9905 /// resolved, and NULL otherwise. When @p Complain is true, this 9906 /// routine will emit diagnostics if there is an error. 9907 FunctionDecl * 9908 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 9909 QualType TargetType, 9910 bool Complain, 9911 DeclAccessPair &FoundResult, 9912 bool *pHadMultipleCandidates) { 9913 assert(AddressOfExpr->getType() == Context.OverloadTy); 9914 9915 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 9916 Complain); 9917 int NumMatches = Resolver.getNumMatches(); 9918 FunctionDecl* Fn = 0; 9919 if (NumMatches == 0 && Complain) { 9920 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 9921 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 9922 else 9923 Resolver.ComplainNoMatchesFound(); 9924 } 9925 else if (NumMatches > 1 && Complain) 9926 Resolver.ComplainMultipleMatchesFound(); 9927 else if (NumMatches == 1) { 9928 Fn = Resolver.getMatchingFunctionDecl(); 9929 assert(Fn); 9930 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 9931 if (Complain) { 9932 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 9933 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 9934 else 9935 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 9936 } 9937 } 9938 9939 if (pHadMultipleCandidates) 9940 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 9941 return Fn; 9942 } 9943 9944 /// \brief Given an expression that refers to an overloaded function, try to 9945 /// resolve that overloaded function expression down to a single function. 9946 /// 9947 /// This routine can only resolve template-ids that refer to a single function 9948 /// template, where that template-id refers to a single template whose template 9949 /// arguments are either provided by the template-id or have defaults, 9950 /// as described in C++0x [temp.arg.explicit]p3. 9951 /// 9952 /// If no template-ids are found, no diagnostics are emitted and NULL is 9953 /// returned. 9954 FunctionDecl * 9955 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 9956 bool Complain, 9957 DeclAccessPair *FoundResult) { 9958 // C++ [over.over]p1: 9959 // [...] [Note: any redundant set of parentheses surrounding the 9960 // overloaded function name is ignored (5.1). ] 9961 // C++ [over.over]p1: 9962 // [...] The overloaded function name can be preceded by the & 9963 // operator. 9964 9965 // If we didn't actually find any template-ids, we're done. 9966 if (!ovl->hasExplicitTemplateArgs()) 9967 return 0; 9968 9969 TemplateArgumentListInfo ExplicitTemplateArgs; 9970 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 9971 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 9972 9973 // Look through all of the overloaded functions, searching for one 9974 // whose type matches exactly. 9975 FunctionDecl *Matched = 0; 9976 for (UnresolvedSetIterator I = ovl->decls_begin(), 9977 E = ovl->decls_end(); I != E; ++I) { 9978 // C++0x [temp.arg.explicit]p3: 9979 // [...] In contexts where deduction is done and fails, or in contexts 9980 // where deduction is not done, if a template argument list is 9981 // specified and it, along with any default template arguments, 9982 // identifies a single function template specialization, then the 9983 // template-id is an lvalue for the function template specialization. 9984 FunctionTemplateDecl *FunctionTemplate 9985 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 9986 9987 // C++ [over.over]p2: 9988 // If the name is a function template, template argument deduction is 9989 // done (14.8.2.2), and if the argument deduction succeeds, the 9990 // resulting template argument list is used to generate a single 9991 // function template specialization, which is added to the set of 9992 // overloaded functions considered. 9993 FunctionDecl *Specialization = 0; 9994 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 9995 if (TemplateDeductionResult Result 9996 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 9997 Specialization, Info, 9998 /*InOverloadResolution=*/true)) { 9999 // Make a note of the failed deduction for diagnostics. 10000 // TODO: Actually use the failed-deduction info? 10001 FailedCandidates.addCandidate() 10002 .set(FunctionTemplate->getTemplatedDecl(), 10003 MakeDeductionFailureInfo(Context, Result, Info)); 10004 continue; 10005 } 10006 10007 assert(Specialization && "no specialization and no error?"); 10008 10009 // Multiple matches; we can't resolve to a single declaration. 10010 if (Matched) { 10011 if (Complain) { 10012 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 10013 << ovl->getName(); 10014 NoteAllOverloadCandidates(ovl); 10015 } 10016 return 0; 10017 } 10018 10019 Matched = Specialization; 10020 if (FoundResult) *FoundResult = I.getPair(); 10021 } 10022 10023 if (Matched && getLangOpts().CPlusPlus1y && 10024 Matched->getReturnType()->isUndeducedType() && 10025 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 10026 return 0; 10027 10028 return Matched; 10029 } 10030 10031 10032 10033 10034 // Resolve and fix an overloaded expression that can be resolved 10035 // because it identifies a single function template specialization. 10036 // 10037 // Last three arguments should only be supplied if Complain = true 10038 // 10039 // Return true if it was logically possible to so resolve the 10040 // expression, regardless of whether or not it succeeded. Always 10041 // returns true if 'complain' is set. 10042 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 10043 ExprResult &SrcExpr, bool doFunctionPointerConverion, 10044 bool complain, const SourceRange& OpRangeForComplaining, 10045 QualType DestTypeForComplaining, 10046 unsigned DiagIDForComplaining) { 10047 assert(SrcExpr.get()->getType() == Context.OverloadTy); 10048 10049 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 10050 10051 DeclAccessPair found; 10052 ExprResult SingleFunctionExpression; 10053 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 10054 ovl.Expression, /*complain*/ false, &found)) { 10055 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 10056 SrcExpr = ExprError(); 10057 return true; 10058 } 10059 10060 // It is only correct to resolve to an instance method if we're 10061 // resolving a form that's permitted to be a pointer to member. 10062 // Otherwise we'll end up making a bound member expression, which 10063 // is illegal in all the contexts we resolve like this. 10064 if (!ovl.HasFormOfMemberPointer && 10065 isa<CXXMethodDecl>(fn) && 10066 cast<CXXMethodDecl>(fn)->isInstance()) { 10067 if (!complain) return false; 10068 10069 Diag(ovl.Expression->getExprLoc(), 10070 diag::err_bound_member_function) 10071 << 0 << ovl.Expression->getSourceRange(); 10072 10073 // TODO: I believe we only end up here if there's a mix of 10074 // static and non-static candidates (otherwise the expression 10075 // would have 'bound member' type, not 'overload' type). 10076 // Ideally we would note which candidate was chosen and why 10077 // the static candidates were rejected. 10078 SrcExpr = ExprError(); 10079 return true; 10080 } 10081 10082 // Fix the expression to refer to 'fn'. 10083 SingleFunctionExpression = 10084 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn)); 10085 10086 // If desired, do function-to-pointer decay. 10087 if (doFunctionPointerConverion) { 10088 SingleFunctionExpression = 10089 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take()); 10090 if (SingleFunctionExpression.isInvalid()) { 10091 SrcExpr = ExprError(); 10092 return true; 10093 } 10094 } 10095 } 10096 10097 if (!SingleFunctionExpression.isUsable()) { 10098 if (complain) { 10099 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 10100 << ovl.Expression->getName() 10101 << DestTypeForComplaining 10102 << OpRangeForComplaining 10103 << ovl.Expression->getQualifierLoc().getSourceRange(); 10104 NoteAllOverloadCandidates(SrcExpr.get()); 10105 10106 SrcExpr = ExprError(); 10107 return true; 10108 } 10109 10110 return false; 10111 } 10112 10113 SrcExpr = SingleFunctionExpression; 10114 return true; 10115 } 10116 10117 /// \brief Add a single candidate to the overload set. 10118 static void AddOverloadedCallCandidate(Sema &S, 10119 DeclAccessPair FoundDecl, 10120 TemplateArgumentListInfo *ExplicitTemplateArgs, 10121 ArrayRef<Expr *> Args, 10122 OverloadCandidateSet &CandidateSet, 10123 bool PartialOverloading, 10124 bool KnownValid) { 10125 NamedDecl *Callee = FoundDecl.getDecl(); 10126 if (isa<UsingShadowDecl>(Callee)) 10127 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 10128 10129 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 10130 if (ExplicitTemplateArgs) { 10131 assert(!KnownValid && "Explicit template arguments?"); 10132 return; 10133 } 10134 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false, 10135 PartialOverloading); 10136 return; 10137 } 10138 10139 if (FunctionTemplateDecl *FuncTemplate 10140 = dyn_cast<FunctionTemplateDecl>(Callee)) { 10141 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 10142 ExplicitTemplateArgs, Args, CandidateSet); 10143 return; 10144 } 10145 10146 assert(!KnownValid && "unhandled case in overloaded call candidate"); 10147 } 10148 10149 /// \brief Add the overload candidates named by callee and/or found by argument 10150 /// dependent lookup to the given overload set. 10151 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 10152 ArrayRef<Expr *> Args, 10153 OverloadCandidateSet &CandidateSet, 10154 bool PartialOverloading) { 10155 10156 #ifndef NDEBUG 10157 // Verify that ArgumentDependentLookup is consistent with the rules 10158 // in C++0x [basic.lookup.argdep]p3: 10159 // 10160 // Let X be the lookup set produced by unqualified lookup (3.4.1) 10161 // and let Y be the lookup set produced by argument dependent 10162 // lookup (defined as follows). If X contains 10163 // 10164 // -- a declaration of a class member, or 10165 // 10166 // -- a block-scope function declaration that is not a 10167 // using-declaration, or 10168 // 10169 // -- a declaration that is neither a function or a function 10170 // template 10171 // 10172 // then Y is empty. 10173 10174 if (ULE->requiresADL()) { 10175 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10176 E = ULE->decls_end(); I != E; ++I) { 10177 assert(!(*I)->getDeclContext()->isRecord()); 10178 assert(isa<UsingShadowDecl>(*I) || 10179 !(*I)->getDeclContext()->isFunctionOrMethod()); 10180 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 10181 } 10182 } 10183 #endif 10184 10185 // It would be nice to avoid this copy. 10186 TemplateArgumentListInfo TABuffer; 10187 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 10188 if (ULE->hasExplicitTemplateArgs()) { 10189 ULE->copyTemplateArgumentsInto(TABuffer); 10190 ExplicitTemplateArgs = &TABuffer; 10191 } 10192 10193 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10194 E = ULE->decls_end(); I != E; ++I) 10195 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 10196 CandidateSet, PartialOverloading, 10197 /*KnownValid*/ true); 10198 10199 if (ULE->requiresADL()) 10200 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false, 10201 ULE->getExprLoc(), 10202 Args, ExplicitTemplateArgs, 10203 CandidateSet, PartialOverloading); 10204 } 10205 10206 /// Determine whether a declaration with the specified name could be moved into 10207 /// a different namespace. 10208 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 10209 switch (Name.getCXXOverloadedOperator()) { 10210 case OO_New: case OO_Array_New: 10211 case OO_Delete: case OO_Array_Delete: 10212 return false; 10213 10214 default: 10215 return true; 10216 } 10217 } 10218 10219 /// Attempt to recover from an ill-formed use of a non-dependent name in a 10220 /// template, where the non-dependent name was declared after the template 10221 /// was defined. This is common in code written for a compilers which do not 10222 /// correctly implement two-stage name lookup. 10223 /// 10224 /// Returns true if a viable candidate was found and a diagnostic was issued. 10225 static bool 10226 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 10227 const CXXScopeSpec &SS, LookupResult &R, 10228 TemplateArgumentListInfo *ExplicitTemplateArgs, 10229 ArrayRef<Expr *> Args) { 10230 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 10231 return false; 10232 10233 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 10234 if (DC->isTransparentContext()) 10235 continue; 10236 10237 SemaRef.LookupQualifiedName(R, DC); 10238 10239 if (!R.empty()) { 10240 R.suppressDiagnostics(); 10241 10242 if (isa<CXXRecordDecl>(DC)) { 10243 // Don't diagnose names we find in classes; we get much better 10244 // diagnostics for these from DiagnoseEmptyLookup. 10245 R.clear(); 10246 return false; 10247 } 10248 10249 OverloadCandidateSet Candidates(FnLoc); 10250 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10251 AddOverloadedCallCandidate(SemaRef, I.getPair(), 10252 ExplicitTemplateArgs, Args, 10253 Candidates, false, /*KnownValid*/ false); 10254 10255 OverloadCandidateSet::iterator Best; 10256 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 10257 // No viable functions. Don't bother the user with notes for functions 10258 // which don't work and shouldn't be found anyway. 10259 R.clear(); 10260 return false; 10261 } 10262 10263 // Find the namespaces where ADL would have looked, and suggest 10264 // declaring the function there instead. 10265 Sema::AssociatedNamespaceSet AssociatedNamespaces; 10266 Sema::AssociatedClassSet AssociatedClasses; 10267 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 10268 AssociatedNamespaces, 10269 AssociatedClasses); 10270 Sema::AssociatedNamespaceSet SuggestedNamespaces; 10271 if (canBeDeclaredInNamespace(R.getLookupName())) { 10272 DeclContext *Std = SemaRef.getStdNamespace(); 10273 for (Sema::AssociatedNamespaceSet::iterator 10274 it = AssociatedNamespaces.begin(), 10275 end = AssociatedNamespaces.end(); it != end; ++it) { 10276 // Never suggest declaring a function within namespace 'std'. 10277 if (Std && Std->Encloses(*it)) 10278 continue; 10279 10280 // Never suggest declaring a function within a namespace with a 10281 // reserved name, like __gnu_cxx. 10282 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 10283 if (NS && 10284 NS->getQualifiedNameAsString().find("__") != std::string::npos) 10285 continue; 10286 10287 SuggestedNamespaces.insert(*it); 10288 } 10289 } 10290 10291 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 10292 << R.getLookupName(); 10293 if (SuggestedNamespaces.empty()) { 10294 SemaRef.Diag(Best->Function->getLocation(), 10295 diag::note_not_found_by_two_phase_lookup) 10296 << R.getLookupName() << 0; 10297 } else if (SuggestedNamespaces.size() == 1) { 10298 SemaRef.Diag(Best->Function->getLocation(), 10299 diag::note_not_found_by_two_phase_lookup) 10300 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 10301 } else { 10302 // FIXME: It would be useful to list the associated namespaces here, 10303 // but the diagnostics infrastructure doesn't provide a way to produce 10304 // a localized representation of a list of items. 10305 SemaRef.Diag(Best->Function->getLocation(), 10306 diag::note_not_found_by_two_phase_lookup) 10307 << R.getLookupName() << 2; 10308 } 10309 10310 // Try to recover by calling this function. 10311 return true; 10312 } 10313 10314 R.clear(); 10315 } 10316 10317 return false; 10318 } 10319 10320 /// Attempt to recover from ill-formed use of a non-dependent operator in a 10321 /// template, where the non-dependent operator was declared after the template 10322 /// was defined. 10323 /// 10324 /// Returns true if a viable candidate was found and a diagnostic was issued. 10325 static bool 10326 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 10327 SourceLocation OpLoc, 10328 ArrayRef<Expr *> Args) { 10329 DeclarationName OpName = 10330 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 10331 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 10332 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 10333 /*ExplicitTemplateArgs=*/0, Args); 10334 } 10335 10336 namespace { 10337 class BuildRecoveryCallExprRAII { 10338 Sema &SemaRef; 10339 public: 10340 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 10341 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 10342 SemaRef.IsBuildingRecoveryCallExpr = true; 10343 } 10344 10345 ~BuildRecoveryCallExprRAII() { 10346 SemaRef.IsBuildingRecoveryCallExpr = false; 10347 } 10348 }; 10349 10350 } 10351 10352 /// Attempts to recover from a call where no functions were found. 10353 /// 10354 /// Returns true if new candidates were found. 10355 static ExprResult 10356 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10357 UnresolvedLookupExpr *ULE, 10358 SourceLocation LParenLoc, 10359 llvm::MutableArrayRef<Expr *> Args, 10360 SourceLocation RParenLoc, 10361 bool EmptyLookup, bool AllowTypoCorrection) { 10362 // Do not try to recover if it is already building a recovery call. 10363 // This stops infinite loops for template instantiations like 10364 // 10365 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 10366 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 10367 // 10368 if (SemaRef.IsBuildingRecoveryCallExpr) 10369 return ExprError(); 10370 BuildRecoveryCallExprRAII RCE(SemaRef); 10371 10372 CXXScopeSpec SS; 10373 SS.Adopt(ULE->getQualifierLoc()); 10374 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 10375 10376 TemplateArgumentListInfo TABuffer; 10377 TemplateArgumentListInfo *ExplicitTemplateArgs = 0; 10378 if (ULE->hasExplicitTemplateArgs()) { 10379 ULE->copyTemplateArgumentsInto(TABuffer); 10380 ExplicitTemplateArgs = &TABuffer; 10381 } 10382 10383 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 10384 Sema::LookupOrdinaryName); 10385 FunctionCallFilterCCC Validator(SemaRef, Args.size(), 10386 ExplicitTemplateArgs != 0, 10387 dyn_cast<MemberExpr>(Fn)); 10388 NoTypoCorrectionCCC RejectAll; 10389 CorrectionCandidateCallback *CCC = AllowTypoCorrection ? 10390 (CorrectionCandidateCallback*)&Validator : 10391 (CorrectionCandidateCallback*)&RejectAll; 10392 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 10393 ExplicitTemplateArgs, Args) && 10394 (!EmptyLookup || 10395 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC, 10396 ExplicitTemplateArgs, Args))) 10397 return ExprError(); 10398 10399 assert(!R.empty() && "lookup results empty despite recovery"); 10400 10401 // Build an implicit member call if appropriate. Just drop the 10402 // casts and such from the call, we don't really care. 10403 ExprResult NewFn = ExprError(); 10404 if ((*R.begin())->isCXXClassMember()) 10405 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, 10406 R, ExplicitTemplateArgs); 10407 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 10408 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 10409 ExplicitTemplateArgs); 10410 else 10411 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 10412 10413 if (NewFn.isInvalid()) 10414 return ExprError(); 10415 10416 // This shouldn't cause an infinite loop because we're giving it 10417 // an expression with viable lookup results, which should never 10418 // end up here. 10419 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc, 10420 MultiExprArg(Args.data(), Args.size()), 10421 RParenLoc); 10422 } 10423 10424 /// \brief Constructs and populates an OverloadedCandidateSet from 10425 /// the given function. 10426 /// \returns true when an the ExprResult output parameter has been set. 10427 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 10428 UnresolvedLookupExpr *ULE, 10429 MultiExprArg Args, 10430 SourceLocation RParenLoc, 10431 OverloadCandidateSet *CandidateSet, 10432 ExprResult *Result) { 10433 #ifndef NDEBUG 10434 if (ULE->requiresADL()) { 10435 // To do ADL, we must have found an unqualified name. 10436 assert(!ULE->getQualifier() && "qualified name with ADL"); 10437 10438 // We don't perform ADL for implicit declarations of builtins. 10439 // Verify that this was correctly set up. 10440 FunctionDecl *F; 10441 if (ULE->decls_begin() + 1 == ULE->decls_end() && 10442 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 10443 F->getBuiltinID() && F->isImplicit()) 10444 llvm_unreachable("performing ADL for builtin"); 10445 10446 // We don't perform ADL in C. 10447 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 10448 } 10449 #endif 10450 10451 UnbridgedCastsSet UnbridgedCasts; 10452 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 10453 *Result = ExprError(); 10454 return true; 10455 } 10456 10457 // Add the functions denoted by the callee to the set of candidate 10458 // functions, including those from argument-dependent lookup. 10459 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 10460 10461 // If we found nothing, try to recover. 10462 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail 10463 // out if it fails. 10464 if (CandidateSet->empty()) { 10465 // In Microsoft mode, if we are inside a template class member function then 10466 // create a type dependent CallExpr. The goal is to postpone name lookup 10467 // to instantiation time to be able to search into type dependent base 10468 // classes. 10469 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() && 10470 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 10471 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, 10472 Context.DependentTy, VK_RValue, 10473 RParenLoc); 10474 CE->setTypeDependent(true); 10475 *Result = Owned(CE); 10476 return true; 10477 } 10478 return false; 10479 } 10480 10481 UnbridgedCasts.restore(); 10482 return false; 10483 } 10484 10485 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 10486 /// the completed call expression. If overload resolution fails, emits 10487 /// diagnostics and returns ExprError() 10488 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10489 UnresolvedLookupExpr *ULE, 10490 SourceLocation LParenLoc, 10491 MultiExprArg Args, 10492 SourceLocation RParenLoc, 10493 Expr *ExecConfig, 10494 OverloadCandidateSet *CandidateSet, 10495 OverloadCandidateSet::iterator *Best, 10496 OverloadingResult OverloadResult, 10497 bool AllowTypoCorrection) { 10498 if (CandidateSet->empty()) 10499 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 10500 RParenLoc, /*EmptyLookup=*/true, 10501 AllowTypoCorrection); 10502 10503 switch (OverloadResult) { 10504 case OR_Success: { 10505 FunctionDecl *FDecl = (*Best)->Function; 10506 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 10507 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 10508 return ExprError(); 10509 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10510 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10511 ExecConfig); 10512 } 10513 10514 case OR_No_Viable_Function: { 10515 // Try to recover by looking for viable functions which the user might 10516 // have meant to call. 10517 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 10518 Args, RParenLoc, 10519 /*EmptyLookup=*/false, 10520 AllowTypoCorrection); 10521 if (!Recovery.isInvalid()) 10522 return Recovery; 10523 10524 SemaRef.Diag(Fn->getLocStart(), 10525 diag::err_ovl_no_viable_function_in_call) 10526 << ULE->getName() << Fn->getSourceRange(); 10527 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10528 break; 10529 } 10530 10531 case OR_Ambiguous: 10532 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 10533 << ULE->getName() << Fn->getSourceRange(); 10534 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 10535 break; 10536 10537 case OR_Deleted: { 10538 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 10539 << (*Best)->Function->isDeleted() 10540 << ULE->getName() 10541 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 10542 << Fn->getSourceRange(); 10543 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 10544 10545 // We emitted an error for the unvailable/deleted function call but keep 10546 // the call in the AST. 10547 FunctionDecl *FDecl = (*Best)->Function; 10548 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 10549 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 10550 ExecConfig); 10551 } 10552 } 10553 10554 // Overload resolution failed. 10555 return ExprError(); 10556 } 10557 10558 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 10559 /// (which eventually refers to the declaration Func) and the call 10560 /// arguments Args/NumArgs, attempt to resolve the function call down 10561 /// to a specific function. If overload resolution succeeds, returns 10562 /// the call expression produced by overload resolution. 10563 /// Otherwise, emits diagnostics and returns ExprError. 10564 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 10565 UnresolvedLookupExpr *ULE, 10566 SourceLocation LParenLoc, 10567 MultiExprArg Args, 10568 SourceLocation RParenLoc, 10569 Expr *ExecConfig, 10570 bool AllowTypoCorrection) { 10571 OverloadCandidateSet CandidateSet(Fn->getExprLoc()); 10572 ExprResult result; 10573 10574 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 10575 &result)) 10576 return result; 10577 10578 OverloadCandidateSet::iterator Best; 10579 OverloadingResult OverloadResult = 10580 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 10581 10582 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 10583 RParenLoc, ExecConfig, &CandidateSet, 10584 &Best, OverloadResult, 10585 AllowTypoCorrection); 10586 } 10587 10588 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 10589 return Functions.size() > 1 || 10590 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 10591 } 10592 10593 /// \brief Create a unary operation that may resolve to an overloaded 10594 /// operator. 10595 /// 10596 /// \param OpLoc The location of the operator itself (e.g., '*'). 10597 /// 10598 /// \param OpcIn The UnaryOperator::Opcode that describes this 10599 /// operator. 10600 /// 10601 /// \param Fns The set of non-member functions that will be 10602 /// considered by overload resolution. The caller needs to build this 10603 /// set based on the context using, e.g., 10604 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10605 /// set should not contain any member functions; those will be added 10606 /// by CreateOverloadedUnaryOp(). 10607 /// 10608 /// \param Input The input argument. 10609 ExprResult 10610 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 10611 const UnresolvedSetImpl &Fns, 10612 Expr *Input) { 10613 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 10614 10615 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 10616 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 10617 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10618 // TODO: provide better source location info. 10619 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10620 10621 if (checkPlaceholderForOverload(*this, Input)) 10622 return ExprError(); 10623 10624 Expr *Args[2] = { Input, 0 }; 10625 unsigned NumArgs = 1; 10626 10627 // For post-increment and post-decrement, add the implicit '0' as 10628 // the second argument, so that we know this is a post-increment or 10629 // post-decrement. 10630 if (Opc == UO_PostInc || Opc == UO_PostDec) { 10631 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 10632 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 10633 SourceLocation()); 10634 NumArgs = 2; 10635 } 10636 10637 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 10638 10639 if (Input->isTypeDependent()) { 10640 if (Fns.empty()) 10641 return Owned(new (Context) UnaryOperator(Input, 10642 Opc, 10643 Context.DependentTy, 10644 VK_RValue, OK_Ordinary, 10645 OpLoc)); 10646 10647 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10648 UnresolvedLookupExpr *Fn 10649 = UnresolvedLookupExpr::Create(Context, NamingClass, 10650 NestedNameSpecifierLoc(), OpNameInfo, 10651 /*ADL*/ true, IsOverloaded(Fns), 10652 Fns.begin(), Fns.end()); 10653 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, 10654 Context.DependentTy, 10655 VK_RValue, 10656 OpLoc, false)); 10657 } 10658 10659 // Build an empty overload set. 10660 OverloadCandidateSet CandidateSet(OpLoc); 10661 10662 // Add the candidates from the given function set. 10663 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false); 10664 10665 // Add operator candidates that are member functions. 10666 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10667 10668 // Add candidates from ADL. 10669 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc, 10670 ArgsArray, /*ExplicitTemplateArgs*/ 0, 10671 CandidateSet); 10672 10673 // Add builtin operator candidates. 10674 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 10675 10676 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10677 10678 // Perform overload resolution. 10679 OverloadCandidateSet::iterator Best; 10680 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10681 case OR_Success: { 10682 // We found a built-in operator or an overloaded operator. 10683 FunctionDecl *FnDecl = Best->Function; 10684 10685 if (FnDecl) { 10686 // We matched an overloaded operator. Build a call to that 10687 // operator. 10688 10689 // Convert the arguments. 10690 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10691 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl); 10692 10693 ExprResult InputRes = 10694 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0, 10695 Best->FoundDecl, Method); 10696 if (InputRes.isInvalid()) 10697 return ExprError(); 10698 Input = InputRes.take(); 10699 } else { 10700 // Convert the arguments. 10701 ExprResult InputInit 10702 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 10703 Context, 10704 FnDecl->getParamDecl(0)), 10705 SourceLocation(), 10706 Input); 10707 if (InputInit.isInvalid()) 10708 return ExprError(); 10709 Input = InputInit.take(); 10710 } 10711 10712 // Build the actual expression node. 10713 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 10714 HadMultipleCandidates, OpLoc); 10715 if (FnExpr.isInvalid()) 10716 return ExprError(); 10717 10718 // Determine the result type. 10719 QualType ResultTy = FnDecl->getReturnType(); 10720 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10721 ResultTy = ResultTy.getNonLValueExprType(Context); 10722 10723 Args[0] = Input; 10724 CallExpr *TheCall = 10725 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray, 10726 ResultTy, VK, OpLoc, false); 10727 10728 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 10729 return ExprError(); 10730 10731 return MaybeBindToTemporary(TheCall); 10732 } else { 10733 // We matched a built-in operator. Convert the arguments, then 10734 // break out so that we will build the appropriate built-in 10735 // operator node. 10736 ExprResult InputRes = 10737 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 10738 Best->Conversions[0], AA_Passing); 10739 if (InputRes.isInvalid()) 10740 return ExprError(); 10741 Input = InputRes.take(); 10742 break; 10743 } 10744 } 10745 10746 case OR_No_Viable_Function: 10747 // This is an erroneous use of an operator which can be overloaded by 10748 // a non-member function. Check for non-member operators which were 10749 // defined too late to be candidates. 10750 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 10751 // FIXME: Recover by calling the found function. 10752 return ExprError(); 10753 10754 // No viable function; fall through to handling this as a 10755 // built-in operator, which will produce an error message for us. 10756 break; 10757 10758 case OR_Ambiguous: 10759 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 10760 << UnaryOperator::getOpcodeStr(Opc) 10761 << Input->getType() 10762 << Input->getSourceRange(); 10763 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 10764 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10765 return ExprError(); 10766 10767 case OR_Deleted: 10768 Diag(OpLoc, diag::err_ovl_deleted_oper) 10769 << Best->Function->isDeleted() 10770 << UnaryOperator::getOpcodeStr(Opc) 10771 << getDeletedOrUnavailableSuffix(Best->Function) 10772 << Input->getSourceRange(); 10773 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 10774 UnaryOperator::getOpcodeStr(Opc), OpLoc); 10775 return ExprError(); 10776 } 10777 10778 // Either we found no viable overloaded operator or we matched a 10779 // built-in operator. In either case, fall through to trying to 10780 // build a built-in operation. 10781 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 10782 } 10783 10784 /// \brief Create a binary operation that may resolve to an overloaded 10785 /// operator. 10786 /// 10787 /// \param OpLoc The location of the operator itself (e.g., '+'). 10788 /// 10789 /// \param OpcIn The BinaryOperator::Opcode that describes this 10790 /// operator. 10791 /// 10792 /// \param Fns The set of non-member functions that will be 10793 /// considered by overload resolution. The caller needs to build this 10794 /// set based on the context using, e.g., 10795 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 10796 /// set should not contain any member functions; those will be added 10797 /// by CreateOverloadedBinOp(). 10798 /// 10799 /// \param LHS Left-hand argument. 10800 /// \param RHS Right-hand argument. 10801 ExprResult 10802 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 10803 unsigned OpcIn, 10804 const UnresolvedSetImpl &Fns, 10805 Expr *LHS, Expr *RHS) { 10806 Expr *Args[2] = { LHS, RHS }; 10807 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple 10808 10809 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 10810 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 10811 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 10812 10813 // If either side is type-dependent, create an appropriate dependent 10814 // expression. 10815 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 10816 if (Fns.empty()) { 10817 // If there are no functions to store, just build a dependent 10818 // BinaryOperator or CompoundAssignment. 10819 if (Opc <= BO_Assign || Opc > BO_OrAssign) 10820 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc, 10821 Context.DependentTy, 10822 VK_RValue, OK_Ordinary, 10823 OpLoc, 10824 FPFeatures.fp_contract)); 10825 10826 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc, 10827 Context.DependentTy, 10828 VK_LValue, 10829 OK_Ordinary, 10830 Context.DependentTy, 10831 Context.DependentTy, 10832 OpLoc, 10833 FPFeatures.fp_contract)); 10834 } 10835 10836 // FIXME: save results of ADL from here? 10837 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 10838 // TODO: provide better source location info in DNLoc component. 10839 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 10840 UnresolvedLookupExpr *Fn 10841 = UnresolvedLookupExpr::Create(Context, NamingClass, 10842 NestedNameSpecifierLoc(), OpNameInfo, 10843 /*ADL*/ true, IsOverloaded(Fns), 10844 Fns.begin(), Fns.end()); 10845 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args, 10846 Context.DependentTy, VK_RValue, 10847 OpLoc, FPFeatures.fp_contract)); 10848 } 10849 10850 // Always do placeholder-like conversions on the RHS. 10851 if (checkPlaceholderForOverload(*this, Args[1])) 10852 return ExprError(); 10853 10854 // Do placeholder-like conversion on the LHS; note that we should 10855 // not get here with a PseudoObject LHS. 10856 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 10857 if (checkPlaceholderForOverload(*this, Args[0])) 10858 return ExprError(); 10859 10860 // If this is the assignment operator, we only perform overload resolution 10861 // if the left-hand side is a class or enumeration type. This is actually 10862 // a hack. The standard requires that we do overload resolution between the 10863 // various built-in candidates, but as DR507 points out, this can lead to 10864 // problems. So we do it this way, which pretty much follows what GCC does. 10865 // Note that we go the traditional code path for compound assignment forms. 10866 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 10867 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10868 10869 // If this is the .* operator, which is not overloadable, just 10870 // create a built-in binary operator. 10871 if (Opc == BO_PtrMemD) 10872 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 10873 10874 // Build an empty overload set. 10875 OverloadCandidateSet CandidateSet(OpLoc); 10876 10877 // Add the candidates from the given function set. 10878 AddFunctionCandidates(Fns, Args, CandidateSet, false); 10879 10880 // Add operator candidates that are member functions. 10881 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 10882 10883 // Add candidates from ADL. 10884 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, 10885 OpLoc, Args, 10886 /*ExplicitTemplateArgs*/ 0, 10887 CandidateSet); 10888 10889 // Add builtin operator candidates. 10890 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 10891 10892 bool HadMultipleCandidates = (CandidateSet.size() > 1); 10893 10894 // Perform overload resolution. 10895 OverloadCandidateSet::iterator Best; 10896 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 10897 case OR_Success: { 10898 // We found a built-in operator or an overloaded operator. 10899 FunctionDecl *FnDecl = Best->Function; 10900 10901 if (FnDecl) { 10902 // We matched an overloaded operator. Build a call to that 10903 // operator. 10904 10905 // Convert the arguments. 10906 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 10907 // Best->Access is only meaningful for class members. 10908 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 10909 10910 ExprResult Arg1 = 10911 PerformCopyInitialization( 10912 InitializedEntity::InitializeParameter(Context, 10913 FnDecl->getParamDecl(0)), 10914 SourceLocation(), Owned(Args[1])); 10915 if (Arg1.isInvalid()) 10916 return ExprError(); 10917 10918 ExprResult Arg0 = 10919 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 10920 Best->FoundDecl, Method); 10921 if (Arg0.isInvalid()) 10922 return ExprError(); 10923 Args[0] = Arg0.takeAs<Expr>(); 10924 Args[1] = RHS = Arg1.takeAs<Expr>(); 10925 } else { 10926 // Convert the arguments. 10927 ExprResult Arg0 = PerformCopyInitialization( 10928 InitializedEntity::InitializeParameter(Context, 10929 FnDecl->getParamDecl(0)), 10930 SourceLocation(), Owned(Args[0])); 10931 if (Arg0.isInvalid()) 10932 return ExprError(); 10933 10934 ExprResult Arg1 = 10935 PerformCopyInitialization( 10936 InitializedEntity::InitializeParameter(Context, 10937 FnDecl->getParamDecl(1)), 10938 SourceLocation(), Owned(Args[1])); 10939 if (Arg1.isInvalid()) 10940 return ExprError(); 10941 Args[0] = LHS = Arg0.takeAs<Expr>(); 10942 Args[1] = RHS = Arg1.takeAs<Expr>(); 10943 } 10944 10945 // Build the actual expression node. 10946 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 10947 Best->FoundDecl, 10948 HadMultipleCandidates, OpLoc); 10949 if (FnExpr.isInvalid()) 10950 return ExprError(); 10951 10952 // Determine the result type. 10953 QualType ResultTy = FnDecl->getReturnType(); 10954 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 10955 ResultTy = ResultTy.getNonLValueExprType(Context); 10956 10957 CXXOperatorCallExpr *TheCall = 10958 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), 10959 Args, ResultTy, VK, OpLoc, 10960 FPFeatures.fp_contract); 10961 10962 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 10963 FnDecl)) 10964 return ExprError(); 10965 10966 ArrayRef<const Expr *> ArgsArray(Args, 2); 10967 // Cut off the implicit 'this'. 10968 if (isa<CXXMethodDecl>(FnDecl)) 10969 ArgsArray = ArgsArray.slice(1); 10970 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc, 10971 TheCall->getSourceRange(), VariadicDoesNotApply); 10972 10973 return MaybeBindToTemporary(TheCall); 10974 } else { 10975 // We matched a built-in operator. Convert the arguments, then 10976 // break out so that we will build the appropriate built-in 10977 // operator node. 10978 ExprResult ArgsRes0 = 10979 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 10980 Best->Conversions[0], AA_Passing); 10981 if (ArgsRes0.isInvalid()) 10982 return ExprError(); 10983 Args[0] = ArgsRes0.take(); 10984 10985 ExprResult ArgsRes1 = 10986 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 10987 Best->Conversions[1], AA_Passing); 10988 if (ArgsRes1.isInvalid()) 10989 return ExprError(); 10990 Args[1] = ArgsRes1.take(); 10991 break; 10992 } 10993 } 10994 10995 case OR_No_Viable_Function: { 10996 // C++ [over.match.oper]p9: 10997 // If the operator is the operator , [...] and there are no 10998 // viable functions, then the operator is assumed to be the 10999 // built-in operator and interpreted according to clause 5. 11000 if (Opc == BO_Comma) 11001 break; 11002 11003 // For class as left operand for assignment or compound assigment 11004 // operator do not fall through to handling in built-in, but report that 11005 // no overloaded assignment operator found 11006 ExprResult Result = ExprError(); 11007 if (Args[0]->getType()->isRecordType() && 11008 Opc >= BO_Assign && Opc <= BO_OrAssign) { 11009 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11010 << BinaryOperator::getOpcodeStr(Opc) 11011 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11012 if (Args[0]->getType()->isIncompleteType()) { 11013 Diag(OpLoc, diag::note_assign_lhs_incomplete) 11014 << Args[0]->getType() 11015 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11016 } 11017 } else { 11018 // This is an erroneous use of an operator which can be overloaded by 11019 // a non-member function. Check for non-member operators which were 11020 // defined too late to be candidates. 11021 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 11022 // FIXME: Recover by calling the found function. 11023 return ExprError(); 11024 11025 // No viable function; try to create a built-in operation, which will 11026 // produce an error. Then, show the non-viable candidates. 11027 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11028 } 11029 assert(Result.isInvalid() && 11030 "C++ binary operator overloading is missing candidates!"); 11031 if (Result.isInvalid()) 11032 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11033 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11034 return Result; 11035 } 11036 11037 case OR_Ambiguous: 11038 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 11039 << BinaryOperator::getOpcodeStr(Opc) 11040 << Args[0]->getType() << Args[1]->getType() 11041 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11042 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11043 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11044 return ExprError(); 11045 11046 case OR_Deleted: 11047 if (isImplicitlyDeleted(Best->Function)) { 11048 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11049 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 11050 << Context.getRecordType(Method->getParent()) 11051 << getSpecialMember(Method); 11052 11053 // The user probably meant to call this special member. Just 11054 // explain why it's deleted. 11055 NoteDeletedFunction(Method); 11056 return ExprError(); 11057 } else { 11058 Diag(OpLoc, diag::err_ovl_deleted_oper) 11059 << Best->Function->isDeleted() 11060 << BinaryOperator::getOpcodeStr(Opc) 11061 << getDeletedOrUnavailableSuffix(Best->Function) 11062 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11063 } 11064 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11065 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11066 return ExprError(); 11067 } 11068 11069 // We matched a built-in operator; build it. 11070 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11071 } 11072 11073 ExprResult 11074 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 11075 SourceLocation RLoc, 11076 Expr *Base, Expr *Idx) { 11077 Expr *Args[2] = { Base, Idx }; 11078 DeclarationName OpName = 11079 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 11080 11081 // If either side is type-dependent, create an appropriate dependent 11082 // expression. 11083 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11084 11085 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators 11086 // CHECKME: no 'operator' keyword? 11087 DeclarationNameInfo OpNameInfo(OpName, LLoc); 11088 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11089 UnresolvedLookupExpr *Fn 11090 = UnresolvedLookupExpr::Create(Context, NamingClass, 11091 NestedNameSpecifierLoc(), OpNameInfo, 11092 /*ADL*/ true, /*Overloaded*/ false, 11093 UnresolvedSetIterator(), 11094 UnresolvedSetIterator()); 11095 // Can't add any actual overloads yet 11096 11097 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn, 11098 Args, 11099 Context.DependentTy, 11100 VK_RValue, 11101 RLoc, false)); 11102 } 11103 11104 // Handle placeholders on both operands. 11105 if (checkPlaceholderForOverload(*this, Args[0])) 11106 return ExprError(); 11107 if (checkPlaceholderForOverload(*this, Args[1])) 11108 return ExprError(); 11109 11110 // Build an empty overload set. 11111 OverloadCandidateSet CandidateSet(LLoc); 11112 11113 // Subscript can only be overloaded as a member function. 11114 11115 // Add operator candidates that are member functions. 11116 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11117 11118 // Add builtin operator candidates. 11119 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11120 11121 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11122 11123 // Perform overload resolution. 11124 OverloadCandidateSet::iterator Best; 11125 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 11126 case OR_Success: { 11127 // We found a built-in operator or an overloaded operator. 11128 FunctionDecl *FnDecl = Best->Function; 11129 11130 if (FnDecl) { 11131 // We matched an overloaded operator. Build a call to that 11132 // operator. 11133 11134 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 11135 11136 // Convert the arguments. 11137 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 11138 ExprResult Arg0 = 11139 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0, 11140 Best->FoundDecl, Method); 11141 if (Arg0.isInvalid()) 11142 return ExprError(); 11143 Args[0] = Arg0.take(); 11144 11145 // Convert the arguments. 11146 ExprResult InputInit 11147 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11148 Context, 11149 FnDecl->getParamDecl(0)), 11150 SourceLocation(), 11151 Owned(Args[1])); 11152 if (InputInit.isInvalid()) 11153 return ExprError(); 11154 11155 Args[1] = InputInit.takeAs<Expr>(); 11156 11157 // Build the actual expression node. 11158 DeclarationNameInfo OpLocInfo(OpName, LLoc); 11159 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11160 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11161 Best->FoundDecl, 11162 HadMultipleCandidates, 11163 OpLocInfo.getLoc(), 11164 OpLocInfo.getInfo()); 11165 if (FnExpr.isInvalid()) 11166 return ExprError(); 11167 11168 // Determine the result type 11169 QualType ResultTy = FnDecl->getReturnType(); 11170 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11171 ResultTy = ResultTy.getNonLValueExprType(Context); 11172 11173 CXXOperatorCallExpr *TheCall = 11174 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 11175 FnExpr.take(), Args, 11176 ResultTy, VK, RLoc, 11177 false); 11178 11179 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 11180 return ExprError(); 11181 11182 return MaybeBindToTemporary(TheCall); 11183 } else { 11184 // We matched a built-in operator. Convert the arguments, then 11185 // break out so that we will build the appropriate built-in 11186 // operator node. 11187 ExprResult ArgsRes0 = 11188 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11189 Best->Conversions[0], AA_Passing); 11190 if (ArgsRes0.isInvalid()) 11191 return ExprError(); 11192 Args[0] = ArgsRes0.take(); 11193 11194 ExprResult ArgsRes1 = 11195 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11196 Best->Conversions[1], AA_Passing); 11197 if (ArgsRes1.isInvalid()) 11198 return ExprError(); 11199 Args[1] = ArgsRes1.take(); 11200 11201 break; 11202 } 11203 } 11204 11205 case OR_No_Viable_Function: { 11206 if (CandidateSet.empty()) 11207 Diag(LLoc, diag::err_ovl_no_oper) 11208 << Args[0]->getType() << /*subscript*/ 0 11209 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11210 else 11211 Diag(LLoc, diag::err_ovl_no_viable_subscript) 11212 << Args[0]->getType() 11213 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11214 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11215 "[]", LLoc); 11216 return ExprError(); 11217 } 11218 11219 case OR_Ambiguous: 11220 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 11221 << "[]" 11222 << Args[0]->getType() << Args[1]->getType() 11223 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11224 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11225 "[]", LLoc); 11226 return ExprError(); 11227 11228 case OR_Deleted: 11229 Diag(LLoc, diag::err_ovl_deleted_oper) 11230 << Best->Function->isDeleted() << "[]" 11231 << getDeletedOrUnavailableSuffix(Best->Function) 11232 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11233 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11234 "[]", LLoc); 11235 return ExprError(); 11236 } 11237 11238 // We matched a built-in operator; build it. 11239 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 11240 } 11241 11242 /// BuildCallToMemberFunction - Build a call to a member 11243 /// function. MemExpr is the expression that refers to the member 11244 /// function (and includes the object parameter), Args/NumArgs are the 11245 /// arguments to the function call (not including the object 11246 /// parameter). The caller needs to validate that the member 11247 /// expression refers to a non-static member function or an overloaded 11248 /// member function. 11249 ExprResult 11250 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 11251 SourceLocation LParenLoc, 11252 MultiExprArg Args, 11253 SourceLocation RParenLoc) { 11254 assert(MemExprE->getType() == Context.BoundMemberTy || 11255 MemExprE->getType() == Context.OverloadTy); 11256 11257 // Dig out the member expression. This holds both the object 11258 // argument and the member function we're referring to. 11259 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 11260 11261 // Determine whether this is a call to a pointer-to-member function. 11262 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 11263 assert(op->getType() == Context.BoundMemberTy); 11264 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 11265 11266 QualType fnType = 11267 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 11268 11269 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 11270 QualType resultType = proto->getCallResultType(Context); 11271 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 11272 11273 // Check that the object type isn't more qualified than the 11274 // member function we're calling. 11275 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 11276 11277 QualType objectType = op->getLHS()->getType(); 11278 if (op->getOpcode() == BO_PtrMemI) 11279 objectType = objectType->castAs<PointerType>()->getPointeeType(); 11280 Qualifiers objectQuals = objectType.getQualifiers(); 11281 11282 Qualifiers difference = objectQuals - funcQuals; 11283 difference.removeObjCGCAttr(); 11284 difference.removeAddressSpace(); 11285 if (difference) { 11286 std::string qualsString = difference.getAsString(); 11287 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 11288 << fnType.getUnqualifiedType() 11289 << qualsString 11290 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 11291 } 11292 11293 CXXMemberCallExpr *call 11294 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11295 resultType, valueKind, RParenLoc); 11296 11297 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 11298 call, 0)) 11299 return ExprError(); 11300 11301 if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc)) 11302 return ExprError(); 11303 11304 if (CheckOtherCall(call, proto)) 11305 return ExprError(); 11306 11307 return MaybeBindToTemporary(call); 11308 } 11309 11310 UnbridgedCastsSet UnbridgedCasts; 11311 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11312 return ExprError(); 11313 11314 MemberExpr *MemExpr; 11315 CXXMethodDecl *Method = 0; 11316 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public); 11317 NestedNameSpecifier *Qualifier = 0; 11318 if (isa<MemberExpr>(NakedMemExpr)) { 11319 MemExpr = cast<MemberExpr>(NakedMemExpr); 11320 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 11321 FoundDecl = MemExpr->getFoundDecl(); 11322 Qualifier = MemExpr->getQualifier(); 11323 UnbridgedCasts.restore(); 11324 } else { 11325 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 11326 Qualifier = UnresExpr->getQualifier(); 11327 11328 QualType ObjectType = UnresExpr->getBaseType(); 11329 Expr::Classification ObjectClassification 11330 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 11331 : UnresExpr->getBase()->Classify(Context); 11332 11333 // Add overload candidates 11334 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc()); 11335 11336 // FIXME: avoid copy. 11337 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 11338 if (UnresExpr->hasExplicitTemplateArgs()) { 11339 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11340 TemplateArgs = &TemplateArgsBuffer; 11341 } 11342 11343 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 11344 E = UnresExpr->decls_end(); I != E; ++I) { 11345 11346 NamedDecl *Func = *I; 11347 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 11348 if (isa<UsingShadowDecl>(Func)) 11349 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 11350 11351 11352 // Microsoft supports direct constructor calls. 11353 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 11354 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 11355 Args, CandidateSet); 11356 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 11357 // If explicit template arguments were provided, we can't call a 11358 // non-template member function. 11359 if (TemplateArgs) 11360 continue; 11361 11362 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 11363 ObjectClassification, Args, CandidateSet, 11364 /*SuppressUserConversions=*/false); 11365 } else { 11366 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 11367 I.getPair(), ActingDC, TemplateArgs, 11368 ObjectType, ObjectClassification, 11369 Args, CandidateSet, 11370 /*SuppressUsedConversions=*/false); 11371 } 11372 } 11373 11374 DeclarationName DeclName = UnresExpr->getMemberName(); 11375 11376 UnbridgedCasts.restore(); 11377 11378 OverloadCandidateSet::iterator Best; 11379 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 11380 Best)) { 11381 case OR_Success: 11382 Method = cast<CXXMethodDecl>(Best->Function); 11383 FoundDecl = Best->FoundDecl; 11384 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 11385 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 11386 return ExprError(); 11387 // If FoundDecl is different from Method (such as if one is a template 11388 // and the other a specialization), make sure DiagnoseUseOfDecl is 11389 // called on both. 11390 // FIXME: This would be more comprehensively addressed by modifying 11391 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 11392 // being used. 11393 if (Method != FoundDecl.getDecl() && 11394 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 11395 return ExprError(); 11396 break; 11397 11398 case OR_No_Viable_Function: 11399 Diag(UnresExpr->getMemberLoc(), 11400 diag::err_ovl_no_viable_member_function_in_call) 11401 << DeclName << MemExprE->getSourceRange(); 11402 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11403 // FIXME: Leaking incoming expressions! 11404 return ExprError(); 11405 11406 case OR_Ambiguous: 11407 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 11408 << DeclName << MemExprE->getSourceRange(); 11409 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11410 // FIXME: Leaking incoming expressions! 11411 return ExprError(); 11412 11413 case OR_Deleted: 11414 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 11415 << Best->Function->isDeleted() 11416 << DeclName 11417 << getDeletedOrUnavailableSuffix(Best->Function) 11418 << MemExprE->getSourceRange(); 11419 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11420 // FIXME: Leaking incoming expressions! 11421 return ExprError(); 11422 } 11423 11424 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 11425 11426 // If overload resolution picked a static member, build a 11427 // non-member call based on that function. 11428 if (Method->isStatic()) { 11429 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 11430 RParenLoc); 11431 } 11432 11433 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 11434 } 11435 11436 QualType ResultType = Method->getReturnType(); 11437 ExprValueKind VK = Expr::getValueKindForType(ResultType); 11438 ResultType = ResultType.getNonLValueExprType(Context); 11439 11440 assert(Method && "Member call to something that isn't a method?"); 11441 CXXMemberCallExpr *TheCall = 11442 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11443 ResultType, VK, RParenLoc); 11444 11445 // Check for a valid return type. 11446 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 11447 TheCall, Method)) 11448 return ExprError(); 11449 11450 // Convert the object argument (for a non-static member function call). 11451 // We only need to do this if there was actually an overload; otherwise 11452 // it was done at lookup. 11453 if (!Method->isStatic()) { 11454 ExprResult ObjectArg = 11455 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 11456 FoundDecl, Method); 11457 if (ObjectArg.isInvalid()) 11458 return ExprError(); 11459 MemExpr->setBase(ObjectArg.take()); 11460 } 11461 11462 // Convert the rest of the arguments 11463 const FunctionProtoType *Proto = 11464 Method->getType()->getAs<FunctionProtoType>(); 11465 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 11466 RParenLoc)) 11467 return ExprError(); 11468 11469 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11470 11471 if (CheckFunctionCall(Method, TheCall, Proto)) 11472 return ExprError(); 11473 11474 if ((isa<CXXConstructorDecl>(CurContext) || 11475 isa<CXXDestructorDecl>(CurContext)) && 11476 TheCall->getMethodDecl()->isPure()) { 11477 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 11478 11479 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) { 11480 Diag(MemExpr->getLocStart(), 11481 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 11482 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 11483 << MD->getParent()->getDeclName(); 11484 11485 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 11486 } 11487 } 11488 return MaybeBindToTemporary(TheCall); 11489 } 11490 11491 /// BuildCallToObjectOfClassType - Build a call to an object of class 11492 /// type (C++ [over.call.object]), which can end up invoking an 11493 /// overloaded function call operator (@c operator()) or performing a 11494 /// user-defined conversion on the object argument. 11495 ExprResult 11496 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 11497 SourceLocation LParenLoc, 11498 MultiExprArg Args, 11499 SourceLocation RParenLoc) { 11500 if (checkPlaceholderForOverload(*this, Obj)) 11501 return ExprError(); 11502 ExprResult Object = Owned(Obj); 11503 11504 UnbridgedCastsSet UnbridgedCasts; 11505 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11506 return ExprError(); 11507 11508 assert(Object.get()->getType()->isRecordType() && "Requires object type argument"); 11509 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 11510 11511 // C++ [over.call.object]p1: 11512 // If the primary-expression E in the function call syntax 11513 // evaluates to a class object of type "cv T", then the set of 11514 // candidate functions includes at least the function call 11515 // operators of T. The function call operators of T are obtained by 11516 // ordinary lookup of the name operator() in the context of 11517 // (E).operator(). 11518 OverloadCandidateSet CandidateSet(LParenLoc); 11519 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 11520 11521 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 11522 diag::err_incomplete_object_call, Object.get())) 11523 return true; 11524 11525 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 11526 LookupQualifiedName(R, Record->getDecl()); 11527 R.suppressDiagnostics(); 11528 11529 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11530 Oper != OperEnd; ++Oper) { 11531 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 11532 Object.get()->Classify(Context), 11533 Args, CandidateSet, 11534 /*SuppressUserConversions=*/ false); 11535 } 11536 11537 // C++ [over.call.object]p2: 11538 // In addition, for each (non-explicit in C++0x) conversion function 11539 // declared in T of the form 11540 // 11541 // operator conversion-type-id () cv-qualifier; 11542 // 11543 // where cv-qualifier is the same cv-qualification as, or a 11544 // greater cv-qualification than, cv, and where conversion-type-id 11545 // denotes the type "pointer to function of (P1,...,Pn) returning 11546 // R", or the type "reference to pointer to function of 11547 // (P1,...,Pn) returning R", or the type "reference to function 11548 // of (P1,...,Pn) returning R", a surrogate call function [...] 11549 // is also considered as a candidate function. Similarly, 11550 // surrogate call functions are added to the set of candidate 11551 // functions for each conversion function declared in an 11552 // accessible base class provided the function is not hidden 11553 // within T by another intervening declaration. 11554 std::pair<CXXRecordDecl::conversion_iterator, 11555 CXXRecordDecl::conversion_iterator> Conversions 11556 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 11557 for (CXXRecordDecl::conversion_iterator 11558 I = Conversions.first, E = Conversions.second; I != E; ++I) { 11559 NamedDecl *D = *I; 11560 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 11561 if (isa<UsingShadowDecl>(D)) 11562 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 11563 11564 // Skip over templated conversion functions; they aren't 11565 // surrogates. 11566 if (isa<FunctionTemplateDecl>(D)) 11567 continue; 11568 11569 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 11570 if (!Conv->isExplicit()) { 11571 // Strip the reference type (if any) and then the pointer type (if 11572 // any) to get down to what might be a function type. 11573 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 11574 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 11575 ConvType = ConvPtrType->getPointeeType(); 11576 11577 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 11578 { 11579 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 11580 Object.get(), Args, CandidateSet); 11581 } 11582 } 11583 } 11584 11585 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11586 11587 // Perform overload resolution. 11588 OverloadCandidateSet::iterator Best; 11589 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 11590 Best)) { 11591 case OR_Success: 11592 // Overload resolution succeeded; we'll build the appropriate call 11593 // below. 11594 break; 11595 11596 case OR_No_Viable_Function: 11597 if (CandidateSet.empty()) 11598 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 11599 << Object.get()->getType() << /*call*/ 1 11600 << Object.get()->getSourceRange(); 11601 else 11602 Diag(Object.get()->getLocStart(), 11603 diag::err_ovl_no_viable_object_call) 11604 << Object.get()->getType() << Object.get()->getSourceRange(); 11605 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11606 break; 11607 11608 case OR_Ambiguous: 11609 Diag(Object.get()->getLocStart(), 11610 diag::err_ovl_ambiguous_object_call) 11611 << Object.get()->getType() << Object.get()->getSourceRange(); 11612 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11613 break; 11614 11615 case OR_Deleted: 11616 Diag(Object.get()->getLocStart(), 11617 diag::err_ovl_deleted_object_call) 11618 << Best->Function->isDeleted() 11619 << Object.get()->getType() 11620 << getDeletedOrUnavailableSuffix(Best->Function) 11621 << Object.get()->getSourceRange(); 11622 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11623 break; 11624 } 11625 11626 if (Best == CandidateSet.end()) 11627 return true; 11628 11629 UnbridgedCasts.restore(); 11630 11631 if (Best->Function == 0) { 11632 // Since there is no function declaration, this is one of the 11633 // surrogate candidates. Dig out the conversion function. 11634 CXXConversionDecl *Conv 11635 = cast<CXXConversionDecl>( 11636 Best->Conversions[0].UserDefined.ConversionFunction); 11637 11638 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11639 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 11640 return ExprError(); 11641 assert(Conv == Best->FoundDecl.getDecl() && 11642 "Found Decl & conversion-to-functionptr should be same, right?!"); 11643 // We selected one of the surrogate functions that converts the 11644 // object parameter to a function pointer. Perform the conversion 11645 // on the object argument, then let ActOnCallExpr finish the job. 11646 11647 // Create an implicit member expr to refer to the conversion operator. 11648 // and then call it. 11649 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 11650 Conv, HadMultipleCandidates); 11651 if (Call.isInvalid()) 11652 return ExprError(); 11653 // Record usage of conversion in an implicit cast. 11654 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(), 11655 CK_UserDefinedConversion, 11656 Call.get(), 0, VK_RValue)); 11657 11658 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 11659 } 11660 11661 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl); 11662 11663 // We found an overloaded operator(). Build a CXXOperatorCallExpr 11664 // that calls this method, using Object for the implicit object 11665 // parameter and passing along the remaining arguments. 11666 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11667 11668 // An error diagnostic has already been printed when parsing the declaration. 11669 if (Method->isInvalidDecl()) 11670 return ExprError(); 11671 11672 const FunctionProtoType *Proto = 11673 Method->getType()->getAs<FunctionProtoType>(); 11674 11675 unsigned NumParams = Proto->getNumParams(); 11676 11677 DeclarationNameInfo OpLocInfo( 11678 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 11679 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 11680 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11681 HadMultipleCandidates, 11682 OpLocInfo.getLoc(), 11683 OpLocInfo.getInfo()); 11684 if (NewFn.isInvalid()) 11685 return true; 11686 11687 // Build the full argument list for the method call (the implicit object 11688 // parameter is placed at the beginning of the list). 11689 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]); 11690 MethodArgs[0] = Object.get(); 11691 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 11692 11693 // Once we've built TheCall, all of the expressions are properly 11694 // owned. 11695 QualType ResultTy = Method->getReturnType(); 11696 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11697 ResultTy = ResultTy.getNonLValueExprType(Context); 11698 11699 CXXOperatorCallExpr *TheCall = new (Context) 11700 CXXOperatorCallExpr(Context, OO_Call, NewFn.take(), 11701 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 11702 ResultTy, VK, RParenLoc, false); 11703 MethodArgs.reset(); 11704 11705 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 11706 return true; 11707 11708 // We may have default arguments. If so, we need to allocate more 11709 // slots in the call for them. 11710 if (Args.size() < NumParams) 11711 TheCall->setNumArgs(Context, NumParams + 1); 11712 11713 bool IsError = false; 11714 11715 // Initialize the implicit object parameter. 11716 ExprResult ObjRes = 11717 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0, 11718 Best->FoundDecl, Method); 11719 if (ObjRes.isInvalid()) 11720 IsError = true; 11721 else 11722 Object = ObjRes; 11723 TheCall->setArg(0, Object.take()); 11724 11725 // Check the argument types. 11726 for (unsigned i = 0; i != NumParams; i++) { 11727 Expr *Arg; 11728 if (i < Args.size()) { 11729 Arg = Args[i]; 11730 11731 // Pass the argument. 11732 11733 ExprResult InputInit 11734 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11735 Context, 11736 Method->getParamDecl(i)), 11737 SourceLocation(), Arg); 11738 11739 IsError |= InputInit.isInvalid(); 11740 Arg = InputInit.takeAs<Expr>(); 11741 } else { 11742 ExprResult DefArg 11743 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 11744 if (DefArg.isInvalid()) { 11745 IsError = true; 11746 break; 11747 } 11748 11749 Arg = DefArg.takeAs<Expr>(); 11750 } 11751 11752 TheCall->setArg(i + 1, Arg); 11753 } 11754 11755 // If this is a variadic call, handle args passed through "...". 11756 if (Proto->isVariadic()) { 11757 // Promote the arguments (C99 6.5.2.2p7). 11758 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 11759 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); 11760 IsError |= Arg.isInvalid(); 11761 TheCall->setArg(i + 1, Arg.take()); 11762 } 11763 } 11764 11765 if (IsError) return true; 11766 11767 DiagnoseSentinelCalls(Method, LParenLoc, Args); 11768 11769 if (CheckFunctionCall(Method, TheCall, Proto)) 11770 return true; 11771 11772 return MaybeBindToTemporary(TheCall); 11773 } 11774 11775 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 11776 /// (if one exists), where @c Base is an expression of class type and 11777 /// @c Member is the name of the member we're trying to find. 11778 ExprResult 11779 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 11780 bool *NoArrowOperatorFound) { 11781 assert(Base->getType()->isRecordType() && 11782 "left-hand side must have class type"); 11783 11784 if (checkPlaceholderForOverload(*this, Base)) 11785 return ExprError(); 11786 11787 SourceLocation Loc = Base->getExprLoc(); 11788 11789 // C++ [over.ref]p1: 11790 // 11791 // [...] An expression x->m is interpreted as (x.operator->())->m 11792 // for a class object x of type T if T::operator->() exists and if 11793 // the operator is selected as the best match function by the 11794 // overload resolution mechanism (13.3). 11795 DeclarationName OpName = 11796 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 11797 OverloadCandidateSet CandidateSet(Loc); 11798 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 11799 11800 if (RequireCompleteType(Loc, Base->getType(), 11801 diag::err_typecheck_incomplete_tag, Base)) 11802 return ExprError(); 11803 11804 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 11805 LookupQualifiedName(R, BaseRecord->getDecl()); 11806 R.suppressDiagnostics(); 11807 11808 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 11809 Oper != OperEnd; ++Oper) { 11810 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 11811 None, CandidateSet, /*SuppressUserConversions=*/false); 11812 } 11813 11814 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11815 11816 // Perform overload resolution. 11817 OverloadCandidateSet::iterator Best; 11818 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11819 case OR_Success: 11820 // Overload resolution succeeded; we'll build the call below. 11821 break; 11822 11823 case OR_No_Viable_Function: 11824 if (CandidateSet.empty()) { 11825 QualType BaseType = Base->getType(); 11826 if (NoArrowOperatorFound) { 11827 // Report this specific error to the caller instead of emitting a 11828 // diagnostic, as requested. 11829 *NoArrowOperatorFound = true; 11830 return ExprError(); 11831 } 11832 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 11833 << BaseType << Base->getSourceRange(); 11834 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 11835 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 11836 << FixItHint::CreateReplacement(OpLoc, "."); 11837 } 11838 } else 11839 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11840 << "operator->" << Base->getSourceRange(); 11841 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11842 return ExprError(); 11843 11844 case OR_Ambiguous: 11845 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11846 << "->" << Base->getType() << Base->getSourceRange(); 11847 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 11848 return ExprError(); 11849 11850 case OR_Deleted: 11851 Diag(OpLoc, diag::err_ovl_deleted_oper) 11852 << Best->Function->isDeleted() 11853 << "->" 11854 << getDeletedOrUnavailableSuffix(Best->Function) 11855 << Base->getSourceRange(); 11856 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 11857 return ExprError(); 11858 } 11859 11860 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl); 11861 11862 // Convert the object parameter. 11863 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11864 ExprResult BaseResult = 11865 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0, 11866 Best->FoundDecl, Method); 11867 if (BaseResult.isInvalid()) 11868 return ExprError(); 11869 Base = BaseResult.take(); 11870 11871 // Build the operator call. 11872 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 11873 HadMultipleCandidates, OpLoc); 11874 if (FnExpr.isInvalid()) 11875 return ExprError(); 11876 11877 QualType ResultTy = Method->getReturnType(); 11878 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11879 ResultTy = ResultTy.getNonLValueExprType(Context); 11880 CXXOperatorCallExpr *TheCall = 11881 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(), 11882 Base, ResultTy, VK, OpLoc, false); 11883 11884 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 11885 return ExprError(); 11886 11887 return MaybeBindToTemporary(TheCall); 11888 } 11889 11890 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 11891 /// a literal operator described by the provided lookup results. 11892 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 11893 DeclarationNameInfo &SuffixInfo, 11894 ArrayRef<Expr*> Args, 11895 SourceLocation LitEndLoc, 11896 TemplateArgumentListInfo *TemplateArgs) { 11897 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 11898 11899 OverloadCandidateSet CandidateSet(UDSuffixLoc); 11900 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true, 11901 TemplateArgs); 11902 11903 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11904 11905 // Perform overload resolution. This will usually be trivial, but might need 11906 // to perform substitutions for a literal operator template. 11907 OverloadCandidateSet::iterator Best; 11908 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 11909 case OR_Success: 11910 case OR_Deleted: 11911 break; 11912 11913 case OR_No_Viable_Function: 11914 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 11915 << R.getLookupName(); 11916 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 11917 return ExprError(); 11918 11919 case OR_Ambiguous: 11920 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 11921 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 11922 return ExprError(); 11923 } 11924 11925 FunctionDecl *FD = Best->Function; 11926 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 11927 HadMultipleCandidates, 11928 SuffixInfo.getLoc(), 11929 SuffixInfo.getInfo()); 11930 if (Fn.isInvalid()) 11931 return true; 11932 11933 // Check the argument types. This should almost always be a no-op, except 11934 // that array-to-pointer decay is applied to string literals. 11935 Expr *ConvArgs[2]; 11936 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 11937 ExprResult InputInit = PerformCopyInitialization( 11938 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 11939 SourceLocation(), Args[ArgIdx]); 11940 if (InputInit.isInvalid()) 11941 return true; 11942 ConvArgs[ArgIdx] = InputInit.take(); 11943 } 11944 11945 QualType ResultTy = FD->getReturnType(); 11946 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11947 ResultTy = ResultTy.getNonLValueExprType(Context); 11948 11949 UserDefinedLiteral *UDL = 11950 new (Context) UserDefinedLiteral(Context, Fn.take(), 11951 llvm::makeArrayRef(ConvArgs, Args.size()), 11952 ResultTy, VK, LitEndLoc, UDSuffixLoc); 11953 11954 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 11955 return ExprError(); 11956 11957 if (CheckFunctionCall(FD, UDL, NULL)) 11958 return ExprError(); 11959 11960 return MaybeBindToTemporary(UDL); 11961 } 11962 11963 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 11964 /// given LookupResult is non-empty, it is assumed to describe a member which 11965 /// will be invoked. Otherwise, the function will be found via argument 11966 /// dependent lookup. 11967 /// CallExpr is set to a valid expression and FRS_Success returned on success, 11968 /// otherwise CallExpr is set to ExprError() and some non-success value 11969 /// is returned. 11970 Sema::ForRangeStatus 11971 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc, 11972 SourceLocation RangeLoc, VarDecl *Decl, 11973 BeginEndFunction BEF, 11974 const DeclarationNameInfo &NameInfo, 11975 LookupResult &MemberLookup, 11976 OverloadCandidateSet *CandidateSet, 11977 Expr *Range, ExprResult *CallExpr) { 11978 CandidateSet->clear(); 11979 if (!MemberLookup.empty()) { 11980 ExprResult MemberRef = 11981 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 11982 /*IsPtr=*/false, CXXScopeSpec(), 11983 /*TemplateKWLoc=*/SourceLocation(), 11984 /*FirstQualifierInScope=*/0, 11985 MemberLookup, 11986 /*TemplateArgs=*/0); 11987 if (MemberRef.isInvalid()) { 11988 *CallExpr = ExprError(); 11989 Diag(Range->getLocStart(), diag::note_in_for_range) 11990 << RangeLoc << BEF << Range->getType(); 11991 return FRS_DiagnosticIssued; 11992 } 11993 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0); 11994 if (CallExpr->isInvalid()) { 11995 *CallExpr = ExprError(); 11996 Diag(Range->getLocStart(), diag::note_in_for_range) 11997 << RangeLoc << BEF << Range->getType(); 11998 return FRS_DiagnosticIssued; 11999 } 12000 } else { 12001 UnresolvedSet<0> FoundNames; 12002 UnresolvedLookupExpr *Fn = 12003 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0, 12004 NestedNameSpecifierLoc(), NameInfo, 12005 /*NeedsADL=*/true, /*Overloaded=*/false, 12006 FoundNames.begin(), FoundNames.end()); 12007 12008 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 12009 CandidateSet, CallExpr); 12010 if (CandidateSet->empty() || CandidateSetError) { 12011 *CallExpr = ExprError(); 12012 return FRS_NoViableFunction; 12013 } 12014 OverloadCandidateSet::iterator Best; 12015 OverloadingResult OverloadResult = 12016 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 12017 12018 if (OverloadResult == OR_No_Viable_Function) { 12019 *CallExpr = ExprError(); 12020 return FRS_NoViableFunction; 12021 } 12022 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 12023 Loc, 0, CandidateSet, &Best, 12024 OverloadResult, 12025 /*AllowTypoCorrection=*/false); 12026 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 12027 *CallExpr = ExprError(); 12028 Diag(Range->getLocStart(), diag::note_in_for_range) 12029 << RangeLoc << BEF << Range->getType(); 12030 return FRS_DiagnosticIssued; 12031 } 12032 } 12033 return FRS_Success; 12034 } 12035 12036 12037 /// FixOverloadedFunctionReference - E is an expression that refers to 12038 /// a C++ overloaded function (possibly with some parentheses and 12039 /// perhaps a '&' around it). We have resolved the overloaded function 12040 /// to the function declaration Fn, so patch up the expression E to 12041 /// refer (possibly indirectly) to Fn. Returns the new expr. 12042 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 12043 FunctionDecl *Fn) { 12044 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 12045 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 12046 Found, Fn); 12047 if (SubExpr == PE->getSubExpr()) 12048 return PE; 12049 12050 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 12051 } 12052 12053 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 12054 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 12055 Found, Fn); 12056 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 12057 SubExpr->getType()) && 12058 "Implicit cast type cannot be determined from overload"); 12059 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 12060 if (SubExpr == ICE->getSubExpr()) 12061 return ICE; 12062 12063 return ImplicitCastExpr::Create(Context, ICE->getType(), 12064 ICE->getCastKind(), 12065 SubExpr, 0, 12066 ICE->getValueKind()); 12067 } 12068 12069 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 12070 assert(UnOp->getOpcode() == UO_AddrOf && 12071 "Can only take the address of an overloaded function"); 12072 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12073 if (Method->isStatic()) { 12074 // Do nothing: static member functions aren't any different 12075 // from non-member functions. 12076 } else { 12077 // Fix the subexpression, which really has to be an 12078 // UnresolvedLookupExpr holding an overloaded member function 12079 // or template. 12080 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12081 Found, Fn); 12082 if (SubExpr == UnOp->getSubExpr()) 12083 return UnOp; 12084 12085 assert(isa<DeclRefExpr>(SubExpr) 12086 && "fixed to something other than a decl ref"); 12087 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 12088 && "fixed to a member ref with no nested name qualifier"); 12089 12090 // We have taken the address of a pointer to member 12091 // function. Perform the computation here so that we get the 12092 // appropriate pointer to member type. 12093 QualType ClassType 12094 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 12095 QualType MemPtrType 12096 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 12097 12098 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 12099 VK_RValue, OK_Ordinary, 12100 UnOp->getOperatorLoc()); 12101 } 12102 } 12103 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12104 Found, Fn); 12105 if (SubExpr == UnOp->getSubExpr()) 12106 return UnOp; 12107 12108 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 12109 Context.getPointerType(SubExpr->getType()), 12110 VK_RValue, OK_Ordinary, 12111 UnOp->getOperatorLoc()); 12112 } 12113 12114 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12115 // FIXME: avoid copy. 12116 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 12117 if (ULE->hasExplicitTemplateArgs()) { 12118 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 12119 TemplateArgs = &TemplateArgsBuffer; 12120 } 12121 12122 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12123 ULE->getQualifierLoc(), 12124 ULE->getTemplateKeywordLoc(), 12125 Fn, 12126 /*enclosing*/ false, // FIXME? 12127 ULE->getNameLoc(), 12128 Fn->getType(), 12129 VK_LValue, 12130 Found.getDecl(), 12131 TemplateArgs); 12132 MarkDeclRefReferenced(DRE); 12133 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 12134 return DRE; 12135 } 12136 12137 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 12138 // FIXME: avoid copy. 12139 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0; 12140 if (MemExpr->hasExplicitTemplateArgs()) { 12141 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12142 TemplateArgs = &TemplateArgsBuffer; 12143 } 12144 12145 Expr *Base; 12146 12147 // If we're filling in a static method where we used to have an 12148 // implicit member access, rewrite to a simple decl ref. 12149 if (MemExpr->isImplicitAccess()) { 12150 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12151 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12152 MemExpr->getQualifierLoc(), 12153 MemExpr->getTemplateKeywordLoc(), 12154 Fn, 12155 /*enclosing*/ false, 12156 MemExpr->getMemberLoc(), 12157 Fn->getType(), 12158 VK_LValue, 12159 Found.getDecl(), 12160 TemplateArgs); 12161 MarkDeclRefReferenced(DRE); 12162 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 12163 return DRE; 12164 } else { 12165 SourceLocation Loc = MemExpr->getMemberLoc(); 12166 if (MemExpr->getQualifier()) 12167 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 12168 CheckCXXThisCapture(Loc); 12169 Base = new (Context) CXXThisExpr(Loc, 12170 MemExpr->getBaseType(), 12171 /*isImplicit=*/true); 12172 } 12173 } else 12174 Base = MemExpr->getBase(); 12175 12176 ExprValueKind valueKind; 12177 QualType type; 12178 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12179 valueKind = VK_LValue; 12180 type = Fn->getType(); 12181 } else { 12182 valueKind = VK_RValue; 12183 type = Context.BoundMemberTy; 12184 } 12185 12186 MemberExpr *ME = MemberExpr::Create(Context, Base, 12187 MemExpr->isArrow(), 12188 MemExpr->getQualifierLoc(), 12189 MemExpr->getTemplateKeywordLoc(), 12190 Fn, 12191 Found, 12192 MemExpr->getMemberNameInfo(), 12193 TemplateArgs, 12194 type, valueKind, OK_Ordinary); 12195 ME->setHadMultipleCandidates(true); 12196 MarkMemberReferenced(ME); 12197 return ME; 12198 } 12199 12200 llvm_unreachable("Invalid reference to overloaded function"); 12201 } 12202 12203 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 12204 DeclAccessPair Found, 12205 FunctionDecl *Fn) { 12206 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn)); 12207 } 12208 12209 } // end namespace clang 12210