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