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