1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file provides Sema routines for C++ overloading. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/Overload.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/CXXInheritance.h" 17 #include "clang/AST/DeclObjC.h" 18 #include "clang/AST/Expr.h" 19 #include "clang/AST/ExprCXX.h" 20 #include "clang/AST/ExprObjC.h" 21 #include "clang/AST/TypeOrdering.h" 22 #include "clang/Basic/Diagnostic.h" 23 #include "clang/Basic/DiagnosticOptions.h" 24 #include "clang/Basic/PartialDiagnostic.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/SemaInternal.h" 29 #include "clang/Sema/Template.h" 30 #include "clang/Sema/TemplateDeduction.h" 31 #include "llvm/ADT/DenseSet.h" 32 #include "llvm/ADT/STLExtras.h" 33 #include "llvm/ADT/SmallPtrSet.h" 34 #include "llvm/ADT/SmallString.h" 35 #include <algorithm> 36 #include <cstdlib> 37 38 using namespace clang; 39 using namespace sema; 40 41 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 42 return std::any_of(FD->param_begin(), FD->param_end(), 43 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>)); 44 } 45 46 /// A convenience routine for creating a decayed reference to a function. 47 static ExprResult 48 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 49 bool HadMultipleCandidates, 50 SourceLocation Loc = SourceLocation(), 51 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 52 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 53 return ExprError(); 54 // If FoundDecl is different from Fn (such as if one is a template 55 // and the other a specialization), make sure DiagnoseUseOfDecl is 56 // called on both. 57 // FIXME: This would be more comprehensively addressed by modifying 58 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 59 // being used. 60 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 61 return ExprError(); 62 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 63 VK_LValue, Loc, LocInfo); 64 if (HadMultipleCandidates) 65 DRE->setHadMultipleCandidates(true); 66 67 S.MarkDeclRefReferenced(DRE); 68 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 69 CK_FunctionToPointerDecay); 70 } 71 72 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 73 bool InOverloadResolution, 74 StandardConversionSequence &SCS, 75 bool CStyle, 76 bool AllowObjCWritebackConversion); 77 78 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 79 QualType &ToType, 80 bool InOverloadResolution, 81 StandardConversionSequence &SCS, 82 bool CStyle); 83 static OverloadingResult 84 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 85 UserDefinedConversionSequence& User, 86 OverloadCandidateSet& Conversions, 87 bool AllowExplicit, 88 bool AllowObjCConversionOnExplicit); 89 90 91 static ImplicitConversionSequence::CompareKind 92 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 93 const StandardConversionSequence& SCS1, 94 const StandardConversionSequence& SCS2); 95 96 static ImplicitConversionSequence::CompareKind 97 CompareQualificationConversions(Sema &S, 98 const StandardConversionSequence& SCS1, 99 const StandardConversionSequence& SCS2); 100 101 static ImplicitConversionSequence::CompareKind 102 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 103 const StandardConversionSequence& SCS1, 104 const StandardConversionSequence& SCS2); 105 106 /// GetConversionRank - Retrieve the implicit conversion rank 107 /// corresponding to the given implicit conversion kind. 108 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 109 static const ImplicitConversionRank 110 Rank[(int)ICK_Num_Conversion_Kinds] = { 111 ICR_Exact_Match, 112 ICR_Exact_Match, 113 ICR_Exact_Match, 114 ICR_Exact_Match, 115 ICR_Exact_Match, 116 ICR_Exact_Match, 117 ICR_Promotion, 118 ICR_Promotion, 119 ICR_Promotion, 120 ICR_Conversion, 121 ICR_Conversion, 122 ICR_Conversion, 123 ICR_Conversion, 124 ICR_Conversion, 125 ICR_Conversion, 126 ICR_Conversion, 127 ICR_Conversion, 128 ICR_Conversion, 129 ICR_Conversion, 130 ICR_Conversion, 131 ICR_Complex_Real_Conversion, 132 ICR_Conversion, 133 ICR_Conversion, 134 ICR_Writeback_Conversion, 135 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 136 // it was omitted by the patch that added 137 // ICK_Zero_Event_Conversion 138 ICR_C_Conversion 139 }; 140 return Rank[(int)Kind]; 141 } 142 143 /// GetImplicitConversionName - Return the name of this kind of 144 /// implicit conversion. 145 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 146 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 147 "No conversion", 148 "Lvalue-to-rvalue", 149 "Array-to-pointer", 150 "Function-to-pointer", 151 "Noreturn adjustment", 152 "Qualification", 153 "Integral promotion", 154 "Floating point promotion", 155 "Complex promotion", 156 "Integral conversion", 157 "Floating conversion", 158 "Complex conversion", 159 "Floating-integral conversion", 160 "Pointer conversion", 161 "Pointer-to-member conversion", 162 "Boolean conversion", 163 "Compatible-types conversion", 164 "Derived-to-base conversion", 165 "Vector conversion", 166 "Vector splat", 167 "Complex-real conversion", 168 "Block Pointer conversion", 169 "Transparent Union Conversion", 170 "Writeback conversion", 171 "OpenCL Zero Event Conversion", 172 "C specific type conversion" 173 }; 174 return Name[Kind]; 175 } 176 177 /// StandardConversionSequence - Set the standard conversion 178 /// sequence to the identity conversion. 179 void StandardConversionSequence::setAsIdentityConversion() { 180 First = ICK_Identity; 181 Second = ICK_Identity; 182 Third = ICK_Identity; 183 DeprecatedStringLiteralToCharPtr = false; 184 QualificationIncludesObjCLifetime = false; 185 ReferenceBinding = false; 186 DirectBinding = false; 187 IsLvalueReference = true; 188 BindsToFunctionLvalue = false; 189 BindsToRvalue = false; 190 BindsImplicitObjectArgumentWithoutRefQualifier = false; 191 ObjCLifetimeConversionBinding = false; 192 CopyConstructor = nullptr; 193 } 194 195 /// getRank - Retrieve the rank of this standard conversion sequence 196 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 197 /// implicit conversions. 198 ImplicitConversionRank StandardConversionSequence::getRank() const { 199 ImplicitConversionRank Rank = ICR_Exact_Match; 200 if (GetConversionRank(First) > Rank) 201 Rank = GetConversionRank(First); 202 if (GetConversionRank(Second) > Rank) 203 Rank = GetConversionRank(Second); 204 if (GetConversionRank(Third) > Rank) 205 Rank = GetConversionRank(Third); 206 return Rank; 207 } 208 209 /// isPointerConversionToBool - Determines whether this conversion is 210 /// a conversion of a pointer or pointer-to-member to bool. This is 211 /// used as part of the ranking of standard conversion sequences 212 /// (C++ 13.3.3.2p4). 213 bool StandardConversionSequence::isPointerConversionToBool() const { 214 // Note that FromType has not necessarily been transformed by the 215 // array-to-pointer or function-to-pointer implicit conversions, so 216 // check for their presence as well as checking whether FromType is 217 // a pointer. 218 if (getToType(1)->isBooleanType() && 219 (getFromType()->isPointerType() || 220 getFromType()->isObjCObjectPointerType() || 221 getFromType()->isBlockPointerType() || 222 getFromType()->isNullPtrType() || 223 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 224 return true; 225 226 return false; 227 } 228 229 /// isPointerConversionToVoidPointer - Determines whether this 230 /// conversion is a conversion of a pointer to a void pointer. This is 231 /// used as part of the ranking of standard conversion sequences (C++ 232 /// 13.3.3.2p4). 233 bool 234 StandardConversionSequence:: 235 isPointerConversionToVoidPointer(ASTContext& Context) const { 236 QualType FromType = getFromType(); 237 QualType ToType = getToType(1); 238 239 // Note that FromType has not necessarily been transformed by the 240 // array-to-pointer implicit conversion, so check for its presence 241 // and redo the conversion to get a pointer. 242 if (First == ICK_Array_To_Pointer) 243 FromType = Context.getArrayDecayedType(FromType); 244 245 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 246 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 247 return ToPtrType->getPointeeType()->isVoidType(); 248 249 return false; 250 } 251 252 /// Skip any implicit casts which could be either part of a narrowing conversion 253 /// or after one in an implicit conversion. 254 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 255 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 256 switch (ICE->getCastKind()) { 257 case CK_NoOp: 258 case CK_IntegralCast: 259 case CK_IntegralToBoolean: 260 case CK_IntegralToFloating: 261 case CK_BooleanToSignedIntegral: 262 case CK_FloatingToIntegral: 263 case CK_FloatingToBoolean: 264 case CK_FloatingCast: 265 Converted = ICE->getSubExpr(); 266 continue; 267 268 default: 269 return Converted; 270 } 271 } 272 273 return Converted; 274 } 275 276 /// Check if this standard conversion sequence represents a narrowing 277 /// conversion, according to C++11 [dcl.init.list]p7. 278 /// 279 /// \param Ctx The AST context. 280 /// \param Converted The result of applying this standard conversion sequence. 281 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 282 /// value of the expression prior to the narrowing conversion. 283 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 284 /// type of the expression prior to the narrowing conversion. 285 NarrowingKind 286 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 287 const Expr *Converted, 288 APValue &ConstantValue, 289 QualType &ConstantType) const { 290 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 291 292 // C++11 [dcl.init.list]p7: 293 // A narrowing conversion is an implicit conversion ... 294 QualType FromType = getToType(0); 295 QualType ToType = getToType(1); 296 switch (Second) { 297 // 'bool' is an integral type; dispatch to the right place to handle it. 298 case ICK_Boolean_Conversion: 299 if (FromType->isRealFloatingType()) 300 goto FloatingIntegralConversion; 301 if (FromType->isIntegralOrUnscopedEnumerationType()) 302 goto IntegralConversion; 303 // Boolean conversions can be from pointers and pointers to members 304 // [conv.bool], and those aren't considered narrowing conversions. 305 return NK_Not_Narrowing; 306 307 // -- from a floating-point type to an integer type, or 308 // 309 // -- from an integer type or unscoped enumeration type to a floating-point 310 // type, except where the source is a constant expression and the actual 311 // value after conversion will fit into the target type and will produce 312 // the original value when converted back to the original type, or 313 case ICK_Floating_Integral: 314 FloatingIntegralConversion: 315 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 316 return NK_Type_Narrowing; 317 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 318 llvm::APSInt IntConstantValue; 319 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 320 if (Initializer && 321 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 322 // Convert the integer to the floating type. 323 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 324 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 325 llvm::APFloat::rmNearestTiesToEven); 326 // And back. 327 llvm::APSInt ConvertedValue = IntConstantValue; 328 bool ignored; 329 Result.convertToInteger(ConvertedValue, 330 llvm::APFloat::rmTowardZero, &ignored); 331 // If the resulting value is different, this was a narrowing conversion. 332 if (IntConstantValue != ConvertedValue) { 333 ConstantValue = APValue(IntConstantValue); 334 ConstantType = Initializer->getType(); 335 return NK_Constant_Narrowing; 336 } 337 } else { 338 // Variables are always narrowings. 339 return NK_Variable_Narrowing; 340 } 341 } 342 return NK_Not_Narrowing; 343 344 // -- from long double to double or float, or from double to float, except 345 // where the source is a constant expression and the actual value after 346 // conversion is within the range of values that can be represented (even 347 // if it cannot be represented exactly), or 348 case ICK_Floating_Conversion: 349 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 350 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 351 // FromType is larger than ToType. 352 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 353 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 354 // Constant! 355 assert(ConstantValue.isFloat()); 356 llvm::APFloat FloatVal = ConstantValue.getFloat(); 357 // Convert the source value into the target type. 358 bool ignored; 359 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 360 Ctx.getFloatTypeSemantics(ToType), 361 llvm::APFloat::rmNearestTiesToEven, &ignored); 362 // If there was no overflow, the source value is within the range of 363 // values that can be represented. 364 if (ConvertStatus & llvm::APFloat::opOverflow) { 365 ConstantType = Initializer->getType(); 366 return NK_Constant_Narrowing; 367 } 368 } else { 369 return NK_Variable_Narrowing; 370 } 371 } 372 return NK_Not_Narrowing; 373 374 // -- from an integer type or unscoped enumeration type to an integer type 375 // that cannot represent all the values of the original type, except where 376 // the source is a constant expression and the actual value after 377 // conversion will fit into the target type and will produce the original 378 // value when converted back to the original type. 379 case ICK_Integral_Conversion: 380 IntegralConversion: { 381 assert(FromType->isIntegralOrUnscopedEnumerationType()); 382 assert(ToType->isIntegralOrUnscopedEnumerationType()); 383 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 384 const unsigned FromWidth = Ctx.getIntWidth(FromType); 385 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 386 const unsigned ToWidth = Ctx.getIntWidth(ToType); 387 388 if (FromWidth > ToWidth || 389 (FromWidth == ToWidth && FromSigned != ToSigned) || 390 (FromSigned && !ToSigned)) { 391 // Not all values of FromType can be represented in ToType. 392 llvm::APSInt InitializerValue; 393 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 394 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 395 // Such conversions on variables are always narrowing. 396 return NK_Variable_Narrowing; 397 } 398 bool Narrowing = false; 399 if (FromWidth < ToWidth) { 400 // Negative -> unsigned is narrowing. Otherwise, more bits is never 401 // narrowing. 402 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 403 Narrowing = true; 404 } else { 405 // Add a bit to the InitializerValue so we don't have to worry about 406 // signed vs. unsigned comparisons. 407 InitializerValue = InitializerValue.extend( 408 InitializerValue.getBitWidth() + 1); 409 // Convert the initializer to and from the target width and signed-ness. 410 llvm::APSInt ConvertedValue = InitializerValue; 411 ConvertedValue = ConvertedValue.trunc(ToWidth); 412 ConvertedValue.setIsSigned(ToSigned); 413 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 414 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 415 // If the result is different, this was a narrowing conversion. 416 if (ConvertedValue != InitializerValue) 417 Narrowing = true; 418 } 419 if (Narrowing) { 420 ConstantType = Initializer->getType(); 421 ConstantValue = APValue(InitializerValue); 422 return NK_Constant_Narrowing; 423 } 424 } 425 return NK_Not_Narrowing; 426 } 427 428 default: 429 // Other kinds of conversions are not narrowings. 430 return NK_Not_Narrowing; 431 } 432 } 433 434 /// dump - Print this standard conversion sequence to standard 435 /// error. Useful for debugging overloading issues. 436 void StandardConversionSequence::dump() const { 437 raw_ostream &OS = llvm::errs(); 438 bool PrintedSomething = false; 439 if (First != ICK_Identity) { 440 OS << GetImplicitConversionName(First); 441 PrintedSomething = true; 442 } 443 444 if (Second != ICK_Identity) { 445 if (PrintedSomething) { 446 OS << " -> "; 447 } 448 OS << GetImplicitConversionName(Second); 449 450 if (CopyConstructor) { 451 OS << " (by copy constructor)"; 452 } else if (DirectBinding) { 453 OS << " (direct reference binding)"; 454 } else if (ReferenceBinding) { 455 OS << " (reference binding)"; 456 } 457 PrintedSomething = true; 458 } 459 460 if (Third != ICK_Identity) { 461 if (PrintedSomething) { 462 OS << " -> "; 463 } 464 OS << GetImplicitConversionName(Third); 465 PrintedSomething = true; 466 } 467 468 if (!PrintedSomething) { 469 OS << "No conversions required"; 470 } 471 } 472 473 /// dump - Print this user-defined conversion sequence to standard 474 /// error. Useful for debugging overloading issues. 475 void UserDefinedConversionSequence::dump() const { 476 raw_ostream &OS = llvm::errs(); 477 if (Before.First || Before.Second || Before.Third) { 478 Before.dump(); 479 OS << " -> "; 480 } 481 if (ConversionFunction) 482 OS << '\'' << *ConversionFunction << '\''; 483 else 484 OS << "aggregate initialization"; 485 if (After.First || After.Second || After.Third) { 486 OS << " -> "; 487 After.dump(); 488 } 489 } 490 491 /// dump - Print this implicit conversion sequence to standard 492 /// error. Useful for debugging overloading issues. 493 void ImplicitConversionSequence::dump() const { 494 raw_ostream &OS = llvm::errs(); 495 if (isStdInitializerListElement()) 496 OS << "Worst std::initializer_list element conversion: "; 497 switch (ConversionKind) { 498 case StandardConversion: 499 OS << "Standard conversion: "; 500 Standard.dump(); 501 break; 502 case UserDefinedConversion: 503 OS << "User-defined conversion: "; 504 UserDefined.dump(); 505 break; 506 case EllipsisConversion: 507 OS << "Ellipsis conversion"; 508 break; 509 case AmbiguousConversion: 510 OS << "Ambiguous conversion"; 511 break; 512 case BadConversion: 513 OS << "Bad conversion"; 514 break; 515 } 516 517 OS << "\n"; 518 } 519 520 void AmbiguousConversionSequence::construct() { 521 new (&conversions()) ConversionSet(); 522 } 523 524 void AmbiguousConversionSequence::destruct() { 525 conversions().~ConversionSet(); 526 } 527 528 void 529 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 530 FromTypePtr = O.FromTypePtr; 531 ToTypePtr = O.ToTypePtr; 532 new (&conversions()) ConversionSet(O.conversions()); 533 } 534 535 namespace { 536 // Structure used by DeductionFailureInfo to store 537 // template argument information. 538 struct DFIArguments { 539 TemplateArgument FirstArg; 540 TemplateArgument SecondArg; 541 }; 542 // Structure used by DeductionFailureInfo to store 543 // template parameter and template argument information. 544 struct DFIParamWithArguments : DFIArguments { 545 TemplateParameter Param; 546 }; 547 // Structure used by DeductionFailureInfo to store template argument 548 // information and the index of the problematic call argument. 549 struct DFIDeducedMismatchArgs : DFIArguments { 550 TemplateArgumentList *TemplateArgs; 551 unsigned CallArgIndex; 552 }; 553 } 554 555 /// \brief Convert from Sema's representation of template deduction information 556 /// to the form used in overload-candidate information. 557 DeductionFailureInfo 558 clang::MakeDeductionFailureInfo(ASTContext &Context, 559 Sema::TemplateDeductionResult TDK, 560 TemplateDeductionInfo &Info) { 561 DeductionFailureInfo Result; 562 Result.Result = static_cast<unsigned>(TDK); 563 Result.HasDiagnostic = false; 564 switch (TDK) { 565 case Sema::TDK_Success: 566 case Sema::TDK_Invalid: 567 case Sema::TDK_InstantiationDepth: 568 case Sema::TDK_TooManyArguments: 569 case Sema::TDK_TooFewArguments: 570 case Sema::TDK_MiscellaneousDeductionFailure: 571 Result.Data = nullptr; 572 break; 573 574 case Sema::TDK_Incomplete: 575 case Sema::TDK_InvalidExplicitArguments: 576 Result.Data = Info.Param.getOpaqueValue(); 577 break; 578 579 case Sema::TDK_DeducedMismatch: { 580 // FIXME: Should allocate from normal heap so that we can free this later. 581 auto *Saved = new (Context) DFIDeducedMismatchArgs; 582 Saved->FirstArg = Info.FirstArg; 583 Saved->SecondArg = Info.SecondArg; 584 Saved->TemplateArgs = Info.take(); 585 Saved->CallArgIndex = Info.CallArgIndex; 586 Result.Data = Saved; 587 break; 588 } 589 590 case Sema::TDK_NonDeducedMismatch: { 591 // FIXME: Should allocate from normal heap so that we can free this later. 592 DFIArguments *Saved = new (Context) DFIArguments; 593 Saved->FirstArg = Info.FirstArg; 594 Saved->SecondArg = Info.SecondArg; 595 Result.Data = Saved; 596 break; 597 } 598 599 case Sema::TDK_Inconsistent: 600 case Sema::TDK_Underqualified: { 601 // FIXME: Should allocate from normal heap so that we can free this later. 602 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 603 Saved->Param = Info.Param; 604 Saved->FirstArg = Info.FirstArg; 605 Saved->SecondArg = Info.SecondArg; 606 Result.Data = Saved; 607 break; 608 } 609 610 case Sema::TDK_SubstitutionFailure: 611 Result.Data = Info.take(); 612 if (Info.hasSFINAEDiagnostic()) { 613 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 614 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 615 Info.takeSFINAEDiagnostic(*Diag); 616 Result.HasDiagnostic = true; 617 } 618 break; 619 620 case Sema::TDK_FailedOverloadResolution: 621 Result.Data = Info.Expression; 622 break; 623 } 624 625 return Result; 626 } 627 628 void DeductionFailureInfo::Destroy() { 629 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 630 case Sema::TDK_Success: 631 case Sema::TDK_Invalid: 632 case Sema::TDK_InstantiationDepth: 633 case Sema::TDK_Incomplete: 634 case Sema::TDK_TooManyArguments: 635 case Sema::TDK_TooFewArguments: 636 case Sema::TDK_InvalidExplicitArguments: 637 case Sema::TDK_FailedOverloadResolution: 638 break; 639 640 case Sema::TDK_Inconsistent: 641 case Sema::TDK_Underqualified: 642 case Sema::TDK_DeducedMismatch: 643 case Sema::TDK_NonDeducedMismatch: 644 // FIXME: Destroy the data? 645 Data = nullptr; 646 break; 647 648 case Sema::TDK_SubstitutionFailure: 649 // FIXME: Destroy the template argument list? 650 Data = nullptr; 651 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 652 Diag->~PartialDiagnosticAt(); 653 HasDiagnostic = false; 654 } 655 break; 656 657 // Unhandled 658 case Sema::TDK_MiscellaneousDeductionFailure: 659 break; 660 } 661 } 662 663 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 664 if (HasDiagnostic) 665 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 666 return nullptr; 667 } 668 669 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 670 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 671 case Sema::TDK_Success: 672 case Sema::TDK_Invalid: 673 case Sema::TDK_InstantiationDepth: 674 case Sema::TDK_TooManyArguments: 675 case Sema::TDK_TooFewArguments: 676 case Sema::TDK_SubstitutionFailure: 677 case Sema::TDK_DeducedMismatch: 678 case Sema::TDK_NonDeducedMismatch: 679 case Sema::TDK_FailedOverloadResolution: 680 return TemplateParameter(); 681 682 case Sema::TDK_Incomplete: 683 case Sema::TDK_InvalidExplicitArguments: 684 return TemplateParameter::getFromOpaqueValue(Data); 685 686 case Sema::TDK_Inconsistent: 687 case Sema::TDK_Underqualified: 688 return static_cast<DFIParamWithArguments*>(Data)->Param; 689 690 // Unhandled 691 case Sema::TDK_MiscellaneousDeductionFailure: 692 break; 693 } 694 695 return TemplateParameter(); 696 } 697 698 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 699 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 700 case Sema::TDK_Success: 701 case Sema::TDK_Invalid: 702 case Sema::TDK_InstantiationDepth: 703 case Sema::TDK_TooManyArguments: 704 case Sema::TDK_TooFewArguments: 705 case Sema::TDK_Incomplete: 706 case Sema::TDK_InvalidExplicitArguments: 707 case Sema::TDK_Inconsistent: 708 case Sema::TDK_Underqualified: 709 case Sema::TDK_NonDeducedMismatch: 710 case Sema::TDK_FailedOverloadResolution: 711 return nullptr; 712 713 case Sema::TDK_DeducedMismatch: 714 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 715 716 case Sema::TDK_SubstitutionFailure: 717 return static_cast<TemplateArgumentList*>(Data); 718 719 // Unhandled 720 case Sema::TDK_MiscellaneousDeductionFailure: 721 break; 722 } 723 724 return nullptr; 725 } 726 727 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 728 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 729 case Sema::TDK_Success: 730 case Sema::TDK_Invalid: 731 case Sema::TDK_InstantiationDepth: 732 case Sema::TDK_Incomplete: 733 case Sema::TDK_TooManyArguments: 734 case Sema::TDK_TooFewArguments: 735 case Sema::TDK_InvalidExplicitArguments: 736 case Sema::TDK_SubstitutionFailure: 737 case Sema::TDK_FailedOverloadResolution: 738 return nullptr; 739 740 case Sema::TDK_Inconsistent: 741 case Sema::TDK_Underqualified: 742 case Sema::TDK_DeducedMismatch: 743 case Sema::TDK_NonDeducedMismatch: 744 return &static_cast<DFIArguments*>(Data)->FirstArg; 745 746 // Unhandled 747 case Sema::TDK_MiscellaneousDeductionFailure: 748 break; 749 } 750 751 return nullptr; 752 } 753 754 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 755 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 756 case Sema::TDK_Success: 757 case Sema::TDK_Invalid: 758 case Sema::TDK_InstantiationDepth: 759 case Sema::TDK_Incomplete: 760 case Sema::TDK_TooManyArguments: 761 case Sema::TDK_TooFewArguments: 762 case Sema::TDK_InvalidExplicitArguments: 763 case Sema::TDK_SubstitutionFailure: 764 case Sema::TDK_FailedOverloadResolution: 765 return nullptr; 766 767 case Sema::TDK_Inconsistent: 768 case Sema::TDK_Underqualified: 769 case Sema::TDK_DeducedMismatch: 770 case Sema::TDK_NonDeducedMismatch: 771 return &static_cast<DFIArguments*>(Data)->SecondArg; 772 773 // Unhandled 774 case Sema::TDK_MiscellaneousDeductionFailure: 775 break; 776 } 777 778 return nullptr; 779 } 780 781 Expr *DeductionFailureInfo::getExpr() { 782 if (static_cast<Sema::TemplateDeductionResult>(Result) == 783 Sema::TDK_FailedOverloadResolution) 784 return static_cast<Expr*>(Data); 785 786 return nullptr; 787 } 788 789 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 790 if (static_cast<Sema::TemplateDeductionResult>(Result) == 791 Sema::TDK_DeducedMismatch) 792 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 793 794 return llvm::None; 795 } 796 797 void OverloadCandidateSet::destroyCandidates() { 798 for (iterator i = begin(), e = end(); i != e; ++i) { 799 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 800 i->Conversions[ii].~ImplicitConversionSequence(); 801 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 802 i->DeductionFailure.Destroy(); 803 } 804 } 805 806 void OverloadCandidateSet::clear() { 807 destroyCandidates(); 808 NumInlineSequences = 0; 809 Candidates.clear(); 810 Functions.clear(); 811 } 812 813 namespace { 814 class UnbridgedCastsSet { 815 struct Entry { 816 Expr **Addr; 817 Expr *Saved; 818 }; 819 SmallVector<Entry, 2> Entries; 820 821 public: 822 void save(Sema &S, Expr *&E) { 823 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 824 Entry entry = { &E, E }; 825 Entries.push_back(entry); 826 E = S.stripARCUnbridgedCast(E); 827 } 828 829 void restore() { 830 for (SmallVectorImpl<Entry>::iterator 831 i = Entries.begin(), e = Entries.end(); i != e; ++i) 832 *i->Addr = i->Saved; 833 } 834 }; 835 } 836 837 /// checkPlaceholderForOverload - Do any interesting placeholder-like 838 /// preprocessing on the given expression. 839 /// 840 /// \param unbridgedCasts a collection to which to add unbridged casts; 841 /// without this, they will be immediately diagnosed as errors 842 /// 843 /// Return true on unrecoverable error. 844 static bool 845 checkPlaceholderForOverload(Sema &S, Expr *&E, 846 UnbridgedCastsSet *unbridgedCasts = nullptr) { 847 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 848 // We can't handle overloaded expressions here because overload 849 // resolution might reasonably tweak them. 850 if (placeholder->getKind() == BuiltinType::Overload) return false; 851 852 // If the context potentially accepts unbridged ARC casts, strip 853 // the unbridged cast and add it to the collection for later restoration. 854 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 855 unbridgedCasts) { 856 unbridgedCasts->save(S, E); 857 return false; 858 } 859 860 // Go ahead and check everything else. 861 ExprResult result = S.CheckPlaceholderExpr(E); 862 if (result.isInvalid()) 863 return true; 864 865 E = result.get(); 866 return false; 867 } 868 869 // Nothing to do. 870 return false; 871 } 872 873 /// checkArgPlaceholdersForOverload - Check a set of call operands for 874 /// placeholders. 875 static bool checkArgPlaceholdersForOverload(Sema &S, 876 MultiExprArg Args, 877 UnbridgedCastsSet &unbridged) { 878 for (unsigned i = 0, e = Args.size(); i != e; ++i) 879 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 880 return true; 881 882 return false; 883 } 884 885 // IsOverload - Determine whether the given New declaration is an 886 // overload of the declarations in Old. This routine returns false if 887 // New and Old cannot be overloaded, e.g., if New has the same 888 // signature as some function in Old (C++ 1.3.10) or if the Old 889 // declarations aren't functions (or function templates) at all. When 890 // it does return false, MatchedDecl will point to the decl that New 891 // cannot be overloaded with. This decl may be a UsingShadowDecl on 892 // top of the underlying declaration. 893 // 894 // Example: Given the following input: 895 // 896 // void f(int, float); // #1 897 // void f(int, int); // #2 898 // int f(int, int); // #3 899 // 900 // When we process #1, there is no previous declaration of "f", 901 // so IsOverload will not be used. 902 // 903 // When we process #2, Old contains only the FunctionDecl for #1. By 904 // comparing the parameter types, we see that #1 and #2 are overloaded 905 // (since they have different signatures), so this routine returns 906 // false; MatchedDecl is unchanged. 907 // 908 // When we process #3, Old is an overload set containing #1 and #2. We 909 // compare the signatures of #3 to #1 (they're overloaded, so we do 910 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 911 // identical (return types of functions are not part of the 912 // signature), IsOverload returns false and MatchedDecl will be set to 913 // point to the FunctionDecl for #2. 914 // 915 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 916 // into a class by a using declaration. The rules for whether to hide 917 // shadow declarations ignore some properties which otherwise figure 918 // into a function template's signature. 919 Sema::OverloadKind 920 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 921 NamedDecl *&Match, bool NewIsUsingDecl) { 922 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 923 I != E; ++I) { 924 NamedDecl *OldD = *I; 925 926 bool OldIsUsingDecl = false; 927 if (isa<UsingShadowDecl>(OldD)) { 928 OldIsUsingDecl = true; 929 930 // We can always introduce two using declarations into the same 931 // context, even if they have identical signatures. 932 if (NewIsUsingDecl) continue; 933 934 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 935 } 936 937 // A using-declaration does not conflict with another declaration 938 // if one of them is hidden. 939 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 940 continue; 941 942 // If either declaration was introduced by a using declaration, 943 // we'll need to use slightly different rules for matching. 944 // Essentially, these rules are the normal rules, except that 945 // function templates hide function templates with different 946 // return types or template parameter lists. 947 bool UseMemberUsingDeclRules = 948 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 949 !New->getFriendObjectKind(); 950 951 if (FunctionDecl *OldF = OldD->getAsFunction()) { 952 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 953 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 954 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 955 continue; 956 } 957 958 if (!isa<FunctionTemplateDecl>(OldD) && 959 !shouldLinkPossiblyHiddenDecl(*I, New)) 960 continue; 961 962 Match = *I; 963 return Ovl_Match; 964 } 965 } else if (isa<UsingDecl>(OldD)) { 966 // We can overload with these, which can show up when doing 967 // redeclaration checks for UsingDecls. 968 assert(Old.getLookupKind() == LookupUsingDeclName); 969 } else if (isa<TagDecl>(OldD)) { 970 // We can always overload with tags by hiding them. 971 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 972 // Optimistically assume that an unresolved using decl will 973 // overload; if it doesn't, we'll have to diagnose during 974 // template instantiation. 975 } else { 976 // (C++ 13p1): 977 // Only function declarations can be overloaded; object and type 978 // declarations cannot be overloaded. 979 Match = *I; 980 return Ovl_NonFunction; 981 } 982 } 983 984 return Ovl_Overload; 985 } 986 987 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 988 bool UseUsingDeclRules) { 989 // C++ [basic.start.main]p2: This function shall not be overloaded. 990 if (New->isMain()) 991 return false; 992 993 // MSVCRT user defined entry points cannot be overloaded. 994 if (New->isMSVCRTEntryPoint()) 995 return false; 996 997 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 998 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 999 1000 // C++ [temp.fct]p2: 1001 // A function template can be overloaded with other function templates 1002 // and with normal (non-template) functions. 1003 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1004 return true; 1005 1006 // Is the function New an overload of the function Old? 1007 QualType OldQType = Context.getCanonicalType(Old->getType()); 1008 QualType NewQType = Context.getCanonicalType(New->getType()); 1009 1010 // Compare the signatures (C++ 1.3.10) of the two functions to 1011 // determine whether they are overloads. If we find any mismatch 1012 // in the signature, they are overloads. 1013 1014 // If either of these functions is a K&R-style function (no 1015 // prototype), then we consider them to have matching signatures. 1016 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1017 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1018 return false; 1019 1020 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1021 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1022 1023 // The signature of a function includes the types of its 1024 // parameters (C++ 1.3.10), which includes the presence or absence 1025 // of the ellipsis; see C++ DR 357). 1026 if (OldQType != NewQType && 1027 (OldType->getNumParams() != NewType->getNumParams() || 1028 OldType->isVariadic() != NewType->isVariadic() || 1029 !FunctionParamTypesAreEqual(OldType, NewType))) 1030 return true; 1031 1032 // C++ [temp.over.link]p4: 1033 // The signature of a function template consists of its function 1034 // signature, its return type and its template parameter list. The names 1035 // of the template parameters are significant only for establishing the 1036 // relationship between the template parameters and the rest of the 1037 // signature. 1038 // 1039 // We check the return type and template parameter lists for function 1040 // templates first; the remaining checks follow. 1041 // 1042 // However, we don't consider either of these when deciding whether 1043 // a member introduced by a shadow declaration is hidden. 1044 if (!UseUsingDeclRules && NewTemplate && 1045 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1046 OldTemplate->getTemplateParameters(), 1047 false, TPL_TemplateMatch) || 1048 OldType->getReturnType() != NewType->getReturnType())) 1049 return true; 1050 1051 // If the function is a class member, its signature includes the 1052 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1053 // 1054 // As part of this, also check whether one of the member functions 1055 // is static, in which case they are not overloads (C++ 1056 // 13.1p2). While not part of the definition of the signature, 1057 // this check is important to determine whether these functions 1058 // can be overloaded. 1059 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1060 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1061 if (OldMethod && NewMethod && 1062 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1063 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1064 if (!UseUsingDeclRules && 1065 (OldMethod->getRefQualifier() == RQ_None || 1066 NewMethod->getRefQualifier() == RQ_None)) { 1067 // C++0x [over.load]p2: 1068 // - Member function declarations with the same name and the same 1069 // parameter-type-list as well as member function template 1070 // declarations with the same name, the same parameter-type-list, and 1071 // the same template parameter lists cannot be overloaded if any of 1072 // them, but not all, have a ref-qualifier (8.3.5). 1073 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1074 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1075 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1076 } 1077 return true; 1078 } 1079 1080 // We may not have applied the implicit const for a constexpr member 1081 // function yet (because we haven't yet resolved whether this is a static 1082 // or non-static member function). Add it now, on the assumption that this 1083 // is a redeclaration of OldMethod. 1084 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1085 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1086 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1087 !isa<CXXConstructorDecl>(NewMethod)) 1088 NewQuals |= Qualifiers::Const; 1089 1090 // We do not allow overloading based off of '__restrict'. 1091 OldQuals &= ~Qualifiers::Restrict; 1092 NewQuals &= ~Qualifiers::Restrict; 1093 if (OldQuals != NewQuals) 1094 return true; 1095 } 1096 1097 // Though pass_object_size is placed on parameters and takes an argument, we 1098 // consider it to be a function-level modifier for the sake of function 1099 // identity. Either the function has one or more parameters with 1100 // pass_object_size or it doesn't. 1101 if (functionHasPassObjectSizeParams(New) != 1102 functionHasPassObjectSizeParams(Old)) 1103 return true; 1104 1105 // enable_if attributes are an order-sensitive part of the signature. 1106 for (specific_attr_iterator<EnableIfAttr> 1107 NewI = New->specific_attr_begin<EnableIfAttr>(), 1108 NewE = New->specific_attr_end<EnableIfAttr>(), 1109 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1110 OldE = Old->specific_attr_end<EnableIfAttr>(); 1111 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1112 if (NewI == NewE || OldI == OldE) 1113 return true; 1114 llvm::FoldingSetNodeID NewID, OldID; 1115 NewI->getCond()->Profile(NewID, Context, true); 1116 OldI->getCond()->Profile(OldID, Context, true); 1117 if (NewID != OldID) 1118 return true; 1119 } 1120 1121 if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads) { 1122 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1123 OldTarget = IdentifyCUDATarget(Old); 1124 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global) 1125 return false; 1126 1127 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1128 1129 // Don't allow mixing of HD with other kinds. This guarantees that 1130 // we have only one viable function with this signature on any 1131 // side of CUDA compilation . 1132 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice)) 1133 return false; 1134 1135 // Allow overloading of functions with same signature, but 1136 // different CUDA target attributes. 1137 return NewTarget != OldTarget; 1138 } 1139 1140 // The signatures match; this is not an overload. 1141 return false; 1142 } 1143 1144 /// \brief Checks availability of the function depending on the current 1145 /// function context. Inside an unavailable function, unavailability is ignored. 1146 /// 1147 /// \returns true if \arg FD is unavailable and current context is inside 1148 /// an available function, false otherwise. 1149 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1150 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1151 } 1152 1153 /// \brief Tries a user-defined conversion from From to ToType. 1154 /// 1155 /// Produces an implicit conversion sequence for when a standard conversion 1156 /// is not an option. See TryImplicitConversion for more information. 1157 static ImplicitConversionSequence 1158 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1159 bool SuppressUserConversions, 1160 bool AllowExplicit, 1161 bool InOverloadResolution, 1162 bool CStyle, 1163 bool AllowObjCWritebackConversion, 1164 bool AllowObjCConversionOnExplicit) { 1165 ImplicitConversionSequence ICS; 1166 1167 if (SuppressUserConversions) { 1168 // We're not in the case above, so there is no conversion that 1169 // we can perform. 1170 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1171 return ICS; 1172 } 1173 1174 // Attempt user-defined conversion. 1175 OverloadCandidateSet Conversions(From->getExprLoc(), 1176 OverloadCandidateSet::CSK_Normal); 1177 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1178 Conversions, AllowExplicit, 1179 AllowObjCConversionOnExplicit)) { 1180 case OR_Success: 1181 case OR_Deleted: 1182 ICS.setUserDefined(); 1183 ICS.UserDefined.Before.setAsIdentityConversion(); 1184 // C++ [over.ics.user]p4: 1185 // A conversion of an expression of class type to the same class 1186 // type is given Exact Match rank, and a conversion of an 1187 // expression of class type to a base class of that type is 1188 // given Conversion rank, in spite of the fact that a copy 1189 // constructor (i.e., a user-defined conversion function) is 1190 // called for those cases. 1191 if (CXXConstructorDecl *Constructor 1192 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1193 QualType FromCanon 1194 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1195 QualType ToCanon 1196 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1197 if (Constructor->isCopyConstructor() && 1198 (FromCanon == ToCanon || 1199 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) { 1200 // Turn this into a "standard" conversion sequence, so that it 1201 // gets ranked with standard conversion sequences. 1202 ICS.setStandard(); 1203 ICS.Standard.setAsIdentityConversion(); 1204 ICS.Standard.setFromType(From->getType()); 1205 ICS.Standard.setAllToTypes(ToType); 1206 ICS.Standard.CopyConstructor = Constructor; 1207 if (ToCanon != FromCanon) 1208 ICS.Standard.Second = ICK_Derived_To_Base; 1209 } 1210 } 1211 break; 1212 1213 case OR_Ambiguous: 1214 ICS.setAmbiguous(); 1215 ICS.Ambiguous.setFromType(From->getType()); 1216 ICS.Ambiguous.setToType(ToType); 1217 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1218 Cand != Conversions.end(); ++Cand) 1219 if (Cand->Viable) 1220 ICS.Ambiguous.addConversion(Cand->Function); 1221 break; 1222 1223 // Fall through. 1224 case OR_No_Viable_Function: 1225 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1226 break; 1227 } 1228 1229 return ICS; 1230 } 1231 1232 /// TryImplicitConversion - Attempt to perform an implicit conversion 1233 /// from the given expression (Expr) to the given type (ToType). This 1234 /// function returns an implicit conversion sequence that can be used 1235 /// to perform the initialization. Given 1236 /// 1237 /// void f(float f); 1238 /// void g(int i) { f(i); } 1239 /// 1240 /// this routine would produce an implicit conversion sequence to 1241 /// describe the initialization of f from i, which will be a standard 1242 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1243 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1244 // 1245 /// Note that this routine only determines how the conversion can be 1246 /// performed; it does not actually perform the conversion. As such, 1247 /// it will not produce any diagnostics if no conversion is available, 1248 /// but will instead return an implicit conversion sequence of kind 1249 /// "BadConversion". 1250 /// 1251 /// If @p SuppressUserConversions, then user-defined conversions are 1252 /// not permitted. 1253 /// If @p AllowExplicit, then explicit user-defined conversions are 1254 /// permitted. 1255 /// 1256 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1257 /// writeback conversion, which allows __autoreleasing id* parameters to 1258 /// be initialized with __strong id* or __weak id* arguments. 1259 static ImplicitConversionSequence 1260 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1261 bool SuppressUserConversions, 1262 bool AllowExplicit, 1263 bool InOverloadResolution, 1264 bool CStyle, 1265 bool AllowObjCWritebackConversion, 1266 bool AllowObjCConversionOnExplicit) { 1267 ImplicitConversionSequence ICS; 1268 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1269 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1270 ICS.setStandard(); 1271 return ICS; 1272 } 1273 1274 if (!S.getLangOpts().CPlusPlus) { 1275 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1276 return ICS; 1277 } 1278 1279 // C++ [over.ics.user]p4: 1280 // A conversion of an expression of class type to the same class 1281 // type is given Exact Match rank, and a conversion of an 1282 // expression of class type to a base class of that type is 1283 // given Conversion rank, in spite of the fact that a copy/move 1284 // constructor (i.e., a user-defined conversion function) is 1285 // called for those cases. 1286 QualType FromType = From->getType(); 1287 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1288 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1289 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) { 1290 ICS.setStandard(); 1291 ICS.Standard.setAsIdentityConversion(); 1292 ICS.Standard.setFromType(FromType); 1293 ICS.Standard.setAllToTypes(ToType); 1294 1295 // We don't actually check at this point whether there is a valid 1296 // copy/move constructor, since overloading just assumes that it 1297 // exists. When we actually perform initialization, we'll find the 1298 // appropriate constructor to copy the returned object, if needed. 1299 ICS.Standard.CopyConstructor = nullptr; 1300 1301 // Determine whether this is considered a derived-to-base conversion. 1302 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1303 ICS.Standard.Second = ICK_Derived_To_Base; 1304 1305 return ICS; 1306 } 1307 1308 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1309 AllowExplicit, InOverloadResolution, CStyle, 1310 AllowObjCWritebackConversion, 1311 AllowObjCConversionOnExplicit); 1312 } 1313 1314 ImplicitConversionSequence 1315 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1316 bool SuppressUserConversions, 1317 bool AllowExplicit, 1318 bool InOverloadResolution, 1319 bool CStyle, 1320 bool AllowObjCWritebackConversion) { 1321 return ::TryImplicitConversion(*this, From, ToType, 1322 SuppressUserConversions, AllowExplicit, 1323 InOverloadResolution, CStyle, 1324 AllowObjCWritebackConversion, 1325 /*AllowObjCConversionOnExplicit=*/false); 1326 } 1327 1328 /// PerformImplicitConversion - Perform an implicit conversion of the 1329 /// expression From to the type ToType. Returns the 1330 /// converted expression. Flavor is the kind of conversion we're 1331 /// performing, used in the error message. If @p AllowExplicit, 1332 /// explicit user-defined conversions are permitted. 1333 ExprResult 1334 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1335 AssignmentAction Action, bool AllowExplicit) { 1336 ImplicitConversionSequence ICS; 1337 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1338 } 1339 1340 ExprResult 1341 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1342 AssignmentAction Action, bool AllowExplicit, 1343 ImplicitConversionSequence& ICS) { 1344 if (checkPlaceholderForOverload(*this, From)) 1345 return ExprError(); 1346 1347 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1348 bool AllowObjCWritebackConversion 1349 = getLangOpts().ObjCAutoRefCount && 1350 (Action == AA_Passing || Action == AA_Sending); 1351 if (getLangOpts().ObjC1) 1352 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1353 ToType, From->getType(), From); 1354 ICS = ::TryImplicitConversion(*this, From, ToType, 1355 /*SuppressUserConversions=*/false, 1356 AllowExplicit, 1357 /*InOverloadResolution=*/false, 1358 /*CStyle=*/false, 1359 AllowObjCWritebackConversion, 1360 /*AllowObjCConversionOnExplicit=*/false); 1361 return PerformImplicitConversion(From, ToType, ICS, Action); 1362 } 1363 1364 /// \brief Determine whether the conversion from FromType to ToType is a valid 1365 /// conversion that strips "noreturn" off the nested function type. 1366 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1367 QualType &ResultTy) { 1368 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1369 return false; 1370 1371 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1372 // where F adds one of the following at most once: 1373 // - a pointer 1374 // - a member pointer 1375 // - a block pointer 1376 CanQualType CanTo = Context.getCanonicalType(ToType); 1377 CanQualType CanFrom = Context.getCanonicalType(FromType); 1378 Type::TypeClass TyClass = CanTo->getTypeClass(); 1379 if (TyClass != CanFrom->getTypeClass()) return false; 1380 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1381 if (TyClass == Type::Pointer) { 1382 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1383 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1384 } else if (TyClass == Type::BlockPointer) { 1385 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1386 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1387 } else if (TyClass == Type::MemberPointer) { 1388 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1389 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1390 } else { 1391 return false; 1392 } 1393 1394 TyClass = CanTo->getTypeClass(); 1395 if (TyClass != CanFrom->getTypeClass()) return false; 1396 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1397 return false; 1398 } 1399 1400 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1401 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1402 if (!EInfo.getNoReturn()) return false; 1403 1404 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1405 assert(QualType(FromFn, 0).isCanonical()); 1406 if (QualType(FromFn, 0) != CanTo) return false; 1407 1408 ResultTy = ToType; 1409 return true; 1410 } 1411 1412 /// \brief Determine whether the conversion from FromType to ToType is a valid 1413 /// vector conversion. 1414 /// 1415 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1416 /// conversion. 1417 static bool IsVectorConversion(Sema &S, QualType FromType, 1418 QualType ToType, ImplicitConversionKind &ICK) { 1419 // We need at least one of these types to be a vector type to have a vector 1420 // conversion. 1421 if (!ToType->isVectorType() && !FromType->isVectorType()) 1422 return false; 1423 1424 // Identical types require no conversions. 1425 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1426 return false; 1427 1428 // There are no conversions between extended vector types, only identity. 1429 if (ToType->isExtVectorType()) { 1430 // There are no conversions between extended vector types other than the 1431 // identity conversion. 1432 if (FromType->isExtVectorType()) 1433 return false; 1434 1435 // Vector splat from any arithmetic type to a vector. 1436 if (FromType->isArithmeticType()) { 1437 ICK = ICK_Vector_Splat; 1438 return true; 1439 } 1440 } 1441 1442 // We can perform the conversion between vector types in the following cases: 1443 // 1)vector types are equivalent AltiVec and GCC vector types 1444 // 2)lax vector conversions are permitted and the vector types are of the 1445 // same size 1446 if (ToType->isVectorType() && FromType->isVectorType()) { 1447 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1448 S.isLaxVectorConversion(FromType, ToType)) { 1449 ICK = ICK_Vector_Conversion; 1450 return true; 1451 } 1452 } 1453 1454 return false; 1455 } 1456 1457 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1458 bool InOverloadResolution, 1459 StandardConversionSequence &SCS, 1460 bool CStyle); 1461 1462 /// IsStandardConversion - Determines whether there is a standard 1463 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1464 /// expression From to the type ToType. Standard conversion sequences 1465 /// only consider non-class types; for conversions that involve class 1466 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1467 /// contain the standard conversion sequence required to perform this 1468 /// conversion and this routine will return true. Otherwise, this 1469 /// routine will return false and the value of SCS is unspecified. 1470 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1471 bool InOverloadResolution, 1472 StandardConversionSequence &SCS, 1473 bool CStyle, 1474 bool AllowObjCWritebackConversion) { 1475 QualType FromType = From->getType(); 1476 1477 // Standard conversions (C++ [conv]) 1478 SCS.setAsIdentityConversion(); 1479 SCS.IncompatibleObjC = false; 1480 SCS.setFromType(FromType); 1481 SCS.CopyConstructor = nullptr; 1482 1483 // There are no standard conversions for class types in C++, so 1484 // abort early. When overloading in C, however, we do permit them. 1485 if (S.getLangOpts().CPlusPlus && 1486 (FromType->isRecordType() || ToType->isRecordType())) 1487 return false; 1488 1489 // The first conversion can be an lvalue-to-rvalue conversion, 1490 // array-to-pointer conversion, or function-to-pointer conversion 1491 // (C++ 4p1). 1492 1493 if (FromType == S.Context.OverloadTy) { 1494 DeclAccessPair AccessPair; 1495 if (FunctionDecl *Fn 1496 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1497 AccessPair)) { 1498 // We were able to resolve the address of the overloaded function, 1499 // so we can convert to the type of that function. 1500 FromType = Fn->getType(); 1501 SCS.setFromType(FromType); 1502 1503 // we can sometimes resolve &foo<int> regardless of ToType, so check 1504 // if the type matches (identity) or we are converting to bool 1505 if (!S.Context.hasSameUnqualifiedType( 1506 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1507 QualType resultTy; 1508 // if the function type matches except for [[noreturn]], it's ok 1509 if (!S.IsNoReturnConversion(FromType, 1510 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1511 // otherwise, only a boolean conversion is standard 1512 if (!ToType->isBooleanType()) 1513 return false; 1514 } 1515 1516 // Check if the "from" expression is taking the address of an overloaded 1517 // function and recompute the FromType accordingly. Take advantage of the 1518 // fact that non-static member functions *must* have such an address-of 1519 // expression. 1520 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1521 if (Method && !Method->isStatic()) { 1522 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1523 "Non-unary operator on non-static member address"); 1524 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1525 == UO_AddrOf && 1526 "Non-address-of operator on non-static member address"); 1527 const Type *ClassType 1528 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1529 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1530 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1531 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1532 UO_AddrOf && 1533 "Non-address-of operator for overloaded function expression"); 1534 FromType = S.Context.getPointerType(FromType); 1535 } 1536 1537 // Check that we've computed the proper type after overload resolution. 1538 assert(S.Context.hasSameType( 1539 FromType, 1540 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1541 } else { 1542 return false; 1543 } 1544 } 1545 // Lvalue-to-rvalue conversion (C++11 4.1): 1546 // A glvalue (3.10) of a non-function, non-array type T can 1547 // be converted to a prvalue. 1548 bool argIsLValue = From->isGLValue(); 1549 if (argIsLValue && 1550 !FromType->isFunctionType() && !FromType->isArrayType() && 1551 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1552 SCS.First = ICK_Lvalue_To_Rvalue; 1553 1554 // C11 6.3.2.1p2: 1555 // ... if the lvalue has atomic type, the value has the non-atomic version 1556 // of the type of the lvalue ... 1557 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1558 FromType = Atomic->getValueType(); 1559 1560 // If T is a non-class type, the type of the rvalue is the 1561 // cv-unqualified version of T. Otherwise, the type of the rvalue 1562 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1563 // just strip the qualifiers because they don't matter. 1564 FromType = FromType.getUnqualifiedType(); 1565 } else if (FromType->isArrayType()) { 1566 // Array-to-pointer conversion (C++ 4.2) 1567 SCS.First = ICK_Array_To_Pointer; 1568 1569 // An lvalue or rvalue of type "array of N T" or "array of unknown 1570 // bound of T" can be converted to an rvalue of type "pointer to 1571 // T" (C++ 4.2p1). 1572 FromType = S.Context.getArrayDecayedType(FromType); 1573 1574 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1575 // This conversion is deprecated in C++03 (D.4) 1576 SCS.DeprecatedStringLiteralToCharPtr = true; 1577 1578 // For the purpose of ranking in overload resolution 1579 // (13.3.3.1.1), this conversion is considered an 1580 // array-to-pointer conversion followed by a qualification 1581 // conversion (4.4). (C++ 4.2p2) 1582 SCS.Second = ICK_Identity; 1583 SCS.Third = ICK_Qualification; 1584 SCS.QualificationIncludesObjCLifetime = false; 1585 SCS.setAllToTypes(FromType); 1586 return true; 1587 } 1588 } else if (FromType->isFunctionType() && argIsLValue) { 1589 // Function-to-pointer conversion (C++ 4.3). 1590 SCS.First = ICK_Function_To_Pointer; 1591 1592 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1593 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1594 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1595 return false; 1596 1597 // An lvalue of function type T can be converted to an rvalue of 1598 // type "pointer to T." The result is a pointer to the 1599 // function. (C++ 4.3p1). 1600 FromType = S.Context.getPointerType(FromType); 1601 } else { 1602 // We don't require any conversions for the first step. 1603 SCS.First = ICK_Identity; 1604 } 1605 SCS.setToType(0, FromType); 1606 1607 // The second conversion can be an integral promotion, floating 1608 // point promotion, integral conversion, floating point conversion, 1609 // floating-integral conversion, pointer conversion, 1610 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1611 // For overloading in C, this can also be a "compatible-type" 1612 // conversion. 1613 bool IncompatibleObjC = false; 1614 ImplicitConversionKind SecondICK = ICK_Identity; 1615 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1616 // The unqualified versions of the types are the same: there's no 1617 // conversion to do. 1618 SCS.Second = ICK_Identity; 1619 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1620 // Integral promotion (C++ 4.5). 1621 SCS.Second = ICK_Integral_Promotion; 1622 FromType = ToType.getUnqualifiedType(); 1623 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1624 // Floating point promotion (C++ 4.6). 1625 SCS.Second = ICK_Floating_Promotion; 1626 FromType = ToType.getUnqualifiedType(); 1627 } else if (S.IsComplexPromotion(FromType, ToType)) { 1628 // Complex promotion (Clang extension) 1629 SCS.Second = ICK_Complex_Promotion; 1630 FromType = ToType.getUnqualifiedType(); 1631 } else if (ToType->isBooleanType() && 1632 (FromType->isArithmeticType() || 1633 FromType->isAnyPointerType() || 1634 FromType->isBlockPointerType() || 1635 FromType->isMemberPointerType() || 1636 FromType->isNullPtrType())) { 1637 // Boolean conversions (C++ 4.12). 1638 SCS.Second = ICK_Boolean_Conversion; 1639 FromType = S.Context.BoolTy; 1640 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1641 ToType->isIntegralType(S.Context)) { 1642 // Integral conversions (C++ 4.7). 1643 SCS.Second = ICK_Integral_Conversion; 1644 FromType = ToType.getUnqualifiedType(); 1645 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1646 // Complex conversions (C99 6.3.1.6) 1647 SCS.Second = ICK_Complex_Conversion; 1648 FromType = ToType.getUnqualifiedType(); 1649 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1650 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1651 // Complex-real conversions (C99 6.3.1.7) 1652 SCS.Second = ICK_Complex_Real; 1653 FromType = ToType.getUnqualifiedType(); 1654 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1655 // Floating point conversions (C++ 4.8). 1656 SCS.Second = ICK_Floating_Conversion; 1657 FromType = ToType.getUnqualifiedType(); 1658 } else if ((FromType->isRealFloatingType() && 1659 ToType->isIntegralType(S.Context)) || 1660 (FromType->isIntegralOrUnscopedEnumerationType() && 1661 ToType->isRealFloatingType())) { 1662 // Floating-integral conversions (C++ 4.9). 1663 SCS.Second = ICK_Floating_Integral; 1664 FromType = ToType.getUnqualifiedType(); 1665 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1666 SCS.Second = ICK_Block_Pointer_Conversion; 1667 } else if (AllowObjCWritebackConversion && 1668 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1669 SCS.Second = ICK_Writeback_Conversion; 1670 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1671 FromType, IncompatibleObjC)) { 1672 // Pointer conversions (C++ 4.10). 1673 SCS.Second = ICK_Pointer_Conversion; 1674 SCS.IncompatibleObjC = IncompatibleObjC; 1675 FromType = FromType.getUnqualifiedType(); 1676 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1677 InOverloadResolution, FromType)) { 1678 // Pointer to member conversions (4.11). 1679 SCS.Second = ICK_Pointer_Member; 1680 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1681 SCS.Second = SecondICK; 1682 FromType = ToType.getUnqualifiedType(); 1683 } else if (!S.getLangOpts().CPlusPlus && 1684 S.Context.typesAreCompatible(ToType, FromType)) { 1685 // Compatible conversions (Clang extension for C function overloading) 1686 SCS.Second = ICK_Compatible_Conversion; 1687 FromType = ToType.getUnqualifiedType(); 1688 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1689 // Treat a conversion that strips "noreturn" as an identity conversion. 1690 SCS.Second = ICK_NoReturn_Adjustment; 1691 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1692 InOverloadResolution, 1693 SCS, CStyle)) { 1694 SCS.Second = ICK_TransparentUnionConversion; 1695 FromType = ToType; 1696 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1697 CStyle)) { 1698 // tryAtomicConversion has updated the standard conversion sequence 1699 // appropriately. 1700 return true; 1701 } else if (ToType->isEventT() && 1702 From->isIntegerConstantExpr(S.getASTContext()) && 1703 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1704 SCS.Second = ICK_Zero_Event_Conversion; 1705 FromType = ToType; 1706 } else { 1707 // No second conversion required. 1708 SCS.Second = ICK_Identity; 1709 } 1710 SCS.setToType(1, FromType); 1711 1712 QualType CanonFrom; 1713 QualType CanonTo; 1714 // The third conversion can be a qualification conversion (C++ 4p1). 1715 bool ObjCLifetimeConversion; 1716 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1717 ObjCLifetimeConversion)) { 1718 SCS.Third = ICK_Qualification; 1719 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1720 FromType = ToType; 1721 CanonFrom = S.Context.getCanonicalType(FromType); 1722 CanonTo = S.Context.getCanonicalType(ToType); 1723 } else { 1724 // No conversion required 1725 SCS.Third = ICK_Identity; 1726 1727 // C++ [over.best.ics]p6: 1728 // [...] Any difference in top-level cv-qualification is 1729 // subsumed by the initialization itself and does not constitute 1730 // a conversion. [...] 1731 CanonFrom = S.Context.getCanonicalType(FromType); 1732 CanonTo = S.Context.getCanonicalType(ToType); 1733 if (CanonFrom.getLocalUnqualifiedType() 1734 == CanonTo.getLocalUnqualifiedType() && 1735 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1736 FromType = ToType; 1737 CanonFrom = CanonTo; 1738 } 1739 } 1740 SCS.setToType(2, FromType); 1741 1742 if (CanonFrom == CanonTo) 1743 return true; 1744 1745 // If we have not converted the argument type to the parameter type, 1746 // this is a bad conversion sequence, unless we're resolving an overload in C. 1747 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1748 return false; 1749 1750 ExprResult ER = ExprResult{From}; 1751 auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER, 1752 /*Diagnose=*/false, 1753 /*DiagnoseCFAudited=*/false, 1754 /*ConvertRHS=*/false); 1755 if (Conv != Sema::Compatible) 1756 return false; 1757 1758 SCS.setAllToTypes(ToType); 1759 // We need to set all three because we want this conversion to rank terribly, 1760 // and we don't know what conversions it may overlap with. 1761 SCS.First = ICK_C_Only_Conversion; 1762 SCS.Second = ICK_C_Only_Conversion; 1763 SCS.Third = ICK_C_Only_Conversion; 1764 return true; 1765 } 1766 1767 static bool 1768 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1769 QualType &ToType, 1770 bool InOverloadResolution, 1771 StandardConversionSequence &SCS, 1772 bool CStyle) { 1773 1774 const RecordType *UT = ToType->getAsUnionType(); 1775 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1776 return false; 1777 // The field to initialize within the transparent union. 1778 RecordDecl *UD = UT->getDecl(); 1779 // It's compatible if the expression matches any of the fields. 1780 for (const auto *it : UD->fields()) { 1781 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1782 CStyle, /*ObjCWritebackConversion=*/false)) { 1783 ToType = it->getType(); 1784 return true; 1785 } 1786 } 1787 return false; 1788 } 1789 1790 /// IsIntegralPromotion - Determines whether the conversion from the 1791 /// expression From (whose potentially-adjusted type is FromType) to 1792 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1793 /// sets PromotedType to the promoted type. 1794 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1795 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1796 // All integers are built-in. 1797 if (!To) { 1798 return false; 1799 } 1800 1801 // An rvalue of type char, signed char, unsigned char, short int, or 1802 // unsigned short int can be converted to an rvalue of type int if 1803 // int can represent all the values of the source type; otherwise, 1804 // the source rvalue can be converted to an rvalue of type unsigned 1805 // int (C++ 4.5p1). 1806 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1807 !FromType->isEnumeralType()) { 1808 if (// We can promote any signed, promotable integer type to an int 1809 (FromType->isSignedIntegerType() || 1810 // We can promote any unsigned integer type whose size is 1811 // less than int to an int. 1812 (!FromType->isSignedIntegerType() && 1813 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1814 return To->getKind() == BuiltinType::Int; 1815 } 1816 1817 return To->getKind() == BuiltinType::UInt; 1818 } 1819 1820 // C++11 [conv.prom]p3: 1821 // A prvalue of an unscoped enumeration type whose underlying type is not 1822 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1823 // following types that can represent all the values of the enumeration 1824 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1825 // unsigned int, long int, unsigned long int, long long int, or unsigned 1826 // long long int. If none of the types in that list can represent all the 1827 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1828 // type can be converted to an rvalue a prvalue of the extended integer type 1829 // with lowest integer conversion rank (4.13) greater than the rank of long 1830 // long in which all the values of the enumeration can be represented. If 1831 // there are two such extended types, the signed one is chosen. 1832 // C++11 [conv.prom]p4: 1833 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1834 // can be converted to a prvalue of its underlying type. Moreover, if 1835 // integral promotion can be applied to its underlying type, a prvalue of an 1836 // unscoped enumeration type whose underlying type is fixed can also be 1837 // converted to a prvalue of the promoted underlying type. 1838 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1839 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1840 // provided for a scoped enumeration. 1841 if (FromEnumType->getDecl()->isScoped()) 1842 return false; 1843 1844 // We can perform an integral promotion to the underlying type of the enum, 1845 // even if that's not the promoted type. Note that the check for promoting 1846 // the underlying type is based on the type alone, and does not consider 1847 // the bitfield-ness of the actual source expression. 1848 if (FromEnumType->getDecl()->isFixed()) { 1849 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1850 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1851 IsIntegralPromotion(nullptr, Underlying, ToType); 1852 } 1853 1854 // We have already pre-calculated the promotion type, so this is trivial. 1855 if (ToType->isIntegerType() && 1856 isCompleteType(From->getLocStart(), FromType)) 1857 return Context.hasSameUnqualifiedType( 1858 ToType, FromEnumType->getDecl()->getPromotionType()); 1859 } 1860 1861 // C++0x [conv.prom]p2: 1862 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1863 // to an rvalue a prvalue of the first of the following types that can 1864 // represent all the values of its underlying type: int, unsigned int, 1865 // long int, unsigned long int, long long int, or unsigned long long int. 1866 // If none of the types in that list can represent all the values of its 1867 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1868 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1869 // type. 1870 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1871 ToType->isIntegerType()) { 1872 // Determine whether the type we're converting from is signed or 1873 // unsigned. 1874 bool FromIsSigned = FromType->isSignedIntegerType(); 1875 uint64_t FromSize = Context.getTypeSize(FromType); 1876 1877 // The types we'll try to promote to, in the appropriate 1878 // order. Try each of these types. 1879 QualType PromoteTypes[6] = { 1880 Context.IntTy, Context.UnsignedIntTy, 1881 Context.LongTy, Context.UnsignedLongTy , 1882 Context.LongLongTy, Context.UnsignedLongLongTy 1883 }; 1884 for (int Idx = 0; Idx < 6; ++Idx) { 1885 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1886 if (FromSize < ToSize || 1887 (FromSize == ToSize && 1888 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1889 // We found the type that we can promote to. If this is the 1890 // type we wanted, we have a promotion. Otherwise, no 1891 // promotion. 1892 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1893 } 1894 } 1895 } 1896 1897 // An rvalue for an integral bit-field (9.6) can be converted to an 1898 // rvalue of type int if int can represent all the values of the 1899 // bit-field; otherwise, it can be converted to unsigned int if 1900 // unsigned int can represent all the values of the bit-field. If 1901 // the bit-field is larger yet, no integral promotion applies to 1902 // it. If the bit-field has an enumerated type, it is treated as any 1903 // other value of that type for promotion purposes (C++ 4.5p3). 1904 // FIXME: We should delay checking of bit-fields until we actually perform the 1905 // conversion. 1906 if (From) { 1907 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1908 llvm::APSInt BitWidth; 1909 if (FromType->isIntegralType(Context) && 1910 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1911 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1912 ToSize = Context.getTypeSize(ToType); 1913 1914 // Are we promoting to an int from a bitfield that fits in an int? 1915 if (BitWidth < ToSize || 1916 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1917 return To->getKind() == BuiltinType::Int; 1918 } 1919 1920 // Are we promoting to an unsigned int from an unsigned bitfield 1921 // that fits into an unsigned int? 1922 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1923 return To->getKind() == BuiltinType::UInt; 1924 } 1925 1926 return false; 1927 } 1928 } 1929 } 1930 1931 // An rvalue of type bool can be converted to an rvalue of type int, 1932 // with false becoming zero and true becoming one (C++ 4.5p4). 1933 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1934 return true; 1935 } 1936 1937 return false; 1938 } 1939 1940 /// IsFloatingPointPromotion - Determines whether the conversion from 1941 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1942 /// returns true and sets PromotedType to the promoted type. 1943 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1944 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1945 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1946 /// An rvalue of type float can be converted to an rvalue of type 1947 /// double. (C++ 4.6p1). 1948 if (FromBuiltin->getKind() == BuiltinType::Float && 1949 ToBuiltin->getKind() == BuiltinType::Double) 1950 return true; 1951 1952 // C99 6.3.1.5p1: 1953 // When a float is promoted to double or long double, or a 1954 // double is promoted to long double [...]. 1955 if (!getLangOpts().CPlusPlus && 1956 (FromBuiltin->getKind() == BuiltinType::Float || 1957 FromBuiltin->getKind() == BuiltinType::Double) && 1958 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1959 return true; 1960 1961 // Half can be promoted to float. 1962 if (!getLangOpts().NativeHalfType && 1963 FromBuiltin->getKind() == BuiltinType::Half && 1964 ToBuiltin->getKind() == BuiltinType::Float) 1965 return true; 1966 } 1967 1968 return false; 1969 } 1970 1971 /// \brief Determine if a conversion is a complex promotion. 1972 /// 1973 /// A complex promotion is defined as a complex -> complex conversion 1974 /// where the conversion between the underlying real types is a 1975 /// floating-point or integral promotion. 1976 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1977 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1978 if (!FromComplex) 1979 return false; 1980 1981 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1982 if (!ToComplex) 1983 return false; 1984 1985 return IsFloatingPointPromotion(FromComplex->getElementType(), 1986 ToComplex->getElementType()) || 1987 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 1988 ToComplex->getElementType()); 1989 } 1990 1991 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1992 /// the pointer type FromPtr to a pointer to type ToPointee, with the 1993 /// same type qualifiers as FromPtr has on its pointee type. ToType, 1994 /// if non-empty, will be a pointer to ToType that may or may not have 1995 /// the right set of qualifiers on its pointee. 1996 /// 1997 static QualType 1998 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1999 QualType ToPointee, QualType ToType, 2000 ASTContext &Context, 2001 bool StripObjCLifetime = false) { 2002 assert((FromPtr->getTypeClass() == Type::Pointer || 2003 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2004 "Invalid similarly-qualified pointer type"); 2005 2006 /// Conversions to 'id' subsume cv-qualifier conversions. 2007 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2008 return ToType.getUnqualifiedType(); 2009 2010 QualType CanonFromPointee 2011 = Context.getCanonicalType(FromPtr->getPointeeType()); 2012 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2013 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2014 2015 if (StripObjCLifetime) 2016 Quals.removeObjCLifetime(); 2017 2018 // Exact qualifier match -> return the pointer type we're converting to. 2019 if (CanonToPointee.getLocalQualifiers() == Quals) { 2020 // ToType is exactly what we need. Return it. 2021 if (!ToType.isNull()) 2022 return ToType.getUnqualifiedType(); 2023 2024 // Build a pointer to ToPointee. It has the right qualifiers 2025 // already. 2026 if (isa<ObjCObjectPointerType>(ToType)) 2027 return Context.getObjCObjectPointerType(ToPointee); 2028 return Context.getPointerType(ToPointee); 2029 } 2030 2031 // Just build a canonical type that has the right qualifiers. 2032 QualType QualifiedCanonToPointee 2033 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2034 2035 if (isa<ObjCObjectPointerType>(ToType)) 2036 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2037 return Context.getPointerType(QualifiedCanonToPointee); 2038 } 2039 2040 static bool isNullPointerConstantForConversion(Expr *Expr, 2041 bool InOverloadResolution, 2042 ASTContext &Context) { 2043 // Handle value-dependent integral null pointer constants correctly. 2044 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2045 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2046 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2047 return !InOverloadResolution; 2048 2049 return Expr->isNullPointerConstant(Context, 2050 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2051 : Expr::NPC_ValueDependentIsNull); 2052 } 2053 2054 /// IsPointerConversion - Determines whether the conversion of the 2055 /// expression From, which has the (possibly adjusted) type FromType, 2056 /// can be converted to the type ToType via a pointer conversion (C++ 2057 /// 4.10). If so, returns true and places the converted type (that 2058 /// might differ from ToType in its cv-qualifiers at some level) into 2059 /// ConvertedType. 2060 /// 2061 /// This routine also supports conversions to and from block pointers 2062 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2063 /// pointers to interfaces. FIXME: Once we've determined the 2064 /// appropriate overloading rules for Objective-C, we may want to 2065 /// split the Objective-C checks into a different routine; however, 2066 /// GCC seems to consider all of these conversions to be pointer 2067 /// conversions, so for now they live here. IncompatibleObjC will be 2068 /// set if the conversion is an allowed Objective-C conversion that 2069 /// should result in a warning. 2070 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2071 bool InOverloadResolution, 2072 QualType& ConvertedType, 2073 bool &IncompatibleObjC) { 2074 IncompatibleObjC = false; 2075 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2076 IncompatibleObjC)) 2077 return true; 2078 2079 // Conversion from a null pointer constant to any Objective-C pointer type. 2080 if (ToType->isObjCObjectPointerType() && 2081 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2082 ConvertedType = ToType; 2083 return true; 2084 } 2085 2086 // Blocks: Block pointers can be converted to void*. 2087 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2088 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2089 ConvertedType = ToType; 2090 return true; 2091 } 2092 // Blocks: A null pointer constant can be converted to a block 2093 // pointer type. 2094 if (ToType->isBlockPointerType() && 2095 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2096 ConvertedType = ToType; 2097 return true; 2098 } 2099 2100 // If the left-hand-side is nullptr_t, the right side can be a null 2101 // pointer constant. 2102 if (ToType->isNullPtrType() && 2103 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2104 ConvertedType = ToType; 2105 return true; 2106 } 2107 2108 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2109 if (!ToTypePtr) 2110 return false; 2111 2112 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2113 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2114 ConvertedType = ToType; 2115 return true; 2116 } 2117 2118 // Beyond this point, both types need to be pointers 2119 // , including objective-c pointers. 2120 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2121 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2122 !getLangOpts().ObjCAutoRefCount) { 2123 ConvertedType = BuildSimilarlyQualifiedPointerType( 2124 FromType->getAs<ObjCObjectPointerType>(), 2125 ToPointeeType, 2126 ToType, Context); 2127 return true; 2128 } 2129 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2130 if (!FromTypePtr) 2131 return false; 2132 2133 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2134 2135 // If the unqualified pointee types are the same, this can't be a 2136 // pointer conversion, so don't do all of the work below. 2137 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2138 return false; 2139 2140 // An rvalue of type "pointer to cv T," where T is an object type, 2141 // can be converted to an rvalue of type "pointer to cv void" (C++ 2142 // 4.10p2). 2143 if (FromPointeeType->isIncompleteOrObjectType() && 2144 ToPointeeType->isVoidType()) { 2145 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2146 ToPointeeType, 2147 ToType, Context, 2148 /*StripObjCLifetime=*/true); 2149 return true; 2150 } 2151 2152 // MSVC allows implicit function to void* type conversion. 2153 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2154 ToPointeeType->isVoidType()) { 2155 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2156 ToPointeeType, 2157 ToType, Context); 2158 return true; 2159 } 2160 2161 // When we're overloading in C, we allow a special kind of pointer 2162 // conversion for compatible-but-not-identical pointee types. 2163 if (!getLangOpts().CPlusPlus && 2164 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2165 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2166 ToPointeeType, 2167 ToType, Context); 2168 return true; 2169 } 2170 2171 // C++ [conv.ptr]p3: 2172 // 2173 // An rvalue of type "pointer to cv D," where D is a class type, 2174 // can be converted to an rvalue of type "pointer to cv B," where 2175 // B is a base class (clause 10) of D. If B is an inaccessible 2176 // (clause 11) or ambiguous (10.2) base class of D, a program that 2177 // necessitates this conversion is ill-formed. The result of the 2178 // conversion is a pointer to the base class sub-object of the 2179 // derived class object. The null pointer value is converted to 2180 // the null pointer value of the destination type. 2181 // 2182 // Note that we do not check for ambiguity or inaccessibility 2183 // here. That is handled by CheckPointerConversion. 2184 if (getLangOpts().CPlusPlus && 2185 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2186 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2187 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) { 2188 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2189 ToPointeeType, 2190 ToType, Context); 2191 return true; 2192 } 2193 2194 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2195 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2196 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2197 ToPointeeType, 2198 ToType, Context); 2199 return true; 2200 } 2201 2202 return false; 2203 } 2204 2205 /// \brief Adopt the given qualifiers for the given type. 2206 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2207 Qualifiers TQs = T.getQualifiers(); 2208 2209 // Check whether qualifiers already match. 2210 if (TQs == Qs) 2211 return T; 2212 2213 if (Qs.compatiblyIncludes(TQs)) 2214 return Context.getQualifiedType(T, Qs); 2215 2216 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2217 } 2218 2219 /// isObjCPointerConversion - Determines whether this is an 2220 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2221 /// with the same arguments and return values. 2222 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2223 QualType& ConvertedType, 2224 bool &IncompatibleObjC) { 2225 if (!getLangOpts().ObjC1) 2226 return false; 2227 2228 // The set of qualifiers on the type we're converting from. 2229 Qualifiers FromQualifiers = FromType.getQualifiers(); 2230 2231 // First, we handle all conversions on ObjC object pointer types. 2232 const ObjCObjectPointerType* ToObjCPtr = 2233 ToType->getAs<ObjCObjectPointerType>(); 2234 const ObjCObjectPointerType *FromObjCPtr = 2235 FromType->getAs<ObjCObjectPointerType>(); 2236 2237 if (ToObjCPtr && FromObjCPtr) { 2238 // If the pointee types are the same (ignoring qualifications), 2239 // then this is not a pointer conversion. 2240 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2241 FromObjCPtr->getPointeeType())) 2242 return false; 2243 2244 // Conversion between Objective-C pointers. 2245 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2246 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2247 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2248 if (getLangOpts().CPlusPlus && LHS && RHS && 2249 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2250 FromObjCPtr->getPointeeType())) 2251 return false; 2252 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2253 ToObjCPtr->getPointeeType(), 2254 ToType, Context); 2255 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2256 return true; 2257 } 2258 2259 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2260 // Okay: this is some kind of implicit downcast of Objective-C 2261 // interfaces, which is permitted. However, we're going to 2262 // complain about it. 2263 IncompatibleObjC = true; 2264 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2265 ToObjCPtr->getPointeeType(), 2266 ToType, Context); 2267 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2268 return true; 2269 } 2270 } 2271 // Beyond this point, both types need to be C pointers or block pointers. 2272 QualType ToPointeeType; 2273 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2274 ToPointeeType = ToCPtr->getPointeeType(); 2275 else if (const BlockPointerType *ToBlockPtr = 2276 ToType->getAs<BlockPointerType>()) { 2277 // Objective C++: We're able to convert from a pointer to any object 2278 // to a block pointer type. 2279 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2280 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2281 return true; 2282 } 2283 ToPointeeType = ToBlockPtr->getPointeeType(); 2284 } 2285 else if (FromType->getAs<BlockPointerType>() && 2286 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2287 // Objective C++: We're able to convert from a block pointer type to a 2288 // pointer to any object. 2289 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2290 return true; 2291 } 2292 else 2293 return false; 2294 2295 QualType FromPointeeType; 2296 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2297 FromPointeeType = FromCPtr->getPointeeType(); 2298 else if (const BlockPointerType *FromBlockPtr = 2299 FromType->getAs<BlockPointerType>()) 2300 FromPointeeType = FromBlockPtr->getPointeeType(); 2301 else 2302 return false; 2303 2304 // If we have pointers to pointers, recursively check whether this 2305 // is an Objective-C conversion. 2306 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2307 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2308 IncompatibleObjC)) { 2309 // We always complain about this conversion. 2310 IncompatibleObjC = true; 2311 ConvertedType = Context.getPointerType(ConvertedType); 2312 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2313 return true; 2314 } 2315 // Allow conversion of pointee being objective-c pointer to another one; 2316 // as in I* to id. 2317 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2318 ToPointeeType->getAs<ObjCObjectPointerType>() && 2319 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2320 IncompatibleObjC)) { 2321 2322 ConvertedType = Context.getPointerType(ConvertedType); 2323 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2324 return true; 2325 } 2326 2327 // If we have pointers to functions or blocks, check whether the only 2328 // differences in the argument and result types are in Objective-C 2329 // pointer conversions. If so, we permit the conversion (but 2330 // complain about it). 2331 const FunctionProtoType *FromFunctionType 2332 = FromPointeeType->getAs<FunctionProtoType>(); 2333 const FunctionProtoType *ToFunctionType 2334 = ToPointeeType->getAs<FunctionProtoType>(); 2335 if (FromFunctionType && ToFunctionType) { 2336 // If the function types are exactly the same, this isn't an 2337 // Objective-C pointer conversion. 2338 if (Context.getCanonicalType(FromPointeeType) 2339 == Context.getCanonicalType(ToPointeeType)) 2340 return false; 2341 2342 // Perform the quick checks that will tell us whether these 2343 // function types are obviously different. 2344 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2345 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2346 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2347 return false; 2348 2349 bool HasObjCConversion = false; 2350 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2351 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2352 // Okay, the types match exactly. Nothing to do. 2353 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2354 ToFunctionType->getReturnType(), 2355 ConvertedType, IncompatibleObjC)) { 2356 // Okay, we have an Objective-C pointer conversion. 2357 HasObjCConversion = true; 2358 } else { 2359 // Function types are too different. Abort. 2360 return false; 2361 } 2362 2363 // Check argument types. 2364 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2365 ArgIdx != NumArgs; ++ArgIdx) { 2366 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2367 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2368 if (Context.getCanonicalType(FromArgType) 2369 == Context.getCanonicalType(ToArgType)) { 2370 // Okay, the types match exactly. Nothing to do. 2371 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2372 ConvertedType, IncompatibleObjC)) { 2373 // Okay, we have an Objective-C pointer conversion. 2374 HasObjCConversion = true; 2375 } else { 2376 // Argument types are too different. Abort. 2377 return false; 2378 } 2379 } 2380 2381 if (HasObjCConversion) { 2382 // We had an Objective-C conversion. Allow this pointer 2383 // conversion, but complain about it. 2384 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2385 IncompatibleObjC = true; 2386 return true; 2387 } 2388 } 2389 2390 return false; 2391 } 2392 2393 /// \brief Determine whether this is an Objective-C writeback conversion, 2394 /// used for parameter passing when performing automatic reference counting. 2395 /// 2396 /// \param FromType The type we're converting form. 2397 /// 2398 /// \param ToType The type we're converting to. 2399 /// 2400 /// \param ConvertedType The type that will be produced after applying 2401 /// this conversion. 2402 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2403 QualType &ConvertedType) { 2404 if (!getLangOpts().ObjCAutoRefCount || 2405 Context.hasSameUnqualifiedType(FromType, ToType)) 2406 return false; 2407 2408 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2409 QualType ToPointee; 2410 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2411 ToPointee = ToPointer->getPointeeType(); 2412 else 2413 return false; 2414 2415 Qualifiers ToQuals = ToPointee.getQualifiers(); 2416 if (!ToPointee->isObjCLifetimeType() || 2417 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2418 !ToQuals.withoutObjCLifetime().empty()) 2419 return false; 2420 2421 // Argument must be a pointer to __strong to __weak. 2422 QualType FromPointee; 2423 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2424 FromPointee = FromPointer->getPointeeType(); 2425 else 2426 return false; 2427 2428 Qualifiers FromQuals = FromPointee.getQualifiers(); 2429 if (!FromPointee->isObjCLifetimeType() || 2430 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2431 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2432 return false; 2433 2434 // Make sure that we have compatible qualifiers. 2435 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2436 if (!ToQuals.compatiblyIncludes(FromQuals)) 2437 return false; 2438 2439 // Remove qualifiers from the pointee type we're converting from; they 2440 // aren't used in the compatibility check belong, and we'll be adding back 2441 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2442 FromPointee = FromPointee.getUnqualifiedType(); 2443 2444 // The unqualified form of the pointee types must be compatible. 2445 ToPointee = ToPointee.getUnqualifiedType(); 2446 bool IncompatibleObjC; 2447 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2448 FromPointee = ToPointee; 2449 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2450 IncompatibleObjC)) 2451 return false; 2452 2453 /// \brief Construct the type we're converting to, which is a pointer to 2454 /// __autoreleasing pointee. 2455 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2456 ConvertedType = Context.getPointerType(FromPointee); 2457 return true; 2458 } 2459 2460 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2461 QualType& ConvertedType) { 2462 QualType ToPointeeType; 2463 if (const BlockPointerType *ToBlockPtr = 2464 ToType->getAs<BlockPointerType>()) 2465 ToPointeeType = ToBlockPtr->getPointeeType(); 2466 else 2467 return false; 2468 2469 QualType FromPointeeType; 2470 if (const BlockPointerType *FromBlockPtr = 2471 FromType->getAs<BlockPointerType>()) 2472 FromPointeeType = FromBlockPtr->getPointeeType(); 2473 else 2474 return false; 2475 // We have pointer to blocks, check whether the only 2476 // differences in the argument and result types are in Objective-C 2477 // pointer conversions. If so, we permit the conversion. 2478 2479 const FunctionProtoType *FromFunctionType 2480 = FromPointeeType->getAs<FunctionProtoType>(); 2481 const FunctionProtoType *ToFunctionType 2482 = ToPointeeType->getAs<FunctionProtoType>(); 2483 2484 if (!FromFunctionType || !ToFunctionType) 2485 return false; 2486 2487 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2488 return true; 2489 2490 // Perform the quick checks that will tell us whether these 2491 // function types are obviously different. 2492 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2493 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2494 return false; 2495 2496 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2497 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2498 if (FromEInfo != ToEInfo) 2499 return false; 2500 2501 bool IncompatibleObjC = false; 2502 if (Context.hasSameType(FromFunctionType->getReturnType(), 2503 ToFunctionType->getReturnType())) { 2504 // Okay, the types match exactly. Nothing to do. 2505 } else { 2506 QualType RHS = FromFunctionType->getReturnType(); 2507 QualType LHS = ToFunctionType->getReturnType(); 2508 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2509 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2510 LHS = LHS.getUnqualifiedType(); 2511 2512 if (Context.hasSameType(RHS,LHS)) { 2513 // OK exact match. 2514 } else if (isObjCPointerConversion(RHS, LHS, 2515 ConvertedType, IncompatibleObjC)) { 2516 if (IncompatibleObjC) 2517 return false; 2518 // Okay, we have an Objective-C pointer conversion. 2519 } 2520 else 2521 return false; 2522 } 2523 2524 // Check argument types. 2525 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2526 ArgIdx != NumArgs; ++ArgIdx) { 2527 IncompatibleObjC = false; 2528 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2529 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2530 if (Context.hasSameType(FromArgType, ToArgType)) { 2531 // Okay, the types match exactly. Nothing to do. 2532 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2533 ConvertedType, IncompatibleObjC)) { 2534 if (IncompatibleObjC) 2535 return false; 2536 // Okay, we have an Objective-C pointer conversion. 2537 } else 2538 // Argument types are too different. Abort. 2539 return false; 2540 } 2541 if (LangOpts.ObjCAutoRefCount && 2542 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2543 ToFunctionType)) 2544 return false; 2545 2546 ConvertedType = ToType; 2547 return true; 2548 } 2549 2550 enum { 2551 ft_default, 2552 ft_different_class, 2553 ft_parameter_arity, 2554 ft_parameter_mismatch, 2555 ft_return_type, 2556 ft_qualifer_mismatch 2557 }; 2558 2559 /// Attempts to get the FunctionProtoType from a Type. Handles 2560 /// MemberFunctionPointers properly. 2561 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2562 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2563 return FPT; 2564 2565 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2566 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2567 2568 return nullptr; 2569 } 2570 2571 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2572 /// function types. Catches different number of parameter, mismatch in 2573 /// parameter types, and different return types. 2574 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2575 QualType FromType, QualType ToType) { 2576 // If either type is not valid, include no extra info. 2577 if (FromType.isNull() || ToType.isNull()) { 2578 PDiag << ft_default; 2579 return; 2580 } 2581 2582 // Get the function type from the pointers. 2583 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2584 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2585 *ToMember = ToType->getAs<MemberPointerType>(); 2586 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2587 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2588 << QualType(FromMember->getClass(), 0); 2589 return; 2590 } 2591 FromType = FromMember->getPointeeType(); 2592 ToType = ToMember->getPointeeType(); 2593 } 2594 2595 if (FromType->isPointerType()) 2596 FromType = FromType->getPointeeType(); 2597 if (ToType->isPointerType()) 2598 ToType = ToType->getPointeeType(); 2599 2600 // Remove references. 2601 FromType = FromType.getNonReferenceType(); 2602 ToType = ToType.getNonReferenceType(); 2603 2604 // Don't print extra info for non-specialized template functions. 2605 if (FromType->isInstantiationDependentType() && 2606 !FromType->getAs<TemplateSpecializationType>()) { 2607 PDiag << ft_default; 2608 return; 2609 } 2610 2611 // No extra info for same types. 2612 if (Context.hasSameType(FromType, ToType)) { 2613 PDiag << ft_default; 2614 return; 2615 } 2616 2617 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2618 *ToFunction = tryGetFunctionProtoType(ToType); 2619 2620 // Both types need to be function types. 2621 if (!FromFunction || !ToFunction) { 2622 PDiag << ft_default; 2623 return; 2624 } 2625 2626 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2627 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2628 << FromFunction->getNumParams(); 2629 return; 2630 } 2631 2632 // Handle different parameter types. 2633 unsigned ArgPos; 2634 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2635 PDiag << ft_parameter_mismatch << ArgPos + 1 2636 << ToFunction->getParamType(ArgPos) 2637 << FromFunction->getParamType(ArgPos); 2638 return; 2639 } 2640 2641 // Handle different return type. 2642 if (!Context.hasSameType(FromFunction->getReturnType(), 2643 ToFunction->getReturnType())) { 2644 PDiag << ft_return_type << ToFunction->getReturnType() 2645 << FromFunction->getReturnType(); 2646 return; 2647 } 2648 2649 unsigned FromQuals = FromFunction->getTypeQuals(), 2650 ToQuals = ToFunction->getTypeQuals(); 2651 if (FromQuals != ToQuals) { 2652 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2653 return; 2654 } 2655 2656 // Unable to find a difference, so add no extra info. 2657 PDiag << ft_default; 2658 } 2659 2660 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2661 /// for equality of their argument types. Caller has already checked that 2662 /// they have same number of arguments. If the parameters are different, 2663 /// ArgPos will have the parameter index of the first different parameter. 2664 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2665 const FunctionProtoType *NewType, 2666 unsigned *ArgPos) { 2667 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2668 N = NewType->param_type_begin(), 2669 E = OldType->param_type_end(); 2670 O && (O != E); ++O, ++N) { 2671 if (!Context.hasSameType(O->getUnqualifiedType(), 2672 N->getUnqualifiedType())) { 2673 if (ArgPos) 2674 *ArgPos = O - OldType->param_type_begin(); 2675 return false; 2676 } 2677 } 2678 return true; 2679 } 2680 2681 /// CheckPointerConversion - Check the pointer conversion from the 2682 /// expression From to the type ToType. This routine checks for 2683 /// ambiguous or inaccessible derived-to-base pointer 2684 /// conversions for which IsPointerConversion has already returned 2685 /// true. It returns true and produces a diagnostic if there was an 2686 /// error, or returns false otherwise. 2687 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2688 CastKind &Kind, 2689 CXXCastPath& BasePath, 2690 bool IgnoreBaseAccess, 2691 bool Diagnose) { 2692 QualType FromType = From->getType(); 2693 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2694 2695 Kind = CK_BitCast; 2696 2697 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2698 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2699 Expr::NPCK_ZeroExpression) { 2700 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2701 DiagRuntimeBehavior(From->getExprLoc(), From, 2702 PDiag(diag::warn_impcast_bool_to_null_pointer) 2703 << ToType << From->getSourceRange()); 2704 else if (!isUnevaluatedContext()) 2705 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2706 << ToType << From->getSourceRange(); 2707 } 2708 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2709 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2710 QualType FromPointeeType = FromPtrType->getPointeeType(), 2711 ToPointeeType = ToPtrType->getPointeeType(); 2712 2713 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2714 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2715 // We must have a derived-to-base conversion. Check an 2716 // ambiguous or inaccessible conversion. 2717 unsigned InaccessibleID = 0; 2718 unsigned AmbigiousID = 0; 2719 if (Diagnose) { 2720 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2721 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2722 } 2723 if (CheckDerivedToBaseConversion( 2724 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2725 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2726 &BasePath, IgnoreBaseAccess)) 2727 return true; 2728 2729 // The conversion was successful. 2730 Kind = CK_DerivedToBase; 2731 } 2732 2733 if (Diagnose && !IsCStyleOrFunctionalCast && 2734 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2735 assert(getLangOpts().MSVCCompat && 2736 "this should only be possible with MSVCCompat!"); 2737 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2738 << From->getSourceRange(); 2739 } 2740 } 2741 } else if (const ObjCObjectPointerType *ToPtrType = 2742 ToType->getAs<ObjCObjectPointerType>()) { 2743 if (const ObjCObjectPointerType *FromPtrType = 2744 FromType->getAs<ObjCObjectPointerType>()) { 2745 // Objective-C++ conversions are always okay. 2746 // FIXME: We should have a different class of conversions for the 2747 // Objective-C++ implicit conversions. 2748 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2749 return false; 2750 } else if (FromType->isBlockPointerType()) { 2751 Kind = CK_BlockPointerToObjCPointerCast; 2752 } else { 2753 Kind = CK_CPointerToObjCPointerCast; 2754 } 2755 } else if (ToType->isBlockPointerType()) { 2756 if (!FromType->isBlockPointerType()) 2757 Kind = CK_AnyPointerToBlockPointerCast; 2758 } 2759 2760 // We shouldn't fall into this case unless it's valid for other 2761 // reasons. 2762 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2763 Kind = CK_NullToPointer; 2764 2765 return false; 2766 } 2767 2768 /// IsMemberPointerConversion - Determines whether the conversion of the 2769 /// expression From, which has the (possibly adjusted) type FromType, can be 2770 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2771 /// If so, returns true and places the converted type (that might differ from 2772 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2773 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2774 QualType ToType, 2775 bool InOverloadResolution, 2776 QualType &ConvertedType) { 2777 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2778 if (!ToTypePtr) 2779 return false; 2780 2781 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2782 if (From->isNullPointerConstant(Context, 2783 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2784 : Expr::NPC_ValueDependentIsNull)) { 2785 ConvertedType = ToType; 2786 return true; 2787 } 2788 2789 // Otherwise, both types have to be member pointers. 2790 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2791 if (!FromTypePtr) 2792 return false; 2793 2794 // A pointer to member of B can be converted to a pointer to member of D, 2795 // where D is derived from B (C++ 4.11p2). 2796 QualType FromClass(FromTypePtr->getClass(), 0); 2797 QualType ToClass(ToTypePtr->getClass(), 0); 2798 2799 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2800 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) { 2801 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2802 ToClass.getTypePtr()); 2803 return true; 2804 } 2805 2806 return false; 2807 } 2808 2809 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2810 /// expression From to the type ToType. This routine checks for ambiguous or 2811 /// virtual or inaccessible base-to-derived member pointer conversions 2812 /// for which IsMemberPointerConversion has already returned true. It returns 2813 /// true and produces a diagnostic if there was an error, or returns false 2814 /// otherwise. 2815 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2816 CastKind &Kind, 2817 CXXCastPath &BasePath, 2818 bool IgnoreBaseAccess) { 2819 QualType FromType = From->getType(); 2820 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2821 if (!FromPtrType) { 2822 // This must be a null pointer to member pointer conversion 2823 assert(From->isNullPointerConstant(Context, 2824 Expr::NPC_ValueDependentIsNull) && 2825 "Expr must be null pointer constant!"); 2826 Kind = CK_NullToMemberPointer; 2827 return false; 2828 } 2829 2830 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2831 assert(ToPtrType && "No member pointer cast has a target type " 2832 "that is not a member pointer."); 2833 2834 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2835 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2836 2837 // FIXME: What about dependent types? 2838 assert(FromClass->isRecordType() && "Pointer into non-class."); 2839 assert(ToClass->isRecordType() && "Pointer into non-class."); 2840 2841 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2842 /*DetectVirtual=*/true); 2843 bool DerivationOkay = 2844 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths); 2845 assert(DerivationOkay && 2846 "Should not have been called if derivation isn't OK."); 2847 (void)DerivationOkay; 2848 2849 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2850 getUnqualifiedType())) { 2851 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2852 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2853 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2854 return true; 2855 } 2856 2857 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2858 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2859 << FromClass << ToClass << QualType(VBase, 0) 2860 << From->getSourceRange(); 2861 return true; 2862 } 2863 2864 if (!IgnoreBaseAccess) 2865 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2866 Paths.front(), 2867 diag::err_downcast_from_inaccessible_base); 2868 2869 // Must be a base to derived member conversion. 2870 BuildBasePathArray(Paths, BasePath); 2871 Kind = CK_BaseToDerivedMemberPointer; 2872 return false; 2873 } 2874 2875 /// Determine whether the lifetime conversion between the two given 2876 /// qualifiers sets is nontrivial. 2877 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 2878 Qualifiers ToQuals) { 2879 // Converting anything to const __unsafe_unretained is trivial. 2880 if (ToQuals.hasConst() && 2881 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 2882 return false; 2883 2884 return true; 2885 } 2886 2887 /// IsQualificationConversion - Determines whether the conversion from 2888 /// an rvalue of type FromType to ToType is a qualification conversion 2889 /// (C++ 4.4). 2890 /// 2891 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2892 /// when the qualification conversion involves a change in the Objective-C 2893 /// object lifetime. 2894 bool 2895 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2896 bool CStyle, bool &ObjCLifetimeConversion) { 2897 FromType = Context.getCanonicalType(FromType); 2898 ToType = Context.getCanonicalType(ToType); 2899 ObjCLifetimeConversion = false; 2900 2901 // If FromType and ToType are the same type, this is not a 2902 // qualification conversion. 2903 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2904 return false; 2905 2906 // (C++ 4.4p4): 2907 // A conversion can add cv-qualifiers at levels other than the first 2908 // in multi-level pointers, subject to the following rules: [...] 2909 bool PreviousToQualsIncludeConst = true; 2910 bool UnwrappedAnyPointer = false; 2911 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2912 // Within each iteration of the loop, we check the qualifiers to 2913 // determine if this still looks like a qualification 2914 // conversion. Then, if all is well, we unwrap one more level of 2915 // pointers or pointers-to-members and do it all again 2916 // until there are no more pointers or pointers-to-members left to 2917 // unwrap. 2918 UnwrappedAnyPointer = true; 2919 2920 Qualifiers FromQuals = FromType.getQualifiers(); 2921 Qualifiers ToQuals = ToType.getQualifiers(); 2922 2923 // Objective-C ARC: 2924 // Check Objective-C lifetime conversions. 2925 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2926 UnwrappedAnyPointer) { 2927 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2928 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 2929 ObjCLifetimeConversion = true; 2930 FromQuals.removeObjCLifetime(); 2931 ToQuals.removeObjCLifetime(); 2932 } else { 2933 // Qualification conversions cannot cast between different 2934 // Objective-C lifetime qualifiers. 2935 return false; 2936 } 2937 } 2938 2939 // Allow addition/removal of GC attributes but not changing GC attributes. 2940 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2941 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2942 FromQuals.removeObjCGCAttr(); 2943 ToQuals.removeObjCGCAttr(); 2944 } 2945 2946 // -- for every j > 0, if const is in cv 1,j then const is in cv 2947 // 2,j, and similarly for volatile. 2948 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2949 return false; 2950 2951 // -- if the cv 1,j and cv 2,j are different, then const is in 2952 // every cv for 0 < k < j. 2953 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2954 && !PreviousToQualsIncludeConst) 2955 return false; 2956 2957 // Keep track of whether all prior cv-qualifiers in the "to" type 2958 // include const. 2959 PreviousToQualsIncludeConst 2960 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2961 } 2962 2963 // We are left with FromType and ToType being the pointee types 2964 // after unwrapping the original FromType and ToType the same number 2965 // of types. If we unwrapped any pointers, and if FromType and 2966 // ToType have the same unqualified type (since we checked 2967 // qualifiers above), then this is a qualification conversion. 2968 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2969 } 2970 2971 /// \brief - Determine whether this is a conversion from a scalar type to an 2972 /// atomic type. 2973 /// 2974 /// If successful, updates \c SCS's second and third steps in the conversion 2975 /// sequence to finish the conversion. 2976 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2977 bool InOverloadResolution, 2978 StandardConversionSequence &SCS, 2979 bool CStyle) { 2980 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2981 if (!ToAtomic) 2982 return false; 2983 2984 StandardConversionSequence InnerSCS; 2985 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2986 InOverloadResolution, InnerSCS, 2987 CStyle, /*AllowObjCWritebackConversion=*/false)) 2988 return false; 2989 2990 SCS.Second = InnerSCS.Second; 2991 SCS.setToType(1, InnerSCS.getToType(1)); 2992 SCS.Third = InnerSCS.Third; 2993 SCS.QualificationIncludesObjCLifetime 2994 = InnerSCS.QualificationIncludesObjCLifetime; 2995 SCS.setToType(2, InnerSCS.getToType(2)); 2996 return true; 2997 } 2998 2999 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3000 CXXConstructorDecl *Constructor, 3001 QualType Type) { 3002 const FunctionProtoType *CtorType = 3003 Constructor->getType()->getAs<FunctionProtoType>(); 3004 if (CtorType->getNumParams() > 0) { 3005 QualType FirstArg = CtorType->getParamType(0); 3006 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3007 return true; 3008 } 3009 return false; 3010 } 3011 3012 static OverloadingResult 3013 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3014 CXXRecordDecl *To, 3015 UserDefinedConversionSequence &User, 3016 OverloadCandidateSet &CandidateSet, 3017 bool AllowExplicit) { 3018 DeclContext::lookup_result R = S.LookupConstructors(To); 3019 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3020 Con != ConEnd; ++Con) { 3021 NamedDecl *D = *Con; 3022 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3023 3024 // Find the constructor (which may be a template). 3025 CXXConstructorDecl *Constructor = nullptr; 3026 FunctionTemplateDecl *ConstructorTmpl 3027 = dyn_cast<FunctionTemplateDecl>(D); 3028 if (ConstructorTmpl) 3029 Constructor 3030 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3031 else 3032 Constructor = cast<CXXConstructorDecl>(D); 3033 3034 bool Usable = !Constructor->isInvalidDecl() && 3035 S.isInitListConstructor(Constructor) && 3036 (AllowExplicit || !Constructor->isExplicit()); 3037 if (Usable) { 3038 // If the first argument is (a reference to) the target type, 3039 // suppress conversions. 3040 bool SuppressUserConversions = 3041 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 3042 if (ConstructorTmpl) 3043 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3044 /*ExplicitArgs*/ nullptr, 3045 From, CandidateSet, 3046 SuppressUserConversions); 3047 else 3048 S.AddOverloadCandidate(Constructor, FoundDecl, 3049 From, CandidateSet, 3050 SuppressUserConversions); 3051 } 3052 } 3053 3054 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3055 3056 OverloadCandidateSet::iterator Best; 3057 switch (auto Result = 3058 CandidateSet.BestViableFunction(S, From->getLocStart(), 3059 Best, true)) { 3060 case OR_Deleted: 3061 case OR_Success: { 3062 // Record the standard conversion we used and the conversion function. 3063 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3064 QualType ThisType = Constructor->getThisType(S.Context); 3065 // Initializer lists don't have conversions as such. 3066 User.Before.setAsIdentityConversion(); 3067 User.HadMultipleCandidates = HadMultipleCandidates; 3068 User.ConversionFunction = Constructor; 3069 User.FoundConversionFunction = Best->FoundDecl; 3070 User.After.setAsIdentityConversion(); 3071 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3072 User.After.setAllToTypes(ToType); 3073 return Result; 3074 } 3075 3076 case OR_No_Viable_Function: 3077 return OR_No_Viable_Function; 3078 case OR_Ambiguous: 3079 return OR_Ambiguous; 3080 } 3081 3082 llvm_unreachable("Invalid OverloadResult!"); 3083 } 3084 3085 /// Determines whether there is a user-defined conversion sequence 3086 /// (C++ [over.ics.user]) that converts expression From to the type 3087 /// ToType. If such a conversion exists, User will contain the 3088 /// user-defined conversion sequence that performs such a conversion 3089 /// and this routine will return true. Otherwise, this routine returns 3090 /// false and User is unspecified. 3091 /// 3092 /// \param AllowExplicit true if the conversion should consider C++0x 3093 /// "explicit" conversion functions as well as non-explicit conversion 3094 /// functions (C++0x [class.conv.fct]p2). 3095 /// 3096 /// \param AllowObjCConversionOnExplicit true if the conversion should 3097 /// allow an extra Objective-C pointer conversion on uses of explicit 3098 /// constructors. Requires \c AllowExplicit to also be set. 3099 static OverloadingResult 3100 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3101 UserDefinedConversionSequence &User, 3102 OverloadCandidateSet &CandidateSet, 3103 bool AllowExplicit, 3104 bool AllowObjCConversionOnExplicit) { 3105 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3106 3107 // Whether we will only visit constructors. 3108 bool ConstructorsOnly = false; 3109 3110 // If the type we are conversion to is a class type, enumerate its 3111 // constructors. 3112 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3113 // C++ [over.match.ctor]p1: 3114 // When objects of class type are direct-initialized (8.5), or 3115 // copy-initialized from an expression of the same or a 3116 // derived class type (8.5), overload resolution selects the 3117 // constructor. [...] For copy-initialization, the candidate 3118 // functions are all the converting constructors (12.3.1) of 3119 // that class. The argument list is the expression-list within 3120 // the parentheses of the initializer. 3121 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3122 (From->getType()->getAs<RecordType>() && 3123 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType))) 3124 ConstructorsOnly = true; 3125 3126 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3127 // We're not going to find any constructors. 3128 } else if (CXXRecordDecl *ToRecordDecl 3129 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3130 3131 Expr **Args = &From; 3132 unsigned NumArgs = 1; 3133 bool ListInitializing = false; 3134 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3135 // But first, see if there is an init-list-constructor that will work. 3136 OverloadingResult Result = IsInitializerListConstructorConversion( 3137 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3138 if (Result != OR_No_Viable_Function) 3139 return Result; 3140 // Never mind. 3141 CandidateSet.clear(); 3142 3143 // If we're list-initializing, we pass the individual elements as 3144 // arguments, not the entire list. 3145 Args = InitList->getInits(); 3146 NumArgs = InitList->getNumInits(); 3147 ListInitializing = true; 3148 } 3149 3150 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3151 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3152 Con != ConEnd; ++Con) { 3153 NamedDecl *D = *Con; 3154 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3155 3156 // Find the constructor (which may be a template). 3157 CXXConstructorDecl *Constructor = nullptr; 3158 FunctionTemplateDecl *ConstructorTmpl 3159 = dyn_cast<FunctionTemplateDecl>(D); 3160 if (ConstructorTmpl) 3161 Constructor 3162 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3163 else 3164 Constructor = cast<CXXConstructorDecl>(D); 3165 3166 bool Usable = !Constructor->isInvalidDecl(); 3167 if (ListInitializing) 3168 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3169 else 3170 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3171 if (Usable) { 3172 bool SuppressUserConversions = !ConstructorsOnly; 3173 if (SuppressUserConversions && ListInitializing) { 3174 SuppressUserConversions = false; 3175 if (NumArgs == 1) { 3176 // If the first argument is (a reference to) the target type, 3177 // suppress conversions. 3178 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3179 S.Context, Constructor, ToType); 3180 } 3181 } 3182 if (ConstructorTmpl) 3183 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3184 /*ExplicitArgs*/ nullptr, 3185 llvm::makeArrayRef(Args, NumArgs), 3186 CandidateSet, SuppressUserConversions); 3187 else 3188 // Allow one user-defined conversion when user specifies a 3189 // From->ToType conversion via an static cast (c-style, etc). 3190 S.AddOverloadCandidate(Constructor, FoundDecl, 3191 llvm::makeArrayRef(Args, NumArgs), 3192 CandidateSet, SuppressUserConversions); 3193 } 3194 } 3195 } 3196 } 3197 3198 // Enumerate conversion functions, if we're allowed to. 3199 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3200 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) { 3201 // No conversion functions from incomplete types. 3202 } else if (const RecordType *FromRecordType 3203 = From->getType()->getAs<RecordType>()) { 3204 if (CXXRecordDecl *FromRecordDecl 3205 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3206 // Add all of the conversion functions as candidates. 3207 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3208 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3209 DeclAccessPair FoundDecl = I.getPair(); 3210 NamedDecl *D = FoundDecl.getDecl(); 3211 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3212 if (isa<UsingShadowDecl>(D)) 3213 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3214 3215 CXXConversionDecl *Conv; 3216 FunctionTemplateDecl *ConvTemplate; 3217 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3218 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3219 else 3220 Conv = cast<CXXConversionDecl>(D); 3221 3222 if (AllowExplicit || !Conv->isExplicit()) { 3223 if (ConvTemplate) 3224 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3225 ActingContext, From, ToType, 3226 CandidateSet, 3227 AllowObjCConversionOnExplicit); 3228 else 3229 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3230 From, ToType, CandidateSet, 3231 AllowObjCConversionOnExplicit); 3232 } 3233 } 3234 } 3235 } 3236 3237 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3238 3239 OverloadCandidateSet::iterator Best; 3240 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(), 3241 Best, true)) { 3242 case OR_Success: 3243 case OR_Deleted: 3244 // Record the standard conversion we used and the conversion function. 3245 if (CXXConstructorDecl *Constructor 3246 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3247 // C++ [over.ics.user]p1: 3248 // If the user-defined conversion is specified by a 3249 // constructor (12.3.1), the initial standard conversion 3250 // sequence converts the source type to the type required by 3251 // the argument of the constructor. 3252 // 3253 QualType ThisType = Constructor->getThisType(S.Context); 3254 if (isa<InitListExpr>(From)) { 3255 // Initializer lists don't have conversions as such. 3256 User.Before.setAsIdentityConversion(); 3257 } else { 3258 if (Best->Conversions[0].isEllipsis()) 3259 User.EllipsisConversion = true; 3260 else { 3261 User.Before = Best->Conversions[0].Standard; 3262 User.EllipsisConversion = false; 3263 } 3264 } 3265 User.HadMultipleCandidates = HadMultipleCandidates; 3266 User.ConversionFunction = Constructor; 3267 User.FoundConversionFunction = Best->FoundDecl; 3268 User.After.setAsIdentityConversion(); 3269 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3270 User.After.setAllToTypes(ToType); 3271 return Result; 3272 } 3273 if (CXXConversionDecl *Conversion 3274 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3275 // C++ [over.ics.user]p1: 3276 // 3277 // [...] If the user-defined conversion is specified by a 3278 // conversion function (12.3.2), the initial standard 3279 // conversion sequence converts the source type to the 3280 // implicit object parameter of the conversion function. 3281 User.Before = Best->Conversions[0].Standard; 3282 User.HadMultipleCandidates = HadMultipleCandidates; 3283 User.ConversionFunction = Conversion; 3284 User.FoundConversionFunction = Best->FoundDecl; 3285 User.EllipsisConversion = false; 3286 3287 // C++ [over.ics.user]p2: 3288 // The second standard conversion sequence converts the 3289 // result of the user-defined conversion to the target type 3290 // for the sequence. Since an implicit conversion sequence 3291 // is an initialization, the special rules for 3292 // initialization by user-defined conversion apply when 3293 // selecting the best user-defined conversion for a 3294 // user-defined conversion sequence (see 13.3.3 and 3295 // 13.3.3.1). 3296 User.After = Best->FinalConversion; 3297 return Result; 3298 } 3299 llvm_unreachable("Not a constructor or conversion function?"); 3300 3301 case OR_No_Viable_Function: 3302 return OR_No_Viable_Function; 3303 3304 case OR_Ambiguous: 3305 return OR_Ambiguous; 3306 } 3307 3308 llvm_unreachable("Invalid OverloadResult!"); 3309 } 3310 3311 bool 3312 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3313 ImplicitConversionSequence ICS; 3314 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3315 OverloadCandidateSet::CSK_Normal); 3316 OverloadingResult OvResult = 3317 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3318 CandidateSet, false, false); 3319 if (OvResult == OR_Ambiguous) 3320 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3321 << From->getType() << ToType << From->getSourceRange(); 3322 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3323 if (!RequireCompleteType(From->getLocStart(), ToType, 3324 diag::err_typecheck_nonviable_condition_incomplete, 3325 From->getType(), From->getSourceRange())) 3326 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3327 << false << From->getType() << From->getSourceRange() << ToType; 3328 } else 3329 return false; 3330 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3331 return true; 3332 } 3333 3334 /// \brief Compare the user-defined conversion functions or constructors 3335 /// of two user-defined conversion sequences to determine whether any ordering 3336 /// is possible. 3337 static ImplicitConversionSequence::CompareKind 3338 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3339 FunctionDecl *Function2) { 3340 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3341 return ImplicitConversionSequence::Indistinguishable; 3342 3343 // Objective-C++: 3344 // If both conversion functions are implicitly-declared conversions from 3345 // a lambda closure type to a function pointer and a block pointer, 3346 // respectively, always prefer the conversion to a function pointer, 3347 // because the function pointer is more lightweight and is more likely 3348 // to keep code working. 3349 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3350 if (!Conv1) 3351 return ImplicitConversionSequence::Indistinguishable; 3352 3353 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3354 if (!Conv2) 3355 return ImplicitConversionSequence::Indistinguishable; 3356 3357 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3358 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3359 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3360 if (Block1 != Block2) 3361 return Block1 ? ImplicitConversionSequence::Worse 3362 : ImplicitConversionSequence::Better; 3363 } 3364 3365 return ImplicitConversionSequence::Indistinguishable; 3366 } 3367 3368 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3369 const ImplicitConversionSequence &ICS) { 3370 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3371 (ICS.isUserDefined() && 3372 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3373 } 3374 3375 /// CompareImplicitConversionSequences - Compare two implicit 3376 /// conversion sequences to determine whether one is better than the 3377 /// other or if they are indistinguishable (C++ 13.3.3.2). 3378 static ImplicitConversionSequence::CompareKind 3379 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3380 const ImplicitConversionSequence& ICS1, 3381 const ImplicitConversionSequence& ICS2) 3382 { 3383 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3384 // conversion sequences (as defined in 13.3.3.1) 3385 // -- a standard conversion sequence (13.3.3.1.1) is a better 3386 // conversion sequence than a user-defined conversion sequence or 3387 // an ellipsis conversion sequence, and 3388 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3389 // conversion sequence than an ellipsis conversion sequence 3390 // (13.3.3.1.3). 3391 // 3392 // C++0x [over.best.ics]p10: 3393 // For the purpose of ranking implicit conversion sequences as 3394 // described in 13.3.3.2, the ambiguous conversion sequence is 3395 // treated as a user-defined sequence that is indistinguishable 3396 // from any other user-defined conversion sequence. 3397 3398 // String literal to 'char *' conversion has been deprecated in C++03. It has 3399 // been removed from C++11. We still accept this conversion, if it happens at 3400 // the best viable function. Otherwise, this conversion is considered worse 3401 // than ellipsis conversion. Consider this as an extension; this is not in the 3402 // standard. For example: 3403 // 3404 // int &f(...); // #1 3405 // void f(char*); // #2 3406 // void g() { int &r = f("foo"); } 3407 // 3408 // In C++03, we pick #2 as the best viable function. 3409 // In C++11, we pick #1 as the best viable function, because ellipsis 3410 // conversion is better than string-literal to char* conversion (since there 3411 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3412 // convert arguments, #2 would be the best viable function in C++11. 3413 // If the best viable function has this conversion, a warning will be issued 3414 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3415 3416 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3417 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3418 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3419 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3420 ? ImplicitConversionSequence::Worse 3421 : ImplicitConversionSequence::Better; 3422 3423 if (ICS1.getKindRank() < ICS2.getKindRank()) 3424 return ImplicitConversionSequence::Better; 3425 if (ICS2.getKindRank() < ICS1.getKindRank()) 3426 return ImplicitConversionSequence::Worse; 3427 3428 // The following checks require both conversion sequences to be of 3429 // the same kind. 3430 if (ICS1.getKind() != ICS2.getKind()) 3431 return ImplicitConversionSequence::Indistinguishable; 3432 3433 ImplicitConversionSequence::CompareKind Result = 3434 ImplicitConversionSequence::Indistinguishable; 3435 3436 // Two implicit conversion sequences of the same form are 3437 // indistinguishable conversion sequences unless one of the 3438 // following rules apply: (C++ 13.3.3.2p3): 3439 3440 // List-initialization sequence L1 is a better conversion sequence than 3441 // list-initialization sequence L2 if: 3442 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3443 // if not that, 3444 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3445 // and N1 is smaller than N2., 3446 // even if one of the other rules in this paragraph would otherwise apply. 3447 if (!ICS1.isBad()) { 3448 if (ICS1.isStdInitializerListElement() && 3449 !ICS2.isStdInitializerListElement()) 3450 return ImplicitConversionSequence::Better; 3451 if (!ICS1.isStdInitializerListElement() && 3452 ICS2.isStdInitializerListElement()) 3453 return ImplicitConversionSequence::Worse; 3454 } 3455 3456 if (ICS1.isStandard()) 3457 // Standard conversion sequence S1 is a better conversion sequence than 3458 // standard conversion sequence S2 if [...] 3459 Result = CompareStandardConversionSequences(S, Loc, 3460 ICS1.Standard, ICS2.Standard); 3461 else if (ICS1.isUserDefined()) { 3462 // User-defined conversion sequence U1 is a better conversion 3463 // sequence than another user-defined conversion sequence U2 if 3464 // they contain the same user-defined conversion function or 3465 // constructor and if the second standard conversion sequence of 3466 // U1 is better than the second standard conversion sequence of 3467 // U2 (C++ 13.3.3.2p3). 3468 if (ICS1.UserDefined.ConversionFunction == 3469 ICS2.UserDefined.ConversionFunction) 3470 Result = CompareStandardConversionSequences(S, Loc, 3471 ICS1.UserDefined.After, 3472 ICS2.UserDefined.After); 3473 else 3474 Result = compareConversionFunctions(S, 3475 ICS1.UserDefined.ConversionFunction, 3476 ICS2.UserDefined.ConversionFunction); 3477 } 3478 3479 return Result; 3480 } 3481 3482 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3483 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3484 Qualifiers Quals; 3485 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3486 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3487 } 3488 3489 return Context.hasSameUnqualifiedType(T1, T2); 3490 } 3491 3492 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3493 // determine if one is a proper subset of the other. 3494 static ImplicitConversionSequence::CompareKind 3495 compareStandardConversionSubsets(ASTContext &Context, 3496 const StandardConversionSequence& SCS1, 3497 const StandardConversionSequence& SCS2) { 3498 ImplicitConversionSequence::CompareKind Result 3499 = ImplicitConversionSequence::Indistinguishable; 3500 3501 // the identity conversion sequence is considered to be a subsequence of 3502 // any non-identity conversion sequence 3503 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3504 return ImplicitConversionSequence::Better; 3505 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3506 return ImplicitConversionSequence::Worse; 3507 3508 if (SCS1.Second != SCS2.Second) { 3509 if (SCS1.Second == ICK_Identity) 3510 Result = ImplicitConversionSequence::Better; 3511 else if (SCS2.Second == ICK_Identity) 3512 Result = ImplicitConversionSequence::Worse; 3513 else 3514 return ImplicitConversionSequence::Indistinguishable; 3515 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3516 return ImplicitConversionSequence::Indistinguishable; 3517 3518 if (SCS1.Third == SCS2.Third) { 3519 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3520 : ImplicitConversionSequence::Indistinguishable; 3521 } 3522 3523 if (SCS1.Third == ICK_Identity) 3524 return Result == ImplicitConversionSequence::Worse 3525 ? ImplicitConversionSequence::Indistinguishable 3526 : ImplicitConversionSequence::Better; 3527 3528 if (SCS2.Third == ICK_Identity) 3529 return Result == ImplicitConversionSequence::Better 3530 ? ImplicitConversionSequence::Indistinguishable 3531 : ImplicitConversionSequence::Worse; 3532 3533 return ImplicitConversionSequence::Indistinguishable; 3534 } 3535 3536 /// \brief Determine whether one of the given reference bindings is better 3537 /// than the other based on what kind of bindings they are. 3538 static bool 3539 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3540 const StandardConversionSequence &SCS2) { 3541 // C++0x [over.ics.rank]p3b4: 3542 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3543 // implicit object parameter of a non-static member function declared 3544 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3545 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3546 // lvalue reference to a function lvalue and S2 binds an rvalue 3547 // reference*. 3548 // 3549 // FIXME: Rvalue references. We're going rogue with the above edits, 3550 // because the semantics in the current C++0x working paper (N3225 at the 3551 // time of this writing) break the standard definition of std::forward 3552 // and std::reference_wrapper when dealing with references to functions. 3553 // Proposed wording changes submitted to CWG for consideration. 3554 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3555 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3556 return false; 3557 3558 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3559 SCS2.IsLvalueReference) || 3560 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3561 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3562 } 3563 3564 /// CompareStandardConversionSequences - Compare two standard 3565 /// conversion sequences to determine whether one is better than the 3566 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3567 static ImplicitConversionSequence::CompareKind 3568 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3569 const StandardConversionSequence& SCS1, 3570 const StandardConversionSequence& SCS2) 3571 { 3572 // Standard conversion sequence S1 is a better conversion sequence 3573 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3574 3575 // -- S1 is a proper subsequence of S2 (comparing the conversion 3576 // sequences in the canonical form defined by 13.3.3.1.1, 3577 // excluding any Lvalue Transformation; the identity conversion 3578 // sequence is considered to be a subsequence of any 3579 // non-identity conversion sequence) or, if not that, 3580 if (ImplicitConversionSequence::CompareKind CK 3581 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3582 return CK; 3583 3584 // -- the rank of S1 is better than the rank of S2 (by the rules 3585 // defined below), or, if not that, 3586 ImplicitConversionRank Rank1 = SCS1.getRank(); 3587 ImplicitConversionRank Rank2 = SCS2.getRank(); 3588 if (Rank1 < Rank2) 3589 return ImplicitConversionSequence::Better; 3590 else if (Rank2 < Rank1) 3591 return ImplicitConversionSequence::Worse; 3592 3593 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3594 // are indistinguishable unless one of the following rules 3595 // applies: 3596 3597 // A conversion that is not a conversion of a pointer, or 3598 // pointer to member, to bool is better than another conversion 3599 // that is such a conversion. 3600 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3601 return SCS2.isPointerConversionToBool() 3602 ? ImplicitConversionSequence::Better 3603 : ImplicitConversionSequence::Worse; 3604 3605 // C++ [over.ics.rank]p4b2: 3606 // 3607 // If class B is derived directly or indirectly from class A, 3608 // conversion of B* to A* is better than conversion of B* to 3609 // void*, and conversion of A* to void* is better than conversion 3610 // of B* to void*. 3611 bool SCS1ConvertsToVoid 3612 = SCS1.isPointerConversionToVoidPointer(S.Context); 3613 bool SCS2ConvertsToVoid 3614 = SCS2.isPointerConversionToVoidPointer(S.Context); 3615 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3616 // Exactly one of the conversion sequences is a conversion to 3617 // a void pointer; it's the worse conversion. 3618 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3619 : ImplicitConversionSequence::Worse; 3620 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3621 // Neither conversion sequence converts to a void pointer; compare 3622 // their derived-to-base conversions. 3623 if (ImplicitConversionSequence::CompareKind DerivedCK 3624 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3625 return DerivedCK; 3626 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3627 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3628 // Both conversion sequences are conversions to void 3629 // pointers. Compare the source types to determine if there's an 3630 // inheritance relationship in their sources. 3631 QualType FromType1 = SCS1.getFromType(); 3632 QualType FromType2 = SCS2.getFromType(); 3633 3634 // Adjust the types we're converting from via the array-to-pointer 3635 // conversion, if we need to. 3636 if (SCS1.First == ICK_Array_To_Pointer) 3637 FromType1 = S.Context.getArrayDecayedType(FromType1); 3638 if (SCS2.First == ICK_Array_To_Pointer) 3639 FromType2 = S.Context.getArrayDecayedType(FromType2); 3640 3641 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3642 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3643 3644 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3645 return ImplicitConversionSequence::Better; 3646 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3647 return ImplicitConversionSequence::Worse; 3648 3649 // Objective-C++: If one interface is more specific than the 3650 // other, it is the better one. 3651 const ObjCObjectPointerType* FromObjCPtr1 3652 = FromType1->getAs<ObjCObjectPointerType>(); 3653 const ObjCObjectPointerType* FromObjCPtr2 3654 = FromType2->getAs<ObjCObjectPointerType>(); 3655 if (FromObjCPtr1 && FromObjCPtr2) { 3656 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3657 FromObjCPtr2); 3658 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3659 FromObjCPtr1); 3660 if (AssignLeft != AssignRight) { 3661 return AssignLeft? ImplicitConversionSequence::Better 3662 : ImplicitConversionSequence::Worse; 3663 } 3664 } 3665 } 3666 3667 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3668 // bullet 3). 3669 if (ImplicitConversionSequence::CompareKind QualCK 3670 = CompareQualificationConversions(S, SCS1, SCS2)) 3671 return QualCK; 3672 3673 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3674 // Check for a better reference binding based on the kind of bindings. 3675 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3676 return ImplicitConversionSequence::Better; 3677 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3678 return ImplicitConversionSequence::Worse; 3679 3680 // C++ [over.ics.rank]p3b4: 3681 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3682 // which the references refer are the same type except for 3683 // top-level cv-qualifiers, and the type to which the reference 3684 // initialized by S2 refers is more cv-qualified than the type 3685 // to which the reference initialized by S1 refers. 3686 QualType T1 = SCS1.getToType(2); 3687 QualType T2 = SCS2.getToType(2); 3688 T1 = S.Context.getCanonicalType(T1); 3689 T2 = S.Context.getCanonicalType(T2); 3690 Qualifiers T1Quals, T2Quals; 3691 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3692 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3693 if (UnqualT1 == UnqualT2) { 3694 // Objective-C++ ARC: If the references refer to objects with different 3695 // lifetimes, prefer bindings that don't change lifetime. 3696 if (SCS1.ObjCLifetimeConversionBinding != 3697 SCS2.ObjCLifetimeConversionBinding) { 3698 return SCS1.ObjCLifetimeConversionBinding 3699 ? ImplicitConversionSequence::Worse 3700 : ImplicitConversionSequence::Better; 3701 } 3702 3703 // If the type is an array type, promote the element qualifiers to the 3704 // type for comparison. 3705 if (isa<ArrayType>(T1) && T1Quals) 3706 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3707 if (isa<ArrayType>(T2) && T2Quals) 3708 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3709 if (T2.isMoreQualifiedThan(T1)) 3710 return ImplicitConversionSequence::Better; 3711 else if (T1.isMoreQualifiedThan(T2)) 3712 return ImplicitConversionSequence::Worse; 3713 } 3714 } 3715 3716 // In Microsoft mode, prefer an integral conversion to a 3717 // floating-to-integral conversion if the integral conversion 3718 // is between types of the same size. 3719 // For example: 3720 // void f(float); 3721 // void f(int); 3722 // int main { 3723 // long a; 3724 // f(a); 3725 // } 3726 // Here, MSVC will call f(int) instead of generating a compile error 3727 // as clang will do in standard mode. 3728 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3729 SCS2.Second == ICK_Floating_Integral && 3730 S.Context.getTypeSize(SCS1.getFromType()) == 3731 S.Context.getTypeSize(SCS1.getToType(2))) 3732 return ImplicitConversionSequence::Better; 3733 3734 return ImplicitConversionSequence::Indistinguishable; 3735 } 3736 3737 /// CompareQualificationConversions - Compares two standard conversion 3738 /// sequences to determine whether they can be ranked based on their 3739 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3740 static ImplicitConversionSequence::CompareKind 3741 CompareQualificationConversions(Sema &S, 3742 const StandardConversionSequence& SCS1, 3743 const StandardConversionSequence& SCS2) { 3744 // C++ 13.3.3.2p3: 3745 // -- S1 and S2 differ only in their qualification conversion and 3746 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3747 // cv-qualification signature of type T1 is a proper subset of 3748 // the cv-qualification signature of type T2, and S1 is not the 3749 // deprecated string literal array-to-pointer conversion (4.2). 3750 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3751 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3752 return ImplicitConversionSequence::Indistinguishable; 3753 3754 // FIXME: the example in the standard doesn't use a qualification 3755 // conversion (!) 3756 QualType T1 = SCS1.getToType(2); 3757 QualType T2 = SCS2.getToType(2); 3758 T1 = S.Context.getCanonicalType(T1); 3759 T2 = S.Context.getCanonicalType(T2); 3760 Qualifiers T1Quals, T2Quals; 3761 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3762 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3763 3764 // If the types are the same, we won't learn anything by unwrapped 3765 // them. 3766 if (UnqualT1 == UnqualT2) 3767 return ImplicitConversionSequence::Indistinguishable; 3768 3769 // If the type is an array type, promote the element qualifiers to the type 3770 // for comparison. 3771 if (isa<ArrayType>(T1) && T1Quals) 3772 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3773 if (isa<ArrayType>(T2) && T2Quals) 3774 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3775 3776 ImplicitConversionSequence::CompareKind Result 3777 = ImplicitConversionSequence::Indistinguishable; 3778 3779 // Objective-C++ ARC: 3780 // Prefer qualification conversions not involving a change in lifetime 3781 // to qualification conversions that do not change lifetime. 3782 if (SCS1.QualificationIncludesObjCLifetime != 3783 SCS2.QualificationIncludesObjCLifetime) { 3784 Result = SCS1.QualificationIncludesObjCLifetime 3785 ? ImplicitConversionSequence::Worse 3786 : ImplicitConversionSequence::Better; 3787 } 3788 3789 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3790 // Within each iteration of the loop, we check the qualifiers to 3791 // determine if this still looks like a qualification 3792 // conversion. Then, if all is well, we unwrap one more level of 3793 // pointers or pointers-to-members and do it all again 3794 // until there are no more pointers or pointers-to-members left 3795 // to unwrap. This essentially mimics what 3796 // IsQualificationConversion does, but here we're checking for a 3797 // strict subset of qualifiers. 3798 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3799 // The qualifiers are the same, so this doesn't tell us anything 3800 // about how the sequences rank. 3801 ; 3802 else if (T2.isMoreQualifiedThan(T1)) { 3803 // T1 has fewer qualifiers, so it could be the better sequence. 3804 if (Result == ImplicitConversionSequence::Worse) 3805 // Neither has qualifiers that are a subset of the other's 3806 // qualifiers. 3807 return ImplicitConversionSequence::Indistinguishable; 3808 3809 Result = ImplicitConversionSequence::Better; 3810 } else if (T1.isMoreQualifiedThan(T2)) { 3811 // T2 has fewer qualifiers, so it could be the better sequence. 3812 if (Result == ImplicitConversionSequence::Better) 3813 // Neither has qualifiers that are a subset of the other's 3814 // qualifiers. 3815 return ImplicitConversionSequence::Indistinguishable; 3816 3817 Result = ImplicitConversionSequence::Worse; 3818 } else { 3819 // Qualifiers are disjoint. 3820 return ImplicitConversionSequence::Indistinguishable; 3821 } 3822 3823 // If the types after this point are equivalent, we're done. 3824 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3825 break; 3826 } 3827 3828 // Check that the winning standard conversion sequence isn't using 3829 // the deprecated string literal array to pointer conversion. 3830 switch (Result) { 3831 case ImplicitConversionSequence::Better: 3832 if (SCS1.DeprecatedStringLiteralToCharPtr) 3833 Result = ImplicitConversionSequence::Indistinguishable; 3834 break; 3835 3836 case ImplicitConversionSequence::Indistinguishable: 3837 break; 3838 3839 case ImplicitConversionSequence::Worse: 3840 if (SCS2.DeprecatedStringLiteralToCharPtr) 3841 Result = ImplicitConversionSequence::Indistinguishable; 3842 break; 3843 } 3844 3845 return Result; 3846 } 3847 3848 /// CompareDerivedToBaseConversions - Compares two standard conversion 3849 /// sequences to determine whether they can be ranked based on their 3850 /// various kinds of derived-to-base conversions (C++ 3851 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3852 /// conversions between Objective-C interface types. 3853 static ImplicitConversionSequence::CompareKind 3854 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 3855 const StandardConversionSequence& SCS1, 3856 const StandardConversionSequence& SCS2) { 3857 QualType FromType1 = SCS1.getFromType(); 3858 QualType ToType1 = SCS1.getToType(1); 3859 QualType FromType2 = SCS2.getFromType(); 3860 QualType ToType2 = SCS2.getToType(1); 3861 3862 // Adjust the types we're converting from via the array-to-pointer 3863 // conversion, if we need to. 3864 if (SCS1.First == ICK_Array_To_Pointer) 3865 FromType1 = S.Context.getArrayDecayedType(FromType1); 3866 if (SCS2.First == ICK_Array_To_Pointer) 3867 FromType2 = S.Context.getArrayDecayedType(FromType2); 3868 3869 // Canonicalize all of the types. 3870 FromType1 = S.Context.getCanonicalType(FromType1); 3871 ToType1 = S.Context.getCanonicalType(ToType1); 3872 FromType2 = S.Context.getCanonicalType(FromType2); 3873 ToType2 = S.Context.getCanonicalType(ToType2); 3874 3875 // C++ [over.ics.rank]p4b3: 3876 // 3877 // If class B is derived directly or indirectly from class A and 3878 // class C is derived directly or indirectly from B, 3879 // 3880 // Compare based on pointer conversions. 3881 if (SCS1.Second == ICK_Pointer_Conversion && 3882 SCS2.Second == ICK_Pointer_Conversion && 3883 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3884 FromType1->isPointerType() && FromType2->isPointerType() && 3885 ToType1->isPointerType() && ToType2->isPointerType()) { 3886 QualType FromPointee1 3887 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3888 QualType ToPointee1 3889 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3890 QualType FromPointee2 3891 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3892 QualType ToPointee2 3893 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3894 3895 // -- conversion of C* to B* is better than conversion of C* to A*, 3896 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3897 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 3898 return ImplicitConversionSequence::Better; 3899 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 3900 return ImplicitConversionSequence::Worse; 3901 } 3902 3903 // -- conversion of B* to A* is better than conversion of C* to A*, 3904 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3905 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3906 return ImplicitConversionSequence::Better; 3907 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3908 return ImplicitConversionSequence::Worse; 3909 } 3910 } else if (SCS1.Second == ICK_Pointer_Conversion && 3911 SCS2.Second == ICK_Pointer_Conversion) { 3912 const ObjCObjectPointerType *FromPtr1 3913 = FromType1->getAs<ObjCObjectPointerType>(); 3914 const ObjCObjectPointerType *FromPtr2 3915 = FromType2->getAs<ObjCObjectPointerType>(); 3916 const ObjCObjectPointerType *ToPtr1 3917 = ToType1->getAs<ObjCObjectPointerType>(); 3918 const ObjCObjectPointerType *ToPtr2 3919 = ToType2->getAs<ObjCObjectPointerType>(); 3920 3921 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3922 // Apply the same conversion ranking rules for Objective-C pointer types 3923 // that we do for C++ pointers to class types. However, we employ the 3924 // Objective-C pseudo-subtyping relationship used for assignment of 3925 // Objective-C pointer types. 3926 bool FromAssignLeft 3927 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3928 bool FromAssignRight 3929 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3930 bool ToAssignLeft 3931 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3932 bool ToAssignRight 3933 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3934 3935 // A conversion to an a non-id object pointer type or qualified 'id' 3936 // type is better than a conversion to 'id'. 3937 if (ToPtr1->isObjCIdType() && 3938 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3939 return ImplicitConversionSequence::Worse; 3940 if (ToPtr2->isObjCIdType() && 3941 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3942 return ImplicitConversionSequence::Better; 3943 3944 // A conversion to a non-id object pointer type is better than a 3945 // conversion to a qualified 'id' type 3946 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3947 return ImplicitConversionSequence::Worse; 3948 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3949 return ImplicitConversionSequence::Better; 3950 3951 // A conversion to an a non-Class object pointer type or qualified 'Class' 3952 // type is better than a conversion to 'Class'. 3953 if (ToPtr1->isObjCClassType() && 3954 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3955 return ImplicitConversionSequence::Worse; 3956 if (ToPtr2->isObjCClassType() && 3957 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3958 return ImplicitConversionSequence::Better; 3959 3960 // A conversion to a non-Class object pointer type is better than a 3961 // conversion to a qualified 'Class' type. 3962 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3963 return ImplicitConversionSequence::Worse; 3964 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3965 return ImplicitConversionSequence::Better; 3966 3967 // -- "conversion of C* to B* is better than conversion of C* to A*," 3968 if (S.Context.hasSameType(FromType1, FromType2) && 3969 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3970 (ToAssignLeft != ToAssignRight)) 3971 return ToAssignLeft? ImplicitConversionSequence::Worse 3972 : ImplicitConversionSequence::Better; 3973 3974 // -- "conversion of B* to A* is better than conversion of C* to A*," 3975 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3976 (FromAssignLeft != FromAssignRight)) 3977 return FromAssignLeft? ImplicitConversionSequence::Better 3978 : ImplicitConversionSequence::Worse; 3979 } 3980 } 3981 3982 // Ranking of member-pointer types. 3983 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3984 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3985 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3986 const MemberPointerType * FromMemPointer1 = 3987 FromType1->getAs<MemberPointerType>(); 3988 const MemberPointerType * ToMemPointer1 = 3989 ToType1->getAs<MemberPointerType>(); 3990 const MemberPointerType * FromMemPointer2 = 3991 FromType2->getAs<MemberPointerType>(); 3992 const MemberPointerType * ToMemPointer2 = 3993 ToType2->getAs<MemberPointerType>(); 3994 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3995 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3996 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3997 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3998 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3999 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4000 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4001 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4002 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4003 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4004 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4005 return ImplicitConversionSequence::Worse; 4006 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4007 return ImplicitConversionSequence::Better; 4008 } 4009 // conversion of B::* to C::* is better than conversion of A::* to C::* 4010 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4011 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4012 return ImplicitConversionSequence::Better; 4013 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4014 return ImplicitConversionSequence::Worse; 4015 } 4016 } 4017 4018 if (SCS1.Second == ICK_Derived_To_Base) { 4019 // -- conversion of C to B is better than conversion of C to A, 4020 // -- binding of an expression of type C to a reference of type 4021 // B& is better than binding an expression of type C to a 4022 // reference of type A&, 4023 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4024 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4025 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4026 return ImplicitConversionSequence::Better; 4027 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4028 return ImplicitConversionSequence::Worse; 4029 } 4030 4031 // -- conversion of B to A is better than conversion of C to A. 4032 // -- binding of an expression of type B to a reference of type 4033 // A& is better than binding an expression of type C to a 4034 // reference of type A&, 4035 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4036 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4037 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4038 return ImplicitConversionSequence::Better; 4039 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4040 return ImplicitConversionSequence::Worse; 4041 } 4042 } 4043 4044 return ImplicitConversionSequence::Indistinguishable; 4045 } 4046 4047 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 4048 /// C++ class. 4049 static bool isTypeValid(QualType T) { 4050 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4051 return !Record->isInvalidDecl(); 4052 4053 return true; 4054 } 4055 4056 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4057 /// determine whether they are reference-related, 4058 /// reference-compatible, reference-compatible with added 4059 /// qualification, or incompatible, for use in C++ initialization by 4060 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4061 /// type, and the first type (T1) is the pointee type of the reference 4062 /// type being initialized. 4063 Sema::ReferenceCompareResult 4064 Sema::CompareReferenceRelationship(SourceLocation Loc, 4065 QualType OrigT1, QualType OrigT2, 4066 bool &DerivedToBase, 4067 bool &ObjCConversion, 4068 bool &ObjCLifetimeConversion) { 4069 assert(!OrigT1->isReferenceType() && 4070 "T1 must be the pointee type of the reference type"); 4071 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4072 4073 QualType T1 = Context.getCanonicalType(OrigT1); 4074 QualType T2 = Context.getCanonicalType(OrigT2); 4075 Qualifiers T1Quals, T2Quals; 4076 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4077 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4078 4079 // C++ [dcl.init.ref]p4: 4080 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4081 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4082 // T1 is a base class of T2. 4083 DerivedToBase = false; 4084 ObjCConversion = false; 4085 ObjCLifetimeConversion = false; 4086 if (UnqualT1 == UnqualT2) { 4087 // Nothing to do. 4088 } else if (isCompleteType(Loc, OrigT2) && 4089 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4090 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4091 DerivedToBase = true; 4092 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4093 UnqualT2->isObjCObjectOrInterfaceType() && 4094 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4095 ObjCConversion = true; 4096 else 4097 return Ref_Incompatible; 4098 4099 // At this point, we know that T1 and T2 are reference-related (at 4100 // least). 4101 4102 // If the type is an array type, promote the element qualifiers to the type 4103 // for comparison. 4104 if (isa<ArrayType>(T1) && T1Quals) 4105 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4106 if (isa<ArrayType>(T2) && T2Quals) 4107 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4108 4109 // C++ [dcl.init.ref]p4: 4110 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4111 // reference-related to T2 and cv1 is the same cv-qualification 4112 // as, or greater cv-qualification than, cv2. For purposes of 4113 // overload resolution, cases for which cv1 is greater 4114 // cv-qualification than cv2 are identified as 4115 // reference-compatible with added qualification (see 13.3.3.2). 4116 // 4117 // Note that we also require equivalence of Objective-C GC and address-space 4118 // qualifiers when performing these computations, so that e.g., an int in 4119 // address space 1 is not reference-compatible with an int in address 4120 // space 2. 4121 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4122 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4123 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4124 ObjCLifetimeConversion = true; 4125 4126 T1Quals.removeObjCLifetime(); 4127 T2Quals.removeObjCLifetime(); 4128 } 4129 4130 if (T1Quals == T2Quals) 4131 return Ref_Compatible; 4132 else if (T1Quals.compatiblyIncludes(T2Quals)) 4133 return Ref_Compatible_With_Added_Qualification; 4134 else 4135 return Ref_Related; 4136 } 4137 4138 /// \brief Look for a user-defined conversion to an value reference-compatible 4139 /// with DeclType. Return true if something definite is found. 4140 static bool 4141 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4142 QualType DeclType, SourceLocation DeclLoc, 4143 Expr *Init, QualType T2, bool AllowRvalues, 4144 bool AllowExplicit) { 4145 assert(T2->isRecordType() && "Can only find conversions of record types."); 4146 CXXRecordDecl *T2RecordDecl 4147 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4148 4149 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4150 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4151 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4152 NamedDecl *D = *I; 4153 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4154 if (isa<UsingShadowDecl>(D)) 4155 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4156 4157 FunctionTemplateDecl *ConvTemplate 4158 = dyn_cast<FunctionTemplateDecl>(D); 4159 CXXConversionDecl *Conv; 4160 if (ConvTemplate) 4161 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4162 else 4163 Conv = cast<CXXConversionDecl>(D); 4164 4165 // If this is an explicit conversion, and we're not allowed to consider 4166 // explicit conversions, skip it. 4167 if (!AllowExplicit && Conv->isExplicit()) 4168 continue; 4169 4170 if (AllowRvalues) { 4171 bool DerivedToBase = false; 4172 bool ObjCConversion = false; 4173 bool ObjCLifetimeConversion = false; 4174 4175 // If we are initializing an rvalue reference, don't permit conversion 4176 // functions that return lvalues. 4177 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4178 const ReferenceType *RefType 4179 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4180 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4181 continue; 4182 } 4183 4184 if (!ConvTemplate && 4185 S.CompareReferenceRelationship( 4186 DeclLoc, 4187 Conv->getConversionType().getNonReferenceType() 4188 .getUnqualifiedType(), 4189 DeclType.getNonReferenceType().getUnqualifiedType(), 4190 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4191 Sema::Ref_Incompatible) 4192 continue; 4193 } else { 4194 // If the conversion function doesn't return a reference type, 4195 // it can't be considered for this conversion. An rvalue reference 4196 // is only acceptable if its referencee is a function type. 4197 4198 const ReferenceType *RefType = 4199 Conv->getConversionType()->getAs<ReferenceType>(); 4200 if (!RefType || 4201 (!RefType->isLValueReferenceType() && 4202 !RefType->getPointeeType()->isFunctionType())) 4203 continue; 4204 } 4205 4206 if (ConvTemplate) 4207 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4208 Init, DeclType, CandidateSet, 4209 /*AllowObjCConversionOnExplicit=*/false); 4210 else 4211 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4212 DeclType, CandidateSet, 4213 /*AllowObjCConversionOnExplicit=*/false); 4214 } 4215 4216 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4217 4218 OverloadCandidateSet::iterator Best; 4219 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4220 case OR_Success: 4221 // C++ [over.ics.ref]p1: 4222 // 4223 // [...] If the parameter binds directly to the result of 4224 // applying a conversion function to the argument 4225 // expression, the implicit conversion sequence is a 4226 // user-defined conversion sequence (13.3.3.1.2), with the 4227 // second standard conversion sequence either an identity 4228 // conversion or, if the conversion function returns an 4229 // entity of a type that is a derived class of the parameter 4230 // type, a derived-to-base Conversion. 4231 if (!Best->FinalConversion.DirectBinding) 4232 return false; 4233 4234 ICS.setUserDefined(); 4235 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4236 ICS.UserDefined.After = Best->FinalConversion; 4237 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4238 ICS.UserDefined.ConversionFunction = Best->Function; 4239 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4240 ICS.UserDefined.EllipsisConversion = false; 4241 assert(ICS.UserDefined.After.ReferenceBinding && 4242 ICS.UserDefined.After.DirectBinding && 4243 "Expected a direct reference binding!"); 4244 return true; 4245 4246 case OR_Ambiguous: 4247 ICS.setAmbiguous(); 4248 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4249 Cand != CandidateSet.end(); ++Cand) 4250 if (Cand->Viable) 4251 ICS.Ambiguous.addConversion(Cand->Function); 4252 return true; 4253 4254 case OR_No_Viable_Function: 4255 case OR_Deleted: 4256 // There was no suitable conversion, or we found a deleted 4257 // conversion; continue with other checks. 4258 return false; 4259 } 4260 4261 llvm_unreachable("Invalid OverloadResult!"); 4262 } 4263 4264 /// \brief Compute an implicit conversion sequence for reference 4265 /// initialization. 4266 static ImplicitConversionSequence 4267 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4268 SourceLocation DeclLoc, 4269 bool SuppressUserConversions, 4270 bool AllowExplicit) { 4271 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4272 4273 // Most paths end in a failed conversion. 4274 ImplicitConversionSequence ICS; 4275 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4276 4277 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4278 QualType T2 = Init->getType(); 4279 4280 // If the initializer is the address of an overloaded function, try 4281 // to resolve the overloaded function. If all goes well, T2 is the 4282 // type of the resulting function. 4283 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4284 DeclAccessPair Found; 4285 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4286 false, Found)) 4287 T2 = Fn->getType(); 4288 } 4289 4290 // Compute some basic properties of the types and the initializer. 4291 bool isRValRef = DeclType->isRValueReferenceType(); 4292 bool DerivedToBase = false; 4293 bool ObjCConversion = false; 4294 bool ObjCLifetimeConversion = false; 4295 Expr::Classification InitCategory = Init->Classify(S.Context); 4296 Sema::ReferenceCompareResult RefRelationship 4297 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4298 ObjCConversion, ObjCLifetimeConversion); 4299 4300 4301 // C++0x [dcl.init.ref]p5: 4302 // A reference to type "cv1 T1" is initialized by an expression 4303 // of type "cv2 T2" as follows: 4304 4305 // -- If reference is an lvalue reference and the initializer expression 4306 if (!isRValRef) { 4307 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4308 // reference-compatible with "cv2 T2," or 4309 // 4310 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4311 if (InitCategory.isLValue() && 4312 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4313 // C++ [over.ics.ref]p1: 4314 // When a parameter of reference type binds directly (8.5.3) 4315 // to an argument expression, the implicit conversion sequence 4316 // is the identity conversion, unless the argument expression 4317 // has a type that is a derived class of the parameter type, 4318 // in which case the implicit conversion sequence is a 4319 // derived-to-base Conversion (13.3.3.1). 4320 ICS.setStandard(); 4321 ICS.Standard.First = ICK_Identity; 4322 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4323 : ObjCConversion? ICK_Compatible_Conversion 4324 : ICK_Identity; 4325 ICS.Standard.Third = ICK_Identity; 4326 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4327 ICS.Standard.setToType(0, T2); 4328 ICS.Standard.setToType(1, T1); 4329 ICS.Standard.setToType(2, T1); 4330 ICS.Standard.ReferenceBinding = true; 4331 ICS.Standard.DirectBinding = true; 4332 ICS.Standard.IsLvalueReference = !isRValRef; 4333 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4334 ICS.Standard.BindsToRvalue = false; 4335 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4336 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4337 ICS.Standard.CopyConstructor = nullptr; 4338 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4339 4340 // Nothing more to do: the inaccessibility/ambiguity check for 4341 // derived-to-base conversions is suppressed when we're 4342 // computing the implicit conversion sequence (C++ 4343 // [over.best.ics]p2). 4344 return ICS; 4345 } 4346 4347 // -- has a class type (i.e., T2 is a class type), where T1 is 4348 // not reference-related to T2, and can be implicitly 4349 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4350 // is reference-compatible with "cv3 T3" 92) (this 4351 // conversion is selected by enumerating the applicable 4352 // conversion functions (13.3.1.6) and choosing the best 4353 // one through overload resolution (13.3)), 4354 if (!SuppressUserConversions && T2->isRecordType() && 4355 S.isCompleteType(DeclLoc, T2) && 4356 RefRelationship == Sema::Ref_Incompatible) { 4357 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4358 Init, T2, /*AllowRvalues=*/false, 4359 AllowExplicit)) 4360 return ICS; 4361 } 4362 } 4363 4364 // -- Otherwise, the reference shall be an lvalue reference to a 4365 // non-volatile const type (i.e., cv1 shall be const), or the reference 4366 // shall be an rvalue reference. 4367 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4368 return ICS; 4369 4370 // -- If the initializer expression 4371 // 4372 // -- is an xvalue, class prvalue, array prvalue or function 4373 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4374 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4375 (InitCategory.isXValue() || 4376 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4377 (InitCategory.isLValue() && T2->isFunctionType()))) { 4378 ICS.setStandard(); 4379 ICS.Standard.First = ICK_Identity; 4380 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4381 : ObjCConversion? ICK_Compatible_Conversion 4382 : ICK_Identity; 4383 ICS.Standard.Third = ICK_Identity; 4384 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4385 ICS.Standard.setToType(0, T2); 4386 ICS.Standard.setToType(1, T1); 4387 ICS.Standard.setToType(2, T1); 4388 ICS.Standard.ReferenceBinding = true; 4389 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4390 // binding unless we're binding to a class prvalue. 4391 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4392 // allow the use of rvalue references in C++98/03 for the benefit of 4393 // standard library implementors; therefore, we need the xvalue check here. 4394 ICS.Standard.DirectBinding = 4395 S.getLangOpts().CPlusPlus11 || 4396 !(InitCategory.isPRValue() || T2->isRecordType()); 4397 ICS.Standard.IsLvalueReference = !isRValRef; 4398 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4399 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4400 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4401 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4402 ICS.Standard.CopyConstructor = nullptr; 4403 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4404 return ICS; 4405 } 4406 4407 // -- has a class type (i.e., T2 is a class type), where T1 is not 4408 // reference-related to T2, and can be implicitly converted to 4409 // an xvalue, class prvalue, or function lvalue of type 4410 // "cv3 T3", where "cv1 T1" is reference-compatible with 4411 // "cv3 T3", 4412 // 4413 // then the reference is bound to the value of the initializer 4414 // expression in the first case and to the result of the conversion 4415 // in the second case (or, in either case, to an appropriate base 4416 // class subobject). 4417 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4418 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4419 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4420 Init, T2, /*AllowRvalues=*/true, 4421 AllowExplicit)) { 4422 // In the second case, if the reference is an rvalue reference 4423 // and the second standard conversion sequence of the 4424 // user-defined conversion sequence includes an lvalue-to-rvalue 4425 // conversion, the program is ill-formed. 4426 if (ICS.isUserDefined() && isRValRef && 4427 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4428 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4429 4430 return ICS; 4431 } 4432 4433 // A temporary of function type cannot be created; don't even try. 4434 if (T1->isFunctionType()) 4435 return ICS; 4436 4437 // -- Otherwise, a temporary of type "cv1 T1" is created and 4438 // initialized from the initializer expression using the 4439 // rules for a non-reference copy initialization (8.5). The 4440 // reference is then bound to the temporary. If T1 is 4441 // reference-related to T2, cv1 must be the same 4442 // cv-qualification as, or greater cv-qualification than, 4443 // cv2; otherwise, the program is ill-formed. 4444 if (RefRelationship == Sema::Ref_Related) { 4445 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4446 // we would be reference-compatible or reference-compatible with 4447 // added qualification. But that wasn't the case, so the reference 4448 // initialization fails. 4449 // 4450 // Note that we only want to check address spaces and cvr-qualifiers here. 4451 // ObjC GC and lifetime qualifiers aren't important. 4452 Qualifiers T1Quals = T1.getQualifiers(); 4453 Qualifiers T2Quals = T2.getQualifiers(); 4454 T1Quals.removeObjCGCAttr(); 4455 T1Quals.removeObjCLifetime(); 4456 T2Quals.removeObjCGCAttr(); 4457 T2Quals.removeObjCLifetime(); 4458 if (!T1Quals.compatiblyIncludes(T2Quals)) 4459 return ICS; 4460 } 4461 4462 // If at least one of the types is a class type, the types are not 4463 // related, and we aren't allowed any user conversions, the 4464 // reference binding fails. This case is important for breaking 4465 // recursion, since TryImplicitConversion below will attempt to 4466 // create a temporary through the use of a copy constructor. 4467 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4468 (T1->isRecordType() || T2->isRecordType())) 4469 return ICS; 4470 4471 // If T1 is reference-related to T2 and the reference is an rvalue 4472 // reference, the initializer expression shall not be an lvalue. 4473 if (RefRelationship >= Sema::Ref_Related && 4474 isRValRef && Init->Classify(S.Context).isLValue()) 4475 return ICS; 4476 4477 // C++ [over.ics.ref]p2: 4478 // When a parameter of reference type is not bound directly to 4479 // an argument expression, the conversion sequence is the one 4480 // required to convert the argument expression to the 4481 // underlying type of the reference according to 4482 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4483 // to copy-initializing a temporary of the underlying type with 4484 // the argument expression. Any difference in top-level 4485 // cv-qualification is subsumed by the initialization itself 4486 // and does not constitute a conversion. 4487 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4488 /*AllowExplicit=*/false, 4489 /*InOverloadResolution=*/false, 4490 /*CStyle=*/false, 4491 /*AllowObjCWritebackConversion=*/false, 4492 /*AllowObjCConversionOnExplicit=*/false); 4493 4494 // Of course, that's still a reference binding. 4495 if (ICS.isStandard()) { 4496 ICS.Standard.ReferenceBinding = true; 4497 ICS.Standard.IsLvalueReference = !isRValRef; 4498 ICS.Standard.BindsToFunctionLvalue = false; 4499 ICS.Standard.BindsToRvalue = true; 4500 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4501 ICS.Standard.ObjCLifetimeConversionBinding = false; 4502 } else if (ICS.isUserDefined()) { 4503 const ReferenceType *LValRefType = 4504 ICS.UserDefined.ConversionFunction->getReturnType() 4505 ->getAs<LValueReferenceType>(); 4506 4507 // C++ [over.ics.ref]p3: 4508 // Except for an implicit object parameter, for which see 13.3.1, a 4509 // standard conversion sequence cannot be formed if it requires [...] 4510 // binding an rvalue reference to an lvalue other than a function 4511 // lvalue. 4512 // Note that the function case is not possible here. 4513 if (DeclType->isRValueReferenceType() && LValRefType) { 4514 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4515 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4516 // reference to an rvalue! 4517 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4518 return ICS; 4519 } 4520 4521 ICS.UserDefined.Before.setAsIdentityConversion(); 4522 ICS.UserDefined.After.ReferenceBinding = true; 4523 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4524 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4525 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4526 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4527 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4528 } 4529 4530 return ICS; 4531 } 4532 4533 static ImplicitConversionSequence 4534 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4535 bool SuppressUserConversions, 4536 bool InOverloadResolution, 4537 bool AllowObjCWritebackConversion, 4538 bool AllowExplicit = false); 4539 4540 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4541 /// initializer list From. 4542 static ImplicitConversionSequence 4543 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4544 bool SuppressUserConversions, 4545 bool InOverloadResolution, 4546 bool AllowObjCWritebackConversion) { 4547 // C++11 [over.ics.list]p1: 4548 // When an argument is an initializer list, it is not an expression and 4549 // special rules apply for converting it to a parameter type. 4550 4551 ImplicitConversionSequence Result; 4552 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4553 4554 // We need a complete type for what follows. Incomplete types can never be 4555 // initialized from init lists. 4556 if (!S.isCompleteType(From->getLocStart(), ToType)) 4557 return Result; 4558 4559 // Per DR1467: 4560 // If the parameter type is a class X and the initializer list has a single 4561 // element of type cv U, where U is X or a class derived from X, the 4562 // implicit conversion sequence is the one required to convert the element 4563 // to the parameter type. 4564 // 4565 // Otherwise, if the parameter type is a character array [... ] 4566 // and the initializer list has a single element that is an 4567 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4568 // implicit conversion sequence is the identity conversion. 4569 if (From->getNumInits() == 1) { 4570 if (ToType->isRecordType()) { 4571 QualType InitType = From->getInit(0)->getType(); 4572 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4573 S.IsDerivedFrom(From->getLocStart(), InitType, ToType)) 4574 return TryCopyInitialization(S, From->getInit(0), ToType, 4575 SuppressUserConversions, 4576 InOverloadResolution, 4577 AllowObjCWritebackConversion); 4578 } 4579 // FIXME: Check the other conditions here: array of character type, 4580 // initializer is a string literal. 4581 if (ToType->isArrayType()) { 4582 InitializedEntity Entity = 4583 InitializedEntity::InitializeParameter(S.Context, ToType, 4584 /*Consumed=*/false); 4585 if (S.CanPerformCopyInitialization(Entity, From)) { 4586 Result.setStandard(); 4587 Result.Standard.setAsIdentityConversion(); 4588 Result.Standard.setFromType(ToType); 4589 Result.Standard.setAllToTypes(ToType); 4590 return Result; 4591 } 4592 } 4593 } 4594 4595 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4596 // C++11 [over.ics.list]p2: 4597 // If the parameter type is std::initializer_list<X> or "array of X" and 4598 // all the elements can be implicitly converted to X, the implicit 4599 // conversion sequence is the worst conversion necessary to convert an 4600 // element of the list to X. 4601 // 4602 // C++14 [over.ics.list]p3: 4603 // Otherwise, if the parameter type is "array of N X", if the initializer 4604 // list has exactly N elements or if it has fewer than N elements and X is 4605 // default-constructible, and if all the elements of the initializer list 4606 // can be implicitly converted to X, the implicit conversion sequence is 4607 // the worst conversion necessary to convert an element of the list to X. 4608 // 4609 // FIXME: We're missing a lot of these checks. 4610 bool toStdInitializerList = false; 4611 QualType X; 4612 if (ToType->isArrayType()) 4613 X = S.Context.getAsArrayType(ToType)->getElementType(); 4614 else 4615 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4616 if (!X.isNull()) { 4617 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4618 Expr *Init = From->getInit(i); 4619 ImplicitConversionSequence ICS = 4620 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4621 InOverloadResolution, 4622 AllowObjCWritebackConversion); 4623 // If a single element isn't convertible, fail. 4624 if (ICS.isBad()) { 4625 Result = ICS; 4626 break; 4627 } 4628 // Otherwise, look for the worst conversion. 4629 if (Result.isBad() || 4630 CompareImplicitConversionSequences(S, From->getLocStart(), ICS, 4631 Result) == 4632 ImplicitConversionSequence::Worse) 4633 Result = ICS; 4634 } 4635 4636 // For an empty list, we won't have computed any conversion sequence. 4637 // Introduce the identity conversion sequence. 4638 if (From->getNumInits() == 0) { 4639 Result.setStandard(); 4640 Result.Standard.setAsIdentityConversion(); 4641 Result.Standard.setFromType(ToType); 4642 Result.Standard.setAllToTypes(ToType); 4643 } 4644 4645 Result.setStdInitializerListElement(toStdInitializerList); 4646 return Result; 4647 } 4648 4649 // C++14 [over.ics.list]p4: 4650 // C++11 [over.ics.list]p3: 4651 // Otherwise, if the parameter is a non-aggregate class X and overload 4652 // resolution chooses a single best constructor [...] the implicit 4653 // conversion sequence is a user-defined conversion sequence. If multiple 4654 // constructors are viable but none is better than the others, the 4655 // implicit conversion sequence is a user-defined conversion sequence. 4656 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4657 // This function can deal with initializer lists. 4658 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4659 /*AllowExplicit=*/false, 4660 InOverloadResolution, /*CStyle=*/false, 4661 AllowObjCWritebackConversion, 4662 /*AllowObjCConversionOnExplicit=*/false); 4663 } 4664 4665 // C++14 [over.ics.list]p5: 4666 // C++11 [over.ics.list]p4: 4667 // Otherwise, if the parameter has an aggregate type which can be 4668 // initialized from the initializer list [...] the implicit conversion 4669 // sequence is a user-defined conversion sequence. 4670 if (ToType->isAggregateType()) { 4671 // Type is an aggregate, argument is an init list. At this point it comes 4672 // down to checking whether the initialization works. 4673 // FIXME: Find out whether this parameter is consumed or not. 4674 InitializedEntity Entity = 4675 InitializedEntity::InitializeParameter(S.Context, ToType, 4676 /*Consumed=*/false); 4677 if (S.CanPerformCopyInitialization(Entity, From)) { 4678 Result.setUserDefined(); 4679 Result.UserDefined.Before.setAsIdentityConversion(); 4680 // Initializer lists don't have a type. 4681 Result.UserDefined.Before.setFromType(QualType()); 4682 Result.UserDefined.Before.setAllToTypes(QualType()); 4683 4684 Result.UserDefined.After.setAsIdentityConversion(); 4685 Result.UserDefined.After.setFromType(ToType); 4686 Result.UserDefined.After.setAllToTypes(ToType); 4687 Result.UserDefined.ConversionFunction = nullptr; 4688 } 4689 return Result; 4690 } 4691 4692 // C++14 [over.ics.list]p6: 4693 // C++11 [over.ics.list]p5: 4694 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4695 if (ToType->isReferenceType()) { 4696 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4697 // mention initializer lists in any way. So we go by what list- 4698 // initialization would do and try to extrapolate from that. 4699 4700 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4701 4702 // If the initializer list has a single element that is reference-related 4703 // to the parameter type, we initialize the reference from that. 4704 if (From->getNumInits() == 1) { 4705 Expr *Init = From->getInit(0); 4706 4707 QualType T2 = Init->getType(); 4708 4709 // If the initializer is the address of an overloaded function, try 4710 // to resolve the overloaded function. If all goes well, T2 is the 4711 // type of the resulting function. 4712 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4713 DeclAccessPair Found; 4714 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4715 Init, ToType, false, Found)) 4716 T2 = Fn->getType(); 4717 } 4718 4719 // Compute some basic properties of the types and the initializer. 4720 bool dummy1 = false; 4721 bool dummy2 = false; 4722 bool dummy3 = false; 4723 Sema::ReferenceCompareResult RefRelationship 4724 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4725 dummy2, dummy3); 4726 4727 if (RefRelationship >= Sema::Ref_Related) { 4728 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4729 SuppressUserConversions, 4730 /*AllowExplicit=*/false); 4731 } 4732 } 4733 4734 // Otherwise, we bind the reference to a temporary created from the 4735 // initializer list. 4736 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4737 InOverloadResolution, 4738 AllowObjCWritebackConversion); 4739 if (Result.isFailure()) 4740 return Result; 4741 assert(!Result.isEllipsis() && 4742 "Sub-initialization cannot result in ellipsis conversion."); 4743 4744 // Can we even bind to a temporary? 4745 if (ToType->isRValueReferenceType() || 4746 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4747 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4748 Result.UserDefined.After; 4749 SCS.ReferenceBinding = true; 4750 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4751 SCS.BindsToRvalue = true; 4752 SCS.BindsToFunctionLvalue = false; 4753 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4754 SCS.ObjCLifetimeConversionBinding = false; 4755 } else 4756 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4757 From, ToType); 4758 return Result; 4759 } 4760 4761 // C++14 [over.ics.list]p7: 4762 // C++11 [over.ics.list]p6: 4763 // Otherwise, if the parameter type is not a class: 4764 if (!ToType->isRecordType()) { 4765 // - if the initializer list has one element that is not itself an 4766 // initializer list, the implicit conversion sequence is the one 4767 // required to convert the element to the parameter type. 4768 unsigned NumInits = From->getNumInits(); 4769 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4770 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4771 SuppressUserConversions, 4772 InOverloadResolution, 4773 AllowObjCWritebackConversion); 4774 // - if the initializer list has no elements, the implicit conversion 4775 // sequence is the identity conversion. 4776 else if (NumInits == 0) { 4777 Result.setStandard(); 4778 Result.Standard.setAsIdentityConversion(); 4779 Result.Standard.setFromType(ToType); 4780 Result.Standard.setAllToTypes(ToType); 4781 } 4782 return Result; 4783 } 4784 4785 // C++14 [over.ics.list]p8: 4786 // C++11 [over.ics.list]p7: 4787 // In all cases other than those enumerated above, no conversion is possible 4788 return Result; 4789 } 4790 4791 /// TryCopyInitialization - Try to copy-initialize a value of type 4792 /// ToType from the expression From. Return the implicit conversion 4793 /// sequence required to pass this argument, which may be a bad 4794 /// conversion sequence (meaning that the argument cannot be passed to 4795 /// a parameter of this type). If @p SuppressUserConversions, then we 4796 /// do not permit any user-defined conversion sequences. 4797 static ImplicitConversionSequence 4798 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4799 bool SuppressUserConversions, 4800 bool InOverloadResolution, 4801 bool AllowObjCWritebackConversion, 4802 bool AllowExplicit) { 4803 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4804 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4805 InOverloadResolution,AllowObjCWritebackConversion); 4806 4807 if (ToType->isReferenceType()) 4808 return TryReferenceInit(S, From, ToType, 4809 /*FIXME:*/From->getLocStart(), 4810 SuppressUserConversions, 4811 AllowExplicit); 4812 4813 return TryImplicitConversion(S, From, ToType, 4814 SuppressUserConversions, 4815 /*AllowExplicit=*/false, 4816 InOverloadResolution, 4817 /*CStyle=*/false, 4818 AllowObjCWritebackConversion, 4819 /*AllowObjCConversionOnExplicit=*/false); 4820 } 4821 4822 static bool TryCopyInitialization(const CanQualType FromQTy, 4823 const CanQualType ToQTy, 4824 Sema &S, 4825 SourceLocation Loc, 4826 ExprValueKind FromVK) { 4827 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4828 ImplicitConversionSequence ICS = 4829 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4830 4831 return !ICS.isBad(); 4832 } 4833 4834 /// TryObjectArgumentInitialization - Try to initialize the object 4835 /// parameter of the given member function (@c Method) from the 4836 /// expression @p From. 4837 static ImplicitConversionSequence 4838 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 4839 Expr::Classification FromClassification, 4840 CXXMethodDecl *Method, 4841 CXXRecordDecl *ActingContext) { 4842 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4843 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4844 // const volatile object. 4845 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4846 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4847 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4848 4849 // Set up the conversion sequence as a "bad" conversion, to allow us 4850 // to exit early. 4851 ImplicitConversionSequence ICS; 4852 4853 // We need to have an object of class type. 4854 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4855 FromType = PT->getPointeeType(); 4856 4857 // When we had a pointer, it's implicitly dereferenced, so we 4858 // better have an lvalue. 4859 assert(FromClassification.isLValue()); 4860 } 4861 4862 assert(FromType->isRecordType()); 4863 4864 // C++0x [over.match.funcs]p4: 4865 // For non-static member functions, the type of the implicit object 4866 // parameter is 4867 // 4868 // - "lvalue reference to cv X" for functions declared without a 4869 // ref-qualifier or with the & ref-qualifier 4870 // - "rvalue reference to cv X" for functions declared with the && 4871 // ref-qualifier 4872 // 4873 // where X is the class of which the function is a member and cv is the 4874 // cv-qualification on the member function declaration. 4875 // 4876 // However, when finding an implicit conversion sequence for the argument, we 4877 // are not allowed to create temporaries or perform user-defined conversions 4878 // (C++ [over.match.funcs]p5). We perform a simplified version of 4879 // reference binding here, that allows class rvalues to bind to 4880 // non-constant references. 4881 4882 // First check the qualifiers. 4883 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4884 if (ImplicitParamType.getCVRQualifiers() 4885 != FromTypeCanon.getLocalCVRQualifiers() && 4886 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4887 ICS.setBad(BadConversionSequence::bad_qualifiers, 4888 FromType, ImplicitParamType); 4889 return ICS; 4890 } 4891 4892 // Check that we have either the same type or a derived type. It 4893 // affects the conversion rank. 4894 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4895 ImplicitConversionKind SecondKind; 4896 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4897 SecondKind = ICK_Identity; 4898 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 4899 SecondKind = ICK_Derived_To_Base; 4900 else { 4901 ICS.setBad(BadConversionSequence::unrelated_class, 4902 FromType, ImplicitParamType); 4903 return ICS; 4904 } 4905 4906 // Check the ref-qualifier. 4907 switch (Method->getRefQualifier()) { 4908 case RQ_None: 4909 // Do nothing; we don't care about lvalueness or rvalueness. 4910 break; 4911 4912 case RQ_LValue: 4913 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4914 // non-const lvalue reference cannot bind to an rvalue 4915 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4916 ImplicitParamType); 4917 return ICS; 4918 } 4919 break; 4920 4921 case RQ_RValue: 4922 if (!FromClassification.isRValue()) { 4923 // rvalue reference cannot bind to an lvalue 4924 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4925 ImplicitParamType); 4926 return ICS; 4927 } 4928 break; 4929 } 4930 4931 // Success. Mark this as a reference binding. 4932 ICS.setStandard(); 4933 ICS.Standard.setAsIdentityConversion(); 4934 ICS.Standard.Second = SecondKind; 4935 ICS.Standard.setFromType(FromType); 4936 ICS.Standard.setAllToTypes(ImplicitParamType); 4937 ICS.Standard.ReferenceBinding = true; 4938 ICS.Standard.DirectBinding = true; 4939 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4940 ICS.Standard.BindsToFunctionLvalue = false; 4941 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4942 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4943 = (Method->getRefQualifier() == RQ_None); 4944 return ICS; 4945 } 4946 4947 /// PerformObjectArgumentInitialization - Perform initialization of 4948 /// the implicit object parameter for the given Method with the given 4949 /// expression. 4950 ExprResult 4951 Sema::PerformObjectArgumentInitialization(Expr *From, 4952 NestedNameSpecifier *Qualifier, 4953 NamedDecl *FoundDecl, 4954 CXXMethodDecl *Method) { 4955 QualType FromRecordType, DestType; 4956 QualType ImplicitParamRecordType = 4957 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4958 4959 Expr::Classification FromClassification; 4960 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4961 FromRecordType = PT->getPointeeType(); 4962 DestType = Method->getThisType(Context); 4963 FromClassification = Expr::Classification::makeSimpleLValue(); 4964 } else { 4965 FromRecordType = From->getType(); 4966 DestType = ImplicitParamRecordType; 4967 FromClassification = From->Classify(Context); 4968 } 4969 4970 // Note that we always use the true parent context when performing 4971 // the actual argument initialization. 4972 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 4973 *this, From->getLocStart(), From->getType(), FromClassification, Method, 4974 Method->getParent()); 4975 if (ICS.isBad()) { 4976 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4977 Qualifiers FromQs = FromRecordType.getQualifiers(); 4978 Qualifiers ToQs = DestType.getQualifiers(); 4979 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4980 if (CVR) { 4981 Diag(From->getLocStart(), 4982 diag::err_member_function_call_bad_cvr) 4983 << Method->getDeclName() << FromRecordType << (CVR - 1) 4984 << From->getSourceRange(); 4985 Diag(Method->getLocation(), diag::note_previous_decl) 4986 << Method->getDeclName(); 4987 return ExprError(); 4988 } 4989 } 4990 4991 return Diag(From->getLocStart(), 4992 diag::err_implicit_object_parameter_init) 4993 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4994 } 4995 4996 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4997 ExprResult FromRes = 4998 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4999 if (FromRes.isInvalid()) 5000 return ExprError(); 5001 From = FromRes.get(); 5002 } 5003 5004 if (!Context.hasSameType(From->getType(), DestType)) 5005 From = ImpCastExprToType(From, DestType, CK_NoOp, 5006 From->getValueKind()).get(); 5007 return From; 5008 } 5009 5010 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5011 /// expression From to bool (C++0x [conv]p3). 5012 static ImplicitConversionSequence 5013 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5014 return TryImplicitConversion(S, From, S.Context.BoolTy, 5015 /*SuppressUserConversions=*/false, 5016 /*AllowExplicit=*/true, 5017 /*InOverloadResolution=*/false, 5018 /*CStyle=*/false, 5019 /*AllowObjCWritebackConversion=*/false, 5020 /*AllowObjCConversionOnExplicit=*/false); 5021 } 5022 5023 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5024 /// of the expression From to bool (C++0x [conv]p3). 5025 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5026 if (checkPlaceholderForOverload(*this, From)) 5027 return ExprError(); 5028 5029 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5030 if (!ICS.isBad()) 5031 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5032 5033 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5034 return Diag(From->getLocStart(), 5035 diag::err_typecheck_bool_condition) 5036 << From->getType() << From->getSourceRange(); 5037 return ExprError(); 5038 } 5039 5040 /// Check that the specified conversion is permitted in a converted constant 5041 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5042 /// is acceptable. 5043 static bool CheckConvertedConstantConversions(Sema &S, 5044 StandardConversionSequence &SCS) { 5045 // Since we know that the target type is an integral or unscoped enumeration 5046 // type, most conversion kinds are impossible. All possible First and Third 5047 // conversions are fine. 5048 switch (SCS.Second) { 5049 case ICK_Identity: 5050 case ICK_NoReturn_Adjustment: 5051 case ICK_Integral_Promotion: 5052 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5053 return true; 5054 5055 case ICK_Boolean_Conversion: 5056 // Conversion from an integral or unscoped enumeration type to bool is 5057 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5058 // conversion, so we allow it in a converted constant expression. 5059 // 5060 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5061 // a lot of popular code. We should at least add a warning for this 5062 // (non-conforming) extension. 5063 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5064 SCS.getToType(2)->isBooleanType(); 5065 5066 case ICK_Pointer_Conversion: 5067 case ICK_Pointer_Member: 5068 // C++1z: null pointer conversions and null member pointer conversions are 5069 // only permitted if the source type is std::nullptr_t. 5070 return SCS.getFromType()->isNullPtrType(); 5071 5072 case ICK_Floating_Promotion: 5073 case ICK_Complex_Promotion: 5074 case ICK_Floating_Conversion: 5075 case ICK_Complex_Conversion: 5076 case ICK_Floating_Integral: 5077 case ICK_Compatible_Conversion: 5078 case ICK_Derived_To_Base: 5079 case ICK_Vector_Conversion: 5080 case ICK_Vector_Splat: 5081 case ICK_Complex_Real: 5082 case ICK_Block_Pointer_Conversion: 5083 case ICK_TransparentUnionConversion: 5084 case ICK_Writeback_Conversion: 5085 case ICK_Zero_Event_Conversion: 5086 case ICK_C_Only_Conversion: 5087 return false; 5088 5089 case ICK_Lvalue_To_Rvalue: 5090 case ICK_Array_To_Pointer: 5091 case ICK_Function_To_Pointer: 5092 llvm_unreachable("found a first conversion kind in Second"); 5093 5094 case ICK_Qualification: 5095 llvm_unreachable("found a third conversion kind in Second"); 5096 5097 case ICK_Num_Conversion_Kinds: 5098 break; 5099 } 5100 5101 llvm_unreachable("unknown conversion kind"); 5102 } 5103 5104 /// CheckConvertedConstantExpression - Check that the expression From is a 5105 /// converted constant expression of type T, perform the conversion and produce 5106 /// the converted expression, per C++11 [expr.const]p3. 5107 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5108 QualType T, APValue &Value, 5109 Sema::CCEKind CCE, 5110 bool RequireInt) { 5111 assert(S.getLangOpts().CPlusPlus11 && 5112 "converted constant expression outside C++11"); 5113 5114 if (checkPlaceholderForOverload(S, From)) 5115 return ExprError(); 5116 5117 // C++1z [expr.const]p3: 5118 // A converted constant expression of type T is an expression, 5119 // implicitly converted to type T, where the converted 5120 // expression is a constant expression and the implicit conversion 5121 // sequence contains only [... list of conversions ...]. 5122 ImplicitConversionSequence ICS = 5123 TryCopyInitialization(S, From, T, 5124 /*SuppressUserConversions=*/false, 5125 /*InOverloadResolution=*/false, 5126 /*AllowObjcWritebackConversion=*/false, 5127 /*AllowExplicit=*/false); 5128 StandardConversionSequence *SCS = nullptr; 5129 switch (ICS.getKind()) { 5130 case ImplicitConversionSequence::StandardConversion: 5131 SCS = &ICS.Standard; 5132 break; 5133 case ImplicitConversionSequence::UserDefinedConversion: 5134 // We are converting to a non-class type, so the Before sequence 5135 // must be trivial. 5136 SCS = &ICS.UserDefined.After; 5137 break; 5138 case ImplicitConversionSequence::AmbiguousConversion: 5139 case ImplicitConversionSequence::BadConversion: 5140 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5141 return S.Diag(From->getLocStart(), 5142 diag::err_typecheck_converted_constant_expression) 5143 << From->getType() << From->getSourceRange() << T; 5144 return ExprError(); 5145 5146 case ImplicitConversionSequence::EllipsisConversion: 5147 llvm_unreachable("ellipsis conversion in converted constant expression"); 5148 } 5149 5150 // Check that we would only use permitted conversions. 5151 if (!CheckConvertedConstantConversions(S, *SCS)) { 5152 return S.Diag(From->getLocStart(), 5153 diag::err_typecheck_converted_constant_expression_disallowed) 5154 << From->getType() << From->getSourceRange() << T; 5155 } 5156 // [...] and where the reference binding (if any) binds directly. 5157 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5158 return S.Diag(From->getLocStart(), 5159 diag::err_typecheck_converted_constant_expression_indirect) 5160 << From->getType() << From->getSourceRange() << T; 5161 } 5162 5163 ExprResult Result = 5164 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5165 if (Result.isInvalid()) 5166 return Result; 5167 5168 // Check for a narrowing implicit conversion. 5169 APValue PreNarrowingValue; 5170 QualType PreNarrowingType; 5171 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5172 PreNarrowingType)) { 5173 case NK_Variable_Narrowing: 5174 // Implicit conversion to a narrower type, and the value is not a constant 5175 // expression. We'll diagnose this in a moment. 5176 case NK_Not_Narrowing: 5177 break; 5178 5179 case NK_Constant_Narrowing: 5180 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5181 << CCE << /*Constant*/1 5182 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5183 break; 5184 5185 case NK_Type_Narrowing: 5186 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5187 << CCE << /*Constant*/0 << From->getType() << T; 5188 break; 5189 } 5190 5191 // Check the expression is a constant expression. 5192 SmallVector<PartialDiagnosticAt, 8> Notes; 5193 Expr::EvalResult Eval; 5194 Eval.Diag = &Notes; 5195 5196 if ((T->isReferenceType() 5197 ? !Result.get()->EvaluateAsLValue(Eval, S.Context) 5198 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) || 5199 (RequireInt && !Eval.Val.isInt())) { 5200 // The expression can't be folded, so we can't keep it at this position in 5201 // the AST. 5202 Result = ExprError(); 5203 } else { 5204 Value = Eval.Val; 5205 5206 if (Notes.empty()) { 5207 // It's a constant expression. 5208 return Result; 5209 } 5210 } 5211 5212 // It's not a constant expression. Produce an appropriate diagnostic. 5213 if (Notes.size() == 1 && 5214 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5215 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5216 else { 5217 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5218 << CCE << From->getSourceRange(); 5219 for (unsigned I = 0; I < Notes.size(); ++I) 5220 S.Diag(Notes[I].first, Notes[I].second); 5221 } 5222 return ExprError(); 5223 } 5224 5225 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5226 APValue &Value, CCEKind CCE) { 5227 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5228 } 5229 5230 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5231 llvm::APSInt &Value, 5232 CCEKind CCE) { 5233 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5234 5235 APValue V; 5236 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5237 if (!R.isInvalid()) 5238 Value = V.getInt(); 5239 return R; 5240 } 5241 5242 5243 /// dropPointerConversions - If the given standard conversion sequence 5244 /// involves any pointer conversions, remove them. This may change 5245 /// the result type of the conversion sequence. 5246 static void dropPointerConversion(StandardConversionSequence &SCS) { 5247 if (SCS.Second == ICK_Pointer_Conversion) { 5248 SCS.Second = ICK_Identity; 5249 SCS.Third = ICK_Identity; 5250 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5251 } 5252 } 5253 5254 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5255 /// convert the expression From to an Objective-C pointer type. 5256 static ImplicitConversionSequence 5257 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5258 // Do an implicit conversion to 'id'. 5259 QualType Ty = S.Context.getObjCIdType(); 5260 ImplicitConversionSequence ICS 5261 = TryImplicitConversion(S, From, Ty, 5262 // FIXME: Are these flags correct? 5263 /*SuppressUserConversions=*/false, 5264 /*AllowExplicit=*/true, 5265 /*InOverloadResolution=*/false, 5266 /*CStyle=*/false, 5267 /*AllowObjCWritebackConversion=*/false, 5268 /*AllowObjCConversionOnExplicit=*/true); 5269 5270 // Strip off any final conversions to 'id'. 5271 switch (ICS.getKind()) { 5272 case ImplicitConversionSequence::BadConversion: 5273 case ImplicitConversionSequence::AmbiguousConversion: 5274 case ImplicitConversionSequence::EllipsisConversion: 5275 break; 5276 5277 case ImplicitConversionSequence::UserDefinedConversion: 5278 dropPointerConversion(ICS.UserDefined.After); 5279 break; 5280 5281 case ImplicitConversionSequence::StandardConversion: 5282 dropPointerConversion(ICS.Standard); 5283 break; 5284 } 5285 5286 return ICS; 5287 } 5288 5289 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5290 /// conversion of the expression From to an Objective-C pointer type. 5291 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5292 if (checkPlaceholderForOverload(*this, From)) 5293 return ExprError(); 5294 5295 QualType Ty = Context.getObjCIdType(); 5296 ImplicitConversionSequence ICS = 5297 TryContextuallyConvertToObjCPointer(*this, From); 5298 if (!ICS.isBad()) 5299 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5300 return ExprError(); 5301 } 5302 5303 /// Determine whether the provided type is an integral type, or an enumeration 5304 /// type of a permitted flavor. 5305 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5306 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5307 : T->isIntegralOrUnscopedEnumerationType(); 5308 } 5309 5310 static ExprResult 5311 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5312 Sema::ContextualImplicitConverter &Converter, 5313 QualType T, UnresolvedSetImpl &ViableConversions) { 5314 5315 if (Converter.Suppress) 5316 return ExprError(); 5317 5318 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5319 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5320 CXXConversionDecl *Conv = 5321 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5322 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5323 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5324 } 5325 return From; 5326 } 5327 5328 static bool 5329 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5330 Sema::ContextualImplicitConverter &Converter, 5331 QualType T, bool HadMultipleCandidates, 5332 UnresolvedSetImpl &ExplicitConversions) { 5333 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5334 DeclAccessPair Found = ExplicitConversions[0]; 5335 CXXConversionDecl *Conversion = 5336 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5337 5338 // The user probably meant to invoke the given explicit 5339 // conversion; use it. 5340 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5341 std::string TypeStr; 5342 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5343 5344 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5345 << FixItHint::CreateInsertion(From->getLocStart(), 5346 "static_cast<" + TypeStr + ">(") 5347 << FixItHint::CreateInsertion( 5348 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5349 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5350 5351 // If we aren't in a SFINAE context, build a call to the 5352 // explicit conversion function. 5353 if (SemaRef.isSFINAEContext()) 5354 return true; 5355 5356 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5357 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5358 HadMultipleCandidates); 5359 if (Result.isInvalid()) 5360 return true; 5361 // Record usage of conversion in an implicit cast. 5362 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5363 CK_UserDefinedConversion, Result.get(), 5364 nullptr, Result.get()->getValueKind()); 5365 } 5366 return false; 5367 } 5368 5369 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5370 Sema::ContextualImplicitConverter &Converter, 5371 QualType T, bool HadMultipleCandidates, 5372 DeclAccessPair &Found) { 5373 CXXConversionDecl *Conversion = 5374 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5375 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5376 5377 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5378 if (!Converter.SuppressConversion) { 5379 if (SemaRef.isSFINAEContext()) 5380 return true; 5381 5382 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5383 << From->getSourceRange(); 5384 } 5385 5386 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5387 HadMultipleCandidates); 5388 if (Result.isInvalid()) 5389 return true; 5390 // Record usage of conversion in an implicit cast. 5391 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5392 CK_UserDefinedConversion, Result.get(), 5393 nullptr, Result.get()->getValueKind()); 5394 return false; 5395 } 5396 5397 static ExprResult finishContextualImplicitConversion( 5398 Sema &SemaRef, SourceLocation Loc, Expr *From, 5399 Sema::ContextualImplicitConverter &Converter) { 5400 if (!Converter.match(From->getType()) && !Converter.Suppress) 5401 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5402 << From->getSourceRange(); 5403 5404 return SemaRef.DefaultLvalueConversion(From); 5405 } 5406 5407 static void 5408 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5409 UnresolvedSetImpl &ViableConversions, 5410 OverloadCandidateSet &CandidateSet) { 5411 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5412 DeclAccessPair FoundDecl = ViableConversions[I]; 5413 NamedDecl *D = FoundDecl.getDecl(); 5414 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5415 if (isa<UsingShadowDecl>(D)) 5416 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5417 5418 CXXConversionDecl *Conv; 5419 FunctionTemplateDecl *ConvTemplate; 5420 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5421 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5422 else 5423 Conv = cast<CXXConversionDecl>(D); 5424 5425 if (ConvTemplate) 5426 SemaRef.AddTemplateConversionCandidate( 5427 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5428 /*AllowObjCConversionOnExplicit=*/false); 5429 else 5430 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5431 ToType, CandidateSet, 5432 /*AllowObjCConversionOnExplicit=*/false); 5433 } 5434 } 5435 5436 /// \brief Attempt to convert the given expression to a type which is accepted 5437 /// by the given converter. 5438 /// 5439 /// This routine will attempt to convert an expression of class type to a 5440 /// type accepted by the specified converter. In C++11 and before, the class 5441 /// must have a single non-explicit conversion function converting to a matching 5442 /// type. In C++1y, there can be multiple such conversion functions, but only 5443 /// one target type. 5444 /// 5445 /// \param Loc The source location of the construct that requires the 5446 /// conversion. 5447 /// 5448 /// \param From The expression we're converting from. 5449 /// 5450 /// \param Converter Used to control and diagnose the conversion process. 5451 /// 5452 /// \returns The expression, converted to an integral or enumeration type if 5453 /// successful. 5454 ExprResult Sema::PerformContextualImplicitConversion( 5455 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5456 // We can't perform any more checking for type-dependent expressions. 5457 if (From->isTypeDependent()) 5458 return From; 5459 5460 // Process placeholders immediately. 5461 if (From->hasPlaceholderType()) { 5462 ExprResult result = CheckPlaceholderExpr(From); 5463 if (result.isInvalid()) 5464 return result; 5465 From = result.get(); 5466 } 5467 5468 // If the expression already has a matching type, we're golden. 5469 QualType T = From->getType(); 5470 if (Converter.match(T)) 5471 return DefaultLvalueConversion(From); 5472 5473 // FIXME: Check for missing '()' if T is a function type? 5474 5475 // We can only perform contextual implicit conversions on objects of class 5476 // type. 5477 const RecordType *RecordTy = T->getAs<RecordType>(); 5478 if (!RecordTy || !getLangOpts().CPlusPlus) { 5479 if (!Converter.Suppress) 5480 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5481 return From; 5482 } 5483 5484 // We must have a complete class type. 5485 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5486 ContextualImplicitConverter &Converter; 5487 Expr *From; 5488 5489 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5490 : Converter(Converter), From(From) {} 5491 5492 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5493 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5494 } 5495 } IncompleteDiagnoser(Converter, From); 5496 5497 if (Converter.Suppress ? !isCompleteType(Loc, T) 5498 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5499 return From; 5500 5501 // Look for a conversion to an integral or enumeration type. 5502 UnresolvedSet<4> 5503 ViableConversions; // These are *potentially* viable in C++1y. 5504 UnresolvedSet<4> ExplicitConversions; 5505 const auto &Conversions = 5506 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5507 5508 bool HadMultipleCandidates = 5509 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5510 5511 // To check that there is only one target type, in C++1y: 5512 QualType ToType; 5513 bool HasUniqueTargetType = true; 5514 5515 // Collect explicit or viable (potentially in C++1y) conversions. 5516 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5517 NamedDecl *D = (*I)->getUnderlyingDecl(); 5518 CXXConversionDecl *Conversion; 5519 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5520 if (ConvTemplate) { 5521 if (getLangOpts().CPlusPlus14) 5522 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5523 else 5524 continue; // C++11 does not consider conversion operator templates(?). 5525 } else 5526 Conversion = cast<CXXConversionDecl>(D); 5527 5528 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5529 "Conversion operator templates are considered potentially " 5530 "viable in C++1y"); 5531 5532 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5533 if (Converter.match(CurToType) || ConvTemplate) { 5534 5535 if (Conversion->isExplicit()) { 5536 // FIXME: For C++1y, do we need this restriction? 5537 // cf. diagnoseNoViableConversion() 5538 if (!ConvTemplate) 5539 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5540 } else { 5541 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5542 if (ToType.isNull()) 5543 ToType = CurToType.getUnqualifiedType(); 5544 else if (HasUniqueTargetType && 5545 (CurToType.getUnqualifiedType() != ToType)) 5546 HasUniqueTargetType = false; 5547 } 5548 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5549 } 5550 } 5551 } 5552 5553 if (getLangOpts().CPlusPlus14) { 5554 // C++1y [conv]p6: 5555 // ... An expression e of class type E appearing in such a context 5556 // is said to be contextually implicitly converted to a specified 5557 // type T and is well-formed if and only if e can be implicitly 5558 // converted to a type T that is determined as follows: E is searched 5559 // for conversion functions whose return type is cv T or reference to 5560 // cv T such that T is allowed by the context. There shall be 5561 // exactly one such T. 5562 5563 // If no unique T is found: 5564 if (ToType.isNull()) { 5565 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5566 HadMultipleCandidates, 5567 ExplicitConversions)) 5568 return ExprError(); 5569 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5570 } 5571 5572 // If more than one unique Ts are found: 5573 if (!HasUniqueTargetType) 5574 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5575 ViableConversions); 5576 5577 // If one unique T is found: 5578 // First, build a candidate set from the previously recorded 5579 // potentially viable conversions. 5580 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5581 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5582 CandidateSet); 5583 5584 // Then, perform overload resolution over the candidate set. 5585 OverloadCandidateSet::iterator Best; 5586 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5587 case OR_Success: { 5588 // Apply this conversion. 5589 DeclAccessPair Found = 5590 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5591 if (recordConversion(*this, Loc, From, Converter, T, 5592 HadMultipleCandidates, Found)) 5593 return ExprError(); 5594 break; 5595 } 5596 case OR_Ambiguous: 5597 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5598 ViableConversions); 5599 case OR_No_Viable_Function: 5600 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5601 HadMultipleCandidates, 5602 ExplicitConversions)) 5603 return ExprError(); 5604 // fall through 'OR_Deleted' case. 5605 case OR_Deleted: 5606 // We'll complain below about a non-integral condition type. 5607 break; 5608 } 5609 } else { 5610 switch (ViableConversions.size()) { 5611 case 0: { 5612 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5613 HadMultipleCandidates, 5614 ExplicitConversions)) 5615 return ExprError(); 5616 5617 // We'll complain below about a non-integral condition type. 5618 break; 5619 } 5620 case 1: { 5621 // Apply this conversion. 5622 DeclAccessPair Found = ViableConversions[0]; 5623 if (recordConversion(*this, Loc, From, Converter, T, 5624 HadMultipleCandidates, Found)) 5625 return ExprError(); 5626 break; 5627 } 5628 default: 5629 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5630 ViableConversions); 5631 } 5632 } 5633 5634 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5635 } 5636 5637 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5638 /// an acceptable non-member overloaded operator for a call whose 5639 /// arguments have types T1 (and, if non-empty, T2). This routine 5640 /// implements the check in C++ [over.match.oper]p3b2 concerning 5641 /// enumeration types. 5642 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5643 FunctionDecl *Fn, 5644 ArrayRef<Expr *> Args) { 5645 QualType T1 = Args[0]->getType(); 5646 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5647 5648 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5649 return true; 5650 5651 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5652 return true; 5653 5654 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5655 if (Proto->getNumParams() < 1) 5656 return false; 5657 5658 if (T1->isEnumeralType()) { 5659 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5660 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5661 return true; 5662 } 5663 5664 if (Proto->getNumParams() < 2) 5665 return false; 5666 5667 if (!T2.isNull() && T2->isEnumeralType()) { 5668 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5669 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5670 return true; 5671 } 5672 5673 return false; 5674 } 5675 5676 /// AddOverloadCandidate - Adds the given function to the set of 5677 /// candidate functions, using the given function call arguments. If 5678 /// @p SuppressUserConversions, then don't allow user-defined 5679 /// conversions via constructors or conversion operators. 5680 /// 5681 /// \param PartialOverloading true if we are performing "partial" overloading 5682 /// based on an incomplete set of function arguments. This feature is used by 5683 /// code completion. 5684 void 5685 Sema::AddOverloadCandidate(FunctionDecl *Function, 5686 DeclAccessPair FoundDecl, 5687 ArrayRef<Expr *> Args, 5688 OverloadCandidateSet &CandidateSet, 5689 bool SuppressUserConversions, 5690 bool PartialOverloading, 5691 bool AllowExplicit) { 5692 const FunctionProtoType *Proto 5693 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5694 assert(Proto && "Functions without a prototype cannot be overloaded"); 5695 assert(!Function->getDescribedFunctionTemplate() && 5696 "Use AddTemplateOverloadCandidate for function templates"); 5697 5698 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5699 if (!isa<CXXConstructorDecl>(Method)) { 5700 // If we get here, it's because we're calling a member function 5701 // that is named without a member access expression (e.g., 5702 // "this->f") that was either written explicitly or created 5703 // implicitly. This can happen with a qualified call to a member 5704 // function, e.g., X::f(). We use an empty type for the implied 5705 // object argument (C++ [over.call.func]p3), and the acting context 5706 // is irrelevant. 5707 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5708 QualType(), Expr::Classification::makeSimpleLValue(), 5709 Args, CandidateSet, SuppressUserConversions, 5710 PartialOverloading); 5711 return; 5712 } 5713 // We treat a constructor like a non-member function, since its object 5714 // argument doesn't participate in overload resolution. 5715 } 5716 5717 if (!CandidateSet.isNewCandidate(Function)) 5718 return; 5719 5720 // C++ [over.match.oper]p3: 5721 // if no operand has a class type, only those non-member functions in the 5722 // lookup set that have a first parameter of type T1 or "reference to 5723 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5724 // is a right operand) a second parameter of type T2 or "reference to 5725 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5726 // candidate functions. 5727 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5728 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5729 return; 5730 5731 // C++11 [class.copy]p11: [DR1402] 5732 // A defaulted move constructor that is defined as deleted is ignored by 5733 // overload resolution. 5734 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5735 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5736 Constructor->isMoveConstructor()) 5737 return; 5738 5739 // Overload resolution is always an unevaluated context. 5740 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5741 5742 // Add this candidate 5743 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5744 Candidate.FoundDecl = FoundDecl; 5745 Candidate.Function = Function; 5746 Candidate.Viable = true; 5747 Candidate.IsSurrogate = false; 5748 Candidate.IgnoreObjectArgument = false; 5749 Candidate.ExplicitCallArguments = Args.size(); 5750 5751 if (Constructor) { 5752 // C++ [class.copy]p3: 5753 // A member function template is never instantiated to perform the copy 5754 // of a class object to an object of its class type. 5755 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5756 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 5757 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5758 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(), 5759 ClassType))) { 5760 Candidate.Viable = false; 5761 Candidate.FailureKind = ovl_fail_illegal_constructor; 5762 return; 5763 } 5764 } 5765 5766 unsigned NumParams = Proto->getNumParams(); 5767 5768 // (C++ 13.3.2p2): A candidate function having fewer than m 5769 // parameters is viable only if it has an ellipsis in its parameter 5770 // list (8.3.5). 5771 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 5772 !Proto->isVariadic()) { 5773 Candidate.Viable = false; 5774 Candidate.FailureKind = ovl_fail_too_many_arguments; 5775 return; 5776 } 5777 5778 // (C++ 13.3.2p2): A candidate function having more than m parameters 5779 // is viable only if the (m+1)st parameter has a default argument 5780 // (8.3.6). For the purposes of overload resolution, the 5781 // parameter list is truncated on the right, so that there are 5782 // exactly m parameters. 5783 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5784 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5785 // Not enough arguments. 5786 Candidate.Viable = false; 5787 Candidate.FailureKind = ovl_fail_too_few_arguments; 5788 return; 5789 } 5790 5791 // (CUDA B.1): Check for invalid calls between targets. 5792 if (getLangOpts().CUDA) 5793 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5794 // Skip the check for callers that are implicit members, because in this 5795 // case we may not yet know what the member's target is; the target is 5796 // inferred for the member automatically, based on the bases and fields of 5797 // the class. 5798 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) { 5799 Candidate.Viable = false; 5800 Candidate.FailureKind = ovl_fail_bad_target; 5801 return; 5802 } 5803 5804 // Determine the implicit conversion sequences for each of the 5805 // arguments. 5806 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5807 if (ArgIdx < NumParams) { 5808 // (C++ 13.3.2p3): for F to be a viable function, there shall 5809 // exist for each argument an implicit conversion sequence 5810 // (13.3.3.1) that converts that argument to the corresponding 5811 // parameter of F. 5812 QualType ParamType = Proto->getParamType(ArgIdx); 5813 Candidate.Conversions[ArgIdx] 5814 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5815 SuppressUserConversions, 5816 /*InOverloadResolution=*/true, 5817 /*AllowObjCWritebackConversion=*/ 5818 getLangOpts().ObjCAutoRefCount, 5819 AllowExplicit); 5820 if (Candidate.Conversions[ArgIdx].isBad()) { 5821 Candidate.Viable = false; 5822 Candidate.FailureKind = ovl_fail_bad_conversion; 5823 return; 5824 } 5825 } else { 5826 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5827 // argument for which there is no corresponding parameter is 5828 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5829 Candidate.Conversions[ArgIdx].setEllipsis(); 5830 } 5831 } 5832 5833 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5834 Candidate.Viable = false; 5835 Candidate.FailureKind = ovl_fail_enable_if; 5836 Candidate.DeductionFailure.Data = FailedAttr; 5837 return; 5838 } 5839 } 5840 5841 ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, 5842 bool IsInstance) { 5843 SmallVector<ObjCMethodDecl*, 4> Methods; 5844 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance)) 5845 return nullptr; 5846 5847 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5848 bool Match = true; 5849 ObjCMethodDecl *Method = Methods[b]; 5850 unsigned NumNamedArgs = Sel.getNumArgs(); 5851 // Method might have more arguments than selector indicates. This is due 5852 // to addition of c-style arguments in method. 5853 if (Method->param_size() > NumNamedArgs) 5854 NumNamedArgs = Method->param_size(); 5855 if (Args.size() < NumNamedArgs) 5856 continue; 5857 5858 for (unsigned i = 0; i < NumNamedArgs; i++) { 5859 // We can't do any type-checking on a type-dependent argument. 5860 if (Args[i]->isTypeDependent()) { 5861 Match = false; 5862 break; 5863 } 5864 5865 ParmVarDecl *param = Method->parameters()[i]; 5866 Expr *argExpr = Args[i]; 5867 assert(argExpr && "SelectBestMethod(): missing expression"); 5868 5869 // Strip the unbridged-cast placeholder expression off unless it's 5870 // a consumed argument. 5871 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 5872 !param->hasAttr<CFConsumedAttr>()) 5873 argExpr = stripARCUnbridgedCast(argExpr); 5874 5875 // If the parameter is __unknown_anytype, move on to the next method. 5876 if (param->getType() == Context.UnknownAnyTy) { 5877 Match = false; 5878 break; 5879 } 5880 5881 ImplicitConversionSequence ConversionState 5882 = TryCopyInitialization(*this, argExpr, param->getType(), 5883 /*SuppressUserConversions*/false, 5884 /*InOverloadResolution=*/true, 5885 /*AllowObjCWritebackConversion=*/ 5886 getLangOpts().ObjCAutoRefCount, 5887 /*AllowExplicit*/false); 5888 if (ConversionState.isBad()) { 5889 Match = false; 5890 break; 5891 } 5892 } 5893 // Promote additional arguments to variadic methods. 5894 if (Match && Method->isVariadic()) { 5895 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 5896 if (Args[i]->isTypeDependent()) { 5897 Match = false; 5898 break; 5899 } 5900 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 5901 nullptr); 5902 if (Arg.isInvalid()) { 5903 Match = false; 5904 break; 5905 } 5906 } 5907 } else { 5908 // Check for extra arguments to non-variadic methods. 5909 if (Args.size() != NumNamedArgs) 5910 Match = false; 5911 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 5912 // Special case when selectors have no argument. In this case, select 5913 // one with the most general result type of 'id'. 5914 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5915 QualType ReturnT = Methods[b]->getReturnType(); 5916 if (ReturnT->isObjCIdType()) 5917 return Methods[b]; 5918 } 5919 } 5920 } 5921 5922 if (Match) 5923 return Method; 5924 } 5925 return nullptr; 5926 } 5927 5928 // specific_attr_iterator iterates over enable_if attributes in reverse, and 5929 // enable_if is order-sensitive. As a result, we need to reverse things 5930 // sometimes. Size of 4 elements is arbitrary. 5931 static SmallVector<EnableIfAttr *, 4> 5932 getOrderedEnableIfAttrs(const FunctionDecl *Function) { 5933 SmallVector<EnableIfAttr *, 4> Result; 5934 if (!Function->hasAttrs()) 5935 return Result; 5936 5937 const auto &FuncAttrs = Function->getAttrs(); 5938 for (Attr *Attr : FuncAttrs) 5939 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr)) 5940 Result.push_back(EnableIf); 5941 5942 std::reverse(Result.begin(), Result.end()); 5943 return Result; 5944 } 5945 5946 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 5947 bool MissingImplicitThis) { 5948 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function); 5949 if (EnableIfAttrs.empty()) 5950 return nullptr; 5951 5952 SFINAETrap Trap(*this); 5953 SmallVector<Expr *, 16> ConvertedArgs; 5954 bool InitializationFailed = false; 5955 bool ContainsValueDependentExpr = false; 5956 5957 // Convert the arguments. 5958 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 5959 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 5960 !cast<CXXMethodDecl>(Function)->isStatic() && 5961 !isa<CXXConstructorDecl>(Function)) { 5962 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 5963 ExprResult R = 5964 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 5965 Method, Method); 5966 if (R.isInvalid()) { 5967 InitializationFailed = true; 5968 break; 5969 } 5970 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5971 ConvertedArgs.push_back(R.get()); 5972 } else { 5973 ExprResult R = 5974 PerformCopyInitialization(InitializedEntity::InitializeParameter( 5975 Context, 5976 Function->getParamDecl(i)), 5977 SourceLocation(), 5978 Args[i]); 5979 if (R.isInvalid()) { 5980 InitializationFailed = true; 5981 break; 5982 } 5983 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5984 ConvertedArgs.push_back(R.get()); 5985 } 5986 } 5987 5988 if (InitializationFailed || Trap.hasErrorOccurred()) 5989 return EnableIfAttrs[0]; 5990 5991 // Push default arguments if needed. 5992 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 5993 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 5994 ParmVarDecl *P = Function->getParamDecl(i); 5995 ExprResult R = PerformCopyInitialization( 5996 InitializedEntity::InitializeParameter(Context, 5997 Function->getParamDecl(i)), 5998 SourceLocation(), 5999 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg() 6000 : P->getDefaultArg()); 6001 if (R.isInvalid()) { 6002 InitializationFailed = true; 6003 break; 6004 } 6005 ContainsValueDependentExpr |= R.get()->isValueDependent(); 6006 ConvertedArgs.push_back(R.get()); 6007 } 6008 6009 if (InitializationFailed || Trap.hasErrorOccurred()) 6010 return EnableIfAttrs[0]; 6011 } 6012 6013 for (auto *EIA : EnableIfAttrs) { 6014 APValue Result; 6015 if (EIA->getCond()->isValueDependent()) { 6016 // Don't even try now, we'll examine it after instantiation. 6017 continue; 6018 } 6019 6020 if (!EIA->getCond()->EvaluateWithSubstitution( 6021 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) { 6022 if (!ContainsValueDependentExpr) 6023 return EIA; 6024 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) { 6025 return EIA; 6026 } 6027 } 6028 return nullptr; 6029 } 6030 6031 /// \brief Add all of the function declarations in the given function set to 6032 /// the overload candidate set. 6033 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6034 ArrayRef<Expr *> Args, 6035 OverloadCandidateSet& CandidateSet, 6036 TemplateArgumentListInfo *ExplicitTemplateArgs, 6037 bool SuppressUserConversions, 6038 bool PartialOverloading) { 6039 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6040 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6041 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6042 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 6043 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6044 cast<CXXMethodDecl>(FD)->getParent(), 6045 Args[0]->getType(), Args[0]->Classify(Context), 6046 Args.slice(1), CandidateSet, 6047 SuppressUserConversions, PartialOverloading); 6048 else 6049 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 6050 SuppressUserConversions, PartialOverloading); 6051 } else { 6052 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 6053 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 6054 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 6055 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 6056 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6057 ExplicitTemplateArgs, 6058 Args[0]->getType(), 6059 Args[0]->Classify(Context), Args.slice(1), 6060 CandidateSet, SuppressUserConversions, 6061 PartialOverloading); 6062 else 6063 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6064 ExplicitTemplateArgs, Args, 6065 CandidateSet, SuppressUserConversions, 6066 PartialOverloading); 6067 } 6068 } 6069 } 6070 6071 /// AddMethodCandidate - Adds a named decl (which is some kind of 6072 /// method) as a method candidate to the given overload set. 6073 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6074 QualType ObjectType, 6075 Expr::Classification ObjectClassification, 6076 ArrayRef<Expr *> Args, 6077 OverloadCandidateSet& CandidateSet, 6078 bool SuppressUserConversions) { 6079 NamedDecl *Decl = FoundDecl.getDecl(); 6080 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6081 6082 if (isa<UsingShadowDecl>(Decl)) 6083 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6084 6085 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6086 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6087 "Expected a member function template"); 6088 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6089 /*ExplicitArgs*/ nullptr, 6090 ObjectType, ObjectClassification, 6091 Args, CandidateSet, 6092 SuppressUserConversions); 6093 } else { 6094 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6095 ObjectType, ObjectClassification, 6096 Args, 6097 CandidateSet, SuppressUserConversions); 6098 } 6099 } 6100 6101 /// AddMethodCandidate - Adds the given C++ member function to the set 6102 /// of candidate functions, using the given function call arguments 6103 /// and the object argument (@c Object). For example, in a call 6104 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6105 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6106 /// allow user-defined conversions via constructors or conversion 6107 /// operators. 6108 void 6109 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6110 CXXRecordDecl *ActingContext, QualType ObjectType, 6111 Expr::Classification ObjectClassification, 6112 ArrayRef<Expr *> Args, 6113 OverloadCandidateSet &CandidateSet, 6114 bool SuppressUserConversions, 6115 bool PartialOverloading) { 6116 const FunctionProtoType *Proto 6117 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6118 assert(Proto && "Methods without a prototype cannot be overloaded"); 6119 assert(!isa<CXXConstructorDecl>(Method) && 6120 "Use AddOverloadCandidate for constructors"); 6121 6122 if (!CandidateSet.isNewCandidate(Method)) 6123 return; 6124 6125 // C++11 [class.copy]p23: [DR1402] 6126 // A defaulted move assignment operator that is defined as deleted is 6127 // ignored by overload resolution. 6128 if (Method->isDefaulted() && Method->isDeleted() && 6129 Method->isMoveAssignmentOperator()) 6130 return; 6131 6132 // Overload resolution is always an unevaluated context. 6133 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6134 6135 // Add this candidate 6136 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6137 Candidate.FoundDecl = FoundDecl; 6138 Candidate.Function = Method; 6139 Candidate.IsSurrogate = false; 6140 Candidate.IgnoreObjectArgument = false; 6141 Candidate.ExplicitCallArguments = Args.size(); 6142 6143 unsigned NumParams = Proto->getNumParams(); 6144 6145 // (C++ 13.3.2p2): A candidate function having fewer than m 6146 // parameters is viable only if it has an ellipsis in its parameter 6147 // list (8.3.5). 6148 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6149 !Proto->isVariadic()) { 6150 Candidate.Viable = false; 6151 Candidate.FailureKind = ovl_fail_too_many_arguments; 6152 return; 6153 } 6154 6155 // (C++ 13.3.2p2): A candidate function having more than m parameters 6156 // is viable only if the (m+1)st parameter has a default argument 6157 // (8.3.6). For the purposes of overload resolution, the 6158 // parameter list is truncated on the right, so that there are 6159 // exactly m parameters. 6160 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6161 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6162 // Not enough arguments. 6163 Candidate.Viable = false; 6164 Candidate.FailureKind = ovl_fail_too_few_arguments; 6165 return; 6166 } 6167 6168 Candidate.Viable = true; 6169 6170 if (Method->isStatic() || ObjectType.isNull()) 6171 // The implicit object argument is ignored. 6172 Candidate.IgnoreObjectArgument = true; 6173 else { 6174 // Determine the implicit conversion sequence for the object 6175 // parameter. 6176 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6177 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6178 Method, ActingContext); 6179 if (Candidate.Conversions[0].isBad()) { 6180 Candidate.Viable = false; 6181 Candidate.FailureKind = ovl_fail_bad_conversion; 6182 return; 6183 } 6184 } 6185 6186 // (CUDA B.1): Check for invalid calls between targets. 6187 if (getLangOpts().CUDA) 6188 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6189 if (CheckCUDATarget(Caller, Method)) { 6190 Candidate.Viable = false; 6191 Candidate.FailureKind = ovl_fail_bad_target; 6192 return; 6193 } 6194 6195 // Determine the implicit conversion sequences for each of the 6196 // arguments. 6197 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6198 if (ArgIdx < NumParams) { 6199 // (C++ 13.3.2p3): for F to be a viable function, there shall 6200 // exist for each argument an implicit conversion sequence 6201 // (13.3.3.1) that converts that argument to the corresponding 6202 // parameter of F. 6203 QualType ParamType = Proto->getParamType(ArgIdx); 6204 Candidate.Conversions[ArgIdx + 1] 6205 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6206 SuppressUserConversions, 6207 /*InOverloadResolution=*/true, 6208 /*AllowObjCWritebackConversion=*/ 6209 getLangOpts().ObjCAutoRefCount); 6210 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6211 Candidate.Viable = false; 6212 Candidate.FailureKind = ovl_fail_bad_conversion; 6213 return; 6214 } 6215 } else { 6216 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6217 // argument for which there is no corresponding parameter is 6218 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6219 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6220 } 6221 } 6222 6223 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6224 Candidate.Viable = false; 6225 Candidate.FailureKind = ovl_fail_enable_if; 6226 Candidate.DeductionFailure.Data = FailedAttr; 6227 return; 6228 } 6229 } 6230 6231 /// \brief Add a C++ member function template as a candidate to the candidate 6232 /// set, using template argument deduction to produce an appropriate member 6233 /// function template specialization. 6234 void 6235 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6236 DeclAccessPair FoundDecl, 6237 CXXRecordDecl *ActingContext, 6238 TemplateArgumentListInfo *ExplicitTemplateArgs, 6239 QualType ObjectType, 6240 Expr::Classification ObjectClassification, 6241 ArrayRef<Expr *> Args, 6242 OverloadCandidateSet& CandidateSet, 6243 bool SuppressUserConversions, 6244 bool PartialOverloading) { 6245 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6246 return; 6247 6248 // C++ [over.match.funcs]p7: 6249 // In each case where a candidate is a function template, candidate 6250 // function template specializations are generated using template argument 6251 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6252 // candidate functions in the usual way.113) A given name can refer to one 6253 // or more function templates and also to a set of overloaded non-template 6254 // functions. In such a case, the candidate functions generated from each 6255 // function template are combined with the set of non-template candidate 6256 // functions. 6257 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6258 FunctionDecl *Specialization = nullptr; 6259 if (TemplateDeductionResult Result 6260 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 6261 Specialization, Info, PartialOverloading)) { 6262 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6263 Candidate.FoundDecl = FoundDecl; 6264 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6265 Candidate.Viable = false; 6266 Candidate.FailureKind = ovl_fail_bad_deduction; 6267 Candidate.IsSurrogate = false; 6268 Candidate.IgnoreObjectArgument = false; 6269 Candidate.ExplicitCallArguments = Args.size(); 6270 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6271 Info); 6272 return; 6273 } 6274 6275 // Add the function template specialization produced by template argument 6276 // deduction as a candidate. 6277 assert(Specialization && "Missing member function template specialization?"); 6278 assert(isa<CXXMethodDecl>(Specialization) && 6279 "Specialization is not a member function?"); 6280 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6281 ActingContext, ObjectType, ObjectClassification, Args, 6282 CandidateSet, SuppressUserConversions, PartialOverloading); 6283 } 6284 6285 /// \brief Add a C++ function template specialization as a candidate 6286 /// in the candidate set, using template argument deduction to produce 6287 /// an appropriate function template specialization. 6288 void 6289 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6290 DeclAccessPair FoundDecl, 6291 TemplateArgumentListInfo *ExplicitTemplateArgs, 6292 ArrayRef<Expr *> Args, 6293 OverloadCandidateSet& CandidateSet, 6294 bool SuppressUserConversions, 6295 bool PartialOverloading) { 6296 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6297 return; 6298 6299 // C++ [over.match.funcs]p7: 6300 // In each case where a candidate is a function template, candidate 6301 // function template specializations are generated using template argument 6302 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6303 // candidate functions in the usual way.113) A given name can refer to one 6304 // or more function templates and also to a set of overloaded non-template 6305 // functions. In such a case, the candidate functions generated from each 6306 // function template are combined with the set of non-template candidate 6307 // functions. 6308 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6309 FunctionDecl *Specialization = nullptr; 6310 if (TemplateDeductionResult Result 6311 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 6312 Specialization, Info, PartialOverloading)) { 6313 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6314 Candidate.FoundDecl = FoundDecl; 6315 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6316 Candidate.Viable = false; 6317 Candidate.FailureKind = ovl_fail_bad_deduction; 6318 Candidate.IsSurrogate = false; 6319 Candidate.IgnoreObjectArgument = false; 6320 Candidate.ExplicitCallArguments = Args.size(); 6321 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6322 Info); 6323 return; 6324 } 6325 6326 // Add the function template specialization produced by template argument 6327 // deduction as a candidate. 6328 assert(Specialization && "Missing function template specialization?"); 6329 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6330 SuppressUserConversions, PartialOverloading); 6331 } 6332 6333 /// Determine whether this is an allowable conversion from the result 6334 /// of an explicit conversion operator to the expected type, per C++ 6335 /// [over.match.conv]p1 and [over.match.ref]p1. 6336 /// 6337 /// \param ConvType The return type of the conversion function. 6338 /// 6339 /// \param ToType The type we are converting to. 6340 /// 6341 /// \param AllowObjCPointerConversion Allow a conversion from one 6342 /// Objective-C pointer to another. 6343 /// 6344 /// \returns true if the conversion is allowable, false otherwise. 6345 static bool isAllowableExplicitConversion(Sema &S, 6346 QualType ConvType, QualType ToType, 6347 bool AllowObjCPointerConversion) { 6348 QualType ToNonRefType = ToType.getNonReferenceType(); 6349 6350 // Easy case: the types are the same. 6351 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6352 return true; 6353 6354 // Allow qualification conversions. 6355 bool ObjCLifetimeConversion; 6356 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6357 ObjCLifetimeConversion)) 6358 return true; 6359 6360 // If we're not allowed to consider Objective-C pointer conversions, 6361 // we're done. 6362 if (!AllowObjCPointerConversion) 6363 return false; 6364 6365 // Is this an Objective-C pointer conversion? 6366 bool IncompatibleObjC = false; 6367 QualType ConvertedType; 6368 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6369 IncompatibleObjC); 6370 } 6371 6372 /// AddConversionCandidate - Add a C++ conversion function as a 6373 /// candidate in the candidate set (C++ [over.match.conv], 6374 /// C++ [over.match.copy]). From is the expression we're converting from, 6375 /// and ToType is the type that we're eventually trying to convert to 6376 /// (which may or may not be the same type as the type that the 6377 /// conversion function produces). 6378 void 6379 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6380 DeclAccessPair FoundDecl, 6381 CXXRecordDecl *ActingContext, 6382 Expr *From, QualType ToType, 6383 OverloadCandidateSet& CandidateSet, 6384 bool AllowObjCConversionOnExplicit) { 6385 assert(!Conversion->getDescribedFunctionTemplate() && 6386 "Conversion function templates use AddTemplateConversionCandidate"); 6387 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6388 if (!CandidateSet.isNewCandidate(Conversion)) 6389 return; 6390 6391 // If the conversion function has an undeduced return type, trigger its 6392 // deduction now. 6393 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6394 if (DeduceReturnType(Conversion, From->getExprLoc())) 6395 return; 6396 ConvType = Conversion->getConversionType().getNonReferenceType(); 6397 } 6398 6399 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6400 // operator is only a candidate if its return type is the target type or 6401 // can be converted to the target type with a qualification conversion. 6402 if (Conversion->isExplicit() && 6403 !isAllowableExplicitConversion(*this, ConvType, ToType, 6404 AllowObjCConversionOnExplicit)) 6405 return; 6406 6407 // Overload resolution is always an unevaluated context. 6408 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6409 6410 // Add this candidate 6411 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6412 Candidate.FoundDecl = FoundDecl; 6413 Candidate.Function = Conversion; 6414 Candidate.IsSurrogate = false; 6415 Candidate.IgnoreObjectArgument = false; 6416 Candidate.FinalConversion.setAsIdentityConversion(); 6417 Candidate.FinalConversion.setFromType(ConvType); 6418 Candidate.FinalConversion.setAllToTypes(ToType); 6419 Candidate.Viable = true; 6420 Candidate.ExplicitCallArguments = 1; 6421 6422 // C++ [over.match.funcs]p4: 6423 // For conversion functions, the function is considered to be a member of 6424 // the class of the implicit implied object argument for the purpose of 6425 // defining the type of the implicit object parameter. 6426 // 6427 // Determine the implicit conversion sequence for the implicit 6428 // object parameter. 6429 QualType ImplicitParamType = From->getType(); 6430 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6431 ImplicitParamType = FromPtrType->getPointeeType(); 6432 CXXRecordDecl *ConversionContext 6433 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6434 6435 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6436 *this, CandidateSet.getLocation(), From->getType(), 6437 From->Classify(Context), Conversion, ConversionContext); 6438 6439 if (Candidate.Conversions[0].isBad()) { 6440 Candidate.Viable = false; 6441 Candidate.FailureKind = ovl_fail_bad_conversion; 6442 return; 6443 } 6444 6445 // We won't go through a user-defined type conversion function to convert a 6446 // derived to base as such conversions are given Conversion Rank. They only 6447 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6448 QualType FromCanon 6449 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6450 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6451 if (FromCanon == ToCanon || 6452 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 6453 Candidate.Viable = false; 6454 Candidate.FailureKind = ovl_fail_trivial_conversion; 6455 return; 6456 } 6457 6458 // To determine what the conversion from the result of calling the 6459 // conversion function to the type we're eventually trying to 6460 // convert to (ToType), we need to synthesize a call to the 6461 // conversion function and attempt copy initialization from it. This 6462 // makes sure that we get the right semantics with respect to 6463 // lvalues/rvalues and the type. Fortunately, we can allocate this 6464 // call on the stack and we don't need its arguments to be 6465 // well-formed. 6466 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6467 VK_LValue, From->getLocStart()); 6468 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6469 Context.getPointerType(Conversion->getType()), 6470 CK_FunctionToPointerDecay, 6471 &ConversionRef, VK_RValue); 6472 6473 QualType ConversionType = Conversion->getConversionType(); 6474 if (!isCompleteType(From->getLocStart(), ConversionType)) { 6475 Candidate.Viable = false; 6476 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6477 return; 6478 } 6479 6480 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6481 6482 // Note that it is safe to allocate CallExpr on the stack here because 6483 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6484 // allocator). 6485 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6486 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6487 From->getLocStart()); 6488 ImplicitConversionSequence ICS = 6489 TryCopyInitialization(*this, &Call, ToType, 6490 /*SuppressUserConversions=*/true, 6491 /*InOverloadResolution=*/false, 6492 /*AllowObjCWritebackConversion=*/false); 6493 6494 switch (ICS.getKind()) { 6495 case ImplicitConversionSequence::StandardConversion: 6496 Candidate.FinalConversion = ICS.Standard; 6497 6498 // C++ [over.ics.user]p3: 6499 // If the user-defined conversion is specified by a specialization of a 6500 // conversion function template, the second standard conversion sequence 6501 // shall have exact match rank. 6502 if (Conversion->getPrimaryTemplate() && 6503 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6504 Candidate.Viable = false; 6505 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6506 return; 6507 } 6508 6509 // C++0x [dcl.init.ref]p5: 6510 // In the second case, if the reference is an rvalue reference and 6511 // the second standard conversion sequence of the user-defined 6512 // conversion sequence includes an lvalue-to-rvalue conversion, the 6513 // program is ill-formed. 6514 if (ToType->isRValueReferenceType() && 6515 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6516 Candidate.Viable = false; 6517 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6518 return; 6519 } 6520 break; 6521 6522 case ImplicitConversionSequence::BadConversion: 6523 Candidate.Viable = false; 6524 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6525 return; 6526 6527 default: 6528 llvm_unreachable( 6529 "Can only end up with a standard conversion sequence or failure"); 6530 } 6531 6532 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6533 Candidate.Viable = false; 6534 Candidate.FailureKind = ovl_fail_enable_if; 6535 Candidate.DeductionFailure.Data = FailedAttr; 6536 return; 6537 } 6538 } 6539 6540 /// \brief Adds a conversion function template specialization 6541 /// candidate to the overload set, using template argument deduction 6542 /// to deduce the template arguments of the conversion function 6543 /// template from the type that we are converting to (C++ 6544 /// [temp.deduct.conv]). 6545 void 6546 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6547 DeclAccessPair FoundDecl, 6548 CXXRecordDecl *ActingDC, 6549 Expr *From, QualType ToType, 6550 OverloadCandidateSet &CandidateSet, 6551 bool AllowObjCConversionOnExplicit) { 6552 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6553 "Only conversion function templates permitted here"); 6554 6555 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6556 return; 6557 6558 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6559 CXXConversionDecl *Specialization = nullptr; 6560 if (TemplateDeductionResult Result 6561 = DeduceTemplateArguments(FunctionTemplate, ToType, 6562 Specialization, Info)) { 6563 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6564 Candidate.FoundDecl = FoundDecl; 6565 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6566 Candidate.Viable = false; 6567 Candidate.FailureKind = ovl_fail_bad_deduction; 6568 Candidate.IsSurrogate = false; 6569 Candidate.IgnoreObjectArgument = false; 6570 Candidate.ExplicitCallArguments = 1; 6571 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6572 Info); 6573 return; 6574 } 6575 6576 // Add the conversion function template specialization produced by 6577 // template argument deduction as a candidate. 6578 assert(Specialization && "Missing function template specialization?"); 6579 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6580 CandidateSet, AllowObjCConversionOnExplicit); 6581 } 6582 6583 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6584 /// converts the given @c Object to a function pointer via the 6585 /// conversion function @c Conversion, and then attempts to call it 6586 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6587 /// the type of function that we'll eventually be calling. 6588 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6589 DeclAccessPair FoundDecl, 6590 CXXRecordDecl *ActingContext, 6591 const FunctionProtoType *Proto, 6592 Expr *Object, 6593 ArrayRef<Expr *> Args, 6594 OverloadCandidateSet& CandidateSet) { 6595 if (!CandidateSet.isNewCandidate(Conversion)) 6596 return; 6597 6598 // Overload resolution is always an unevaluated context. 6599 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6600 6601 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6602 Candidate.FoundDecl = FoundDecl; 6603 Candidate.Function = nullptr; 6604 Candidate.Surrogate = Conversion; 6605 Candidate.Viable = true; 6606 Candidate.IsSurrogate = true; 6607 Candidate.IgnoreObjectArgument = false; 6608 Candidate.ExplicitCallArguments = Args.size(); 6609 6610 // Determine the implicit conversion sequence for the implicit 6611 // object parameter. 6612 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 6613 *this, CandidateSet.getLocation(), Object->getType(), 6614 Object->Classify(Context), Conversion, ActingContext); 6615 if (ObjectInit.isBad()) { 6616 Candidate.Viable = false; 6617 Candidate.FailureKind = ovl_fail_bad_conversion; 6618 Candidate.Conversions[0] = ObjectInit; 6619 return; 6620 } 6621 6622 // The first conversion is actually a user-defined conversion whose 6623 // first conversion is ObjectInit's standard conversion (which is 6624 // effectively a reference binding). Record it as such. 6625 Candidate.Conversions[0].setUserDefined(); 6626 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6627 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6628 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6629 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6630 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6631 Candidate.Conversions[0].UserDefined.After 6632 = Candidate.Conversions[0].UserDefined.Before; 6633 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6634 6635 // Find the 6636 unsigned NumParams = Proto->getNumParams(); 6637 6638 // (C++ 13.3.2p2): A candidate function having fewer than m 6639 // parameters is viable only if it has an ellipsis in its parameter 6640 // list (8.3.5). 6641 if (Args.size() > NumParams && !Proto->isVariadic()) { 6642 Candidate.Viable = false; 6643 Candidate.FailureKind = ovl_fail_too_many_arguments; 6644 return; 6645 } 6646 6647 // Function types don't have any default arguments, so just check if 6648 // we have enough arguments. 6649 if (Args.size() < NumParams) { 6650 // Not enough arguments. 6651 Candidate.Viable = false; 6652 Candidate.FailureKind = ovl_fail_too_few_arguments; 6653 return; 6654 } 6655 6656 // Determine the implicit conversion sequences for each of the 6657 // arguments. 6658 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6659 if (ArgIdx < NumParams) { 6660 // (C++ 13.3.2p3): for F to be a viable function, there shall 6661 // exist for each argument an implicit conversion sequence 6662 // (13.3.3.1) that converts that argument to the corresponding 6663 // parameter of F. 6664 QualType ParamType = Proto->getParamType(ArgIdx); 6665 Candidate.Conversions[ArgIdx + 1] 6666 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6667 /*SuppressUserConversions=*/false, 6668 /*InOverloadResolution=*/false, 6669 /*AllowObjCWritebackConversion=*/ 6670 getLangOpts().ObjCAutoRefCount); 6671 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6672 Candidate.Viable = false; 6673 Candidate.FailureKind = ovl_fail_bad_conversion; 6674 return; 6675 } 6676 } else { 6677 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6678 // argument for which there is no corresponding parameter is 6679 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6680 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6681 } 6682 } 6683 6684 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6685 Candidate.Viable = false; 6686 Candidate.FailureKind = ovl_fail_enable_if; 6687 Candidate.DeductionFailure.Data = FailedAttr; 6688 return; 6689 } 6690 } 6691 6692 /// \brief Add overload candidates for overloaded operators that are 6693 /// member functions. 6694 /// 6695 /// Add the overloaded operator candidates that are member functions 6696 /// for the operator Op that was used in an operator expression such 6697 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6698 /// CandidateSet will store the added overload candidates. (C++ 6699 /// [over.match.oper]). 6700 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6701 SourceLocation OpLoc, 6702 ArrayRef<Expr *> Args, 6703 OverloadCandidateSet& CandidateSet, 6704 SourceRange OpRange) { 6705 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6706 6707 // C++ [over.match.oper]p3: 6708 // For a unary operator @ with an operand of a type whose 6709 // cv-unqualified version is T1, and for a binary operator @ with 6710 // a left operand of a type whose cv-unqualified version is T1 and 6711 // a right operand of a type whose cv-unqualified version is T2, 6712 // three sets of candidate functions, designated member 6713 // candidates, non-member candidates and built-in candidates, are 6714 // constructed as follows: 6715 QualType T1 = Args[0]->getType(); 6716 6717 // -- If T1 is a complete class type or a class currently being 6718 // defined, the set of member candidates is the result of the 6719 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6720 // the set of member candidates is empty. 6721 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6722 // Complete the type if it can be completed. 6723 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 6724 return; 6725 // If the type is neither complete nor being defined, bail out now. 6726 if (!T1Rec->getDecl()->getDefinition()) 6727 return; 6728 6729 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6730 LookupQualifiedName(Operators, T1Rec->getDecl()); 6731 Operators.suppressDiagnostics(); 6732 6733 for (LookupResult::iterator Oper = Operators.begin(), 6734 OperEnd = Operators.end(); 6735 Oper != OperEnd; 6736 ++Oper) 6737 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6738 Args[0]->Classify(Context), 6739 Args.slice(1), 6740 CandidateSet, 6741 /* SuppressUserConversions = */ false); 6742 } 6743 } 6744 6745 /// AddBuiltinCandidate - Add a candidate for a built-in 6746 /// operator. ResultTy and ParamTys are the result and parameter types 6747 /// of the built-in candidate, respectively. Args and NumArgs are the 6748 /// arguments being passed to the candidate. IsAssignmentOperator 6749 /// should be true when this built-in candidate is an assignment 6750 /// operator. NumContextualBoolArguments is the number of arguments 6751 /// (at the beginning of the argument list) that will be contextually 6752 /// converted to bool. 6753 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6754 ArrayRef<Expr *> Args, 6755 OverloadCandidateSet& CandidateSet, 6756 bool IsAssignmentOperator, 6757 unsigned NumContextualBoolArguments) { 6758 // Overload resolution is always an unevaluated context. 6759 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6760 6761 // Add this candidate 6762 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6763 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 6764 Candidate.Function = nullptr; 6765 Candidate.IsSurrogate = false; 6766 Candidate.IgnoreObjectArgument = false; 6767 Candidate.BuiltinTypes.ResultTy = ResultTy; 6768 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6769 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6770 6771 // Determine the implicit conversion sequences for each of the 6772 // arguments. 6773 Candidate.Viable = true; 6774 Candidate.ExplicitCallArguments = Args.size(); 6775 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6776 // C++ [over.match.oper]p4: 6777 // For the built-in assignment operators, conversions of the 6778 // left operand are restricted as follows: 6779 // -- no temporaries are introduced to hold the left operand, and 6780 // -- no user-defined conversions are applied to the left 6781 // operand to achieve a type match with the left-most 6782 // parameter of a built-in candidate. 6783 // 6784 // We block these conversions by turning off user-defined 6785 // conversions, since that is the only way that initialization of 6786 // a reference to a non-class type can occur from something that 6787 // is not of the same type. 6788 if (ArgIdx < NumContextualBoolArguments) { 6789 assert(ParamTys[ArgIdx] == Context.BoolTy && 6790 "Contextual conversion to bool requires bool type"); 6791 Candidate.Conversions[ArgIdx] 6792 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6793 } else { 6794 Candidate.Conversions[ArgIdx] 6795 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6796 ArgIdx == 0 && IsAssignmentOperator, 6797 /*InOverloadResolution=*/false, 6798 /*AllowObjCWritebackConversion=*/ 6799 getLangOpts().ObjCAutoRefCount); 6800 } 6801 if (Candidate.Conversions[ArgIdx].isBad()) { 6802 Candidate.Viable = false; 6803 Candidate.FailureKind = ovl_fail_bad_conversion; 6804 break; 6805 } 6806 } 6807 } 6808 6809 namespace { 6810 6811 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6812 /// candidate operator functions for built-in operators (C++ 6813 /// [over.built]). The types are separated into pointer types and 6814 /// enumeration types. 6815 class BuiltinCandidateTypeSet { 6816 /// TypeSet - A set of types. 6817 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6818 6819 /// PointerTypes - The set of pointer types that will be used in the 6820 /// built-in candidates. 6821 TypeSet PointerTypes; 6822 6823 /// MemberPointerTypes - The set of member pointer types that will be 6824 /// used in the built-in candidates. 6825 TypeSet MemberPointerTypes; 6826 6827 /// EnumerationTypes - The set of enumeration types that will be 6828 /// used in the built-in candidates. 6829 TypeSet EnumerationTypes; 6830 6831 /// \brief The set of vector types that will be used in the built-in 6832 /// candidates. 6833 TypeSet VectorTypes; 6834 6835 /// \brief A flag indicating non-record types are viable candidates 6836 bool HasNonRecordTypes; 6837 6838 /// \brief A flag indicating whether either arithmetic or enumeration types 6839 /// were present in the candidate set. 6840 bool HasArithmeticOrEnumeralTypes; 6841 6842 /// \brief A flag indicating whether the nullptr type was present in the 6843 /// candidate set. 6844 bool HasNullPtrType; 6845 6846 /// Sema - The semantic analysis instance where we are building the 6847 /// candidate type set. 6848 Sema &SemaRef; 6849 6850 /// Context - The AST context in which we will build the type sets. 6851 ASTContext &Context; 6852 6853 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6854 const Qualifiers &VisibleQuals); 6855 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6856 6857 public: 6858 /// iterator - Iterates through the types that are part of the set. 6859 typedef TypeSet::iterator iterator; 6860 6861 BuiltinCandidateTypeSet(Sema &SemaRef) 6862 : HasNonRecordTypes(false), 6863 HasArithmeticOrEnumeralTypes(false), 6864 HasNullPtrType(false), 6865 SemaRef(SemaRef), 6866 Context(SemaRef.Context) { } 6867 6868 void AddTypesConvertedFrom(QualType Ty, 6869 SourceLocation Loc, 6870 bool AllowUserConversions, 6871 bool AllowExplicitConversions, 6872 const Qualifiers &VisibleTypeConversionsQuals); 6873 6874 /// pointer_begin - First pointer type found; 6875 iterator pointer_begin() { return PointerTypes.begin(); } 6876 6877 /// pointer_end - Past the last pointer type found; 6878 iterator pointer_end() { return PointerTypes.end(); } 6879 6880 /// member_pointer_begin - First member pointer type found; 6881 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6882 6883 /// member_pointer_end - Past the last member pointer type found; 6884 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6885 6886 /// enumeration_begin - First enumeration type found; 6887 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6888 6889 /// enumeration_end - Past the last enumeration type found; 6890 iterator enumeration_end() { return EnumerationTypes.end(); } 6891 6892 iterator vector_begin() { return VectorTypes.begin(); } 6893 iterator vector_end() { return VectorTypes.end(); } 6894 6895 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6896 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6897 bool hasNullPtrType() const { return HasNullPtrType; } 6898 }; 6899 6900 } // end anonymous namespace 6901 6902 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6903 /// the set of pointer types along with any more-qualified variants of 6904 /// that type. For example, if @p Ty is "int const *", this routine 6905 /// will add "int const *", "int const volatile *", "int const 6906 /// restrict *", and "int const volatile restrict *" to the set of 6907 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6908 /// false otherwise. 6909 /// 6910 /// FIXME: what to do about extended qualifiers? 6911 bool 6912 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6913 const Qualifiers &VisibleQuals) { 6914 6915 // Insert this type. 6916 if (!PointerTypes.insert(Ty).second) 6917 return false; 6918 6919 QualType PointeeTy; 6920 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6921 bool buildObjCPtr = false; 6922 if (!PointerTy) { 6923 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6924 PointeeTy = PTy->getPointeeType(); 6925 buildObjCPtr = true; 6926 } else { 6927 PointeeTy = PointerTy->getPointeeType(); 6928 } 6929 6930 // Don't add qualified variants of arrays. For one, they're not allowed 6931 // (the qualifier would sink to the element type), and for another, the 6932 // only overload situation where it matters is subscript or pointer +- int, 6933 // and those shouldn't have qualifier variants anyway. 6934 if (PointeeTy->isArrayType()) 6935 return true; 6936 6937 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6938 bool hasVolatile = VisibleQuals.hasVolatile(); 6939 bool hasRestrict = VisibleQuals.hasRestrict(); 6940 6941 // Iterate through all strict supersets of BaseCVR. 6942 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6943 if ((CVR | BaseCVR) != CVR) continue; 6944 // Skip over volatile if no volatile found anywhere in the types. 6945 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6946 6947 // Skip over restrict if no restrict found anywhere in the types, or if 6948 // the type cannot be restrict-qualified. 6949 if ((CVR & Qualifiers::Restrict) && 6950 (!hasRestrict || 6951 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6952 continue; 6953 6954 // Build qualified pointee type. 6955 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6956 6957 // Build qualified pointer type. 6958 QualType QPointerTy; 6959 if (!buildObjCPtr) 6960 QPointerTy = Context.getPointerType(QPointeeTy); 6961 else 6962 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6963 6964 // Insert qualified pointer type. 6965 PointerTypes.insert(QPointerTy); 6966 } 6967 6968 return true; 6969 } 6970 6971 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6972 /// to the set of pointer types along with any more-qualified variants of 6973 /// that type. For example, if @p Ty is "int const *", this routine 6974 /// will add "int const *", "int const volatile *", "int const 6975 /// restrict *", and "int const volatile restrict *" to the set of 6976 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6977 /// false otherwise. 6978 /// 6979 /// FIXME: what to do about extended qualifiers? 6980 bool 6981 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6982 QualType Ty) { 6983 // Insert this type. 6984 if (!MemberPointerTypes.insert(Ty).second) 6985 return false; 6986 6987 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6988 assert(PointerTy && "type was not a member pointer type!"); 6989 6990 QualType PointeeTy = PointerTy->getPointeeType(); 6991 // Don't add qualified variants of arrays. For one, they're not allowed 6992 // (the qualifier would sink to the element type), and for another, the 6993 // only overload situation where it matters is subscript or pointer +- int, 6994 // and those shouldn't have qualifier variants anyway. 6995 if (PointeeTy->isArrayType()) 6996 return true; 6997 const Type *ClassTy = PointerTy->getClass(); 6998 6999 // Iterate through all strict supersets of the pointee type's CVR 7000 // qualifiers. 7001 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7002 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7003 if ((CVR | BaseCVR) != CVR) continue; 7004 7005 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7006 MemberPointerTypes.insert( 7007 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7008 } 7009 7010 return true; 7011 } 7012 7013 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7014 /// Ty can be implicit converted to the given set of @p Types. We're 7015 /// primarily interested in pointer types and enumeration types. We also 7016 /// take member pointer types, for the conditional operator. 7017 /// AllowUserConversions is true if we should look at the conversion 7018 /// functions of a class type, and AllowExplicitConversions if we 7019 /// should also include the explicit conversion functions of a class 7020 /// type. 7021 void 7022 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7023 SourceLocation Loc, 7024 bool AllowUserConversions, 7025 bool AllowExplicitConversions, 7026 const Qualifiers &VisibleQuals) { 7027 // Only deal with canonical types. 7028 Ty = Context.getCanonicalType(Ty); 7029 7030 // Look through reference types; they aren't part of the type of an 7031 // expression for the purposes of conversions. 7032 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7033 Ty = RefTy->getPointeeType(); 7034 7035 // If we're dealing with an array type, decay to the pointer. 7036 if (Ty->isArrayType()) 7037 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7038 7039 // Otherwise, we don't care about qualifiers on the type. 7040 Ty = Ty.getLocalUnqualifiedType(); 7041 7042 // Flag if we ever add a non-record type. 7043 const RecordType *TyRec = Ty->getAs<RecordType>(); 7044 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7045 7046 // Flag if we encounter an arithmetic type. 7047 HasArithmeticOrEnumeralTypes = 7048 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7049 7050 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7051 PointerTypes.insert(Ty); 7052 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7053 // Insert our type, and its more-qualified variants, into the set 7054 // of types. 7055 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7056 return; 7057 } else if (Ty->isMemberPointerType()) { 7058 // Member pointers are far easier, since the pointee can't be converted. 7059 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7060 return; 7061 } else if (Ty->isEnumeralType()) { 7062 HasArithmeticOrEnumeralTypes = true; 7063 EnumerationTypes.insert(Ty); 7064 } else if (Ty->isVectorType()) { 7065 // We treat vector types as arithmetic types in many contexts as an 7066 // extension. 7067 HasArithmeticOrEnumeralTypes = true; 7068 VectorTypes.insert(Ty); 7069 } else if (Ty->isNullPtrType()) { 7070 HasNullPtrType = true; 7071 } else if (AllowUserConversions && TyRec) { 7072 // No conversion functions in incomplete types. 7073 if (!SemaRef.isCompleteType(Loc, Ty)) 7074 return; 7075 7076 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7077 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7078 if (isa<UsingShadowDecl>(D)) 7079 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7080 7081 // Skip conversion function templates; they don't tell us anything 7082 // about which builtin types we can convert to. 7083 if (isa<FunctionTemplateDecl>(D)) 7084 continue; 7085 7086 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7087 if (AllowExplicitConversions || !Conv->isExplicit()) { 7088 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7089 VisibleQuals); 7090 } 7091 } 7092 } 7093 } 7094 7095 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 7096 /// the volatile- and non-volatile-qualified assignment operators for the 7097 /// given type to the candidate set. 7098 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7099 QualType T, 7100 ArrayRef<Expr *> Args, 7101 OverloadCandidateSet &CandidateSet) { 7102 QualType ParamTypes[2]; 7103 7104 // T& operator=(T&, T) 7105 ParamTypes[0] = S.Context.getLValueReferenceType(T); 7106 ParamTypes[1] = T; 7107 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7108 /*IsAssignmentOperator=*/true); 7109 7110 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7111 // volatile T& operator=(volatile T&, T) 7112 ParamTypes[0] 7113 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 7114 ParamTypes[1] = T; 7115 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7116 /*IsAssignmentOperator=*/true); 7117 } 7118 } 7119 7120 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7121 /// if any, found in visible type conversion functions found in ArgExpr's type. 7122 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7123 Qualifiers VRQuals; 7124 const RecordType *TyRec; 7125 if (const MemberPointerType *RHSMPType = 7126 ArgExpr->getType()->getAs<MemberPointerType>()) 7127 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7128 else 7129 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7130 if (!TyRec) { 7131 // Just to be safe, assume the worst case. 7132 VRQuals.addVolatile(); 7133 VRQuals.addRestrict(); 7134 return VRQuals; 7135 } 7136 7137 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7138 if (!ClassDecl->hasDefinition()) 7139 return VRQuals; 7140 7141 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7142 if (isa<UsingShadowDecl>(D)) 7143 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7144 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7145 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7146 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7147 CanTy = ResTypeRef->getPointeeType(); 7148 // Need to go down the pointer/mempointer chain and add qualifiers 7149 // as see them. 7150 bool done = false; 7151 while (!done) { 7152 if (CanTy.isRestrictQualified()) 7153 VRQuals.addRestrict(); 7154 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7155 CanTy = ResTypePtr->getPointeeType(); 7156 else if (const MemberPointerType *ResTypeMPtr = 7157 CanTy->getAs<MemberPointerType>()) 7158 CanTy = ResTypeMPtr->getPointeeType(); 7159 else 7160 done = true; 7161 if (CanTy.isVolatileQualified()) 7162 VRQuals.addVolatile(); 7163 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7164 return VRQuals; 7165 } 7166 } 7167 } 7168 return VRQuals; 7169 } 7170 7171 namespace { 7172 7173 /// \brief Helper class to manage the addition of builtin operator overload 7174 /// candidates. It provides shared state and utility methods used throughout 7175 /// the process, as well as a helper method to add each group of builtin 7176 /// operator overloads from the standard to a candidate set. 7177 class BuiltinOperatorOverloadBuilder { 7178 // Common instance state available to all overload candidate addition methods. 7179 Sema &S; 7180 ArrayRef<Expr *> Args; 7181 Qualifiers VisibleTypeConversionsQuals; 7182 bool HasArithmeticOrEnumeralCandidateType; 7183 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7184 OverloadCandidateSet &CandidateSet; 7185 7186 // Define some constants used to index and iterate over the arithemetic types 7187 // provided via the getArithmeticType() method below. 7188 // The "promoted arithmetic types" are the arithmetic 7189 // types are that preserved by promotion (C++ [over.built]p2). 7190 static const unsigned FirstIntegralType = 3; 7191 static const unsigned LastIntegralType = 20; 7192 static const unsigned FirstPromotedIntegralType = 3, 7193 LastPromotedIntegralType = 11; 7194 static const unsigned FirstPromotedArithmeticType = 0, 7195 LastPromotedArithmeticType = 11; 7196 static const unsigned NumArithmeticTypes = 20; 7197 7198 /// \brief Get the canonical type for a given arithmetic type index. 7199 CanQualType getArithmeticType(unsigned index) { 7200 assert(index < NumArithmeticTypes); 7201 static CanQualType ASTContext::* const 7202 ArithmeticTypes[NumArithmeticTypes] = { 7203 // Start of promoted types. 7204 &ASTContext::FloatTy, 7205 &ASTContext::DoubleTy, 7206 &ASTContext::LongDoubleTy, 7207 7208 // Start of integral types. 7209 &ASTContext::IntTy, 7210 &ASTContext::LongTy, 7211 &ASTContext::LongLongTy, 7212 &ASTContext::Int128Ty, 7213 &ASTContext::UnsignedIntTy, 7214 &ASTContext::UnsignedLongTy, 7215 &ASTContext::UnsignedLongLongTy, 7216 &ASTContext::UnsignedInt128Ty, 7217 // End of promoted types. 7218 7219 &ASTContext::BoolTy, 7220 &ASTContext::CharTy, 7221 &ASTContext::WCharTy, 7222 &ASTContext::Char16Ty, 7223 &ASTContext::Char32Ty, 7224 &ASTContext::SignedCharTy, 7225 &ASTContext::ShortTy, 7226 &ASTContext::UnsignedCharTy, 7227 &ASTContext::UnsignedShortTy, 7228 // End of integral types. 7229 // FIXME: What about complex? What about half? 7230 }; 7231 return S.Context.*ArithmeticTypes[index]; 7232 } 7233 7234 /// \brief Gets the canonical type resulting from the usual arithemetic 7235 /// converions for the given arithmetic types. 7236 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 7237 // Accelerator table for performing the usual arithmetic conversions. 7238 // The rules are basically: 7239 // - if either is floating-point, use the wider floating-point 7240 // - if same signedness, use the higher rank 7241 // - if same size, use unsigned of the higher rank 7242 // - use the larger type 7243 // These rules, together with the axiom that higher ranks are 7244 // never smaller, are sufficient to precompute all of these results 7245 // *except* when dealing with signed types of higher rank. 7246 // (we could precompute SLL x UI for all known platforms, but it's 7247 // better not to make any assumptions). 7248 // We assume that int128 has a higher rank than long long on all platforms. 7249 enum PromotedType { 7250 Dep=-1, 7251 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 7252 }; 7253 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 7254 [LastPromotedArithmeticType] = { 7255 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 7256 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 7257 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 7258 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 7259 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 7260 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 7261 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 7262 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 7263 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 7264 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 7265 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 7266 }; 7267 7268 assert(L < LastPromotedArithmeticType); 7269 assert(R < LastPromotedArithmeticType); 7270 int Idx = ConversionsTable[L][R]; 7271 7272 // Fast path: the table gives us a concrete answer. 7273 if (Idx != Dep) return getArithmeticType(Idx); 7274 7275 // Slow path: we need to compare widths. 7276 // An invariant is that the signed type has higher rank. 7277 CanQualType LT = getArithmeticType(L), 7278 RT = getArithmeticType(R); 7279 unsigned LW = S.Context.getIntWidth(LT), 7280 RW = S.Context.getIntWidth(RT); 7281 7282 // If they're different widths, use the signed type. 7283 if (LW > RW) return LT; 7284 else if (LW < RW) return RT; 7285 7286 // Otherwise, use the unsigned type of the signed type's rank. 7287 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 7288 assert(L == SLL || R == SLL); 7289 return S.Context.UnsignedLongLongTy; 7290 } 7291 7292 /// \brief Helper method to factor out the common pattern of adding overloads 7293 /// for '++' and '--' builtin operators. 7294 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7295 bool HasVolatile, 7296 bool HasRestrict) { 7297 QualType ParamTypes[2] = { 7298 S.Context.getLValueReferenceType(CandidateTy), 7299 S.Context.IntTy 7300 }; 7301 7302 // Non-volatile version. 7303 if (Args.size() == 1) 7304 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7305 else 7306 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7307 7308 // Use a heuristic to reduce number of builtin candidates in the set: 7309 // add volatile version only if there are conversions to a volatile type. 7310 if (HasVolatile) { 7311 ParamTypes[0] = 7312 S.Context.getLValueReferenceType( 7313 S.Context.getVolatileType(CandidateTy)); 7314 if (Args.size() == 1) 7315 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7316 else 7317 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7318 } 7319 7320 // Add restrict version only if there are conversions to a restrict type 7321 // and our candidate type is a non-restrict-qualified pointer. 7322 if (HasRestrict && CandidateTy->isAnyPointerType() && 7323 !CandidateTy.isRestrictQualified()) { 7324 ParamTypes[0] 7325 = S.Context.getLValueReferenceType( 7326 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7327 if (Args.size() == 1) 7328 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7329 else 7330 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7331 7332 if (HasVolatile) { 7333 ParamTypes[0] 7334 = S.Context.getLValueReferenceType( 7335 S.Context.getCVRQualifiedType(CandidateTy, 7336 (Qualifiers::Volatile | 7337 Qualifiers::Restrict))); 7338 if (Args.size() == 1) 7339 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7340 else 7341 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7342 } 7343 } 7344 7345 } 7346 7347 public: 7348 BuiltinOperatorOverloadBuilder( 7349 Sema &S, ArrayRef<Expr *> Args, 7350 Qualifiers VisibleTypeConversionsQuals, 7351 bool HasArithmeticOrEnumeralCandidateType, 7352 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7353 OverloadCandidateSet &CandidateSet) 7354 : S(S), Args(Args), 7355 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7356 HasArithmeticOrEnumeralCandidateType( 7357 HasArithmeticOrEnumeralCandidateType), 7358 CandidateTypes(CandidateTypes), 7359 CandidateSet(CandidateSet) { 7360 // Validate some of our static helper constants in debug builds. 7361 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7362 "Invalid first promoted integral type"); 7363 assert(getArithmeticType(LastPromotedIntegralType - 1) 7364 == S.Context.UnsignedInt128Ty && 7365 "Invalid last promoted integral type"); 7366 assert(getArithmeticType(FirstPromotedArithmeticType) 7367 == S.Context.FloatTy && 7368 "Invalid first promoted arithmetic type"); 7369 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7370 == S.Context.UnsignedInt128Ty && 7371 "Invalid last promoted arithmetic type"); 7372 } 7373 7374 // C++ [over.built]p3: 7375 // 7376 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7377 // is either volatile or empty, there exist candidate operator 7378 // functions of the form 7379 // 7380 // VQ T& operator++(VQ T&); 7381 // T operator++(VQ T&, int); 7382 // 7383 // C++ [over.built]p4: 7384 // 7385 // For every pair (T, VQ), where T is an arithmetic type other 7386 // than bool, and VQ is either volatile or empty, there exist 7387 // candidate operator functions of the form 7388 // 7389 // VQ T& operator--(VQ T&); 7390 // T operator--(VQ T&, int); 7391 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7392 if (!HasArithmeticOrEnumeralCandidateType) 7393 return; 7394 7395 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7396 Arith < NumArithmeticTypes; ++Arith) { 7397 addPlusPlusMinusMinusStyleOverloads( 7398 getArithmeticType(Arith), 7399 VisibleTypeConversionsQuals.hasVolatile(), 7400 VisibleTypeConversionsQuals.hasRestrict()); 7401 } 7402 } 7403 7404 // C++ [over.built]p5: 7405 // 7406 // For every pair (T, VQ), where T is a cv-qualified or 7407 // cv-unqualified object type, and VQ is either volatile or 7408 // empty, there exist candidate operator functions of the form 7409 // 7410 // T*VQ& operator++(T*VQ&); 7411 // T*VQ& operator--(T*VQ&); 7412 // T* operator++(T*VQ&, int); 7413 // T* operator--(T*VQ&, int); 7414 void addPlusPlusMinusMinusPointerOverloads() { 7415 for (BuiltinCandidateTypeSet::iterator 7416 Ptr = CandidateTypes[0].pointer_begin(), 7417 PtrEnd = CandidateTypes[0].pointer_end(); 7418 Ptr != PtrEnd; ++Ptr) { 7419 // Skip pointer types that aren't pointers to object types. 7420 if (!(*Ptr)->getPointeeType()->isObjectType()) 7421 continue; 7422 7423 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7424 (!(*Ptr).isVolatileQualified() && 7425 VisibleTypeConversionsQuals.hasVolatile()), 7426 (!(*Ptr).isRestrictQualified() && 7427 VisibleTypeConversionsQuals.hasRestrict())); 7428 } 7429 } 7430 7431 // C++ [over.built]p6: 7432 // For every cv-qualified or cv-unqualified object type T, there 7433 // exist candidate operator functions of the form 7434 // 7435 // T& operator*(T*); 7436 // 7437 // C++ [over.built]p7: 7438 // For every function type T that does not have cv-qualifiers or a 7439 // ref-qualifier, there exist candidate operator functions of the form 7440 // T& operator*(T*); 7441 void addUnaryStarPointerOverloads() { 7442 for (BuiltinCandidateTypeSet::iterator 7443 Ptr = CandidateTypes[0].pointer_begin(), 7444 PtrEnd = CandidateTypes[0].pointer_end(); 7445 Ptr != PtrEnd; ++Ptr) { 7446 QualType ParamTy = *Ptr; 7447 QualType PointeeTy = ParamTy->getPointeeType(); 7448 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7449 continue; 7450 7451 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7452 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7453 continue; 7454 7455 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7456 &ParamTy, Args, CandidateSet); 7457 } 7458 } 7459 7460 // C++ [over.built]p9: 7461 // For every promoted arithmetic type T, there exist candidate 7462 // operator functions of the form 7463 // 7464 // T operator+(T); 7465 // T operator-(T); 7466 void addUnaryPlusOrMinusArithmeticOverloads() { 7467 if (!HasArithmeticOrEnumeralCandidateType) 7468 return; 7469 7470 for (unsigned Arith = FirstPromotedArithmeticType; 7471 Arith < LastPromotedArithmeticType; ++Arith) { 7472 QualType ArithTy = getArithmeticType(Arith); 7473 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7474 } 7475 7476 // Extension: We also add these operators for vector types. 7477 for (BuiltinCandidateTypeSet::iterator 7478 Vec = CandidateTypes[0].vector_begin(), 7479 VecEnd = CandidateTypes[0].vector_end(); 7480 Vec != VecEnd; ++Vec) { 7481 QualType VecTy = *Vec; 7482 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7483 } 7484 } 7485 7486 // C++ [over.built]p8: 7487 // For every type T, there exist candidate operator functions of 7488 // the form 7489 // 7490 // T* operator+(T*); 7491 void addUnaryPlusPointerOverloads() { 7492 for (BuiltinCandidateTypeSet::iterator 7493 Ptr = CandidateTypes[0].pointer_begin(), 7494 PtrEnd = CandidateTypes[0].pointer_end(); 7495 Ptr != PtrEnd; ++Ptr) { 7496 QualType ParamTy = *Ptr; 7497 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7498 } 7499 } 7500 7501 // C++ [over.built]p10: 7502 // For every promoted integral type T, there exist candidate 7503 // operator functions of the form 7504 // 7505 // T operator~(T); 7506 void addUnaryTildePromotedIntegralOverloads() { 7507 if (!HasArithmeticOrEnumeralCandidateType) 7508 return; 7509 7510 for (unsigned Int = FirstPromotedIntegralType; 7511 Int < LastPromotedIntegralType; ++Int) { 7512 QualType IntTy = getArithmeticType(Int); 7513 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7514 } 7515 7516 // Extension: We also add this operator for vector types. 7517 for (BuiltinCandidateTypeSet::iterator 7518 Vec = CandidateTypes[0].vector_begin(), 7519 VecEnd = CandidateTypes[0].vector_end(); 7520 Vec != VecEnd; ++Vec) { 7521 QualType VecTy = *Vec; 7522 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7523 } 7524 } 7525 7526 // C++ [over.match.oper]p16: 7527 // For every pointer to member type T, there exist candidate operator 7528 // functions of the form 7529 // 7530 // bool operator==(T,T); 7531 // bool operator!=(T,T); 7532 void addEqualEqualOrNotEqualMemberPointerOverloads() { 7533 /// Set of (canonical) types that we've already handled. 7534 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7535 7536 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7537 for (BuiltinCandidateTypeSet::iterator 7538 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7539 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7540 MemPtr != MemPtrEnd; 7541 ++MemPtr) { 7542 // Don't add the same builtin candidate twice. 7543 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7544 continue; 7545 7546 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7547 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7548 } 7549 } 7550 } 7551 7552 // C++ [over.built]p15: 7553 // 7554 // For every T, where T is an enumeration type, a pointer type, or 7555 // std::nullptr_t, there exist candidate operator functions of the form 7556 // 7557 // bool operator<(T, T); 7558 // bool operator>(T, T); 7559 // bool operator<=(T, T); 7560 // bool operator>=(T, T); 7561 // bool operator==(T, T); 7562 // bool operator!=(T, T); 7563 void addRelationalPointerOrEnumeralOverloads() { 7564 // C++ [over.match.oper]p3: 7565 // [...]the built-in candidates include all of the candidate operator 7566 // functions defined in 13.6 that, compared to the given operator, [...] 7567 // do not have the same parameter-type-list as any non-template non-member 7568 // candidate. 7569 // 7570 // Note that in practice, this only affects enumeration types because there 7571 // aren't any built-in candidates of record type, and a user-defined operator 7572 // must have an operand of record or enumeration type. Also, the only other 7573 // overloaded operator with enumeration arguments, operator=, 7574 // cannot be overloaded for enumeration types, so this is the only place 7575 // where we must suppress candidates like this. 7576 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7577 UserDefinedBinaryOperators; 7578 7579 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7580 if (CandidateTypes[ArgIdx].enumeration_begin() != 7581 CandidateTypes[ArgIdx].enumeration_end()) { 7582 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7583 CEnd = CandidateSet.end(); 7584 C != CEnd; ++C) { 7585 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7586 continue; 7587 7588 if (C->Function->isFunctionTemplateSpecialization()) 7589 continue; 7590 7591 QualType FirstParamType = 7592 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7593 QualType SecondParamType = 7594 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7595 7596 // Skip if either parameter isn't of enumeral type. 7597 if (!FirstParamType->isEnumeralType() || 7598 !SecondParamType->isEnumeralType()) 7599 continue; 7600 7601 // Add this operator to the set of known user-defined operators. 7602 UserDefinedBinaryOperators.insert( 7603 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7604 S.Context.getCanonicalType(SecondParamType))); 7605 } 7606 } 7607 } 7608 7609 /// Set of (canonical) types that we've already handled. 7610 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7611 7612 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7613 for (BuiltinCandidateTypeSet::iterator 7614 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7615 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7616 Ptr != PtrEnd; ++Ptr) { 7617 // Don't add the same builtin candidate twice. 7618 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7619 continue; 7620 7621 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7622 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7623 } 7624 for (BuiltinCandidateTypeSet::iterator 7625 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7626 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7627 Enum != EnumEnd; ++Enum) { 7628 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7629 7630 // Don't add the same builtin candidate twice, or if a user defined 7631 // candidate exists. 7632 if (!AddedTypes.insert(CanonType).second || 7633 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7634 CanonType))) 7635 continue; 7636 7637 QualType ParamTypes[2] = { *Enum, *Enum }; 7638 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7639 } 7640 7641 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7642 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7643 if (AddedTypes.insert(NullPtrTy).second && 7644 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7645 NullPtrTy))) { 7646 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7647 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7648 CandidateSet); 7649 } 7650 } 7651 } 7652 } 7653 7654 // C++ [over.built]p13: 7655 // 7656 // For every cv-qualified or cv-unqualified object type T 7657 // there exist candidate operator functions of the form 7658 // 7659 // T* operator+(T*, ptrdiff_t); 7660 // T& operator[](T*, ptrdiff_t); [BELOW] 7661 // T* operator-(T*, ptrdiff_t); 7662 // T* operator+(ptrdiff_t, T*); 7663 // T& operator[](ptrdiff_t, T*); [BELOW] 7664 // 7665 // C++ [over.built]p14: 7666 // 7667 // For every T, where T is a pointer to object type, there 7668 // exist candidate operator functions of the form 7669 // 7670 // ptrdiff_t operator-(T, T); 7671 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7672 /// Set of (canonical) types that we've already handled. 7673 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7674 7675 for (int Arg = 0; Arg < 2; ++Arg) { 7676 QualType AsymmetricParamTypes[2] = { 7677 S.Context.getPointerDiffType(), 7678 S.Context.getPointerDiffType(), 7679 }; 7680 for (BuiltinCandidateTypeSet::iterator 7681 Ptr = CandidateTypes[Arg].pointer_begin(), 7682 PtrEnd = CandidateTypes[Arg].pointer_end(); 7683 Ptr != PtrEnd; ++Ptr) { 7684 QualType PointeeTy = (*Ptr)->getPointeeType(); 7685 if (!PointeeTy->isObjectType()) 7686 continue; 7687 7688 AsymmetricParamTypes[Arg] = *Ptr; 7689 if (Arg == 0 || Op == OO_Plus) { 7690 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7691 // T* operator+(ptrdiff_t, T*); 7692 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet); 7693 } 7694 if (Op == OO_Minus) { 7695 // ptrdiff_t operator-(T, T); 7696 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7697 continue; 7698 7699 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7700 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7701 Args, CandidateSet); 7702 } 7703 } 7704 } 7705 } 7706 7707 // C++ [over.built]p12: 7708 // 7709 // For every pair of promoted arithmetic types L and R, there 7710 // exist candidate operator functions of the form 7711 // 7712 // LR operator*(L, R); 7713 // LR operator/(L, R); 7714 // LR operator+(L, R); 7715 // LR operator-(L, R); 7716 // bool operator<(L, R); 7717 // bool operator>(L, R); 7718 // bool operator<=(L, R); 7719 // bool operator>=(L, R); 7720 // bool operator==(L, R); 7721 // bool operator!=(L, R); 7722 // 7723 // where LR is the result of the usual arithmetic conversions 7724 // between types L and R. 7725 // 7726 // C++ [over.built]p24: 7727 // 7728 // For every pair of promoted arithmetic types L and R, there exist 7729 // candidate operator functions of the form 7730 // 7731 // LR operator?(bool, L, R); 7732 // 7733 // where LR is the result of the usual arithmetic conversions 7734 // between types L and R. 7735 // Our candidates ignore the first parameter. 7736 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7737 if (!HasArithmeticOrEnumeralCandidateType) 7738 return; 7739 7740 for (unsigned Left = FirstPromotedArithmeticType; 7741 Left < LastPromotedArithmeticType; ++Left) { 7742 for (unsigned Right = FirstPromotedArithmeticType; 7743 Right < LastPromotedArithmeticType; ++Right) { 7744 QualType LandR[2] = { getArithmeticType(Left), 7745 getArithmeticType(Right) }; 7746 QualType Result = 7747 isComparison ? S.Context.BoolTy 7748 : getUsualArithmeticConversions(Left, Right); 7749 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7750 } 7751 } 7752 7753 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7754 // conditional operator for vector types. 7755 for (BuiltinCandidateTypeSet::iterator 7756 Vec1 = CandidateTypes[0].vector_begin(), 7757 Vec1End = CandidateTypes[0].vector_end(); 7758 Vec1 != Vec1End; ++Vec1) { 7759 for (BuiltinCandidateTypeSet::iterator 7760 Vec2 = CandidateTypes[1].vector_begin(), 7761 Vec2End = CandidateTypes[1].vector_end(); 7762 Vec2 != Vec2End; ++Vec2) { 7763 QualType LandR[2] = { *Vec1, *Vec2 }; 7764 QualType Result = S.Context.BoolTy; 7765 if (!isComparison) { 7766 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7767 Result = *Vec1; 7768 else 7769 Result = *Vec2; 7770 } 7771 7772 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7773 } 7774 } 7775 } 7776 7777 // C++ [over.built]p17: 7778 // 7779 // For every pair of promoted integral types L and R, there 7780 // exist candidate operator functions of the form 7781 // 7782 // LR operator%(L, R); 7783 // LR operator&(L, R); 7784 // LR operator^(L, R); 7785 // LR operator|(L, R); 7786 // L operator<<(L, R); 7787 // L operator>>(L, R); 7788 // 7789 // where LR is the result of the usual arithmetic conversions 7790 // between types L and R. 7791 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7792 if (!HasArithmeticOrEnumeralCandidateType) 7793 return; 7794 7795 for (unsigned Left = FirstPromotedIntegralType; 7796 Left < LastPromotedIntegralType; ++Left) { 7797 for (unsigned Right = FirstPromotedIntegralType; 7798 Right < LastPromotedIntegralType; ++Right) { 7799 QualType LandR[2] = { getArithmeticType(Left), 7800 getArithmeticType(Right) }; 7801 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7802 ? LandR[0] 7803 : getUsualArithmeticConversions(Left, Right); 7804 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7805 } 7806 } 7807 } 7808 7809 // C++ [over.built]p20: 7810 // 7811 // For every pair (T, VQ), where T is an enumeration or 7812 // pointer to member type and VQ is either volatile or 7813 // empty, there exist candidate operator functions of the form 7814 // 7815 // VQ T& operator=(VQ T&, T); 7816 void addAssignmentMemberPointerOrEnumeralOverloads() { 7817 /// Set of (canonical) types that we've already handled. 7818 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7819 7820 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7821 for (BuiltinCandidateTypeSet::iterator 7822 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7823 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7824 Enum != EnumEnd; ++Enum) { 7825 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 7826 continue; 7827 7828 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7829 } 7830 7831 for (BuiltinCandidateTypeSet::iterator 7832 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7833 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7834 MemPtr != MemPtrEnd; ++MemPtr) { 7835 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7836 continue; 7837 7838 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7839 } 7840 } 7841 } 7842 7843 // C++ [over.built]p19: 7844 // 7845 // For every pair (T, VQ), where T is any type and VQ is either 7846 // volatile or empty, there exist candidate operator functions 7847 // of the form 7848 // 7849 // T*VQ& operator=(T*VQ&, T*); 7850 // 7851 // C++ [over.built]p21: 7852 // 7853 // For every pair (T, VQ), where T is a cv-qualified or 7854 // cv-unqualified object type and VQ is either volatile or 7855 // empty, there exist candidate operator functions of the form 7856 // 7857 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7858 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7859 void addAssignmentPointerOverloads(bool isEqualOp) { 7860 /// Set of (canonical) types that we've already handled. 7861 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7862 7863 for (BuiltinCandidateTypeSet::iterator 7864 Ptr = CandidateTypes[0].pointer_begin(), 7865 PtrEnd = CandidateTypes[0].pointer_end(); 7866 Ptr != PtrEnd; ++Ptr) { 7867 // If this is operator=, keep track of the builtin candidates we added. 7868 if (isEqualOp) 7869 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7870 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7871 continue; 7872 7873 // non-volatile version 7874 QualType ParamTypes[2] = { 7875 S.Context.getLValueReferenceType(*Ptr), 7876 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7877 }; 7878 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7879 /*IsAssigmentOperator=*/ isEqualOp); 7880 7881 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7882 VisibleTypeConversionsQuals.hasVolatile(); 7883 if (NeedVolatile) { 7884 // volatile version 7885 ParamTypes[0] = 7886 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7887 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7888 /*IsAssigmentOperator=*/isEqualOp); 7889 } 7890 7891 if (!(*Ptr).isRestrictQualified() && 7892 VisibleTypeConversionsQuals.hasRestrict()) { 7893 // restrict version 7894 ParamTypes[0] 7895 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7896 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7897 /*IsAssigmentOperator=*/isEqualOp); 7898 7899 if (NeedVolatile) { 7900 // volatile restrict version 7901 ParamTypes[0] 7902 = S.Context.getLValueReferenceType( 7903 S.Context.getCVRQualifiedType(*Ptr, 7904 (Qualifiers::Volatile | 7905 Qualifiers::Restrict))); 7906 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7907 /*IsAssigmentOperator=*/isEqualOp); 7908 } 7909 } 7910 } 7911 7912 if (isEqualOp) { 7913 for (BuiltinCandidateTypeSet::iterator 7914 Ptr = CandidateTypes[1].pointer_begin(), 7915 PtrEnd = CandidateTypes[1].pointer_end(); 7916 Ptr != PtrEnd; ++Ptr) { 7917 // Make sure we don't add the same candidate twice. 7918 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7919 continue; 7920 7921 QualType ParamTypes[2] = { 7922 S.Context.getLValueReferenceType(*Ptr), 7923 *Ptr, 7924 }; 7925 7926 // non-volatile version 7927 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7928 /*IsAssigmentOperator=*/true); 7929 7930 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7931 VisibleTypeConversionsQuals.hasVolatile(); 7932 if (NeedVolatile) { 7933 // volatile version 7934 ParamTypes[0] = 7935 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7936 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7937 /*IsAssigmentOperator=*/true); 7938 } 7939 7940 if (!(*Ptr).isRestrictQualified() && 7941 VisibleTypeConversionsQuals.hasRestrict()) { 7942 // restrict version 7943 ParamTypes[0] 7944 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7945 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7946 /*IsAssigmentOperator=*/true); 7947 7948 if (NeedVolatile) { 7949 // volatile restrict version 7950 ParamTypes[0] 7951 = S.Context.getLValueReferenceType( 7952 S.Context.getCVRQualifiedType(*Ptr, 7953 (Qualifiers::Volatile | 7954 Qualifiers::Restrict))); 7955 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7956 /*IsAssigmentOperator=*/true); 7957 } 7958 } 7959 } 7960 } 7961 } 7962 7963 // C++ [over.built]p18: 7964 // 7965 // For every triple (L, VQ, R), where L is an arithmetic type, 7966 // VQ is either volatile or empty, and R is a promoted 7967 // arithmetic type, there exist candidate operator functions of 7968 // the form 7969 // 7970 // VQ L& operator=(VQ L&, R); 7971 // VQ L& operator*=(VQ L&, R); 7972 // VQ L& operator/=(VQ L&, R); 7973 // VQ L& operator+=(VQ L&, R); 7974 // VQ L& operator-=(VQ L&, R); 7975 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7976 if (!HasArithmeticOrEnumeralCandidateType) 7977 return; 7978 7979 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7980 for (unsigned Right = FirstPromotedArithmeticType; 7981 Right < LastPromotedArithmeticType; ++Right) { 7982 QualType ParamTypes[2]; 7983 ParamTypes[1] = getArithmeticType(Right); 7984 7985 // Add this built-in operator as a candidate (VQ is empty). 7986 ParamTypes[0] = 7987 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7988 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7989 /*IsAssigmentOperator=*/isEqualOp); 7990 7991 // Add this built-in operator as a candidate (VQ is 'volatile'). 7992 if (VisibleTypeConversionsQuals.hasVolatile()) { 7993 ParamTypes[0] = 7994 S.Context.getVolatileType(getArithmeticType(Left)); 7995 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7996 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7997 /*IsAssigmentOperator=*/isEqualOp); 7998 } 7999 } 8000 } 8001 8002 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8003 for (BuiltinCandidateTypeSet::iterator 8004 Vec1 = CandidateTypes[0].vector_begin(), 8005 Vec1End = CandidateTypes[0].vector_end(); 8006 Vec1 != Vec1End; ++Vec1) { 8007 for (BuiltinCandidateTypeSet::iterator 8008 Vec2 = CandidateTypes[1].vector_begin(), 8009 Vec2End = CandidateTypes[1].vector_end(); 8010 Vec2 != Vec2End; ++Vec2) { 8011 QualType ParamTypes[2]; 8012 ParamTypes[1] = *Vec2; 8013 // Add this built-in operator as a candidate (VQ is empty). 8014 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8015 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8016 /*IsAssigmentOperator=*/isEqualOp); 8017 8018 // Add this built-in operator as a candidate (VQ is 'volatile'). 8019 if (VisibleTypeConversionsQuals.hasVolatile()) { 8020 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8021 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8022 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8023 /*IsAssigmentOperator=*/isEqualOp); 8024 } 8025 } 8026 } 8027 } 8028 8029 // C++ [over.built]p22: 8030 // 8031 // For every triple (L, VQ, R), where L is an integral type, VQ 8032 // is either volatile or empty, and R is a promoted integral 8033 // type, there exist candidate operator functions of the form 8034 // 8035 // VQ L& operator%=(VQ L&, R); 8036 // VQ L& operator<<=(VQ L&, R); 8037 // VQ L& operator>>=(VQ L&, R); 8038 // VQ L& operator&=(VQ L&, R); 8039 // VQ L& operator^=(VQ L&, R); 8040 // VQ L& operator|=(VQ L&, R); 8041 void addAssignmentIntegralOverloads() { 8042 if (!HasArithmeticOrEnumeralCandidateType) 8043 return; 8044 8045 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8046 for (unsigned Right = FirstPromotedIntegralType; 8047 Right < LastPromotedIntegralType; ++Right) { 8048 QualType ParamTypes[2]; 8049 ParamTypes[1] = getArithmeticType(Right); 8050 8051 // Add this built-in operator as a candidate (VQ is empty). 8052 ParamTypes[0] = 8053 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8054 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8055 if (VisibleTypeConversionsQuals.hasVolatile()) { 8056 // Add this built-in operator as a candidate (VQ is 'volatile'). 8057 ParamTypes[0] = getArithmeticType(Left); 8058 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8059 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8060 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8061 } 8062 } 8063 } 8064 } 8065 8066 // C++ [over.operator]p23: 8067 // 8068 // There also exist candidate operator functions of the form 8069 // 8070 // bool operator!(bool); 8071 // bool operator&&(bool, bool); 8072 // bool operator||(bool, bool); 8073 void addExclaimOverload() { 8074 QualType ParamTy = S.Context.BoolTy; 8075 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 8076 /*IsAssignmentOperator=*/false, 8077 /*NumContextualBoolArguments=*/1); 8078 } 8079 void addAmpAmpOrPipePipeOverload() { 8080 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8081 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 8082 /*IsAssignmentOperator=*/false, 8083 /*NumContextualBoolArguments=*/2); 8084 } 8085 8086 // C++ [over.built]p13: 8087 // 8088 // For every cv-qualified or cv-unqualified object type T there 8089 // exist candidate operator functions of the form 8090 // 8091 // T* operator+(T*, ptrdiff_t); [ABOVE] 8092 // T& operator[](T*, ptrdiff_t); 8093 // T* operator-(T*, ptrdiff_t); [ABOVE] 8094 // T* operator+(ptrdiff_t, T*); [ABOVE] 8095 // T& operator[](ptrdiff_t, T*); 8096 void addSubscriptOverloads() { 8097 for (BuiltinCandidateTypeSet::iterator 8098 Ptr = CandidateTypes[0].pointer_begin(), 8099 PtrEnd = CandidateTypes[0].pointer_end(); 8100 Ptr != PtrEnd; ++Ptr) { 8101 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8102 QualType PointeeType = (*Ptr)->getPointeeType(); 8103 if (!PointeeType->isObjectType()) 8104 continue; 8105 8106 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8107 8108 // T& operator[](T*, ptrdiff_t) 8109 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8110 } 8111 8112 for (BuiltinCandidateTypeSet::iterator 8113 Ptr = CandidateTypes[1].pointer_begin(), 8114 PtrEnd = CandidateTypes[1].pointer_end(); 8115 Ptr != PtrEnd; ++Ptr) { 8116 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8117 QualType PointeeType = (*Ptr)->getPointeeType(); 8118 if (!PointeeType->isObjectType()) 8119 continue; 8120 8121 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8122 8123 // T& operator[](ptrdiff_t, T*) 8124 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8125 } 8126 } 8127 8128 // C++ [over.built]p11: 8129 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8130 // C1 is the same type as C2 or is a derived class of C2, T is an object 8131 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8132 // there exist candidate operator functions of the form 8133 // 8134 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8135 // 8136 // where CV12 is the union of CV1 and CV2. 8137 void addArrowStarOverloads() { 8138 for (BuiltinCandidateTypeSet::iterator 8139 Ptr = CandidateTypes[0].pointer_begin(), 8140 PtrEnd = CandidateTypes[0].pointer_end(); 8141 Ptr != PtrEnd; ++Ptr) { 8142 QualType C1Ty = (*Ptr); 8143 QualType C1; 8144 QualifierCollector Q1; 8145 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8146 if (!isa<RecordType>(C1)) 8147 continue; 8148 // heuristic to reduce number of builtin candidates in the set. 8149 // Add volatile/restrict version only if there are conversions to a 8150 // volatile/restrict type. 8151 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8152 continue; 8153 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8154 continue; 8155 for (BuiltinCandidateTypeSet::iterator 8156 MemPtr = CandidateTypes[1].member_pointer_begin(), 8157 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8158 MemPtr != MemPtrEnd; ++MemPtr) { 8159 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8160 QualType C2 = QualType(mptr->getClass(), 0); 8161 C2 = C2.getUnqualifiedType(); 8162 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8163 break; 8164 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8165 // build CV12 T& 8166 QualType T = mptr->getPointeeType(); 8167 if (!VisibleTypeConversionsQuals.hasVolatile() && 8168 T.isVolatileQualified()) 8169 continue; 8170 if (!VisibleTypeConversionsQuals.hasRestrict() && 8171 T.isRestrictQualified()) 8172 continue; 8173 T = Q1.apply(S.Context, T); 8174 QualType ResultTy = S.Context.getLValueReferenceType(T); 8175 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8176 } 8177 } 8178 } 8179 8180 // Note that we don't consider the first argument, since it has been 8181 // contextually converted to bool long ago. The candidates below are 8182 // therefore added as binary. 8183 // 8184 // C++ [over.built]p25: 8185 // For every type T, where T is a pointer, pointer-to-member, or scoped 8186 // enumeration type, there exist candidate operator functions of the form 8187 // 8188 // T operator?(bool, T, T); 8189 // 8190 void addConditionalOperatorOverloads() { 8191 /// Set of (canonical) types that we've already handled. 8192 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8193 8194 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8195 for (BuiltinCandidateTypeSet::iterator 8196 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8197 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8198 Ptr != PtrEnd; ++Ptr) { 8199 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8200 continue; 8201 8202 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8203 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 8204 } 8205 8206 for (BuiltinCandidateTypeSet::iterator 8207 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8208 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8209 MemPtr != MemPtrEnd; ++MemPtr) { 8210 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8211 continue; 8212 8213 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8214 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 8215 } 8216 8217 if (S.getLangOpts().CPlusPlus11) { 8218 for (BuiltinCandidateTypeSet::iterator 8219 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8220 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8221 Enum != EnumEnd; ++Enum) { 8222 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8223 continue; 8224 8225 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8226 continue; 8227 8228 QualType ParamTypes[2] = { *Enum, *Enum }; 8229 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 8230 } 8231 } 8232 } 8233 } 8234 }; 8235 8236 } // end anonymous namespace 8237 8238 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8239 /// operator overloads to the candidate set (C++ [over.built]), based 8240 /// on the operator @p Op and the arguments given. For example, if the 8241 /// operator is a binary '+', this routine might add "int 8242 /// operator+(int, int)" to cover integer addition. 8243 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8244 SourceLocation OpLoc, 8245 ArrayRef<Expr *> Args, 8246 OverloadCandidateSet &CandidateSet) { 8247 // Find all of the types that the arguments can convert to, but only 8248 // if the operator we're looking at has built-in operator candidates 8249 // that make use of these types. Also record whether we encounter non-record 8250 // candidate types or either arithmetic or enumeral candidate types. 8251 Qualifiers VisibleTypeConversionsQuals; 8252 VisibleTypeConversionsQuals.addConst(); 8253 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8254 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8255 8256 bool HasNonRecordCandidateType = false; 8257 bool HasArithmeticOrEnumeralCandidateType = false; 8258 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8259 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8260 CandidateTypes.emplace_back(*this); 8261 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8262 OpLoc, 8263 true, 8264 (Op == OO_Exclaim || 8265 Op == OO_AmpAmp || 8266 Op == OO_PipePipe), 8267 VisibleTypeConversionsQuals); 8268 HasNonRecordCandidateType = HasNonRecordCandidateType || 8269 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8270 HasArithmeticOrEnumeralCandidateType = 8271 HasArithmeticOrEnumeralCandidateType || 8272 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8273 } 8274 8275 // Exit early when no non-record types have been added to the candidate set 8276 // for any of the arguments to the operator. 8277 // 8278 // We can't exit early for !, ||, or &&, since there we have always have 8279 // 'bool' overloads. 8280 if (!HasNonRecordCandidateType && 8281 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8282 return; 8283 8284 // Setup an object to manage the common state for building overloads. 8285 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8286 VisibleTypeConversionsQuals, 8287 HasArithmeticOrEnumeralCandidateType, 8288 CandidateTypes, CandidateSet); 8289 8290 // Dispatch over the operation to add in only those overloads which apply. 8291 switch (Op) { 8292 case OO_None: 8293 case NUM_OVERLOADED_OPERATORS: 8294 llvm_unreachable("Expected an overloaded operator"); 8295 8296 case OO_New: 8297 case OO_Delete: 8298 case OO_Array_New: 8299 case OO_Array_Delete: 8300 case OO_Call: 8301 llvm_unreachable( 8302 "Special operators don't use AddBuiltinOperatorCandidates"); 8303 8304 case OO_Comma: 8305 case OO_Arrow: 8306 case OO_Coawait: 8307 // C++ [over.match.oper]p3: 8308 // -- For the operator ',', the unary operator '&', the 8309 // operator '->', or the operator 'co_await', the 8310 // built-in candidates set is empty. 8311 break; 8312 8313 case OO_Plus: // '+' is either unary or binary 8314 if (Args.size() == 1) 8315 OpBuilder.addUnaryPlusPointerOverloads(); 8316 // Fall through. 8317 8318 case OO_Minus: // '-' is either unary or binary 8319 if (Args.size() == 1) { 8320 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8321 } else { 8322 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8323 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8324 } 8325 break; 8326 8327 case OO_Star: // '*' is either unary or binary 8328 if (Args.size() == 1) 8329 OpBuilder.addUnaryStarPointerOverloads(); 8330 else 8331 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8332 break; 8333 8334 case OO_Slash: 8335 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8336 break; 8337 8338 case OO_PlusPlus: 8339 case OO_MinusMinus: 8340 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8341 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8342 break; 8343 8344 case OO_EqualEqual: 8345 case OO_ExclaimEqual: 8346 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 8347 // Fall through. 8348 8349 case OO_Less: 8350 case OO_Greater: 8351 case OO_LessEqual: 8352 case OO_GreaterEqual: 8353 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8354 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8355 break; 8356 8357 case OO_Percent: 8358 case OO_Caret: 8359 case OO_Pipe: 8360 case OO_LessLess: 8361 case OO_GreaterGreater: 8362 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8363 break; 8364 8365 case OO_Amp: // '&' is either unary or binary 8366 if (Args.size() == 1) 8367 // C++ [over.match.oper]p3: 8368 // -- For the operator ',', the unary operator '&', or the 8369 // operator '->', the built-in candidates set is empty. 8370 break; 8371 8372 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8373 break; 8374 8375 case OO_Tilde: 8376 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8377 break; 8378 8379 case OO_Equal: 8380 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8381 // Fall through. 8382 8383 case OO_PlusEqual: 8384 case OO_MinusEqual: 8385 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8386 // Fall through. 8387 8388 case OO_StarEqual: 8389 case OO_SlashEqual: 8390 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8391 break; 8392 8393 case OO_PercentEqual: 8394 case OO_LessLessEqual: 8395 case OO_GreaterGreaterEqual: 8396 case OO_AmpEqual: 8397 case OO_CaretEqual: 8398 case OO_PipeEqual: 8399 OpBuilder.addAssignmentIntegralOverloads(); 8400 break; 8401 8402 case OO_Exclaim: 8403 OpBuilder.addExclaimOverload(); 8404 break; 8405 8406 case OO_AmpAmp: 8407 case OO_PipePipe: 8408 OpBuilder.addAmpAmpOrPipePipeOverload(); 8409 break; 8410 8411 case OO_Subscript: 8412 OpBuilder.addSubscriptOverloads(); 8413 break; 8414 8415 case OO_ArrowStar: 8416 OpBuilder.addArrowStarOverloads(); 8417 break; 8418 8419 case OO_Conditional: 8420 OpBuilder.addConditionalOperatorOverloads(); 8421 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8422 break; 8423 } 8424 } 8425 8426 /// \brief Add function candidates found via argument-dependent lookup 8427 /// to the set of overloading candidates. 8428 /// 8429 /// This routine performs argument-dependent name lookup based on the 8430 /// given function name (which may also be an operator name) and adds 8431 /// all of the overload candidates found by ADL to the overload 8432 /// candidate set (C++ [basic.lookup.argdep]). 8433 void 8434 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8435 SourceLocation Loc, 8436 ArrayRef<Expr *> Args, 8437 TemplateArgumentListInfo *ExplicitTemplateArgs, 8438 OverloadCandidateSet& CandidateSet, 8439 bool PartialOverloading) { 8440 ADLResult Fns; 8441 8442 // FIXME: This approach for uniquing ADL results (and removing 8443 // redundant candidates from the set) relies on pointer-equality, 8444 // which means we need to key off the canonical decl. However, 8445 // always going back to the canonical decl might not get us the 8446 // right set of default arguments. What default arguments are 8447 // we supposed to consider on ADL candidates, anyway? 8448 8449 // FIXME: Pass in the explicit template arguments? 8450 ArgumentDependentLookup(Name, Loc, Args, Fns); 8451 8452 // Erase all of the candidates we already knew about. 8453 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8454 CandEnd = CandidateSet.end(); 8455 Cand != CandEnd; ++Cand) 8456 if (Cand->Function) { 8457 Fns.erase(Cand->Function); 8458 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8459 Fns.erase(FunTmpl); 8460 } 8461 8462 // For each of the ADL candidates we found, add it to the overload 8463 // set. 8464 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8465 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8466 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8467 if (ExplicitTemplateArgs) 8468 continue; 8469 8470 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8471 PartialOverloading); 8472 } else 8473 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8474 FoundDecl, ExplicitTemplateArgs, 8475 Args, CandidateSet, PartialOverloading); 8476 } 8477 } 8478 8479 // Determines whether Cand1 is "better" in terms of its enable_if attrs than 8480 // Cand2 for overloading. This function assumes that all of the enable_if attrs 8481 // on Cand1 and Cand2 have conditions that evaluate to true. 8482 // 8483 // Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 8484 // Cand1's first N enable_if attributes have precisely the same conditions as 8485 // Cand2's first N enable_if attributes (where N = the number of enable_if 8486 // attributes on Cand2), and Cand1 has more than N enable_if attributes. 8487 static bool hasBetterEnableIfAttrs(Sema &S, const FunctionDecl *Cand1, 8488 const FunctionDecl *Cand2) { 8489 8490 // FIXME: The next several lines are just 8491 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8492 // instead of reverse order which is how they're stored in the AST. 8493 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1); 8494 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2); 8495 8496 // Candidate 1 is better if it has strictly more attributes and 8497 // the common sequence is identical. 8498 if (Cand1Attrs.size() <= Cand2Attrs.size()) 8499 return false; 8500 8501 auto Cand1I = Cand1Attrs.begin(); 8502 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8503 for (auto &Cand2A : Cand2Attrs) { 8504 Cand1ID.clear(); 8505 Cand2ID.clear(); 8506 8507 auto &Cand1A = *Cand1I++; 8508 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true); 8509 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true); 8510 if (Cand1ID != Cand2ID) 8511 return false; 8512 } 8513 8514 return true; 8515 } 8516 8517 /// isBetterOverloadCandidate - Determines whether the first overload 8518 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8519 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, 8520 const OverloadCandidate &Cand2, 8521 SourceLocation Loc, 8522 bool UserDefinedConversion) { 8523 // Define viable functions to be better candidates than non-viable 8524 // functions. 8525 if (!Cand2.Viable) 8526 return Cand1.Viable; 8527 else if (!Cand1.Viable) 8528 return false; 8529 8530 // C++ [over.match.best]p1: 8531 // 8532 // -- if F is a static member function, ICS1(F) is defined such 8533 // that ICS1(F) is neither better nor worse than ICS1(G) for 8534 // any function G, and, symmetrically, ICS1(G) is neither 8535 // better nor worse than ICS1(F). 8536 unsigned StartArg = 0; 8537 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8538 StartArg = 1; 8539 8540 // C++ [over.match.best]p1: 8541 // A viable function F1 is defined to be a better function than another 8542 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8543 // conversion sequence than ICSi(F2), and then... 8544 unsigned NumArgs = Cand1.NumConversions; 8545 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8546 bool HasBetterConversion = false; 8547 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8548 switch (CompareImplicitConversionSequences(S, Loc, 8549 Cand1.Conversions[ArgIdx], 8550 Cand2.Conversions[ArgIdx])) { 8551 case ImplicitConversionSequence::Better: 8552 // Cand1 has a better conversion sequence. 8553 HasBetterConversion = true; 8554 break; 8555 8556 case ImplicitConversionSequence::Worse: 8557 // Cand1 can't be better than Cand2. 8558 return false; 8559 8560 case ImplicitConversionSequence::Indistinguishable: 8561 // Do nothing. 8562 break; 8563 } 8564 } 8565 8566 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8567 // ICSj(F2), or, if not that, 8568 if (HasBetterConversion) 8569 return true; 8570 8571 // -- the context is an initialization by user-defined conversion 8572 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8573 // from the return type of F1 to the destination type (i.e., 8574 // the type of the entity being initialized) is a better 8575 // conversion sequence than the standard conversion sequence 8576 // from the return type of F2 to the destination type. 8577 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8578 isa<CXXConversionDecl>(Cand1.Function) && 8579 isa<CXXConversionDecl>(Cand2.Function)) { 8580 // First check whether we prefer one of the conversion functions over the 8581 // other. This only distinguishes the results in non-standard, extension 8582 // cases such as the conversion from a lambda closure type to a function 8583 // pointer or block. 8584 ImplicitConversionSequence::CompareKind Result = 8585 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8586 if (Result == ImplicitConversionSequence::Indistinguishable) 8587 Result = CompareStandardConversionSequences(S, Loc, 8588 Cand1.FinalConversion, 8589 Cand2.FinalConversion); 8590 8591 if (Result != ImplicitConversionSequence::Indistinguishable) 8592 return Result == ImplicitConversionSequence::Better; 8593 8594 // FIXME: Compare kind of reference binding if conversion functions 8595 // convert to a reference type used in direct reference binding, per 8596 // C++14 [over.match.best]p1 section 2 bullet 3. 8597 } 8598 8599 // -- F1 is a non-template function and F2 is a function template 8600 // specialization, or, if not that, 8601 bool Cand1IsSpecialization = Cand1.Function && 8602 Cand1.Function->getPrimaryTemplate(); 8603 bool Cand2IsSpecialization = Cand2.Function && 8604 Cand2.Function->getPrimaryTemplate(); 8605 if (Cand1IsSpecialization != Cand2IsSpecialization) 8606 return Cand2IsSpecialization; 8607 8608 // -- F1 and F2 are function template specializations, and the function 8609 // template for F1 is more specialized than the template for F2 8610 // according to the partial ordering rules described in 14.5.5.2, or, 8611 // if not that, 8612 if (Cand1IsSpecialization && Cand2IsSpecialization) { 8613 if (FunctionTemplateDecl *BetterTemplate 8614 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8615 Cand2.Function->getPrimaryTemplate(), 8616 Loc, 8617 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8618 : TPOC_Call, 8619 Cand1.ExplicitCallArguments, 8620 Cand2.ExplicitCallArguments)) 8621 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8622 } 8623 8624 // Check for enable_if value-based overload resolution. 8625 if (Cand1.Function && Cand2.Function && 8626 (Cand1.Function->hasAttr<EnableIfAttr>() || 8627 Cand2.Function->hasAttr<EnableIfAttr>())) 8628 return hasBetterEnableIfAttrs(S, Cand1.Function, Cand2.Function); 8629 8630 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads && 8631 Cand1.Function && Cand2.Function) { 8632 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8633 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 8634 S.IdentifyCUDAPreference(Caller, Cand2.Function); 8635 } 8636 8637 bool HasPS1 = Cand1.Function != nullptr && 8638 functionHasPassObjectSizeParams(Cand1.Function); 8639 bool HasPS2 = Cand2.Function != nullptr && 8640 functionHasPassObjectSizeParams(Cand2.Function); 8641 return HasPS1 != HasPS2 && HasPS1; 8642 } 8643 8644 /// Determine whether two declarations are "equivalent" for the purposes of 8645 /// name lookup and overload resolution. This applies when the same internal/no 8646 /// linkage entity is defined by two modules (probably by textually including 8647 /// the same header). In such a case, we don't consider the declarations to 8648 /// declare the same entity, but we also don't want lookups with both 8649 /// declarations visible to be ambiguous in some cases (this happens when using 8650 /// a modularized libstdc++). 8651 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 8652 const NamedDecl *B) { 8653 auto *VA = dyn_cast_or_null<ValueDecl>(A); 8654 auto *VB = dyn_cast_or_null<ValueDecl>(B); 8655 if (!VA || !VB) 8656 return false; 8657 8658 // The declarations must be declaring the same name as an internal linkage 8659 // entity in different modules. 8660 if (!VA->getDeclContext()->getRedeclContext()->Equals( 8661 VB->getDeclContext()->getRedeclContext()) || 8662 getOwningModule(const_cast<ValueDecl *>(VA)) == 8663 getOwningModule(const_cast<ValueDecl *>(VB)) || 8664 VA->isExternallyVisible() || VB->isExternallyVisible()) 8665 return false; 8666 8667 // Check that the declarations appear to be equivalent. 8668 // 8669 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 8670 // For constants and functions, we should check the initializer or body is 8671 // the same. For non-constant variables, we shouldn't allow it at all. 8672 if (Context.hasSameType(VA->getType(), VB->getType())) 8673 return true; 8674 8675 // Enum constants within unnamed enumerations will have different types, but 8676 // may still be similar enough to be interchangeable for our purposes. 8677 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 8678 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 8679 // Only handle anonymous enums. If the enumerations were named and 8680 // equivalent, they would have been merged to the same type. 8681 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 8682 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 8683 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 8684 !Context.hasSameType(EnumA->getIntegerType(), 8685 EnumB->getIntegerType())) 8686 return false; 8687 // Allow this only if the value is the same for both enumerators. 8688 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 8689 } 8690 } 8691 8692 // Nothing else is sufficiently similar. 8693 return false; 8694 } 8695 8696 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 8697 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 8698 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 8699 8700 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 8701 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 8702 << !M << (M ? M->getFullModuleName() : ""); 8703 8704 for (auto *E : Equiv) { 8705 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 8706 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 8707 << !M << (M ? M->getFullModuleName() : ""); 8708 } 8709 } 8710 8711 /// \brief Computes the best viable function (C++ 13.3.3) 8712 /// within an overload candidate set. 8713 /// 8714 /// \param Loc The location of the function name (or operator symbol) for 8715 /// which overload resolution occurs. 8716 /// 8717 /// \param Best If overload resolution was successful or found a deleted 8718 /// function, \p Best points to the candidate function found. 8719 /// 8720 /// \returns The result of overload resolution. 8721 OverloadingResult 8722 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8723 iterator &Best, 8724 bool UserDefinedConversion) { 8725 // Find the best viable function. 8726 Best = end(); 8727 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8728 if (Cand->Viable) 8729 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8730 UserDefinedConversion)) 8731 Best = Cand; 8732 } 8733 8734 // If we didn't find any viable functions, abort. 8735 if (Best == end()) 8736 return OR_No_Viable_Function; 8737 8738 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 8739 8740 // Make sure that this function is better than every other viable 8741 // function. If not, we have an ambiguity. 8742 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8743 if (Cand->Viable && 8744 Cand != Best && 8745 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8746 UserDefinedConversion)) { 8747 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 8748 Cand->Function)) { 8749 EquivalentCands.push_back(Cand->Function); 8750 continue; 8751 } 8752 8753 Best = end(); 8754 return OR_Ambiguous; 8755 } 8756 } 8757 8758 // Best is the best viable function. 8759 if (Best->Function && 8760 (Best->Function->isDeleted() || 8761 S.isFunctionConsideredUnavailable(Best->Function))) 8762 return OR_Deleted; 8763 8764 if (!EquivalentCands.empty()) 8765 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 8766 EquivalentCands); 8767 8768 return OR_Success; 8769 } 8770 8771 namespace { 8772 8773 enum OverloadCandidateKind { 8774 oc_function, 8775 oc_method, 8776 oc_constructor, 8777 oc_function_template, 8778 oc_method_template, 8779 oc_constructor_template, 8780 oc_implicit_default_constructor, 8781 oc_implicit_copy_constructor, 8782 oc_implicit_move_constructor, 8783 oc_implicit_copy_assignment, 8784 oc_implicit_move_assignment, 8785 oc_implicit_inherited_constructor 8786 }; 8787 8788 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8789 FunctionDecl *Fn, 8790 std::string &Description) { 8791 bool isTemplate = false; 8792 8793 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8794 isTemplate = true; 8795 Description = S.getTemplateArgumentBindingsText( 8796 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8797 } 8798 8799 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8800 if (!Ctor->isImplicit()) 8801 return isTemplate ? oc_constructor_template : oc_constructor; 8802 8803 if (Ctor->getInheritedConstructor()) 8804 return oc_implicit_inherited_constructor; 8805 8806 if (Ctor->isDefaultConstructor()) 8807 return oc_implicit_default_constructor; 8808 8809 if (Ctor->isMoveConstructor()) 8810 return oc_implicit_move_constructor; 8811 8812 assert(Ctor->isCopyConstructor() && 8813 "unexpected sort of implicit constructor"); 8814 return oc_implicit_copy_constructor; 8815 } 8816 8817 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8818 // This actually gets spelled 'candidate function' for now, but 8819 // it doesn't hurt to split it out. 8820 if (!Meth->isImplicit()) 8821 return isTemplate ? oc_method_template : oc_method; 8822 8823 if (Meth->isMoveAssignmentOperator()) 8824 return oc_implicit_move_assignment; 8825 8826 if (Meth->isCopyAssignmentOperator()) 8827 return oc_implicit_copy_assignment; 8828 8829 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8830 return oc_method; 8831 } 8832 8833 return isTemplate ? oc_function_template : oc_function; 8834 } 8835 8836 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) { 8837 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8838 if (!Ctor) return; 8839 8840 Ctor = Ctor->getInheritedConstructor(); 8841 if (!Ctor) return; 8842 8843 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8844 } 8845 8846 } // end anonymous namespace 8847 8848 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 8849 const FunctionDecl *FD) { 8850 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 8851 bool AlwaysTrue; 8852 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 8853 return false; 8854 if (!AlwaysTrue) 8855 return false; 8856 } 8857 return true; 8858 } 8859 8860 /// \brief Returns true if we can take the address of the function. 8861 /// 8862 /// \param Complain - If true, we'll emit a diagnostic 8863 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 8864 /// we in overload resolution? 8865 /// \param Loc - The location of the statement we're complaining about. Ignored 8866 /// if we're not complaining, or if we're in overload resolution. 8867 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 8868 bool Complain, 8869 bool InOverloadResolution, 8870 SourceLocation Loc) { 8871 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 8872 if (Complain) { 8873 if (InOverloadResolution) 8874 S.Diag(FD->getLocStart(), 8875 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 8876 else 8877 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 8878 } 8879 return false; 8880 } 8881 8882 auto I = std::find_if(FD->param_begin(), FD->param_end(), 8883 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>)); 8884 if (I == FD->param_end()) 8885 return true; 8886 8887 if (Complain) { 8888 // Add one to ParamNo because it's user-facing 8889 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 8890 if (InOverloadResolution) 8891 S.Diag(FD->getLocation(), 8892 diag::note_ovl_candidate_has_pass_object_size_params) 8893 << ParamNo; 8894 else 8895 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 8896 << FD << ParamNo; 8897 } 8898 return false; 8899 } 8900 8901 static bool checkAddressOfCandidateIsAvailable(Sema &S, 8902 const FunctionDecl *FD) { 8903 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 8904 /*InOverloadResolution=*/true, 8905 /*Loc=*/SourceLocation()); 8906 } 8907 8908 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 8909 bool Complain, 8910 SourceLocation Loc) { 8911 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 8912 /*InOverloadResolution=*/false, 8913 Loc); 8914 } 8915 8916 // Notes the location of an overload candidate. 8917 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType, 8918 bool TakingAddress) { 8919 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 8920 return; 8921 8922 std::string FnDesc; 8923 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8924 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8925 << (unsigned) K << FnDesc; 8926 8927 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8928 Diag(Fn->getLocation(), PD); 8929 MaybeEmitInheritedConstructorNote(*this, Fn); 8930 } 8931 8932 // Notes the location of all overload candidates designated through 8933 // OverloadedExpr 8934 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 8935 bool TakingAddress) { 8936 assert(OverloadedExpr->getType() == Context.OverloadTy); 8937 8938 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8939 OverloadExpr *OvlExpr = Ovl.Expression; 8940 8941 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8942 IEnd = OvlExpr->decls_end(); 8943 I != IEnd; ++I) { 8944 if (FunctionTemplateDecl *FunTmpl = 8945 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8946 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType, 8947 TakingAddress); 8948 } else if (FunctionDecl *Fun 8949 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8950 NoteOverloadCandidate(Fun, DestType, TakingAddress); 8951 } 8952 } 8953 } 8954 8955 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 8956 /// "lead" diagnostic; it will be given two arguments, the source and 8957 /// target types of the conversion. 8958 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8959 Sema &S, 8960 SourceLocation CaretLoc, 8961 const PartialDiagnostic &PDiag) const { 8962 S.Diag(CaretLoc, PDiag) 8963 << Ambiguous.getFromType() << Ambiguous.getToType(); 8964 // FIXME: The note limiting machinery is borrowed from 8965 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8966 // refactoring here. 8967 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8968 unsigned CandsShown = 0; 8969 AmbiguousConversionSequence::const_iterator I, E; 8970 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8971 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8972 break; 8973 ++CandsShown; 8974 S.NoteOverloadCandidate(*I); 8975 } 8976 if (I != E) 8977 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8978 } 8979 8980 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 8981 unsigned I, bool TakingCandidateAddress) { 8982 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8983 assert(Conv.isBad()); 8984 assert(Cand->Function && "for now, candidate must be a function"); 8985 FunctionDecl *Fn = Cand->Function; 8986 8987 // There's a conversion slot for the object argument if this is a 8988 // non-constructor method. Note that 'I' corresponds the 8989 // conversion-slot index. 8990 bool isObjectArgument = false; 8991 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8992 if (I == 0) 8993 isObjectArgument = true; 8994 else 8995 I--; 8996 } 8997 8998 std::string FnDesc; 8999 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 9000 9001 Expr *FromExpr = Conv.Bad.FromExpr; 9002 QualType FromTy = Conv.Bad.getFromType(); 9003 QualType ToTy = Conv.Bad.getToType(); 9004 9005 if (FromTy == S.Context.OverloadTy) { 9006 assert(FromExpr && "overload set argument came from implicit argument?"); 9007 Expr *E = FromExpr->IgnoreParens(); 9008 if (isa<UnaryOperator>(E)) 9009 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9010 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9011 9012 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9013 << (unsigned) FnKind << FnDesc 9014 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9015 << ToTy << Name << I+1; 9016 MaybeEmitInheritedConstructorNote(S, Fn); 9017 return; 9018 } 9019 9020 // Do some hand-waving analysis to see if the non-viability is due 9021 // to a qualifier mismatch. 9022 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9023 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9024 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9025 CToTy = RT->getPointeeType(); 9026 else { 9027 // TODO: detect and diagnose the full richness of const mismatches. 9028 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9029 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 9030 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 9031 } 9032 9033 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9034 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9035 Qualifiers FromQs = CFromTy.getQualifiers(); 9036 Qualifiers ToQs = CToTy.getQualifiers(); 9037 9038 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9039 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9040 << (unsigned) FnKind << FnDesc 9041 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9042 << FromTy 9043 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 9044 << (unsigned) isObjectArgument << I+1; 9045 MaybeEmitInheritedConstructorNote(S, Fn); 9046 return; 9047 } 9048 9049 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9050 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9051 << (unsigned) FnKind << FnDesc 9052 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9053 << FromTy 9054 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9055 << (unsigned) isObjectArgument << I+1; 9056 MaybeEmitInheritedConstructorNote(S, Fn); 9057 return; 9058 } 9059 9060 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9061 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9062 << (unsigned) FnKind << FnDesc 9063 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9064 << FromTy 9065 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9066 << (unsigned) isObjectArgument << I+1; 9067 MaybeEmitInheritedConstructorNote(S, Fn); 9068 return; 9069 } 9070 9071 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9072 assert(CVR && "unexpected qualifiers mismatch"); 9073 9074 if (isObjectArgument) { 9075 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9076 << (unsigned) FnKind << FnDesc 9077 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9078 << FromTy << (CVR - 1); 9079 } else { 9080 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9081 << (unsigned) FnKind << FnDesc 9082 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9083 << FromTy << (CVR - 1) << I+1; 9084 } 9085 MaybeEmitInheritedConstructorNote(S, Fn); 9086 return; 9087 } 9088 9089 // Special diagnostic for failure to convert an initializer list, since 9090 // telling the user that it has type void is not useful. 9091 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9092 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9093 << (unsigned) FnKind << FnDesc 9094 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9095 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9096 MaybeEmitInheritedConstructorNote(S, Fn); 9097 return; 9098 } 9099 9100 // Diagnose references or pointers to incomplete types differently, 9101 // since it's far from impossible that the incompleteness triggered 9102 // the failure. 9103 QualType TempFromTy = FromTy.getNonReferenceType(); 9104 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9105 TempFromTy = PTy->getPointeeType(); 9106 if (TempFromTy->isIncompleteType()) { 9107 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9108 << (unsigned) FnKind << FnDesc 9109 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9110 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9111 MaybeEmitInheritedConstructorNote(S, Fn); 9112 return; 9113 } 9114 9115 // Diagnose base -> derived pointer conversions. 9116 unsigned BaseToDerivedConversion = 0; 9117 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9118 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9119 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9120 FromPtrTy->getPointeeType()) && 9121 !FromPtrTy->getPointeeType()->isIncompleteType() && 9122 !ToPtrTy->getPointeeType()->isIncompleteType() && 9123 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9124 FromPtrTy->getPointeeType())) 9125 BaseToDerivedConversion = 1; 9126 } 9127 } else if (const ObjCObjectPointerType *FromPtrTy 9128 = FromTy->getAs<ObjCObjectPointerType>()) { 9129 if (const ObjCObjectPointerType *ToPtrTy 9130 = ToTy->getAs<ObjCObjectPointerType>()) 9131 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9132 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9133 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9134 FromPtrTy->getPointeeType()) && 9135 FromIface->isSuperClassOf(ToIface)) 9136 BaseToDerivedConversion = 2; 9137 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9138 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9139 !FromTy->isIncompleteType() && 9140 !ToRefTy->getPointeeType()->isIncompleteType() && 9141 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9142 BaseToDerivedConversion = 3; 9143 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9144 ToTy.getNonReferenceType().getCanonicalType() == 9145 FromTy.getNonReferenceType().getCanonicalType()) { 9146 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9147 << (unsigned) FnKind << FnDesc 9148 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9149 << (unsigned) isObjectArgument << I + 1; 9150 MaybeEmitInheritedConstructorNote(S, Fn); 9151 return; 9152 } 9153 } 9154 9155 if (BaseToDerivedConversion) { 9156 S.Diag(Fn->getLocation(), 9157 diag::note_ovl_candidate_bad_base_to_derived_conv) 9158 << (unsigned) FnKind << FnDesc 9159 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9160 << (BaseToDerivedConversion - 1) 9161 << FromTy << ToTy << I+1; 9162 MaybeEmitInheritedConstructorNote(S, Fn); 9163 return; 9164 } 9165 9166 if (isa<ObjCObjectPointerType>(CFromTy) && 9167 isa<PointerType>(CToTy)) { 9168 Qualifiers FromQs = CFromTy.getQualifiers(); 9169 Qualifiers ToQs = CToTy.getQualifiers(); 9170 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9171 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9172 << (unsigned) FnKind << FnDesc 9173 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9174 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9175 MaybeEmitInheritedConstructorNote(S, Fn); 9176 return; 9177 } 9178 } 9179 9180 if (TakingCandidateAddress && 9181 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9182 return; 9183 9184 // Emit the generic diagnostic and, optionally, add the hints to it. 9185 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9186 FDiag << (unsigned) FnKind << FnDesc 9187 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9188 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 9189 << (unsigned) (Cand->Fix.Kind); 9190 9191 // If we can fix the conversion, suggest the FixIts. 9192 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9193 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9194 FDiag << *HI; 9195 S.Diag(Fn->getLocation(), FDiag); 9196 9197 MaybeEmitInheritedConstructorNote(S, Fn); 9198 } 9199 9200 /// Additional arity mismatch diagnosis specific to a function overload 9201 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9202 /// over a candidate in any candidate set. 9203 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9204 unsigned NumArgs) { 9205 FunctionDecl *Fn = Cand->Function; 9206 unsigned MinParams = Fn->getMinRequiredArguments(); 9207 9208 // With invalid overloaded operators, it's possible that we think we 9209 // have an arity mismatch when in fact it looks like we have the 9210 // right number of arguments, because only overloaded operators have 9211 // the weird behavior of overloading member and non-member functions. 9212 // Just don't report anything. 9213 if (Fn->isInvalidDecl() && 9214 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9215 return true; 9216 9217 if (NumArgs < MinParams) { 9218 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9219 (Cand->FailureKind == ovl_fail_bad_deduction && 9220 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9221 } else { 9222 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9223 (Cand->FailureKind == ovl_fail_bad_deduction && 9224 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9225 } 9226 9227 return false; 9228 } 9229 9230 /// General arity mismatch diagnosis over a candidate in a candidate set. 9231 static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) { 9232 assert(isa<FunctionDecl>(D) && 9233 "The templated declaration should at least be a function" 9234 " when diagnosing bad template argument deduction due to too many" 9235 " or too few arguments"); 9236 9237 FunctionDecl *Fn = cast<FunctionDecl>(D); 9238 9239 // TODO: treat calls to a missing default constructor as a special case 9240 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9241 unsigned MinParams = Fn->getMinRequiredArguments(); 9242 9243 // at least / at most / exactly 9244 unsigned mode, modeCount; 9245 if (NumFormalArgs < MinParams) { 9246 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9247 FnTy->isTemplateVariadic()) 9248 mode = 0; // "at least" 9249 else 9250 mode = 2; // "exactly" 9251 modeCount = MinParams; 9252 } else { 9253 if (MinParams != FnTy->getNumParams()) 9254 mode = 1; // "at most" 9255 else 9256 mode = 2; // "exactly" 9257 modeCount = FnTy->getNumParams(); 9258 } 9259 9260 std::string Description; 9261 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 9262 9263 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9264 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9265 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9266 << mode << Fn->getParamDecl(0) << NumFormalArgs; 9267 else 9268 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9269 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9270 << mode << modeCount << NumFormalArgs; 9271 MaybeEmitInheritedConstructorNote(S, Fn); 9272 } 9273 9274 /// Arity mismatch diagnosis specific to a function overload candidate. 9275 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9276 unsigned NumFormalArgs) { 9277 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9278 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs); 9279 } 9280 9281 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9282 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated)) 9283 return FD->getDescribedFunctionTemplate(); 9284 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated)) 9285 return RD->getDescribedClassTemplate(); 9286 9287 llvm_unreachable("Unsupported: Getting the described template declaration" 9288 " for bad deduction diagnosis"); 9289 } 9290 9291 /// Diagnose a failed template-argument deduction. 9292 static void DiagnoseBadDeduction(Sema &S, Decl *Templated, 9293 DeductionFailureInfo &DeductionFailure, 9294 unsigned NumArgs, 9295 bool TakingCandidateAddress) { 9296 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9297 NamedDecl *ParamD; 9298 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9299 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9300 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9301 switch (DeductionFailure.Result) { 9302 case Sema::TDK_Success: 9303 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9304 9305 case Sema::TDK_Incomplete: { 9306 assert(ParamD && "no parameter found for incomplete deduction result"); 9307 S.Diag(Templated->getLocation(), 9308 diag::note_ovl_candidate_incomplete_deduction) 9309 << ParamD->getDeclName(); 9310 MaybeEmitInheritedConstructorNote(S, Templated); 9311 return; 9312 } 9313 9314 case Sema::TDK_Underqualified: { 9315 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9316 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9317 9318 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9319 9320 // Param will have been canonicalized, but it should just be a 9321 // qualified version of ParamD, so move the qualifiers to that. 9322 QualifierCollector Qs; 9323 Qs.strip(Param); 9324 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9325 assert(S.Context.hasSameType(Param, NonCanonParam)); 9326 9327 // Arg has also been canonicalized, but there's nothing we can do 9328 // about that. It also doesn't matter as much, because it won't 9329 // have any template parameters in it (because deduction isn't 9330 // done on dependent types). 9331 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9332 9333 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9334 << ParamD->getDeclName() << Arg << NonCanonParam; 9335 MaybeEmitInheritedConstructorNote(S, Templated); 9336 return; 9337 } 9338 9339 case Sema::TDK_Inconsistent: { 9340 assert(ParamD && "no parameter found for inconsistent deduction result"); 9341 int which = 0; 9342 if (isa<TemplateTypeParmDecl>(ParamD)) 9343 which = 0; 9344 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 9345 which = 1; 9346 else { 9347 which = 2; 9348 } 9349 9350 S.Diag(Templated->getLocation(), 9351 diag::note_ovl_candidate_inconsistent_deduction) 9352 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 9353 << *DeductionFailure.getSecondArg(); 9354 MaybeEmitInheritedConstructorNote(S, Templated); 9355 return; 9356 } 9357 9358 case Sema::TDK_InvalidExplicitArguments: 9359 assert(ParamD && "no parameter found for invalid explicit arguments"); 9360 if (ParamD->getDeclName()) 9361 S.Diag(Templated->getLocation(), 9362 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9363 << ParamD->getDeclName(); 9364 else { 9365 int index = 0; 9366 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9367 index = TTP->getIndex(); 9368 else if (NonTypeTemplateParmDecl *NTTP 9369 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9370 index = NTTP->getIndex(); 9371 else 9372 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9373 S.Diag(Templated->getLocation(), 9374 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9375 << (index + 1); 9376 } 9377 MaybeEmitInheritedConstructorNote(S, Templated); 9378 return; 9379 9380 case Sema::TDK_TooManyArguments: 9381 case Sema::TDK_TooFewArguments: 9382 DiagnoseArityMismatch(S, Templated, NumArgs); 9383 return; 9384 9385 case Sema::TDK_InstantiationDepth: 9386 S.Diag(Templated->getLocation(), 9387 diag::note_ovl_candidate_instantiation_depth); 9388 MaybeEmitInheritedConstructorNote(S, Templated); 9389 return; 9390 9391 case Sema::TDK_SubstitutionFailure: { 9392 // Format the template argument list into the argument string. 9393 SmallString<128> TemplateArgString; 9394 if (TemplateArgumentList *Args = 9395 DeductionFailure.getTemplateArgumentList()) { 9396 TemplateArgString = " "; 9397 TemplateArgString += S.getTemplateArgumentBindingsText( 9398 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9399 } 9400 9401 // If this candidate was disabled by enable_if, say so. 9402 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9403 if (PDiag && PDiag->second.getDiagID() == 9404 diag::err_typename_nested_not_found_enable_if) { 9405 // FIXME: Use the source range of the condition, and the fully-qualified 9406 // name of the enable_if template. These are both present in PDiag. 9407 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9408 << "'enable_if'" << TemplateArgString; 9409 return; 9410 } 9411 9412 // Format the SFINAE diagnostic into the argument string. 9413 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9414 // formatted message in another diagnostic. 9415 SmallString<128> SFINAEArgString; 9416 SourceRange R; 9417 if (PDiag) { 9418 SFINAEArgString = ": "; 9419 R = SourceRange(PDiag->first, PDiag->first); 9420 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9421 } 9422 9423 S.Diag(Templated->getLocation(), 9424 diag::note_ovl_candidate_substitution_failure) 9425 << TemplateArgString << SFINAEArgString << R; 9426 MaybeEmitInheritedConstructorNote(S, Templated); 9427 return; 9428 } 9429 9430 case Sema::TDK_FailedOverloadResolution: { 9431 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 9432 S.Diag(Templated->getLocation(), 9433 diag::note_ovl_candidate_failed_overload_resolution) 9434 << R.Expression->getName(); 9435 return; 9436 } 9437 9438 case Sema::TDK_DeducedMismatch: { 9439 // Format the template argument list into the argument string. 9440 SmallString<128> TemplateArgString; 9441 if (TemplateArgumentList *Args = 9442 DeductionFailure.getTemplateArgumentList()) { 9443 TemplateArgString = " "; 9444 TemplateArgString += S.getTemplateArgumentBindingsText( 9445 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9446 } 9447 9448 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 9449 << (*DeductionFailure.getCallArgIndex() + 1) 9450 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 9451 << TemplateArgString; 9452 break; 9453 } 9454 9455 case Sema::TDK_NonDeducedMismatch: { 9456 // FIXME: Provide a source location to indicate what we couldn't match. 9457 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9458 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9459 if (FirstTA.getKind() == TemplateArgument::Template && 9460 SecondTA.getKind() == TemplateArgument::Template) { 9461 TemplateName FirstTN = FirstTA.getAsTemplate(); 9462 TemplateName SecondTN = SecondTA.getAsTemplate(); 9463 if (FirstTN.getKind() == TemplateName::Template && 9464 SecondTN.getKind() == TemplateName::Template) { 9465 if (FirstTN.getAsTemplateDecl()->getName() == 9466 SecondTN.getAsTemplateDecl()->getName()) { 9467 // FIXME: This fixes a bad diagnostic where both templates are named 9468 // the same. This particular case is a bit difficult since: 9469 // 1) It is passed as a string to the diagnostic printer. 9470 // 2) The diagnostic printer only attempts to find a better 9471 // name for types, not decls. 9472 // Ideally, this should folded into the diagnostic printer. 9473 S.Diag(Templated->getLocation(), 9474 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 9475 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 9476 return; 9477 } 9478 } 9479 } 9480 9481 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 9482 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 9483 return; 9484 9485 // FIXME: For generic lambda parameters, check if the function is a lambda 9486 // call operator, and if so, emit a prettier and more informative 9487 // diagnostic that mentions 'auto' and lambda in addition to 9488 // (or instead of?) the canonical template type parameters. 9489 S.Diag(Templated->getLocation(), 9490 diag::note_ovl_candidate_non_deduced_mismatch) 9491 << FirstTA << SecondTA; 9492 return; 9493 } 9494 // TODO: diagnose these individually, then kill off 9495 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9496 case Sema::TDK_MiscellaneousDeductionFailure: 9497 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9498 MaybeEmitInheritedConstructorNote(S, Templated); 9499 return; 9500 } 9501 } 9502 9503 /// Diagnose a failed template-argument deduction, for function calls. 9504 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 9505 unsigned NumArgs, 9506 bool TakingCandidateAddress) { 9507 unsigned TDK = Cand->DeductionFailure.Result; 9508 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9509 if (CheckArityMismatch(S, Cand, NumArgs)) 9510 return; 9511 } 9512 DiagnoseBadDeduction(S, Cand->Function, // pattern 9513 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 9514 } 9515 9516 /// CUDA: diagnose an invalid call across targets. 9517 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9518 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 9519 FunctionDecl *Callee = Cand->Function; 9520 9521 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 9522 CalleeTarget = S.IdentifyCUDATarget(Callee); 9523 9524 std::string FnDesc; 9525 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 9526 9527 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 9528 << (unsigned)FnKind << CalleeTarget << CallerTarget; 9529 9530 // This could be an implicit constructor for which we could not infer the 9531 // target due to a collsion. Diagnose that case. 9532 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 9533 if (Meth != nullptr && Meth->isImplicit()) { 9534 CXXRecordDecl *ParentClass = Meth->getParent(); 9535 Sema::CXXSpecialMember CSM; 9536 9537 switch (FnKind) { 9538 default: 9539 return; 9540 case oc_implicit_default_constructor: 9541 CSM = Sema::CXXDefaultConstructor; 9542 break; 9543 case oc_implicit_copy_constructor: 9544 CSM = Sema::CXXCopyConstructor; 9545 break; 9546 case oc_implicit_move_constructor: 9547 CSM = Sema::CXXMoveConstructor; 9548 break; 9549 case oc_implicit_copy_assignment: 9550 CSM = Sema::CXXCopyAssignment; 9551 break; 9552 case oc_implicit_move_assignment: 9553 CSM = Sema::CXXMoveAssignment; 9554 break; 9555 }; 9556 9557 bool ConstRHS = false; 9558 if (Meth->getNumParams()) { 9559 if (const ReferenceType *RT = 9560 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 9561 ConstRHS = RT->getPointeeType().isConstQualified(); 9562 } 9563 } 9564 9565 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 9566 /* ConstRHS */ ConstRHS, 9567 /* Diagnose */ true); 9568 } 9569 } 9570 9571 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 9572 FunctionDecl *Callee = Cand->Function; 9573 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 9574 9575 S.Diag(Callee->getLocation(), 9576 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9577 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9578 } 9579 9580 /// Generates a 'note' diagnostic for an overload candidate. We've 9581 /// already generated a primary error at the call site. 9582 /// 9583 /// It really does need to be a single diagnostic with its caret 9584 /// pointed at the candidate declaration. Yes, this creates some 9585 /// major challenges of technical writing. Yes, this makes pointing 9586 /// out problems with specific arguments quite awkward. It's still 9587 /// better than generating twenty screens of text for every failed 9588 /// overload. 9589 /// 9590 /// It would be great to be able to express per-candidate problems 9591 /// more richly for those diagnostic clients that cared, but we'd 9592 /// still have to be just as careful with the default diagnostics. 9593 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9594 unsigned NumArgs, 9595 bool TakingCandidateAddress) { 9596 FunctionDecl *Fn = Cand->Function; 9597 9598 // Note deleted candidates, but only if they're viable. 9599 if (Cand->Viable && (Fn->isDeleted() || 9600 S.isFunctionConsideredUnavailable(Fn))) { 9601 std::string FnDesc; 9602 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 9603 9604 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9605 << FnKind << FnDesc 9606 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9607 MaybeEmitInheritedConstructorNote(S, Fn); 9608 return; 9609 } 9610 9611 // We don't really have anything else to say about viable candidates. 9612 if (Cand->Viable) { 9613 S.NoteOverloadCandidate(Fn); 9614 return; 9615 } 9616 9617 switch (Cand->FailureKind) { 9618 case ovl_fail_too_many_arguments: 9619 case ovl_fail_too_few_arguments: 9620 return DiagnoseArityMismatch(S, Cand, NumArgs); 9621 9622 case ovl_fail_bad_deduction: 9623 return DiagnoseBadDeduction(S, Cand, NumArgs, TakingCandidateAddress); 9624 9625 case ovl_fail_illegal_constructor: { 9626 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 9627 << (Fn->getPrimaryTemplate() ? 1 : 0); 9628 MaybeEmitInheritedConstructorNote(S, Fn); 9629 return; 9630 } 9631 9632 case ovl_fail_trivial_conversion: 9633 case ovl_fail_bad_final_conversion: 9634 case ovl_fail_final_conversion_not_exact: 9635 return S.NoteOverloadCandidate(Fn); 9636 9637 case ovl_fail_bad_conversion: { 9638 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9639 for (unsigned N = Cand->NumConversions; I != N; ++I) 9640 if (Cand->Conversions[I].isBad()) 9641 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 9642 9643 // FIXME: this currently happens when we're called from SemaInit 9644 // when user-conversion overload fails. Figure out how to handle 9645 // those conditions and diagnose them well. 9646 return S.NoteOverloadCandidate(Fn); 9647 } 9648 9649 case ovl_fail_bad_target: 9650 return DiagnoseBadTarget(S, Cand); 9651 9652 case ovl_fail_enable_if: 9653 return DiagnoseFailedEnableIfAttr(S, Cand); 9654 9655 case ovl_fail_addr_not_available: { 9656 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 9657 (void)Available; 9658 assert(!Available); 9659 break; 9660 } 9661 } 9662 } 9663 9664 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9665 // Desugar the type of the surrogate down to a function type, 9666 // retaining as many typedefs as possible while still showing 9667 // the function type (and, therefore, its parameter types). 9668 QualType FnType = Cand->Surrogate->getConversionType(); 9669 bool isLValueReference = false; 9670 bool isRValueReference = false; 9671 bool isPointer = false; 9672 if (const LValueReferenceType *FnTypeRef = 9673 FnType->getAs<LValueReferenceType>()) { 9674 FnType = FnTypeRef->getPointeeType(); 9675 isLValueReference = true; 9676 } else if (const RValueReferenceType *FnTypeRef = 9677 FnType->getAs<RValueReferenceType>()) { 9678 FnType = FnTypeRef->getPointeeType(); 9679 isRValueReference = true; 9680 } 9681 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9682 FnType = FnTypePtr->getPointeeType(); 9683 isPointer = true; 9684 } 9685 // Desugar down to a function type. 9686 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9687 // Reconstruct the pointer/reference as appropriate. 9688 if (isPointer) FnType = S.Context.getPointerType(FnType); 9689 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9690 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9691 9692 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9693 << FnType; 9694 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 9695 } 9696 9697 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 9698 SourceLocation OpLoc, 9699 OverloadCandidate *Cand) { 9700 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9701 std::string TypeStr("operator"); 9702 TypeStr += Opc; 9703 TypeStr += "("; 9704 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9705 if (Cand->NumConversions == 1) { 9706 TypeStr += ")"; 9707 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9708 } else { 9709 TypeStr += ", "; 9710 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9711 TypeStr += ")"; 9712 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9713 } 9714 } 9715 9716 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9717 OverloadCandidate *Cand) { 9718 unsigned NoOperands = Cand->NumConversions; 9719 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9720 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9721 if (ICS.isBad()) break; // all meaningless after first invalid 9722 if (!ICS.isAmbiguous()) continue; 9723 9724 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 9725 S.PDiag(diag::note_ambiguous_type_conversion)); 9726 } 9727 } 9728 9729 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9730 if (Cand->Function) 9731 return Cand->Function->getLocation(); 9732 if (Cand->IsSurrogate) 9733 return Cand->Surrogate->getLocation(); 9734 return SourceLocation(); 9735 } 9736 9737 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 9738 switch ((Sema::TemplateDeductionResult)DFI.Result) { 9739 case Sema::TDK_Success: 9740 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9741 9742 case Sema::TDK_Invalid: 9743 case Sema::TDK_Incomplete: 9744 return 1; 9745 9746 case Sema::TDK_Underqualified: 9747 case Sema::TDK_Inconsistent: 9748 return 2; 9749 9750 case Sema::TDK_SubstitutionFailure: 9751 case Sema::TDK_DeducedMismatch: 9752 case Sema::TDK_NonDeducedMismatch: 9753 case Sema::TDK_MiscellaneousDeductionFailure: 9754 return 3; 9755 9756 case Sema::TDK_InstantiationDepth: 9757 case Sema::TDK_FailedOverloadResolution: 9758 return 4; 9759 9760 case Sema::TDK_InvalidExplicitArguments: 9761 return 5; 9762 9763 case Sema::TDK_TooManyArguments: 9764 case Sema::TDK_TooFewArguments: 9765 return 6; 9766 } 9767 llvm_unreachable("Unhandled deduction result"); 9768 } 9769 9770 namespace { 9771 struct CompareOverloadCandidatesForDisplay { 9772 Sema &S; 9773 SourceLocation Loc; 9774 size_t NumArgs; 9775 9776 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs) 9777 : S(S), NumArgs(nArgs) {} 9778 9779 bool operator()(const OverloadCandidate *L, 9780 const OverloadCandidate *R) { 9781 // Fast-path this check. 9782 if (L == R) return false; 9783 9784 // Order first by viability. 9785 if (L->Viable) { 9786 if (!R->Viable) return true; 9787 9788 // TODO: introduce a tri-valued comparison for overload 9789 // candidates. Would be more worthwhile if we had a sort 9790 // that could exploit it. 9791 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 9792 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 9793 } else if (R->Viable) 9794 return false; 9795 9796 assert(L->Viable == R->Viable); 9797 9798 // Criteria by which we can sort non-viable candidates: 9799 if (!L->Viable) { 9800 // 1. Arity mismatches come after other candidates. 9801 if (L->FailureKind == ovl_fail_too_many_arguments || 9802 L->FailureKind == ovl_fail_too_few_arguments) { 9803 if (R->FailureKind == ovl_fail_too_many_arguments || 9804 R->FailureKind == ovl_fail_too_few_arguments) { 9805 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 9806 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 9807 if (LDist == RDist) { 9808 if (L->FailureKind == R->FailureKind) 9809 // Sort non-surrogates before surrogates. 9810 return !L->IsSurrogate && R->IsSurrogate; 9811 // Sort candidates requiring fewer parameters than there were 9812 // arguments given after candidates requiring more parameters 9813 // than there were arguments given. 9814 return L->FailureKind == ovl_fail_too_many_arguments; 9815 } 9816 return LDist < RDist; 9817 } 9818 return false; 9819 } 9820 if (R->FailureKind == ovl_fail_too_many_arguments || 9821 R->FailureKind == ovl_fail_too_few_arguments) 9822 return true; 9823 9824 // 2. Bad conversions come first and are ordered by the number 9825 // of bad conversions and quality of good conversions. 9826 if (L->FailureKind == ovl_fail_bad_conversion) { 9827 if (R->FailureKind != ovl_fail_bad_conversion) 9828 return true; 9829 9830 // The conversion that can be fixed with a smaller number of changes, 9831 // comes first. 9832 unsigned numLFixes = L->Fix.NumConversionsFixed; 9833 unsigned numRFixes = R->Fix.NumConversionsFixed; 9834 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 9835 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 9836 if (numLFixes != numRFixes) { 9837 return numLFixes < numRFixes; 9838 } 9839 9840 // If there's any ordering between the defined conversions... 9841 // FIXME: this might not be transitive. 9842 assert(L->NumConversions == R->NumConversions); 9843 9844 int leftBetter = 0; 9845 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 9846 for (unsigned E = L->NumConversions; I != E; ++I) { 9847 switch (CompareImplicitConversionSequences(S, Loc, 9848 L->Conversions[I], 9849 R->Conversions[I])) { 9850 case ImplicitConversionSequence::Better: 9851 leftBetter++; 9852 break; 9853 9854 case ImplicitConversionSequence::Worse: 9855 leftBetter--; 9856 break; 9857 9858 case ImplicitConversionSequence::Indistinguishable: 9859 break; 9860 } 9861 } 9862 if (leftBetter > 0) return true; 9863 if (leftBetter < 0) return false; 9864 9865 } else if (R->FailureKind == ovl_fail_bad_conversion) 9866 return false; 9867 9868 if (L->FailureKind == ovl_fail_bad_deduction) { 9869 if (R->FailureKind != ovl_fail_bad_deduction) 9870 return true; 9871 9872 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9873 return RankDeductionFailure(L->DeductionFailure) 9874 < RankDeductionFailure(R->DeductionFailure); 9875 } else if (R->FailureKind == ovl_fail_bad_deduction) 9876 return false; 9877 9878 // TODO: others? 9879 } 9880 9881 // Sort everything else by location. 9882 SourceLocation LLoc = GetLocationForCandidate(L); 9883 SourceLocation RLoc = GetLocationForCandidate(R); 9884 9885 // Put candidates without locations (e.g. builtins) at the end. 9886 if (LLoc.isInvalid()) return false; 9887 if (RLoc.isInvalid()) return true; 9888 9889 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9890 } 9891 }; 9892 } 9893 9894 /// CompleteNonViableCandidate - Normally, overload resolution only 9895 /// computes up to the first. Produces the FixIt set if possible. 9896 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 9897 ArrayRef<Expr *> Args) { 9898 assert(!Cand->Viable); 9899 9900 // Don't do anything on failures other than bad conversion. 9901 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 9902 9903 // We only want the FixIts if all the arguments can be corrected. 9904 bool Unfixable = false; 9905 // Use a implicit copy initialization to check conversion fixes. 9906 Cand->Fix.setConversionChecker(TryCopyInitialization); 9907 9908 // Skip forward to the first bad conversion. 9909 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 9910 unsigned ConvCount = Cand->NumConversions; 9911 while (true) { 9912 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 9913 ConvIdx++; 9914 if (Cand->Conversions[ConvIdx - 1].isBad()) { 9915 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 9916 break; 9917 } 9918 } 9919 9920 if (ConvIdx == ConvCount) 9921 return; 9922 9923 assert(!Cand->Conversions[ConvIdx].isInitialized() && 9924 "remaining conversion is initialized?"); 9925 9926 // FIXME: this should probably be preserved from the overload 9927 // operation somehow. 9928 bool SuppressUserConversions = false; 9929 9930 const FunctionProtoType* Proto; 9931 unsigned ArgIdx = ConvIdx; 9932 9933 if (Cand->IsSurrogate) { 9934 QualType ConvType 9935 = Cand->Surrogate->getConversionType().getNonReferenceType(); 9936 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9937 ConvType = ConvPtrType->getPointeeType(); 9938 Proto = ConvType->getAs<FunctionProtoType>(); 9939 ArgIdx--; 9940 } else if (Cand->Function) { 9941 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 9942 if (isa<CXXMethodDecl>(Cand->Function) && 9943 !isa<CXXConstructorDecl>(Cand->Function)) 9944 ArgIdx--; 9945 } else { 9946 // Builtin binary operator with a bad first conversion. 9947 assert(ConvCount <= 3); 9948 for (; ConvIdx != ConvCount; ++ConvIdx) 9949 Cand->Conversions[ConvIdx] 9950 = TryCopyInitialization(S, Args[ConvIdx], 9951 Cand->BuiltinTypes.ParamTypes[ConvIdx], 9952 SuppressUserConversions, 9953 /*InOverloadResolution*/ true, 9954 /*AllowObjCWritebackConversion=*/ 9955 S.getLangOpts().ObjCAutoRefCount); 9956 return; 9957 } 9958 9959 // Fill in the rest of the conversions. 9960 unsigned NumParams = Proto->getNumParams(); 9961 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 9962 if (ArgIdx < NumParams) { 9963 Cand->Conversions[ConvIdx] = TryCopyInitialization( 9964 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 9965 /*InOverloadResolution=*/true, 9966 /*AllowObjCWritebackConversion=*/ 9967 S.getLangOpts().ObjCAutoRefCount); 9968 // Store the FixIt in the candidate if it exists. 9969 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 9970 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 9971 } 9972 else 9973 Cand->Conversions[ConvIdx].setEllipsis(); 9974 } 9975 } 9976 9977 /// PrintOverloadCandidates - When overload resolution fails, prints 9978 /// diagnostic messages containing the candidates in the candidate 9979 /// set. 9980 void OverloadCandidateSet::NoteCandidates(Sema &S, 9981 OverloadCandidateDisplayKind OCD, 9982 ArrayRef<Expr *> Args, 9983 StringRef Opc, 9984 SourceLocation OpLoc) { 9985 // Sort the candidates by viability and position. Sorting directly would 9986 // be prohibitive, so we make a set of pointers and sort those. 9987 SmallVector<OverloadCandidate*, 32> Cands; 9988 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 9989 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9990 if (Cand->Viable) 9991 Cands.push_back(Cand); 9992 else if (OCD == OCD_AllCandidates) { 9993 CompleteNonViableCandidate(S, Cand, Args); 9994 if (Cand->Function || Cand->IsSurrogate) 9995 Cands.push_back(Cand); 9996 // Otherwise, this a non-viable builtin candidate. We do not, in general, 9997 // want to list every possible builtin candidate. 9998 } 9999 } 10000 10001 std::sort(Cands.begin(), Cands.end(), 10002 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size())); 10003 10004 bool ReportedAmbiguousConversions = false; 10005 10006 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 10007 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10008 unsigned CandsShown = 0; 10009 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10010 OverloadCandidate *Cand = *I; 10011 10012 // Set an arbitrary limit on the number of candidate functions we'll spam 10013 // the user with. FIXME: This limit should depend on details of the 10014 // candidate list. 10015 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10016 break; 10017 } 10018 ++CandsShown; 10019 10020 if (Cand->Function) 10021 NoteFunctionCandidate(S, Cand, Args.size(), 10022 /*TakingCandidateAddress=*/false); 10023 else if (Cand->IsSurrogate) 10024 NoteSurrogateCandidate(S, Cand); 10025 else { 10026 assert(Cand->Viable && 10027 "Non-viable built-in candidates are not added to Cands."); 10028 // Generally we only see ambiguities including viable builtin 10029 // operators if overload resolution got screwed up by an 10030 // ambiguous user-defined conversion. 10031 // 10032 // FIXME: It's quite possible for different conversions to see 10033 // different ambiguities, though. 10034 if (!ReportedAmbiguousConversions) { 10035 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10036 ReportedAmbiguousConversions = true; 10037 } 10038 10039 // If this is a viable builtin, print it. 10040 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10041 } 10042 } 10043 10044 if (I != E) 10045 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10046 } 10047 10048 static SourceLocation 10049 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10050 return Cand->Specialization ? Cand->Specialization->getLocation() 10051 : SourceLocation(); 10052 } 10053 10054 namespace { 10055 struct CompareTemplateSpecCandidatesForDisplay { 10056 Sema &S; 10057 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10058 10059 bool operator()(const TemplateSpecCandidate *L, 10060 const TemplateSpecCandidate *R) { 10061 // Fast-path this check. 10062 if (L == R) 10063 return false; 10064 10065 // Assuming that both candidates are not matches... 10066 10067 // Sort by the ranking of deduction failures. 10068 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10069 return RankDeductionFailure(L->DeductionFailure) < 10070 RankDeductionFailure(R->DeductionFailure); 10071 10072 // Sort everything else by location. 10073 SourceLocation LLoc = GetLocationForCandidate(L); 10074 SourceLocation RLoc = GetLocationForCandidate(R); 10075 10076 // Put candidates without locations (e.g. builtins) at the end. 10077 if (LLoc.isInvalid()) 10078 return false; 10079 if (RLoc.isInvalid()) 10080 return true; 10081 10082 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10083 } 10084 }; 10085 } 10086 10087 /// Diagnose a template argument deduction failure. 10088 /// We are treating these failures as overload failures due to bad 10089 /// deductions. 10090 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10091 bool ForTakingAddress) { 10092 DiagnoseBadDeduction(S, Specialization, // pattern 10093 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10094 } 10095 10096 void TemplateSpecCandidateSet::destroyCandidates() { 10097 for (iterator i = begin(), e = end(); i != e; ++i) { 10098 i->DeductionFailure.Destroy(); 10099 } 10100 } 10101 10102 void TemplateSpecCandidateSet::clear() { 10103 destroyCandidates(); 10104 Candidates.clear(); 10105 } 10106 10107 /// NoteCandidates - When no template specialization match is found, prints 10108 /// diagnostic messages containing the non-matching specializations that form 10109 /// the candidate set. 10110 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10111 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10112 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10113 // Sort the candidates by position (assuming no candidate is a match). 10114 // Sorting directly would be prohibitive, so we make a set of pointers 10115 // and sort those. 10116 SmallVector<TemplateSpecCandidate *, 32> Cands; 10117 Cands.reserve(size()); 10118 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10119 if (Cand->Specialization) 10120 Cands.push_back(Cand); 10121 // Otherwise, this is a non-matching builtin candidate. We do not, 10122 // in general, want to list every possible builtin candidate. 10123 } 10124 10125 std::sort(Cands.begin(), Cands.end(), 10126 CompareTemplateSpecCandidatesForDisplay(S)); 10127 10128 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10129 // for generalization purposes (?). 10130 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10131 10132 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10133 unsigned CandsShown = 0; 10134 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10135 TemplateSpecCandidate *Cand = *I; 10136 10137 // Set an arbitrary limit on the number of candidates we'll spam 10138 // the user with. FIXME: This limit should depend on details of the 10139 // candidate list. 10140 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10141 break; 10142 ++CandsShown; 10143 10144 assert(Cand->Specialization && 10145 "Non-matching built-in candidates are not added to Cands."); 10146 Cand->NoteDeductionFailure(S, ForTakingAddress); 10147 } 10148 10149 if (I != E) 10150 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10151 } 10152 10153 // [PossiblyAFunctionType] --> [Return] 10154 // NonFunctionType --> NonFunctionType 10155 // R (A) --> R(A) 10156 // R (*)(A) --> R (A) 10157 // R (&)(A) --> R (A) 10158 // R (S::*)(A) --> R (A) 10159 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10160 QualType Ret = PossiblyAFunctionType; 10161 if (const PointerType *ToTypePtr = 10162 PossiblyAFunctionType->getAs<PointerType>()) 10163 Ret = ToTypePtr->getPointeeType(); 10164 else if (const ReferenceType *ToTypeRef = 10165 PossiblyAFunctionType->getAs<ReferenceType>()) 10166 Ret = ToTypeRef->getPointeeType(); 10167 else if (const MemberPointerType *MemTypePtr = 10168 PossiblyAFunctionType->getAs<MemberPointerType>()) 10169 Ret = MemTypePtr->getPointeeType(); 10170 Ret = 10171 Context.getCanonicalType(Ret).getUnqualifiedType(); 10172 return Ret; 10173 } 10174 10175 namespace { 10176 // A helper class to help with address of function resolution 10177 // - allows us to avoid passing around all those ugly parameters 10178 class AddressOfFunctionResolver { 10179 Sema& S; 10180 Expr* SourceExpr; 10181 const QualType& TargetType; 10182 QualType TargetFunctionType; // Extracted function type from target type 10183 10184 bool Complain; 10185 //DeclAccessPair& ResultFunctionAccessPair; 10186 ASTContext& Context; 10187 10188 bool TargetTypeIsNonStaticMemberFunction; 10189 bool FoundNonTemplateFunction; 10190 bool StaticMemberFunctionFromBoundPointer; 10191 bool HasComplained; 10192 10193 OverloadExpr::FindResult OvlExprInfo; 10194 OverloadExpr *OvlExpr; 10195 TemplateArgumentListInfo OvlExplicitTemplateArgs; 10196 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 10197 TemplateSpecCandidateSet FailedCandidates; 10198 10199 public: 10200 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 10201 const QualType &TargetType, bool Complain) 10202 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 10203 Complain(Complain), Context(S.getASTContext()), 10204 TargetTypeIsNonStaticMemberFunction( 10205 !!TargetType->getAs<MemberPointerType>()), 10206 FoundNonTemplateFunction(false), 10207 StaticMemberFunctionFromBoundPointer(false), 10208 HasComplained(false), 10209 OvlExprInfo(OverloadExpr::find(SourceExpr)), 10210 OvlExpr(OvlExprInfo.Expression), 10211 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 10212 ExtractUnqualifiedFunctionTypeFromTargetType(); 10213 10214 if (TargetFunctionType->isFunctionType()) { 10215 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 10216 if (!UME->isImplicitAccess() && 10217 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 10218 StaticMemberFunctionFromBoundPointer = true; 10219 } else if (OvlExpr->hasExplicitTemplateArgs()) { 10220 DeclAccessPair dap; 10221 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 10222 OvlExpr, false, &dap)) { 10223 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 10224 if (!Method->isStatic()) { 10225 // If the target type is a non-function type and the function found 10226 // is a non-static member function, pretend as if that was the 10227 // target, it's the only possible type to end up with. 10228 TargetTypeIsNonStaticMemberFunction = true; 10229 10230 // And skip adding the function if its not in the proper form. 10231 // We'll diagnose this due to an empty set of functions. 10232 if (!OvlExprInfo.HasFormOfMemberPointer) 10233 return; 10234 } 10235 10236 Matches.push_back(std::make_pair(dap, Fn)); 10237 } 10238 return; 10239 } 10240 10241 if (OvlExpr->hasExplicitTemplateArgs()) 10242 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 10243 10244 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 10245 // C++ [over.over]p4: 10246 // If more than one function is selected, [...] 10247 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 10248 if (FoundNonTemplateFunction) 10249 EliminateAllTemplateMatches(); 10250 else 10251 EliminateAllExceptMostSpecializedTemplate(); 10252 } 10253 } 10254 10255 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads && 10256 Matches.size() > 1) 10257 EliminateSuboptimalCudaMatches(); 10258 } 10259 10260 bool hasComplained() const { return HasComplained; } 10261 10262 private: 10263 // Is A considered a better overload candidate for the desired type than B? 10264 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 10265 return hasBetterEnableIfAttrs(S, A, B); 10266 } 10267 10268 // Returns true if we've eliminated any (read: all but one) candidates, false 10269 // otherwise. 10270 bool eliminiateSuboptimalOverloadCandidates() { 10271 // Same algorithm as overload resolution -- one pass to pick the "best", 10272 // another pass to be sure that nothing is better than the best. 10273 auto Best = Matches.begin(); 10274 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 10275 if (isBetterCandidate(I->second, Best->second)) 10276 Best = I; 10277 10278 const FunctionDecl *BestFn = Best->second; 10279 auto IsBestOrInferiorToBest = [this, BestFn]( 10280 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 10281 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 10282 }; 10283 10284 // Note: We explicitly leave Matches unmodified if there isn't a clear best 10285 // option, so we can potentially give the user a better error 10286 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest)) 10287 return false; 10288 Matches[0] = *Best; 10289 Matches.resize(1); 10290 return true; 10291 } 10292 10293 bool isTargetTypeAFunction() const { 10294 return TargetFunctionType->isFunctionType(); 10295 } 10296 10297 // [ToType] [Return] 10298 10299 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 10300 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 10301 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 10302 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 10303 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 10304 } 10305 10306 // return true if any matching specializations were found 10307 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 10308 const DeclAccessPair& CurAccessFunPair) { 10309 if (CXXMethodDecl *Method 10310 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 10311 // Skip non-static function templates when converting to pointer, and 10312 // static when converting to member pointer. 10313 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10314 return false; 10315 } 10316 else if (TargetTypeIsNonStaticMemberFunction) 10317 return false; 10318 10319 // C++ [over.over]p2: 10320 // If the name is a function template, template argument deduction is 10321 // done (14.8.2.2), and if the argument deduction succeeds, the 10322 // resulting template argument list is used to generate a single 10323 // function template specialization, which is added to the set of 10324 // overloaded functions considered. 10325 FunctionDecl *Specialization = nullptr; 10326 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10327 if (Sema::TemplateDeductionResult Result 10328 = S.DeduceTemplateArguments(FunctionTemplate, 10329 &OvlExplicitTemplateArgs, 10330 TargetFunctionType, Specialization, 10331 Info, /*InOverloadResolution=*/true)) { 10332 // Make a note of the failed deduction for diagnostics. 10333 FailedCandidates.addCandidate() 10334 .set(FunctionTemplate->getTemplatedDecl(), 10335 MakeDeductionFailureInfo(Context, Result, Info)); 10336 return false; 10337 } 10338 10339 // Template argument deduction ensures that we have an exact match or 10340 // compatible pointer-to-function arguments that would be adjusted by ICS. 10341 // This function template specicalization works. 10342 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 10343 assert(S.isSameOrCompatibleFunctionType( 10344 Context.getCanonicalType(Specialization->getType()), 10345 Context.getCanonicalType(TargetFunctionType))); 10346 10347 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 10348 return false; 10349 10350 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 10351 return true; 10352 } 10353 10354 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 10355 const DeclAccessPair& CurAccessFunPair) { 10356 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 10357 // Skip non-static functions when converting to pointer, and static 10358 // when converting to member pointer. 10359 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10360 return false; 10361 } 10362 else if (TargetTypeIsNonStaticMemberFunction) 10363 return false; 10364 10365 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 10366 if (S.getLangOpts().CUDA) 10367 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 10368 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl)) 10369 return false; 10370 10371 // If any candidate has a placeholder return type, trigger its deduction 10372 // now. 10373 if (S.getLangOpts().CPlusPlus14 && 10374 FunDecl->getReturnType()->isUndeducedType() && 10375 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) { 10376 HasComplained |= Complain; 10377 return false; 10378 } 10379 10380 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 10381 return false; 10382 10383 QualType ResultTy; 10384 if (Context.hasSameUnqualifiedType(TargetFunctionType, 10385 FunDecl->getType()) || 10386 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 10387 ResultTy) || 10388 (!S.getLangOpts().CPlusPlus && TargetType->isVoidPointerType())) { 10389 Matches.push_back(std::make_pair( 10390 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 10391 FoundNonTemplateFunction = true; 10392 return true; 10393 } 10394 } 10395 10396 return false; 10397 } 10398 10399 bool FindAllFunctionsThatMatchTargetTypeExactly() { 10400 bool Ret = false; 10401 10402 // If the overload expression doesn't have the form of a pointer to 10403 // member, don't try to convert it to a pointer-to-member type. 10404 if (IsInvalidFormOfPointerToMemberFunction()) 10405 return false; 10406 10407 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10408 E = OvlExpr->decls_end(); 10409 I != E; ++I) { 10410 // Look through any using declarations to find the underlying function. 10411 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 10412 10413 // C++ [over.over]p3: 10414 // Non-member functions and static member functions match 10415 // targets of type "pointer-to-function" or "reference-to-function." 10416 // Nonstatic member functions match targets of 10417 // type "pointer-to-member-function." 10418 // Note that according to DR 247, the containing class does not matter. 10419 if (FunctionTemplateDecl *FunctionTemplate 10420 = dyn_cast<FunctionTemplateDecl>(Fn)) { 10421 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 10422 Ret = true; 10423 } 10424 // If we have explicit template arguments supplied, skip non-templates. 10425 else if (!OvlExpr->hasExplicitTemplateArgs() && 10426 AddMatchingNonTemplateFunction(Fn, I.getPair())) 10427 Ret = true; 10428 } 10429 assert(Ret || Matches.empty()); 10430 return Ret; 10431 } 10432 10433 void EliminateAllExceptMostSpecializedTemplate() { 10434 // [...] and any given function template specialization F1 is 10435 // eliminated if the set contains a second function template 10436 // specialization whose function template is more specialized 10437 // than the function template of F1 according to the partial 10438 // ordering rules of 14.5.5.2. 10439 10440 // The algorithm specified above is quadratic. We instead use a 10441 // two-pass algorithm (similar to the one used to identify the 10442 // best viable function in an overload set) that identifies the 10443 // best function template (if it exists). 10444 10445 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 10446 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 10447 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 10448 10449 // TODO: It looks like FailedCandidates does not serve much purpose 10450 // here, since the no_viable diagnostic has index 0. 10451 UnresolvedSetIterator Result = S.getMostSpecialized( 10452 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 10453 SourceExpr->getLocStart(), S.PDiag(), 10454 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0] 10455 .second->getDeclName(), 10456 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template, 10457 Complain, TargetFunctionType); 10458 10459 if (Result != MatchesCopy.end()) { 10460 // Make it the first and only element 10461 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 10462 Matches[0].second = cast<FunctionDecl>(*Result); 10463 Matches.resize(1); 10464 } else 10465 HasComplained |= Complain; 10466 } 10467 10468 void EliminateAllTemplateMatches() { 10469 // [...] any function template specializations in the set are 10470 // eliminated if the set also contains a non-template function, [...] 10471 for (unsigned I = 0, N = Matches.size(); I != N; ) { 10472 if (Matches[I].second->getPrimaryTemplate() == nullptr) 10473 ++I; 10474 else { 10475 Matches[I] = Matches[--N]; 10476 Matches.resize(N); 10477 } 10478 } 10479 } 10480 10481 void EliminateSuboptimalCudaMatches() { 10482 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 10483 } 10484 10485 public: 10486 void ComplainNoMatchesFound() const { 10487 assert(Matches.empty()); 10488 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 10489 << OvlExpr->getName() << TargetFunctionType 10490 << OvlExpr->getSourceRange(); 10491 if (FailedCandidates.empty()) 10492 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10493 /*TakingAddress=*/true); 10494 else { 10495 // We have some deduction failure messages. Use them to diagnose 10496 // the function templates, and diagnose the non-template candidates 10497 // normally. 10498 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10499 IEnd = OvlExpr->decls_end(); 10500 I != IEnd; ++I) 10501 if (FunctionDecl *Fun = 10502 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 10503 if (!functionHasPassObjectSizeParams(Fun)) 10504 S.NoteOverloadCandidate(Fun, TargetFunctionType, 10505 /*TakingAddress=*/true); 10506 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 10507 } 10508 } 10509 10510 bool IsInvalidFormOfPointerToMemberFunction() const { 10511 return TargetTypeIsNonStaticMemberFunction && 10512 !OvlExprInfo.HasFormOfMemberPointer; 10513 } 10514 10515 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 10516 // TODO: Should we condition this on whether any functions might 10517 // have matched, or is it more appropriate to do that in callers? 10518 // TODO: a fixit wouldn't hurt. 10519 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 10520 << TargetType << OvlExpr->getSourceRange(); 10521 } 10522 10523 bool IsStaticMemberFunctionFromBoundPointer() const { 10524 return StaticMemberFunctionFromBoundPointer; 10525 } 10526 10527 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 10528 S.Diag(OvlExpr->getLocStart(), 10529 diag::err_invalid_form_pointer_member_function) 10530 << OvlExpr->getSourceRange(); 10531 } 10532 10533 void ComplainOfInvalidConversion() const { 10534 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 10535 << OvlExpr->getName() << TargetType; 10536 } 10537 10538 void ComplainMultipleMatchesFound() const { 10539 assert(Matches.size() > 1); 10540 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 10541 << OvlExpr->getName() 10542 << OvlExpr->getSourceRange(); 10543 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10544 /*TakingAddress=*/true); 10545 } 10546 10547 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 10548 10549 int getNumMatches() const { return Matches.size(); } 10550 10551 FunctionDecl* getMatchingFunctionDecl() const { 10552 if (Matches.size() != 1) return nullptr; 10553 return Matches[0].second; 10554 } 10555 10556 const DeclAccessPair* getMatchingFunctionAccessPair() const { 10557 if (Matches.size() != 1) return nullptr; 10558 return &Matches[0].first; 10559 } 10560 }; 10561 } 10562 10563 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 10564 /// an overloaded function (C++ [over.over]), where @p From is an 10565 /// expression with overloaded function type and @p ToType is the type 10566 /// we're trying to resolve to. For example: 10567 /// 10568 /// @code 10569 /// int f(double); 10570 /// int f(int); 10571 /// 10572 /// int (*pfd)(double) = f; // selects f(double) 10573 /// @endcode 10574 /// 10575 /// This routine returns the resulting FunctionDecl if it could be 10576 /// resolved, and NULL otherwise. When @p Complain is true, this 10577 /// routine will emit diagnostics if there is an error. 10578 FunctionDecl * 10579 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 10580 QualType TargetType, 10581 bool Complain, 10582 DeclAccessPair &FoundResult, 10583 bool *pHadMultipleCandidates) { 10584 assert(AddressOfExpr->getType() == Context.OverloadTy); 10585 10586 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 10587 Complain); 10588 int NumMatches = Resolver.getNumMatches(); 10589 FunctionDecl *Fn = nullptr; 10590 bool ShouldComplain = Complain && !Resolver.hasComplained(); 10591 if (NumMatches == 0 && ShouldComplain) { 10592 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 10593 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 10594 else 10595 Resolver.ComplainNoMatchesFound(); 10596 } 10597 else if (NumMatches > 1 && ShouldComplain) 10598 Resolver.ComplainMultipleMatchesFound(); 10599 else if (NumMatches == 1) { 10600 Fn = Resolver.getMatchingFunctionDecl(); 10601 assert(Fn); 10602 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 10603 if (Complain) { 10604 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 10605 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 10606 else 10607 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 10608 } 10609 } 10610 10611 if (pHadMultipleCandidates) 10612 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 10613 return Fn; 10614 } 10615 10616 /// \brief Given an expression that refers to an overloaded function, try to 10617 /// resolve that overloaded function expression down to a single function. 10618 /// 10619 /// This routine can only resolve template-ids that refer to a single function 10620 /// template, where that template-id refers to a single template whose template 10621 /// arguments are either provided by the template-id or have defaults, 10622 /// as described in C++0x [temp.arg.explicit]p3. 10623 /// 10624 /// If no template-ids are found, no diagnostics are emitted and NULL is 10625 /// returned. 10626 FunctionDecl * 10627 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 10628 bool Complain, 10629 DeclAccessPair *FoundResult) { 10630 // C++ [over.over]p1: 10631 // [...] [Note: any redundant set of parentheses surrounding the 10632 // overloaded function name is ignored (5.1). ] 10633 // C++ [over.over]p1: 10634 // [...] The overloaded function name can be preceded by the & 10635 // operator. 10636 10637 // If we didn't actually find any template-ids, we're done. 10638 if (!ovl->hasExplicitTemplateArgs()) 10639 return nullptr; 10640 10641 TemplateArgumentListInfo ExplicitTemplateArgs; 10642 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 10643 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 10644 10645 // Look through all of the overloaded functions, searching for one 10646 // whose type matches exactly. 10647 FunctionDecl *Matched = nullptr; 10648 for (UnresolvedSetIterator I = ovl->decls_begin(), 10649 E = ovl->decls_end(); I != E; ++I) { 10650 // C++0x [temp.arg.explicit]p3: 10651 // [...] In contexts where deduction is done and fails, or in contexts 10652 // where deduction is not done, if a template argument list is 10653 // specified and it, along with any default template arguments, 10654 // identifies a single function template specialization, then the 10655 // template-id is an lvalue for the function template specialization. 10656 FunctionTemplateDecl *FunctionTemplate 10657 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 10658 10659 // C++ [over.over]p2: 10660 // If the name is a function template, template argument deduction is 10661 // done (14.8.2.2), and if the argument deduction succeeds, the 10662 // resulting template argument list is used to generate a single 10663 // function template specialization, which is added to the set of 10664 // overloaded functions considered. 10665 FunctionDecl *Specialization = nullptr; 10666 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10667 if (TemplateDeductionResult Result 10668 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 10669 Specialization, Info, 10670 /*InOverloadResolution=*/true)) { 10671 // Make a note of the failed deduction for diagnostics. 10672 // TODO: Actually use the failed-deduction info? 10673 FailedCandidates.addCandidate() 10674 .set(FunctionTemplate->getTemplatedDecl(), 10675 MakeDeductionFailureInfo(Context, Result, Info)); 10676 continue; 10677 } 10678 10679 assert(Specialization && "no specialization and no error?"); 10680 10681 // Multiple matches; we can't resolve to a single declaration. 10682 if (Matched) { 10683 if (Complain) { 10684 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 10685 << ovl->getName(); 10686 NoteAllOverloadCandidates(ovl); 10687 } 10688 return nullptr; 10689 } 10690 10691 Matched = Specialization; 10692 if (FoundResult) *FoundResult = I.getPair(); 10693 } 10694 10695 if (Matched && getLangOpts().CPlusPlus14 && 10696 Matched->getReturnType()->isUndeducedType() && 10697 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 10698 return nullptr; 10699 10700 return Matched; 10701 } 10702 10703 10704 10705 10706 // Resolve and fix an overloaded expression that can be resolved 10707 // because it identifies a single function template specialization. 10708 // 10709 // Last three arguments should only be supplied if Complain = true 10710 // 10711 // Return true if it was logically possible to so resolve the 10712 // expression, regardless of whether or not it succeeded. Always 10713 // returns true if 'complain' is set. 10714 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 10715 ExprResult &SrcExpr, bool doFunctionPointerConverion, 10716 bool complain, SourceRange OpRangeForComplaining, 10717 QualType DestTypeForComplaining, 10718 unsigned DiagIDForComplaining) { 10719 assert(SrcExpr.get()->getType() == Context.OverloadTy); 10720 10721 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 10722 10723 DeclAccessPair found; 10724 ExprResult SingleFunctionExpression; 10725 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 10726 ovl.Expression, /*complain*/ false, &found)) { 10727 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 10728 SrcExpr = ExprError(); 10729 return true; 10730 } 10731 10732 // It is only correct to resolve to an instance method if we're 10733 // resolving a form that's permitted to be a pointer to member. 10734 // Otherwise we'll end up making a bound member expression, which 10735 // is illegal in all the contexts we resolve like this. 10736 if (!ovl.HasFormOfMemberPointer && 10737 isa<CXXMethodDecl>(fn) && 10738 cast<CXXMethodDecl>(fn)->isInstance()) { 10739 if (!complain) return false; 10740 10741 Diag(ovl.Expression->getExprLoc(), 10742 diag::err_bound_member_function) 10743 << 0 << ovl.Expression->getSourceRange(); 10744 10745 // TODO: I believe we only end up here if there's a mix of 10746 // static and non-static candidates (otherwise the expression 10747 // would have 'bound member' type, not 'overload' type). 10748 // Ideally we would note which candidate was chosen and why 10749 // the static candidates were rejected. 10750 SrcExpr = ExprError(); 10751 return true; 10752 } 10753 10754 // Fix the expression to refer to 'fn'. 10755 SingleFunctionExpression = 10756 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 10757 10758 // If desired, do function-to-pointer decay. 10759 if (doFunctionPointerConverion) { 10760 SingleFunctionExpression = 10761 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 10762 if (SingleFunctionExpression.isInvalid()) { 10763 SrcExpr = ExprError(); 10764 return true; 10765 } 10766 } 10767 } 10768 10769 if (!SingleFunctionExpression.isUsable()) { 10770 if (complain) { 10771 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 10772 << ovl.Expression->getName() 10773 << DestTypeForComplaining 10774 << OpRangeForComplaining 10775 << ovl.Expression->getQualifierLoc().getSourceRange(); 10776 NoteAllOverloadCandidates(SrcExpr.get()); 10777 10778 SrcExpr = ExprError(); 10779 return true; 10780 } 10781 10782 return false; 10783 } 10784 10785 SrcExpr = SingleFunctionExpression; 10786 return true; 10787 } 10788 10789 /// \brief Add a single candidate to the overload set. 10790 static void AddOverloadedCallCandidate(Sema &S, 10791 DeclAccessPair FoundDecl, 10792 TemplateArgumentListInfo *ExplicitTemplateArgs, 10793 ArrayRef<Expr *> Args, 10794 OverloadCandidateSet &CandidateSet, 10795 bool PartialOverloading, 10796 bool KnownValid) { 10797 NamedDecl *Callee = FoundDecl.getDecl(); 10798 if (isa<UsingShadowDecl>(Callee)) 10799 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 10800 10801 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 10802 if (ExplicitTemplateArgs) { 10803 assert(!KnownValid && "Explicit template arguments?"); 10804 return; 10805 } 10806 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 10807 /*SuppressUsedConversions=*/false, 10808 PartialOverloading); 10809 return; 10810 } 10811 10812 if (FunctionTemplateDecl *FuncTemplate 10813 = dyn_cast<FunctionTemplateDecl>(Callee)) { 10814 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 10815 ExplicitTemplateArgs, Args, CandidateSet, 10816 /*SuppressUsedConversions=*/false, 10817 PartialOverloading); 10818 return; 10819 } 10820 10821 assert(!KnownValid && "unhandled case in overloaded call candidate"); 10822 } 10823 10824 /// \brief Add the overload candidates named by callee and/or found by argument 10825 /// dependent lookup to the given overload set. 10826 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 10827 ArrayRef<Expr *> Args, 10828 OverloadCandidateSet &CandidateSet, 10829 bool PartialOverloading) { 10830 10831 #ifndef NDEBUG 10832 // Verify that ArgumentDependentLookup is consistent with the rules 10833 // in C++0x [basic.lookup.argdep]p3: 10834 // 10835 // Let X be the lookup set produced by unqualified lookup (3.4.1) 10836 // and let Y be the lookup set produced by argument dependent 10837 // lookup (defined as follows). If X contains 10838 // 10839 // -- a declaration of a class member, or 10840 // 10841 // -- a block-scope function declaration that is not a 10842 // using-declaration, or 10843 // 10844 // -- a declaration that is neither a function or a function 10845 // template 10846 // 10847 // then Y is empty. 10848 10849 if (ULE->requiresADL()) { 10850 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10851 E = ULE->decls_end(); I != E; ++I) { 10852 assert(!(*I)->getDeclContext()->isRecord()); 10853 assert(isa<UsingShadowDecl>(*I) || 10854 !(*I)->getDeclContext()->isFunctionOrMethod()); 10855 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 10856 } 10857 } 10858 #endif 10859 10860 // It would be nice to avoid this copy. 10861 TemplateArgumentListInfo TABuffer; 10862 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 10863 if (ULE->hasExplicitTemplateArgs()) { 10864 ULE->copyTemplateArgumentsInto(TABuffer); 10865 ExplicitTemplateArgs = &TABuffer; 10866 } 10867 10868 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10869 E = ULE->decls_end(); I != E; ++I) 10870 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 10871 CandidateSet, PartialOverloading, 10872 /*KnownValid*/ true); 10873 10874 if (ULE->requiresADL()) 10875 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 10876 Args, ExplicitTemplateArgs, 10877 CandidateSet, PartialOverloading); 10878 } 10879 10880 /// Determine whether a declaration with the specified name could be moved into 10881 /// a different namespace. 10882 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 10883 switch (Name.getCXXOverloadedOperator()) { 10884 case OO_New: case OO_Array_New: 10885 case OO_Delete: case OO_Array_Delete: 10886 return false; 10887 10888 default: 10889 return true; 10890 } 10891 } 10892 10893 /// Attempt to recover from an ill-formed use of a non-dependent name in a 10894 /// template, where the non-dependent name was declared after the template 10895 /// was defined. This is common in code written for a compilers which do not 10896 /// correctly implement two-stage name lookup. 10897 /// 10898 /// Returns true if a viable candidate was found and a diagnostic was issued. 10899 static bool 10900 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 10901 const CXXScopeSpec &SS, LookupResult &R, 10902 OverloadCandidateSet::CandidateSetKind CSK, 10903 TemplateArgumentListInfo *ExplicitTemplateArgs, 10904 ArrayRef<Expr *> Args, 10905 bool *DoDiagnoseEmptyLookup = nullptr) { 10906 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 10907 return false; 10908 10909 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 10910 if (DC->isTransparentContext()) 10911 continue; 10912 10913 SemaRef.LookupQualifiedName(R, DC); 10914 10915 if (!R.empty()) { 10916 R.suppressDiagnostics(); 10917 10918 if (isa<CXXRecordDecl>(DC)) { 10919 // Don't diagnose names we find in classes; we get much better 10920 // diagnostics for these from DiagnoseEmptyLookup. 10921 R.clear(); 10922 if (DoDiagnoseEmptyLookup) 10923 *DoDiagnoseEmptyLookup = true; 10924 return false; 10925 } 10926 10927 OverloadCandidateSet Candidates(FnLoc, CSK); 10928 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10929 AddOverloadedCallCandidate(SemaRef, I.getPair(), 10930 ExplicitTemplateArgs, Args, 10931 Candidates, false, /*KnownValid*/ false); 10932 10933 OverloadCandidateSet::iterator Best; 10934 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 10935 // No viable functions. Don't bother the user with notes for functions 10936 // which don't work and shouldn't be found anyway. 10937 R.clear(); 10938 return false; 10939 } 10940 10941 // Find the namespaces where ADL would have looked, and suggest 10942 // declaring the function there instead. 10943 Sema::AssociatedNamespaceSet AssociatedNamespaces; 10944 Sema::AssociatedClassSet AssociatedClasses; 10945 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 10946 AssociatedNamespaces, 10947 AssociatedClasses); 10948 Sema::AssociatedNamespaceSet SuggestedNamespaces; 10949 if (canBeDeclaredInNamespace(R.getLookupName())) { 10950 DeclContext *Std = SemaRef.getStdNamespace(); 10951 for (Sema::AssociatedNamespaceSet::iterator 10952 it = AssociatedNamespaces.begin(), 10953 end = AssociatedNamespaces.end(); it != end; ++it) { 10954 // Never suggest declaring a function within namespace 'std'. 10955 if (Std && Std->Encloses(*it)) 10956 continue; 10957 10958 // Never suggest declaring a function within a namespace with a 10959 // reserved name, like __gnu_cxx. 10960 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 10961 if (NS && 10962 NS->getQualifiedNameAsString().find("__") != std::string::npos) 10963 continue; 10964 10965 SuggestedNamespaces.insert(*it); 10966 } 10967 } 10968 10969 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 10970 << R.getLookupName(); 10971 if (SuggestedNamespaces.empty()) { 10972 SemaRef.Diag(Best->Function->getLocation(), 10973 diag::note_not_found_by_two_phase_lookup) 10974 << R.getLookupName() << 0; 10975 } else if (SuggestedNamespaces.size() == 1) { 10976 SemaRef.Diag(Best->Function->getLocation(), 10977 diag::note_not_found_by_two_phase_lookup) 10978 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 10979 } else { 10980 // FIXME: It would be useful to list the associated namespaces here, 10981 // but the diagnostics infrastructure doesn't provide a way to produce 10982 // a localized representation of a list of items. 10983 SemaRef.Diag(Best->Function->getLocation(), 10984 diag::note_not_found_by_two_phase_lookup) 10985 << R.getLookupName() << 2; 10986 } 10987 10988 // Try to recover by calling this function. 10989 return true; 10990 } 10991 10992 R.clear(); 10993 } 10994 10995 return false; 10996 } 10997 10998 /// Attempt to recover from ill-formed use of a non-dependent operator in a 10999 /// template, where the non-dependent operator was declared after the template 11000 /// was defined. 11001 /// 11002 /// Returns true if a viable candidate was found and a diagnostic was issued. 11003 static bool 11004 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11005 SourceLocation OpLoc, 11006 ArrayRef<Expr *> Args) { 11007 DeclarationName OpName = 11008 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11009 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11010 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11011 OverloadCandidateSet::CSK_Operator, 11012 /*ExplicitTemplateArgs=*/nullptr, Args); 11013 } 11014 11015 namespace { 11016 class BuildRecoveryCallExprRAII { 11017 Sema &SemaRef; 11018 public: 11019 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11020 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11021 SemaRef.IsBuildingRecoveryCallExpr = true; 11022 } 11023 11024 ~BuildRecoveryCallExprRAII() { 11025 SemaRef.IsBuildingRecoveryCallExpr = false; 11026 } 11027 }; 11028 11029 } 11030 11031 static std::unique_ptr<CorrectionCandidateCallback> 11032 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 11033 bool HasTemplateArgs, bool AllowTypoCorrection) { 11034 if (!AllowTypoCorrection) 11035 return llvm::make_unique<NoTypoCorrectionCCC>(); 11036 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 11037 HasTemplateArgs, ME); 11038 } 11039 11040 /// Attempts to recover from a call where no functions were found. 11041 /// 11042 /// Returns true if new candidates were found. 11043 static ExprResult 11044 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11045 UnresolvedLookupExpr *ULE, 11046 SourceLocation LParenLoc, 11047 MutableArrayRef<Expr *> Args, 11048 SourceLocation RParenLoc, 11049 bool EmptyLookup, bool AllowTypoCorrection) { 11050 // Do not try to recover if it is already building a recovery call. 11051 // This stops infinite loops for template instantiations like 11052 // 11053 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 11054 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 11055 // 11056 if (SemaRef.IsBuildingRecoveryCallExpr) 11057 return ExprError(); 11058 BuildRecoveryCallExprRAII RCE(SemaRef); 11059 11060 CXXScopeSpec SS; 11061 SS.Adopt(ULE->getQualifierLoc()); 11062 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11063 11064 TemplateArgumentListInfo TABuffer; 11065 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11066 if (ULE->hasExplicitTemplateArgs()) { 11067 ULE->copyTemplateArgumentsInto(TABuffer); 11068 ExplicitTemplateArgs = &TABuffer; 11069 } 11070 11071 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 11072 Sema::LookupOrdinaryName); 11073 bool DoDiagnoseEmptyLookup = EmptyLookup; 11074 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 11075 OverloadCandidateSet::CSK_Normal, 11076 ExplicitTemplateArgs, Args, 11077 &DoDiagnoseEmptyLookup) && 11078 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 11079 S, SS, R, 11080 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 11081 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 11082 ExplicitTemplateArgs, Args))) 11083 return ExprError(); 11084 11085 assert(!R.empty() && "lookup results empty despite recovery"); 11086 11087 // Build an implicit member call if appropriate. Just drop the 11088 // casts and such from the call, we don't really care. 11089 ExprResult NewFn = ExprError(); 11090 if ((*R.begin())->isCXXClassMember()) 11091 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 11092 ExplicitTemplateArgs, S); 11093 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 11094 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 11095 ExplicitTemplateArgs); 11096 else 11097 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 11098 11099 if (NewFn.isInvalid()) 11100 return ExprError(); 11101 11102 // This shouldn't cause an infinite loop because we're giving it 11103 // an expression with viable lookup results, which should never 11104 // end up here. 11105 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 11106 MultiExprArg(Args.data(), Args.size()), 11107 RParenLoc); 11108 } 11109 11110 /// \brief Constructs and populates an OverloadedCandidateSet from 11111 /// the given function. 11112 /// \returns true when an the ExprResult output parameter has been set. 11113 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 11114 UnresolvedLookupExpr *ULE, 11115 MultiExprArg Args, 11116 SourceLocation RParenLoc, 11117 OverloadCandidateSet *CandidateSet, 11118 ExprResult *Result) { 11119 #ifndef NDEBUG 11120 if (ULE->requiresADL()) { 11121 // To do ADL, we must have found an unqualified name. 11122 assert(!ULE->getQualifier() && "qualified name with ADL"); 11123 11124 // We don't perform ADL for implicit declarations of builtins. 11125 // Verify that this was correctly set up. 11126 FunctionDecl *F; 11127 if (ULE->decls_begin() + 1 == ULE->decls_end() && 11128 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 11129 F->getBuiltinID() && F->isImplicit()) 11130 llvm_unreachable("performing ADL for builtin"); 11131 11132 // We don't perform ADL in C. 11133 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 11134 } 11135 #endif 11136 11137 UnbridgedCastsSet UnbridgedCasts; 11138 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 11139 *Result = ExprError(); 11140 return true; 11141 } 11142 11143 // Add the functions denoted by the callee to the set of candidate 11144 // functions, including those from argument-dependent lookup. 11145 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 11146 11147 if (getLangOpts().MSVCCompat && 11148 CurContext->isDependentContext() && !isSFINAEContext() && 11149 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 11150 11151 OverloadCandidateSet::iterator Best; 11152 if (CandidateSet->empty() || 11153 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) == 11154 OR_No_Viable_Function) { 11155 // In Microsoft mode, if we are inside a template class member function then 11156 // create a type dependent CallExpr. The goal is to postpone name lookup 11157 // to instantiation time to be able to search into type dependent base 11158 // classes. 11159 CallExpr *CE = new (Context) CallExpr( 11160 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 11161 CE->setTypeDependent(true); 11162 CE->setValueDependent(true); 11163 CE->setInstantiationDependent(true); 11164 *Result = CE; 11165 return true; 11166 } 11167 } 11168 11169 if (CandidateSet->empty()) 11170 return false; 11171 11172 UnbridgedCasts.restore(); 11173 return false; 11174 } 11175 11176 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 11177 /// the completed call expression. If overload resolution fails, emits 11178 /// diagnostics and returns ExprError() 11179 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11180 UnresolvedLookupExpr *ULE, 11181 SourceLocation LParenLoc, 11182 MultiExprArg Args, 11183 SourceLocation RParenLoc, 11184 Expr *ExecConfig, 11185 OverloadCandidateSet *CandidateSet, 11186 OverloadCandidateSet::iterator *Best, 11187 OverloadingResult OverloadResult, 11188 bool AllowTypoCorrection) { 11189 if (CandidateSet->empty()) 11190 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 11191 RParenLoc, /*EmptyLookup=*/true, 11192 AllowTypoCorrection); 11193 11194 switch (OverloadResult) { 11195 case OR_Success: { 11196 FunctionDecl *FDecl = (*Best)->Function; 11197 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 11198 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 11199 return ExprError(); 11200 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11201 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11202 ExecConfig); 11203 } 11204 11205 case OR_No_Viable_Function: { 11206 // Try to recover by looking for viable functions which the user might 11207 // have meant to call. 11208 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 11209 Args, RParenLoc, 11210 /*EmptyLookup=*/false, 11211 AllowTypoCorrection); 11212 if (!Recovery.isInvalid()) 11213 return Recovery; 11214 11215 // If the user passes in a function that we can't take the address of, we 11216 // generally end up emitting really bad error messages. Here, we attempt to 11217 // emit better ones. 11218 for (const Expr *Arg : Args) { 11219 if (!Arg->getType()->isFunctionType()) 11220 continue; 11221 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 11222 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 11223 if (FD && 11224 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11225 Arg->getExprLoc())) 11226 return ExprError(); 11227 } 11228 } 11229 11230 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call) 11231 << ULE->getName() << Fn->getSourceRange(); 11232 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11233 break; 11234 } 11235 11236 case OR_Ambiguous: 11237 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 11238 << ULE->getName() << Fn->getSourceRange(); 11239 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 11240 break; 11241 11242 case OR_Deleted: { 11243 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 11244 << (*Best)->Function->isDeleted() 11245 << ULE->getName() 11246 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 11247 << Fn->getSourceRange(); 11248 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11249 11250 // We emitted an error for the unvailable/deleted function call but keep 11251 // the call in the AST. 11252 FunctionDecl *FDecl = (*Best)->Function; 11253 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11254 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11255 ExecConfig); 11256 } 11257 } 11258 11259 // Overload resolution failed. 11260 return ExprError(); 11261 } 11262 11263 static void markUnaddressableCandidatesUnviable(Sema &S, 11264 OverloadCandidateSet &CS) { 11265 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 11266 if (I->Viable && 11267 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 11268 I->Viable = false; 11269 I->FailureKind = ovl_fail_addr_not_available; 11270 } 11271 } 11272 } 11273 11274 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 11275 /// (which eventually refers to the declaration Func) and the call 11276 /// arguments Args/NumArgs, attempt to resolve the function call down 11277 /// to a specific function. If overload resolution succeeds, returns 11278 /// the call expression produced by overload resolution. 11279 /// Otherwise, emits diagnostics and returns ExprError. 11280 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 11281 UnresolvedLookupExpr *ULE, 11282 SourceLocation LParenLoc, 11283 MultiExprArg Args, 11284 SourceLocation RParenLoc, 11285 Expr *ExecConfig, 11286 bool AllowTypoCorrection, 11287 bool CalleesAddressIsTaken) { 11288 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 11289 OverloadCandidateSet::CSK_Normal); 11290 ExprResult result; 11291 11292 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 11293 &result)) 11294 return result; 11295 11296 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 11297 // functions that aren't addressible are considered unviable. 11298 if (CalleesAddressIsTaken) 11299 markUnaddressableCandidatesUnviable(*this, CandidateSet); 11300 11301 OverloadCandidateSet::iterator Best; 11302 OverloadingResult OverloadResult = 11303 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 11304 11305 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 11306 RParenLoc, ExecConfig, &CandidateSet, 11307 &Best, OverloadResult, 11308 AllowTypoCorrection); 11309 } 11310 11311 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 11312 return Functions.size() > 1 || 11313 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 11314 } 11315 11316 /// \brief Create a unary operation that may resolve to an overloaded 11317 /// operator. 11318 /// 11319 /// \param OpLoc The location of the operator itself (e.g., '*'). 11320 /// 11321 /// \param Opc The UnaryOperatorKind that describes this operator. 11322 /// 11323 /// \param Fns The set of non-member functions that will be 11324 /// considered by overload resolution. The caller needs to build this 11325 /// set based on the context using, e.g., 11326 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11327 /// set should not contain any member functions; those will be added 11328 /// by CreateOverloadedUnaryOp(). 11329 /// 11330 /// \param Input The input argument. 11331 ExprResult 11332 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 11333 const UnresolvedSetImpl &Fns, 11334 Expr *Input) { 11335 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 11336 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 11337 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11338 // TODO: provide better source location info. 11339 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11340 11341 if (checkPlaceholderForOverload(*this, Input)) 11342 return ExprError(); 11343 11344 Expr *Args[2] = { Input, nullptr }; 11345 unsigned NumArgs = 1; 11346 11347 // For post-increment and post-decrement, add the implicit '0' as 11348 // the second argument, so that we know this is a post-increment or 11349 // post-decrement. 11350 if (Opc == UO_PostInc || Opc == UO_PostDec) { 11351 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 11352 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 11353 SourceLocation()); 11354 NumArgs = 2; 11355 } 11356 11357 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 11358 11359 if (Input->isTypeDependent()) { 11360 if (Fns.empty()) 11361 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 11362 VK_RValue, OK_Ordinary, OpLoc); 11363 11364 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11365 UnresolvedLookupExpr *Fn 11366 = UnresolvedLookupExpr::Create(Context, NamingClass, 11367 NestedNameSpecifierLoc(), OpNameInfo, 11368 /*ADL*/ true, IsOverloaded(Fns), 11369 Fns.begin(), Fns.end()); 11370 return new (Context) 11371 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 11372 VK_RValue, OpLoc, false); 11373 } 11374 11375 // Build an empty overload set. 11376 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11377 11378 // Add the candidates from the given function set. 11379 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 11380 11381 // Add operator candidates that are member functions. 11382 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11383 11384 // Add candidates from ADL. 11385 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 11386 /*ExplicitTemplateArgs*/nullptr, 11387 CandidateSet); 11388 11389 // Add builtin operator candidates. 11390 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11391 11392 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11393 11394 // Perform overload resolution. 11395 OverloadCandidateSet::iterator Best; 11396 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11397 case OR_Success: { 11398 // We found a built-in operator or an overloaded operator. 11399 FunctionDecl *FnDecl = Best->Function; 11400 11401 if (FnDecl) { 11402 // We matched an overloaded operator. Build a call to that 11403 // operator. 11404 11405 // Convert the arguments. 11406 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11407 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 11408 11409 ExprResult InputRes = 11410 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 11411 Best->FoundDecl, Method); 11412 if (InputRes.isInvalid()) 11413 return ExprError(); 11414 Input = InputRes.get(); 11415 } else { 11416 // Convert the arguments. 11417 ExprResult InputInit 11418 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11419 Context, 11420 FnDecl->getParamDecl(0)), 11421 SourceLocation(), 11422 Input); 11423 if (InputInit.isInvalid()) 11424 return ExprError(); 11425 Input = InputInit.get(); 11426 } 11427 11428 // Build the actual expression node. 11429 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 11430 HadMultipleCandidates, OpLoc); 11431 if (FnExpr.isInvalid()) 11432 return ExprError(); 11433 11434 // Determine the result type. 11435 QualType ResultTy = FnDecl->getReturnType(); 11436 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11437 ResultTy = ResultTy.getNonLValueExprType(Context); 11438 11439 Args[0] = Input; 11440 CallExpr *TheCall = 11441 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 11442 ResultTy, VK, OpLoc, false); 11443 11444 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 11445 return ExprError(); 11446 11447 return MaybeBindToTemporary(TheCall); 11448 } else { 11449 // We matched a built-in operator. Convert the arguments, then 11450 // break out so that we will build the appropriate built-in 11451 // operator node. 11452 ExprResult InputRes = 11453 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 11454 Best->Conversions[0], AA_Passing); 11455 if (InputRes.isInvalid()) 11456 return ExprError(); 11457 Input = InputRes.get(); 11458 break; 11459 } 11460 } 11461 11462 case OR_No_Viable_Function: 11463 // This is an erroneous use of an operator which can be overloaded by 11464 // a non-member function. Check for non-member operators which were 11465 // defined too late to be candidates. 11466 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 11467 // FIXME: Recover by calling the found function. 11468 return ExprError(); 11469 11470 // No viable function; fall through to handling this as a 11471 // built-in operator, which will produce an error message for us. 11472 break; 11473 11474 case OR_Ambiguous: 11475 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11476 << UnaryOperator::getOpcodeStr(Opc) 11477 << Input->getType() 11478 << Input->getSourceRange(); 11479 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 11480 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11481 return ExprError(); 11482 11483 case OR_Deleted: 11484 Diag(OpLoc, diag::err_ovl_deleted_oper) 11485 << Best->Function->isDeleted() 11486 << UnaryOperator::getOpcodeStr(Opc) 11487 << getDeletedOrUnavailableSuffix(Best->Function) 11488 << Input->getSourceRange(); 11489 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 11490 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11491 return ExprError(); 11492 } 11493 11494 // Either we found no viable overloaded operator or we matched a 11495 // built-in operator. In either case, fall through to trying to 11496 // build a built-in operation. 11497 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11498 } 11499 11500 /// \brief Create a binary operation that may resolve to an overloaded 11501 /// operator. 11502 /// 11503 /// \param OpLoc The location of the operator itself (e.g., '+'). 11504 /// 11505 /// \param Opc The BinaryOperatorKind that describes this operator. 11506 /// 11507 /// \param Fns The set of non-member functions that will be 11508 /// considered by overload resolution. The caller needs to build this 11509 /// set based on the context using, e.g., 11510 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11511 /// set should not contain any member functions; those will be added 11512 /// by CreateOverloadedBinOp(). 11513 /// 11514 /// \param LHS Left-hand argument. 11515 /// \param RHS Right-hand argument. 11516 ExprResult 11517 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 11518 BinaryOperatorKind Opc, 11519 const UnresolvedSetImpl &Fns, 11520 Expr *LHS, Expr *RHS) { 11521 Expr *Args[2] = { LHS, RHS }; 11522 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 11523 11524 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 11525 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11526 11527 // If either side is type-dependent, create an appropriate dependent 11528 // expression. 11529 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11530 if (Fns.empty()) { 11531 // If there are no functions to store, just build a dependent 11532 // BinaryOperator or CompoundAssignment. 11533 if (Opc <= BO_Assign || Opc > BO_OrAssign) 11534 return new (Context) BinaryOperator( 11535 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 11536 OpLoc, FPFeatures.fp_contract); 11537 11538 return new (Context) CompoundAssignOperator( 11539 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 11540 Context.DependentTy, Context.DependentTy, OpLoc, 11541 FPFeatures.fp_contract); 11542 } 11543 11544 // FIXME: save results of ADL from here? 11545 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11546 // TODO: provide better source location info in DNLoc component. 11547 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11548 UnresolvedLookupExpr *Fn 11549 = UnresolvedLookupExpr::Create(Context, NamingClass, 11550 NestedNameSpecifierLoc(), OpNameInfo, 11551 /*ADL*/ true, IsOverloaded(Fns), 11552 Fns.begin(), Fns.end()); 11553 return new (Context) 11554 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 11555 VK_RValue, OpLoc, FPFeatures.fp_contract); 11556 } 11557 11558 // Always do placeholder-like conversions on the RHS. 11559 if (checkPlaceholderForOverload(*this, Args[1])) 11560 return ExprError(); 11561 11562 // Do placeholder-like conversion on the LHS; note that we should 11563 // not get here with a PseudoObject LHS. 11564 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 11565 if (checkPlaceholderForOverload(*this, Args[0])) 11566 return ExprError(); 11567 11568 // If this is the assignment operator, we only perform overload resolution 11569 // if the left-hand side is a class or enumeration type. This is actually 11570 // a hack. The standard requires that we do overload resolution between the 11571 // various built-in candidates, but as DR507 points out, this can lead to 11572 // problems. So we do it this way, which pretty much follows what GCC does. 11573 // Note that we go the traditional code path for compound assignment forms. 11574 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 11575 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11576 11577 // If this is the .* operator, which is not overloadable, just 11578 // create a built-in binary operator. 11579 if (Opc == BO_PtrMemD) 11580 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11581 11582 // Build an empty overload set. 11583 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11584 11585 // Add the candidates from the given function set. 11586 AddFunctionCandidates(Fns, Args, CandidateSet); 11587 11588 // Add operator candidates that are member functions. 11589 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11590 11591 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 11592 // performed for an assignment operator (nor for operator[] nor operator->, 11593 // which don't get here). 11594 if (Opc != BO_Assign) 11595 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 11596 /*ExplicitTemplateArgs*/ nullptr, 11597 CandidateSet); 11598 11599 // Add builtin operator candidates. 11600 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11601 11602 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11603 11604 // Perform overload resolution. 11605 OverloadCandidateSet::iterator Best; 11606 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11607 case OR_Success: { 11608 // We found a built-in operator or an overloaded operator. 11609 FunctionDecl *FnDecl = Best->Function; 11610 11611 if (FnDecl) { 11612 // We matched an overloaded operator. Build a call to that 11613 // operator. 11614 11615 // Convert the arguments. 11616 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11617 // Best->Access is only meaningful for class members. 11618 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 11619 11620 ExprResult Arg1 = 11621 PerformCopyInitialization( 11622 InitializedEntity::InitializeParameter(Context, 11623 FnDecl->getParamDecl(0)), 11624 SourceLocation(), Args[1]); 11625 if (Arg1.isInvalid()) 11626 return ExprError(); 11627 11628 ExprResult Arg0 = 11629 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11630 Best->FoundDecl, Method); 11631 if (Arg0.isInvalid()) 11632 return ExprError(); 11633 Args[0] = Arg0.getAs<Expr>(); 11634 Args[1] = RHS = Arg1.getAs<Expr>(); 11635 } else { 11636 // Convert the arguments. 11637 ExprResult Arg0 = PerformCopyInitialization( 11638 InitializedEntity::InitializeParameter(Context, 11639 FnDecl->getParamDecl(0)), 11640 SourceLocation(), Args[0]); 11641 if (Arg0.isInvalid()) 11642 return ExprError(); 11643 11644 ExprResult Arg1 = 11645 PerformCopyInitialization( 11646 InitializedEntity::InitializeParameter(Context, 11647 FnDecl->getParamDecl(1)), 11648 SourceLocation(), Args[1]); 11649 if (Arg1.isInvalid()) 11650 return ExprError(); 11651 Args[0] = LHS = Arg0.getAs<Expr>(); 11652 Args[1] = RHS = Arg1.getAs<Expr>(); 11653 } 11654 11655 // Build the actual expression node. 11656 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11657 Best->FoundDecl, 11658 HadMultipleCandidates, OpLoc); 11659 if (FnExpr.isInvalid()) 11660 return ExprError(); 11661 11662 // Determine the result type. 11663 QualType ResultTy = FnDecl->getReturnType(); 11664 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11665 ResultTy = ResultTy.getNonLValueExprType(Context); 11666 11667 CXXOperatorCallExpr *TheCall = 11668 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 11669 Args, ResultTy, VK, OpLoc, 11670 FPFeatures.fp_contract); 11671 11672 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 11673 FnDecl)) 11674 return ExprError(); 11675 11676 ArrayRef<const Expr *> ArgsArray(Args, 2); 11677 // Cut off the implicit 'this'. 11678 if (isa<CXXMethodDecl>(FnDecl)) 11679 ArgsArray = ArgsArray.slice(1); 11680 11681 // Check for a self move. 11682 if (Op == OO_Equal) 11683 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 11684 11685 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc, 11686 TheCall->getSourceRange(), VariadicDoesNotApply); 11687 11688 return MaybeBindToTemporary(TheCall); 11689 } else { 11690 // We matched a built-in operator. Convert the arguments, then 11691 // break out so that we will build the appropriate built-in 11692 // operator node. 11693 ExprResult ArgsRes0 = 11694 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11695 Best->Conversions[0], AA_Passing); 11696 if (ArgsRes0.isInvalid()) 11697 return ExprError(); 11698 Args[0] = ArgsRes0.get(); 11699 11700 ExprResult ArgsRes1 = 11701 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11702 Best->Conversions[1], AA_Passing); 11703 if (ArgsRes1.isInvalid()) 11704 return ExprError(); 11705 Args[1] = ArgsRes1.get(); 11706 break; 11707 } 11708 } 11709 11710 case OR_No_Viable_Function: { 11711 // C++ [over.match.oper]p9: 11712 // If the operator is the operator , [...] and there are no 11713 // viable functions, then the operator is assumed to be the 11714 // built-in operator and interpreted according to clause 5. 11715 if (Opc == BO_Comma) 11716 break; 11717 11718 // For class as left operand for assignment or compound assigment 11719 // operator do not fall through to handling in built-in, but report that 11720 // no overloaded assignment operator found 11721 ExprResult Result = ExprError(); 11722 if (Args[0]->getType()->isRecordType() && 11723 Opc >= BO_Assign && Opc <= BO_OrAssign) { 11724 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11725 << BinaryOperator::getOpcodeStr(Opc) 11726 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11727 if (Args[0]->getType()->isIncompleteType()) { 11728 Diag(OpLoc, diag::note_assign_lhs_incomplete) 11729 << Args[0]->getType() 11730 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11731 } 11732 } else { 11733 // This is an erroneous use of an operator which can be overloaded by 11734 // a non-member function. Check for non-member operators which were 11735 // defined too late to be candidates. 11736 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 11737 // FIXME: Recover by calling the found function. 11738 return ExprError(); 11739 11740 // No viable function; try to create a built-in operation, which will 11741 // produce an error. Then, show the non-viable candidates. 11742 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11743 } 11744 assert(Result.isInvalid() && 11745 "C++ binary operator overloading is missing candidates!"); 11746 if (Result.isInvalid()) 11747 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11748 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11749 return Result; 11750 } 11751 11752 case OR_Ambiguous: 11753 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 11754 << BinaryOperator::getOpcodeStr(Opc) 11755 << Args[0]->getType() << Args[1]->getType() 11756 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11757 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11758 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11759 return ExprError(); 11760 11761 case OR_Deleted: 11762 if (isImplicitlyDeleted(Best->Function)) { 11763 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11764 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 11765 << Context.getRecordType(Method->getParent()) 11766 << getSpecialMember(Method); 11767 11768 // The user probably meant to call this special member. Just 11769 // explain why it's deleted. 11770 NoteDeletedFunction(Method); 11771 return ExprError(); 11772 } else { 11773 Diag(OpLoc, diag::err_ovl_deleted_oper) 11774 << Best->Function->isDeleted() 11775 << BinaryOperator::getOpcodeStr(Opc) 11776 << getDeletedOrUnavailableSuffix(Best->Function) 11777 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11778 } 11779 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11780 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11781 return ExprError(); 11782 } 11783 11784 // We matched a built-in operator; build it. 11785 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11786 } 11787 11788 ExprResult 11789 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 11790 SourceLocation RLoc, 11791 Expr *Base, Expr *Idx) { 11792 Expr *Args[2] = { Base, Idx }; 11793 DeclarationName OpName = 11794 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 11795 11796 // If either side is type-dependent, create an appropriate dependent 11797 // expression. 11798 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11799 11800 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11801 // CHECKME: no 'operator' keyword? 11802 DeclarationNameInfo OpNameInfo(OpName, LLoc); 11803 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11804 UnresolvedLookupExpr *Fn 11805 = UnresolvedLookupExpr::Create(Context, NamingClass, 11806 NestedNameSpecifierLoc(), OpNameInfo, 11807 /*ADL*/ true, /*Overloaded*/ false, 11808 UnresolvedSetIterator(), 11809 UnresolvedSetIterator()); 11810 // Can't add any actual overloads yet 11811 11812 return new (Context) 11813 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 11814 Context.DependentTy, VK_RValue, RLoc, false); 11815 } 11816 11817 // Handle placeholders on both operands. 11818 if (checkPlaceholderForOverload(*this, Args[0])) 11819 return ExprError(); 11820 if (checkPlaceholderForOverload(*this, Args[1])) 11821 return ExprError(); 11822 11823 // Build an empty overload set. 11824 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 11825 11826 // Subscript can only be overloaded as a member function. 11827 11828 // Add operator candidates that are member functions. 11829 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11830 11831 // Add builtin operator candidates. 11832 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11833 11834 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11835 11836 // Perform overload resolution. 11837 OverloadCandidateSet::iterator Best; 11838 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 11839 case OR_Success: { 11840 // We found a built-in operator or an overloaded operator. 11841 FunctionDecl *FnDecl = Best->Function; 11842 11843 if (FnDecl) { 11844 // We matched an overloaded operator. Build a call to that 11845 // operator. 11846 11847 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 11848 11849 // Convert the arguments. 11850 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 11851 ExprResult Arg0 = 11852 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11853 Best->FoundDecl, Method); 11854 if (Arg0.isInvalid()) 11855 return ExprError(); 11856 Args[0] = Arg0.get(); 11857 11858 // Convert the arguments. 11859 ExprResult InputInit 11860 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11861 Context, 11862 FnDecl->getParamDecl(0)), 11863 SourceLocation(), 11864 Args[1]); 11865 if (InputInit.isInvalid()) 11866 return ExprError(); 11867 11868 Args[1] = InputInit.getAs<Expr>(); 11869 11870 // Build the actual expression node. 11871 DeclarationNameInfo OpLocInfo(OpName, LLoc); 11872 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11873 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11874 Best->FoundDecl, 11875 HadMultipleCandidates, 11876 OpLocInfo.getLoc(), 11877 OpLocInfo.getInfo()); 11878 if (FnExpr.isInvalid()) 11879 return ExprError(); 11880 11881 // Determine the result type 11882 QualType ResultTy = FnDecl->getReturnType(); 11883 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11884 ResultTy = ResultTy.getNonLValueExprType(Context); 11885 11886 CXXOperatorCallExpr *TheCall = 11887 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 11888 FnExpr.get(), Args, 11889 ResultTy, VK, RLoc, 11890 false); 11891 11892 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 11893 return ExprError(); 11894 11895 return MaybeBindToTemporary(TheCall); 11896 } else { 11897 // We matched a built-in operator. Convert the arguments, then 11898 // break out so that we will build the appropriate built-in 11899 // operator node. 11900 ExprResult ArgsRes0 = 11901 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11902 Best->Conversions[0], AA_Passing); 11903 if (ArgsRes0.isInvalid()) 11904 return ExprError(); 11905 Args[0] = ArgsRes0.get(); 11906 11907 ExprResult ArgsRes1 = 11908 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11909 Best->Conversions[1], AA_Passing); 11910 if (ArgsRes1.isInvalid()) 11911 return ExprError(); 11912 Args[1] = ArgsRes1.get(); 11913 11914 break; 11915 } 11916 } 11917 11918 case OR_No_Viable_Function: { 11919 if (CandidateSet.empty()) 11920 Diag(LLoc, diag::err_ovl_no_oper) 11921 << Args[0]->getType() << /*subscript*/ 0 11922 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11923 else 11924 Diag(LLoc, diag::err_ovl_no_viable_subscript) 11925 << Args[0]->getType() 11926 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11927 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11928 "[]", LLoc); 11929 return ExprError(); 11930 } 11931 11932 case OR_Ambiguous: 11933 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 11934 << "[]" 11935 << Args[0]->getType() << Args[1]->getType() 11936 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11937 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11938 "[]", LLoc); 11939 return ExprError(); 11940 11941 case OR_Deleted: 11942 Diag(LLoc, diag::err_ovl_deleted_oper) 11943 << Best->Function->isDeleted() << "[]" 11944 << getDeletedOrUnavailableSuffix(Best->Function) 11945 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11946 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11947 "[]", LLoc); 11948 return ExprError(); 11949 } 11950 11951 // We matched a built-in operator; build it. 11952 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 11953 } 11954 11955 /// BuildCallToMemberFunction - Build a call to a member 11956 /// function. MemExpr is the expression that refers to the member 11957 /// function (and includes the object parameter), Args/NumArgs are the 11958 /// arguments to the function call (not including the object 11959 /// parameter). The caller needs to validate that the member 11960 /// expression refers to a non-static member function or an overloaded 11961 /// member function. 11962 ExprResult 11963 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 11964 SourceLocation LParenLoc, 11965 MultiExprArg Args, 11966 SourceLocation RParenLoc) { 11967 assert(MemExprE->getType() == Context.BoundMemberTy || 11968 MemExprE->getType() == Context.OverloadTy); 11969 11970 // Dig out the member expression. This holds both the object 11971 // argument and the member function we're referring to. 11972 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 11973 11974 // Determine whether this is a call to a pointer-to-member function. 11975 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 11976 assert(op->getType() == Context.BoundMemberTy); 11977 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 11978 11979 QualType fnType = 11980 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 11981 11982 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 11983 QualType resultType = proto->getCallResultType(Context); 11984 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 11985 11986 // Check that the object type isn't more qualified than the 11987 // member function we're calling. 11988 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 11989 11990 QualType objectType = op->getLHS()->getType(); 11991 if (op->getOpcode() == BO_PtrMemI) 11992 objectType = objectType->castAs<PointerType>()->getPointeeType(); 11993 Qualifiers objectQuals = objectType.getQualifiers(); 11994 11995 Qualifiers difference = objectQuals - funcQuals; 11996 difference.removeObjCGCAttr(); 11997 difference.removeAddressSpace(); 11998 if (difference) { 11999 std::string qualsString = difference.getAsString(); 12000 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12001 << fnType.getUnqualifiedType() 12002 << qualsString 12003 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12004 } 12005 12006 CXXMemberCallExpr *call 12007 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12008 resultType, valueKind, RParenLoc); 12009 12010 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 12011 call, nullptr)) 12012 return ExprError(); 12013 12014 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12015 return ExprError(); 12016 12017 if (CheckOtherCall(call, proto)) 12018 return ExprError(); 12019 12020 return MaybeBindToTemporary(call); 12021 } 12022 12023 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 12024 return new (Context) 12025 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 12026 12027 UnbridgedCastsSet UnbridgedCasts; 12028 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12029 return ExprError(); 12030 12031 MemberExpr *MemExpr; 12032 CXXMethodDecl *Method = nullptr; 12033 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 12034 NestedNameSpecifier *Qualifier = nullptr; 12035 if (isa<MemberExpr>(NakedMemExpr)) { 12036 MemExpr = cast<MemberExpr>(NakedMemExpr); 12037 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 12038 FoundDecl = MemExpr->getFoundDecl(); 12039 Qualifier = MemExpr->getQualifier(); 12040 UnbridgedCasts.restore(); 12041 } else { 12042 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 12043 Qualifier = UnresExpr->getQualifier(); 12044 12045 QualType ObjectType = UnresExpr->getBaseType(); 12046 Expr::Classification ObjectClassification 12047 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 12048 : UnresExpr->getBase()->Classify(Context); 12049 12050 // Add overload candidates 12051 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 12052 OverloadCandidateSet::CSK_Normal); 12053 12054 // FIXME: avoid copy. 12055 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12056 if (UnresExpr->hasExplicitTemplateArgs()) { 12057 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12058 TemplateArgs = &TemplateArgsBuffer; 12059 } 12060 12061 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 12062 E = UnresExpr->decls_end(); I != E; ++I) { 12063 12064 NamedDecl *Func = *I; 12065 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 12066 if (isa<UsingShadowDecl>(Func)) 12067 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 12068 12069 12070 // Microsoft supports direct constructor calls. 12071 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 12072 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 12073 Args, CandidateSet); 12074 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 12075 // If explicit template arguments were provided, we can't call a 12076 // non-template member function. 12077 if (TemplateArgs) 12078 continue; 12079 12080 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 12081 ObjectClassification, Args, CandidateSet, 12082 /*SuppressUserConversions=*/false); 12083 } else { 12084 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 12085 I.getPair(), ActingDC, TemplateArgs, 12086 ObjectType, ObjectClassification, 12087 Args, CandidateSet, 12088 /*SuppressUsedConversions=*/false); 12089 } 12090 } 12091 12092 DeclarationName DeclName = UnresExpr->getMemberName(); 12093 12094 UnbridgedCasts.restore(); 12095 12096 OverloadCandidateSet::iterator Best; 12097 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 12098 Best)) { 12099 case OR_Success: 12100 Method = cast<CXXMethodDecl>(Best->Function); 12101 FoundDecl = Best->FoundDecl; 12102 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 12103 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 12104 return ExprError(); 12105 // If FoundDecl is different from Method (such as if one is a template 12106 // and the other a specialization), make sure DiagnoseUseOfDecl is 12107 // called on both. 12108 // FIXME: This would be more comprehensively addressed by modifying 12109 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 12110 // being used. 12111 if (Method != FoundDecl.getDecl() && 12112 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 12113 return ExprError(); 12114 break; 12115 12116 case OR_No_Viable_Function: 12117 Diag(UnresExpr->getMemberLoc(), 12118 diag::err_ovl_no_viable_member_function_in_call) 12119 << DeclName << MemExprE->getSourceRange(); 12120 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12121 // FIXME: Leaking incoming expressions! 12122 return ExprError(); 12123 12124 case OR_Ambiguous: 12125 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 12126 << DeclName << MemExprE->getSourceRange(); 12127 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12128 // FIXME: Leaking incoming expressions! 12129 return ExprError(); 12130 12131 case OR_Deleted: 12132 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 12133 << Best->Function->isDeleted() 12134 << DeclName 12135 << getDeletedOrUnavailableSuffix(Best->Function) 12136 << MemExprE->getSourceRange(); 12137 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12138 // FIXME: Leaking incoming expressions! 12139 return ExprError(); 12140 } 12141 12142 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 12143 12144 // If overload resolution picked a static member, build a 12145 // non-member call based on that function. 12146 if (Method->isStatic()) { 12147 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 12148 RParenLoc); 12149 } 12150 12151 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 12152 } 12153 12154 QualType ResultType = Method->getReturnType(); 12155 ExprValueKind VK = Expr::getValueKindForType(ResultType); 12156 ResultType = ResultType.getNonLValueExprType(Context); 12157 12158 assert(Method && "Member call to something that isn't a method?"); 12159 CXXMemberCallExpr *TheCall = 12160 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12161 ResultType, VK, RParenLoc); 12162 12163 // (CUDA B.1): Check for invalid calls between targets. 12164 if (getLangOpts().CUDA) { 12165 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) { 12166 if (CheckCUDATarget(Caller, Method)) { 12167 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target) 12168 << IdentifyCUDATarget(Method) << Method->getIdentifier() 12169 << IdentifyCUDATarget(Caller); 12170 return ExprError(); 12171 } 12172 } 12173 } 12174 12175 // Check for a valid return type. 12176 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 12177 TheCall, Method)) 12178 return ExprError(); 12179 12180 // Convert the object argument (for a non-static member function call). 12181 // We only need to do this if there was actually an overload; otherwise 12182 // it was done at lookup. 12183 if (!Method->isStatic()) { 12184 ExprResult ObjectArg = 12185 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 12186 FoundDecl, Method); 12187 if (ObjectArg.isInvalid()) 12188 return ExprError(); 12189 MemExpr->setBase(ObjectArg.get()); 12190 } 12191 12192 // Convert the rest of the arguments 12193 const FunctionProtoType *Proto = 12194 Method->getType()->getAs<FunctionProtoType>(); 12195 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 12196 RParenLoc)) 12197 return ExprError(); 12198 12199 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12200 12201 if (CheckFunctionCall(Method, TheCall, Proto)) 12202 return ExprError(); 12203 12204 // In the case the method to call was not selected by the overloading 12205 // resolution process, we still need to handle the enable_if attribute. Do 12206 // that here, so it will not hide previous -- and more relevant -- errors 12207 if (isa<MemberExpr>(NakedMemExpr)) { 12208 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 12209 Diag(MemExprE->getLocStart(), 12210 diag::err_ovl_no_viable_member_function_in_call) 12211 << Method << Method->getSourceRange(); 12212 Diag(Method->getLocation(), 12213 diag::note_ovl_candidate_disabled_by_enable_if_attr) 12214 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 12215 return ExprError(); 12216 } 12217 } 12218 12219 if ((isa<CXXConstructorDecl>(CurContext) || 12220 isa<CXXDestructorDecl>(CurContext)) && 12221 TheCall->getMethodDecl()->isPure()) { 12222 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 12223 12224 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 12225 MemExpr->performsVirtualDispatch(getLangOpts())) { 12226 Diag(MemExpr->getLocStart(), 12227 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 12228 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 12229 << MD->getParent()->getDeclName(); 12230 12231 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 12232 if (getLangOpts().AppleKext) 12233 Diag(MemExpr->getLocStart(), 12234 diag::note_pure_qualified_call_kext) 12235 << MD->getParent()->getDeclName() 12236 << MD->getDeclName(); 12237 } 12238 } 12239 12240 if (CXXDestructorDecl *DD = 12241 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 12242 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 12243 bool CallCanBeVirtual = !cast<MemberExpr>(NakedMemExpr)->hasQualifier() || 12244 getLangOpts().AppleKext; 12245 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false, 12246 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 12247 MemExpr->getMemberLoc()); 12248 } 12249 12250 return MaybeBindToTemporary(TheCall); 12251 } 12252 12253 /// BuildCallToObjectOfClassType - Build a call to an object of class 12254 /// type (C++ [over.call.object]), which can end up invoking an 12255 /// overloaded function call operator (@c operator()) or performing a 12256 /// user-defined conversion on the object argument. 12257 ExprResult 12258 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 12259 SourceLocation LParenLoc, 12260 MultiExprArg Args, 12261 SourceLocation RParenLoc) { 12262 if (checkPlaceholderForOverload(*this, Obj)) 12263 return ExprError(); 12264 ExprResult Object = Obj; 12265 12266 UnbridgedCastsSet UnbridgedCasts; 12267 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12268 return ExprError(); 12269 12270 assert(Object.get()->getType()->isRecordType() && 12271 "Requires object type argument"); 12272 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 12273 12274 // C++ [over.call.object]p1: 12275 // If the primary-expression E in the function call syntax 12276 // evaluates to a class object of type "cv T", then the set of 12277 // candidate functions includes at least the function call 12278 // operators of T. The function call operators of T are obtained by 12279 // ordinary lookup of the name operator() in the context of 12280 // (E).operator(). 12281 OverloadCandidateSet CandidateSet(LParenLoc, 12282 OverloadCandidateSet::CSK_Operator); 12283 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 12284 12285 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 12286 diag::err_incomplete_object_call, Object.get())) 12287 return true; 12288 12289 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 12290 LookupQualifiedName(R, Record->getDecl()); 12291 R.suppressDiagnostics(); 12292 12293 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12294 Oper != OperEnd; ++Oper) { 12295 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 12296 Object.get()->Classify(Context), 12297 Args, CandidateSet, 12298 /*SuppressUserConversions=*/ false); 12299 } 12300 12301 // C++ [over.call.object]p2: 12302 // In addition, for each (non-explicit in C++0x) conversion function 12303 // declared in T of the form 12304 // 12305 // operator conversion-type-id () cv-qualifier; 12306 // 12307 // where cv-qualifier is the same cv-qualification as, or a 12308 // greater cv-qualification than, cv, and where conversion-type-id 12309 // denotes the type "pointer to function of (P1,...,Pn) returning 12310 // R", or the type "reference to pointer to function of 12311 // (P1,...,Pn) returning R", or the type "reference to function 12312 // of (P1,...,Pn) returning R", a surrogate call function [...] 12313 // is also considered as a candidate function. Similarly, 12314 // surrogate call functions are added to the set of candidate 12315 // functions for each conversion function declared in an 12316 // accessible base class provided the function is not hidden 12317 // within T by another intervening declaration. 12318 const auto &Conversions = 12319 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 12320 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 12321 NamedDecl *D = *I; 12322 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 12323 if (isa<UsingShadowDecl>(D)) 12324 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 12325 12326 // Skip over templated conversion functions; they aren't 12327 // surrogates. 12328 if (isa<FunctionTemplateDecl>(D)) 12329 continue; 12330 12331 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 12332 if (!Conv->isExplicit()) { 12333 // Strip the reference type (if any) and then the pointer type (if 12334 // any) to get down to what might be a function type. 12335 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 12336 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 12337 ConvType = ConvPtrType->getPointeeType(); 12338 12339 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 12340 { 12341 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 12342 Object.get(), Args, CandidateSet); 12343 } 12344 } 12345 } 12346 12347 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12348 12349 // Perform overload resolution. 12350 OverloadCandidateSet::iterator Best; 12351 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 12352 Best)) { 12353 case OR_Success: 12354 // Overload resolution succeeded; we'll build the appropriate call 12355 // below. 12356 break; 12357 12358 case OR_No_Viable_Function: 12359 if (CandidateSet.empty()) 12360 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 12361 << Object.get()->getType() << /*call*/ 1 12362 << Object.get()->getSourceRange(); 12363 else 12364 Diag(Object.get()->getLocStart(), 12365 diag::err_ovl_no_viable_object_call) 12366 << Object.get()->getType() << Object.get()->getSourceRange(); 12367 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12368 break; 12369 12370 case OR_Ambiguous: 12371 Diag(Object.get()->getLocStart(), 12372 diag::err_ovl_ambiguous_object_call) 12373 << Object.get()->getType() << Object.get()->getSourceRange(); 12374 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12375 break; 12376 12377 case OR_Deleted: 12378 Diag(Object.get()->getLocStart(), 12379 diag::err_ovl_deleted_object_call) 12380 << Best->Function->isDeleted() 12381 << Object.get()->getType() 12382 << getDeletedOrUnavailableSuffix(Best->Function) 12383 << Object.get()->getSourceRange(); 12384 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12385 break; 12386 } 12387 12388 if (Best == CandidateSet.end()) 12389 return true; 12390 12391 UnbridgedCasts.restore(); 12392 12393 if (Best->Function == nullptr) { 12394 // Since there is no function declaration, this is one of the 12395 // surrogate candidates. Dig out the conversion function. 12396 CXXConversionDecl *Conv 12397 = cast<CXXConversionDecl>( 12398 Best->Conversions[0].UserDefined.ConversionFunction); 12399 12400 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 12401 Best->FoundDecl); 12402 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 12403 return ExprError(); 12404 assert(Conv == Best->FoundDecl.getDecl() && 12405 "Found Decl & conversion-to-functionptr should be same, right?!"); 12406 // We selected one of the surrogate functions that converts the 12407 // object parameter to a function pointer. Perform the conversion 12408 // on the object argument, then let ActOnCallExpr finish the job. 12409 12410 // Create an implicit member expr to refer to the conversion operator. 12411 // and then call it. 12412 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 12413 Conv, HadMultipleCandidates); 12414 if (Call.isInvalid()) 12415 return ExprError(); 12416 // Record usage of conversion in an implicit cast. 12417 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 12418 CK_UserDefinedConversion, Call.get(), 12419 nullptr, VK_RValue); 12420 12421 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 12422 } 12423 12424 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 12425 12426 // We found an overloaded operator(). Build a CXXOperatorCallExpr 12427 // that calls this method, using Object for the implicit object 12428 // parameter and passing along the remaining arguments. 12429 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12430 12431 // An error diagnostic has already been printed when parsing the declaration. 12432 if (Method->isInvalidDecl()) 12433 return ExprError(); 12434 12435 const FunctionProtoType *Proto = 12436 Method->getType()->getAs<FunctionProtoType>(); 12437 12438 unsigned NumParams = Proto->getNumParams(); 12439 12440 DeclarationNameInfo OpLocInfo( 12441 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 12442 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 12443 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12444 HadMultipleCandidates, 12445 OpLocInfo.getLoc(), 12446 OpLocInfo.getInfo()); 12447 if (NewFn.isInvalid()) 12448 return true; 12449 12450 // Build the full argument list for the method call (the implicit object 12451 // parameter is placed at the beginning of the list). 12452 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]); 12453 MethodArgs[0] = Object.get(); 12454 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 12455 12456 // Once we've built TheCall, all of the expressions are properly 12457 // owned. 12458 QualType ResultTy = Method->getReturnType(); 12459 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12460 ResultTy = ResultTy.getNonLValueExprType(Context); 12461 12462 CXXOperatorCallExpr *TheCall = new (Context) 12463 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), 12464 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 12465 ResultTy, VK, RParenLoc, false); 12466 MethodArgs.reset(); 12467 12468 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 12469 return true; 12470 12471 // We may have default arguments. If so, we need to allocate more 12472 // slots in the call for them. 12473 if (Args.size() < NumParams) 12474 TheCall->setNumArgs(Context, NumParams + 1); 12475 12476 bool IsError = false; 12477 12478 // Initialize the implicit object parameter. 12479 ExprResult ObjRes = 12480 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 12481 Best->FoundDecl, Method); 12482 if (ObjRes.isInvalid()) 12483 IsError = true; 12484 else 12485 Object = ObjRes; 12486 TheCall->setArg(0, Object.get()); 12487 12488 // Check the argument types. 12489 for (unsigned i = 0; i != NumParams; i++) { 12490 Expr *Arg; 12491 if (i < Args.size()) { 12492 Arg = Args[i]; 12493 12494 // Pass the argument. 12495 12496 ExprResult InputInit 12497 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12498 Context, 12499 Method->getParamDecl(i)), 12500 SourceLocation(), Arg); 12501 12502 IsError |= InputInit.isInvalid(); 12503 Arg = InputInit.getAs<Expr>(); 12504 } else { 12505 ExprResult DefArg 12506 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 12507 if (DefArg.isInvalid()) { 12508 IsError = true; 12509 break; 12510 } 12511 12512 Arg = DefArg.getAs<Expr>(); 12513 } 12514 12515 TheCall->setArg(i + 1, Arg); 12516 } 12517 12518 // If this is a variadic call, handle args passed through "...". 12519 if (Proto->isVariadic()) { 12520 // Promote the arguments (C99 6.5.2.2p7). 12521 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 12522 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 12523 nullptr); 12524 IsError |= Arg.isInvalid(); 12525 TheCall->setArg(i + 1, Arg.get()); 12526 } 12527 } 12528 12529 if (IsError) return true; 12530 12531 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12532 12533 if (CheckFunctionCall(Method, TheCall, Proto)) 12534 return true; 12535 12536 return MaybeBindToTemporary(TheCall); 12537 } 12538 12539 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 12540 /// (if one exists), where @c Base is an expression of class type and 12541 /// @c Member is the name of the member we're trying to find. 12542 ExprResult 12543 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 12544 bool *NoArrowOperatorFound) { 12545 assert(Base->getType()->isRecordType() && 12546 "left-hand side must have class type"); 12547 12548 if (checkPlaceholderForOverload(*this, Base)) 12549 return ExprError(); 12550 12551 SourceLocation Loc = Base->getExprLoc(); 12552 12553 // C++ [over.ref]p1: 12554 // 12555 // [...] An expression x->m is interpreted as (x.operator->())->m 12556 // for a class object x of type T if T::operator->() exists and if 12557 // the operator is selected as the best match function by the 12558 // overload resolution mechanism (13.3). 12559 DeclarationName OpName = 12560 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 12561 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 12562 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 12563 12564 if (RequireCompleteType(Loc, Base->getType(), 12565 diag::err_typecheck_incomplete_tag, Base)) 12566 return ExprError(); 12567 12568 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 12569 LookupQualifiedName(R, BaseRecord->getDecl()); 12570 R.suppressDiagnostics(); 12571 12572 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12573 Oper != OperEnd; ++Oper) { 12574 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 12575 None, CandidateSet, /*SuppressUserConversions=*/false); 12576 } 12577 12578 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12579 12580 // Perform overload resolution. 12581 OverloadCandidateSet::iterator Best; 12582 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12583 case OR_Success: 12584 // Overload resolution succeeded; we'll build the call below. 12585 break; 12586 12587 case OR_No_Viable_Function: 12588 if (CandidateSet.empty()) { 12589 QualType BaseType = Base->getType(); 12590 if (NoArrowOperatorFound) { 12591 // Report this specific error to the caller instead of emitting a 12592 // diagnostic, as requested. 12593 *NoArrowOperatorFound = true; 12594 return ExprError(); 12595 } 12596 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 12597 << BaseType << Base->getSourceRange(); 12598 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 12599 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 12600 << FixItHint::CreateReplacement(OpLoc, "."); 12601 } 12602 } else 12603 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12604 << "operator->" << Base->getSourceRange(); 12605 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12606 return ExprError(); 12607 12608 case OR_Ambiguous: 12609 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12610 << "->" << Base->getType() << Base->getSourceRange(); 12611 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 12612 return ExprError(); 12613 12614 case OR_Deleted: 12615 Diag(OpLoc, diag::err_ovl_deleted_oper) 12616 << Best->Function->isDeleted() 12617 << "->" 12618 << getDeletedOrUnavailableSuffix(Best->Function) 12619 << Base->getSourceRange(); 12620 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12621 return ExprError(); 12622 } 12623 12624 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 12625 12626 // Convert the object parameter. 12627 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12628 ExprResult BaseResult = 12629 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 12630 Best->FoundDecl, Method); 12631 if (BaseResult.isInvalid()) 12632 return ExprError(); 12633 Base = BaseResult.get(); 12634 12635 // Build the operator call. 12636 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12637 HadMultipleCandidates, OpLoc); 12638 if (FnExpr.isInvalid()) 12639 return ExprError(); 12640 12641 QualType ResultTy = Method->getReturnType(); 12642 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12643 ResultTy = ResultTy.getNonLValueExprType(Context); 12644 CXXOperatorCallExpr *TheCall = 12645 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 12646 Base, ResultTy, VK, OpLoc, false); 12647 12648 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 12649 return ExprError(); 12650 12651 return MaybeBindToTemporary(TheCall); 12652 } 12653 12654 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 12655 /// a literal operator described by the provided lookup results. 12656 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 12657 DeclarationNameInfo &SuffixInfo, 12658 ArrayRef<Expr*> Args, 12659 SourceLocation LitEndLoc, 12660 TemplateArgumentListInfo *TemplateArgs) { 12661 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 12662 12663 OverloadCandidateSet CandidateSet(UDSuffixLoc, 12664 OverloadCandidateSet::CSK_Normal); 12665 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 12666 /*SuppressUserConversions=*/true); 12667 12668 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12669 12670 // Perform overload resolution. This will usually be trivial, but might need 12671 // to perform substitutions for a literal operator template. 12672 OverloadCandidateSet::iterator Best; 12673 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 12674 case OR_Success: 12675 case OR_Deleted: 12676 break; 12677 12678 case OR_No_Viable_Function: 12679 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 12680 << R.getLookupName(); 12681 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12682 return ExprError(); 12683 12684 case OR_Ambiguous: 12685 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 12686 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12687 return ExprError(); 12688 } 12689 12690 FunctionDecl *FD = Best->Function; 12691 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 12692 HadMultipleCandidates, 12693 SuffixInfo.getLoc(), 12694 SuffixInfo.getInfo()); 12695 if (Fn.isInvalid()) 12696 return true; 12697 12698 // Check the argument types. This should almost always be a no-op, except 12699 // that array-to-pointer decay is applied to string literals. 12700 Expr *ConvArgs[2]; 12701 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 12702 ExprResult InputInit = PerformCopyInitialization( 12703 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 12704 SourceLocation(), Args[ArgIdx]); 12705 if (InputInit.isInvalid()) 12706 return true; 12707 ConvArgs[ArgIdx] = InputInit.get(); 12708 } 12709 12710 QualType ResultTy = FD->getReturnType(); 12711 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12712 ResultTy = ResultTy.getNonLValueExprType(Context); 12713 12714 UserDefinedLiteral *UDL = 12715 new (Context) UserDefinedLiteral(Context, Fn.get(), 12716 llvm::makeArrayRef(ConvArgs, Args.size()), 12717 ResultTy, VK, LitEndLoc, UDSuffixLoc); 12718 12719 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 12720 return ExprError(); 12721 12722 if (CheckFunctionCall(FD, UDL, nullptr)) 12723 return ExprError(); 12724 12725 return MaybeBindToTemporary(UDL); 12726 } 12727 12728 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 12729 /// given LookupResult is non-empty, it is assumed to describe a member which 12730 /// will be invoked. Otherwise, the function will be found via argument 12731 /// dependent lookup. 12732 /// CallExpr is set to a valid expression and FRS_Success returned on success, 12733 /// otherwise CallExpr is set to ExprError() and some non-success value 12734 /// is returned. 12735 Sema::ForRangeStatus 12736 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 12737 SourceLocation RangeLoc, 12738 const DeclarationNameInfo &NameInfo, 12739 LookupResult &MemberLookup, 12740 OverloadCandidateSet *CandidateSet, 12741 Expr *Range, ExprResult *CallExpr) { 12742 Scope *S = nullptr; 12743 12744 CandidateSet->clear(); 12745 if (!MemberLookup.empty()) { 12746 ExprResult MemberRef = 12747 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 12748 /*IsPtr=*/false, CXXScopeSpec(), 12749 /*TemplateKWLoc=*/SourceLocation(), 12750 /*FirstQualifierInScope=*/nullptr, 12751 MemberLookup, 12752 /*TemplateArgs=*/nullptr, S); 12753 if (MemberRef.isInvalid()) { 12754 *CallExpr = ExprError(); 12755 return FRS_DiagnosticIssued; 12756 } 12757 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 12758 if (CallExpr->isInvalid()) { 12759 *CallExpr = ExprError(); 12760 return FRS_DiagnosticIssued; 12761 } 12762 } else { 12763 UnresolvedSet<0> FoundNames; 12764 UnresolvedLookupExpr *Fn = 12765 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 12766 NestedNameSpecifierLoc(), NameInfo, 12767 /*NeedsADL=*/true, /*Overloaded=*/false, 12768 FoundNames.begin(), FoundNames.end()); 12769 12770 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 12771 CandidateSet, CallExpr); 12772 if (CandidateSet->empty() || CandidateSetError) { 12773 *CallExpr = ExprError(); 12774 return FRS_NoViableFunction; 12775 } 12776 OverloadCandidateSet::iterator Best; 12777 OverloadingResult OverloadResult = 12778 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 12779 12780 if (OverloadResult == OR_No_Viable_Function) { 12781 *CallExpr = ExprError(); 12782 return FRS_NoViableFunction; 12783 } 12784 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 12785 Loc, nullptr, CandidateSet, &Best, 12786 OverloadResult, 12787 /*AllowTypoCorrection=*/false); 12788 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 12789 *CallExpr = ExprError(); 12790 return FRS_DiagnosticIssued; 12791 } 12792 } 12793 return FRS_Success; 12794 } 12795 12796 12797 /// FixOverloadedFunctionReference - E is an expression that refers to 12798 /// a C++ overloaded function (possibly with some parentheses and 12799 /// perhaps a '&' around it). We have resolved the overloaded function 12800 /// to the function declaration Fn, so patch up the expression E to 12801 /// refer (possibly indirectly) to Fn. Returns the new expr. 12802 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 12803 FunctionDecl *Fn) { 12804 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 12805 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 12806 Found, Fn); 12807 if (SubExpr == PE->getSubExpr()) 12808 return PE; 12809 12810 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 12811 } 12812 12813 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 12814 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 12815 Found, Fn); 12816 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 12817 SubExpr->getType()) && 12818 "Implicit cast type cannot be determined from overload"); 12819 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 12820 if (SubExpr == ICE->getSubExpr()) 12821 return ICE; 12822 12823 return ImplicitCastExpr::Create(Context, ICE->getType(), 12824 ICE->getCastKind(), 12825 SubExpr, nullptr, 12826 ICE->getValueKind()); 12827 } 12828 12829 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 12830 assert(UnOp->getOpcode() == UO_AddrOf && 12831 "Can only take the address of an overloaded function"); 12832 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12833 if (Method->isStatic()) { 12834 // Do nothing: static member functions aren't any different 12835 // from non-member functions. 12836 } else { 12837 // Fix the subexpression, which really has to be an 12838 // UnresolvedLookupExpr holding an overloaded member function 12839 // or template. 12840 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12841 Found, Fn); 12842 if (SubExpr == UnOp->getSubExpr()) 12843 return UnOp; 12844 12845 assert(isa<DeclRefExpr>(SubExpr) 12846 && "fixed to something other than a decl ref"); 12847 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 12848 && "fixed to a member ref with no nested name qualifier"); 12849 12850 // We have taken the address of a pointer to member 12851 // function. Perform the computation here so that we get the 12852 // appropriate pointer to member type. 12853 QualType ClassType 12854 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 12855 QualType MemPtrType 12856 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 12857 12858 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 12859 VK_RValue, OK_Ordinary, 12860 UnOp->getOperatorLoc()); 12861 } 12862 } 12863 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12864 Found, Fn); 12865 if (SubExpr == UnOp->getSubExpr()) 12866 return UnOp; 12867 12868 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 12869 Context.getPointerType(SubExpr->getType()), 12870 VK_RValue, OK_Ordinary, 12871 UnOp->getOperatorLoc()); 12872 } 12873 12874 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12875 // FIXME: avoid copy. 12876 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12877 if (ULE->hasExplicitTemplateArgs()) { 12878 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 12879 TemplateArgs = &TemplateArgsBuffer; 12880 } 12881 12882 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12883 ULE->getQualifierLoc(), 12884 ULE->getTemplateKeywordLoc(), 12885 Fn, 12886 /*enclosing*/ false, // FIXME? 12887 ULE->getNameLoc(), 12888 Fn->getType(), 12889 VK_LValue, 12890 Found.getDecl(), 12891 TemplateArgs); 12892 MarkDeclRefReferenced(DRE); 12893 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 12894 return DRE; 12895 } 12896 12897 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 12898 // FIXME: avoid copy. 12899 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12900 if (MemExpr->hasExplicitTemplateArgs()) { 12901 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12902 TemplateArgs = &TemplateArgsBuffer; 12903 } 12904 12905 Expr *Base; 12906 12907 // If we're filling in a static method where we used to have an 12908 // implicit member access, rewrite to a simple decl ref. 12909 if (MemExpr->isImplicitAccess()) { 12910 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12911 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12912 MemExpr->getQualifierLoc(), 12913 MemExpr->getTemplateKeywordLoc(), 12914 Fn, 12915 /*enclosing*/ false, 12916 MemExpr->getMemberLoc(), 12917 Fn->getType(), 12918 VK_LValue, 12919 Found.getDecl(), 12920 TemplateArgs); 12921 MarkDeclRefReferenced(DRE); 12922 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 12923 return DRE; 12924 } else { 12925 SourceLocation Loc = MemExpr->getMemberLoc(); 12926 if (MemExpr->getQualifier()) 12927 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 12928 CheckCXXThisCapture(Loc); 12929 Base = new (Context) CXXThisExpr(Loc, 12930 MemExpr->getBaseType(), 12931 /*isImplicit=*/true); 12932 } 12933 } else 12934 Base = MemExpr->getBase(); 12935 12936 ExprValueKind valueKind; 12937 QualType type; 12938 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12939 valueKind = VK_LValue; 12940 type = Fn->getType(); 12941 } else { 12942 valueKind = VK_RValue; 12943 type = Context.BoundMemberTy; 12944 } 12945 12946 MemberExpr *ME = MemberExpr::Create( 12947 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 12948 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 12949 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 12950 OK_Ordinary); 12951 ME->setHadMultipleCandidates(true); 12952 MarkMemberReferenced(ME); 12953 return ME; 12954 } 12955 12956 llvm_unreachable("Invalid reference to overloaded function"); 12957 } 12958 12959 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 12960 DeclAccessPair Found, 12961 FunctionDecl *Fn) { 12962 return FixOverloadedFunctionReference(E.get(), Found, Fn); 12963 } 12964