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