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