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 llvm::any_of(FD->parameters(), 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 297 // A conversion to an enumeration type is narrowing if the conversion to 298 // the underlying type is narrowing. This only arises for expressions of 299 // the form 'Enum{init}'. 300 if (auto *ET = ToType->getAs<EnumType>()) 301 ToType = ET->getDecl()->getIntegerType(); 302 303 switch (Second) { 304 // 'bool' is an integral type; dispatch to the right place to handle it. 305 case ICK_Boolean_Conversion: 306 if (FromType->isRealFloatingType()) 307 goto FloatingIntegralConversion; 308 if (FromType->isIntegralOrUnscopedEnumerationType()) 309 goto IntegralConversion; 310 // Boolean conversions can be from pointers and pointers to members 311 // [conv.bool], and those aren't considered narrowing conversions. 312 return NK_Not_Narrowing; 313 314 // -- from a floating-point type to an integer type, or 315 // 316 // -- from an integer type or unscoped enumeration type to a floating-point 317 // type, except where the source is a constant expression and the actual 318 // value after conversion will fit into the target type and will produce 319 // the original value when converted back to the original type, or 320 case ICK_Floating_Integral: 321 FloatingIntegralConversion: 322 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 323 return NK_Type_Narrowing; 324 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 325 llvm::APSInt IntConstantValue; 326 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 327 if (Initializer && 328 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 329 // Convert the integer to the floating type. 330 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 331 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 332 llvm::APFloat::rmNearestTiesToEven); 333 // And back. 334 llvm::APSInt ConvertedValue = IntConstantValue; 335 bool ignored; 336 Result.convertToInteger(ConvertedValue, 337 llvm::APFloat::rmTowardZero, &ignored); 338 // If the resulting value is different, this was a narrowing conversion. 339 if (IntConstantValue != ConvertedValue) { 340 ConstantValue = APValue(IntConstantValue); 341 ConstantType = Initializer->getType(); 342 return NK_Constant_Narrowing; 343 } 344 } else { 345 // Variables are always narrowings. 346 return NK_Variable_Narrowing; 347 } 348 } 349 return NK_Not_Narrowing; 350 351 // -- from long double to double or float, or from double to float, except 352 // where the source is a constant expression and the actual value after 353 // conversion is within the range of values that can be represented (even 354 // if it cannot be represented exactly), or 355 case ICK_Floating_Conversion: 356 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 357 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 358 // FromType is larger than ToType. 359 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 360 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 361 // Constant! 362 assert(ConstantValue.isFloat()); 363 llvm::APFloat FloatVal = ConstantValue.getFloat(); 364 // Convert the source value into the target type. 365 bool ignored; 366 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 367 Ctx.getFloatTypeSemantics(ToType), 368 llvm::APFloat::rmNearestTiesToEven, &ignored); 369 // If there was no overflow, the source value is within the range of 370 // values that can be represented. 371 if (ConvertStatus & llvm::APFloat::opOverflow) { 372 ConstantType = Initializer->getType(); 373 return NK_Constant_Narrowing; 374 } 375 } else { 376 return NK_Variable_Narrowing; 377 } 378 } 379 return NK_Not_Narrowing; 380 381 // -- from an integer type or unscoped enumeration type to an integer type 382 // that cannot represent all the values of the original type, except where 383 // the source is a constant expression and the actual value after 384 // conversion will fit into the target type and will produce the original 385 // value when converted back to the original type. 386 case ICK_Integral_Conversion: 387 IntegralConversion: { 388 assert(FromType->isIntegralOrUnscopedEnumerationType()); 389 assert(ToType->isIntegralOrUnscopedEnumerationType()); 390 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 391 const unsigned FromWidth = Ctx.getIntWidth(FromType); 392 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 393 const unsigned ToWidth = Ctx.getIntWidth(ToType); 394 395 if (FromWidth > ToWidth || 396 (FromWidth == ToWidth && FromSigned != ToSigned) || 397 (FromSigned && !ToSigned)) { 398 // Not all values of FromType can be represented in ToType. 399 llvm::APSInt InitializerValue; 400 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 401 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 402 // Such conversions on variables are always narrowing. 403 return NK_Variable_Narrowing; 404 } 405 bool Narrowing = false; 406 if (FromWidth < ToWidth) { 407 // Negative -> unsigned is narrowing. Otherwise, more bits is never 408 // narrowing. 409 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 410 Narrowing = true; 411 } else { 412 // Add a bit to the InitializerValue so we don't have to worry about 413 // signed vs. unsigned comparisons. 414 InitializerValue = InitializerValue.extend( 415 InitializerValue.getBitWidth() + 1); 416 // Convert the initializer to and from the target width and signed-ness. 417 llvm::APSInt ConvertedValue = InitializerValue; 418 ConvertedValue = ConvertedValue.trunc(ToWidth); 419 ConvertedValue.setIsSigned(ToSigned); 420 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 421 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 422 // If the result is different, this was a narrowing conversion. 423 if (ConvertedValue != InitializerValue) 424 Narrowing = true; 425 } 426 if (Narrowing) { 427 ConstantType = Initializer->getType(); 428 ConstantValue = APValue(InitializerValue); 429 return NK_Constant_Narrowing; 430 } 431 } 432 return NK_Not_Narrowing; 433 } 434 435 default: 436 // Other kinds of conversions are not narrowings. 437 return NK_Not_Narrowing; 438 } 439 } 440 441 /// dump - Print this standard conversion sequence to standard 442 /// error. Useful for debugging overloading issues. 443 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 444 raw_ostream &OS = llvm::errs(); 445 bool PrintedSomething = false; 446 if (First != ICK_Identity) { 447 OS << GetImplicitConversionName(First); 448 PrintedSomething = true; 449 } 450 451 if (Second != ICK_Identity) { 452 if (PrintedSomething) { 453 OS << " -> "; 454 } 455 OS << GetImplicitConversionName(Second); 456 457 if (CopyConstructor) { 458 OS << " (by copy constructor)"; 459 } else if (DirectBinding) { 460 OS << " (direct reference binding)"; 461 } else if (ReferenceBinding) { 462 OS << " (reference binding)"; 463 } 464 PrintedSomething = true; 465 } 466 467 if (Third != ICK_Identity) { 468 if (PrintedSomething) { 469 OS << " -> "; 470 } 471 OS << GetImplicitConversionName(Third); 472 PrintedSomething = true; 473 } 474 475 if (!PrintedSomething) { 476 OS << "No conversions required"; 477 } 478 } 479 480 /// dump - Print this user-defined conversion sequence to standard 481 /// error. Useful for debugging overloading issues. 482 void UserDefinedConversionSequence::dump() const { 483 raw_ostream &OS = llvm::errs(); 484 if (Before.First || Before.Second || Before.Third) { 485 Before.dump(); 486 OS << " -> "; 487 } 488 if (ConversionFunction) 489 OS << '\'' << *ConversionFunction << '\''; 490 else 491 OS << "aggregate initialization"; 492 if (After.First || After.Second || After.Third) { 493 OS << " -> "; 494 After.dump(); 495 } 496 } 497 498 /// dump - Print this implicit conversion sequence to standard 499 /// error. Useful for debugging overloading issues. 500 void ImplicitConversionSequence::dump() const { 501 raw_ostream &OS = llvm::errs(); 502 if (isStdInitializerListElement()) 503 OS << "Worst std::initializer_list element conversion: "; 504 switch (ConversionKind) { 505 case StandardConversion: 506 OS << "Standard conversion: "; 507 Standard.dump(); 508 break; 509 case UserDefinedConversion: 510 OS << "User-defined conversion: "; 511 UserDefined.dump(); 512 break; 513 case EllipsisConversion: 514 OS << "Ellipsis conversion"; 515 break; 516 case AmbiguousConversion: 517 OS << "Ambiguous conversion"; 518 break; 519 case BadConversion: 520 OS << "Bad conversion"; 521 break; 522 } 523 524 OS << "\n"; 525 } 526 527 void AmbiguousConversionSequence::construct() { 528 new (&conversions()) ConversionSet(); 529 } 530 531 void AmbiguousConversionSequence::destruct() { 532 conversions().~ConversionSet(); 533 } 534 535 void 536 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 537 FromTypePtr = O.FromTypePtr; 538 ToTypePtr = O.ToTypePtr; 539 new (&conversions()) ConversionSet(O.conversions()); 540 } 541 542 namespace { 543 // Structure used by DeductionFailureInfo to store 544 // template argument information. 545 struct DFIArguments { 546 TemplateArgument FirstArg; 547 TemplateArgument SecondArg; 548 }; 549 // Structure used by DeductionFailureInfo to store 550 // template parameter and template argument information. 551 struct DFIParamWithArguments : DFIArguments { 552 TemplateParameter Param; 553 }; 554 // Structure used by DeductionFailureInfo to store template argument 555 // information and the index of the problematic call argument. 556 struct DFIDeducedMismatchArgs : DFIArguments { 557 TemplateArgumentList *TemplateArgs; 558 unsigned CallArgIndex; 559 }; 560 } 561 562 /// \brief Convert from Sema's representation of template deduction information 563 /// to the form used in overload-candidate information. 564 DeductionFailureInfo 565 clang::MakeDeductionFailureInfo(ASTContext &Context, 566 Sema::TemplateDeductionResult TDK, 567 TemplateDeductionInfo &Info) { 568 DeductionFailureInfo Result; 569 Result.Result = static_cast<unsigned>(TDK); 570 Result.HasDiagnostic = false; 571 switch (TDK) { 572 case Sema::TDK_Success: 573 case Sema::TDK_Invalid: 574 case Sema::TDK_InstantiationDepth: 575 case Sema::TDK_TooManyArguments: 576 case Sema::TDK_TooFewArguments: 577 case Sema::TDK_MiscellaneousDeductionFailure: 578 Result.Data = nullptr; 579 break; 580 581 case Sema::TDK_Incomplete: 582 case Sema::TDK_InvalidExplicitArguments: 583 Result.Data = Info.Param.getOpaqueValue(); 584 break; 585 586 case Sema::TDK_DeducedMismatch: { 587 // FIXME: Should allocate from normal heap so that we can free this later. 588 auto *Saved = new (Context) DFIDeducedMismatchArgs; 589 Saved->FirstArg = Info.FirstArg; 590 Saved->SecondArg = Info.SecondArg; 591 Saved->TemplateArgs = Info.take(); 592 Saved->CallArgIndex = Info.CallArgIndex; 593 Result.Data = Saved; 594 break; 595 } 596 597 case Sema::TDK_NonDeducedMismatch: { 598 // FIXME: Should allocate from normal heap so that we can free this later. 599 DFIArguments *Saved = new (Context) DFIArguments; 600 Saved->FirstArg = Info.FirstArg; 601 Saved->SecondArg = Info.SecondArg; 602 Result.Data = Saved; 603 break; 604 } 605 606 case Sema::TDK_Inconsistent: 607 case Sema::TDK_Underqualified: { 608 // FIXME: Should allocate from normal heap so that we can free this later. 609 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 610 Saved->Param = Info.Param; 611 Saved->FirstArg = Info.FirstArg; 612 Saved->SecondArg = Info.SecondArg; 613 Result.Data = Saved; 614 break; 615 } 616 617 case Sema::TDK_SubstitutionFailure: 618 Result.Data = Info.take(); 619 if (Info.hasSFINAEDiagnostic()) { 620 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 621 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 622 Info.takeSFINAEDiagnostic(*Diag); 623 Result.HasDiagnostic = true; 624 } 625 break; 626 627 case Sema::TDK_FailedOverloadResolution: 628 Result.Data = Info.Expression; 629 break; 630 } 631 632 return Result; 633 } 634 635 void DeductionFailureInfo::Destroy() { 636 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 637 case Sema::TDK_Success: 638 case Sema::TDK_Invalid: 639 case Sema::TDK_InstantiationDepth: 640 case Sema::TDK_Incomplete: 641 case Sema::TDK_TooManyArguments: 642 case Sema::TDK_TooFewArguments: 643 case Sema::TDK_InvalidExplicitArguments: 644 case Sema::TDK_FailedOverloadResolution: 645 break; 646 647 case Sema::TDK_Inconsistent: 648 case Sema::TDK_Underqualified: 649 case Sema::TDK_DeducedMismatch: 650 case Sema::TDK_NonDeducedMismatch: 651 // FIXME: Destroy the data? 652 Data = nullptr; 653 break; 654 655 case Sema::TDK_SubstitutionFailure: 656 // FIXME: Destroy the template argument list? 657 Data = nullptr; 658 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 659 Diag->~PartialDiagnosticAt(); 660 HasDiagnostic = false; 661 } 662 break; 663 664 // Unhandled 665 case Sema::TDK_MiscellaneousDeductionFailure: 666 break; 667 } 668 } 669 670 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 671 if (HasDiagnostic) 672 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 673 return nullptr; 674 } 675 676 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 677 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 678 case Sema::TDK_Success: 679 case Sema::TDK_Invalid: 680 case Sema::TDK_InstantiationDepth: 681 case Sema::TDK_TooManyArguments: 682 case Sema::TDK_TooFewArguments: 683 case Sema::TDK_SubstitutionFailure: 684 case Sema::TDK_DeducedMismatch: 685 case Sema::TDK_NonDeducedMismatch: 686 case Sema::TDK_FailedOverloadResolution: 687 return TemplateParameter(); 688 689 case Sema::TDK_Incomplete: 690 case Sema::TDK_InvalidExplicitArguments: 691 return TemplateParameter::getFromOpaqueValue(Data); 692 693 case Sema::TDK_Inconsistent: 694 case Sema::TDK_Underqualified: 695 return static_cast<DFIParamWithArguments*>(Data)->Param; 696 697 // Unhandled 698 case Sema::TDK_MiscellaneousDeductionFailure: 699 break; 700 } 701 702 return TemplateParameter(); 703 } 704 705 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 706 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 707 case Sema::TDK_Success: 708 case Sema::TDK_Invalid: 709 case Sema::TDK_InstantiationDepth: 710 case Sema::TDK_TooManyArguments: 711 case Sema::TDK_TooFewArguments: 712 case Sema::TDK_Incomplete: 713 case Sema::TDK_InvalidExplicitArguments: 714 case Sema::TDK_Inconsistent: 715 case Sema::TDK_Underqualified: 716 case Sema::TDK_NonDeducedMismatch: 717 case Sema::TDK_FailedOverloadResolution: 718 return nullptr; 719 720 case Sema::TDK_DeducedMismatch: 721 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 722 723 case Sema::TDK_SubstitutionFailure: 724 return static_cast<TemplateArgumentList*>(Data); 725 726 // Unhandled 727 case Sema::TDK_MiscellaneousDeductionFailure: 728 break; 729 } 730 731 return nullptr; 732 } 733 734 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 735 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 736 case Sema::TDK_Success: 737 case Sema::TDK_Invalid: 738 case Sema::TDK_InstantiationDepth: 739 case Sema::TDK_Incomplete: 740 case Sema::TDK_TooManyArguments: 741 case Sema::TDK_TooFewArguments: 742 case Sema::TDK_InvalidExplicitArguments: 743 case Sema::TDK_SubstitutionFailure: 744 case Sema::TDK_FailedOverloadResolution: 745 return nullptr; 746 747 case Sema::TDK_Inconsistent: 748 case Sema::TDK_Underqualified: 749 case Sema::TDK_DeducedMismatch: 750 case Sema::TDK_NonDeducedMismatch: 751 return &static_cast<DFIArguments*>(Data)->FirstArg; 752 753 // Unhandled 754 case Sema::TDK_MiscellaneousDeductionFailure: 755 break; 756 } 757 758 return nullptr; 759 } 760 761 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 762 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 763 case Sema::TDK_Success: 764 case Sema::TDK_Invalid: 765 case Sema::TDK_InstantiationDepth: 766 case Sema::TDK_Incomplete: 767 case Sema::TDK_TooManyArguments: 768 case Sema::TDK_TooFewArguments: 769 case Sema::TDK_InvalidExplicitArguments: 770 case Sema::TDK_SubstitutionFailure: 771 case Sema::TDK_FailedOverloadResolution: 772 return nullptr; 773 774 case Sema::TDK_Inconsistent: 775 case Sema::TDK_Underqualified: 776 case Sema::TDK_DeducedMismatch: 777 case Sema::TDK_NonDeducedMismatch: 778 return &static_cast<DFIArguments*>(Data)->SecondArg; 779 780 // Unhandled 781 case Sema::TDK_MiscellaneousDeductionFailure: 782 break; 783 } 784 785 return nullptr; 786 } 787 788 Expr *DeductionFailureInfo::getExpr() { 789 if (static_cast<Sema::TemplateDeductionResult>(Result) == 790 Sema::TDK_FailedOverloadResolution) 791 return static_cast<Expr*>(Data); 792 793 return nullptr; 794 } 795 796 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 797 if (static_cast<Sema::TemplateDeductionResult>(Result) == 798 Sema::TDK_DeducedMismatch) 799 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 800 801 return llvm::None; 802 } 803 804 void OverloadCandidateSet::destroyCandidates() { 805 for (iterator i = begin(), e = end(); i != e; ++i) { 806 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 807 i->Conversions[ii].~ImplicitConversionSequence(); 808 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 809 i->DeductionFailure.Destroy(); 810 } 811 } 812 813 void OverloadCandidateSet::clear() { 814 destroyCandidates(); 815 NumInlineSequences = 0; 816 Candidates.clear(); 817 Functions.clear(); 818 } 819 820 namespace { 821 class UnbridgedCastsSet { 822 struct Entry { 823 Expr **Addr; 824 Expr *Saved; 825 }; 826 SmallVector<Entry, 2> Entries; 827 828 public: 829 void save(Sema &S, Expr *&E) { 830 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 831 Entry entry = { &E, E }; 832 Entries.push_back(entry); 833 E = S.stripARCUnbridgedCast(E); 834 } 835 836 void restore() { 837 for (SmallVectorImpl<Entry>::iterator 838 i = Entries.begin(), e = Entries.end(); i != e; ++i) 839 *i->Addr = i->Saved; 840 } 841 }; 842 } 843 844 /// checkPlaceholderForOverload - Do any interesting placeholder-like 845 /// preprocessing on the given expression. 846 /// 847 /// \param unbridgedCasts a collection to which to add unbridged casts; 848 /// without this, they will be immediately diagnosed as errors 849 /// 850 /// Return true on unrecoverable error. 851 static bool 852 checkPlaceholderForOverload(Sema &S, Expr *&E, 853 UnbridgedCastsSet *unbridgedCasts = nullptr) { 854 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 855 // We can't handle overloaded expressions here because overload 856 // resolution might reasonably tweak them. 857 if (placeholder->getKind() == BuiltinType::Overload) return false; 858 859 // If the context potentially accepts unbridged ARC casts, strip 860 // the unbridged cast and add it to the collection for later restoration. 861 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 862 unbridgedCasts) { 863 unbridgedCasts->save(S, E); 864 return false; 865 } 866 867 // Go ahead and check everything else. 868 ExprResult result = S.CheckPlaceholderExpr(E); 869 if (result.isInvalid()) 870 return true; 871 872 E = result.get(); 873 return false; 874 } 875 876 // Nothing to do. 877 return false; 878 } 879 880 /// checkArgPlaceholdersForOverload - Check a set of call operands for 881 /// placeholders. 882 static bool checkArgPlaceholdersForOverload(Sema &S, 883 MultiExprArg Args, 884 UnbridgedCastsSet &unbridged) { 885 for (unsigned i = 0, e = Args.size(); i != e; ++i) 886 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 887 return true; 888 889 return false; 890 } 891 892 // IsOverload - Determine whether the given New declaration is an 893 // overload of the declarations in Old. This routine returns false if 894 // New and Old cannot be overloaded, e.g., if New has the same 895 // signature as some function in Old (C++ 1.3.10) or if the Old 896 // declarations aren't functions (or function templates) at all. When 897 // it does return false, MatchedDecl will point to the decl that New 898 // cannot be overloaded with. This decl may be a UsingShadowDecl on 899 // top of the underlying declaration. 900 // 901 // Example: Given the following input: 902 // 903 // void f(int, float); // #1 904 // void f(int, int); // #2 905 // int f(int, int); // #3 906 // 907 // When we process #1, there is no previous declaration of "f", 908 // so IsOverload will not be used. 909 // 910 // When we process #2, Old contains only the FunctionDecl for #1. By 911 // comparing the parameter types, we see that #1 and #2 are overloaded 912 // (since they have different signatures), so this routine returns 913 // false; MatchedDecl is unchanged. 914 // 915 // When we process #3, Old is an overload set containing #1 and #2. We 916 // compare the signatures of #3 to #1 (they're overloaded, so we do 917 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 918 // identical (return types of functions are not part of the 919 // signature), IsOverload returns false and MatchedDecl will be set to 920 // point to the FunctionDecl for #2. 921 // 922 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 923 // into a class by a using declaration. The rules for whether to hide 924 // shadow declarations ignore some properties which otherwise figure 925 // into a function template's signature. 926 Sema::OverloadKind 927 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 928 NamedDecl *&Match, bool NewIsUsingDecl) { 929 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 930 I != E; ++I) { 931 NamedDecl *OldD = *I; 932 933 bool OldIsUsingDecl = false; 934 if (isa<UsingShadowDecl>(OldD)) { 935 OldIsUsingDecl = true; 936 937 // We can always introduce two using declarations into the same 938 // context, even if they have identical signatures. 939 if (NewIsUsingDecl) continue; 940 941 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 942 } 943 944 // A using-declaration does not conflict with another declaration 945 // if one of them is hidden. 946 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 947 continue; 948 949 // If either declaration was introduced by a using declaration, 950 // we'll need to use slightly different rules for matching. 951 // Essentially, these rules are the normal rules, except that 952 // function templates hide function templates with different 953 // return types or template parameter lists. 954 bool UseMemberUsingDeclRules = 955 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 956 !New->getFriendObjectKind(); 957 958 if (FunctionDecl *OldF = OldD->getAsFunction()) { 959 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 960 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 961 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 962 continue; 963 } 964 965 if (!isa<FunctionTemplateDecl>(OldD) && 966 !shouldLinkPossiblyHiddenDecl(*I, New)) 967 continue; 968 969 Match = *I; 970 return Ovl_Match; 971 } 972 } else if (isa<UsingDecl>(OldD)) { 973 // We can overload with these, which can show up when doing 974 // redeclaration checks for UsingDecls. 975 assert(Old.getLookupKind() == LookupUsingDeclName); 976 } else if (isa<TagDecl>(OldD)) { 977 // We can always overload with tags by hiding them. 978 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 979 // Optimistically assume that an unresolved using decl will 980 // overload; if it doesn't, we'll have to diagnose during 981 // template instantiation. 982 } else { 983 // (C++ 13p1): 984 // Only function declarations can be overloaded; object and type 985 // declarations cannot be overloaded. 986 Match = *I; 987 return Ovl_NonFunction; 988 } 989 } 990 991 return Ovl_Overload; 992 } 993 994 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 995 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 996 // C++ [basic.start.main]p2: This function shall not be overloaded. 997 if (New->isMain()) 998 return false; 999 1000 // MSVCRT user defined entry points cannot be overloaded. 1001 if (New->isMSVCRTEntryPoint()) 1002 return false; 1003 1004 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1005 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1006 1007 // C++ [temp.fct]p2: 1008 // A function template can be overloaded with other function templates 1009 // and with normal (non-template) functions. 1010 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1011 return true; 1012 1013 // Is the function New an overload of the function Old? 1014 QualType OldQType = Context.getCanonicalType(Old->getType()); 1015 QualType NewQType = Context.getCanonicalType(New->getType()); 1016 1017 // Compare the signatures (C++ 1.3.10) of the two functions to 1018 // determine whether they are overloads. If we find any mismatch 1019 // in the signature, they are overloads. 1020 1021 // If either of these functions is a K&R-style function (no 1022 // prototype), then we consider them to have matching signatures. 1023 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1024 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1025 return false; 1026 1027 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1028 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1029 1030 // The signature of a function includes the types of its 1031 // parameters (C++ 1.3.10), which includes the presence or absence 1032 // of the ellipsis; see C++ DR 357). 1033 if (OldQType != NewQType && 1034 (OldType->getNumParams() != NewType->getNumParams() || 1035 OldType->isVariadic() != NewType->isVariadic() || 1036 !FunctionParamTypesAreEqual(OldType, NewType))) 1037 return true; 1038 1039 // C++ [temp.over.link]p4: 1040 // The signature of a function template consists of its function 1041 // signature, its return type and its template parameter list. The names 1042 // of the template parameters are significant only for establishing the 1043 // relationship between the template parameters and the rest of the 1044 // signature. 1045 // 1046 // We check the return type and template parameter lists for function 1047 // templates first; the remaining checks follow. 1048 // 1049 // However, we don't consider either of these when deciding whether 1050 // a member introduced by a shadow declaration is hidden. 1051 if (!UseMemberUsingDeclRules && NewTemplate && 1052 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1053 OldTemplate->getTemplateParameters(), 1054 false, TPL_TemplateMatch) || 1055 OldType->getReturnType() != NewType->getReturnType())) 1056 return true; 1057 1058 // If the function is a class member, its signature includes the 1059 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1060 // 1061 // As part of this, also check whether one of the member functions 1062 // is static, in which case they are not overloads (C++ 1063 // 13.1p2). While not part of the definition of the signature, 1064 // this check is important to determine whether these functions 1065 // can be overloaded. 1066 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1067 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1068 if (OldMethod && NewMethod && 1069 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1070 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1071 if (!UseMemberUsingDeclRules && 1072 (OldMethod->getRefQualifier() == RQ_None || 1073 NewMethod->getRefQualifier() == RQ_None)) { 1074 // C++0x [over.load]p2: 1075 // - Member function declarations with the same name and the same 1076 // parameter-type-list as well as member function template 1077 // declarations with the same name, the same parameter-type-list, and 1078 // the same template parameter lists cannot be overloaded if any of 1079 // them, but not all, have a ref-qualifier (8.3.5). 1080 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1081 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1082 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1083 } 1084 return true; 1085 } 1086 1087 // We may not have applied the implicit const for a constexpr member 1088 // function yet (because we haven't yet resolved whether this is a static 1089 // or non-static member function). Add it now, on the assumption that this 1090 // is a redeclaration of OldMethod. 1091 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1092 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1093 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1094 !isa<CXXConstructorDecl>(NewMethod)) 1095 NewQuals |= Qualifiers::Const; 1096 1097 // We do not allow overloading based off of '__restrict'. 1098 OldQuals &= ~Qualifiers::Restrict; 1099 NewQuals &= ~Qualifiers::Restrict; 1100 if (OldQuals != NewQuals) 1101 return true; 1102 } 1103 1104 // Though pass_object_size is placed on parameters and takes an argument, we 1105 // consider it to be a function-level modifier for the sake of function 1106 // identity. Either the function has one or more parameters with 1107 // pass_object_size or it doesn't. 1108 if (functionHasPassObjectSizeParams(New) != 1109 functionHasPassObjectSizeParams(Old)) 1110 return true; 1111 1112 // enable_if attributes are an order-sensitive part of the signature. 1113 for (specific_attr_iterator<EnableIfAttr> 1114 NewI = New->specific_attr_begin<EnableIfAttr>(), 1115 NewE = New->specific_attr_end<EnableIfAttr>(), 1116 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1117 OldE = Old->specific_attr_end<EnableIfAttr>(); 1118 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1119 if (NewI == NewE || OldI == OldE) 1120 return true; 1121 llvm::FoldingSetNodeID NewID, OldID; 1122 NewI->getCond()->Profile(NewID, Context, true); 1123 OldI->getCond()->Profile(OldID, Context, true); 1124 if (NewID != OldID) 1125 return true; 1126 } 1127 1128 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1129 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1130 OldTarget = IdentifyCUDATarget(Old); 1131 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global) 1132 return false; 1133 1134 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1135 1136 // Don't allow mixing of HD with other kinds. This guarantees that 1137 // we have only one viable function with this signature on any 1138 // side of CUDA compilation . 1139 // __global__ functions can't be overloaded based on attribute 1140 // difference because, like HD, they also exist on both sides. 1141 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice) || 1142 (NewTarget == CFT_Global) || (OldTarget == CFT_Global)) 1143 return false; 1144 1145 // Allow overloading of functions with same signature, but 1146 // different CUDA target attributes. 1147 return NewTarget != OldTarget; 1148 } 1149 1150 // The signatures match; this is not an overload. 1151 return false; 1152 } 1153 1154 /// \brief Checks availability of the function depending on the current 1155 /// function context. Inside an unavailable function, unavailability is ignored. 1156 /// 1157 /// \returns true if \arg FD is unavailable and current context is inside 1158 /// an available function, false otherwise. 1159 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1160 if (!FD->isUnavailable()) 1161 return false; 1162 1163 // Walk up the context of the caller. 1164 Decl *C = cast<Decl>(CurContext); 1165 do { 1166 if (C->isUnavailable()) 1167 return false; 1168 } while ((C = cast_or_null<Decl>(C->getDeclContext()))); 1169 return true; 1170 } 1171 1172 /// \brief Tries a user-defined conversion from From to ToType. 1173 /// 1174 /// Produces an implicit conversion sequence for when a standard conversion 1175 /// is not an option. See TryImplicitConversion for more information. 1176 static ImplicitConversionSequence 1177 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1178 bool SuppressUserConversions, 1179 bool AllowExplicit, 1180 bool InOverloadResolution, 1181 bool CStyle, 1182 bool AllowObjCWritebackConversion, 1183 bool AllowObjCConversionOnExplicit) { 1184 ImplicitConversionSequence ICS; 1185 1186 if (SuppressUserConversions) { 1187 // We're not in the case above, so there is no conversion that 1188 // we can perform. 1189 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1190 return ICS; 1191 } 1192 1193 // Attempt user-defined conversion. 1194 OverloadCandidateSet Conversions(From->getExprLoc(), 1195 OverloadCandidateSet::CSK_Normal); 1196 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1197 Conversions, AllowExplicit, 1198 AllowObjCConversionOnExplicit)) { 1199 case OR_Success: 1200 case OR_Deleted: 1201 ICS.setUserDefined(); 1202 ICS.UserDefined.Before.setAsIdentityConversion(); 1203 // C++ [over.ics.user]p4: 1204 // A conversion of an expression of class type to the same class 1205 // type is given Exact Match rank, and a conversion of an 1206 // expression of class type to a base class of that type is 1207 // given Conversion rank, in spite of the fact that a copy 1208 // constructor (i.e., a user-defined conversion function) is 1209 // called for those cases. 1210 if (CXXConstructorDecl *Constructor 1211 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1212 QualType FromCanon 1213 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1214 QualType ToCanon 1215 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1216 if (Constructor->isCopyConstructor() && 1217 (FromCanon == ToCanon || 1218 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) { 1219 // Turn this into a "standard" conversion sequence, so that it 1220 // gets ranked with standard conversion sequences. 1221 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1222 ICS.setStandard(); 1223 ICS.Standard.setAsIdentityConversion(); 1224 ICS.Standard.setFromType(From->getType()); 1225 ICS.Standard.setAllToTypes(ToType); 1226 ICS.Standard.CopyConstructor = Constructor; 1227 ICS.Standard.FoundCopyConstructor = Found; 1228 if (ToCanon != FromCanon) 1229 ICS.Standard.Second = ICK_Derived_To_Base; 1230 } 1231 } 1232 break; 1233 1234 case OR_Ambiguous: 1235 ICS.setAmbiguous(); 1236 ICS.Ambiguous.setFromType(From->getType()); 1237 ICS.Ambiguous.setToType(ToType); 1238 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1239 Cand != Conversions.end(); ++Cand) 1240 if (Cand->Viable) 1241 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1242 break; 1243 1244 // Fall through. 1245 case OR_No_Viable_Function: 1246 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1247 break; 1248 } 1249 1250 return ICS; 1251 } 1252 1253 /// TryImplicitConversion - Attempt to perform an implicit conversion 1254 /// from the given expression (Expr) to the given type (ToType). This 1255 /// function returns an implicit conversion sequence that can be used 1256 /// to perform the initialization. Given 1257 /// 1258 /// void f(float f); 1259 /// void g(int i) { f(i); } 1260 /// 1261 /// this routine would produce an implicit conversion sequence to 1262 /// describe the initialization of f from i, which will be a standard 1263 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1264 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1265 // 1266 /// Note that this routine only determines how the conversion can be 1267 /// performed; it does not actually perform the conversion. As such, 1268 /// it will not produce any diagnostics if no conversion is available, 1269 /// but will instead return an implicit conversion sequence of kind 1270 /// "BadConversion". 1271 /// 1272 /// If @p SuppressUserConversions, then user-defined conversions are 1273 /// not permitted. 1274 /// If @p AllowExplicit, then explicit user-defined conversions are 1275 /// permitted. 1276 /// 1277 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1278 /// writeback conversion, which allows __autoreleasing id* parameters to 1279 /// be initialized with __strong id* or __weak id* arguments. 1280 static ImplicitConversionSequence 1281 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1282 bool SuppressUserConversions, 1283 bool AllowExplicit, 1284 bool InOverloadResolution, 1285 bool CStyle, 1286 bool AllowObjCWritebackConversion, 1287 bool AllowObjCConversionOnExplicit) { 1288 ImplicitConversionSequence ICS; 1289 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1290 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1291 ICS.setStandard(); 1292 return ICS; 1293 } 1294 1295 if (!S.getLangOpts().CPlusPlus) { 1296 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1297 return ICS; 1298 } 1299 1300 // C++ [over.ics.user]p4: 1301 // A conversion of an expression of class type to the same class 1302 // type is given Exact Match rank, and a conversion of an 1303 // expression of class type to a base class of that type is 1304 // given Conversion rank, in spite of the fact that a copy/move 1305 // constructor (i.e., a user-defined conversion function) is 1306 // called for those cases. 1307 QualType FromType = From->getType(); 1308 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1309 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1310 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) { 1311 ICS.setStandard(); 1312 ICS.Standard.setAsIdentityConversion(); 1313 ICS.Standard.setFromType(FromType); 1314 ICS.Standard.setAllToTypes(ToType); 1315 1316 // We don't actually check at this point whether there is a valid 1317 // copy/move constructor, since overloading just assumes that it 1318 // exists. When we actually perform initialization, we'll find the 1319 // appropriate constructor to copy the returned object, if needed. 1320 ICS.Standard.CopyConstructor = nullptr; 1321 1322 // Determine whether this is considered a derived-to-base conversion. 1323 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1324 ICS.Standard.Second = ICK_Derived_To_Base; 1325 1326 return ICS; 1327 } 1328 1329 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1330 AllowExplicit, InOverloadResolution, CStyle, 1331 AllowObjCWritebackConversion, 1332 AllowObjCConversionOnExplicit); 1333 } 1334 1335 ImplicitConversionSequence 1336 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1337 bool SuppressUserConversions, 1338 bool AllowExplicit, 1339 bool InOverloadResolution, 1340 bool CStyle, 1341 bool AllowObjCWritebackConversion) { 1342 return ::TryImplicitConversion(*this, From, ToType, 1343 SuppressUserConversions, AllowExplicit, 1344 InOverloadResolution, CStyle, 1345 AllowObjCWritebackConversion, 1346 /*AllowObjCConversionOnExplicit=*/false); 1347 } 1348 1349 /// PerformImplicitConversion - Perform an implicit conversion of the 1350 /// expression From to the type ToType. Returns the 1351 /// converted expression. Flavor is the kind of conversion we're 1352 /// performing, used in the error message. If @p AllowExplicit, 1353 /// explicit user-defined conversions are permitted. 1354 ExprResult 1355 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1356 AssignmentAction Action, bool AllowExplicit) { 1357 ImplicitConversionSequence ICS; 1358 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1359 } 1360 1361 ExprResult 1362 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1363 AssignmentAction Action, bool AllowExplicit, 1364 ImplicitConversionSequence& ICS) { 1365 if (checkPlaceholderForOverload(*this, From)) 1366 return ExprError(); 1367 1368 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1369 bool AllowObjCWritebackConversion 1370 = getLangOpts().ObjCAutoRefCount && 1371 (Action == AA_Passing || Action == AA_Sending); 1372 if (getLangOpts().ObjC1) 1373 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1374 ToType, From->getType(), From); 1375 ICS = ::TryImplicitConversion(*this, From, ToType, 1376 /*SuppressUserConversions=*/false, 1377 AllowExplicit, 1378 /*InOverloadResolution=*/false, 1379 /*CStyle=*/false, 1380 AllowObjCWritebackConversion, 1381 /*AllowObjCConversionOnExplicit=*/false); 1382 return PerformImplicitConversion(From, ToType, ICS, Action); 1383 } 1384 1385 /// \brief Determine whether the conversion from FromType to ToType is a valid 1386 /// conversion that strips "noreturn" off the nested function type. 1387 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1388 QualType &ResultTy) { 1389 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1390 return false; 1391 1392 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1393 // where F adds one of the following at most once: 1394 // - a pointer 1395 // - a member pointer 1396 // - a block pointer 1397 CanQualType CanTo = Context.getCanonicalType(ToType); 1398 CanQualType CanFrom = Context.getCanonicalType(FromType); 1399 Type::TypeClass TyClass = CanTo->getTypeClass(); 1400 if (TyClass != CanFrom->getTypeClass()) return false; 1401 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1402 if (TyClass == Type::Pointer) { 1403 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1404 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1405 } else if (TyClass == Type::BlockPointer) { 1406 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1407 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1408 } else if (TyClass == Type::MemberPointer) { 1409 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1410 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1411 } else { 1412 return false; 1413 } 1414 1415 TyClass = CanTo->getTypeClass(); 1416 if (TyClass != CanFrom->getTypeClass()) return false; 1417 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1418 return false; 1419 } 1420 1421 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1422 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1423 if (!EInfo.getNoReturn()) return false; 1424 1425 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1426 assert(QualType(FromFn, 0).isCanonical()); 1427 if (QualType(FromFn, 0) != CanTo) return false; 1428 1429 ResultTy = ToType; 1430 return true; 1431 } 1432 1433 /// \brief Determine whether the conversion from FromType to ToType is a valid 1434 /// vector conversion. 1435 /// 1436 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1437 /// conversion. 1438 static bool IsVectorConversion(Sema &S, QualType FromType, 1439 QualType ToType, ImplicitConversionKind &ICK) { 1440 // We need at least one of these types to be a vector type to have a vector 1441 // conversion. 1442 if (!ToType->isVectorType() && !FromType->isVectorType()) 1443 return false; 1444 1445 // Identical types require no conversions. 1446 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1447 return false; 1448 1449 // There are no conversions between extended vector types, only identity. 1450 if (ToType->isExtVectorType()) { 1451 // There are no conversions between extended vector types other than the 1452 // identity conversion. 1453 if (FromType->isExtVectorType()) 1454 return false; 1455 1456 // Vector splat from any arithmetic type to a vector. 1457 if (FromType->isArithmeticType()) { 1458 ICK = ICK_Vector_Splat; 1459 return true; 1460 } 1461 } 1462 1463 // We can perform the conversion between vector types in the following cases: 1464 // 1)vector types are equivalent AltiVec and GCC vector types 1465 // 2)lax vector conversions are permitted and the vector types are of the 1466 // same size 1467 if (ToType->isVectorType() && FromType->isVectorType()) { 1468 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1469 S.isLaxVectorConversion(FromType, ToType)) { 1470 ICK = ICK_Vector_Conversion; 1471 return true; 1472 } 1473 } 1474 1475 return false; 1476 } 1477 1478 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1479 bool InOverloadResolution, 1480 StandardConversionSequence &SCS, 1481 bool CStyle); 1482 1483 /// IsStandardConversion - Determines whether there is a standard 1484 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1485 /// expression From to the type ToType. Standard conversion sequences 1486 /// only consider non-class types; for conversions that involve class 1487 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1488 /// contain the standard conversion sequence required to perform this 1489 /// conversion and this routine will return true. Otherwise, this 1490 /// routine will return false and the value of SCS is unspecified. 1491 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1492 bool InOverloadResolution, 1493 StandardConversionSequence &SCS, 1494 bool CStyle, 1495 bool AllowObjCWritebackConversion) { 1496 QualType FromType = From->getType(); 1497 1498 // Standard conversions (C++ [conv]) 1499 SCS.setAsIdentityConversion(); 1500 SCS.IncompatibleObjC = false; 1501 SCS.setFromType(FromType); 1502 SCS.CopyConstructor = nullptr; 1503 1504 // There are no standard conversions for class types in C++, so 1505 // abort early. When overloading in C, however, we do permit them. 1506 if (S.getLangOpts().CPlusPlus && 1507 (FromType->isRecordType() || ToType->isRecordType())) 1508 return false; 1509 1510 // The first conversion can be an lvalue-to-rvalue conversion, 1511 // array-to-pointer conversion, or function-to-pointer conversion 1512 // (C++ 4p1). 1513 1514 if (FromType == S.Context.OverloadTy) { 1515 DeclAccessPair AccessPair; 1516 if (FunctionDecl *Fn 1517 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1518 AccessPair)) { 1519 // We were able to resolve the address of the overloaded function, 1520 // so we can convert to the type of that function. 1521 FromType = Fn->getType(); 1522 SCS.setFromType(FromType); 1523 1524 // we can sometimes resolve &foo<int> regardless of ToType, so check 1525 // if the type matches (identity) or we are converting to bool 1526 if (!S.Context.hasSameUnqualifiedType( 1527 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1528 QualType resultTy; 1529 // if the function type matches except for [[noreturn]], it's ok 1530 if (!S.IsNoReturnConversion(FromType, 1531 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1532 // otherwise, only a boolean conversion is standard 1533 if (!ToType->isBooleanType()) 1534 return false; 1535 } 1536 1537 // Check if the "from" expression is taking the address of an overloaded 1538 // function and recompute the FromType accordingly. Take advantage of the 1539 // fact that non-static member functions *must* have such an address-of 1540 // expression. 1541 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1542 if (Method && !Method->isStatic()) { 1543 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1544 "Non-unary operator on non-static member address"); 1545 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1546 == UO_AddrOf && 1547 "Non-address-of operator on non-static member address"); 1548 const Type *ClassType 1549 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1550 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1551 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1552 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1553 UO_AddrOf && 1554 "Non-address-of operator for overloaded function expression"); 1555 FromType = S.Context.getPointerType(FromType); 1556 } 1557 1558 // Check that we've computed the proper type after overload resolution. 1559 assert(S.Context.hasSameType( 1560 FromType, 1561 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1562 } else { 1563 return false; 1564 } 1565 } 1566 // Lvalue-to-rvalue conversion (C++11 4.1): 1567 // A glvalue (3.10) of a non-function, non-array type T can 1568 // be converted to a prvalue. 1569 bool argIsLValue = From->isGLValue(); 1570 if (argIsLValue && 1571 !FromType->isFunctionType() && !FromType->isArrayType() && 1572 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1573 SCS.First = ICK_Lvalue_To_Rvalue; 1574 1575 // C11 6.3.2.1p2: 1576 // ... if the lvalue has atomic type, the value has the non-atomic version 1577 // of the type of the lvalue ... 1578 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1579 FromType = Atomic->getValueType(); 1580 1581 // If T is a non-class type, the type of the rvalue is the 1582 // cv-unqualified version of T. Otherwise, the type of the rvalue 1583 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1584 // just strip the qualifiers because they don't matter. 1585 FromType = FromType.getUnqualifiedType(); 1586 } else if (FromType->isArrayType()) { 1587 // Array-to-pointer conversion (C++ 4.2) 1588 SCS.First = ICK_Array_To_Pointer; 1589 1590 // An lvalue or rvalue of type "array of N T" or "array of unknown 1591 // bound of T" can be converted to an rvalue of type "pointer to 1592 // T" (C++ 4.2p1). 1593 FromType = S.Context.getArrayDecayedType(FromType); 1594 1595 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1596 // This conversion is deprecated in C++03 (D.4) 1597 SCS.DeprecatedStringLiteralToCharPtr = true; 1598 1599 // For the purpose of ranking in overload resolution 1600 // (13.3.3.1.1), this conversion is considered an 1601 // array-to-pointer conversion followed by a qualification 1602 // conversion (4.4). (C++ 4.2p2) 1603 SCS.Second = ICK_Identity; 1604 SCS.Third = ICK_Qualification; 1605 SCS.QualificationIncludesObjCLifetime = false; 1606 SCS.setAllToTypes(FromType); 1607 return true; 1608 } 1609 } else if (FromType->isFunctionType() && argIsLValue) { 1610 // Function-to-pointer conversion (C++ 4.3). 1611 SCS.First = ICK_Function_To_Pointer; 1612 1613 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1614 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1615 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1616 return false; 1617 1618 // An lvalue of function type T can be converted to an rvalue of 1619 // type "pointer to T." The result is a pointer to the 1620 // function. (C++ 4.3p1). 1621 FromType = S.Context.getPointerType(FromType); 1622 } else { 1623 // We don't require any conversions for the first step. 1624 SCS.First = ICK_Identity; 1625 } 1626 SCS.setToType(0, FromType); 1627 1628 // The second conversion can be an integral promotion, floating 1629 // point promotion, integral conversion, floating point conversion, 1630 // floating-integral conversion, pointer conversion, 1631 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1632 // For overloading in C, this can also be a "compatible-type" 1633 // conversion. 1634 bool IncompatibleObjC = false; 1635 ImplicitConversionKind SecondICK = ICK_Identity; 1636 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1637 // The unqualified versions of the types are the same: there's no 1638 // conversion to do. 1639 SCS.Second = ICK_Identity; 1640 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1641 // Integral promotion (C++ 4.5). 1642 SCS.Second = ICK_Integral_Promotion; 1643 FromType = ToType.getUnqualifiedType(); 1644 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1645 // Floating point promotion (C++ 4.6). 1646 SCS.Second = ICK_Floating_Promotion; 1647 FromType = ToType.getUnqualifiedType(); 1648 } else if (S.IsComplexPromotion(FromType, ToType)) { 1649 // Complex promotion (Clang extension) 1650 SCS.Second = ICK_Complex_Promotion; 1651 FromType = ToType.getUnqualifiedType(); 1652 } else if (ToType->isBooleanType() && 1653 (FromType->isArithmeticType() || 1654 FromType->isAnyPointerType() || 1655 FromType->isBlockPointerType() || 1656 FromType->isMemberPointerType() || 1657 FromType->isNullPtrType())) { 1658 // Boolean conversions (C++ 4.12). 1659 SCS.Second = ICK_Boolean_Conversion; 1660 FromType = S.Context.BoolTy; 1661 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1662 ToType->isIntegralType(S.Context)) { 1663 // Integral conversions (C++ 4.7). 1664 SCS.Second = ICK_Integral_Conversion; 1665 FromType = ToType.getUnqualifiedType(); 1666 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1667 // Complex conversions (C99 6.3.1.6) 1668 SCS.Second = ICK_Complex_Conversion; 1669 FromType = ToType.getUnqualifiedType(); 1670 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1671 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1672 // Complex-real conversions (C99 6.3.1.7) 1673 SCS.Second = ICK_Complex_Real; 1674 FromType = ToType.getUnqualifiedType(); 1675 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1676 // FIXME: disable conversions between long double and __float128 if 1677 // their representation is different until there is back end support 1678 // We of course allow this conversion if long double is really double. 1679 if (&S.Context.getFloatTypeSemantics(FromType) != 1680 &S.Context.getFloatTypeSemantics(ToType)) { 1681 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1682 ToType == S.Context.LongDoubleTy) || 1683 (FromType == S.Context.LongDoubleTy && 1684 ToType == S.Context.Float128Ty)); 1685 if (Float128AndLongDouble && 1686 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1687 &llvm::APFloat::IEEEdouble)) 1688 return false; 1689 } 1690 // Floating point conversions (C++ 4.8). 1691 SCS.Second = ICK_Floating_Conversion; 1692 FromType = ToType.getUnqualifiedType(); 1693 } else if ((FromType->isRealFloatingType() && 1694 ToType->isIntegralType(S.Context)) || 1695 (FromType->isIntegralOrUnscopedEnumerationType() && 1696 ToType->isRealFloatingType())) { 1697 // Floating-integral conversions (C++ 4.9). 1698 SCS.Second = ICK_Floating_Integral; 1699 FromType = ToType.getUnqualifiedType(); 1700 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1701 SCS.Second = ICK_Block_Pointer_Conversion; 1702 } else if (AllowObjCWritebackConversion && 1703 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1704 SCS.Second = ICK_Writeback_Conversion; 1705 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1706 FromType, IncompatibleObjC)) { 1707 // Pointer conversions (C++ 4.10). 1708 SCS.Second = ICK_Pointer_Conversion; 1709 SCS.IncompatibleObjC = IncompatibleObjC; 1710 FromType = FromType.getUnqualifiedType(); 1711 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1712 InOverloadResolution, FromType)) { 1713 // Pointer to member conversions (4.11). 1714 SCS.Second = ICK_Pointer_Member; 1715 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1716 SCS.Second = SecondICK; 1717 FromType = ToType.getUnqualifiedType(); 1718 } else if (!S.getLangOpts().CPlusPlus && 1719 S.Context.typesAreCompatible(ToType, FromType)) { 1720 // Compatible conversions (Clang extension for C function overloading) 1721 SCS.Second = ICK_Compatible_Conversion; 1722 FromType = ToType.getUnqualifiedType(); 1723 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1724 // Treat a conversion that strips "noreturn" as an identity conversion. 1725 SCS.Second = ICK_NoReturn_Adjustment; 1726 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1727 InOverloadResolution, 1728 SCS, CStyle)) { 1729 SCS.Second = ICK_TransparentUnionConversion; 1730 FromType = ToType; 1731 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1732 CStyle)) { 1733 // tryAtomicConversion has updated the standard conversion sequence 1734 // appropriately. 1735 return true; 1736 } else if (ToType->isEventT() && 1737 From->isIntegerConstantExpr(S.getASTContext()) && 1738 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1739 SCS.Second = ICK_Zero_Event_Conversion; 1740 FromType = ToType; 1741 } else { 1742 // No second conversion required. 1743 SCS.Second = ICK_Identity; 1744 } 1745 SCS.setToType(1, FromType); 1746 1747 QualType CanonFrom; 1748 QualType CanonTo; 1749 // The third conversion can be a qualification conversion (C++ 4p1). 1750 bool ObjCLifetimeConversion; 1751 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1752 ObjCLifetimeConversion)) { 1753 SCS.Third = ICK_Qualification; 1754 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1755 FromType = ToType; 1756 CanonFrom = S.Context.getCanonicalType(FromType); 1757 CanonTo = S.Context.getCanonicalType(ToType); 1758 } else { 1759 // No conversion required 1760 SCS.Third = ICK_Identity; 1761 1762 // C++ [over.best.ics]p6: 1763 // [...] Any difference in top-level cv-qualification is 1764 // subsumed by the initialization itself and does not constitute 1765 // a conversion. [...] 1766 CanonFrom = S.Context.getCanonicalType(FromType); 1767 CanonTo = S.Context.getCanonicalType(ToType); 1768 if (CanonFrom.getLocalUnqualifiedType() 1769 == CanonTo.getLocalUnqualifiedType() && 1770 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1771 FromType = ToType; 1772 CanonFrom = CanonTo; 1773 } 1774 } 1775 SCS.setToType(2, FromType); 1776 1777 if (CanonFrom == CanonTo) 1778 return true; 1779 1780 // If we have not converted the argument type to the parameter type, 1781 // this is a bad conversion sequence, unless we're resolving an overload in C. 1782 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1783 return false; 1784 1785 ExprResult ER = ExprResult{From}; 1786 auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER, 1787 /*Diagnose=*/false, 1788 /*DiagnoseCFAudited=*/false, 1789 /*ConvertRHS=*/false); 1790 if (Conv != Sema::Compatible) 1791 return false; 1792 1793 SCS.setAllToTypes(ToType); 1794 // We need to set all three because we want this conversion to rank terribly, 1795 // and we don't know what conversions it may overlap with. 1796 SCS.First = ICK_C_Only_Conversion; 1797 SCS.Second = ICK_C_Only_Conversion; 1798 SCS.Third = ICK_C_Only_Conversion; 1799 return true; 1800 } 1801 1802 static bool 1803 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1804 QualType &ToType, 1805 bool InOverloadResolution, 1806 StandardConversionSequence &SCS, 1807 bool CStyle) { 1808 1809 const RecordType *UT = ToType->getAsUnionType(); 1810 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1811 return false; 1812 // The field to initialize within the transparent union. 1813 RecordDecl *UD = UT->getDecl(); 1814 // It's compatible if the expression matches any of the fields. 1815 for (const auto *it : UD->fields()) { 1816 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1817 CStyle, /*ObjCWritebackConversion=*/false)) { 1818 ToType = it->getType(); 1819 return true; 1820 } 1821 } 1822 return false; 1823 } 1824 1825 /// IsIntegralPromotion - Determines whether the conversion from the 1826 /// expression From (whose potentially-adjusted type is FromType) to 1827 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1828 /// sets PromotedType to the promoted type. 1829 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1830 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1831 // All integers are built-in. 1832 if (!To) { 1833 return false; 1834 } 1835 1836 // An rvalue of type char, signed char, unsigned char, short int, or 1837 // unsigned short int can be converted to an rvalue of type int if 1838 // int can represent all the values of the source type; otherwise, 1839 // the source rvalue can be converted to an rvalue of type unsigned 1840 // int (C++ 4.5p1). 1841 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1842 !FromType->isEnumeralType()) { 1843 if (// We can promote any signed, promotable integer type to an int 1844 (FromType->isSignedIntegerType() || 1845 // We can promote any unsigned integer type whose size is 1846 // less than int to an int. 1847 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 1848 return To->getKind() == BuiltinType::Int; 1849 } 1850 1851 return To->getKind() == BuiltinType::UInt; 1852 } 1853 1854 // C++11 [conv.prom]p3: 1855 // A prvalue of an unscoped enumeration type whose underlying type is not 1856 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1857 // following types that can represent all the values of the enumeration 1858 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1859 // unsigned int, long int, unsigned long int, long long int, or unsigned 1860 // long long int. If none of the types in that list can represent all the 1861 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1862 // type can be converted to an rvalue a prvalue of the extended integer type 1863 // with lowest integer conversion rank (4.13) greater than the rank of long 1864 // long in which all the values of the enumeration can be represented. If 1865 // there are two such extended types, the signed one is chosen. 1866 // C++11 [conv.prom]p4: 1867 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1868 // can be converted to a prvalue of its underlying type. Moreover, if 1869 // integral promotion can be applied to its underlying type, a prvalue of an 1870 // unscoped enumeration type whose underlying type is fixed can also be 1871 // converted to a prvalue of the promoted underlying type. 1872 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1873 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1874 // provided for a scoped enumeration. 1875 if (FromEnumType->getDecl()->isScoped()) 1876 return false; 1877 1878 // We can perform an integral promotion to the underlying type of the enum, 1879 // even if that's not the promoted type. Note that the check for promoting 1880 // the underlying type is based on the type alone, and does not consider 1881 // the bitfield-ness of the actual source expression. 1882 if (FromEnumType->getDecl()->isFixed()) { 1883 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1884 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1885 IsIntegralPromotion(nullptr, Underlying, ToType); 1886 } 1887 1888 // We have already pre-calculated the promotion type, so this is trivial. 1889 if (ToType->isIntegerType() && 1890 isCompleteType(From->getLocStart(), FromType)) 1891 return Context.hasSameUnqualifiedType( 1892 ToType, FromEnumType->getDecl()->getPromotionType()); 1893 } 1894 1895 // C++0x [conv.prom]p2: 1896 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1897 // to an rvalue a prvalue of the first of the following types that can 1898 // represent all the values of its underlying type: int, unsigned int, 1899 // long int, unsigned long int, long long int, or unsigned long long int. 1900 // If none of the types in that list can represent all the values of its 1901 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1902 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1903 // type. 1904 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1905 ToType->isIntegerType()) { 1906 // Determine whether the type we're converting from is signed or 1907 // unsigned. 1908 bool FromIsSigned = FromType->isSignedIntegerType(); 1909 uint64_t FromSize = Context.getTypeSize(FromType); 1910 1911 // The types we'll try to promote to, in the appropriate 1912 // order. Try each of these types. 1913 QualType PromoteTypes[6] = { 1914 Context.IntTy, Context.UnsignedIntTy, 1915 Context.LongTy, Context.UnsignedLongTy , 1916 Context.LongLongTy, Context.UnsignedLongLongTy 1917 }; 1918 for (int Idx = 0; Idx < 6; ++Idx) { 1919 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1920 if (FromSize < ToSize || 1921 (FromSize == ToSize && 1922 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1923 // We found the type that we can promote to. If this is the 1924 // type we wanted, we have a promotion. Otherwise, no 1925 // promotion. 1926 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1927 } 1928 } 1929 } 1930 1931 // An rvalue for an integral bit-field (9.6) can be converted to an 1932 // rvalue of type int if int can represent all the values of the 1933 // bit-field; otherwise, it can be converted to unsigned int if 1934 // unsigned int can represent all the values of the bit-field. If 1935 // the bit-field is larger yet, no integral promotion applies to 1936 // it. If the bit-field has an enumerated type, it is treated as any 1937 // other value of that type for promotion purposes (C++ 4.5p3). 1938 // FIXME: We should delay checking of bit-fields until we actually perform the 1939 // conversion. 1940 if (From) { 1941 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1942 llvm::APSInt BitWidth; 1943 if (FromType->isIntegralType(Context) && 1944 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1945 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1946 ToSize = Context.getTypeSize(ToType); 1947 1948 // Are we promoting to an int from a bitfield that fits in an int? 1949 if (BitWidth < ToSize || 1950 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1951 return To->getKind() == BuiltinType::Int; 1952 } 1953 1954 // Are we promoting to an unsigned int from an unsigned bitfield 1955 // that fits into an unsigned int? 1956 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1957 return To->getKind() == BuiltinType::UInt; 1958 } 1959 1960 return false; 1961 } 1962 } 1963 } 1964 1965 // An rvalue of type bool can be converted to an rvalue of type int, 1966 // with false becoming zero and true becoming one (C++ 4.5p4). 1967 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1968 return true; 1969 } 1970 1971 return false; 1972 } 1973 1974 /// IsFloatingPointPromotion - Determines whether the conversion from 1975 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1976 /// returns true and sets PromotedType to the promoted type. 1977 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1978 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1979 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1980 /// An rvalue of type float can be converted to an rvalue of type 1981 /// double. (C++ 4.6p1). 1982 if (FromBuiltin->getKind() == BuiltinType::Float && 1983 ToBuiltin->getKind() == BuiltinType::Double) 1984 return true; 1985 1986 // C99 6.3.1.5p1: 1987 // When a float is promoted to double or long double, or a 1988 // double is promoted to long double [...]. 1989 if (!getLangOpts().CPlusPlus && 1990 (FromBuiltin->getKind() == BuiltinType::Float || 1991 FromBuiltin->getKind() == BuiltinType::Double) && 1992 (ToBuiltin->getKind() == BuiltinType::LongDouble || 1993 ToBuiltin->getKind() == BuiltinType::Float128)) 1994 return true; 1995 1996 // Half can be promoted to float. 1997 if (!getLangOpts().NativeHalfType && 1998 FromBuiltin->getKind() == BuiltinType::Half && 1999 ToBuiltin->getKind() == BuiltinType::Float) 2000 return true; 2001 } 2002 2003 return false; 2004 } 2005 2006 /// \brief Determine if a conversion is a complex promotion. 2007 /// 2008 /// A complex promotion is defined as a complex -> complex conversion 2009 /// where the conversion between the underlying real types is a 2010 /// floating-point or integral promotion. 2011 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2012 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2013 if (!FromComplex) 2014 return false; 2015 2016 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2017 if (!ToComplex) 2018 return false; 2019 2020 return IsFloatingPointPromotion(FromComplex->getElementType(), 2021 ToComplex->getElementType()) || 2022 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2023 ToComplex->getElementType()); 2024 } 2025 2026 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2027 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2028 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2029 /// if non-empty, will be a pointer to ToType that may or may not have 2030 /// the right set of qualifiers on its pointee. 2031 /// 2032 static QualType 2033 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2034 QualType ToPointee, QualType ToType, 2035 ASTContext &Context, 2036 bool StripObjCLifetime = false) { 2037 assert((FromPtr->getTypeClass() == Type::Pointer || 2038 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2039 "Invalid similarly-qualified pointer type"); 2040 2041 /// Conversions to 'id' subsume cv-qualifier conversions. 2042 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2043 return ToType.getUnqualifiedType(); 2044 2045 QualType CanonFromPointee 2046 = Context.getCanonicalType(FromPtr->getPointeeType()); 2047 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2048 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2049 2050 if (StripObjCLifetime) 2051 Quals.removeObjCLifetime(); 2052 2053 // Exact qualifier match -> return the pointer type we're converting to. 2054 if (CanonToPointee.getLocalQualifiers() == Quals) { 2055 // ToType is exactly what we need. Return it. 2056 if (!ToType.isNull()) 2057 return ToType.getUnqualifiedType(); 2058 2059 // Build a pointer to ToPointee. It has the right qualifiers 2060 // already. 2061 if (isa<ObjCObjectPointerType>(ToType)) 2062 return Context.getObjCObjectPointerType(ToPointee); 2063 return Context.getPointerType(ToPointee); 2064 } 2065 2066 // Just build a canonical type that has the right qualifiers. 2067 QualType QualifiedCanonToPointee 2068 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2069 2070 if (isa<ObjCObjectPointerType>(ToType)) 2071 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2072 return Context.getPointerType(QualifiedCanonToPointee); 2073 } 2074 2075 static bool isNullPointerConstantForConversion(Expr *Expr, 2076 bool InOverloadResolution, 2077 ASTContext &Context) { 2078 // Handle value-dependent integral null pointer constants correctly. 2079 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2080 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2081 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2082 return !InOverloadResolution; 2083 2084 return Expr->isNullPointerConstant(Context, 2085 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2086 : Expr::NPC_ValueDependentIsNull); 2087 } 2088 2089 /// IsPointerConversion - Determines whether the conversion of the 2090 /// expression From, which has the (possibly adjusted) type FromType, 2091 /// can be converted to the type ToType via a pointer conversion (C++ 2092 /// 4.10). If so, returns true and places the converted type (that 2093 /// might differ from ToType in its cv-qualifiers at some level) into 2094 /// ConvertedType. 2095 /// 2096 /// This routine also supports conversions to and from block pointers 2097 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2098 /// pointers to interfaces. FIXME: Once we've determined the 2099 /// appropriate overloading rules for Objective-C, we may want to 2100 /// split the Objective-C checks into a different routine; however, 2101 /// GCC seems to consider all of these conversions to be pointer 2102 /// conversions, so for now they live here. IncompatibleObjC will be 2103 /// set if the conversion is an allowed Objective-C conversion that 2104 /// should result in a warning. 2105 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2106 bool InOverloadResolution, 2107 QualType& ConvertedType, 2108 bool &IncompatibleObjC) { 2109 IncompatibleObjC = false; 2110 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2111 IncompatibleObjC)) 2112 return true; 2113 2114 // Conversion from a null pointer constant to any Objective-C pointer type. 2115 if (ToType->isObjCObjectPointerType() && 2116 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2117 ConvertedType = ToType; 2118 return true; 2119 } 2120 2121 // Blocks: Block pointers can be converted to void*. 2122 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2123 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2124 ConvertedType = ToType; 2125 return true; 2126 } 2127 // Blocks: A null pointer constant can be converted to a block 2128 // pointer type. 2129 if (ToType->isBlockPointerType() && 2130 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2131 ConvertedType = ToType; 2132 return true; 2133 } 2134 2135 // If the left-hand-side is nullptr_t, the right side can be a null 2136 // pointer constant. 2137 if (ToType->isNullPtrType() && 2138 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2139 ConvertedType = ToType; 2140 return true; 2141 } 2142 2143 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2144 if (!ToTypePtr) 2145 return false; 2146 2147 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2148 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2149 ConvertedType = ToType; 2150 return true; 2151 } 2152 2153 // Beyond this point, both types need to be pointers 2154 // , including objective-c pointers. 2155 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2156 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2157 !getLangOpts().ObjCAutoRefCount) { 2158 ConvertedType = BuildSimilarlyQualifiedPointerType( 2159 FromType->getAs<ObjCObjectPointerType>(), 2160 ToPointeeType, 2161 ToType, Context); 2162 return true; 2163 } 2164 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2165 if (!FromTypePtr) 2166 return false; 2167 2168 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2169 2170 // If the unqualified pointee types are the same, this can't be a 2171 // pointer conversion, so don't do all of the work below. 2172 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2173 return false; 2174 2175 // An rvalue of type "pointer to cv T," where T is an object type, 2176 // can be converted to an rvalue of type "pointer to cv void" (C++ 2177 // 4.10p2). 2178 if (FromPointeeType->isIncompleteOrObjectType() && 2179 ToPointeeType->isVoidType()) { 2180 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2181 ToPointeeType, 2182 ToType, Context, 2183 /*StripObjCLifetime=*/true); 2184 return true; 2185 } 2186 2187 // MSVC allows implicit function to void* type conversion. 2188 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2189 ToPointeeType->isVoidType()) { 2190 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2191 ToPointeeType, 2192 ToType, Context); 2193 return true; 2194 } 2195 2196 // When we're overloading in C, we allow a special kind of pointer 2197 // conversion for compatible-but-not-identical pointee types. 2198 if (!getLangOpts().CPlusPlus && 2199 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2200 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2201 ToPointeeType, 2202 ToType, Context); 2203 return true; 2204 } 2205 2206 // C++ [conv.ptr]p3: 2207 // 2208 // An rvalue of type "pointer to cv D," where D is a class type, 2209 // can be converted to an rvalue of type "pointer to cv B," where 2210 // B is a base class (clause 10) of D. If B is an inaccessible 2211 // (clause 11) or ambiguous (10.2) base class of D, a program that 2212 // necessitates this conversion is ill-formed. The result of the 2213 // conversion is a pointer to the base class sub-object of the 2214 // derived class object. The null pointer value is converted to 2215 // the null pointer value of the destination type. 2216 // 2217 // Note that we do not check for ambiguity or inaccessibility 2218 // here. That is handled by CheckPointerConversion. 2219 if (getLangOpts().CPlusPlus && 2220 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2221 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2222 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) { 2223 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2224 ToPointeeType, 2225 ToType, Context); 2226 return true; 2227 } 2228 2229 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2230 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2231 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2232 ToPointeeType, 2233 ToType, Context); 2234 return true; 2235 } 2236 2237 return false; 2238 } 2239 2240 /// \brief Adopt the given qualifiers for the given type. 2241 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2242 Qualifiers TQs = T.getQualifiers(); 2243 2244 // Check whether qualifiers already match. 2245 if (TQs == Qs) 2246 return T; 2247 2248 if (Qs.compatiblyIncludes(TQs)) 2249 return Context.getQualifiedType(T, Qs); 2250 2251 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2252 } 2253 2254 /// isObjCPointerConversion - Determines whether this is an 2255 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2256 /// with the same arguments and return values. 2257 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2258 QualType& ConvertedType, 2259 bool &IncompatibleObjC) { 2260 if (!getLangOpts().ObjC1) 2261 return false; 2262 2263 // The set of qualifiers on the type we're converting from. 2264 Qualifiers FromQualifiers = FromType.getQualifiers(); 2265 2266 // First, we handle all conversions on ObjC object pointer types. 2267 const ObjCObjectPointerType* ToObjCPtr = 2268 ToType->getAs<ObjCObjectPointerType>(); 2269 const ObjCObjectPointerType *FromObjCPtr = 2270 FromType->getAs<ObjCObjectPointerType>(); 2271 2272 if (ToObjCPtr && FromObjCPtr) { 2273 // If the pointee types are the same (ignoring qualifications), 2274 // then this is not a pointer conversion. 2275 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2276 FromObjCPtr->getPointeeType())) 2277 return false; 2278 2279 // Conversion between Objective-C pointers. 2280 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2281 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2282 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2283 if (getLangOpts().CPlusPlus && LHS && RHS && 2284 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2285 FromObjCPtr->getPointeeType())) 2286 return false; 2287 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2288 ToObjCPtr->getPointeeType(), 2289 ToType, Context); 2290 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2291 return true; 2292 } 2293 2294 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2295 // Okay: this is some kind of implicit downcast of Objective-C 2296 // interfaces, which is permitted. However, we're going to 2297 // complain about it. 2298 IncompatibleObjC = true; 2299 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2300 ToObjCPtr->getPointeeType(), 2301 ToType, Context); 2302 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2303 return true; 2304 } 2305 } 2306 // Beyond this point, both types need to be C pointers or block pointers. 2307 QualType ToPointeeType; 2308 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2309 ToPointeeType = ToCPtr->getPointeeType(); 2310 else if (const BlockPointerType *ToBlockPtr = 2311 ToType->getAs<BlockPointerType>()) { 2312 // Objective C++: We're able to convert from a pointer to any object 2313 // to a block pointer type. 2314 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2315 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2316 return true; 2317 } 2318 ToPointeeType = ToBlockPtr->getPointeeType(); 2319 } 2320 else if (FromType->getAs<BlockPointerType>() && 2321 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2322 // Objective C++: We're able to convert from a block pointer type to a 2323 // pointer to any object. 2324 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2325 return true; 2326 } 2327 else 2328 return false; 2329 2330 QualType FromPointeeType; 2331 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2332 FromPointeeType = FromCPtr->getPointeeType(); 2333 else if (const BlockPointerType *FromBlockPtr = 2334 FromType->getAs<BlockPointerType>()) 2335 FromPointeeType = FromBlockPtr->getPointeeType(); 2336 else 2337 return false; 2338 2339 // If we have pointers to pointers, recursively check whether this 2340 // is an Objective-C conversion. 2341 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2342 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2343 IncompatibleObjC)) { 2344 // We always complain about this conversion. 2345 IncompatibleObjC = true; 2346 ConvertedType = Context.getPointerType(ConvertedType); 2347 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2348 return true; 2349 } 2350 // Allow conversion of pointee being objective-c pointer to another one; 2351 // as in I* to id. 2352 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2353 ToPointeeType->getAs<ObjCObjectPointerType>() && 2354 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2355 IncompatibleObjC)) { 2356 2357 ConvertedType = Context.getPointerType(ConvertedType); 2358 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2359 return true; 2360 } 2361 2362 // If we have pointers to functions or blocks, check whether the only 2363 // differences in the argument and result types are in Objective-C 2364 // pointer conversions. If so, we permit the conversion (but 2365 // complain about it). 2366 const FunctionProtoType *FromFunctionType 2367 = FromPointeeType->getAs<FunctionProtoType>(); 2368 const FunctionProtoType *ToFunctionType 2369 = ToPointeeType->getAs<FunctionProtoType>(); 2370 if (FromFunctionType && ToFunctionType) { 2371 // If the function types are exactly the same, this isn't an 2372 // Objective-C pointer conversion. 2373 if (Context.getCanonicalType(FromPointeeType) 2374 == Context.getCanonicalType(ToPointeeType)) 2375 return false; 2376 2377 // Perform the quick checks that will tell us whether these 2378 // function types are obviously different. 2379 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2380 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2381 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2382 return false; 2383 2384 bool HasObjCConversion = false; 2385 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2386 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2387 // Okay, the types match exactly. Nothing to do. 2388 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2389 ToFunctionType->getReturnType(), 2390 ConvertedType, IncompatibleObjC)) { 2391 // Okay, we have an Objective-C pointer conversion. 2392 HasObjCConversion = true; 2393 } else { 2394 // Function types are too different. Abort. 2395 return false; 2396 } 2397 2398 // Check argument types. 2399 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2400 ArgIdx != NumArgs; ++ArgIdx) { 2401 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2402 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2403 if (Context.getCanonicalType(FromArgType) 2404 == Context.getCanonicalType(ToArgType)) { 2405 // Okay, the types match exactly. Nothing to do. 2406 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2407 ConvertedType, IncompatibleObjC)) { 2408 // Okay, we have an Objective-C pointer conversion. 2409 HasObjCConversion = true; 2410 } else { 2411 // Argument types are too different. Abort. 2412 return false; 2413 } 2414 } 2415 2416 if (HasObjCConversion) { 2417 // We had an Objective-C conversion. Allow this pointer 2418 // conversion, but complain about it. 2419 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2420 IncompatibleObjC = true; 2421 return true; 2422 } 2423 } 2424 2425 return false; 2426 } 2427 2428 /// \brief Determine whether this is an Objective-C writeback conversion, 2429 /// used for parameter passing when performing automatic reference counting. 2430 /// 2431 /// \param FromType The type we're converting form. 2432 /// 2433 /// \param ToType The type we're converting to. 2434 /// 2435 /// \param ConvertedType The type that will be produced after applying 2436 /// this conversion. 2437 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2438 QualType &ConvertedType) { 2439 if (!getLangOpts().ObjCAutoRefCount || 2440 Context.hasSameUnqualifiedType(FromType, ToType)) 2441 return false; 2442 2443 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2444 QualType ToPointee; 2445 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2446 ToPointee = ToPointer->getPointeeType(); 2447 else 2448 return false; 2449 2450 Qualifiers ToQuals = ToPointee.getQualifiers(); 2451 if (!ToPointee->isObjCLifetimeType() || 2452 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2453 !ToQuals.withoutObjCLifetime().empty()) 2454 return false; 2455 2456 // Argument must be a pointer to __strong to __weak. 2457 QualType FromPointee; 2458 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2459 FromPointee = FromPointer->getPointeeType(); 2460 else 2461 return false; 2462 2463 Qualifiers FromQuals = FromPointee.getQualifiers(); 2464 if (!FromPointee->isObjCLifetimeType() || 2465 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2466 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2467 return false; 2468 2469 // Make sure that we have compatible qualifiers. 2470 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2471 if (!ToQuals.compatiblyIncludes(FromQuals)) 2472 return false; 2473 2474 // Remove qualifiers from the pointee type we're converting from; they 2475 // aren't used in the compatibility check belong, and we'll be adding back 2476 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2477 FromPointee = FromPointee.getUnqualifiedType(); 2478 2479 // The unqualified form of the pointee types must be compatible. 2480 ToPointee = ToPointee.getUnqualifiedType(); 2481 bool IncompatibleObjC; 2482 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2483 FromPointee = ToPointee; 2484 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2485 IncompatibleObjC)) 2486 return false; 2487 2488 /// \brief Construct the type we're converting to, which is a pointer to 2489 /// __autoreleasing pointee. 2490 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2491 ConvertedType = Context.getPointerType(FromPointee); 2492 return true; 2493 } 2494 2495 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2496 QualType& ConvertedType) { 2497 QualType ToPointeeType; 2498 if (const BlockPointerType *ToBlockPtr = 2499 ToType->getAs<BlockPointerType>()) 2500 ToPointeeType = ToBlockPtr->getPointeeType(); 2501 else 2502 return false; 2503 2504 QualType FromPointeeType; 2505 if (const BlockPointerType *FromBlockPtr = 2506 FromType->getAs<BlockPointerType>()) 2507 FromPointeeType = FromBlockPtr->getPointeeType(); 2508 else 2509 return false; 2510 // We have pointer to blocks, check whether the only 2511 // differences in the argument and result types are in Objective-C 2512 // pointer conversions. If so, we permit the conversion. 2513 2514 const FunctionProtoType *FromFunctionType 2515 = FromPointeeType->getAs<FunctionProtoType>(); 2516 const FunctionProtoType *ToFunctionType 2517 = ToPointeeType->getAs<FunctionProtoType>(); 2518 2519 if (!FromFunctionType || !ToFunctionType) 2520 return false; 2521 2522 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2523 return true; 2524 2525 // Perform the quick checks that will tell us whether these 2526 // function types are obviously different. 2527 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2528 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2529 return false; 2530 2531 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2532 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2533 if (FromEInfo != ToEInfo) 2534 return false; 2535 2536 bool IncompatibleObjC = false; 2537 if (Context.hasSameType(FromFunctionType->getReturnType(), 2538 ToFunctionType->getReturnType())) { 2539 // Okay, the types match exactly. Nothing to do. 2540 } else { 2541 QualType RHS = FromFunctionType->getReturnType(); 2542 QualType LHS = ToFunctionType->getReturnType(); 2543 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2544 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2545 LHS = LHS.getUnqualifiedType(); 2546 2547 if (Context.hasSameType(RHS,LHS)) { 2548 // OK exact match. 2549 } else if (isObjCPointerConversion(RHS, LHS, 2550 ConvertedType, IncompatibleObjC)) { 2551 if (IncompatibleObjC) 2552 return false; 2553 // Okay, we have an Objective-C pointer conversion. 2554 } 2555 else 2556 return false; 2557 } 2558 2559 // Check argument types. 2560 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2561 ArgIdx != NumArgs; ++ArgIdx) { 2562 IncompatibleObjC = false; 2563 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2564 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2565 if (Context.hasSameType(FromArgType, ToArgType)) { 2566 // Okay, the types match exactly. Nothing to do. 2567 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2568 ConvertedType, IncompatibleObjC)) { 2569 if (IncompatibleObjC) 2570 return false; 2571 // Okay, we have an Objective-C pointer conversion. 2572 } else 2573 // Argument types are too different. Abort. 2574 return false; 2575 } 2576 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType, 2577 ToFunctionType)) 2578 return false; 2579 2580 ConvertedType = ToType; 2581 return true; 2582 } 2583 2584 enum { 2585 ft_default, 2586 ft_different_class, 2587 ft_parameter_arity, 2588 ft_parameter_mismatch, 2589 ft_return_type, 2590 ft_qualifer_mismatch 2591 }; 2592 2593 /// Attempts to get the FunctionProtoType from a Type. Handles 2594 /// MemberFunctionPointers properly. 2595 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2596 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2597 return FPT; 2598 2599 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2600 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2601 2602 return nullptr; 2603 } 2604 2605 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2606 /// function types. Catches different number of parameter, mismatch in 2607 /// parameter types, and different return types. 2608 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2609 QualType FromType, QualType ToType) { 2610 // If either type is not valid, include no extra info. 2611 if (FromType.isNull() || ToType.isNull()) { 2612 PDiag << ft_default; 2613 return; 2614 } 2615 2616 // Get the function type from the pointers. 2617 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2618 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2619 *ToMember = ToType->getAs<MemberPointerType>(); 2620 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2621 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2622 << QualType(FromMember->getClass(), 0); 2623 return; 2624 } 2625 FromType = FromMember->getPointeeType(); 2626 ToType = ToMember->getPointeeType(); 2627 } 2628 2629 if (FromType->isPointerType()) 2630 FromType = FromType->getPointeeType(); 2631 if (ToType->isPointerType()) 2632 ToType = ToType->getPointeeType(); 2633 2634 // Remove references. 2635 FromType = FromType.getNonReferenceType(); 2636 ToType = ToType.getNonReferenceType(); 2637 2638 // Don't print extra info for non-specialized template functions. 2639 if (FromType->isInstantiationDependentType() && 2640 !FromType->getAs<TemplateSpecializationType>()) { 2641 PDiag << ft_default; 2642 return; 2643 } 2644 2645 // No extra info for same types. 2646 if (Context.hasSameType(FromType, ToType)) { 2647 PDiag << ft_default; 2648 return; 2649 } 2650 2651 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2652 *ToFunction = tryGetFunctionProtoType(ToType); 2653 2654 // Both types need to be function types. 2655 if (!FromFunction || !ToFunction) { 2656 PDiag << ft_default; 2657 return; 2658 } 2659 2660 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2661 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2662 << FromFunction->getNumParams(); 2663 return; 2664 } 2665 2666 // Handle different parameter types. 2667 unsigned ArgPos; 2668 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2669 PDiag << ft_parameter_mismatch << ArgPos + 1 2670 << ToFunction->getParamType(ArgPos) 2671 << FromFunction->getParamType(ArgPos); 2672 return; 2673 } 2674 2675 // Handle different return type. 2676 if (!Context.hasSameType(FromFunction->getReturnType(), 2677 ToFunction->getReturnType())) { 2678 PDiag << ft_return_type << ToFunction->getReturnType() 2679 << FromFunction->getReturnType(); 2680 return; 2681 } 2682 2683 unsigned FromQuals = FromFunction->getTypeQuals(), 2684 ToQuals = ToFunction->getTypeQuals(); 2685 if (FromQuals != ToQuals) { 2686 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2687 return; 2688 } 2689 2690 // Unable to find a difference, so add no extra info. 2691 PDiag << ft_default; 2692 } 2693 2694 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2695 /// for equality of their argument types. Caller has already checked that 2696 /// they have same number of arguments. If the parameters are different, 2697 /// ArgPos will have the parameter index of the first different parameter. 2698 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2699 const FunctionProtoType *NewType, 2700 unsigned *ArgPos) { 2701 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2702 N = NewType->param_type_begin(), 2703 E = OldType->param_type_end(); 2704 O && (O != E); ++O, ++N) { 2705 if (!Context.hasSameType(O->getUnqualifiedType(), 2706 N->getUnqualifiedType())) { 2707 if (ArgPos) 2708 *ArgPos = O - OldType->param_type_begin(); 2709 return false; 2710 } 2711 } 2712 return true; 2713 } 2714 2715 /// CheckPointerConversion - Check the pointer conversion from the 2716 /// expression From to the type ToType. This routine checks for 2717 /// ambiguous or inaccessible derived-to-base pointer 2718 /// conversions for which IsPointerConversion has already returned 2719 /// true. It returns true and produces a diagnostic if there was an 2720 /// error, or returns false otherwise. 2721 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2722 CastKind &Kind, 2723 CXXCastPath& BasePath, 2724 bool IgnoreBaseAccess, 2725 bool Diagnose) { 2726 QualType FromType = From->getType(); 2727 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2728 2729 Kind = CK_BitCast; 2730 2731 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2732 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2733 Expr::NPCK_ZeroExpression) { 2734 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2735 DiagRuntimeBehavior(From->getExprLoc(), From, 2736 PDiag(diag::warn_impcast_bool_to_null_pointer) 2737 << ToType << From->getSourceRange()); 2738 else if (!isUnevaluatedContext()) 2739 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2740 << ToType << From->getSourceRange(); 2741 } 2742 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2743 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2744 QualType FromPointeeType = FromPtrType->getPointeeType(), 2745 ToPointeeType = ToPtrType->getPointeeType(); 2746 2747 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2748 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2749 // We must have a derived-to-base conversion. Check an 2750 // ambiguous or inaccessible conversion. 2751 unsigned InaccessibleID = 0; 2752 unsigned AmbigiousID = 0; 2753 if (Diagnose) { 2754 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2755 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2756 } 2757 if (CheckDerivedToBaseConversion( 2758 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2759 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2760 &BasePath, IgnoreBaseAccess)) 2761 return true; 2762 2763 // The conversion was successful. 2764 Kind = CK_DerivedToBase; 2765 } 2766 2767 if (Diagnose && !IsCStyleOrFunctionalCast && 2768 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2769 assert(getLangOpts().MSVCCompat && 2770 "this should only be possible with MSVCCompat!"); 2771 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2772 << From->getSourceRange(); 2773 } 2774 } 2775 } else if (const ObjCObjectPointerType *ToPtrType = 2776 ToType->getAs<ObjCObjectPointerType>()) { 2777 if (const ObjCObjectPointerType *FromPtrType = 2778 FromType->getAs<ObjCObjectPointerType>()) { 2779 // Objective-C++ conversions are always okay. 2780 // FIXME: We should have a different class of conversions for the 2781 // Objective-C++ implicit conversions. 2782 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2783 return false; 2784 } else if (FromType->isBlockPointerType()) { 2785 Kind = CK_BlockPointerToObjCPointerCast; 2786 } else { 2787 Kind = CK_CPointerToObjCPointerCast; 2788 } 2789 } else if (ToType->isBlockPointerType()) { 2790 if (!FromType->isBlockPointerType()) 2791 Kind = CK_AnyPointerToBlockPointerCast; 2792 } 2793 2794 // We shouldn't fall into this case unless it's valid for other 2795 // reasons. 2796 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2797 Kind = CK_NullToPointer; 2798 2799 return false; 2800 } 2801 2802 /// IsMemberPointerConversion - Determines whether the conversion of the 2803 /// expression From, which has the (possibly adjusted) type FromType, can be 2804 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2805 /// If so, returns true and places the converted type (that might differ from 2806 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2807 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2808 QualType ToType, 2809 bool InOverloadResolution, 2810 QualType &ConvertedType) { 2811 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2812 if (!ToTypePtr) 2813 return false; 2814 2815 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2816 if (From->isNullPointerConstant(Context, 2817 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2818 : Expr::NPC_ValueDependentIsNull)) { 2819 ConvertedType = ToType; 2820 return true; 2821 } 2822 2823 // Otherwise, both types have to be member pointers. 2824 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2825 if (!FromTypePtr) 2826 return false; 2827 2828 // A pointer to member of B can be converted to a pointer to member of D, 2829 // where D is derived from B (C++ 4.11p2). 2830 QualType FromClass(FromTypePtr->getClass(), 0); 2831 QualType ToClass(ToTypePtr->getClass(), 0); 2832 2833 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2834 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) { 2835 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2836 ToClass.getTypePtr()); 2837 return true; 2838 } 2839 2840 return false; 2841 } 2842 2843 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2844 /// expression From to the type ToType. This routine checks for ambiguous or 2845 /// virtual or inaccessible base-to-derived member pointer conversions 2846 /// for which IsMemberPointerConversion has already returned true. It returns 2847 /// true and produces a diagnostic if there was an error, or returns false 2848 /// otherwise. 2849 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2850 CastKind &Kind, 2851 CXXCastPath &BasePath, 2852 bool IgnoreBaseAccess) { 2853 QualType FromType = From->getType(); 2854 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2855 if (!FromPtrType) { 2856 // This must be a null pointer to member pointer conversion 2857 assert(From->isNullPointerConstant(Context, 2858 Expr::NPC_ValueDependentIsNull) && 2859 "Expr must be null pointer constant!"); 2860 Kind = CK_NullToMemberPointer; 2861 return false; 2862 } 2863 2864 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2865 assert(ToPtrType && "No member pointer cast has a target type " 2866 "that is not a member pointer."); 2867 2868 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2869 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2870 2871 // FIXME: What about dependent types? 2872 assert(FromClass->isRecordType() && "Pointer into non-class."); 2873 assert(ToClass->isRecordType() && "Pointer into non-class."); 2874 2875 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2876 /*DetectVirtual=*/true); 2877 bool DerivationOkay = 2878 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths); 2879 assert(DerivationOkay && 2880 "Should not have been called if derivation isn't OK."); 2881 (void)DerivationOkay; 2882 2883 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2884 getUnqualifiedType())) { 2885 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2886 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2887 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2888 return true; 2889 } 2890 2891 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2892 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2893 << FromClass << ToClass << QualType(VBase, 0) 2894 << From->getSourceRange(); 2895 return true; 2896 } 2897 2898 if (!IgnoreBaseAccess) 2899 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2900 Paths.front(), 2901 diag::err_downcast_from_inaccessible_base); 2902 2903 // Must be a base to derived member conversion. 2904 BuildBasePathArray(Paths, BasePath); 2905 Kind = CK_BaseToDerivedMemberPointer; 2906 return false; 2907 } 2908 2909 /// Determine whether the lifetime conversion between the two given 2910 /// qualifiers sets is nontrivial. 2911 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 2912 Qualifiers ToQuals) { 2913 // Converting anything to const __unsafe_unretained is trivial. 2914 if (ToQuals.hasConst() && 2915 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 2916 return false; 2917 2918 return true; 2919 } 2920 2921 /// IsQualificationConversion - Determines whether the conversion from 2922 /// an rvalue of type FromType to ToType is a qualification conversion 2923 /// (C++ 4.4). 2924 /// 2925 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2926 /// when the qualification conversion involves a change in the Objective-C 2927 /// object lifetime. 2928 bool 2929 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2930 bool CStyle, bool &ObjCLifetimeConversion) { 2931 FromType = Context.getCanonicalType(FromType); 2932 ToType = Context.getCanonicalType(ToType); 2933 ObjCLifetimeConversion = false; 2934 2935 // If FromType and ToType are the same type, this is not a 2936 // qualification conversion. 2937 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2938 return false; 2939 2940 // (C++ 4.4p4): 2941 // A conversion can add cv-qualifiers at levels other than the first 2942 // in multi-level pointers, subject to the following rules: [...] 2943 bool PreviousToQualsIncludeConst = true; 2944 bool UnwrappedAnyPointer = false; 2945 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2946 // Within each iteration of the loop, we check the qualifiers to 2947 // determine if this still looks like a qualification 2948 // conversion. Then, if all is well, we unwrap one more level of 2949 // pointers or pointers-to-members and do it all again 2950 // until there are no more pointers or pointers-to-members left to 2951 // unwrap. 2952 UnwrappedAnyPointer = true; 2953 2954 Qualifiers FromQuals = FromType.getQualifiers(); 2955 Qualifiers ToQuals = ToType.getQualifiers(); 2956 2957 // Ignore __unaligned qualifier if this type is void. 2958 if (ToType.getUnqualifiedType()->isVoidType()) 2959 FromQuals.removeUnaligned(); 2960 2961 // Objective-C ARC: 2962 // Check Objective-C lifetime conversions. 2963 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2964 UnwrappedAnyPointer) { 2965 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2966 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 2967 ObjCLifetimeConversion = true; 2968 FromQuals.removeObjCLifetime(); 2969 ToQuals.removeObjCLifetime(); 2970 } else { 2971 // Qualification conversions cannot cast between different 2972 // Objective-C lifetime qualifiers. 2973 return false; 2974 } 2975 } 2976 2977 // Allow addition/removal of GC attributes but not changing GC attributes. 2978 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2979 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2980 FromQuals.removeObjCGCAttr(); 2981 ToQuals.removeObjCGCAttr(); 2982 } 2983 2984 // -- for every j > 0, if const is in cv 1,j then const is in cv 2985 // 2,j, and similarly for volatile. 2986 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2987 return false; 2988 2989 // -- if the cv 1,j and cv 2,j are different, then const is in 2990 // every cv for 0 < k < j. 2991 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2992 && !PreviousToQualsIncludeConst) 2993 return false; 2994 2995 // Keep track of whether all prior cv-qualifiers in the "to" type 2996 // include const. 2997 PreviousToQualsIncludeConst 2998 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2999 } 3000 3001 // We are left with FromType and ToType being the pointee types 3002 // after unwrapping the original FromType and ToType the same number 3003 // of types. If we unwrapped any pointers, and if FromType and 3004 // ToType have the same unqualified type (since we checked 3005 // qualifiers above), then this is a qualification conversion. 3006 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3007 } 3008 3009 /// \brief - Determine whether this is a conversion from a scalar type to an 3010 /// atomic type. 3011 /// 3012 /// If successful, updates \c SCS's second and third steps in the conversion 3013 /// sequence to finish the conversion. 3014 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3015 bool InOverloadResolution, 3016 StandardConversionSequence &SCS, 3017 bool CStyle) { 3018 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3019 if (!ToAtomic) 3020 return false; 3021 3022 StandardConversionSequence InnerSCS; 3023 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3024 InOverloadResolution, InnerSCS, 3025 CStyle, /*AllowObjCWritebackConversion=*/false)) 3026 return false; 3027 3028 SCS.Second = InnerSCS.Second; 3029 SCS.setToType(1, InnerSCS.getToType(1)); 3030 SCS.Third = InnerSCS.Third; 3031 SCS.QualificationIncludesObjCLifetime 3032 = InnerSCS.QualificationIncludesObjCLifetime; 3033 SCS.setToType(2, InnerSCS.getToType(2)); 3034 return true; 3035 } 3036 3037 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3038 CXXConstructorDecl *Constructor, 3039 QualType Type) { 3040 const FunctionProtoType *CtorType = 3041 Constructor->getType()->getAs<FunctionProtoType>(); 3042 if (CtorType->getNumParams() > 0) { 3043 QualType FirstArg = CtorType->getParamType(0); 3044 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3045 return true; 3046 } 3047 return false; 3048 } 3049 3050 static OverloadingResult 3051 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3052 CXXRecordDecl *To, 3053 UserDefinedConversionSequence &User, 3054 OverloadCandidateSet &CandidateSet, 3055 bool AllowExplicit) { 3056 for (auto *D : S.LookupConstructors(To)) { 3057 auto Info = getConstructorInfo(D); 3058 if (!Info) 3059 continue; 3060 3061 bool Usable = !Info.Constructor->isInvalidDecl() && 3062 S.isInitListConstructor(Info.Constructor) && 3063 (AllowExplicit || !Info.Constructor->isExplicit()); 3064 if (Usable) { 3065 // If the first argument is (a reference to) the target type, 3066 // suppress conversions. 3067 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3068 S.Context, Info.Constructor, ToType); 3069 if (Info.ConstructorTmpl) 3070 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3071 /*ExplicitArgs*/ nullptr, From, 3072 CandidateSet, SuppressUserConversions); 3073 else 3074 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3075 CandidateSet, SuppressUserConversions); 3076 } 3077 } 3078 3079 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3080 3081 OverloadCandidateSet::iterator Best; 3082 switch (auto Result = 3083 CandidateSet.BestViableFunction(S, From->getLocStart(), 3084 Best, true)) { 3085 case OR_Deleted: 3086 case OR_Success: { 3087 // Record the standard conversion we used and the conversion function. 3088 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3089 QualType ThisType = Constructor->getThisType(S.Context); 3090 // Initializer lists don't have conversions as such. 3091 User.Before.setAsIdentityConversion(); 3092 User.HadMultipleCandidates = HadMultipleCandidates; 3093 User.ConversionFunction = Constructor; 3094 User.FoundConversionFunction = Best->FoundDecl; 3095 User.After.setAsIdentityConversion(); 3096 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3097 User.After.setAllToTypes(ToType); 3098 return Result; 3099 } 3100 3101 case OR_No_Viable_Function: 3102 return OR_No_Viable_Function; 3103 case OR_Ambiguous: 3104 return OR_Ambiguous; 3105 } 3106 3107 llvm_unreachable("Invalid OverloadResult!"); 3108 } 3109 3110 /// Determines whether there is a user-defined conversion sequence 3111 /// (C++ [over.ics.user]) that converts expression From to the type 3112 /// ToType. If such a conversion exists, User will contain the 3113 /// user-defined conversion sequence that performs such a conversion 3114 /// and this routine will return true. Otherwise, this routine returns 3115 /// false and User is unspecified. 3116 /// 3117 /// \param AllowExplicit true if the conversion should consider C++0x 3118 /// "explicit" conversion functions as well as non-explicit conversion 3119 /// functions (C++0x [class.conv.fct]p2). 3120 /// 3121 /// \param AllowObjCConversionOnExplicit true if the conversion should 3122 /// allow an extra Objective-C pointer conversion on uses of explicit 3123 /// constructors. Requires \c AllowExplicit to also be set. 3124 static OverloadingResult 3125 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3126 UserDefinedConversionSequence &User, 3127 OverloadCandidateSet &CandidateSet, 3128 bool AllowExplicit, 3129 bool AllowObjCConversionOnExplicit) { 3130 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3131 3132 // Whether we will only visit constructors. 3133 bool ConstructorsOnly = false; 3134 3135 // If the type we are conversion to is a class type, enumerate its 3136 // constructors. 3137 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3138 // C++ [over.match.ctor]p1: 3139 // When objects of class type are direct-initialized (8.5), or 3140 // copy-initialized from an expression of the same or a 3141 // derived class type (8.5), overload resolution selects the 3142 // constructor. [...] For copy-initialization, the candidate 3143 // functions are all the converting constructors (12.3.1) of 3144 // that class. The argument list is the expression-list within 3145 // the parentheses of the initializer. 3146 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3147 (From->getType()->getAs<RecordType>() && 3148 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType))) 3149 ConstructorsOnly = true; 3150 3151 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3152 // We're not going to find any constructors. 3153 } else if (CXXRecordDecl *ToRecordDecl 3154 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3155 3156 Expr **Args = &From; 3157 unsigned NumArgs = 1; 3158 bool ListInitializing = false; 3159 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3160 // But first, see if there is an init-list-constructor that will work. 3161 OverloadingResult Result = IsInitializerListConstructorConversion( 3162 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3163 if (Result != OR_No_Viable_Function) 3164 return Result; 3165 // Never mind. 3166 CandidateSet.clear(); 3167 3168 // If we're list-initializing, we pass the individual elements as 3169 // arguments, not the entire list. 3170 Args = InitList->getInits(); 3171 NumArgs = InitList->getNumInits(); 3172 ListInitializing = true; 3173 } 3174 3175 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3176 auto Info = getConstructorInfo(D); 3177 if (!Info) 3178 continue; 3179 3180 bool Usable = !Info.Constructor->isInvalidDecl(); 3181 if (ListInitializing) 3182 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3183 else 3184 Usable = Usable && 3185 Info.Constructor->isConvertingConstructor(AllowExplicit); 3186 if (Usable) { 3187 bool SuppressUserConversions = !ConstructorsOnly; 3188 if (SuppressUserConversions && ListInitializing) { 3189 SuppressUserConversions = false; 3190 if (NumArgs == 1) { 3191 // If the first argument is (a reference to) the target type, 3192 // suppress conversions. 3193 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3194 S.Context, Info.Constructor, ToType); 3195 } 3196 } 3197 if (Info.ConstructorTmpl) 3198 S.AddTemplateOverloadCandidate( 3199 Info.ConstructorTmpl, Info.FoundDecl, 3200 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3201 CandidateSet, SuppressUserConversions); 3202 else 3203 // Allow one user-defined conversion when user specifies a 3204 // From->ToType conversion via an static cast (c-style, etc). 3205 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3206 llvm::makeArrayRef(Args, NumArgs), 3207 CandidateSet, SuppressUserConversions); 3208 } 3209 } 3210 } 3211 } 3212 3213 // Enumerate conversion functions, if we're allowed to. 3214 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3215 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) { 3216 // No conversion functions from incomplete types. 3217 } else if (const RecordType *FromRecordType 3218 = From->getType()->getAs<RecordType>()) { 3219 if (CXXRecordDecl *FromRecordDecl 3220 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3221 // Add all of the conversion functions as candidates. 3222 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3223 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3224 DeclAccessPair FoundDecl = I.getPair(); 3225 NamedDecl *D = FoundDecl.getDecl(); 3226 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3227 if (isa<UsingShadowDecl>(D)) 3228 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3229 3230 CXXConversionDecl *Conv; 3231 FunctionTemplateDecl *ConvTemplate; 3232 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3233 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3234 else 3235 Conv = cast<CXXConversionDecl>(D); 3236 3237 if (AllowExplicit || !Conv->isExplicit()) { 3238 if (ConvTemplate) 3239 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3240 ActingContext, From, ToType, 3241 CandidateSet, 3242 AllowObjCConversionOnExplicit); 3243 else 3244 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3245 From, ToType, CandidateSet, 3246 AllowObjCConversionOnExplicit); 3247 } 3248 } 3249 } 3250 } 3251 3252 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3253 3254 OverloadCandidateSet::iterator Best; 3255 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(), 3256 Best, true)) { 3257 case OR_Success: 3258 case OR_Deleted: 3259 // Record the standard conversion we used and the conversion function. 3260 if (CXXConstructorDecl *Constructor 3261 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3262 // C++ [over.ics.user]p1: 3263 // If the user-defined conversion is specified by a 3264 // constructor (12.3.1), the initial standard conversion 3265 // sequence converts the source type to the type required by 3266 // the argument of the constructor. 3267 // 3268 QualType ThisType = Constructor->getThisType(S.Context); 3269 if (isa<InitListExpr>(From)) { 3270 // Initializer lists don't have conversions as such. 3271 User.Before.setAsIdentityConversion(); 3272 } else { 3273 if (Best->Conversions[0].isEllipsis()) 3274 User.EllipsisConversion = true; 3275 else { 3276 User.Before = Best->Conversions[0].Standard; 3277 User.EllipsisConversion = false; 3278 } 3279 } 3280 User.HadMultipleCandidates = HadMultipleCandidates; 3281 User.ConversionFunction = Constructor; 3282 User.FoundConversionFunction = Best->FoundDecl; 3283 User.After.setAsIdentityConversion(); 3284 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3285 User.After.setAllToTypes(ToType); 3286 return Result; 3287 } 3288 if (CXXConversionDecl *Conversion 3289 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3290 // C++ [over.ics.user]p1: 3291 // 3292 // [...] If the user-defined conversion is specified by a 3293 // conversion function (12.3.2), the initial standard 3294 // conversion sequence converts the source type to the 3295 // implicit object parameter of the conversion function. 3296 User.Before = Best->Conversions[0].Standard; 3297 User.HadMultipleCandidates = HadMultipleCandidates; 3298 User.ConversionFunction = Conversion; 3299 User.FoundConversionFunction = Best->FoundDecl; 3300 User.EllipsisConversion = false; 3301 3302 // C++ [over.ics.user]p2: 3303 // The second standard conversion sequence converts the 3304 // result of the user-defined conversion to the target type 3305 // for the sequence. Since an implicit conversion sequence 3306 // is an initialization, the special rules for 3307 // initialization by user-defined conversion apply when 3308 // selecting the best user-defined conversion for a 3309 // user-defined conversion sequence (see 13.3.3 and 3310 // 13.3.3.1). 3311 User.After = Best->FinalConversion; 3312 return Result; 3313 } 3314 llvm_unreachable("Not a constructor or conversion function?"); 3315 3316 case OR_No_Viable_Function: 3317 return OR_No_Viable_Function; 3318 3319 case OR_Ambiguous: 3320 return OR_Ambiguous; 3321 } 3322 3323 llvm_unreachable("Invalid OverloadResult!"); 3324 } 3325 3326 bool 3327 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3328 ImplicitConversionSequence ICS; 3329 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3330 OverloadCandidateSet::CSK_Normal); 3331 OverloadingResult OvResult = 3332 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3333 CandidateSet, false, false); 3334 if (OvResult == OR_Ambiguous) 3335 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3336 << From->getType() << ToType << From->getSourceRange(); 3337 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3338 if (!RequireCompleteType(From->getLocStart(), ToType, 3339 diag::err_typecheck_nonviable_condition_incomplete, 3340 From->getType(), From->getSourceRange())) 3341 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3342 << false << From->getType() << From->getSourceRange() << ToType; 3343 } else 3344 return false; 3345 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3346 return true; 3347 } 3348 3349 /// \brief Compare the user-defined conversion functions or constructors 3350 /// of two user-defined conversion sequences to determine whether any ordering 3351 /// is possible. 3352 static ImplicitConversionSequence::CompareKind 3353 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3354 FunctionDecl *Function2) { 3355 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3356 return ImplicitConversionSequence::Indistinguishable; 3357 3358 // Objective-C++: 3359 // If both conversion functions are implicitly-declared conversions from 3360 // a lambda closure type to a function pointer and a block pointer, 3361 // respectively, always prefer the conversion to a function pointer, 3362 // because the function pointer is more lightweight and is more likely 3363 // to keep code working. 3364 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3365 if (!Conv1) 3366 return ImplicitConversionSequence::Indistinguishable; 3367 3368 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3369 if (!Conv2) 3370 return ImplicitConversionSequence::Indistinguishable; 3371 3372 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3373 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3374 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3375 if (Block1 != Block2) 3376 return Block1 ? ImplicitConversionSequence::Worse 3377 : ImplicitConversionSequence::Better; 3378 } 3379 3380 return ImplicitConversionSequence::Indistinguishable; 3381 } 3382 3383 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3384 const ImplicitConversionSequence &ICS) { 3385 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3386 (ICS.isUserDefined() && 3387 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3388 } 3389 3390 /// CompareImplicitConversionSequences - Compare two implicit 3391 /// conversion sequences to determine whether one is better than the 3392 /// other or if they are indistinguishable (C++ 13.3.3.2). 3393 static ImplicitConversionSequence::CompareKind 3394 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3395 const ImplicitConversionSequence& ICS1, 3396 const ImplicitConversionSequence& ICS2) 3397 { 3398 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3399 // conversion sequences (as defined in 13.3.3.1) 3400 // -- a standard conversion sequence (13.3.3.1.1) is a better 3401 // conversion sequence than a user-defined conversion sequence or 3402 // an ellipsis conversion sequence, and 3403 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3404 // conversion sequence than an ellipsis conversion sequence 3405 // (13.3.3.1.3). 3406 // 3407 // C++0x [over.best.ics]p10: 3408 // For the purpose of ranking implicit conversion sequences as 3409 // described in 13.3.3.2, the ambiguous conversion sequence is 3410 // treated as a user-defined sequence that is indistinguishable 3411 // from any other user-defined conversion sequence. 3412 3413 // String literal to 'char *' conversion has been deprecated in C++03. It has 3414 // been removed from C++11. We still accept this conversion, if it happens at 3415 // the best viable function. Otherwise, this conversion is considered worse 3416 // than ellipsis conversion. Consider this as an extension; this is not in the 3417 // standard. For example: 3418 // 3419 // int &f(...); // #1 3420 // void f(char*); // #2 3421 // void g() { int &r = f("foo"); } 3422 // 3423 // In C++03, we pick #2 as the best viable function. 3424 // In C++11, we pick #1 as the best viable function, because ellipsis 3425 // conversion is better than string-literal to char* conversion (since there 3426 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3427 // convert arguments, #2 would be the best viable function in C++11. 3428 // If the best viable function has this conversion, a warning will be issued 3429 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3430 3431 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3432 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3433 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3434 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3435 ? ImplicitConversionSequence::Worse 3436 : ImplicitConversionSequence::Better; 3437 3438 if (ICS1.getKindRank() < ICS2.getKindRank()) 3439 return ImplicitConversionSequence::Better; 3440 if (ICS2.getKindRank() < ICS1.getKindRank()) 3441 return ImplicitConversionSequence::Worse; 3442 3443 // The following checks require both conversion sequences to be of 3444 // the same kind. 3445 if (ICS1.getKind() != ICS2.getKind()) 3446 return ImplicitConversionSequence::Indistinguishable; 3447 3448 ImplicitConversionSequence::CompareKind Result = 3449 ImplicitConversionSequence::Indistinguishable; 3450 3451 // Two implicit conversion sequences of the same form are 3452 // indistinguishable conversion sequences unless one of the 3453 // following rules apply: (C++ 13.3.3.2p3): 3454 3455 // List-initialization sequence L1 is a better conversion sequence than 3456 // list-initialization sequence L2 if: 3457 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3458 // if not that, 3459 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3460 // and N1 is smaller than N2., 3461 // even if one of the other rules in this paragraph would otherwise apply. 3462 if (!ICS1.isBad()) { 3463 if (ICS1.isStdInitializerListElement() && 3464 !ICS2.isStdInitializerListElement()) 3465 return ImplicitConversionSequence::Better; 3466 if (!ICS1.isStdInitializerListElement() && 3467 ICS2.isStdInitializerListElement()) 3468 return ImplicitConversionSequence::Worse; 3469 } 3470 3471 if (ICS1.isStandard()) 3472 // Standard conversion sequence S1 is a better conversion sequence than 3473 // standard conversion sequence S2 if [...] 3474 Result = CompareStandardConversionSequences(S, Loc, 3475 ICS1.Standard, ICS2.Standard); 3476 else if (ICS1.isUserDefined()) { 3477 // User-defined conversion sequence U1 is a better conversion 3478 // sequence than another user-defined conversion sequence U2 if 3479 // they contain the same user-defined conversion function or 3480 // constructor and if the second standard conversion sequence of 3481 // U1 is better than the second standard conversion sequence of 3482 // U2 (C++ 13.3.3.2p3). 3483 if (ICS1.UserDefined.ConversionFunction == 3484 ICS2.UserDefined.ConversionFunction) 3485 Result = CompareStandardConversionSequences(S, Loc, 3486 ICS1.UserDefined.After, 3487 ICS2.UserDefined.After); 3488 else 3489 Result = compareConversionFunctions(S, 3490 ICS1.UserDefined.ConversionFunction, 3491 ICS2.UserDefined.ConversionFunction); 3492 } 3493 3494 return Result; 3495 } 3496 3497 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3498 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3499 Qualifiers Quals; 3500 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3501 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3502 } 3503 3504 return Context.hasSameUnqualifiedType(T1, T2); 3505 } 3506 3507 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3508 // determine if one is a proper subset of the other. 3509 static ImplicitConversionSequence::CompareKind 3510 compareStandardConversionSubsets(ASTContext &Context, 3511 const StandardConversionSequence& SCS1, 3512 const StandardConversionSequence& SCS2) { 3513 ImplicitConversionSequence::CompareKind Result 3514 = ImplicitConversionSequence::Indistinguishable; 3515 3516 // the identity conversion sequence is considered to be a subsequence of 3517 // any non-identity conversion sequence 3518 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3519 return ImplicitConversionSequence::Better; 3520 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3521 return ImplicitConversionSequence::Worse; 3522 3523 if (SCS1.Second != SCS2.Second) { 3524 if (SCS1.Second == ICK_Identity) 3525 Result = ImplicitConversionSequence::Better; 3526 else if (SCS2.Second == ICK_Identity) 3527 Result = ImplicitConversionSequence::Worse; 3528 else 3529 return ImplicitConversionSequence::Indistinguishable; 3530 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3531 return ImplicitConversionSequence::Indistinguishable; 3532 3533 if (SCS1.Third == SCS2.Third) { 3534 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3535 : ImplicitConversionSequence::Indistinguishable; 3536 } 3537 3538 if (SCS1.Third == ICK_Identity) 3539 return Result == ImplicitConversionSequence::Worse 3540 ? ImplicitConversionSequence::Indistinguishable 3541 : ImplicitConversionSequence::Better; 3542 3543 if (SCS2.Third == ICK_Identity) 3544 return Result == ImplicitConversionSequence::Better 3545 ? ImplicitConversionSequence::Indistinguishable 3546 : ImplicitConversionSequence::Worse; 3547 3548 return ImplicitConversionSequence::Indistinguishable; 3549 } 3550 3551 /// \brief Determine whether one of the given reference bindings is better 3552 /// than the other based on what kind of bindings they are. 3553 static bool 3554 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3555 const StandardConversionSequence &SCS2) { 3556 // C++0x [over.ics.rank]p3b4: 3557 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3558 // implicit object parameter of a non-static member function declared 3559 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3560 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3561 // lvalue reference to a function lvalue and S2 binds an rvalue 3562 // reference*. 3563 // 3564 // FIXME: Rvalue references. We're going rogue with the above edits, 3565 // because the semantics in the current C++0x working paper (N3225 at the 3566 // time of this writing) break the standard definition of std::forward 3567 // and std::reference_wrapper when dealing with references to functions. 3568 // Proposed wording changes submitted to CWG for consideration. 3569 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3570 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3571 return false; 3572 3573 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3574 SCS2.IsLvalueReference) || 3575 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3576 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3577 } 3578 3579 /// CompareStandardConversionSequences - Compare two standard 3580 /// conversion sequences to determine whether one is better than the 3581 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3582 static ImplicitConversionSequence::CompareKind 3583 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3584 const StandardConversionSequence& SCS1, 3585 const StandardConversionSequence& SCS2) 3586 { 3587 // Standard conversion sequence S1 is a better conversion sequence 3588 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3589 3590 // -- S1 is a proper subsequence of S2 (comparing the conversion 3591 // sequences in the canonical form defined by 13.3.3.1.1, 3592 // excluding any Lvalue Transformation; the identity conversion 3593 // sequence is considered to be a subsequence of any 3594 // non-identity conversion sequence) or, if not that, 3595 if (ImplicitConversionSequence::CompareKind CK 3596 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3597 return CK; 3598 3599 // -- the rank of S1 is better than the rank of S2 (by the rules 3600 // defined below), or, if not that, 3601 ImplicitConversionRank Rank1 = SCS1.getRank(); 3602 ImplicitConversionRank Rank2 = SCS2.getRank(); 3603 if (Rank1 < Rank2) 3604 return ImplicitConversionSequence::Better; 3605 else if (Rank2 < Rank1) 3606 return ImplicitConversionSequence::Worse; 3607 3608 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3609 // are indistinguishable unless one of the following rules 3610 // applies: 3611 3612 // A conversion that is not a conversion of a pointer, or 3613 // pointer to member, to bool is better than another conversion 3614 // that is such a conversion. 3615 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3616 return SCS2.isPointerConversionToBool() 3617 ? ImplicitConversionSequence::Better 3618 : ImplicitConversionSequence::Worse; 3619 3620 // C++ [over.ics.rank]p4b2: 3621 // 3622 // If class B is derived directly or indirectly from class A, 3623 // conversion of B* to A* is better than conversion of B* to 3624 // void*, and conversion of A* to void* is better than conversion 3625 // of B* to void*. 3626 bool SCS1ConvertsToVoid 3627 = SCS1.isPointerConversionToVoidPointer(S.Context); 3628 bool SCS2ConvertsToVoid 3629 = SCS2.isPointerConversionToVoidPointer(S.Context); 3630 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3631 // Exactly one of the conversion sequences is a conversion to 3632 // a void pointer; it's the worse conversion. 3633 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3634 : ImplicitConversionSequence::Worse; 3635 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3636 // Neither conversion sequence converts to a void pointer; compare 3637 // their derived-to-base conversions. 3638 if (ImplicitConversionSequence::CompareKind DerivedCK 3639 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3640 return DerivedCK; 3641 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3642 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3643 // Both conversion sequences are conversions to void 3644 // pointers. Compare the source types to determine if there's an 3645 // inheritance relationship in their sources. 3646 QualType FromType1 = SCS1.getFromType(); 3647 QualType FromType2 = SCS2.getFromType(); 3648 3649 // Adjust the types we're converting from via the array-to-pointer 3650 // conversion, if we need to. 3651 if (SCS1.First == ICK_Array_To_Pointer) 3652 FromType1 = S.Context.getArrayDecayedType(FromType1); 3653 if (SCS2.First == ICK_Array_To_Pointer) 3654 FromType2 = S.Context.getArrayDecayedType(FromType2); 3655 3656 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3657 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3658 3659 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3660 return ImplicitConversionSequence::Better; 3661 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3662 return ImplicitConversionSequence::Worse; 3663 3664 // Objective-C++: If one interface is more specific than the 3665 // other, it is the better one. 3666 const ObjCObjectPointerType* FromObjCPtr1 3667 = FromType1->getAs<ObjCObjectPointerType>(); 3668 const ObjCObjectPointerType* FromObjCPtr2 3669 = FromType2->getAs<ObjCObjectPointerType>(); 3670 if (FromObjCPtr1 && FromObjCPtr2) { 3671 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3672 FromObjCPtr2); 3673 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3674 FromObjCPtr1); 3675 if (AssignLeft != AssignRight) { 3676 return AssignLeft? ImplicitConversionSequence::Better 3677 : ImplicitConversionSequence::Worse; 3678 } 3679 } 3680 } 3681 3682 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3683 // bullet 3). 3684 if (ImplicitConversionSequence::CompareKind QualCK 3685 = CompareQualificationConversions(S, SCS1, SCS2)) 3686 return QualCK; 3687 3688 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3689 // Check for a better reference binding based on the kind of bindings. 3690 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3691 return ImplicitConversionSequence::Better; 3692 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3693 return ImplicitConversionSequence::Worse; 3694 3695 // C++ [over.ics.rank]p3b4: 3696 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3697 // which the references refer are the same type except for 3698 // top-level cv-qualifiers, and the type to which the reference 3699 // initialized by S2 refers is more cv-qualified than the type 3700 // to which the reference initialized by S1 refers. 3701 QualType T1 = SCS1.getToType(2); 3702 QualType T2 = SCS2.getToType(2); 3703 T1 = S.Context.getCanonicalType(T1); 3704 T2 = S.Context.getCanonicalType(T2); 3705 Qualifiers T1Quals, T2Quals; 3706 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3707 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3708 if (UnqualT1 == UnqualT2) { 3709 // Objective-C++ ARC: If the references refer to objects with different 3710 // lifetimes, prefer bindings that don't change lifetime. 3711 if (SCS1.ObjCLifetimeConversionBinding != 3712 SCS2.ObjCLifetimeConversionBinding) { 3713 return SCS1.ObjCLifetimeConversionBinding 3714 ? ImplicitConversionSequence::Worse 3715 : ImplicitConversionSequence::Better; 3716 } 3717 3718 // If the type is an array type, promote the element qualifiers to the 3719 // type for comparison. 3720 if (isa<ArrayType>(T1) && T1Quals) 3721 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3722 if (isa<ArrayType>(T2) && T2Quals) 3723 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3724 if (T2.isMoreQualifiedThan(T1)) 3725 return ImplicitConversionSequence::Better; 3726 else if (T1.isMoreQualifiedThan(T2)) 3727 return ImplicitConversionSequence::Worse; 3728 } 3729 } 3730 3731 // In Microsoft mode, prefer an integral conversion to a 3732 // floating-to-integral conversion if the integral conversion 3733 // is between types of the same size. 3734 // For example: 3735 // void f(float); 3736 // void f(int); 3737 // int main { 3738 // long a; 3739 // f(a); 3740 // } 3741 // Here, MSVC will call f(int) instead of generating a compile error 3742 // as clang will do in standard mode. 3743 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3744 SCS2.Second == ICK_Floating_Integral && 3745 S.Context.getTypeSize(SCS1.getFromType()) == 3746 S.Context.getTypeSize(SCS1.getToType(2))) 3747 return ImplicitConversionSequence::Better; 3748 3749 return ImplicitConversionSequence::Indistinguishable; 3750 } 3751 3752 /// CompareQualificationConversions - Compares two standard conversion 3753 /// sequences to determine whether they can be ranked based on their 3754 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3755 static ImplicitConversionSequence::CompareKind 3756 CompareQualificationConversions(Sema &S, 3757 const StandardConversionSequence& SCS1, 3758 const StandardConversionSequence& SCS2) { 3759 // C++ 13.3.3.2p3: 3760 // -- S1 and S2 differ only in their qualification conversion and 3761 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3762 // cv-qualification signature of type T1 is a proper subset of 3763 // the cv-qualification signature of type T2, and S1 is not the 3764 // deprecated string literal array-to-pointer conversion (4.2). 3765 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3766 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3767 return ImplicitConversionSequence::Indistinguishable; 3768 3769 // FIXME: the example in the standard doesn't use a qualification 3770 // conversion (!) 3771 QualType T1 = SCS1.getToType(2); 3772 QualType T2 = SCS2.getToType(2); 3773 T1 = S.Context.getCanonicalType(T1); 3774 T2 = S.Context.getCanonicalType(T2); 3775 Qualifiers T1Quals, T2Quals; 3776 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3777 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3778 3779 // If the types are the same, we won't learn anything by unwrapped 3780 // them. 3781 if (UnqualT1 == UnqualT2) 3782 return ImplicitConversionSequence::Indistinguishable; 3783 3784 // If the type is an array type, promote the element qualifiers to the type 3785 // for comparison. 3786 if (isa<ArrayType>(T1) && T1Quals) 3787 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3788 if (isa<ArrayType>(T2) && T2Quals) 3789 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3790 3791 ImplicitConversionSequence::CompareKind Result 3792 = ImplicitConversionSequence::Indistinguishable; 3793 3794 // Objective-C++ ARC: 3795 // Prefer qualification conversions not involving a change in lifetime 3796 // to qualification conversions that do not change lifetime. 3797 if (SCS1.QualificationIncludesObjCLifetime != 3798 SCS2.QualificationIncludesObjCLifetime) { 3799 Result = SCS1.QualificationIncludesObjCLifetime 3800 ? ImplicitConversionSequence::Worse 3801 : ImplicitConversionSequence::Better; 3802 } 3803 3804 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3805 // Within each iteration of the loop, we check the qualifiers to 3806 // determine if this still looks like a qualification 3807 // conversion. Then, if all is well, we unwrap one more level of 3808 // pointers or pointers-to-members and do it all again 3809 // until there are no more pointers or pointers-to-members left 3810 // to unwrap. This essentially mimics what 3811 // IsQualificationConversion does, but here we're checking for a 3812 // strict subset of qualifiers. 3813 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3814 // The qualifiers are the same, so this doesn't tell us anything 3815 // about how the sequences rank. 3816 ; 3817 else if (T2.isMoreQualifiedThan(T1)) { 3818 // T1 has fewer qualifiers, so it could be the better sequence. 3819 if (Result == ImplicitConversionSequence::Worse) 3820 // Neither has qualifiers that are a subset of the other's 3821 // qualifiers. 3822 return ImplicitConversionSequence::Indistinguishable; 3823 3824 Result = ImplicitConversionSequence::Better; 3825 } else if (T1.isMoreQualifiedThan(T2)) { 3826 // T2 has fewer qualifiers, so it could be the better sequence. 3827 if (Result == ImplicitConversionSequence::Better) 3828 // Neither has qualifiers that are a subset of the other's 3829 // qualifiers. 3830 return ImplicitConversionSequence::Indistinguishable; 3831 3832 Result = ImplicitConversionSequence::Worse; 3833 } else { 3834 // Qualifiers are disjoint. 3835 return ImplicitConversionSequence::Indistinguishable; 3836 } 3837 3838 // If the types after this point are equivalent, we're done. 3839 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3840 break; 3841 } 3842 3843 // Check that the winning standard conversion sequence isn't using 3844 // the deprecated string literal array to pointer conversion. 3845 switch (Result) { 3846 case ImplicitConversionSequence::Better: 3847 if (SCS1.DeprecatedStringLiteralToCharPtr) 3848 Result = ImplicitConversionSequence::Indistinguishable; 3849 break; 3850 3851 case ImplicitConversionSequence::Indistinguishable: 3852 break; 3853 3854 case ImplicitConversionSequence::Worse: 3855 if (SCS2.DeprecatedStringLiteralToCharPtr) 3856 Result = ImplicitConversionSequence::Indistinguishable; 3857 break; 3858 } 3859 3860 return Result; 3861 } 3862 3863 /// CompareDerivedToBaseConversions - Compares two standard conversion 3864 /// sequences to determine whether they can be ranked based on their 3865 /// various kinds of derived-to-base conversions (C++ 3866 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3867 /// conversions between Objective-C interface types. 3868 static ImplicitConversionSequence::CompareKind 3869 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 3870 const StandardConversionSequence& SCS1, 3871 const StandardConversionSequence& SCS2) { 3872 QualType FromType1 = SCS1.getFromType(); 3873 QualType ToType1 = SCS1.getToType(1); 3874 QualType FromType2 = SCS2.getFromType(); 3875 QualType ToType2 = SCS2.getToType(1); 3876 3877 // Adjust the types we're converting from via the array-to-pointer 3878 // conversion, if we need to. 3879 if (SCS1.First == ICK_Array_To_Pointer) 3880 FromType1 = S.Context.getArrayDecayedType(FromType1); 3881 if (SCS2.First == ICK_Array_To_Pointer) 3882 FromType2 = S.Context.getArrayDecayedType(FromType2); 3883 3884 // Canonicalize all of the types. 3885 FromType1 = S.Context.getCanonicalType(FromType1); 3886 ToType1 = S.Context.getCanonicalType(ToType1); 3887 FromType2 = S.Context.getCanonicalType(FromType2); 3888 ToType2 = S.Context.getCanonicalType(ToType2); 3889 3890 // C++ [over.ics.rank]p4b3: 3891 // 3892 // If class B is derived directly or indirectly from class A and 3893 // class C is derived directly or indirectly from B, 3894 // 3895 // Compare based on pointer conversions. 3896 if (SCS1.Second == ICK_Pointer_Conversion && 3897 SCS2.Second == ICK_Pointer_Conversion && 3898 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3899 FromType1->isPointerType() && FromType2->isPointerType() && 3900 ToType1->isPointerType() && ToType2->isPointerType()) { 3901 QualType FromPointee1 3902 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3903 QualType ToPointee1 3904 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3905 QualType FromPointee2 3906 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3907 QualType ToPointee2 3908 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3909 3910 // -- conversion of C* to B* is better than conversion of C* to A*, 3911 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3912 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 3913 return ImplicitConversionSequence::Better; 3914 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 3915 return ImplicitConversionSequence::Worse; 3916 } 3917 3918 // -- conversion of B* to A* is better than conversion of C* to A*, 3919 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3920 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3921 return ImplicitConversionSequence::Better; 3922 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3923 return ImplicitConversionSequence::Worse; 3924 } 3925 } else if (SCS1.Second == ICK_Pointer_Conversion && 3926 SCS2.Second == ICK_Pointer_Conversion) { 3927 const ObjCObjectPointerType *FromPtr1 3928 = FromType1->getAs<ObjCObjectPointerType>(); 3929 const ObjCObjectPointerType *FromPtr2 3930 = FromType2->getAs<ObjCObjectPointerType>(); 3931 const ObjCObjectPointerType *ToPtr1 3932 = ToType1->getAs<ObjCObjectPointerType>(); 3933 const ObjCObjectPointerType *ToPtr2 3934 = ToType2->getAs<ObjCObjectPointerType>(); 3935 3936 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3937 // Apply the same conversion ranking rules for Objective-C pointer types 3938 // that we do for C++ pointers to class types. However, we employ the 3939 // Objective-C pseudo-subtyping relationship used for assignment of 3940 // Objective-C pointer types. 3941 bool FromAssignLeft 3942 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3943 bool FromAssignRight 3944 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3945 bool ToAssignLeft 3946 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3947 bool ToAssignRight 3948 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3949 3950 // A conversion to an a non-id object pointer type or qualified 'id' 3951 // type is better than a conversion to 'id'. 3952 if (ToPtr1->isObjCIdType() && 3953 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3954 return ImplicitConversionSequence::Worse; 3955 if (ToPtr2->isObjCIdType() && 3956 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3957 return ImplicitConversionSequence::Better; 3958 3959 // A conversion to a non-id object pointer type is better than a 3960 // conversion to a qualified 'id' type 3961 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3962 return ImplicitConversionSequence::Worse; 3963 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3964 return ImplicitConversionSequence::Better; 3965 3966 // A conversion to an a non-Class object pointer type or qualified 'Class' 3967 // type is better than a conversion to 'Class'. 3968 if (ToPtr1->isObjCClassType() && 3969 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3970 return ImplicitConversionSequence::Worse; 3971 if (ToPtr2->isObjCClassType() && 3972 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3973 return ImplicitConversionSequence::Better; 3974 3975 // A conversion to a non-Class object pointer type is better than a 3976 // conversion to a qualified 'Class' type. 3977 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3978 return ImplicitConversionSequence::Worse; 3979 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3980 return ImplicitConversionSequence::Better; 3981 3982 // -- "conversion of C* to B* is better than conversion of C* to A*," 3983 if (S.Context.hasSameType(FromType1, FromType2) && 3984 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3985 (ToAssignLeft != ToAssignRight)) 3986 return ToAssignLeft? ImplicitConversionSequence::Worse 3987 : ImplicitConversionSequence::Better; 3988 3989 // -- "conversion of B* to A* is better than conversion of C* to A*," 3990 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3991 (FromAssignLeft != FromAssignRight)) 3992 return FromAssignLeft? ImplicitConversionSequence::Better 3993 : ImplicitConversionSequence::Worse; 3994 } 3995 } 3996 3997 // Ranking of member-pointer types. 3998 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3999 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4000 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4001 const MemberPointerType * FromMemPointer1 = 4002 FromType1->getAs<MemberPointerType>(); 4003 const MemberPointerType * ToMemPointer1 = 4004 ToType1->getAs<MemberPointerType>(); 4005 const MemberPointerType * FromMemPointer2 = 4006 FromType2->getAs<MemberPointerType>(); 4007 const MemberPointerType * ToMemPointer2 = 4008 ToType2->getAs<MemberPointerType>(); 4009 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4010 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4011 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4012 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4013 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4014 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4015 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4016 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4017 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4018 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4019 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4020 return ImplicitConversionSequence::Worse; 4021 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4022 return ImplicitConversionSequence::Better; 4023 } 4024 // conversion of B::* to C::* is better than conversion of A::* to C::* 4025 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4026 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4027 return ImplicitConversionSequence::Better; 4028 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4029 return ImplicitConversionSequence::Worse; 4030 } 4031 } 4032 4033 if (SCS1.Second == ICK_Derived_To_Base) { 4034 // -- conversion of C to B is better than conversion of C to A, 4035 // -- binding of an expression of type C to a reference of type 4036 // B& is better than binding an expression of type C to a 4037 // reference of type A&, 4038 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4039 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4040 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4041 return ImplicitConversionSequence::Better; 4042 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4043 return ImplicitConversionSequence::Worse; 4044 } 4045 4046 // -- conversion of B to A is better than conversion of C to A. 4047 // -- binding of an expression of type B to a reference of type 4048 // A& is better than binding an expression of type C to a 4049 // reference of type A&, 4050 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4051 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4052 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4053 return ImplicitConversionSequence::Better; 4054 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4055 return ImplicitConversionSequence::Worse; 4056 } 4057 } 4058 4059 return ImplicitConversionSequence::Indistinguishable; 4060 } 4061 4062 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 4063 /// C++ class. 4064 static bool isTypeValid(QualType T) { 4065 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4066 return !Record->isInvalidDecl(); 4067 4068 return true; 4069 } 4070 4071 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4072 /// determine whether they are reference-related, 4073 /// reference-compatible, reference-compatible with added 4074 /// qualification, or incompatible, for use in C++ initialization by 4075 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4076 /// type, and the first type (T1) is the pointee type of the reference 4077 /// type being initialized. 4078 Sema::ReferenceCompareResult 4079 Sema::CompareReferenceRelationship(SourceLocation Loc, 4080 QualType OrigT1, QualType OrigT2, 4081 bool &DerivedToBase, 4082 bool &ObjCConversion, 4083 bool &ObjCLifetimeConversion) { 4084 assert(!OrigT1->isReferenceType() && 4085 "T1 must be the pointee type of the reference type"); 4086 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4087 4088 QualType T1 = Context.getCanonicalType(OrigT1); 4089 QualType T2 = Context.getCanonicalType(OrigT2); 4090 Qualifiers T1Quals, T2Quals; 4091 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4092 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4093 4094 // C++ [dcl.init.ref]p4: 4095 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4096 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4097 // T1 is a base class of T2. 4098 DerivedToBase = false; 4099 ObjCConversion = false; 4100 ObjCLifetimeConversion = false; 4101 if (UnqualT1 == UnqualT2) { 4102 // Nothing to do. 4103 } else if (isCompleteType(Loc, OrigT2) && 4104 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4105 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4106 DerivedToBase = true; 4107 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4108 UnqualT2->isObjCObjectOrInterfaceType() && 4109 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4110 ObjCConversion = true; 4111 else 4112 return Ref_Incompatible; 4113 4114 // At this point, we know that T1 and T2 are reference-related (at 4115 // least). 4116 4117 // If the type is an array type, promote the element qualifiers to the type 4118 // for comparison. 4119 if (isa<ArrayType>(T1) && T1Quals) 4120 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4121 if (isa<ArrayType>(T2) && T2Quals) 4122 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4123 4124 // C++ [dcl.init.ref]p4: 4125 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4126 // reference-related to T2 and cv1 is the same cv-qualification 4127 // as, or greater cv-qualification than, cv2. For purposes of 4128 // overload resolution, cases for which cv1 is greater 4129 // cv-qualification than cv2 are identified as 4130 // reference-compatible with added qualification (see 13.3.3.2). 4131 // 4132 // Note that we also require equivalence of Objective-C GC and address-space 4133 // qualifiers when performing these computations, so that e.g., an int in 4134 // address space 1 is not reference-compatible with an int in address 4135 // space 2. 4136 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4137 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4138 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4139 ObjCLifetimeConversion = true; 4140 4141 T1Quals.removeObjCLifetime(); 4142 T2Quals.removeObjCLifetime(); 4143 } 4144 4145 // MS compiler ignores __unaligned qualifier for references; do the same. 4146 T1Quals.removeUnaligned(); 4147 T2Quals.removeUnaligned(); 4148 4149 if (T1Quals == T2Quals) 4150 return Ref_Compatible; 4151 else if (T1Quals.compatiblyIncludes(T2Quals)) 4152 return Ref_Compatible_With_Added_Qualification; 4153 else 4154 return Ref_Related; 4155 } 4156 4157 /// \brief Look for a user-defined conversion to an value reference-compatible 4158 /// with DeclType. Return true if something definite is found. 4159 static bool 4160 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4161 QualType DeclType, SourceLocation DeclLoc, 4162 Expr *Init, QualType T2, bool AllowRvalues, 4163 bool AllowExplicit) { 4164 assert(T2->isRecordType() && "Can only find conversions of record types."); 4165 CXXRecordDecl *T2RecordDecl 4166 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4167 4168 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4169 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4170 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4171 NamedDecl *D = *I; 4172 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4173 if (isa<UsingShadowDecl>(D)) 4174 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4175 4176 FunctionTemplateDecl *ConvTemplate 4177 = dyn_cast<FunctionTemplateDecl>(D); 4178 CXXConversionDecl *Conv; 4179 if (ConvTemplate) 4180 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4181 else 4182 Conv = cast<CXXConversionDecl>(D); 4183 4184 // If this is an explicit conversion, and we're not allowed to consider 4185 // explicit conversions, skip it. 4186 if (!AllowExplicit && Conv->isExplicit()) 4187 continue; 4188 4189 if (AllowRvalues) { 4190 bool DerivedToBase = false; 4191 bool ObjCConversion = false; 4192 bool ObjCLifetimeConversion = false; 4193 4194 // If we are initializing an rvalue reference, don't permit conversion 4195 // functions that return lvalues. 4196 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4197 const ReferenceType *RefType 4198 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4199 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4200 continue; 4201 } 4202 4203 if (!ConvTemplate && 4204 S.CompareReferenceRelationship( 4205 DeclLoc, 4206 Conv->getConversionType().getNonReferenceType() 4207 .getUnqualifiedType(), 4208 DeclType.getNonReferenceType().getUnqualifiedType(), 4209 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4210 Sema::Ref_Incompatible) 4211 continue; 4212 } else { 4213 // If the conversion function doesn't return a reference type, 4214 // it can't be considered for this conversion. An rvalue reference 4215 // is only acceptable if its referencee is a function type. 4216 4217 const ReferenceType *RefType = 4218 Conv->getConversionType()->getAs<ReferenceType>(); 4219 if (!RefType || 4220 (!RefType->isLValueReferenceType() && 4221 !RefType->getPointeeType()->isFunctionType())) 4222 continue; 4223 } 4224 4225 if (ConvTemplate) 4226 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4227 Init, DeclType, CandidateSet, 4228 /*AllowObjCConversionOnExplicit=*/false); 4229 else 4230 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4231 DeclType, CandidateSet, 4232 /*AllowObjCConversionOnExplicit=*/false); 4233 } 4234 4235 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4236 4237 OverloadCandidateSet::iterator Best; 4238 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4239 case OR_Success: 4240 // C++ [over.ics.ref]p1: 4241 // 4242 // [...] If the parameter binds directly to the result of 4243 // applying a conversion function to the argument 4244 // expression, the implicit conversion sequence is a 4245 // user-defined conversion sequence (13.3.3.1.2), with the 4246 // second standard conversion sequence either an identity 4247 // conversion or, if the conversion function returns an 4248 // entity of a type that is a derived class of the parameter 4249 // type, a derived-to-base Conversion. 4250 if (!Best->FinalConversion.DirectBinding) 4251 return false; 4252 4253 ICS.setUserDefined(); 4254 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4255 ICS.UserDefined.After = Best->FinalConversion; 4256 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4257 ICS.UserDefined.ConversionFunction = Best->Function; 4258 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4259 ICS.UserDefined.EllipsisConversion = false; 4260 assert(ICS.UserDefined.After.ReferenceBinding && 4261 ICS.UserDefined.After.DirectBinding && 4262 "Expected a direct reference binding!"); 4263 return true; 4264 4265 case OR_Ambiguous: 4266 ICS.setAmbiguous(); 4267 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4268 Cand != CandidateSet.end(); ++Cand) 4269 if (Cand->Viable) 4270 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4271 return true; 4272 4273 case OR_No_Viable_Function: 4274 case OR_Deleted: 4275 // There was no suitable conversion, or we found a deleted 4276 // conversion; continue with other checks. 4277 return false; 4278 } 4279 4280 llvm_unreachable("Invalid OverloadResult!"); 4281 } 4282 4283 /// \brief Compute an implicit conversion sequence for reference 4284 /// initialization. 4285 static ImplicitConversionSequence 4286 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4287 SourceLocation DeclLoc, 4288 bool SuppressUserConversions, 4289 bool AllowExplicit) { 4290 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4291 4292 // Most paths end in a failed conversion. 4293 ImplicitConversionSequence ICS; 4294 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4295 4296 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4297 QualType T2 = Init->getType(); 4298 4299 // If the initializer is the address of an overloaded function, try 4300 // to resolve the overloaded function. If all goes well, T2 is the 4301 // type of the resulting function. 4302 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4303 DeclAccessPair Found; 4304 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4305 false, Found)) 4306 T2 = Fn->getType(); 4307 } 4308 4309 // Compute some basic properties of the types and the initializer. 4310 bool isRValRef = DeclType->isRValueReferenceType(); 4311 bool DerivedToBase = false; 4312 bool ObjCConversion = false; 4313 bool ObjCLifetimeConversion = false; 4314 Expr::Classification InitCategory = Init->Classify(S.Context); 4315 Sema::ReferenceCompareResult RefRelationship 4316 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4317 ObjCConversion, ObjCLifetimeConversion); 4318 4319 4320 // C++0x [dcl.init.ref]p5: 4321 // A reference to type "cv1 T1" is initialized by an expression 4322 // of type "cv2 T2" as follows: 4323 4324 // -- If reference is an lvalue reference and the initializer expression 4325 if (!isRValRef) { 4326 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4327 // reference-compatible with "cv2 T2," or 4328 // 4329 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4330 if (InitCategory.isLValue() && 4331 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4332 // C++ [over.ics.ref]p1: 4333 // When a parameter of reference type binds directly (8.5.3) 4334 // to an argument expression, the implicit conversion sequence 4335 // is the identity conversion, unless the argument expression 4336 // has a type that is a derived class of the parameter type, 4337 // in which case the implicit conversion sequence is a 4338 // derived-to-base Conversion (13.3.3.1). 4339 ICS.setStandard(); 4340 ICS.Standard.First = ICK_Identity; 4341 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4342 : ObjCConversion? ICK_Compatible_Conversion 4343 : ICK_Identity; 4344 ICS.Standard.Third = ICK_Identity; 4345 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4346 ICS.Standard.setToType(0, T2); 4347 ICS.Standard.setToType(1, T1); 4348 ICS.Standard.setToType(2, T1); 4349 ICS.Standard.ReferenceBinding = true; 4350 ICS.Standard.DirectBinding = true; 4351 ICS.Standard.IsLvalueReference = !isRValRef; 4352 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4353 ICS.Standard.BindsToRvalue = false; 4354 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4355 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4356 ICS.Standard.CopyConstructor = nullptr; 4357 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4358 4359 // Nothing more to do: the inaccessibility/ambiguity check for 4360 // derived-to-base conversions is suppressed when we're 4361 // computing the implicit conversion sequence (C++ 4362 // [over.best.ics]p2). 4363 return ICS; 4364 } 4365 4366 // -- has a class type (i.e., T2 is a class type), where T1 is 4367 // not reference-related to T2, and can be implicitly 4368 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4369 // is reference-compatible with "cv3 T3" 92) (this 4370 // conversion is selected by enumerating the applicable 4371 // conversion functions (13.3.1.6) and choosing the best 4372 // one through overload resolution (13.3)), 4373 if (!SuppressUserConversions && T2->isRecordType() && 4374 S.isCompleteType(DeclLoc, T2) && 4375 RefRelationship == Sema::Ref_Incompatible) { 4376 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4377 Init, T2, /*AllowRvalues=*/false, 4378 AllowExplicit)) 4379 return ICS; 4380 } 4381 } 4382 4383 // -- Otherwise, the reference shall be an lvalue reference to a 4384 // non-volatile const type (i.e., cv1 shall be const), or the reference 4385 // shall be an rvalue reference. 4386 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4387 return ICS; 4388 4389 // -- If the initializer expression 4390 // 4391 // -- is an xvalue, class prvalue, array prvalue or function 4392 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4393 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4394 (InitCategory.isXValue() || 4395 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4396 (InitCategory.isLValue() && T2->isFunctionType()))) { 4397 ICS.setStandard(); 4398 ICS.Standard.First = ICK_Identity; 4399 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4400 : ObjCConversion? ICK_Compatible_Conversion 4401 : ICK_Identity; 4402 ICS.Standard.Third = ICK_Identity; 4403 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4404 ICS.Standard.setToType(0, T2); 4405 ICS.Standard.setToType(1, T1); 4406 ICS.Standard.setToType(2, T1); 4407 ICS.Standard.ReferenceBinding = true; 4408 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4409 // binding unless we're binding to a class prvalue. 4410 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4411 // allow the use of rvalue references in C++98/03 for the benefit of 4412 // standard library implementors; therefore, we need the xvalue check here. 4413 ICS.Standard.DirectBinding = 4414 S.getLangOpts().CPlusPlus11 || 4415 !(InitCategory.isPRValue() || T2->isRecordType()); 4416 ICS.Standard.IsLvalueReference = !isRValRef; 4417 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4418 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4419 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4420 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4421 ICS.Standard.CopyConstructor = nullptr; 4422 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4423 return ICS; 4424 } 4425 4426 // -- has a class type (i.e., T2 is a class type), where T1 is not 4427 // reference-related to T2, and can be implicitly converted to 4428 // an xvalue, class prvalue, or function lvalue of type 4429 // "cv3 T3", where "cv1 T1" is reference-compatible with 4430 // "cv3 T3", 4431 // 4432 // then the reference is bound to the value of the initializer 4433 // expression in the first case and to the result of the conversion 4434 // in the second case (or, in either case, to an appropriate base 4435 // class subobject). 4436 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4437 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4438 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4439 Init, T2, /*AllowRvalues=*/true, 4440 AllowExplicit)) { 4441 // In the second case, if the reference is an rvalue reference 4442 // and the second standard conversion sequence of the 4443 // user-defined conversion sequence includes an lvalue-to-rvalue 4444 // conversion, the program is ill-formed. 4445 if (ICS.isUserDefined() && isRValRef && 4446 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4447 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4448 4449 return ICS; 4450 } 4451 4452 // A temporary of function type cannot be created; don't even try. 4453 if (T1->isFunctionType()) 4454 return ICS; 4455 4456 // -- Otherwise, a temporary of type "cv1 T1" is created and 4457 // initialized from the initializer expression using the 4458 // rules for a non-reference copy initialization (8.5). The 4459 // reference is then bound to the temporary. If T1 is 4460 // reference-related to T2, cv1 must be the same 4461 // cv-qualification as, or greater cv-qualification than, 4462 // cv2; otherwise, the program is ill-formed. 4463 if (RefRelationship == Sema::Ref_Related) { 4464 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4465 // we would be reference-compatible or reference-compatible with 4466 // added qualification. But that wasn't the case, so the reference 4467 // initialization fails. 4468 // 4469 // Note that we only want to check address spaces and cvr-qualifiers here. 4470 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4471 Qualifiers T1Quals = T1.getQualifiers(); 4472 Qualifiers T2Quals = T2.getQualifiers(); 4473 T1Quals.removeObjCGCAttr(); 4474 T1Quals.removeObjCLifetime(); 4475 T2Quals.removeObjCGCAttr(); 4476 T2Quals.removeObjCLifetime(); 4477 // MS compiler ignores __unaligned qualifier for references; do the same. 4478 T1Quals.removeUnaligned(); 4479 T2Quals.removeUnaligned(); 4480 if (!T1Quals.compatiblyIncludes(T2Quals)) 4481 return ICS; 4482 } 4483 4484 // If at least one of the types is a class type, the types are not 4485 // related, and we aren't allowed any user conversions, the 4486 // reference binding fails. This case is important for breaking 4487 // recursion, since TryImplicitConversion below will attempt to 4488 // create a temporary through the use of a copy constructor. 4489 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4490 (T1->isRecordType() || T2->isRecordType())) 4491 return ICS; 4492 4493 // If T1 is reference-related to T2 and the reference is an rvalue 4494 // reference, the initializer expression shall not be an lvalue. 4495 if (RefRelationship >= Sema::Ref_Related && 4496 isRValRef && Init->Classify(S.Context).isLValue()) 4497 return ICS; 4498 4499 // C++ [over.ics.ref]p2: 4500 // When a parameter of reference type is not bound directly to 4501 // an argument expression, the conversion sequence is the one 4502 // required to convert the argument expression to the 4503 // underlying type of the reference according to 4504 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4505 // to copy-initializing a temporary of the underlying type with 4506 // the argument expression. Any difference in top-level 4507 // cv-qualification is subsumed by the initialization itself 4508 // and does not constitute a conversion. 4509 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4510 /*AllowExplicit=*/false, 4511 /*InOverloadResolution=*/false, 4512 /*CStyle=*/false, 4513 /*AllowObjCWritebackConversion=*/false, 4514 /*AllowObjCConversionOnExplicit=*/false); 4515 4516 // Of course, that's still a reference binding. 4517 if (ICS.isStandard()) { 4518 ICS.Standard.ReferenceBinding = true; 4519 ICS.Standard.IsLvalueReference = !isRValRef; 4520 ICS.Standard.BindsToFunctionLvalue = false; 4521 ICS.Standard.BindsToRvalue = true; 4522 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4523 ICS.Standard.ObjCLifetimeConversionBinding = false; 4524 } else if (ICS.isUserDefined()) { 4525 const ReferenceType *LValRefType = 4526 ICS.UserDefined.ConversionFunction->getReturnType() 4527 ->getAs<LValueReferenceType>(); 4528 4529 // C++ [over.ics.ref]p3: 4530 // Except for an implicit object parameter, for which see 13.3.1, a 4531 // standard conversion sequence cannot be formed if it requires [...] 4532 // binding an rvalue reference to an lvalue other than a function 4533 // lvalue. 4534 // Note that the function case is not possible here. 4535 if (DeclType->isRValueReferenceType() && LValRefType) { 4536 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4537 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4538 // reference to an rvalue! 4539 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4540 return ICS; 4541 } 4542 4543 ICS.UserDefined.Before.setAsIdentityConversion(); 4544 ICS.UserDefined.After.ReferenceBinding = true; 4545 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4546 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4547 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4548 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4549 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4550 } 4551 4552 return ICS; 4553 } 4554 4555 static ImplicitConversionSequence 4556 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4557 bool SuppressUserConversions, 4558 bool InOverloadResolution, 4559 bool AllowObjCWritebackConversion, 4560 bool AllowExplicit = false); 4561 4562 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4563 /// initializer list From. 4564 static ImplicitConversionSequence 4565 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4566 bool SuppressUserConversions, 4567 bool InOverloadResolution, 4568 bool AllowObjCWritebackConversion) { 4569 // C++11 [over.ics.list]p1: 4570 // When an argument is an initializer list, it is not an expression and 4571 // special rules apply for converting it to a parameter type. 4572 4573 ImplicitConversionSequence Result; 4574 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4575 4576 // We need a complete type for what follows. Incomplete types can never be 4577 // initialized from init lists. 4578 if (!S.isCompleteType(From->getLocStart(), ToType)) 4579 return Result; 4580 4581 // Per DR1467: 4582 // If the parameter type is a class X and the initializer list has a single 4583 // element of type cv U, where U is X or a class derived from X, the 4584 // implicit conversion sequence is the one required to convert the element 4585 // to the parameter type. 4586 // 4587 // Otherwise, if the parameter type is a character array [... ] 4588 // and the initializer list has a single element that is an 4589 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4590 // implicit conversion sequence is the identity conversion. 4591 if (From->getNumInits() == 1) { 4592 if (ToType->isRecordType()) { 4593 QualType InitType = From->getInit(0)->getType(); 4594 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4595 S.IsDerivedFrom(From->getLocStart(), InitType, ToType)) 4596 return TryCopyInitialization(S, From->getInit(0), ToType, 4597 SuppressUserConversions, 4598 InOverloadResolution, 4599 AllowObjCWritebackConversion); 4600 } 4601 // FIXME: Check the other conditions here: array of character type, 4602 // initializer is a string literal. 4603 if (ToType->isArrayType()) { 4604 InitializedEntity Entity = 4605 InitializedEntity::InitializeParameter(S.Context, ToType, 4606 /*Consumed=*/false); 4607 if (S.CanPerformCopyInitialization(Entity, From)) { 4608 Result.setStandard(); 4609 Result.Standard.setAsIdentityConversion(); 4610 Result.Standard.setFromType(ToType); 4611 Result.Standard.setAllToTypes(ToType); 4612 return Result; 4613 } 4614 } 4615 } 4616 4617 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4618 // C++11 [over.ics.list]p2: 4619 // If the parameter type is std::initializer_list<X> or "array of X" and 4620 // all the elements can be implicitly converted to X, the implicit 4621 // conversion sequence is the worst conversion necessary to convert an 4622 // element of the list to X. 4623 // 4624 // C++14 [over.ics.list]p3: 4625 // Otherwise, if the parameter type is "array of N X", if the initializer 4626 // list has exactly N elements or if it has fewer than N elements and X is 4627 // default-constructible, and if all the elements of the initializer list 4628 // can be implicitly converted to X, the implicit conversion sequence is 4629 // the worst conversion necessary to convert an element of the list to X. 4630 // 4631 // FIXME: We're missing a lot of these checks. 4632 bool toStdInitializerList = false; 4633 QualType X; 4634 if (ToType->isArrayType()) 4635 X = S.Context.getAsArrayType(ToType)->getElementType(); 4636 else 4637 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4638 if (!X.isNull()) { 4639 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4640 Expr *Init = From->getInit(i); 4641 ImplicitConversionSequence ICS = 4642 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4643 InOverloadResolution, 4644 AllowObjCWritebackConversion); 4645 // If a single element isn't convertible, fail. 4646 if (ICS.isBad()) { 4647 Result = ICS; 4648 break; 4649 } 4650 // Otherwise, look for the worst conversion. 4651 if (Result.isBad() || 4652 CompareImplicitConversionSequences(S, From->getLocStart(), ICS, 4653 Result) == 4654 ImplicitConversionSequence::Worse) 4655 Result = ICS; 4656 } 4657 4658 // For an empty list, we won't have computed any conversion sequence. 4659 // Introduce the identity conversion sequence. 4660 if (From->getNumInits() == 0) { 4661 Result.setStandard(); 4662 Result.Standard.setAsIdentityConversion(); 4663 Result.Standard.setFromType(ToType); 4664 Result.Standard.setAllToTypes(ToType); 4665 } 4666 4667 Result.setStdInitializerListElement(toStdInitializerList); 4668 return Result; 4669 } 4670 4671 // C++14 [over.ics.list]p4: 4672 // C++11 [over.ics.list]p3: 4673 // Otherwise, if the parameter is a non-aggregate class X and overload 4674 // resolution chooses a single best constructor [...] the implicit 4675 // conversion sequence is a user-defined conversion sequence. If multiple 4676 // constructors are viable but none is better than the others, the 4677 // implicit conversion sequence is a user-defined conversion sequence. 4678 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4679 // This function can deal with initializer lists. 4680 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4681 /*AllowExplicit=*/false, 4682 InOverloadResolution, /*CStyle=*/false, 4683 AllowObjCWritebackConversion, 4684 /*AllowObjCConversionOnExplicit=*/false); 4685 } 4686 4687 // C++14 [over.ics.list]p5: 4688 // C++11 [over.ics.list]p4: 4689 // Otherwise, if the parameter has an aggregate type which can be 4690 // initialized from the initializer list [...] the implicit conversion 4691 // sequence is a user-defined conversion sequence. 4692 if (ToType->isAggregateType()) { 4693 // Type is an aggregate, argument is an init list. At this point it comes 4694 // down to checking whether the initialization works. 4695 // FIXME: Find out whether this parameter is consumed or not. 4696 InitializedEntity Entity = 4697 InitializedEntity::InitializeParameter(S.Context, ToType, 4698 /*Consumed=*/false); 4699 if (S.CanPerformCopyInitialization(Entity, From)) { 4700 Result.setUserDefined(); 4701 Result.UserDefined.Before.setAsIdentityConversion(); 4702 // Initializer lists don't have a type. 4703 Result.UserDefined.Before.setFromType(QualType()); 4704 Result.UserDefined.Before.setAllToTypes(QualType()); 4705 4706 Result.UserDefined.After.setAsIdentityConversion(); 4707 Result.UserDefined.After.setFromType(ToType); 4708 Result.UserDefined.After.setAllToTypes(ToType); 4709 Result.UserDefined.ConversionFunction = nullptr; 4710 } 4711 return Result; 4712 } 4713 4714 // C++14 [over.ics.list]p6: 4715 // C++11 [over.ics.list]p5: 4716 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4717 if (ToType->isReferenceType()) { 4718 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4719 // mention initializer lists in any way. So we go by what list- 4720 // initialization would do and try to extrapolate from that. 4721 4722 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4723 4724 // If the initializer list has a single element that is reference-related 4725 // to the parameter type, we initialize the reference from that. 4726 if (From->getNumInits() == 1) { 4727 Expr *Init = From->getInit(0); 4728 4729 QualType T2 = Init->getType(); 4730 4731 // If the initializer is the address of an overloaded function, try 4732 // to resolve the overloaded function. If all goes well, T2 is the 4733 // type of the resulting function. 4734 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4735 DeclAccessPair Found; 4736 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4737 Init, ToType, false, Found)) 4738 T2 = Fn->getType(); 4739 } 4740 4741 // Compute some basic properties of the types and the initializer. 4742 bool dummy1 = false; 4743 bool dummy2 = false; 4744 bool dummy3 = false; 4745 Sema::ReferenceCompareResult RefRelationship 4746 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4747 dummy2, dummy3); 4748 4749 if (RefRelationship >= Sema::Ref_Related) { 4750 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4751 SuppressUserConversions, 4752 /*AllowExplicit=*/false); 4753 } 4754 } 4755 4756 // Otherwise, we bind the reference to a temporary created from the 4757 // initializer list. 4758 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4759 InOverloadResolution, 4760 AllowObjCWritebackConversion); 4761 if (Result.isFailure()) 4762 return Result; 4763 assert(!Result.isEllipsis() && 4764 "Sub-initialization cannot result in ellipsis conversion."); 4765 4766 // Can we even bind to a temporary? 4767 if (ToType->isRValueReferenceType() || 4768 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4769 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4770 Result.UserDefined.After; 4771 SCS.ReferenceBinding = true; 4772 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4773 SCS.BindsToRvalue = true; 4774 SCS.BindsToFunctionLvalue = false; 4775 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4776 SCS.ObjCLifetimeConversionBinding = false; 4777 } else 4778 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4779 From, ToType); 4780 return Result; 4781 } 4782 4783 // C++14 [over.ics.list]p7: 4784 // C++11 [over.ics.list]p6: 4785 // Otherwise, if the parameter type is not a class: 4786 if (!ToType->isRecordType()) { 4787 // - if the initializer list has one element that is not itself an 4788 // initializer list, the implicit conversion sequence is the one 4789 // required to convert the element to the parameter type. 4790 unsigned NumInits = From->getNumInits(); 4791 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4792 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4793 SuppressUserConversions, 4794 InOverloadResolution, 4795 AllowObjCWritebackConversion); 4796 // - if the initializer list has no elements, the implicit conversion 4797 // sequence is the identity conversion. 4798 else if (NumInits == 0) { 4799 Result.setStandard(); 4800 Result.Standard.setAsIdentityConversion(); 4801 Result.Standard.setFromType(ToType); 4802 Result.Standard.setAllToTypes(ToType); 4803 } 4804 return Result; 4805 } 4806 4807 // C++14 [over.ics.list]p8: 4808 // C++11 [over.ics.list]p7: 4809 // In all cases other than those enumerated above, no conversion is possible 4810 return Result; 4811 } 4812 4813 /// TryCopyInitialization - Try to copy-initialize a value of type 4814 /// ToType from the expression From. Return the implicit conversion 4815 /// sequence required to pass this argument, which may be a bad 4816 /// conversion sequence (meaning that the argument cannot be passed to 4817 /// a parameter of this type). If @p SuppressUserConversions, then we 4818 /// do not permit any user-defined conversion sequences. 4819 static ImplicitConversionSequence 4820 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4821 bool SuppressUserConversions, 4822 bool InOverloadResolution, 4823 bool AllowObjCWritebackConversion, 4824 bool AllowExplicit) { 4825 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4826 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4827 InOverloadResolution,AllowObjCWritebackConversion); 4828 4829 if (ToType->isReferenceType()) 4830 return TryReferenceInit(S, From, ToType, 4831 /*FIXME:*/From->getLocStart(), 4832 SuppressUserConversions, 4833 AllowExplicit); 4834 4835 return TryImplicitConversion(S, From, ToType, 4836 SuppressUserConversions, 4837 /*AllowExplicit=*/false, 4838 InOverloadResolution, 4839 /*CStyle=*/false, 4840 AllowObjCWritebackConversion, 4841 /*AllowObjCConversionOnExplicit=*/false); 4842 } 4843 4844 static bool TryCopyInitialization(const CanQualType FromQTy, 4845 const CanQualType ToQTy, 4846 Sema &S, 4847 SourceLocation Loc, 4848 ExprValueKind FromVK) { 4849 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4850 ImplicitConversionSequence ICS = 4851 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4852 4853 return !ICS.isBad(); 4854 } 4855 4856 /// TryObjectArgumentInitialization - Try to initialize the object 4857 /// parameter of the given member function (@c Method) from the 4858 /// expression @p From. 4859 static ImplicitConversionSequence 4860 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 4861 Expr::Classification FromClassification, 4862 CXXMethodDecl *Method, 4863 CXXRecordDecl *ActingContext) { 4864 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4865 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4866 // const volatile object. 4867 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4868 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4869 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4870 4871 // Set up the conversion sequence as a "bad" conversion, to allow us 4872 // to exit early. 4873 ImplicitConversionSequence ICS; 4874 4875 // We need to have an object of class type. 4876 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4877 FromType = PT->getPointeeType(); 4878 4879 // When we had a pointer, it's implicitly dereferenced, so we 4880 // better have an lvalue. 4881 assert(FromClassification.isLValue()); 4882 } 4883 4884 assert(FromType->isRecordType()); 4885 4886 // C++0x [over.match.funcs]p4: 4887 // For non-static member functions, the type of the implicit object 4888 // parameter is 4889 // 4890 // - "lvalue reference to cv X" for functions declared without a 4891 // ref-qualifier or with the & ref-qualifier 4892 // - "rvalue reference to cv X" for functions declared with the && 4893 // ref-qualifier 4894 // 4895 // where X is the class of which the function is a member and cv is the 4896 // cv-qualification on the member function declaration. 4897 // 4898 // However, when finding an implicit conversion sequence for the argument, we 4899 // are not allowed to create temporaries or perform user-defined conversions 4900 // (C++ [over.match.funcs]p5). We perform a simplified version of 4901 // reference binding here, that allows class rvalues to bind to 4902 // non-constant references. 4903 4904 // First check the qualifiers. 4905 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4906 if (ImplicitParamType.getCVRQualifiers() 4907 != FromTypeCanon.getLocalCVRQualifiers() && 4908 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4909 ICS.setBad(BadConversionSequence::bad_qualifiers, 4910 FromType, ImplicitParamType); 4911 return ICS; 4912 } 4913 4914 // Check that we have either the same type or a derived type. It 4915 // affects the conversion rank. 4916 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4917 ImplicitConversionKind SecondKind; 4918 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4919 SecondKind = ICK_Identity; 4920 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 4921 SecondKind = ICK_Derived_To_Base; 4922 else { 4923 ICS.setBad(BadConversionSequence::unrelated_class, 4924 FromType, ImplicitParamType); 4925 return ICS; 4926 } 4927 4928 // Check the ref-qualifier. 4929 switch (Method->getRefQualifier()) { 4930 case RQ_None: 4931 // Do nothing; we don't care about lvalueness or rvalueness. 4932 break; 4933 4934 case RQ_LValue: 4935 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4936 // non-const lvalue reference cannot bind to an rvalue 4937 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4938 ImplicitParamType); 4939 return ICS; 4940 } 4941 break; 4942 4943 case RQ_RValue: 4944 if (!FromClassification.isRValue()) { 4945 // rvalue reference cannot bind to an lvalue 4946 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4947 ImplicitParamType); 4948 return ICS; 4949 } 4950 break; 4951 } 4952 4953 // Success. Mark this as a reference binding. 4954 ICS.setStandard(); 4955 ICS.Standard.setAsIdentityConversion(); 4956 ICS.Standard.Second = SecondKind; 4957 ICS.Standard.setFromType(FromType); 4958 ICS.Standard.setAllToTypes(ImplicitParamType); 4959 ICS.Standard.ReferenceBinding = true; 4960 ICS.Standard.DirectBinding = true; 4961 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4962 ICS.Standard.BindsToFunctionLvalue = false; 4963 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4964 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4965 = (Method->getRefQualifier() == RQ_None); 4966 return ICS; 4967 } 4968 4969 /// PerformObjectArgumentInitialization - Perform initialization of 4970 /// the implicit object parameter for the given Method with the given 4971 /// expression. 4972 ExprResult 4973 Sema::PerformObjectArgumentInitialization(Expr *From, 4974 NestedNameSpecifier *Qualifier, 4975 NamedDecl *FoundDecl, 4976 CXXMethodDecl *Method) { 4977 QualType FromRecordType, DestType; 4978 QualType ImplicitParamRecordType = 4979 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4980 4981 Expr::Classification FromClassification; 4982 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4983 FromRecordType = PT->getPointeeType(); 4984 DestType = Method->getThisType(Context); 4985 FromClassification = Expr::Classification::makeSimpleLValue(); 4986 } else { 4987 FromRecordType = From->getType(); 4988 DestType = ImplicitParamRecordType; 4989 FromClassification = From->Classify(Context); 4990 } 4991 4992 // Note that we always use the true parent context when performing 4993 // the actual argument initialization. 4994 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 4995 *this, From->getLocStart(), From->getType(), FromClassification, Method, 4996 Method->getParent()); 4997 if (ICS.isBad()) { 4998 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4999 Qualifiers FromQs = FromRecordType.getQualifiers(); 5000 Qualifiers ToQs = DestType.getQualifiers(); 5001 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5002 if (CVR) { 5003 Diag(From->getLocStart(), 5004 diag::err_member_function_call_bad_cvr) 5005 << Method->getDeclName() << FromRecordType << (CVR - 1) 5006 << From->getSourceRange(); 5007 Diag(Method->getLocation(), diag::note_previous_decl) 5008 << Method->getDeclName(); 5009 return ExprError(); 5010 } 5011 } 5012 5013 return Diag(From->getLocStart(), 5014 diag::err_implicit_object_parameter_init) 5015 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 5016 } 5017 5018 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5019 ExprResult FromRes = 5020 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5021 if (FromRes.isInvalid()) 5022 return ExprError(); 5023 From = FromRes.get(); 5024 } 5025 5026 if (!Context.hasSameType(From->getType(), DestType)) 5027 From = ImpCastExprToType(From, DestType, CK_NoOp, 5028 From->getValueKind()).get(); 5029 return From; 5030 } 5031 5032 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5033 /// expression From to bool (C++0x [conv]p3). 5034 static ImplicitConversionSequence 5035 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5036 return TryImplicitConversion(S, From, S.Context.BoolTy, 5037 /*SuppressUserConversions=*/false, 5038 /*AllowExplicit=*/true, 5039 /*InOverloadResolution=*/false, 5040 /*CStyle=*/false, 5041 /*AllowObjCWritebackConversion=*/false, 5042 /*AllowObjCConversionOnExplicit=*/false); 5043 } 5044 5045 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5046 /// of the expression From to bool (C++0x [conv]p3). 5047 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5048 if (checkPlaceholderForOverload(*this, From)) 5049 return ExprError(); 5050 5051 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5052 if (!ICS.isBad()) 5053 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5054 5055 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5056 return Diag(From->getLocStart(), 5057 diag::err_typecheck_bool_condition) 5058 << From->getType() << From->getSourceRange(); 5059 return ExprError(); 5060 } 5061 5062 /// Check that the specified conversion is permitted in a converted constant 5063 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5064 /// is acceptable. 5065 static bool CheckConvertedConstantConversions(Sema &S, 5066 StandardConversionSequence &SCS) { 5067 // Since we know that the target type is an integral or unscoped enumeration 5068 // type, most conversion kinds are impossible. All possible First and Third 5069 // conversions are fine. 5070 switch (SCS.Second) { 5071 case ICK_Identity: 5072 case ICK_NoReturn_Adjustment: 5073 case ICK_Integral_Promotion: 5074 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5075 return true; 5076 5077 case ICK_Boolean_Conversion: 5078 // Conversion from an integral or unscoped enumeration type to bool is 5079 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5080 // conversion, so we allow it in a converted constant expression. 5081 // 5082 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5083 // a lot of popular code. We should at least add a warning for this 5084 // (non-conforming) extension. 5085 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5086 SCS.getToType(2)->isBooleanType(); 5087 5088 case ICK_Pointer_Conversion: 5089 case ICK_Pointer_Member: 5090 // C++1z: null pointer conversions and null member pointer conversions are 5091 // only permitted if the source type is std::nullptr_t. 5092 return SCS.getFromType()->isNullPtrType(); 5093 5094 case ICK_Floating_Promotion: 5095 case ICK_Complex_Promotion: 5096 case ICK_Floating_Conversion: 5097 case ICK_Complex_Conversion: 5098 case ICK_Floating_Integral: 5099 case ICK_Compatible_Conversion: 5100 case ICK_Derived_To_Base: 5101 case ICK_Vector_Conversion: 5102 case ICK_Vector_Splat: 5103 case ICK_Complex_Real: 5104 case ICK_Block_Pointer_Conversion: 5105 case ICK_TransparentUnionConversion: 5106 case ICK_Writeback_Conversion: 5107 case ICK_Zero_Event_Conversion: 5108 case ICK_C_Only_Conversion: 5109 return false; 5110 5111 case ICK_Lvalue_To_Rvalue: 5112 case ICK_Array_To_Pointer: 5113 case ICK_Function_To_Pointer: 5114 llvm_unreachable("found a first conversion kind in Second"); 5115 5116 case ICK_Qualification: 5117 llvm_unreachable("found a third conversion kind in Second"); 5118 5119 case ICK_Num_Conversion_Kinds: 5120 break; 5121 } 5122 5123 llvm_unreachable("unknown conversion kind"); 5124 } 5125 5126 /// CheckConvertedConstantExpression - Check that the expression From is a 5127 /// converted constant expression of type T, perform the conversion and produce 5128 /// the converted expression, per C++11 [expr.const]p3. 5129 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5130 QualType T, APValue &Value, 5131 Sema::CCEKind CCE, 5132 bool RequireInt) { 5133 assert(S.getLangOpts().CPlusPlus11 && 5134 "converted constant expression outside C++11"); 5135 5136 if (checkPlaceholderForOverload(S, From)) 5137 return ExprError(); 5138 5139 // C++1z [expr.const]p3: 5140 // A converted constant expression of type T is an expression, 5141 // implicitly converted to type T, where the converted 5142 // expression is a constant expression and the implicit conversion 5143 // sequence contains only [... list of conversions ...]. 5144 ImplicitConversionSequence ICS = 5145 TryCopyInitialization(S, From, T, 5146 /*SuppressUserConversions=*/false, 5147 /*InOverloadResolution=*/false, 5148 /*AllowObjcWritebackConversion=*/false, 5149 /*AllowExplicit=*/false); 5150 StandardConversionSequence *SCS = nullptr; 5151 switch (ICS.getKind()) { 5152 case ImplicitConversionSequence::StandardConversion: 5153 SCS = &ICS.Standard; 5154 break; 5155 case ImplicitConversionSequence::UserDefinedConversion: 5156 // We are converting to a non-class type, so the Before sequence 5157 // must be trivial. 5158 SCS = &ICS.UserDefined.After; 5159 break; 5160 case ImplicitConversionSequence::AmbiguousConversion: 5161 case ImplicitConversionSequence::BadConversion: 5162 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5163 return S.Diag(From->getLocStart(), 5164 diag::err_typecheck_converted_constant_expression) 5165 << From->getType() << From->getSourceRange() << T; 5166 return ExprError(); 5167 5168 case ImplicitConversionSequence::EllipsisConversion: 5169 llvm_unreachable("ellipsis conversion in converted constant expression"); 5170 } 5171 5172 // Check that we would only use permitted conversions. 5173 if (!CheckConvertedConstantConversions(S, *SCS)) { 5174 return S.Diag(From->getLocStart(), 5175 diag::err_typecheck_converted_constant_expression_disallowed) 5176 << From->getType() << From->getSourceRange() << T; 5177 } 5178 // [...] and where the reference binding (if any) binds directly. 5179 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5180 return S.Diag(From->getLocStart(), 5181 diag::err_typecheck_converted_constant_expression_indirect) 5182 << From->getType() << From->getSourceRange() << T; 5183 } 5184 5185 ExprResult Result = 5186 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5187 if (Result.isInvalid()) 5188 return Result; 5189 5190 // Check for a narrowing implicit conversion. 5191 APValue PreNarrowingValue; 5192 QualType PreNarrowingType; 5193 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5194 PreNarrowingType)) { 5195 case NK_Variable_Narrowing: 5196 // Implicit conversion to a narrower type, and the value is not a constant 5197 // expression. We'll diagnose this in a moment. 5198 case NK_Not_Narrowing: 5199 break; 5200 5201 case NK_Constant_Narrowing: 5202 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5203 << CCE << /*Constant*/1 5204 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5205 break; 5206 5207 case NK_Type_Narrowing: 5208 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5209 << CCE << /*Constant*/0 << From->getType() << T; 5210 break; 5211 } 5212 5213 // Check the expression is a constant expression. 5214 SmallVector<PartialDiagnosticAt, 8> Notes; 5215 Expr::EvalResult Eval; 5216 Eval.Diag = &Notes; 5217 5218 if ((T->isReferenceType() 5219 ? !Result.get()->EvaluateAsLValue(Eval, S.Context) 5220 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) || 5221 (RequireInt && !Eval.Val.isInt())) { 5222 // The expression can't be folded, so we can't keep it at this position in 5223 // the AST. 5224 Result = ExprError(); 5225 } else { 5226 Value = Eval.Val; 5227 5228 if (Notes.empty()) { 5229 // It's a constant expression. 5230 return Result; 5231 } 5232 } 5233 5234 // It's not a constant expression. Produce an appropriate diagnostic. 5235 if (Notes.size() == 1 && 5236 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5237 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5238 else { 5239 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5240 << CCE << From->getSourceRange(); 5241 for (unsigned I = 0; I < Notes.size(); ++I) 5242 S.Diag(Notes[I].first, Notes[I].second); 5243 } 5244 return ExprError(); 5245 } 5246 5247 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5248 APValue &Value, CCEKind CCE) { 5249 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5250 } 5251 5252 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5253 llvm::APSInt &Value, 5254 CCEKind CCE) { 5255 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5256 5257 APValue V; 5258 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5259 if (!R.isInvalid()) 5260 Value = V.getInt(); 5261 return R; 5262 } 5263 5264 5265 /// dropPointerConversions - If the given standard conversion sequence 5266 /// involves any pointer conversions, remove them. This may change 5267 /// the result type of the conversion sequence. 5268 static void dropPointerConversion(StandardConversionSequence &SCS) { 5269 if (SCS.Second == ICK_Pointer_Conversion) { 5270 SCS.Second = ICK_Identity; 5271 SCS.Third = ICK_Identity; 5272 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5273 } 5274 } 5275 5276 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5277 /// convert the expression From to an Objective-C pointer type. 5278 static ImplicitConversionSequence 5279 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5280 // Do an implicit conversion to 'id'. 5281 QualType Ty = S.Context.getObjCIdType(); 5282 ImplicitConversionSequence ICS 5283 = TryImplicitConversion(S, From, Ty, 5284 // FIXME: Are these flags correct? 5285 /*SuppressUserConversions=*/false, 5286 /*AllowExplicit=*/true, 5287 /*InOverloadResolution=*/false, 5288 /*CStyle=*/false, 5289 /*AllowObjCWritebackConversion=*/false, 5290 /*AllowObjCConversionOnExplicit=*/true); 5291 5292 // Strip off any final conversions to 'id'. 5293 switch (ICS.getKind()) { 5294 case ImplicitConversionSequence::BadConversion: 5295 case ImplicitConversionSequence::AmbiguousConversion: 5296 case ImplicitConversionSequence::EllipsisConversion: 5297 break; 5298 5299 case ImplicitConversionSequence::UserDefinedConversion: 5300 dropPointerConversion(ICS.UserDefined.After); 5301 break; 5302 5303 case ImplicitConversionSequence::StandardConversion: 5304 dropPointerConversion(ICS.Standard); 5305 break; 5306 } 5307 5308 return ICS; 5309 } 5310 5311 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5312 /// conversion of the expression From to an Objective-C pointer type. 5313 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5314 if (checkPlaceholderForOverload(*this, From)) 5315 return ExprError(); 5316 5317 QualType Ty = Context.getObjCIdType(); 5318 ImplicitConversionSequence ICS = 5319 TryContextuallyConvertToObjCPointer(*this, From); 5320 if (!ICS.isBad()) 5321 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5322 return ExprError(); 5323 } 5324 5325 /// Determine whether the provided type is an integral type, or an enumeration 5326 /// type of a permitted flavor. 5327 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5328 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5329 : T->isIntegralOrUnscopedEnumerationType(); 5330 } 5331 5332 static ExprResult 5333 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5334 Sema::ContextualImplicitConverter &Converter, 5335 QualType T, UnresolvedSetImpl &ViableConversions) { 5336 5337 if (Converter.Suppress) 5338 return ExprError(); 5339 5340 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5341 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5342 CXXConversionDecl *Conv = 5343 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5344 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5345 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5346 } 5347 return From; 5348 } 5349 5350 static bool 5351 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5352 Sema::ContextualImplicitConverter &Converter, 5353 QualType T, bool HadMultipleCandidates, 5354 UnresolvedSetImpl &ExplicitConversions) { 5355 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5356 DeclAccessPair Found = ExplicitConversions[0]; 5357 CXXConversionDecl *Conversion = 5358 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5359 5360 // The user probably meant to invoke the given explicit 5361 // conversion; use it. 5362 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5363 std::string TypeStr; 5364 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5365 5366 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5367 << FixItHint::CreateInsertion(From->getLocStart(), 5368 "static_cast<" + TypeStr + ">(") 5369 << FixItHint::CreateInsertion( 5370 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5371 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5372 5373 // If we aren't in a SFINAE context, build a call to the 5374 // explicit conversion function. 5375 if (SemaRef.isSFINAEContext()) 5376 return true; 5377 5378 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5379 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5380 HadMultipleCandidates); 5381 if (Result.isInvalid()) 5382 return true; 5383 // Record usage of conversion in an implicit cast. 5384 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5385 CK_UserDefinedConversion, Result.get(), 5386 nullptr, Result.get()->getValueKind()); 5387 } 5388 return false; 5389 } 5390 5391 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5392 Sema::ContextualImplicitConverter &Converter, 5393 QualType T, bool HadMultipleCandidates, 5394 DeclAccessPair &Found) { 5395 CXXConversionDecl *Conversion = 5396 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5397 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5398 5399 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5400 if (!Converter.SuppressConversion) { 5401 if (SemaRef.isSFINAEContext()) 5402 return true; 5403 5404 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5405 << From->getSourceRange(); 5406 } 5407 5408 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5409 HadMultipleCandidates); 5410 if (Result.isInvalid()) 5411 return true; 5412 // Record usage of conversion in an implicit cast. 5413 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5414 CK_UserDefinedConversion, Result.get(), 5415 nullptr, Result.get()->getValueKind()); 5416 return false; 5417 } 5418 5419 static ExprResult finishContextualImplicitConversion( 5420 Sema &SemaRef, SourceLocation Loc, Expr *From, 5421 Sema::ContextualImplicitConverter &Converter) { 5422 if (!Converter.match(From->getType()) && !Converter.Suppress) 5423 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5424 << From->getSourceRange(); 5425 5426 return SemaRef.DefaultLvalueConversion(From); 5427 } 5428 5429 static void 5430 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5431 UnresolvedSetImpl &ViableConversions, 5432 OverloadCandidateSet &CandidateSet) { 5433 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5434 DeclAccessPair FoundDecl = ViableConversions[I]; 5435 NamedDecl *D = FoundDecl.getDecl(); 5436 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5437 if (isa<UsingShadowDecl>(D)) 5438 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5439 5440 CXXConversionDecl *Conv; 5441 FunctionTemplateDecl *ConvTemplate; 5442 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5443 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5444 else 5445 Conv = cast<CXXConversionDecl>(D); 5446 5447 if (ConvTemplate) 5448 SemaRef.AddTemplateConversionCandidate( 5449 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5450 /*AllowObjCConversionOnExplicit=*/false); 5451 else 5452 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5453 ToType, CandidateSet, 5454 /*AllowObjCConversionOnExplicit=*/false); 5455 } 5456 } 5457 5458 /// \brief Attempt to convert the given expression to a type which is accepted 5459 /// by the given converter. 5460 /// 5461 /// This routine will attempt to convert an expression of class type to a 5462 /// type accepted by the specified converter. In C++11 and before, the class 5463 /// must have a single non-explicit conversion function converting to a matching 5464 /// type. In C++1y, there can be multiple such conversion functions, but only 5465 /// one target type. 5466 /// 5467 /// \param Loc The source location of the construct that requires the 5468 /// conversion. 5469 /// 5470 /// \param From The expression we're converting from. 5471 /// 5472 /// \param Converter Used to control and diagnose the conversion process. 5473 /// 5474 /// \returns The expression, converted to an integral or enumeration type if 5475 /// successful. 5476 ExprResult Sema::PerformContextualImplicitConversion( 5477 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5478 // We can't perform any more checking for type-dependent expressions. 5479 if (From->isTypeDependent()) 5480 return From; 5481 5482 // Process placeholders immediately. 5483 if (From->hasPlaceholderType()) { 5484 ExprResult result = CheckPlaceholderExpr(From); 5485 if (result.isInvalid()) 5486 return result; 5487 From = result.get(); 5488 } 5489 5490 // If the expression already has a matching type, we're golden. 5491 QualType T = From->getType(); 5492 if (Converter.match(T)) 5493 return DefaultLvalueConversion(From); 5494 5495 // FIXME: Check for missing '()' if T is a function type? 5496 5497 // We can only perform contextual implicit conversions on objects of class 5498 // type. 5499 const RecordType *RecordTy = T->getAs<RecordType>(); 5500 if (!RecordTy || !getLangOpts().CPlusPlus) { 5501 if (!Converter.Suppress) 5502 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5503 return From; 5504 } 5505 5506 // We must have a complete class type. 5507 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5508 ContextualImplicitConverter &Converter; 5509 Expr *From; 5510 5511 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5512 : Converter(Converter), From(From) {} 5513 5514 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5515 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5516 } 5517 } IncompleteDiagnoser(Converter, From); 5518 5519 if (Converter.Suppress ? !isCompleteType(Loc, T) 5520 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5521 return From; 5522 5523 // Look for a conversion to an integral or enumeration type. 5524 UnresolvedSet<4> 5525 ViableConversions; // These are *potentially* viable in C++1y. 5526 UnresolvedSet<4> ExplicitConversions; 5527 const auto &Conversions = 5528 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5529 5530 bool HadMultipleCandidates = 5531 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5532 5533 // To check that there is only one target type, in C++1y: 5534 QualType ToType; 5535 bool HasUniqueTargetType = true; 5536 5537 // Collect explicit or viable (potentially in C++1y) conversions. 5538 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5539 NamedDecl *D = (*I)->getUnderlyingDecl(); 5540 CXXConversionDecl *Conversion; 5541 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5542 if (ConvTemplate) { 5543 if (getLangOpts().CPlusPlus14) 5544 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5545 else 5546 continue; // C++11 does not consider conversion operator templates(?). 5547 } else 5548 Conversion = cast<CXXConversionDecl>(D); 5549 5550 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5551 "Conversion operator templates are considered potentially " 5552 "viable in C++1y"); 5553 5554 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5555 if (Converter.match(CurToType) || ConvTemplate) { 5556 5557 if (Conversion->isExplicit()) { 5558 // FIXME: For C++1y, do we need this restriction? 5559 // cf. diagnoseNoViableConversion() 5560 if (!ConvTemplate) 5561 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5562 } else { 5563 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5564 if (ToType.isNull()) 5565 ToType = CurToType.getUnqualifiedType(); 5566 else if (HasUniqueTargetType && 5567 (CurToType.getUnqualifiedType() != ToType)) 5568 HasUniqueTargetType = false; 5569 } 5570 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5571 } 5572 } 5573 } 5574 5575 if (getLangOpts().CPlusPlus14) { 5576 // C++1y [conv]p6: 5577 // ... An expression e of class type E appearing in such a context 5578 // is said to be contextually implicitly converted to a specified 5579 // type T and is well-formed if and only if e can be implicitly 5580 // converted to a type T that is determined as follows: E is searched 5581 // for conversion functions whose return type is cv T or reference to 5582 // cv T such that T is allowed by the context. There shall be 5583 // exactly one such T. 5584 5585 // If no unique T is found: 5586 if (ToType.isNull()) { 5587 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5588 HadMultipleCandidates, 5589 ExplicitConversions)) 5590 return ExprError(); 5591 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5592 } 5593 5594 // If more than one unique Ts are found: 5595 if (!HasUniqueTargetType) 5596 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5597 ViableConversions); 5598 5599 // If one unique T is found: 5600 // First, build a candidate set from the previously recorded 5601 // potentially viable conversions. 5602 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5603 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5604 CandidateSet); 5605 5606 // Then, perform overload resolution over the candidate set. 5607 OverloadCandidateSet::iterator Best; 5608 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5609 case OR_Success: { 5610 // Apply this conversion. 5611 DeclAccessPair Found = 5612 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5613 if (recordConversion(*this, Loc, From, Converter, T, 5614 HadMultipleCandidates, Found)) 5615 return ExprError(); 5616 break; 5617 } 5618 case OR_Ambiguous: 5619 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5620 ViableConversions); 5621 case OR_No_Viable_Function: 5622 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5623 HadMultipleCandidates, 5624 ExplicitConversions)) 5625 return ExprError(); 5626 // fall through 'OR_Deleted' case. 5627 case OR_Deleted: 5628 // We'll complain below about a non-integral condition type. 5629 break; 5630 } 5631 } else { 5632 switch (ViableConversions.size()) { 5633 case 0: { 5634 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5635 HadMultipleCandidates, 5636 ExplicitConversions)) 5637 return ExprError(); 5638 5639 // We'll complain below about a non-integral condition type. 5640 break; 5641 } 5642 case 1: { 5643 // Apply this conversion. 5644 DeclAccessPair Found = ViableConversions[0]; 5645 if (recordConversion(*this, Loc, From, Converter, T, 5646 HadMultipleCandidates, Found)) 5647 return ExprError(); 5648 break; 5649 } 5650 default: 5651 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5652 ViableConversions); 5653 } 5654 } 5655 5656 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5657 } 5658 5659 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5660 /// an acceptable non-member overloaded operator for a call whose 5661 /// arguments have types T1 (and, if non-empty, T2). This routine 5662 /// implements the check in C++ [over.match.oper]p3b2 concerning 5663 /// enumeration types. 5664 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5665 FunctionDecl *Fn, 5666 ArrayRef<Expr *> Args) { 5667 QualType T1 = Args[0]->getType(); 5668 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5669 5670 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5671 return true; 5672 5673 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5674 return true; 5675 5676 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5677 if (Proto->getNumParams() < 1) 5678 return false; 5679 5680 if (T1->isEnumeralType()) { 5681 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5682 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5683 return true; 5684 } 5685 5686 if (Proto->getNumParams() < 2) 5687 return false; 5688 5689 if (!T2.isNull() && T2->isEnumeralType()) { 5690 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5691 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5692 return true; 5693 } 5694 5695 return false; 5696 } 5697 5698 /// AddOverloadCandidate - Adds the given function to the set of 5699 /// candidate functions, using the given function call arguments. If 5700 /// @p SuppressUserConversions, then don't allow user-defined 5701 /// conversions via constructors or conversion operators. 5702 /// 5703 /// \param PartialOverloading true if we are performing "partial" overloading 5704 /// based on an incomplete set of function arguments. This feature is used by 5705 /// code completion. 5706 void 5707 Sema::AddOverloadCandidate(FunctionDecl *Function, 5708 DeclAccessPair FoundDecl, 5709 ArrayRef<Expr *> Args, 5710 OverloadCandidateSet &CandidateSet, 5711 bool SuppressUserConversions, 5712 bool PartialOverloading, 5713 bool AllowExplicit) { 5714 const FunctionProtoType *Proto 5715 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5716 assert(Proto && "Functions without a prototype cannot be overloaded"); 5717 assert(!Function->getDescribedFunctionTemplate() && 5718 "Use AddTemplateOverloadCandidate for function templates"); 5719 5720 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5721 if (!isa<CXXConstructorDecl>(Method)) { 5722 // If we get here, it's because we're calling a member function 5723 // that is named without a member access expression (e.g., 5724 // "this->f") that was either written explicitly or created 5725 // implicitly. This can happen with a qualified call to a member 5726 // function, e.g., X::f(). We use an empty type for the implied 5727 // object argument (C++ [over.call.func]p3), and the acting context 5728 // is irrelevant. 5729 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5730 QualType(), Expr::Classification::makeSimpleLValue(), 5731 Args, CandidateSet, SuppressUserConversions, 5732 PartialOverloading); 5733 return; 5734 } 5735 // We treat a constructor like a non-member function, since its object 5736 // argument doesn't participate in overload resolution. 5737 } 5738 5739 if (!CandidateSet.isNewCandidate(Function)) 5740 return; 5741 5742 // C++ [over.match.oper]p3: 5743 // if no operand has a class type, only those non-member functions in the 5744 // lookup set that have a first parameter of type T1 or "reference to 5745 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5746 // is a right operand) a second parameter of type T2 or "reference to 5747 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5748 // candidate functions. 5749 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5750 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5751 return; 5752 5753 // C++11 [class.copy]p11: [DR1402] 5754 // A defaulted move constructor that is defined as deleted is ignored by 5755 // overload resolution. 5756 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5757 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5758 Constructor->isMoveConstructor()) 5759 return; 5760 5761 // Overload resolution is always an unevaluated context. 5762 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5763 5764 // Add this candidate 5765 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5766 Candidate.FoundDecl = FoundDecl; 5767 Candidate.Function = Function; 5768 Candidate.Viable = true; 5769 Candidate.IsSurrogate = false; 5770 Candidate.IgnoreObjectArgument = false; 5771 Candidate.ExplicitCallArguments = Args.size(); 5772 5773 if (Constructor) { 5774 // C++ [class.copy]p3: 5775 // A member function template is never instantiated to perform the copy 5776 // of a class object to an object of its class type. 5777 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5778 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 5779 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5780 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(), 5781 ClassType))) { 5782 Candidate.Viable = false; 5783 Candidate.FailureKind = ovl_fail_illegal_constructor; 5784 return; 5785 } 5786 } 5787 5788 unsigned NumParams = Proto->getNumParams(); 5789 5790 // (C++ 13.3.2p2): A candidate function having fewer than m 5791 // parameters is viable only if it has an ellipsis in its parameter 5792 // list (8.3.5). 5793 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 5794 !Proto->isVariadic()) { 5795 Candidate.Viable = false; 5796 Candidate.FailureKind = ovl_fail_too_many_arguments; 5797 return; 5798 } 5799 5800 // (C++ 13.3.2p2): A candidate function having more than m parameters 5801 // is viable only if the (m+1)st parameter has a default argument 5802 // (8.3.6). For the purposes of overload resolution, the 5803 // parameter list is truncated on the right, so that there are 5804 // exactly m parameters. 5805 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5806 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5807 // Not enough arguments. 5808 Candidate.Viable = false; 5809 Candidate.FailureKind = ovl_fail_too_few_arguments; 5810 return; 5811 } 5812 5813 // (CUDA B.1): Check for invalid calls between targets. 5814 if (getLangOpts().CUDA) 5815 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5816 // Skip the check for callers that are implicit members, because in this 5817 // case we may not yet know what the member's target is; the target is 5818 // inferred for the member automatically, based on the bases and fields of 5819 // the class. 5820 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) { 5821 Candidate.Viable = false; 5822 Candidate.FailureKind = ovl_fail_bad_target; 5823 return; 5824 } 5825 5826 // Determine the implicit conversion sequences for each of the 5827 // arguments. 5828 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5829 if (ArgIdx < NumParams) { 5830 // (C++ 13.3.2p3): for F to be a viable function, there shall 5831 // exist for each argument an implicit conversion sequence 5832 // (13.3.3.1) that converts that argument to the corresponding 5833 // parameter of F. 5834 QualType ParamType = Proto->getParamType(ArgIdx); 5835 Candidate.Conversions[ArgIdx] 5836 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5837 SuppressUserConversions, 5838 /*InOverloadResolution=*/true, 5839 /*AllowObjCWritebackConversion=*/ 5840 getLangOpts().ObjCAutoRefCount, 5841 AllowExplicit); 5842 if (Candidate.Conversions[ArgIdx].isBad()) { 5843 Candidate.Viable = false; 5844 Candidate.FailureKind = ovl_fail_bad_conversion; 5845 return; 5846 } 5847 } else { 5848 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5849 // argument for which there is no corresponding parameter is 5850 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5851 Candidate.Conversions[ArgIdx].setEllipsis(); 5852 } 5853 } 5854 5855 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5856 Candidate.Viable = false; 5857 Candidate.FailureKind = ovl_fail_enable_if; 5858 Candidate.DeductionFailure.Data = FailedAttr; 5859 return; 5860 } 5861 } 5862 5863 ObjCMethodDecl * 5864 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 5865 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 5866 if (Methods.size() <= 1) 5867 return nullptr; 5868 5869 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5870 bool Match = true; 5871 ObjCMethodDecl *Method = Methods[b]; 5872 unsigned NumNamedArgs = Sel.getNumArgs(); 5873 // Method might have more arguments than selector indicates. This is due 5874 // to addition of c-style arguments in method. 5875 if (Method->param_size() > NumNamedArgs) 5876 NumNamedArgs = Method->param_size(); 5877 if (Args.size() < NumNamedArgs) 5878 continue; 5879 5880 for (unsigned i = 0; i < NumNamedArgs; i++) { 5881 // We can't do any type-checking on a type-dependent argument. 5882 if (Args[i]->isTypeDependent()) { 5883 Match = false; 5884 break; 5885 } 5886 5887 ParmVarDecl *param = Method->parameters()[i]; 5888 Expr *argExpr = Args[i]; 5889 assert(argExpr && "SelectBestMethod(): missing expression"); 5890 5891 // Strip the unbridged-cast placeholder expression off unless it's 5892 // a consumed argument. 5893 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 5894 !param->hasAttr<CFConsumedAttr>()) 5895 argExpr = stripARCUnbridgedCast(argExpr); 5896 5897 // If the parameter is __unknown_anytype, move on to the next method. 5898 if (param->getType() == Context.UnknownAnyTy) { 5899 Match = false; 5900 break; 5901 } 5902 5903 ImplicitConversionSequence ConversionState 5904 = TryCopyInitialization(*this, argExpr, param->getType(), 5905 /*SuppressUserConversions*/false, 5906 /*InOverloadResolution=*/true, 5907 /*AllowObjCWritebackConversion=*/ 5908 getLangOpts().ObjCAutoRefCount, 5909 /*AllowExplicit*/false); 5910 if (ConversionState.isBad()) { 5911 Match = false; 5912 break; 5913 } 5914 } 5915 // Promote additional arguments to variadic methods. 5916 if (Match && Method->isVariadic()) { 5917 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 5918 if (Args[i]->isTypeDependent()) { 5919 Match = false; 5920 break; 5921 } 5922 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 5923 nullptr); 5924 if (Arg.isInvalid()) { 5925 Match = false; 5926 break; 5927 } 5928 } 5929 } else { 5930 // Check for extra arguments to non-variadic methods. 5931 if (Args.size() != NumNamedArgs) 5932 Match = false; 5933 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 5934 // Special case when selectors have no argument. In this case, select 5935 // one with the most general result type of 'id'. 5936 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5937 QualType ReturnT = Methods[b]->getReturnType(); 5938 if (ReturnT->isObjCIdType()) 5939 return Methods[b]; 5940 } 5941 } 5942 } 5943 5944 if (Match) 5945 return Method; 5946 } 5947 return nullptr; 5948 } 5949 5950 // specific_attr_iterator iterates over enable_if attributes in reverse, and 5951 // enable_if is order-sensitive. As a result, we need to reverse things 5952 // sometimes. Size of 4 elements is arbitrary. 5953 static SmallVector<EnableIfAttr *, 4> 5954 getOrderedEnableIfAttrs(const FunctionDecl *Function) { 5955 SmallVector<EnableIfAttr *, 4> Result; 5956 if (!Function->hasAttrs()) 5957 return Result; 5958 5959 const auto &FuncAttrs = Function->getAttrs(); 5960 for (Attr *Attr : FuncAttrs) 5961 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr)) 5962 Result.push_back(EnableIf); 5963 5964 std::reverse(Result.begin(), Result.end()); 5965 return Result; 5966 } 5967 5968 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 5969 bool MissingImplicitThis) { 5970 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function); 5971 if (EnableIfAttrs.empty()) 5972 return nullptr; 5973 5974 SFINAETrap Trap(*this); 5975 SmallVector<Expr *, 16> ConvertedArgs; 5976 bool InitializationFailed = false; 5977 5978 // Ignore any variadic parameters. Converting them is pointless, since the 5979 // user can't refer to them in the enable_if condition. 5980 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 5981 5982 // Convert the arguments. 5983 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 5984 ExprResult R; 5985 if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 5986 !cast<CXXMethodDecl>(Function)->isStatic() && 5987 !isa<CXXConstructorDecl>(Function)) { 5988 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 5989 R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 5990 Method, Method); 5991 } else { 5992 R = PerformCopyInitialization(InitializedEntity::InitializeParameter( 5993 Context, Function->getParamDecl(I)), 5994 SourceLocation(), Args[I]); 5995 } 5996 5997 if (R.isInvalid()) { 5998 InitializationFailed = true; 5999 break; 6000 } 6001 6002 ConvertedArgs.push_back(R.get()); 6003 } 6004 6005 if (InitializationFailed || Trap.hasErrorOccurred()) 6006 return EnableIfAttrs[0]; 6007 6008 // Push default arguments if needed. 6009 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6010 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6011 ParmVarDecl *P = Function->getParamDecl(i); 6012 ExprResult R = PerformCopyInitialization( 6013 InitializedEntity::InitializeParameter(Context, 6014 Function->getParamDecl(i)), 6015 SourceLocation(), 6016 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg() 6017 : P->getDefaultArg()); 6018 if (R.isInvalid()) { 6019 InitializationFailed = true; 6020 break; 6021 } 6022 ConvertedArgs.push_back(R.get()); 6023 } 6024 6025 if (InitializationFailed || Trap.hasErrorOccurred()) 6026 return EnableIfAttrs[0]; 6027 } 6028 6029 for (auto *EIA : EnableIfAttrs) { 6030 APValue Result; 6031 // FIXME: This doesn't consider value-dependent cases, because doing so is 6032 // very difficult. Ideally, we should handle them more gracefully. 6033 if (!EIA->getCond()->EvaluateWithSubstitution( 6034 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6035 return EIA; 6036 6037 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6038 return EIA; 6039 } 6040 return nullptr; 6041 } 6042 6043 /// \brief Add all of the function declarations in the given function set to 6044 /// the overload candidate set. 6045 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6046 ArrayRef<Expr *> Args, 6047 OverloadCandidateSet& CandidateSet, 6048 TemplateArgumentListInfo *ExplicitTemplateArgs, 6049 bool SuppressUserConversions, 6050 bool PartialOverloading) { 6051 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6052 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6053 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6054 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 6055 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6056 cast<CXXMethodDecl>(FD)->getParent(), 6057 Args[0]->getType(), Args[0]->Classify(Context), 6058 Args.slice(1), CandidateSet, 6059 SuppressUserConversions, PartialOverloading); 6060 else 6061 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 6062 SuppressUserConversions, PartialOverloading); 6063 } else { 6064 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 6065 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 6066 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 6067 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 6068 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6069 ExplicitTemplateArgs, 6070 Args[0]->getType(), 6071 Args[0]->Classify(Context), Args.slice(1), 6072 CandidateSet, SuppressUserConversions, 6073 PartialOverloading); 6074 else 6075 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6076 ExplicitTemplateArgs, Args, 6077 CandidateSet, SuppressUserConversions, 6078 PartialOverloading); 6079 } 6080 } 6081 } 6082 6083 /// AddMethodCandidate - Adds a named decl (which is some kind of 6084 /// method) as a method candidate to the given overload set. 6085 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6086 QualType ObjectType, 6087 Expr::Classification ObjectClassification, 6088 ArrayRef<Expr *> Args, 6089 OverloadCandidateSet& CandidateSet, 6090 bool SuppressUserConversions) { 6091 NamedDecl *Decl = FoundDecl.getDecl(); 6092 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6093 6094 if (isa<UsingShadowDecl>(Decl)) 6095 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6096 6097 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6098 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6099 "Expected a member function template"); 6100 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6101 /*ExplicitArgs*/ nullptr, 6102 ObjectType, ObjectClassification, 6103 Args, CandidateSet, 6104 SuppressUserConversions); 6105 } else { 6106 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6107 ObjectType, ObjectClassification, 6108 Args, 6109 CandidateSet, SuppressUserConversions); 6110 } 6111 } 6112 6113 /// AddMethodCandidate - Adds the given C++ member function to the set 6114 /// of candidate functions, using the given function call arguments 6115 /// and the object argument (@c Object). For example, in a call 6116 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6117 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6118 /// allow user-defined conversions via constructors or conversion 6119 /// operators. 6120 void 6121 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6122 CXXRecordDecl *ActingContext, QualType ObjectType, 6123 Expr::Classification ObjectClassification, 6124 ArrayRef<Expr *> Args, 6125 OverloadCandidateSet &CandidateSet, 6126 bool SuppressUserConversions, 6127 bool PartialOverloading) { 6128 const FunctionProtoType *Proto 6129 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6130 assert(Proto && "Methods without a prototype cannot be overloaded"); 6131 assert(!isa<CXXConstructorDecl>(Method) && 6132 "Use AddOverloadCandidate for constructors"); 6133 6134 if (!CandidateSet.isNewCandidate(Method)) 6135 return; 6136 6137 // C++11 [class.copy]p23: [DR1402] 6138 // A defaulted move assignment operator that is defined as deleted is 6139 // ignored by overload resolution. 6140 if (Method->isDefaulted() && Method->isDeleted() && 6141 Method->isMoveAssignmentOperator()) 6142 return; 6143 6144 // Overload resolution is always an unevaluated context. 6145 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6146 6147 // Add this candidate 6148 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6149 Candidate.FoundDecl = FoundDecl; 6150 Candidate.Function = Method; 6151 Candidate.IsSurrogate = false; 6152 Candidate.IgnoreObjectArgument = false; 6153 Candidate.ExplicitCallArguments = Args.size(); 6154 6155 unsigned NumParams = Proto->getNumParams(); 6156 6157 // (C++ 13.3.2p2): A candidate function having fewer than m 6158 // parameters is viable only if it has an ellipsis in its parameter 6159 // list (8.3.5). 6160 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6161 !Proto->isVariadic()) { 6162 Candidate.Viable = false; 6163 Candidate.FailureKind = ovl_fail_too_many_arguments; 6164 return; 6165 } 6166 6167 // (C++ 13.3.2p2): A candidate function having more than m parameters 6168 // is viable only if the (m+1)st parameter has a default argument 6169 // (8.3.6). For the purposes of overload resolution, the 6170 // parameter list is truncated on the right, so that there are 6171 // exactly m parameters. 6172 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6173 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6174 // Not enough arguments. 6175 Candidate.Viable = false; 6176 Candidate.FailureKind = ovl_fail_too_few_arguments; 6177 return; 6178 } 6179 6180 Candidate.Viable = true; 6181 6182 if (Method->isStatic() || ObjectType.isNull()) 6183 // The implicit object argument is ignored. 6184 Candidate.IgnoreObjectArgument = true; 6185 else { 6186 // Determine the implicit conversion sequence for the object 6187 // parameter. 6188 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6189 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6190 Method, ActingContext); 6191 if (Candidate.Conversions[0].isBad()) { 6192 Candidate.Viable = false; 6193 Candidate.FailureKind = ovl_fail_bad_conversion; 6194 return; 6195 } 6196 } 6197 6198 // (CUDA B.1): Check for invalid calls between targets. 6199 if (getLangOpts().CUDA) 6200 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6201 if (CheckCUDATarget(Caller, Method)) { 6202 Candidate.Viable = false; 6203 Candidate.FailureKind = ovl_fail_bad_target; 6204 return; 6205 } 6206 6207 // Determine the implicit conversion sequences for each of the 6208 // arguments. 6209 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6210 if (ArgIdx < NumParams) { 6211 // (C++ 13.3.2p3): for F to be a viable function, there shall 6212 // exist for each argument an implicit conversion sequence 6213 // (13.3.3.1) that converts that argument to the corresponding 6214 // parameter of F. 6215 QualType ParamType = Proto->getParamType(ArgIdx); 6216 Candidate.Conversions[ArgIdx + 1] 6217 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6218 SuppressUserConversions, 6219 /*InOverloadResolution=*/true, 6220 /*AllowObjCWritebackConversion=*/ 6221 getLangOpts().ObjCAutoRefCount); 6222 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6223 Candidate.Viable = false; 6224 Candidate.FailureKind = ovl_fail_bad_conversion; 6225 return; 6226 } 6227 } else { 6228 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6229 // argument for which there is no corresponding parameter is 6230 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6231 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6232 } 6233 } 6234 6235 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6236 Candidate.Viable = false; 6237 Candidate.FailureKind = ovl_fail_enable_if; 6238 Candidate.DeductionFailure.Data = FailedAttr; 6239 return; 6240 } 6241 } 6242 6243 /// \brief Add a C++ member function template as a candidate to the candidate 6244 /// set, using template argument deduction to produce an appropriate member 6245 /// function template specialization. 6246 void 6247 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6248 DeclAccessPair FoundDecl, 6249 CXXRecordDecl *ActingContext, 6250 TemplateArgumentListInfo *ExplicitTemplateArgs, 6251 QualType ObjectType, 6252 Expr::Classification ObjectClassification, 6253 ArrayRef<Expr *> Args, 6254 OverloadCandidateSet& CandidateSet, 6255 bool SuppressUserConversions, 6256 bool PartialOverloading) { 6257 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6258 return; 6259 6260 // C++ [over.match.funcs]p7: 6261 // In each case where a candidate is a function template, candidate 6262 // function template specializations are generated using template argument 6263 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6264 // candidate functions in the usual way.113) A given name can refer to one 6265 // or more function templates and also to a set of overloaded non-template 6266 // functions. In such a case, the candidate functions generated from each 6267 // function template are combined with the set of non-template candidate 6268 // functions. 6269 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6270 FunctionDecl *Specialization = nullptr; 6271 if (TemplateDeductionResult Result 6272 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 6273 Specialization, Info, PartialOverloading)) { 6274 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6275 Candidate.FoundDecl = FoundDecl; 6276 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6277 Candidate.Viable = false; 6278 Candidate.FailureKind = ovl_fail_bad_deduction; 6279 Candidate.IsSurrogate = false; 6280 Candidate.IgnoreObjectArgument = false; 6281 Candidate.ExplicitCallArguments = Args.size(); 6282 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6283 Info); 6284 return; 6285 } 6286 6287 // Add the function template specialization produced by template argument 6288 // deduction as a candidate. 6289 assert(Specialization && "Missing member function template specialization?"); 6290 assert(isa<CXXMethodDecl>(Specialization) && 6291 "Specialization is not a member function?"); 6292 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6293 ActingContext, ObjectType, ObjectClassification, Args, 6294 CandidateSet, SuppressUserConversions, PartialOverloading); 6295 } 6296 6297 /// \brief Add a C++ function template specialization as a candidate 6298 /// in the candidate set, using template argument deduction to produce 6299 /// an appropriate function template specialization. 6300 void 6301 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6302 DeclAccessPair FoundDecl, 6303 TemplateArgumentListInfo *ExplicitTemplateArgs, 6304 ArrayRef<Expr *> Args, 6305 OverloadCandidateSet& CandidateSet, 6306 bool SuppressUserConversions, 6307 bool PartialOverloading) { 6308 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6309 return; 6310 6311 // C++ [over.match.funcs]p7: 6312 // In each case where a candidate is a function template, candidate 6313 // function template specializations are generated using template argument 6314 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6315 // candidate functions in the usual way.113) A given name can refer to one 6316 // or more function templates and also to a set of overloaded non-template 6317 // functions. In such a case, the candidate functions generated from each 6318 // function template are combined with the set of non-template candidate 6319 // functions. 6320 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6321 FunctionDecl *Specialization = nullptr; 6322 if (TemplateDeductionResult Result 6323 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 6324 Specialization, Info, PartialOverloading)) { 6325 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6326 Candidate.FoundDecl = FoundDecl; 6327 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6328 Candidate.Viable = false; 6329 Candidate.FailureKind = ovl_fail_bad_deduction; 6330 Candidate.IsSurrogate = false; 6331 Candidate.IgnoreObjectArgument = false; 6332 Candidate.ExplicitCallArguments = Args.size(); 6333 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6334 Info); 6335 return; 6336 } 6337 6338 // Add the function template specialization produced by template argument 6339 // deduction as a candidate. 6340 assert(Specialization && "Missing function template specialization?"); 6341 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6342 SuppressUserConversions, PartialOverloading); 6343 } 6344 6345 /// Determine whether this is an allowable conversion from the result 6346 /// of an explicit conversion operator to the expected type, per C++ 6347 /// [over.match.conv]p1 and [over.match.ref]p1. 6348 /// 6349 /// \param ConvType The return type of the conversion function. 6350 /// 6351 /// \param ToType The type we are converting to. 6352 /// 6353 /// \param AllowObjCPointerConversion Allow a conversion from one 6354 /// Objective-C pointer to another. 6355 /// 6356 /// \returns true if the conversion is allowable, false otherwise. 6357 static bool isAllowableExplicitConversion(Sema &S, 6358 QualType ConvType, QualType ToType, 6359 bool AllowObjCPointerConversion) { 6360 QualType ToNonRefType = ToType.getNonReferenceType(); 6361 6362 // Easy case: the types are the same. 6363 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6364 return true; 6365 6366 // Allow qualification conversions. 6367 bool ObjCLifetimeConversion; 6368 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6369 ObjCLifetimeConversion)) 6370 return true; 6371 6372 // If we're not allowed to consider Objective-C pointer conversions, 6373 // we're done. 6374 if (!AllowObjCPointerConversion) 6375 return false; 6376 6377 // Is this an Objective-C pointer conversion? 6378 bool IncompatibleObjC = false; 6379 QualType ConvertedType; 6380 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6381 IncompatibleObjC); 6382 } 6383 6384 /// AddConversionCandidate - Add a C++ conversion function as a 6385 /// candidate in the candidate set (C++ [over.match.conv], 6386 /// C++ [over.match.copy]). From is the expression we're converting from, 6387 /// and ToType is the type that we're eventually trying to convert to 6388 /// (which may or may not be the same type as the type that the 6389 /// conversion function produces). 6390 void 6391 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6392 DeclAccessPair FoundDecl, 6393 CXXRecordDecl *ActingContext, 6394 Expr *From, QualType ToType, 6395 OverloadCandidateSet& CandidateSet, 6396 bool AllowObjCConversionOnExplicit) { 6397 assert(!Conversion->getDescribedFunctionTemplate() && 6398 "Conversion function templates use AddTemplateConversionCandidate"); 6399 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6400 if (!CandidateSet.isNewCandidate(Conversion)) 6401 return; 6402 6403 // If the conversion function has an undeduced return type, trigger its 6404 // deduction now. 6405 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6406 if (DeduceReturnType(Conversion, From->getExprLoc())) 6407 return; 6408 ConvType = Conversion->getConversionType().getNonReferenceType(); 6409 } 6410 6411 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6412 // operator is only a candidate if its return type is the target type or 6413 // can be converted to the target type with a qualification conversion. 6414 if (Conversion->isExplicit() && 6415 !isAllowableExplicitConversion(*this, ConvType, ToType, 6416 AllowObjCConversionOnExplicit)) 6417 return; 6418 6419 // Overload resolution is always an unevaluated context. 6420 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6421 6422 // Add this candidate 6423 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6424 Candidate.FoundDecl = FoundDecl; 6425 Candidate.Function = Conversion; 6426 Candidate.IsSurrogate = false; 6427 Candidate.IgnoreObjectArgument = false; 6428 Candidate.FinalConversion.setAsIdentityConversion(); 6429 Candidate.FinalConversion.setFromType(ConvType); 6430 Candidate.FinalConversion.setAllToTypes(ToType); 6431 Candidate.Viable = true; 6432 Candidate.ExplicitCallArguments = 1; 6433 6434 // C++ [over.match.funcs]p4: 6435 // For conversion functions, the function is considered to be a member of 6436 // the class of the implicit implied object argument for the purpose of 6437 // defining the type of the implicit object parameter. 6438 // 6439 // Determine the implicit conversion sequence for the implicit 6440 // object parameter. 6441 QualType ImplicitParamType = From->getType(); 6442 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6443 ImplicitParamType = FromPtrType->getPointeeType(); 6444 CXXRecordDecl *ConversionContext 6445 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6446 6447 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6448 *this, CandidateSet.getLocation(), From->getType(), 6449 From->Classify(Context), Conversion, ConversionContext); 6450 6451 if (Candidate.Conversions[0].isBad()) { 6452 Candidate.Viable = false; 6453 Candidate.FailureKind = ovl_fail_bad_conversion; 6454 return; 6455 } 6456 6457 // We won't go through a user-defined type conversion function to convert a 6458 // derived to base as such conversions are given Conversion Rank. They only 6459 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6460 QualType FromCanon 6461 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6462 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6463 if (FromCanon == ToCanon || 6464 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 6465 Candidate.Viable = false; 6466 Candidate.FailureKind = ovl_fail_trivial_conversion; 6467 return; 6468 } 6469 6470 // To determine what the conversion from the result of calling the 6471 // conversion function to the type we're eventually trying to 6472 // convert to (ToType), we need to synthesize a call to the 6473 // conversion function and attempt copy initialization from it. This 6474 // makes sure that we get the right semantics with respect to 6475 // lvalues/rvalues and the type. Fortunately, we can allocate this 6476 // call on the stack and we don't need its arguments to be 6477 // well-formed. 6478 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6479 VK_LValue, From->getLocStart()); 6480 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6481 Context.getPointerType(Conversion->getType()), 6482 CK_FunctionToPointerDecay, 6483 &ConversionRef, VK_RValue); 6484 6485 QualType ConversionType = Conversion->getConversionType(); 6486 if (!isCompleteType(From->getLocStart(), ConversionType)) { 6487 Candidate.Viable = false; 6488 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6489 return; 6490 } 6491 6492 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6493 6494 // Note that it is safe to allocate CallExpr on the stack here because 6495 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6496 // allocator). 6497 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6498 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6499 From->getLocStart()); 6500 ImplicitConversionSequence ICS = 6501 TryCopyInitialization(*this, &Call, ToType, 6502 /*SuppressUserConversions=*/true, 6503 /*InOverloadResolution=*/false, 6504 /*AllowObjCWritebackConversion=*/false); 6505 6506 switch (ICS.getKind()) { 6507 case ImplicitConversionSequence::StandardConversion: 6508 Candidate.FinalConversion = ICS.Standard; 6509 6510 // C++ [over.ics.user]p3: 6511 // If the user-defined conversion is specified by a specialization of a 6512 // conversion function template, the second standard conversion sequence 6513 // shall have exact match rank. 6514 if (Conversion->getPrimaryTemplate() && 6515 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6516 Candidate.Viable = false; 6517 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6518 return; 6519 } 6520 6521 // C++0x [dcl.init.ref]p5: 6522 // In the second case, if the reference is an rvalue reference and 6523 // the second standard conversion sequence of the user-defined 6524 // conversion sequence includes an lvalue-to-rvalue conversion, the 6525 // program is ill-formed. 6526 if (ToType->isRValueReferenceType() && 6527 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6528 Candidate.Viable = false; 6529 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6530 return; 6531 } 6532 break; 6533 6534 case ImplicitConversionSequence::BadConversion: 6535 Candidate.Viable = false; 6536 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6537 return; 6538 6539 default: 6540 llvm_unreachable( 6541 "Can only end up with a standard conversion sequence or failure"); 6542 } 6543 6544 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6545 Candidate.Viable = false; 6546 Candidate.FailureKind = ovl_fail_enable_if; 6547 Candidate.DeductionFailure.Data = FailedAttr; 6548 return; 6549 } 6550 } 6551 6552 /// \brief Adds a conversion function template specialization 6553 /// candidate to the overload set, using template argument deduction 6554 /// to deduce the template arguments of the conversion function 6555 /// template from the type that we are converting to (C++ 6556 /// [temp.deduct.conv]). 6557 void 6558 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6559 DeclAccessPair FoundDecl, 6560 CXXRecordDecl *ActingDC, 6561 Expr *From, QualType ToType, 6562 OverloadCandidateSet &CandidateSet, 6563 bool AllowObjCConversionOnExplicit) { 6564 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6565 "Only conversion function templates permitted here"); 6566 6567 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6568 return; 6569 6570 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6571 CXXConversionDecl *Specialization = nullptr; 6572 if (TemplateDeductionResult Result 6573 = DeduceTemplateArguments(FunctionTemplate, ToType, 6574 Specialization, Info)) { 6575 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6576 Candidate.FoundDecl = FoundDecl; 6577 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6578 Candidate.Viable = false; 6579 Candidate.FailureKind = ovl_fail_bad_deduction; 6580 Candidate.IsSurrogate = false; 6581 Candidate.IgnoreObjectArgument = false; 6582 Candidate.ExplicitCallArguments = 1; 6583 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6584 Info); 6585 return; 6586 } 6587 6588 // Add the conversion function template specialization produced by 6589 // template argument deduction as a candidate. 6590 assert(Specialization && "Missing function template specialization?"); 6591 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6592 CandidateSet, AllowObjCConversionOnExplicit); 6593 } 6594 6595 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6596 /// converts the given @c Object to a function pointer via the 6597 /// conversion function @c Conversion, and then attempts to call it 6598 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6599 /// the type of function that we'll eventually be calling. 6600 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6601 DeclAccessPair FoundDecl, 6602 CXXRecordDecl *ActingContext, 6603 const FunctionProtoType *Proto, 6604 Expr *Object, 6605 ArrayRef<Expr *> Args, 6606 OverloadCandidateSet& CandidateSet) { 6607 if (!CandidateSet.isNewCandidate(Conversion)) 6608 return; 6609 6610 // Overload resolution is always an unevaluated context. 6611 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6612 6613 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6614 Candidate.FoundDecl = FoundDecl; 6615 Candidate.Function = nullptr; 6616 Candidate.Surrogate = Conversion; 6617 Candidate.Viable = true; 6618 Candidate.IsSurrogate = true; 6619 Candidate.IgnoreObjectArgument = false; 6620 Candidate.ExplicitCallArguments = Args.size(); 6621 6622 // Determine the implicit conversion sequence for the implicit 6623 // object parameter. 6624 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 6625 *this, CandidateSet.getLocation(), Object->getType(), 6626 Object->Classify(Context), Conversion, ActingContext); 6627 if (ObjectInit.isBad()) { 6628 Candidate.Viable = false; 6629 Candidate.FailureKind = ovl_fail_bad_conversion; 6630 Candidate.Conversions[0] = ObjectInit; 6631 return; 6632 } 6633 6634 // The first conversion is actually a user-defined conversion whose 6635 // first conversion is ObjectInit's standard conversion (which is 6636 // effectively a reference binding). Record it as such. 6637 Candidate.Conversions[0].setUserDefined(); 6638 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6639 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6640 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6641 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6642 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6643 Candidate.Conversions[0].UserDefined.After 6644 = Candidate.Conversions[0].UserDefined.Before; 6645 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6646 6647 // Find the 6648 unsigned NumParams = Proto->getNumParams(); 6649 6650 // (C++ 13.3.2p2): A candidate function having fewer than m 6651 // parameters is viable only if it has an ellipsis in its parameter 6652 // list (8.3.5). 6653 if (Args.size() > NumParams && !Proto->isVariadic()) { 6654 Candidate.Viable = false; 6655 Candidate.FailureKind = ovl_fail_too_many_arguments; 6656 return; 6657 } 6658 6659 // Function types don't have any default arguments, so just check if 6660 // we have enough arguments. 6661 if (Args.size() < NumParams) { 6662 // Not enough arguments. 6663 Candidate.Viable = false; 6664 Candidate.FailureKind = ovl_fail_too_few_arguments; 6665 return; 6666 } 6667 6668 // Determine the implicit conversion sequences for each of the 6669 // arguments. 6670 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6671 if (ArgIdx < NumParams) { 6672 // (C++ 13.3.2p3): for F to be a viable function, there shall 6673 // exist for each argument an implicit conversion sequence 6674 // (13.3.3.1) that converts that argument to the corresponding 6675 // parameter of F. 6676 QualType ParamType = Proto->getParamType(ArgIdx); 6677 Candidate.Conversions[ArgIdx + 1] 6678 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6679 /*SuppressUserConversions=*/false, 6680 /*InOverloadResolution=*/false, 6681 /*AllowObjCWritebackConversion=*/ 6682 getLangOpts().ObjCAutoRefCount); 6683 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6684 Candidate.Viable = false; 6685 Candidate.FailureKind = ovl_fail_bad_conversion; 6686 return; 6687 } 6688 } else { 6689 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6690 // argument for which there is no corresponding parameter is 6691 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6692 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6693 } 6694 } 6695 6696 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6697 Candidate.Viable = false; 6698 Candidate.FailureKind = ovl_fail_enable_if; 6699 Candidate.DeductionFailure.Data = FailedAttr; 6700 return; 6701 } 6702 } 6703 6704 /// \brief Add overload candidates for overloaded operators that are 6705 /// member functions. 6706 /// 6707 /// Add the overloaded operator candidates that are member functions 6708 /// for the operator Op that was used in an operator expression such 6709 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6710 /// CandidateSet will store the added overload candidates. (C++ 6711 /// [over.match.oper]). 6712 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6713 SourceLocation OpLoc, 6714 ArrayRef<Expr *> Args, 6715 OverloadCandidateSet& CandidateSet, 6716 SourceRange OpRange) { 6717 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6718 6719 // C++ [over.match.oper]p3: 6720 // For a unary operator @ with an operand of a type whose 6721 // cv-unqualified version is T1, and for a binary operator @ with 6722 // a left operand of a type whose cv-unqualified version is T1 and 6723 // a right operand of a type whose cv-unqualified version is T2, 6724 // three sets of candidate functions, designated member 6725 // candidates, non-member candidates and built-in candidates, are 6726 // constructed as follows: 6727 QualType T1 = Args[0]->getType(); 6728 6729 // -- If T1 is a complete class type or a class currently being 6730 // defined, the set of member candidates is the result of the 6731 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6732 // the set of member candidates is empty. 6733 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6734 // Complete the type if it can be completed. 6735 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 6736 return; 6737 // If the type is neither complete nor being defined, bail out now. 6738 if (!T1Rec->getDecl()->getDefinition()) 6739 return; 6740 6741 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6742 LookupQualifiedName(Operators, T1Rec->getDecl()); 6743 Operators.suppressDiagnostics(); 6744 6745 for (LookupResult::iterator Oper = Operators.begin(), 6746 OperEnd = Operators.end(); 6747 Oper != OperEnd; 6748 ++Oper) 6749 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6750 Args[0]->Classify(Context), 6751 Args.slice(1), 6752 CandidateSet, 6753 /* SuppressUserConversions = */ false); 6754 } 6755 } 6756 6757 /// AddBuiltinCandidate - Add a candidate for a built-in 6758 /// operator. ResultTy and ParamTys are the result and parameter types 6759 /// of the built-in candidate, respectively. Args and NumArgs are the 6760 /// arguments being passed to the candidate. IsAssignmentOperator 6761 /// should be true when this built-in candidate is an assignment 6762 /// operator. NumContextualBoolArguments is the number of arguments 6763 /// (at the beginning of the argument list) that will be contextually 6764 /// converted to bool. 6765 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6766 ArrayRef<Expr *> Args, 6767 OverloadCandidateSet& CandidateSet, 6768 bool IsAssignmentOperator, 6769 unsigned NumContextualBoolArguments) { 6770 // Overload resolution is always an unevaluated context. 6771 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6772 6773 // Add this candidate 6774 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6775 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 6776 Candidate.Function = nullptr; 6777 Candidate.IsSurrogate = false; 6778 Candidate.IgnoreObjectArgument = false; 6779 Candidate.BuiltinTypes.ResultTy = ResultTy; 6780 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6781 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6782 6783 // Determine the implicit conversion sequences for each of the 6784 // arguments. 6785 Candidate.Viable = true; 6786 Candidate.ExplicitCallArguments = Args.size(); 6787 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6788 // C++ [over.match.oper]p4: 6789 // For the built-in assignment operators, conversions of the 6790 // left operand are restricted as follows: 6791 // -- no temporaries are introduced to hold the left operand, and 6792 // -- no user-defined conversions are applied to the left 6793 // operand to achieve a type match with the left-most 6794 // parameter of a built-in candidate. 6795 // 6796 // We block these conversions by turning off user-defined 6797 // conversions, since that is the only way that initialization of 6798 // a reference to a non-class type can occur from something that 6799 // is not of the same type. 6800 if (ArgIdx < NumContextualBoolArguments) { 6801 assert(ParamTys[ArgIdx] == Context.BoolTy && 6802 "Contextual conversion to bool requires bool type"); 6803 Candidate.Conversions[ArgIdx] 6804 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6805 } else { 6806 Candidate.Conversions[ArgIdx] 6807 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6808 ArgIdx == 0 && IsAssignmentOperator, 6809 /*InOverloadResolution=*/false, 6810 /*AllowObjCWritebackConversion=*/ 6811 getLangOpts().ObjCAutoRefCount); 6812 } 6813 if (Candidate.Conversions[ArgIdx].isBad()) { 6814 Candidate.Viable = false; 6815 Candidate.FailureKind = ovl_fail_bad_conversion; 6816 break; 6817 } 6818 } 6819 } 6820 6821 namespace { 6822 6823 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6824 /// candidate operator functions for built-in operators (C++ 6825 /// [over.built]). The types are separated into pointer types and 6826 /// enumeration types. 6827 class BuiltinCandidateTypeSet { 6828 /// TypeSet - A set of types. 6829 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 6830 llvm::SmallPtrSet<QualType, 8>> TypeSet; 6831 6832 /// PointerTypes - The set of pointer types that will be used in the 6833 /// built-in candidates. 6834 TypeSet PointerTypes; 6835 6836 /// MemberPointerTypes - The set of member pointer types that will be 6837 /// used in the built-in candidates. 6838 TypeSet MemberPointerTypes; 6839 6840 /// EnumerationTypes - The set of enumeration types that will be 6841 /// used in the built-in candidates. 6842 TypeSet EnumerationTypes; 6843 6844 /// \brief The set of vector types that will be used in the built-in 6845 /// candidates. 6846 TypeSet VectorTypes; 6847 6848 /// \brief A flag indicating non-record types are viable candidates 6849 bool HasNonRecordTypes; 6850 6851 /// \brief A flag indicating whether either arithmetic or enumeration types 6852 /// were present in the candidate set. 6853 bool HasArithmeticOrEnumeralTypes; 6854 6855 /// \brief A flag indicating whether the nullptr type was present in the 6856 /// candidate set. 6857 bool HasNullPtrType; 6858 6859 /// Sema - The semantic analysis instance where we are building the 6860 /// candidate type set. 6861 Sema &SemaRef; 6862 6863 /// Context - The AST context in which we will build the type sets. 6864 ASTContext &Context; 6865 6866 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6867 const Qualifiers &VisibleQuals); 6868 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6869 6870 public: 6871 /// iterator - Iterates through the types that are part of the set. 6872 typedef TypeSet::iterator iterator; 6873 6874 BuiltinCandidateTypeSet(Sema &SemaRef) 6875 : HasNonRecordTypes(false), 6876 HasArithmeticOrEnumeralTypes(false), 6877 HasNullPtrType(false), 6878 SemaRef(SemaRef), 6879 Context(SemaRef.Context) { } 6880 6881 void AddTypesConvertedFrom(QualType Ty, 6882 SourceLocation Loc, 6883 bool AllowUserConversions, 6884 bool AllowExplicitConversions, 6885 const Qualifiers &VisibleTypeConversionsQuals); 6886 6887 /// pointer_begin - First pointer type found; 6888 iterator pointer_begin() { return PointerTypes.begin(); } 6889 6890 /// pointer_end - Past the last pointer type found; 6891 iterator pointer_end() { return PointerTypes.end(); } 6892 6893 /// member_pointer_begin - First member pointer type found; 6894 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6895 6896 /// member_pointer_end - Past the last member pointer type found; 6897 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6898 6899 /// enumeration_begin - First enumeration type found; 6900 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6901 6902 /// enumeration_end - Past the last enumeration type found; 6903 iterator enumeration_end() { return EnumerationTypes.end(); } 6904 6905 iterator vector_begin() { return VectorTypes.begin(); } 6906 iterator vector_end() { return VectorTypes.end(); } 6907 6908 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6909 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6910 bool hasNullPtrType() const { return HasNullPtrType; } 6911 }; 6912 6913 } // end anonymous namespace 6914 6915 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6916 /// the set of pointer types along with any more-qualified variants of 6917 /// that type. For example, if @p Ty is "int const *", this routine 6918 /// will add "int const *", "int const volatile *", "int const 6919 /// restrict *", and "int const volatile restrict *" to the set of 6920 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6921 /// false otherwise. 6922 /// 6923 /// FIXME: what to do about extended qualifiers? 6924 bool 6925 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6926 const Qualifiers &VisibleQuals) { 6927 6928 // Insert this type. 6929 if (!PointerTypes.insert(Ty)) 6930 return false; 6931 6932 QualType PointeeTy; 6933 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6934 bool buildObjCPtr = false; 6935 if (!PointerTy) { 6936 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6937 PointeeTy = PTy->getPointeeType(); 6938 buildObjCPtr = true; 6939 } else { 6940 PointeeTy = PointerTy->getPointeeType(); 6941 } 6942 6943 // Don't add qualified variants of arrays. For one, they're not allowed 6944 // (the qualifier would sink to the element type), and for another, the 6945 // only overload situation where it matters is subscript or pointer +- int, 6946 // and those shouldn't have qualifier variants anyway. 6947 if (PointeeTy->isArrayType()) 6948 return true; 6949 6950 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6951 bool hasVolatile = VisibleQuals.hasVolatile(); 6952 bool hasRestrict = VisibleQuals.hasRestrict(); 6953 6954 // Iterate through all strict supersets of BaseCVR. 6955 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6956 if ((CVR | BaseCVR) != CVR) continue; 6957 // Skip over volatile if no volatile found anywhere in the types. 6958 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6959 6960 // Skip over restrict if no restrict found anywhere in the types, or if 6961 // the type cannot be restrict-qualified. 6962 if ((CVR & Qualifiers::Restrict) && 6963 (!hasRestrict || 6964 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6965 continue; 6966 6967 // Build qualified pointee type. 6968 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6969 6970 // Build qualified pointer type. 6971 QualType QPointerTy; 6972 if (!buildObjCPtr) 6973 QPointerTy = Context.getPointerType(QPointeeTy); 6974 else 6975 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6976 6977 // Insert qualified pointer type. 6978 PointerTypes.insert(QPointerTy); 6979 } 6980 6981 return true; 6982 } 6983 6984 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6985 /// to the set of pointer types along with any more-qualified variants of 6986 /// that type. For example, if @p Ty is "int const *", this routine 6987 /// will add "int const *", "int const volatile *", "int const 6988 /// restrict *", and "int const volatile restrict *" to the set of 6989 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6990 /// false otherwise. 6991 /// 6992 /// FIXME: what to do about extended qualifiers? 6993 bool 6994 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6995 QualType Ty) { 6996 // Insert this type. 6997 if (!MemberPointerTypes.insert(Ty)) 6998 return false; 6999 7000 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7001 assert(PointerTy && "type was not a member pointer type!"); 7002 7003 QualType PointeeTy = PointerTy->getPointeeType(); 7004 // Don't add qualified variants of arrays. For one, they're not allowed 7005 // (the qualifier would sink to the element type), and for another, the 7006 // only overload situation where it matters is subscript or pointer +- int, 7007 // and those shouldn't have qualifier variants anyway. 7008 if (PointeeTy->isArrayType()) 7009 return true; 7010 const Type *ClassTy = PointerTy->getClass(); 7011 7012 // Iterate through all strict supersets of the pointee type's CVR 7013 // qualifiers. 7014 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7015 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7016 if ((CVR | BaseCVR) != CVR) continue; 7017 7018 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7019 MemberPointerTypes.insert( 7020 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7021 } 7022 7023 return true; 7024 } 7025 7026 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7027 /// Ty can be implicit converted to the given set of @p Types. We're 7028 /// primarily interested in pointer types and enumeration types. We also 7029 /// take member pointer types, for the conditional operator. 7030 /// AllowUserConversions is true if we should look at the conversion 7031 /// functions of a class type, and AllowExplicitConversions if we 7032 /// should also include the explicit conversion functions of a class 7033 /// type. 7034 void 7035 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7036 SourceLocation Loc, 7037 bool AllowUserConversions, 7038 bool AllowExplicitConversions, 7039 const Qualifiers &VisibleQuals) { 7040 // Only deal with canonical types. 7041 Ty = Context.getCanonicalType(Ty); 7042 7043 // Look through reference types; they aren't part of the type of an 7044 // expression for the purposes of conversions. 7045 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7046 Ty = RefTy->getPointeeType(); 7047 7048 // If we're dealing with an array type, decay to the pointer. 7049 if (Ty->isArrayType()) 7050 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7051 7052 // Otherwise, we don't care about qualifiers on the type. 7053 Ty = Ty.getLocalUnqualifiedType(); 7054 7055 // Flag if we ever add a non-record type. 7056 const RecordType *TyRec = Ty->getAs<RecordType>(); 7057 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7058 7059 // Flag if we encounter an arithmetic type. 7060 HasArithmeticOrEnumeralTypes = 7061 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7062 7063 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7064 PointerTypes.insert(Ty); 7065 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7066 // Insert our type, and its more-qualified variants, into the set 7067 // of types. 7068 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7069 return; 7070 } else if (Ty->isMemberPointerType()) { 7071 // Member pointers are far easier, since the pointee can't be converted. 7072 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7073 return; 7074 } else if (Ty->isEnumeralType()) { 7075 HasArithmeticOrEnumeralTypes = true; 7076 EnumerationTypes.insert(Ty); 7077 } else if (Ty->isVectorType()) { 7078 // We treat vector types as arithmetic types in many contexts as an 7079 // extension. 7080 HasArithmeticOrEnumeralTypes = true; 7081 VectorTypes.insert(Ty); 7082 } else if (Ty->isNullPtrType()) { 7083 HasNullPtrType = true; 7084 } else if (AllowUserConversions && TyRec) { 7085 // No conversion functions in incomplete types. 7086 if (!SemaRef.isCompleteType(Loc, Ty)) 7087 return; 7088 7089 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7090 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7091 if (isa<UsingShadowDecl>(D)) 7092 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7093 7094 // Skip conversion function templates; they don't tell us anything 7095 // about which builtin types we can convert to. 7096 if (isa<FunctionTemplateDecl>(D)) 7097 continue; 7098 7099 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7100 if (AllowExplicitConversions || !Conv->isExplicit()) { 7101 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7102 VisibleQuals); 7103 } 7104 } 7105 } 7106 } 7107 7108 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 7109 /// the volatile- and non-volatile-qualified assignment operators for the 7110 /// given type to the candidate set. 7111 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7112 QualType T, 7113 ArrayRef<Expr *> Args, 7114 OverloadCandidateSet &CandidateSet) { 7115 QualType ParamTypes[2]; 7116 7117 // T& operator=(T&, T) 7118 ParamTypes[0] = S.Context.getLValueReferenceType(T); 7119 ParamTypes[1] = T; 7120 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7121 /*IsAssignmentOperator=*/true); 7122 7123 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7124 // volatile T& operator=(volatile T&, T) 7125 ParamTypes[0] 7126 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 7127 ParamTypes[1] = T; 7128 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7129 /*IsAssignmentOperator=*/true); 7130 } 7131 } 7132 7133 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7134 /// if any, found in visible type conversion functions found in ArgExpr's type. 7135 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7136 Qualifiers VRQuals; 7137 const RecordType *TyRec; 7138 if (const MemberPointerType *RHSMPType = 7139 ArgExpr->getType()->getAs<MemberPointerType>()) 7140 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7141 else 7142 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7143 if (!TyRec) { 7144 // Just to be safe, assume the worst case. 7145 VRQuals.addVolatile(); 7146 VRQuals.addRestrict(); 7147 return VRQuals; 7148 } 7149 7150 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7151 if (!ClassDecl->hasDefinition()) 7152 return VRQuals; 7153 7154 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7155 if (isa<UsingShadowDecl>(D)) 7156 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7157 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7158 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7159 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7160 CanTy = ResTypeRef->getPointeeType(); 7161 // Need to go down the pointer/mempointer chain and add qualifiers 7162 // as see them. 7163 bool done = false; 7164 while (!done) { 7165 if (CanTy.isRestrictQualified()) 7166 VRQuals.addRestrict(); 7167 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7168 CanTy = ResTypePtr->getPointeeType(); 7169 else if (const MemberPointerType *ResTypeMPtr = 7170 CanTy->getAs<MemberPointerType>()) 7171 CanTy = ResTypeMPtr->getPointeeType(); 7172 else 7173 done = true; 7174 if (CanTy.isVolatileQualified()) 7175 VRQuals.addVolatile(); 7176 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7177 return VRQuals; 7178 } 7179 } 7180 } 7181 return VRQuals; 7182 } 7183 7184 namespace { 7185 7186 /// \brief Helper class to manage the addition of builtin operator overload 7187 /// candidates. It provides shared state and utility methods used throughout 7188 /// the process, as well as a helper method to add each group of builtin 7189 /// operator overloads from the standard to a candidate set. 7190 class BuiltinOperatorOverloadBuilder { 7191 // Common instance state available to all overload candidate addition methods. 7192 Sema &S; 7193 ArrayRef<Expr *> Args; 7194 Qualifiers VisibleTypeConversionsQuals; 7195 bool HasArithmeticOrEnumeralCandidateType; 7196 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7197 OverloadCandidateSet &CandidateSet; 7198 7199 // Define some constants used to index and iterate over the arithemetic types 7200 // provided via the getArithmeticType() method below. 7201 // The "promoted arithmetic types" are the arithmetic 7202 // types are that preserved by promotion (C++ [over.built]p2). 7203 static const unsigned FirstIntegralType = 4; 7204 static const unsigned LastIntegralType = 21; 7205 static const unsigned FirstPromotedIntegralType = 4, 7206 LastPromotedIntegralType = 12; 7207 static const unsigned FirstPromotedArithmeticType = 0, 7208 LastPromotedArithmeticType = 12; 7209 static const unsigned NumArithmeticTypes = 21; 7210 7211 /// \brief Get the canonical type for a given arithmetic type index. 7212 CanQualType getArithmeticType(unsigned index) { 7213 assert(index < NumArithmeticTypes); 7214 static CanQualType ASTContext::* const 7215 ArithmeticTypes[NumArithmeticTypes] = { 7216 // Start of promoted types. 7217 &ASTContext::FloatTy, 7218 &ASTContext::DoubleTy, 7219 &ASTContext::LongDoubleTy, 7220 &ASTContext::Float128Ty, 7221 7222 // Start of integral types. 7223 &ASTContext::IntTy, 7224 &ASTContext::LongTy, 7225 &ASTContext::LongLongTy, 7226 &ASTContext::Int128Ty, 7227 &ASTContext::UnsignedIntTy, 7228 &ASTContext::UnsignedLongTy, 7229 &ASTContext::UnsignedLongLongTy, 7230 &ASTContext::UnsignedInt128Ty, 7231 // End of promoted types. 7232 7233 &ASTContext::BoolTy, 7234 &ASTContext::CharTy, 7235 &ASTContext::WCharTy, 7236 &ASTContext::Char16Ty, 7237 &ASTContext::Char32Ty, 7238 &ASTContext::SignedCharTy, 7239 &ASTContext::ShortTy, 7240 &ASTContext::UnsignedCharTy, 7241 &ASTContext::UnsignedShortTy, 7242 // End of integral types. 7243 // FIXME: What about complex? What about half? 7244 }; 7245 return S.Context.*ArithmeticTypes[index]; 7246 } 7247 7248 /// \brief Gets the canonical type resulting from the usual arithemetic 7249 /// converions for the given arithmetic types. 7250 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 7251 // Accelerator table for performing the usual arithmetic conversions. 7252 // The rules are basically: 7253 // - if either is floating-point, use the wider floating-point 7254 // - if same signedness, use the higher rank 7255 // - if same size, use unsigned of the higher rank 7256 // - use the larger type 7257 // These rules, together with the axiom that higher ranks are 7258 // never smaller, are sufficient to precompute all of these results 7259 // *except* when dealing with signed types of higher rank. 7260 // (we could precompute SLL x UI for all known platforms, but it's 7261 // better not to make any assumptions). 7262 // We assume that int128 has a higher rank than long long on all platforms. 7263 enum PromotedType : int8_t { 7264 Dep=-1, 7265 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 7266 }; 7267 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 7268 [LastPromotedArithmeticType] = { 7269 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 7270 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 7271 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 7272 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 7273 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 7274 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 7275 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 7276 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 7277 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 7278 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 7279 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 7280 }; 7281 7282 assert(L < LastPromotedArithmeticType); 7283 assert(R < LastPromotedArithmeticType); 7284 int Idx = ConversionsTable[L][R]; 7285 7286 // Fast path: the table gives us a concrete answer. 7287 if (Idx != Dep) return getArithmeticType(Idx); 7288 7289 // Slow path: we need to compare widths. 7290 // An invariant is that the signed type has higher rank. 7291 CanQualType LT = getArithmeticType(L), 7292 RT = getArithmeticType(R); 7293 unsigned LW = S.Context.getIntWidth(LT), 7294 RW = S.Context.getIntWidth(RT); 7295 7296 // If they're different widths, use the signed type. 7297 if (LW > RW) return LT; 7298 else if (LW < RW) return RT; 7299 7300 // Otherwise, use the unsigned type of the signed type's rank. 7301 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 7302 assert(L == SLL || R == SLL); 7303 return S.Context.UnsignedLongLongTy; 7304 } 7305 7306 /// \brief Helper method to factor out the common pattern of adding overloads 7307 /// for '++' and '--' builtin operators. 7308 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7309 bool HasVolatile, 7310 bool HasRestrict) { 7311 QualType ParamTypes[2] = { 7312 S.Context.getLValueReferenceType(CandidateTy), 7313 S.Context.IntTy 7314 }; 7315 7316 // Non-volatile version. 7317 if (Args.size() == 1) 7318 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7319 else 7320 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7321 7322 // Use a heuristic to reduce number of builtin candidates in the set: 7323 // add volatile version only if there are conversions to a volatile type. 7324 if (HasVolatile) { 7325 ParamTypes[0] = 7326 S.Context.getLValueReferenceType( 7327 S.Context.getVolatileType(CandidateTy)); 7328 if (Args.size() == 1) 7329 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7330 else 7331 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7332 } 7333 7334 // Add restrict version only if there are conversions to a restrict type 7335 // and our candidate type is a non-restrict-qualified pointer. 7336 if (HasRestrict && CandidateTy->isAnyPointerType() && 7337 !CandidateTy.isRestrictQualified()) { 7338 ParamTypes[0] 7339 = S.Context.getLValueReferenceType( 7340 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7341 if (Args.size() == 1) 7342 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7343 else 7344 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7345 7346 if (HasVolatile) { 7347 ParamTypes[0] 7348 = S.Context.getLValueReferenceType( 7349 S.Context.getCVRQualifiedType(CandidateTy, 7350 (Qualifiers::Volatile | 7351 Qualifiers::Restrict))); 7352 if (Args.size() == 1) 7353 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7354 else 7355 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7356 } 7357 } 7358 7359 } 7360 7361 public: 7362 BuiltinOperatorOverloadBuilder( 7363 Sema &S, ArrayRef<Expr *> Args, 7364 Qualifiers VisibleTypeConversionsQuals, 7365 bool HasArithmeticOrEnumeralCandidateType, 7366 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7367 OverloadCandidateSet &CandidateSet) 7368 : S(S), Args(Args), 7369 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7370 HasArithmeticOrEnumeralCandidateType( 7371 HasArithmeticOrEnumeralCandidateType), 7372 CandidateTypes(CandidateTypes), 7373 CandidateSet(CandidateSet) { 7374 // Validate some of our static helper constants in debug builds. 7375 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7376 "Invalid first promoted integral type"); 7377 assert(getArithmeticType(LastPromotedIntegralType - 1) 7378 == S.Context.UnsignedInt128Ty && 7379 "Invalid last promoted integral type"); 7380 assert(getArithmeticType(FirstPromotedArithmeticType) 7381 == S.Context.FloatTy && 7382 "Invalid first promoted arithmetic type"); 7383 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7384 == S.Context.UnsignedInt128Ty && 7385 "Invalid last promoted arithmetic type"); 7386 } 7387 7388 // C++ [over.built]p3: 7389 // 7390 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7391 // is either volatile or empty, there exist candidate operator 7392 // functions of the form 7393 // 7394 // VQ T& operator++(VQ T&); 7395 // T operator++(VQ T&, int); 7396 // 7397 // C++ [over.built]p4: 7398 // 7399 // For every pair (T, VQ), where T is an arithmetic type other 7400 // than bool, and VQ is either volatile or empty, there exist 7401 // candidate operator functions of the form 7402 // 7403 // VQ T& operator--(VQ T&); 7404 // T operator--(VQ T&, int); 7405 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7406 if (!HasArithmeticOrEnumeralCandidateType) 7407 return; 7408 7409 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7410 Arith < NumArithmeticTypes; ++Arith) { 7411 addPlusPlusMinusMinusStyleOverloads( 7412 getArithmeticType(Arith), 7413 VisibleTypeConversionsQuals.hasVolatile(), 7414 VisibleTypeConversionsQuals.hasRestrict()); 7415 } 7416 } 7417 7418 // C++ [over.built]p5: 7419 // 7420 // For every pair (T, VQ), where T is a cv-qualified or 7421 // cv-unqualified object type, and VQ is either volatile or 7422 // empty, there exist candidate operator functions of the form 7423 // 7424 // T*VQ& operator++(T*VQ&); 7425 // T*VQ& operator--(T*VQ&); 7426 // T* operator++(T*VQ&, int); 7427 // T* operator--(T*VQ&, int); 7428 void addPlusPlusMinusMinusPointerOverloads() { 7429 for (BuiltinCandidateTypeSet::iterator 7430 Ptr = CandidateTypes[0].pointer_begin(), 7431 PtrEnd = CandidateTypes[0].pointer_end(); 7432 Ptr != PtrEnd; ++Ptr) { 7433 // Skip pointer types that aren't pointers to object types. 7434 if (!(*Ptr)->getPointeeType()->isObjectType()) 7435 continue; 7436 7437 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7438 (!(*Ptr).isVolatileQualified() && 7439 VisibleTypeConversionsQuals.hasVolatile()), 7440 (!(*Ptr).isRestrictQualified() && 7441 VisibleTypeConversionsQuals.hasRestrict())); 7442 } 7443 } 7444 7445 // C++ [over.built]p6: 7446 // For every cv-qualified or cv-unqualified object type T, there 7447 // exist candidate operator functions of the form 7448 // 7449 // T& operator*(T*); 7450 // 7451 // C++ [over.built]p7: 7452 // For every function type T that does not have cv-qualifiers or a 7453 // ref-qualifier, there exist candidate operator functions of the form 7454 // T& operator*(T*); 7455 void addUnaryStarPointerOverloads() { 7456 for (BuiltinCandidateTypeSet::iterator 7457 Ptr = CandidateTypes[0].pointer_begin(), 7458 PtrEnd = CandidateTypes[0].pointer_end(); 7459 Ptr != PtrEnd; ++Ptr) { 7460 QualType ParamTy = *Ptr; 7461 QualType PointeeTy = ParamTy->getPointeeType(); 7462 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7463 continue; 7464 7465 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7466 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7467 continue; 7468 7469 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7470 &ParamTy, Args, CandidateSet); 7471 } 7472 } 7473 7474 // C++ [over.built]p9: 7475 // For every promoted arithmetic type T, there exist candidate 7476 // operator functions of the form 7477 // 7478 // T operator+(T); 7479 // T operator-(T); 7480 void addUnaryPlusOrMinusArithmeticOverloads() { 7481 if (!HasArithmeticOrEnumeralCandidateType) 7482 return; 7483 7484 for (unsigned Arith = FirstPromotedArithmeticType; 7485 Arith < LastPromotedArithmeticType; ++Arith) { 7486 QualType ArithTy = getArithmeticType(Arith); 7487 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7488 } 7489 7490 // Extension: We also add these operators for vector types. 7491 for (BuiltinCandidateTypeSet::iterator 7492 Vec = CandidateTypes[0].vector_begin(), 7493 VecEnd = CandidateTypes[0].vector_end(); 7494 Vec != VecEnd; ++Vec) { 7495 QualType VecTy = *Vec; 7496 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7497 } 7498 } 7499 7500 // C++ [over.built]p8: 7501 // For every type T, there exist candidate operator functions of 7502 // the form 7503 // 7504 // T* operator+(T*); 7505 void addUnaryPlusPointerOverloads() { 7506 for (BuiltinCandidateTypeSet::iterator 7507 Ptr = CandidateTypes[0].pointer_begin(), 7508 PtrEnd = CandidateTypes[0].pointer_end(); 7509 Ptr != PtrEnd; ++Ptr) { 7510 QualType ParamTy = *Ptr; 7511 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7512 } 7513 } 7514 7515 // C++ [over.built]p10: 7516 // For every promoted integral type T, there exist candidate 7517 // operator functions of the form 7518 // 7519 // T operator~(T); 7520 void addUnaryTildePromotedIntegralOverloads() { 7521 if (!HasArithmeticOrEnumeralCandidateType) 7522 return; 7523 7524 for (unsigned Int = FirstPromotedIntegralType; 7525 Int < LastPromotedIntegralType; ++Int) { 7526 QualType IntTy = getArithmeticType(Int); 7527 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7528 } 7529 7530 // Extension: We also add this operator for vector types. 7531 for (BuiltinCandidateTypeSet::iterator 7532 Vec = CandidateTypes[0].vector_begin(), 7533 VecEnd = CandidateTypes[0].vector_end(); 7534 Vec != VecEnd; ++Vec) { 7535 QualType VecTy = *Vec; 7536 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7537 } 7538 } 7539 7540 // C++ [over.match.oper]p16: 7541 // For every pointer to member type T, there exist candidate operator 7542 // functions of the form 7543 // 7544 // bool operator==(T,T); 7545 // bool operator!=(T,T); 7546 void addEqualEqualOrNotEqualMemberPointerOverloads() { 7547 /// Set of (canonical) types that we've already handled. 7548 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7549 7550 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7551 for (BuiltinCandidateTypeSet::iterator 7552 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7553 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7554 MemPtr != MemPtrEnd; 7555 ++MemPtr) { 7556 // Don't add the same builtin candidate twice. 7557 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7558 continue; 7559 7560 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7561 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7562 } 7563 } 7564 } 7565 7566 // C++ [over.built]p15: 7567 // 7568 // For every T, where T is an enumeration type, a pointer type, or 7569 // std::nullptr_t, there exist candidate operator functions of the form 7570 // 7571 // bool operator<(T, T); 7572 // bool operator>(T, T); 7573 // bool operator<=(T, T); 7574 // bool operator>=(T, T); 7575 // bool operator==(T, T); 7576 // bool operator!=(T, T); 7577 void addRelationalPointerOrEnumeralOverloads() { 7578 // C++ [over.match.oper]p3: 7579 // [...]the built-in candidates include all of the candidate operator 7580 // functions defined in 13.6 that, compared to the given operator, [...] 7581 // do not have the same parameter-type-list as any non-template non-member 7582 // candidate. 7583 // 7584 // Note that in practice, this only affects enumeration types because there 7585 // aren't any built-in candidates of record type, and a user-defined operator 7586 // must have an operand of record or enumeration type. Also, the only other 7587 // overloaded operator with enumeration arguments, operator=, 7588 // cannot be overloaded for enumeration types, so this is the only place 7589 // where we must suppress candidates like this. 7590 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7591 UserDefinedBinaryOperators; 7592 7593 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7594 if (CandidateTypes[ArgIdx].enumeration_begin() != 7595 CandidateTypes[ArgIdx].enumeration_end()) { 7596 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7597 CEnd = CandidateSet.end(); 7598 C != CEnd; ++C) { 7599 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7600 continue; 7601 7602 if (C->Function->isFunctionTemplateSpecialization()) 7603 continue; 7604 7605 QualType FirstParamType = 7606 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7607 QualType SecondParamType = 7608 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7609 7610 // Skip if either parameter isn't of enumeral type. 7611 if (!FirstParamType->isEnumeralType() || 7612 !SecondParamType->isEnumeralType()) 7613 continue; 7614 7615 // Add this operator to the set of known user-defined operators. 7616 UserDefinedBinaryOperators.insert( 7617 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7618 S.Context.getCanonicalType(SecondParamType))); 7619 } 7620 } 7621 } 7622 7623 /// Set of (canonical) types that we've already handled. 7624 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7625 7626 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7627 for (BuiltinCandidateTypeSet::iterator 7628 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7629 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7630 Ptr != PtrEnd; ++Ptr) { 7631 // Don't add the same builtin candidate twice. 7632 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7633 continue; 7634 7635 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7636 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7637 } 7638 for (BuiltinCandidateTypeSet::iterator 7639 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7640 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7641 Enum != EnumEnd; ++Enum) { 7642 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7643 7644 // Don't add the same builtin candidate twice, or if a user defined 7645 // candidate exists. 7646 if (!AddedTypes.insert(CanonType).second || 7647 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7648 CanonType))) 7649 continue; 7650 7651 QualType ParamTypes[2] = { *Enum, *Enum }; 7652 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7653 } 7654 7655 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7656 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7657 if (AddedTypes.insert(NullPtrTy).second && 7658 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7659 NullPtrTy))) { 7660 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7661 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7662 CandidateSet); 7663 } 7664 } 7665 } 7666 } 7667 7668 // C++ [over.built]p13: 7669 // 7670 // For every cv-qualified or cv-unqualified object type T 7671 // there exist candidate operator functions of the form 7672 // 7673 // T* operator+(T*, ptrdiff_t); 7674 // T& operator[](T*, ptrdiff_t); [BELOW] 7675 // T* operator-(T*, ptrdiff_t); 7676 // T* operator+(ptrdiff_t, T*); 7677 // T& operator[](ptrdiff_t, T*); [BELOW] 7678 // 7679 // C++ [over.built]p14: 7680 // 7681 // For every T, where T is a pointer to object type, there 7682 // exist candidate operator functions of the form 7683 // 7684 // ptrdiff_t operator-(T, T); 7685 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7686 /// Set of (canonical) types that we've already handled. 7687 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7688 7689 for (int Arg = 0; Arg < 2; ++Arg) { 7690 QualType AsymmetricParamTypes[2] = { 7691 S.Context.getPointerDiffType(), 7692 S.Context.getPointerDiffType(), 7693 }; 7694 for (BuiltinCandidateTypeSet::iterator 7695 Ptr = CandidateTypes[Arg].pointer_begin(), 7696 PtrEnd = CandidateTypes[Arg].pointer_end(); 7697 Ptr != PtrEnd; ++Ptr) { 7698 QualType PointeeTy = (*Ptr)->getPointeeType(); 7699 if (!PointeeTy->isObjectType()) 7700 continue; 7701 7702 AsymmetricParamTypes[Arg] = *Ptr; 7703 if (Arg == 0 || Op == OO_Plus) { 7704 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7705 // T* operator+(ptrdiff_t, T*); 7706 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet); 7707 } 7708 if (Op == OO_Minus) { 7709 // ptrdiff_t operator-(T, T); 7710 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7711 continue; 7712 7713 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7714 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7715 Args, CandidateSet); 7716 } 7717 } 7718 } 7719 } 7720 7721 // C++ [over.built]p12: 7722 // 7723 // For every pair of promoted arithmetic types L and R, there 7724 // exist candidate operator functions of the form 7725 // 7726 // LR operator*(L, R); 7727 // LR operator/(L, R); 7728 // LR operator+(L, R); 7729 // LR operator-(L, R); 7730 // bool operator<(L, R); 7731 // bool operator>(L, R); 7732 // bool operator<=(L, R); 7733 // bool operator>=(L, R); 7734 // bool operator==(L, R); 7735 // bool operator!=(L, R); 7736 // 7737 // where LR is the result of the usual arithmetic conversions 7738 // between types L and R. 7739 // 7740 // C++ [over.built]p24: 7741 // 7742 // For every pair of promoted arithmetic types L and R, there exist 7743 // candidate operator functions of the form 7744 // 7745 // LR operator?(bool, L, R); 7746 // 7747 // where LR is the result of the usual arithmetic conversions 7748 // between types L and R. 7749 // Our candidates ignore the first parameter. 7750 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7751 if (!HasArithmeticOrEnumeralCandidateType) 7752 return; 7753 7754 for (unsigned Left = FirstPromotedArithmeticType; 7755 Left < LastPromotedArithmeticType; ++Left) { 7756 for (unsigned Right = FirstPromotedArithmeticType; 7757 Right < LastPromotedArithmeticType; ++Right) { 7758 QualType LandR[2] = { getArithmeticType(Left), 7759 getArithmeticType(Right) }; 7760 QualType Result = 7761 isComparison ? S.Context.BoolTy 7762 : getUsualArithmeticConversions(Left, Right); 7763 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7764 } 7765 } 7766 7767 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7768 // conditional operator for vector types. 7769 for (BuiltinCandidateTypeSet::iterator 7770 Vec1 = CandidateTypes[0].vector_begin(), 7771 Vec1End = CandidateTypes[0].vector_end(); 7772 Vec1 != Vec1End; ++Vec1) { 7773 for (BuiltinCandidateTypeSet::iterator 7774 Vec2 = CandidateTypes[1].vector_begin(), 7775 Vec2End = CandidateTypes[1].vector_end(); 7776 Vec2 != Vec2End; ++Vec2) { 7777 QualType LandR[2] = { *Vec1, *Vec2 }; 7778 QualType Result = S.Context.BoolTy; 7779 if (!isComparison) { 7780 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7781 Result = *Vec1; 7782 else 7783 Result = *Vec2; 7784 } 7785 7786 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7787 } 7788 } 7789 } 7790 7791 // C++ [over.built]p17: 7792 // 7793 // For every pair of promoted integral types L and R, there 7794 // exist candidate operator functions of the form 7795 // 7796 // LR operator%(L, R); 7797 // LR operator&(L, R); 7798 // LR operator^(L, R); 7799 // LR operator|(L, R); 7800 // L operator<<(L, R); 7801 // L operator>>(L, R); 7802 // 7803 // where LR is the result of the usual arithmetic conversions 7804 // between types L and R. 7805 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7806 if (!HasArithmeticOrEnumeralCandidateType) 7807 return; 7808 7809 for (unsigned Left = FirstPromotedIntegralType; 7810 Left < LastPromotedIntegralType; ++Left) { 7811 for (unsigned Right = FirstPromotedIntegralType; 7812 Right < LastPromotedIntegralType; ++Right) { 7813 QualType LandR[2] = { getArithmeticType(Left), 7814 getArithmeticType(Right) }; 7815 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7816 ? LandR[0] 7817 : getUsualArithmeticConversions(Left, Right); 7818 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7819 } 7820 } 7821 } 7822 7823 // C++ [over.built]p20: 7824 // 7825 // For every pair (T, VQ), where T is an enumeration or 7826 // pointer to member type and VQ is either volatile or 7827 // empty, there exist candidate operator functions of the form 7828 // 7829 // VQ T& operator=(VQ T&, T); 7830 void addAssignmentMemberPointerOrEnumeralOverloads() { 7831 /// Set of (canonical) types that we've already handled. 7832 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7833 7834 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7835 for (BuiltinCandidateTypeSet::iterator 7836 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7837 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7838 Enum != EnumEnd; ++Enum) { 7839 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 7840 continue; 7841 7842 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7843 } 7844 7845 for (BuiltinCandidateTypeSet::iterator 7846 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7847 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7848 MemPtr != MemPtrEnd; ++MemPtr) { 7849 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7850 continue; 7851 7852 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7853 } 7854 } 7855 } 7856 7857 // C++ [over.built]p19: 7858 // 7859 // For every pair (T, VQ), where T is any type and VQ is either 7860 // volatile or empty, there exist candidate operator functions 7861 // of the form 7862 // 7863 // T*VQ& operator=(T*VQ&, T*); 7864 // 7865 // C++ [over.built]p21: 7866 // 7867 // For every pair (T, VQ), where T is a cv-qualified or 7868 // cv-unqualified object type and VQ is either volatile or 7869 // empty, there exist candidate operator functions of the form 7870 // 7871 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7872 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7873 void addAssignmentPointerOverloads(bool isEqualOp) { 7874 /// Set of (canonical) types that we've already handled. 7875 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7876 7877 for (BuiltinCandidateTypeSet::iterator 7878 Ptr = CandidateTypes[0].pointer_begin(), 7879 PtrEnd = CandidateTypes[0].pointer_end(); 7880 Ptr != PtrEnd; ++Ptr) { 7881 // If this is operator=, keep track of the builtin candidates we added. 7882 if (isEqualOp) 7883 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7884 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7885 continue; 7886 7887 // non-volatile version 7888 QualType ParamTypes[2] = { 7889 S.Context.getLValueReferenceType(*Ptr), 7890 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7891 }; 7892 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7893 /*IsAssigmentOperator=*/ isEqualOp); 7894 7895 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7896 VisibleTypeConversionsQuals.hasVolatile(); 7897 if (NeedVolatile) { 7898 // volatile version 7899 ParamTypes[0] = 7900 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7901 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7902 /*IsAssigmentOperator=*/isEqualOp); 7903 } 7904 7905 if (!(*Ptr).isRestrictQualified() && 7906 VisibleTypeConversionsQuals.hasRestrict()) { 7907 // restrict version 7908 ParamTypes[0] 7909 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7910 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7911 /*IsAssigmentOperator=*/isEqualOp); 7912 7913 if (NeedVolatile) { 7914 // volatile restrict version 7915 ParamTypes[0] 7916 = S.Context.getLValueReferenceType( 7917 S.Context.getCVRQualifiedType(*Ptr, 7918 (Qualifiers::Volatile | 7919 Qualifiers::Restrict))); 7920 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7921 /*IsAssigmentOperator=*/isEqualOp); 7922 } 7923 } 7924 } 7925 7926 if (isEqualOp) { 7927 for (BuiltinCandidateTypeSet::iterator 7928 Ptr = CandidateTypes[1].pointer_begin(), 7929 PtrEnd = CandidateTypes[1].pointer_end(); 7930 Ptr != PtrEnd; ++Ptr) { 7931 // Make sure we don't add the same candidate twice. 7932 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7933 continue; 7934 7935 QualType ParamTypes[2] = { 7936 S.Context.getLValueReferenceType(*Ptr), 7937 *Ptr, 7938 }; 7939 7940 // non-volatile version 7941 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7942 /*IsAssigmentOperator=*/true); 7943 7944 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7945 VisibleTypeConversionsQuals.hasVolatile(); 7946 if (NeedVolatile) { 7947 // volatile version 7948 ParamTypes[0] = 7949 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7950 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7951 /*IsAssigmentOperator=*/true); 7952 } 7953 7954 if (!(*Ptr).isRestrictQualified() && 7955 VisibleTypeConversionsQuals.hasRestrict()) { 7956 // restrict version 7957 ParamTypes[0] 7958 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7959 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7960 /*IsAssigmentOperator=*/true); 7961 7962 if (NeedVolatile) { 7963 // volatile restrict version 7964 ParamTypes[0] 7965 = S.Context.getLValueReferenceType( 7966 S.Context.getCVRQualifiedType(*Ptr, 7967 (Qualifiers::Volatile | 7968 Qualifiers::Restrict))); 7969 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7970 /*IsAssigmentOperator=*/true); 7971 } 7972 } 7973 } 7974 } 7975 } 7976 7977 // C++ [over.built]p18: 7978 // 7979 // For every triple (L, VQ, R), where L is an arithmetic type, 7980 // VQ is either volatile or empty, and R is a promoted 7981 // arithmetic type, there exist candidate operator functions of 7982 // the form 7983 // 7984 // VQ L& operator=(VQ L&, R); 7985 // VQ L& operator*=(VQ L&, R); 7986 // VQ L& operator/=(VQ L&, R); 7987 // VQ L& operator+=(VQ L&, R); 7988 // VQ L& operator-=(VQ L&, R); 7989 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7990 if (!HasArithmeticOrEnumeralCandidateType) 7991 return; 7992 7993 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7994 for (unsigned Right = FirstPromotedArithmeticType; 7995 Right < LastPromotedArithmeticType; ++Right) { 7996 QualType ParamTypes[2]; 7997 ParamTypes[1] = getArithmeticType(Right); 7998 7999 // Add this built-in operator as a candidate (VQ is empty). 8000 ParamTypes[0] = 8001 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8002 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8003 /*IsAssigmentOperator=*/isEqualOp); 8004 8005 // Add this built-in operator as a candidate (VQ is 'volatile'). 8006 if (VisibleTypeConversionsQuals.hasVolatile()) { 8007 ParamTypes[0] = 8008 S.Context.getVolatileType(getArithmeticType(Left)); 8009 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8010 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8011 /*IsAssigmentOperator=*/isEqualOp); 8012 } 8013 } 8014 } 8015 8016 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8017 for (BuiltinCandidateTypeSet::iterator 8018 Vec1 = CandidateTypes[0].vector_begin(), 8019 Vec1End = CandidateTypes[0].vector_end(); 8020 Vec1 != Vec1End; ++Vec1) { 8021 for (BuiltinCandidateTypeSet::iterator 8022 Vec2 = CandidateTypes[1].vector_begin(), 8023 Vec2End = CandidateTypes[1].vector_end(); 8024 Vec2 != Vec2End; ++Vec2) { 8025 QualType ParamTypes[2]; 8026 ParamTypes[1] = *Vec2; 8027 // Add this built-in operator as a candidate (VQ is empty). 8028 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8029 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8030 /*IsAssigmentOperator=*/isEqualOp); 8031 8032 // Add this built-in operator as a candidate (VQ is 'volatile'). 8033 if (VisibleTypeConversionsQuals.hasVolatile()) { 8034 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8035 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8036 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8037 /*IsAssigmentOperator=*/isEqualOp); 8038 } 8039 } 8040 } 8041 } 8042 8043 // C++ [over.built]p22: 8044 // 8045 // For every triple (L, VQ, R), where L is an integral type, VQ 8046 // is either volatile or empty, and R is a promoted integral 8047 // type, there exist candidate operator functions of the form 8048 // 8049 // VQ L& operator%=(VQ L&, R); 8050 // VQ L& operator<<=(VQ L&, R); 8051 // VQ L& operator>>=(VQ L&, R); 8052 // VQ L& operator&=(VQ L&, R); 8053 // VQ L& operator^=(VQ L&, R); 8054 // VQ L& operator|=(VQ L&, R); 8055 void addAssignmentIntegralOverloads() { 8056 if (!HasArithmeticOrEnumeralCandidateType) 8057 return; 8058 8059 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8060 for (unsigned Right = FirstPromotedIntegralType; 8061 Right < LastPromotedIntegralType; ++Right) { 8062 QualType ParamTypes[2]; 8063 ParamTypes[1] = getArithmeticType(Right); 8064 8065 // Add this built-in operator as a candidate (VQ is empty). 8066 ParamTypes[0] = 8067 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8068 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8069 if (VisibleTypeConversionsQuals.hasVolatile()) { 8070 // Add this built-in operator as a candidate (VQ is 'volatile'). 8071 ParamTypes[0] = getArithmeticType(Left); 8072 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8073 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8074 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8075 } 8076 } 8077 } 8078 } 8079 8080 // C++ [over.operator]p23: 8081 // 8082 // There also exist candidate operator functions of the form 8083 // 8084 // bool operator!(bool); 8085 // bool operator&&(bool, bool); 8086 // bool operator||(bool, bool); 8087 void addExclaimOverload() { 8088 QualType ParamTy = S.Context.BoolTy; 8089 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 8090 /*IsAssignmentOperator=*/false, 8091 /*NumContextualBoolArguments=*/1); 8092 } 8093 void addAmpAmpOrPipePipeOverload() { 8094 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8095 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 8096 /*IsAssignmentOperator=*/false, 8097 /*NumContextualBoolArguments=*/2); 8098 } 8099 8100 // C++ [over.built]p13: 8101 // 8102 // For every cv-qualified or cv-unqualified object type T there 8103 // exist candidate operator functions of the form 8104 // 8105 // T* operator+(T*, ptrdiff_t); [ABOVE] 8106 // T& operator[](T*, ptrdiff_t); 8107 // T* operator-(T*, ptrdiff_t); [ABOVE] 8108 // T* operator+(ptrdiff_t, T*); [ABOVE] 8109 // T& operator[](ptrdiff_t, T*); 8110 void addSubscriptOverloads() { 8111 for (BuiltinCandidateTypeSet::iterator 8112 Ptr = CandidateTypes[0].pointer_begin(), 8113 PtrEnd = CandidateTypes[0].pointer_end(); 8114 Ptr != PtrEnd; ++Ptr) { 8115 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8116 QualType PointeeType = (*Ptr)->getPointeeType(); 8117 if (!PointeeType->isObjectType()) 8118 continue; 8119 8120 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8121 8122 // T& operator[](T*, ptrdiff_t) 8123 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8124 } 8125 8126 for (BuiltinCandidateTypeSet::iterator 8127 Ptr = CandidateTypes[1].pointer_begin(), 8128 PtrEnd = CandidateTypes[1].pointer_end(); 8129 Ptr != PtrEnd; ++Ptr) { 8130 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8131 QualType PointeeType = (*Ptr)->getPointeeType(); 8132 if (!PointeeType->isObjectType()) 8133 continue; 8134 8135 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8136 8137 // T& operator[](ptrdiff_t, T*) 8138 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8139 } 8140 } 8141 8142 // C++ [over.built]p11: 8143 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8144 // C1 is the same type as C2 or is a derived class of C2, T is an object 8145 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8146 // there exist candidate operator functions of the form 8147 // 8148 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8149 // 8150 // where CV12 is the union of CV1 and CV2. 8151 void addArrowStarOverloads() { 8152 for (BuiltinCandidateTypeSet::iterator 8153 Ptr = CandidateTypes[0].pointer_begin(), 8154 PtrEnd = CandidateTypes[0].pointer_end(); 8155 Ptr != PtrEnd; ++Ptr) { 8156 QualType C1Ty = (*Ptr); 8157 QualType C1; 8158 QualifierCollector Q1; 8159 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8160 if (!isa<RecordType>(C1)) 8161 continue; 8162 // heuristic to reduce number of builtin candidates in the set. 8163 // Add volatile/restrict version only if there are conversions to a 8164 // volatile/restrict type. 8165 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8166 continue; 8167 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8168 continue; 8169 for (BuiltinCandidateTypeSet::iterator 8170 MemPtr = CandidateTypes[1].member_pointer_begin(), 8171 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8172 MemPtr != MemPtrEnd; ++MemPtr) { 8173 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8174 QualType C2 = QualType(mptr->getClass(), 0); 8175 C2 = C2.getUnqualifiedType(); 8176 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8177 break; 8178 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8179 // build CV12 T& 8180 QualType T = mptr->getPointeeType(); 8181 if (!VisibleTypeConversionsQuals.hasVolatile() && 8182 T.isVolatileQualified()) 8183 continue; 8184 if (!VisibleTypeConversionsQuals.hasRestrict() && 8185 T.isRestrictQualified()) 8186 continue; 8187 T = Q1.apply(S.Context, T); 8188 QualType ResultTy = S.Context.getLValueReferenceType(T); 8189 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8190 } 8191 } 8192 } 8193 8194 // Note that we don't consider the first argument, since it has been 8195 // contextually converted to bool long ago. The candidates below are 8196 // therefore added as binary. 8197 // 8198 // C++ [over.built]p25: 8199 // For every type T, where T is a pointer, pointer-to-member, or scoped 8200 // enumeration type, there exist candidate operator functions of the form 8201 // 8202 // T operator?(bool, T, T); 8203 // 8204 void addConditionalOperatorOverloads() { 8205 /// Set of (canonical) types that we've already handled. 8206 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8207 8208 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8209 for (BuiltinCandidateTypeSet::iterator 8210 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8211 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8212 Ptr != PtrEnd; ++Ptr) { 8213 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8214 continue; 8215 8216 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8217 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 8218 } 8219 8220 for (BuiltinCandidateTypeSet::iterator 8221 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8222 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8223 MemPtr != MemPtrEnd; ++MemPtr) { 8224 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8225 continue; 8226 8227 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8228 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 8229 } 8230 8231 if (S.getLangOpts().CPlusPlus11) { 8232 for (BuiltinCandidateTypeSet::iterator 8233 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8234 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8235 Enum != EnumEnd; ++Enum) { 8236 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8237 continue; 8238 8239 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8240 continue; 8241 8242 QualType ParamTypes[2] = { *Enum, *Enum }; 8243 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 8244 } 8245 } 8246 } 8247 } 8248 }; 8249 8250 } // end anonymous namespace 8251 8252 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8253 /// operator overloads to the candidate set (C++ [over.built]), based 8254 /// on the operator @p Op and the arguments given. For example, if the 8255 /// operator is a binary '+', this routine might add "int 8256 /// operator+(int, int)" to cover integer addition. 8257 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8258 SourceLocation OpLoc, 8259 ArrayRef<Expr *> Args, 8260 OverloadCandidateSet &CandidateSet) { 8261 // Find all of the types that the arguments can convert to, but only 8262 // if the operator we're looking at has built-in operator candidates 8263 // that make use of these types. Also record whether we encounter non-record 8264 // candidate types or either arithmetic or enumeral candidate types. 8265 Qualifiers VisibleTypeConversionsQuals; 8266 VisibleTypeConversionsQuals.addConst(); 8267 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8268 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8269 8270 bool HasNonRecordCandidateType = false; 8271 bool HasArithmeticOrEnumeralCandidateType = false; 8272 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8273 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8274 CandidateTypes.emplace_back(*this); 8275 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8276 OpLoc, 8277 true, 8278 (Op == OO_Exclaim || 8279 Op == OO_AmpAmp || 8280 Op == OO_PipePipe), 8281 VisibleTypeConversionsQuals); 8282 HasNonRecordCandidateType = HasNonRecordCandidateType || 8283 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8284 HasArithmeticOrEnumeralCandidateType = 8285 HasArithmeticOrEnumeralCandidateType || 8286 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8287 } 8288 8289 // Exit early when no non-record types have been added to the candidate set 8290 // for any of the arguments to the operator. 8291 // 8292 // We can't exit early for !, ||, or &&, since there we have always have 8293 // 'bool' overloads. 8294 if (!HasNonRecordCandidateType && 8295 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8296 return; 8297 8298 // Setup an object to manage the common state for building overloads. 8299 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8300 VisibleTypeConversionsQuals, 8301 HasArithmeticOrEnumeralCandidateType, 8302 CandidateTypes, CandidateSet); 8303 8304 // Dispatch over the operation to add in only those overloads which apply. 8305 switch (Op) { 8306 case OO_None: 8307 case NUM_OVERLOADED_OPERATORS: 8308 llvm_unreachable("Expected an overloaded operator"); 8309 8310 case OO_New: 8311 case OO_Delete: 8312 case OO_Array_New: 8313 case OO_Array_Delete: 8314 case OO_Call: 8315 llvm_unreachable( 8316 "Special operators don't use AddBuiltinOperatorCandidates"); 8317 8318 case OO_Comma: 8319 case OO_Arrow: 8320 case OO_Coawait: 8321 // C++ [over.match.oper]p3: 8322 // -- For the operator ',', the unary operator '&', the 8323 // operator '->', or the operator 'co_await', the 8324 // built-in candidates set is empty. 8325 break; 8326 8327 case OO_Plus: // '+' is either unary or binary 8328 if (Args.size() == 1) 8329 OpBuilder.addUnaryPlusPointerOverloads(); 8330 // Fall through. 8331 8332 case OO_Minus: // '-' is either unary or binary 8333 if (Args.size() == 1) { 8334 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8335 } else { 8336 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8337 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8338 } 8339 break; 8340 8341 case OO_Star: // '*' is either unary or binary 8342 if (Args.size() == 1) 8343 OpBuilder.addUnaryStarPointerOverloads(); 8344 else 8345 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8346 break; 8347 8348 case OO_Slash: 8349 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8350 break; 8351 8352 case OO_PlusPlus: 8353 case OO_MinusMinus: 8354 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8355 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8356 break; 8357 8358 case OO_EqualEqual: 8359 case OO_ExclaimEqual: 8360 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 8361 // Fall through. 8362 8363 case OO_Less: 8364 case OO_Greater: 8365 case OO_LessEqual: 8366 case OO_GreaterEqual: 8367 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8368 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8369 break; 8370 8371 case OO_Percent: 8372 case OO_Caret: 8373 case OO_Pipe: 8374 case OO_LessLess: 8375 case OO_GreaterGreater: 8376 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8377 break; 8378 8379 case OO_Amp: // '&' is either unary or binary 8380 if (Args.size() == 1) 8381 // C++ [over.match.oper]p3: 8382 // -- For the operator ',', the unary operator '&', or the 8383 // operator '->', the built-in candidates set is empty. 8384 break; 8385 8386 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8387 break; 8388 8389 case OO_Tilde: 8390 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8391 break; 8392 8393 case OO_Equal: 8394 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8395 // Fall through. 8396 8397 case OO_PlusEqual: 8398 case OO_MinusEqual: 8399 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8400 // Fall through. 8401 8402 case OO_StarEqual: 8403 case OO_SlashEqual: 8404 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8405 break; 8406 8407 case OO_PercentEqual: 8408 case OO_LessLessEqual: 8409 case OO_GreaterGreaterEqual: 8410 case OO_AmpEqual: 8411 case OO_CaretEqual: 8412 case OO_PipeEqual: 8413 OpBuilder.addAssignmentIntegralOverloads(); 8414 break; 8415 8416 case OO_Exclaim: 8417 OpBuilder.addExclaimOverload(); 8418 break; 8419 8420 case OO_AmpAmp: 8421 case OO_PipePipe: 8422 OpBuilder.addAmpAmpOrPipePipeOverload(); 8423 break; 8424 8425 case OO_Subscript: 8426 OpBuilder.addSubscriptOverloads(); 8427 break; 8428 8429 case OO_ArrowStar: 8430 OpBuilder.addArrowStarOverloads(); 8431 break; 8432 8433 case OO_Conditional: 8434 OpBuilder.addConditionalOperatorOverloads(); 8435 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8436 break; 8437 } 8438 } 8439 8440 /// \brief Add function candidates found via argument-dependent lookup 8441 /// to the set of overloading candidates. 8442 /// 8443 /// This routine performs argument-dependent name lookup based on the 8444 /// given function name (which may also be an operator name) and adds 8445 /// all of the overload candidates found by ADL to the overload 8446 /// candidate set (C++ [basic.lookup.argdep]). 8447 void 8448 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8449 SourceLocation Loc, 8450 ArrayRef<Expr *> Args, 8451 TemplateArgumentListInfo *ExplicitTemplateArgs, 8452 OverloadCandidateSet& CandidateSet, 8453 bool PartialOverloading) { 8454 ADLResult Fns; 8455 8456 // FIXME: This approach for uniquing ADL results (and removing 8457 // redundant candidates from the set) relies on pointer-equality, 8458 // which means we need to key off the canonical decl. However, 8459 // always going back to the canonical decl might not get us the 8460 // right set of default arguments. What default arguments are 8461 // we supposed to consider on ADL candidates, anyway? 8462 8463 // FIXME: Pass in the explicit template arguments? 8464 ArgumentDependentLookup(Name, Loc, Args, Fns); 8465 8466 // Erase all of the candidates we already knew about. 8467 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8468 CandEnd = CandidateSet.end(); 8469 Cand != CandEnd; ++Cand) 8470 if (Cand->Function) { 8471 Fns.erase(Cand->Function); 8472 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8473 Fns.erase(FunTmpl); 8474 } 8475 8476 // For each of the ADL candidates we found, add it to the overload 8477 // set. 8478 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8479 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8480 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8481 if (ExplicitTemplateArgs) 8482 continue; 8483 8484 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8485 PartialOverloading); 8486 } else 8487 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8488 FoundDecl, ExplicitTemplateArgs, 8489 Args, CandidateSet, PartialOverloading); 8490 } 8491 } 8492 8493 namespace { 8494 enum class Comparison { Equal, Better, Worse }; 8495 } 8496 8497 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 8498 /// overload resolution. 8499 /// 8500 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 8501 /// Cand1's first N enable_if attributes have precisely the same conditions as 8502 /// Cand2's first N enable_if attributes (where N = the number of enable_if 8503 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 8504 /// 8505 /// Note that you can have a pair of candidates such that Cand1's enable_if 8506 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 8507 /// worse than Cand1's. 8508 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 8509 const FunctionDecl *Cand2) { 8510 // Common case: One (or both) decls don't have enable_if attrs. 8511 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 8512 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 8513 if (!Cand1Attr || !Cand2Attr) { 8514 if (Cand1Attr == Cand2Attr) 8515 return Comparison::Equal; 8516 return Cand1Attr ? Comparison::Better : Comparison::Worse; 8517 } 8518 8519 // FIXME: The next several lines are just 8520 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8521 // instead of reverse order which is how they're stored in the AST. 8522 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1); 8523 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2); 8524 8525 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 8526 // has fewer enable_if attributes than Cand2. 8527 if (Cand1Attrs.size() < Cand2Attrs.size()) 8528 return Comparison::Worse; 8529 8530 auto Cand1I = Cand1Attrs.begin(); 8531 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8532 for (auto &Cand2A : Cand2Attrs) { 8533 Cand1ID.clear(); 8534 Cand2ID.clear(); 8535 8536 auto &Cand1A = *Cand1I++; 8537 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true); 8538 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true); 8539 if (Cand1ID != Cand2ID) 8540 return Comparison::Worse; 8541 } 8542 8543 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better; 8544 } 8545 8546 /// isBetterOverloadCandidate - Determines whether the first overload 8547 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8548 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, 8549 const OverloadCandidate &Cand2, 8550 SourceLocation Loc, 8551 bool UserDefinedConversion) { 8552 // Define viable functions to be better candidates than non-viable 8553 // functions. 8554 if (!Cand2.Viable) 8555 return Cand1.Viable; 8556 else if (!Cand1.Viable) 8557 return false; 8558 8559 // C++ [over.match.best]p1: 8560 // 8561 // -- if F is a static member function, ICS1(F) is defined such 8562 // that ICS1(F) is neither better nor worse than ICS1(G) for 8563 // any function G, and, symmetrically, ICS1(G) is neither 8564 // better nor worse than ICS1(F). 8565 unsigned StartArg = 0; 8566 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8567 StartArg = 1; 8568 8569 // C++ [over.match.best]p1: 8570 // A viable function F1 is defined to be a better function than another 8571 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8572 // conversion sequence than ICSi(F2), and then... 8573 unsigned NumArgs = Cand1.NumConversions; 8574 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8575 bool HasBetterConversion = false; 8576 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8577 switch (CompareImplicitConversionSequences(S, Loc, 8578 Cand1.Conversions[ArgIdx], 8579 Cand2.Conversions[ArgIdx])) { 8580 case ImplicitConversionSequence::Better: 8581 // Cand1 has a better conversion sequence. 8582 HasBetterConversion = true; 8583 break; 8584 8585 case ImplicitConversionSequence::Worse: 8586 // Cand1 can't be better than Cand2. 8587 return false; 8588 8589 case ImplicitConversionSequence::Indistinguishable: 8590 // Do nothing. 8591 break; 8592 } 8593 } 8594 8595 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8596 // ICSj(F2), or, if not that, 8597 if (HasBetterConversion) 8598 return true; 8599 8600 // -- the context is an initialization by user-defined conversion 8601 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8602 // from the return type of F1 to the destination type (i.e., 8603 // the type of the entity being initialized) is a better 8604 // conversion sequence than the standard conversion sequence 8605 // from the return type of F2 to the destination type. 8606 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8607 isa<CXXConversionDecl>(Cand1.Function) && 8608 isa<CXXConversionDecl>(Cand2.Function)) { 8609 // First check whether we prefer one of the conversion functions over the 8610 // other. This only distinguishes the results in non-standard, extension 8611 // cases such as the conversion from a lambda closure type to a function 8612 // pointer or block. 8613 ImplicitConversionSequence::CompareKind Result = 8614 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8615 if (Result == ImplicitConversionSequence::Indistinguishable) 8616 Result = CompareStandardConversionSequences(S, Loc, 8617 Cand1.FinalConversion, 8618 Cand2.FinalConversion); 8619 8620 if (Result != ImplicitConversionSequence::Indistinguishable) 8621 return Result == ImplicitConversionSequence::Better; 8622 8623 // FIXME: Compare kind of reference binding if conversion functions 8624 // convert to a reference type used in direct reference binding, per 8625 // C++14 [over.match.best]p1 section 2 bullet 3. 8626 } 8627 8628 // -- F1 is a non-template function and F2 is a function template 8629 // specialization, or, if not that, 8630 bool Cand1IsSpecialization = Cand1.Function && 8631 Cand1.Function->getPrimaryTemplate(); 8632 bool Cand2IsSpecialization = Cand2.Function && 8633 Cand2.Function->getPrimaryTemplate(); 8634 if (Cand1IsSpecialization != Cand2IsSpecialization) 8635 return Cand2IsSpecialization; 8636 8637 // -- F1 and F2 are function template specializations, and the function 8638 // template for F1 is more specialized than the template for F2 8639 // according to the partial ordering rules described in 14.5.5.2, or, 8640 // if not that, 8641 if (Cand1IsSpecialization && Cand2IsSpecialization) { 8642 if (FunctionTemplateDecl *BetterTemplate 8643 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8644 Cand2.Function->getPrimaryTemplate(), 8645 Loc, 8646 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8647 : TPOC_Call, 8648 Cand1.ExplicitCallArguments, 8649 Cand2.ExplicitCallArguments)) 8650 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8651 } 8652 8653 // FIXME: Work around a defect in the C++17 inheriting constructor wording. 8654 // A derived-class constructor beats an (inherited) base class constructor. 8655 bool Cand1IsInherited = 8656 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 8657 bool Cand2IsInherited = 8658 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 8659 if (Cand1IsInherited != Cand2IsInherited) 8660 return Cand2IsInherited; 8661 else if (Cand1IsInherited) { 8662 assert(Cand2IsInherited); 8663 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 8664 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 8665 if (Cand1Class->isDerivedFrom(Cand2Class)) 8666 return true; 8667 if (Cand2Class->isDerivedFrom(Cand1Class)) 8668 return false; 8669 // Inherited from sibling base classes: still ambiguous. 8670 } 8671 8672 // Check for enable_if value-based overload resolution. 8673 if (Cand1.Function && Cand2.Function) { 8674 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 8675 if (Cmp != Comparison::Equal) 8676 return Cmp == Comparison::Better; 8677 } 8678 8679 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 8680 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8681 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 8682 S.IdentifyCUDAPreference(Caller, Cand2.Function); 8683 } 8684 8685 bool HasPS1 = Cand1.Function != nullptr && 8686 functionHasPassObjectSizeParams(Cand1.Function); 8687 bool HasPS2 = Cand2.Function != nullptr && 8688 functionHasPassObjectSizeParams(Cand2.Function); 8689 return HasPS1 != HasPS2 && HasPS1; 8690 } 8691 8692 /// Determine whether two declarations are "equivalent" for the purposes of 8693 /// name lookup and overload resolution. This applies when the same internal/no 8694 /// linkage entity is defined by two modules (probably by textually including 8695 /// the same header). In such a case, we don't consider the declarations to 8696 /// declare the same entity, but we also don't want lookups with both 8697 /// declarations visible to be ambiguous in some cases (this happens when using 8698 /// a modularized libstdc++). 8699 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 8700 const NamedDecl *B) { 8701 auto *VA = dyn_cast_or_null<ValueDecl>(A); 8702 auto *VB = dyn_cast_or_null<ValueDecl>(B); 8703 if (!VA || !VB) 8704 return false; 8705 8706 // The declarations must be declaring the same name as an internal linkage 8707 // entity in different modules. 8708 if (!VA->getDeclContext()->getRedeclContext()->Equals( 8709 VB->getDeclContext()->getRedeclContext()) || 8710 getOwningModule(const_cast<ValueDecl *>(VA)) == 8711 getOwningModule(const_cast<ValueDecl *>(VB)) || 8712 VA->isExternallyVisible() || VB->isExternallyVisible()) 8713 return false; 8714 8715 // Check that the declarations appear to be equivalent. 8716 // 8717 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 8718 // For constants and functions, we should check the initializer or body is 8719 // the same. For non-constant variables, we shouldn't allow it at all. 8720 if (Context.hasSameType(VA->getType(), VB->getType())) 8721 return true; 8722 8723 // Enum constants within unnamed enumerations will have different types, but 8724 // may still be similar enough to be interchangeable for our purposes. 8725 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 8726 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 8727 // Only handle anonymous enums. If the enumerations were named and 8728 // equivalent, they would have been merged to the same type. 8729 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 8730 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 8731 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 8732 !Context.hasSameType(EnumA->getIntegerType(), 8733 EnumB->getIntegerType())) 8734 return false; 8735 // Allow this only if the value is the same for both enumerators. 8736 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 8737 } 8738 } 8739 8740 // Nothing else is sufficiently similar. 8741 return false; 8742 } 8743 8744 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 8745 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 8746 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 8747 8748 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 8749 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 8750 << !M << (M ? M->getFullModuleName() : ""); 8751 8752 for (auto *E : Equiv) { 8753 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 8754 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 8755 << !M << (M ? M->getFullModuleName() : ""); 8756 } 8757 } 8758 8759 /// \brief Computes the best viable function (C++ 13.3.3) 8760 /// within an overload candidate set. 8761 /// 8762 /// \param Loc The location of the function name (or operator symbol) for 8763 /// which overload resolution occurs. 8764 /// 8765 /// \param Best If overload resolution was successful or found a deleted 8766 /// function, \p Best points to the candidate function found. 8767 /// 8768 /// \returns The result of overload resolution. 8769 OverloadingResult 8770 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8771 iterator &Best, 8772 bool UserDefinedConversion) { 8773 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 8774 std::transform(begin(), end(), std::back_inserter(Candidates), 8775 [](OverloadCandidate &Cand) { return &Cand; }); 8776 8777 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA 8778 // but accepted by both clang and NVCC. However during a particular 8779 // compilation mode only one call variant is viable. We need to 8780 // exclude non-viable overload candidates from consideration based 8781 // only on their host/device attributes. Specifically, if one 8782 // candidate call is WrongSide and the other is SameSide, we ignore 8783 // the WrongSide candidate. 8784 if (S.getLangOpts().CUDA) { 8785 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8786 bool ContainsSameSideCandidate = 8787 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 8788 return Cand->Function && 8789 S.IdentifyCUDAPreference(Caller, Cand->Function) == 8790 Sema::CFP_SameSide; 8791 }); 8792 if (ContainsSameSideCandidate) { 8793 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 8794 return Cand->Function && 8795 S.IdentifyCUDAPreference(Caller, Cand->Function) == 8796 Sema::CFP_WrongSide; 8797 }; 8798 Candidates.erase(std::remove_if(Candidates.begin(), Candidates.end(), 8799 IsWrongSideCandidate), 8800 Candidates.end()); 8801 } 8802 } 8803 8804 // Find the best viable function. 8805 Best = end(); 8806 for (auto *Cand : Candidates) 8807 if (Cand->Viable) 8808 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8809 UserDefinedConversion)) 8810 Best = Cand; 8811 8812 // If we didn't find any viable functions, abort. 8813 if (Best == end()) 8814 return OR_No_Viable_Function; 8815 8816 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 8817 8818 // Make sure that this function is better than every other viable 8819 // function. If not, we have an ambiguity. 8820 for (auto *Cand : Candidates) { 8821 if (Cand->Viable && 8822 Cand != Best && 8823 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8824 UserDefinedConversion)) { 8825 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 8826 Cand->Function)) { 8827 EquivalentCands.push_back(Cand->Function); 8828 continue; 8829 } 8830 8831 Best = end(); 8832 return OR_Ambiguous; 8833 } 8834 } 8835 8836 // Best is the best viable function. 8837 if (Best->Function && 8838 (Best->Function->isDeleted() || 8839 S.isFunctionConsideredUnavailable(Best->Function))) 8840 return OR_Deleted; 8841 8842 if (!EquivalentCands.empty()) 8843 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 8844 EquivalentCands); 8845 8846 return OR_Success; 8847 } 8848 8849 namespace { 8850 8851 enum OverloadCandidateKind { 8852 oc_function, 8853 oc_method, 8854 oc_constructor, 8855 oc_function_template, 8856 oc_method_template, 8857 oc_constructor_template, 8858 oc_implicit_default_constructor, 8859 oc_implicit_copy_constructor, 8860 oc_implicit_move_constructor, 8861 oc_implicit_copy_assignment, 8862 oc_implicit_move_assignment, 8863 oc_inherited_constructor, 8864 oc_inherited_constructor_template 8865 }; 8866 8867 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8868 NamedDecl *Found, 8869 FunctionDecl *Fn, 8870 std::string &Description) { 8871 bool isTemplate = false; 8872 8873 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8874 isTemplate = true; 8875 Description = S.getTemplateArgumentBindingsText( 8876 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8877 } 8878 8879 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8880 if (!Ctor->isImplicit()) { 8881 if (isa<ConstructorUsingShadowDecl>(Found)) 8882 return isTemplate ? oc_inherited_constructor_template 8883 : oc_inherited_constructor; 8884 else 8885 return isTemplate ? oc_constructor_template : oc_constructor; 8886 } 8887 8888 if (Ctor->isDefaultConstructor()) 8889 return oc_implicit_default_constructor; 8890 8891 if (Ctor->isMoveConstructor()) 8892 return oc_implicit_move_constructor; 8893 8894 assert(Ctor->isCopyConstructor() && 8895 "unexpected sort of implicit constructor"); 8896 return oc_implicit_copy_constructor; 8897 } 8898 8899 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8900 // This actually gets spelled 'candidate function' for now, but 8901 // it doesn't hurt to split it out. 8902 if (!Meth->isImplicit()) 8903 return isTemplate ? oc_method_template : oc_method; 8904 8905 if (Meth->isMoveAssignmentOperator()) 8906 return oc_implicit_move_assignment; 8907 8908 if (Meth->isCopyAssignmentOperator()) 8909 return oc_implicit_copy_assignment; 8910 8911 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8912 return oc_method; 8913 } 8914 8915 return isTemplate ? oc_function_template : oc_function; 8916 } 8917 8918 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 8919 // FIXME: It'd be nice to only emit a note once per using-decl per overload 8920 // set. 8921 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 8922 S.Diag(FoundDecl->getLocation(), 8923 diag::note_ovl_candidate_inherited_constructor) 8924 << Shadow->getNominatedBaseClass(); 8925 } 8926 8927 } // end anonymous namespace 8928 8929 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 8930 const FunctionDecl *FD) { 8931 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 8932 bool AlwaysTrue; 8933 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 8934 return false; 8935 if (!AlwaysTrue) 8936 return false; 8937 } 8938 return true; 8939 } 8940 8941 /// \brief Returns true if we can take the address of the function. 8942 /// 8943 /// \param Complain - If true, we'll emit a diagnostic 8944 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 8945 /// we in overload resolution? 8946 /// \param Loc - The location of the statement we're complaining about. Ignored 8947 /// if we're not complaining, or if we're in overload resolution. 8948 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 8949 bool Complain, 8950 bool InOverloadResolution, 8951 SourceLocation Loc) { 8952 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 8953 if (Complain) { 8954 if (InOverloadResolution) 8955 S.Diag(FD->getLocStart(), 8956 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 8957 else 8958 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 8959 } 8960 return false; 8961 } 8962 8963 auto I = llvm::find_if( 8964 FD->parameters(), std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>)); 8965 if (I == FD->param_end()) 8966 return true; 8967 8968 if (Complain) { 8969 // Add one to ParamNo because it's user-facing 8970 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 8971 if (InOverloadResolution) 8972 S.Diag(FD->getLocation(), 8973 diag::note_ovl_candidate_has_pass_object_size_params) 8974 << ParamNo; 8975 else 8976 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 8977 << FD << ParamNo; 8978 } 8979 return false; 8980 } 8981 8982 static bool checkAddressOfCandidateIsAvailable(Sema &S, 8983 const FunctionDecl *FD) { 8984 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 8985 /*InOverloadResolution=*/true, 8986 /*Loc=*/SourceLocation()); 8987 } 8988 8989 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 8990 bool Complain, 8991 SourceLocation Loc) { 8992 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 8993 /*InOverloadResolution=*/false, 8994 Loc); 8995 } 8996 8997 // Notes the location of an overload candidate. 8998 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 8999 QualType DestType, bool TakingAddress) { 9000 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9001 return; 9002 9003 std::string FnDesc; 9004 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc); 9005 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9006 << (unsigned) K << FnDesc; 9007 9008 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9009 Diag(Fn->getLocation(), PD); 9010 MaybeEmitInheritedConstructorNote(*this, Found); 9011 } 9012 9013 // Notes the location of all overload candidates designated through 9014 // OverloadedExpr 9015 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9016 bool TakingAddress) { 9017 assert(OverloadedExpr->getType() == Context.OverloadTy); 9018 9019 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9020 OverloadExpr *OvlExpr = Ovl.Expression; 9021 9022 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9023 IEnd = OvlExpr->decls_end(); 9024 I != IEnd; ++I) { 9025 if (FunctionTemplateDecl *FunTmpl = 9026 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9027 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType, 9028 TakingAddress); 9029 } else if (FunctionDecl *Fun 9030 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9031 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress); 9032 } 9033 } 9034 } 9035 9036 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9037 /// "lead" diagnostic; it will be given two arguments, the source and 9038 /// target types of the conversion. 9039 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9040 Sema &S, 9041 SourceLocation CaretLoc, 9042 const PartialDiagnostic &PDiag) const { 9043 S.Diag(CaretLoc, PDiag) 9044 << Ambiguous.getFromType() << Ambiguous.getToType(); 9045 // FIXME: The note limiting machinery is borrowed from 9046 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9047 // refactoring here. 9048 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9049 unsigned CandsShown = 0; 9050 AmbiguousConversionSequence::const_iterator I, E; 9051 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9052 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9053 break; 9054 ++CandsShown; 9055 S.NoteOverloadCandidate(I->first, I->second); 9056 } 9057 if (I != E) 9058 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9059 } 9060 9061 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9062 unsigned I, bool TakingCandidateAddress) { 9063 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9064 assert(Conv.isBad()); 9065 assert(Cand->Function && "for now, candidate must be a function"); 9066 FunctionDecl *Fn = Cand->Function; 9067 9068 // There's a conversion slot for the object argument if this is a 9069 // non-constructor method. Note that 'I' corresponds the 9070 // conversion-slot index. 9071 bool isObjectArgument = false; 9072 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9073 if (I == 0) 9074 isObjectArgument = true; 9075 else 9076 I--; 9077 } 9078 9079 std::string FnDesc; 9080 OverloadCandidateKind FnKind = 9081 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9082 9083 Expr *FromExpr = Conv.Bad.FromExpr; 9084 QualType FromTy = Conv.Bad.getFromType(); 9085 QualType ToTy = Conv.Bad.getToType(); 9086 9087 if (FromTy == S.Context.OverloadTy) { 9088 assert(FromExpr && "overload set argument came from implicit argument?"); 9089 Expr *E = FromExpr->IgnoreParens(); 9090 if (isa<UnaryOperator>(E)) 9091 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9092 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9093 9094 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9095 << (unsigned) FnKind << FnDesc 9096 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9097 << ToTy << Name << I+1; 9098 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9099 return; 9100 } 9101 9102 // Do some hand-waving analysis to see if the non-viability is due 9103 // to a qualifier mismatch. 9104 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9105 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9106 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9107 CToTy = RT->getPointeeType(); 9108 else { 9109 // TODO: detect and diagnose the full richness of const mismatches. 9110 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9111 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9112 CFromTy = FromPT->getPointeeType(); 9113 CToTy = ToPT->getPointeeType(); 9114 } 9115 } 9116 9117 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9118 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9119 Qualifiers FromQs = CFromTy.getQualifiers(); 9120 Qualifiers ToQs = CToTy.getQualifiers(); 9121 9122 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9123 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9124 << (unsigned) FnKind << FnDesc 9125 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9126 << FromTy 9127 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 9128 << (unsigned) isObjectArgument << I+1; 9129 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9130 return; 9131 } 9132 9133 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9134 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9135 << (unsigned) FnKind << FnDesc 9136 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9137 << FromTy 9138 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9139 << (unsigned) isObjectArgument << I+1; 9140 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9141 return; 9142 } 9143 9144 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9145 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9146 << (unsigned) FnKind << FnDesc 9147 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9148 << FromTy 9149 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9150 << (unsigned) isObjectArgument << I+1; 9151 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9152 return; 9153 } 9154 9155 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 9156 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 9157 << (unsigned) FnKind << FnDesc 9158 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9159 << FromTy << FromQs.hasUnaligned() << I+1; 9160 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9161 return; 9162 } 9163 9164 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9165 assert(CVR && "unexpected qualifiers mismatch"); 9166 9167 if (isObjectArgument) { 9168 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9169 << (unsigned) FnKind << FnDesc 9170 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9171 << FromTy << (CVR - 1); 9172 } else { 9173 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9174 << (unsigned) FnKind << FnDesc 9175 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9176 << FromTy << (CVR - 1) << I+1; 9177 } 9178 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9179 return; 9180 } 9181 9182 // Special diagnostic for failure to convert an initializer list, since 9183 // telling the user that it has type void is not useful. 9184 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9185 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9186 << (unsigned) FnKind << FnDesc 9187 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9188 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9189 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9190 return; 9191 } 9192 9193 // Diagnose references or pointers to incomplete types differently, 9194 // since it's far from impossible that the incompleteness triggered 9195 // the failure. 9196 QualType TempFromTy = FromTy.getNonReferenceType(); 9197 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9198 TempFromTy = PTy->getPointeeType(); 9199 if (TempFromTy->isIncompleteType()) { 9200 // Emit the generic diagnostic and, optionally, add the hints to it. 9201 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9202 << (unsigned) FnKind << FnDesc 9203 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9204 << FromTy << ToTy << (unsigned) isObjectArgument << I+1 9205 << (unsigned) (Cand->Fix.Kind); 9206 9207 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9208 return; 9209 } 9210 9211 // Diagnose base -> derived pointer conversions. 9212 unsigned BaseToDerivedConversion = 0; 9213 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9214 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9215 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9216 FromPtrTy->getPointeeType()) && 9217 !FromPtrTy->getPointeeType()->isIncompleteType() && 9218 !ToPtrTy->getPointeeType()->isIncompleteType() && 9219 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9220 FromPtrTy->getPointeeType())) 9221 BaseToDerivedConversion = 1; 9222 } 9223 } else if (const ObjCObjectPointerType *FromPtrTy 9224 = FromTy->getAs<ObjCObjectPointerType>()) { 9225 if (const ObjCObjectPointerType *ToPtrTy 9226 = ToTy->getAs<ObjCObjectPointerType>()) 9227 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9228 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9229 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9230 FromPtrTy->getPointeeType()) && 9231 FromIface->isSuperClassOf(ToIface)) 9232 BaseToDerivedConversion = 2; 9233 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9234 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9235 !FromTy->isIncompleteType() && 9236 !ToRefTy->getPointeeType()->isIncompleteType() && 9237 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9238 BaseToDerivedConversion = 3; 9239 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9240 ToTy.getNonReferenceType().getCanonicalType() == 9241 FromTy.getNonReferenceType().getCanonicalType()) { 9242 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9243 << (unsigned) FnKind << FnDesc 9244 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9245 << (unsigned) isObjectArgument << I + 1; 9246 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9247 return; 9248 } 9249 } 9250 9251 if (BaseToDerivedConversion) { 9252 S.Diag(Fn->getLocation(), 9253 diag::note_ovl_candidate_bad_base_to_derived_conv) 9254 << (unsigned) FnKind << FnDesc 9255 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9256 << (BaseToDerivedConversion - 1) 9257 << FromTy << ToTy << I+1; 9258 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9259 return; 9260 } 9261 9262 if (isa<ObjCObjectPointerType>(CFromTy) && 9263 isa<PointerType>(CToTy)) { 9264 Qualifiers FromQs = CFromTy.getQualifiers(); 9265 Qualifiers ToQs = CToTy.getQualifiers(); 9266 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9267 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9268 << (unsigned) FnKind << FnDesc 9269 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9270 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9271 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9272 return; 9273 } 9274 } 9275 9276 if (TakingCandidateAddress && 9277 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9278 return; 9279 9280 // Emit the generic diagnostic and, optionally, add the hints to it. 9281 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9282 FDiag << (unsigned) FnKind << FnDesc 9283 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9284 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 9285 << (unsigned) (Cand->Fix.Kind); 9286 9287 // If we can fix the conversion, suggest the FixIts. 9288 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9289 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9290 FDiag << *HI; 9291 S.Diag(Fn->getLocation(), FDiag); 9292 9293 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9294 } 9295 9296 /// Additional arity mismatch diagnosis specific to a function overload 9297 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9298 /// over a candidate in any candidate set. 9299 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9300 unsigned NumArgs) { 9301 FunctionDecl *Fn = Cand->Function; 9302 unsigned MinParams = Fn->getMinRequiredArguments(); 9303 9304 // With invalid overloaded operators, it's possible that we think we 9305 // have an arity mismatch when in fact it looks like we have the 9306 // right number of arguments, because only overloaded operators have 9307 // the weird behavior of overloading member and non-member functions. 9308 // Just don't report anything. 9309 if (Fn->isInvalidDecl() && 9310 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9311 return true; 9312 9313 if (NumArgs < MinParams) { 9314 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9315 (Cand->FailureKind == ovl_fail_bad_deduction && 9316 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9317 } else { 9318 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9319 (Cand->FailureKind == ovl_fail_bad_deduction && 9320 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9321 } 9322 9323 return false; 9324 } 9325 9326 /// General arity mismatch diagnosis over a candidate in a candidate set. 9327 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 9328 unsigned NumFormalArgs) { 9329 assert(isa<FunctionDecl>(D) && 9330 "The templated declaration should at least be a function" 9331 " when diagnosing bad template argument deduction due to too many" 9332 " or too few arguments"); 9333 9334 FunctionDecl *Fn = cast<FunctionDecl>(D); 9335 9336 // TODO: treat calls to a missing default constructor as a special case 9337 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9338 unsigned MinParams = Fn->getMinRequiredArguments(); 9339 9340 // at least / at most / exactly 9341 unsigned mode, modeCount; 9342 if (NumFormalArgs < MinParams) { 9343 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9344 FnTy->isTemplateVariadic()) 9345 mode = 0; // "at least" 9346 else 9347 mode = 2; // "exactly" 9348 modeCount = MinParams; 9349 } else { 9350 if (MinParams != FnTy->getNumParams()) 9351 mode = 1; // "at most" 9352 else 9353 mode = 2; // "exactly" 9354 modeCount = FnTy->getNumParams(); 9355 } 9356 9357 std::string Description; 9358 OverloadCandidateKind FnKind = 9359 ClassifyOverloadCandidate(S, Found, Fn, Description); 9360 9361 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9362 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9363 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9364 << mode << Fn->getParamDecl(0) << NumFormalArgs; 9365 else 9366 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9367 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9368 << mode << modeCount << NumFormalArgs; 9369 MaybeEmitInheritedConstructorNote(S, Found); 9370 } 9371 9372 /// Arity mismatch diagnosis specific to a function overload candidate. 9373 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9374 unsigned NumFormalArgs) { 9375 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9376 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 9377 } 9378 9379 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9380 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 9381 return TD; 9382 llvm_unreachable("Unsupported: Getting the described template declaration" 9383 " for bad deduction diagnosis"); 9384 } 9385 9386 /// Diagnose a failed template-argument deduction. 9387 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 9388 DeductionFailureInfo &DeductionFailure, 9389 unsigned NumArgs, 9390 bool TakingCandidateAddress) { 9391 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9392 NamedDecl *ParamD; 9393 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9394 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9395 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9396 switch (DeductionFailure.Result) { 9397 case Sema::TDK_Success: 9398 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9399 9400 case Sema::TDK_Incomplete: { 9401 assert(ParamD && "no parameter found for incomplete deduction result"); 9402 S.Diag(Templated->getLocation(), 9403 diag::note_ovl_candidate_incomplete_deduction) 9404 << ParamD->getDeclName(); 9405 MaybeEmitInheritedConstructorNote(S, Found); 9406 return; 9407 } 9408 9409 case Sema::TDK_Underqualified: { 9410 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9411 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9412 9413 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9414 9415 // Param will have been canonicalized, but it should just be a 9416 // qualified version of ParamD, so move the qualifiers to that. 9417 QualifierCollector Qs; 9418 Qs.strip(Param); 9419 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9420 assert(S.Context.hasSameType(Param, NonCanonParam)); 9421 9422 // Arg has also been canonicalized, but there's nothing we can do 9423 // about that. It also doesn't matter as much, because it won't 9424 // have any template parameters in it (because deduction isn't 9425 // done on dependent types). 9426 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9427 9428 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9429 << ParamD->getDeclName() << Arg << NonCanonParam; 9430 MaybeEmitInheritedConstructorNote(S, Found); 9431 return; 9432 } 9433 9434 case Sema::TDK_Inconsistent: { 9435 assert(ParamD && "no parameter found for inconsistent deduction result"); 9436 int which = 0; 9437 if (isa<TemplateTypeParmDecl>(ParamD)) 9438 which = 0; 9439 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 9440 which = 1; 9441 else { 9442 which = 2; 9443 } 9444 9445 S.Diag(Templated->getLocation(), 9446 diag::note_ovl_candidate_inconsistent_deduction) 9447 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 9448 << *DeductionFailure.getSecondArg(); 9449 MaybeEmitInheritedConstructorNote(S, Found); 9450 return; 9451 } 9452 9453 case Sema::TDK_InvalidExplicitArguments: 9454 assert(ParamD && "no parameter found for invalid explicit arguments"); 9455 if (ParamD->getDeclName()) 9456 S.Diag(Templated->getLocation(), 9457 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9458 << ParamD->getDeclName(); 9459 else { 9460 int index = 0; 9461 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9462 index = TTP->getIndex(); 9463 else if (NonTypeTemplateParmDecl *NTTP 9464 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9465 index = NTTP->getIndex(); 9466 else 9467 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9468 S.Diag(Templated->getLocation(), 9469 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9470 << (index + 1); 9471 } 9472 MaybeEmitInheritedConstructorNote(S, Found); 9473 return; 9474 9475 case Sema::TDK_TooManyArguments: 9476 case Sema::TDK_TooFewArguments: 9477 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 9478 return; 9479 9480 case Sema::TDK_InstantiationDepth: 9481 S.Diag(Templated->getLocation(), 9482 diag::note_ovl_candidate_instantiation_depth); 9483 MaybeEmitInheritedConstructorNote(S, Found); 9484 return; 9485 9486 case Sema::TDK_SubstitutionFailure: { 9487 // Format the template argument list into the argument string. 9488 SmallString<128> TemplateArgString; 9489 if (TemplateArgumentList *Args = 9490 DeductionFailure.getTemplateArgumentList()) { 9491 TemplateArgString = " "; 9492 TemplateArgString += S.getTemplateArgumentBindingsText( 9493 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9494 } 9495 9496 // If this candidate was disabled by enable_if, say so. 9497 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9498 if (PDiag && PDiag->second.getDiagID() == 9499 diag::err_typename_nested_not_found_enable_if) { 9500 // FIXME: Use the source range of the condition, and the fully-qualified 9501 // name of the enable_if template. These are both present in PDiag. 9502 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9503 << "'enable_if'" << TemplateArgString; 9504 return; 9505 } 9506 9507 // Format the SFINAE diagnostic into the argument string. 9508 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9509 // formatted message in another diagnostic. 9510 SmallString<128> SFINAEArgString; 9511 SourceRange R; 9512 if (PDiag) { 9513 SFINAEArgString = ": "; 9514 R = SourceRange(PDiag->first, PDiag->first); 9515 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9516 } 9517 9518 S.Diag(Templated->getLocation(), 9519 diag::note_ovl_candidate_substitution_failure) 9520 << TemplateArgString << SFINAEArgString << R; 9521 MaybeEmitInheritedConstructorNote(S, Found); 9522 return; 9523 } 9524 9525 case Sema::TDK_FailedOverloadResolution: { 9526 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 9527 S.Diag(Templated->getLocation(), 9528 diag::note_ovl_candidate_failed_overload_resolution) 9529 << R.Expression->getName(); 9530 return; 9531 } 9532 9533 case Sema::TDK_DeducedMismatch: { 9534 // Format the template argument list into the argument string. 9535 SmallString<128> TemplateArgString; 9536 if (TemplateArgumentList *Args = 9537 DeductionFailure.getTemplateArgumentList()) { 9538 TemplateArgString = " "; 9539 TemplateArgString += S.getTemplateArgumentBindingsText( 9540 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9541 } 9542 9543 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 9544 << (*DeductionFailure.getCallArgIndex() + 1) 9545 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 9546 << TemplateArgString; 9547 break; 9548 } 9549 9550 case Sema::TDK_NonDeducedMismatch: { 9551 // FIXME: Provide a source location to indicate what we couldn't match. 9552 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9553 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9554 if (FirstTA.getKind() == TemplateArgument::Template && 9555 SecondTA.getKind() == TemplateArgument::Template) { 9556 TemplateName FirstTN = FirstTA.getAsTemplate(); 9557 TemplateName SecondTN = SecondTA.getAsTemplate(); 9558 if (FirstTN.getKind() == TemplateName::Template && 9559 SecondTN.getKind() == TemplateName::Template) { 9560 if (FirstTN.getAsTemplateDecl()->getName() == 9561 SecondTN.getAsTemplateDecl()->getName()) { 9562 // FIXME: This fixes a bad diagnostic where both templates are named 9563 // the same. This particular case is a bit difficult since: 9564 // 1) It is passed as a string to the diagnostic printer. 9565 // 2) The diagnostic printer only attempts to find a better 9566 // name for types, not decls. 9567 // Ideally, this should folded into the diagnostic printer. 9568 S.Diag(Templated->getLocation(), 9569 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 9570 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 9571 return; 9572 } 9573 } 9574 } 9575 9576 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 9577 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 9578 return; 9579 9580 // FIXME: For generic lambda parameters, check if the function is a lambda 9581 // call operator, and if so, emit a prettier and more informative 9582 // diagnostic that mentions 'auto' and lambda in addition to 9583 // (or instead of?) the canonical template type parameters. 9584 S.Diag(Templated->getLocation(), 9585 diag::note_ovl_candidate_non_deduced_mismatch) 9586 << FirstTA << SecondTA; 9587 return; 9588 } 9589 // TODO: diagnose these individually, then kill off 9590 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9591 case Sema::TDK_MiscellaneousDeductionFailure: 9592 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9593 MaybeEmitInheritedConstructorNote(S, Found); 9594 return; 9595 } 9596 } 9597 9598 /// Diagnose a failed template-argument deduction, for function calls. 9599 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 9600 unsigned NumArgs, 9601 bool TakingCandidateAddress) { 9602 unsigned TDK = Cand->DeductionFailure.Result; 9603 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9604 if (CheckArityMismatch(S, Cand, NumArgs)) 9605 return; 9606 } 9607 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 9608 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 9609 } 9610 9611 /// CUDA: diagnose an invalid call across targets. 9612 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9613 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 9614 FunctionDecl *Callee = Cand->Function; 9615 9616 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 9617 CalleeTarget = S.IdentifyCUDATarget(Callee); 9618 9619 std::string FnDesc; 9620 OverloadCandidateKind FnKind = 9621 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc); 9622 9623 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 9624 << (unsigned)FnKind << CalleeTarget << CallerTarget; 9625 9626 // This could be an implicit constructor for which we could not infer the 9627 // target due to a collsion. Diagnose that case. 9628 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 9629 if (Meth != nullptr && Meth->isImplicit()) { 9630 CXXRecordDecl *ParentClass = Meth->getParent(); 9631 Sema::CXXSpecialMember CSM; 9632 9633 switch (FnKind) { 9634 default: 9635 return; 9636 case oc_implicit_default_constructor: 9637 CSM = Sema::CXXDefaultConstructor; 9638 break; 9639 case oc_implicit_copy_constructor: 9640 CSM = Sema::CXXCopyConstructor; 9641 break; 9642 case oc_implicit_move_constructor: 9643 CSM = Sema::CXXMoveConstructor; 9644 break; 9645 case oc_implicit_copy_assignment: 9646 CSM = Sema::CXXCopyAssignment; 9647 break; 9648 case oc_implicit_move_assignment: 9649 CSM = Sema::CXXMoveAssignment; 9650 break; 9651 }; 9652 9653 bool ConstRHS = false; 9654 if (Meth->getNumParams()) { 9655 if (const ReferenceType *RT = 9656 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 9657 ConstRHS = RT->getPointeeType().isConstQualified(); 9658 } 9659 } 9660 9661 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 9662 /* ConstRHS */ ConstRHS, 9663 /* Diagnose */ true); 9664 } 9665 } 9666 9667 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 9668 FunctionDecl *Callee = Cand->Function; 9669 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 9670 9671 S.Diag(Callee->getLocation(), 9672 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9673 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9674 } 9675 9676 /// Generates a 'note' diagnostic for an overload candidate. We've 9677 /// already generated a primary error at the call site. 9678 /// 9679 /// It really does need to be a single diagnostic with its caret 9680 /// pointed at the candidate declaration. Yes, this creates some 9681 /// major challenges of technical writing. Yes, this makes pointing 9682 /// out problems with specific arguments quite awkward. It's still 9683 /// better than generating twenty screens of text for every failed 9684 /// overload. 9685 /// 9686 /// It would be great to be able to express per-candidate problems 9687 /// more richly for those diagnostic clients that cared, but we'd 9688 /// still have to be just as careful with the default diagnostics. 9689 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9690 unsigned NumArgs, 9691 bool TakingCandidateAddress) { 9692 FunctionDecl *Fn = Cand->Function; 9693 9694 // Note deleted candidates, but only if they're viable. 9695 if (Cand->Viable && (Fn->isDeleted() || 9696 S.isFunctionConsideredUnavailable(Fn))) { 9697 std::string FnDesc; 9698 OverloadCandidateKind FnKind = 9699 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9700 9701 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9702 << FnKind << FnDesc 9703 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9704 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9705 return; 9706 } 9707 9708 // We don't really have anything else to say about viable candidates. 9709 if (Cand->Viable) { 9710 S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 9711 return; 9712 } 9713 9714 switch (Cand->FailureKind) { 9715 case ovl_fail_too_many_arguments: 9716 case ovl_fail_too_few_arguments: 9717 return DiagnoseArityMismatch(S, Cand, NumArgs); 9718 9719 case ovl_fail_bad_deduction: 9720 return DiagnoseBadDeduction(S, Cand, NumArgs, 9721 TakingCandidateAddress); 9722 9723 case ovl_fail_illegal_constructor: { 9724 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 9725 << (Fn->getPrimaryTemplate() ? 1 : 0); 9726 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9727 return; 9728 } 9729 9730 case ovl_fail_trivial_conversion: 9731 case ovl_fail_bad_final_conversion: 9732 case ovl_fail_final_conversion_not_exact: 9733 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 9734 9735 case ovl_fail_bad_conversion: { 9736 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9737 for (unsigned N = Cand->NumConversions; I != N; ++I) 9738 if (Cand->Conversions[I].isBad()) 9739 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 9740 9741 // FIXME: this currently happens when we're called from SemaInit 9742 // when user-conversion overload fails. Figure out how to handle 9743 // those conditions and diagnose them well. 9744 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 9745 } 9746 9747 case ovl_fail_bad_target: 9748 return DiagnoseBadTarget(S, Cand); 9749 9750 case ovl_fail_enable_if: 9751 return DiagnoseFailedEnableIfAttr(S, Cand); 9752 9753 case ovl_fail_addr_not_available: { 9754 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 9755 (void)Available; 9756 assert(!Available); 9757 break; 9758 } 9759 } 9760 } 9761 9762 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9763 // Desugar the type of the surrogate down to a function type, 9764 // retaining as many typedefs as possible while still showing 9765 // the function type (and, therefore, its parameter types). 9766 QualType FnType = Cand->Surrogate->getConversionType(); 9767 bool isLValueReference = false; 9768 bool isRValueReference = false; 9769 bool isPointer = false; 9770 if (const LValueReferenceType *FnTypeRef = 9771 FnType->getAs<LValueReferenceType>()) { 9772 FnType = FnTypeRef->getPointeeType(); 9773 isLValueReference = true; 9774 } else if (const RValueReferenceType *FnTypeRef = 9775 FnType->getAs<RValueReferenceType>()) { 9776 FnType = FnTypeRef->getPointeeType(); 9777 isRValueReference = true; 9778 } 9779 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9780 FnType = FnTypePtr->getPointeeType(); 9781 isPointer = true; 9782 } 9783 // Desugar down to a function type. 9784 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9785 // Reconstruct the pointer/reference as appropriate. 9786 if (isPointer) FnType = S.Context.getPointerType(FnType); 9787 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9788 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9789 9790 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9791 << FnType; 9792 } 9793 9794 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 9795 SourceLocation OpLoc, 9796 OverloadCandidate *Cand) { 9797 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9798 std::string TypeStr("operator"); 9799 TypeStr += Opc; 9800 TypeStr += "("; 9801 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9802 if (Cand->NumConversions == 1) { 9803 TypeStr += ")"; 9804 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9805 } else { 9806 TypeStr += ", "; 9807 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9808 TypeStr += ")"; 9809 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9810 } 9811 } 9812 9813 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9814 OverloadCandidate *Cand) { 9815 unsigned NoOperands = Cand->NumConversions; 9816 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9817 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9818 if (ICS.isBad()) break; // all meaningless after first invalid 9819 if (!ICS.isAmbiguous()) continue; 9820 9821 ICS.DiagnoseAmbiguousConversion( 9822 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 9823 } 9824 } 9825 9826 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9827 if (Cand->Function) 9828 return Cand->Function->getLocation(); 9829 if (Cand->IsSurrogate) 9830 return Cand->Surrogate->getLocation(); 9831 return SourceLocation(); 9832 } 9833 9834 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 9835 switch ((Sema::TemplateDeductionResult)DFI.Result) { 9836 case Sema::TDK_Success: 9837 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9838 9839 case Sema::TDK_Invalid: 9840 case Sema::TDK_Incomplete: 9841 return 1; 9842 9843 case Sema::TDK_Underqualified: 9844 case Sema::TDK_Inconsistent: 9845 return 2; 9846 9847 case Sema::TDK_SubstitutionFailure: 9848 case Sema::TDK_DeducedMismatch: 9849 case Sema::TDK_NonDeducedMismatch: 9850 case Sema::TDK_MiscellaneousDeductionFailure: 9851 return 3; 9852 9853 case Sema::TDK_InstantiationDepth: 9854 case Sema::TDK_FailedOverloadResolution: 9855 return 4; 9856 9857 case Sema::TDK_InvalidExplicitArguments: 9858 return 5; 9859 9860 case Sema::TDK_TooManyArguments: 9861 case Sema::TDK_TooFewArguments: 9862 return 6; 9863 } 9864 llvm_unreachable("Unhandled deduction result"); 9865 } 9866 9867 namespace { 9868 struct CompareOverloadCandidatesForDisplay { 9869 Sema &S; 9870 SourceLocation Loc; 9871 size_t NumArgs; 9872 9873 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs) 9874 : S(S), NumArgs(nArgs) {} 9875 9876 bool operator()(const OverloadCandidate *L, 9877 const OverloadCandidate *R) { 9878 // Fast-path this check. 9879 if (L == R) return false; 9880 9881 // Order first by viability. 9882 if (L->Viable) { 9883 if (!R->Viable) return true; 9884 9885 // TODO: introduce a tri-valued comparison for overload 9886 // candidates. Would be more worthwhile if we had a sort 9887 // that could exploit it. 9888 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 9889 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 9890 } else if (R->Viable) 9891 return false; 9892 9893 assert(L->Viable == R->Viable); 9894 9895 // Criteria by which we can sort non-viable candidates: 9896 if (!L->Viable) { 9897 // 1. Arity mismatches come after other candidates. 9898 if (L->FailureKind == ovl_fail_too_many_arguments || 9899 L->FailureKind == ovl_fail_too_few_arguments) { 9900 if (R->FailureKind == ovl_fail_too_many_arguments || 9901 R->FailureKind == ovl_fail_too_few_arguments) { 9902 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 9903 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 9904 if (LDist == RDist) { 9905 if (L->FailureKind == R->FailureKind) 9906 // Sort non-surrogates before surrogates. 9907 return !L->IsSurrogate && R->IsSurrogate; 9908 // Sort candidates requiring fewer parameters than there were 9909 // arguments given after candidates requiring more parameters 9910 // than there were arguments given. 9911 return L->FailureKind == ovl_fail_too_many_arguments; 9912 } 9913 return LDist < RDist; 9914 } 9915 return false; 9916 } 9917 if (R->FailureKind == ovl_fail_too_many_arguments || 9918 R->FailureKind == ovl_fail_too_few_arguments) 9919 return true; 9920 9921 // 2. Bad conversions come first and are ordered by the number 9922 // of bad conversions and quality of good conversions. 9923 if (L->FailureKind == ovl_fail_bad_conversion) { 9924 if (R->FailureKind != ovl_fail_bad_conversion) 9925 return true; 9926 9927 // The conversion that can be fixed with a smaller number of changes, 9928 // comes first. 9929 unsigned numLFixes = L->Fix.NumConversionsFixed; 9930 unsigned numRFixes = R->Fix.NumConversionsFixed; 9931 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 9932 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 9933 if (numLFixes != numRFixes) { 9934 return numLFixes < numRFixes; 9935 } 9936 9937 // If there's any ordering between the defined conversions... 9938 // FIXME: this might not be transitive. 9939 assert(L->NumConversions == R->NumConversions); 9940 9941 int leftBetter = 0; 9942 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 9943 for (unsigned E = L->NumConversions; I != E; ++I) { 9944 switch (CompareImplicitConversionSequences(S, Loc, 9945 L->Conversions[I], 9946 R->Conversions[I])) { 9947 case ImplicitConversionSequence::Better: 9948 leftBetter++; 9949 break; 9950 9951 case ImplicitConversionSequence::Worse: 9952 leftBetter--; 9953 break; 9954 9955 case ImplicitConversionSequence::Indistinguishable: 9956 break; 9957 } 9958 } 9959 if (leftBetter > 0) return true; 9960 if (leftBetter < 0) return false; 9961 9962 } else if (R->FailureKind == ovl_fail_bad_conversion) 9963 return false; 9964 9965 if (L->FailureKind == ovl_fail_bad_deduction) { 9966 if (R->FailureKind != ovl_fail_bad_deduction) 9967 return true; 9968 9969 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9970 return RankDeductionFailure(L->DeductionFailure) 9971 < RankDeductionFailure(R->DeductionFailure); 9972 } else if (R->FailureKind == ovl_fail_bad_deduction) 9973 return false; 9974 9975 // TODO: others? 9976 } 9977 9978 // Sort everything else by location. 9979 SourceLocation LLoc = GetLocationForCandidate(L); 9980 SourceLocation RLoc = GetLocationForCandidate(R); 9981 9982 // Put candidates without locations (e.g. builtins) at the end. 9983 if (LLoc.isInvalid()) return false; 9984 if (RLoc.isInvalid()) return true; 9985 9986 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9987 } 9988 }; 9989 } 9990 9991 /// CompleteNonViableCandidate - Normally, overload resolution only 9992 /// computes up to the first. Produces the FixIt set if possible. 9993 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 9994 ArrayRef<Expr *> Args) { 9995 assert(!Cand->Viable); 9996 9997 // Don't do anything on failures other than bad conversion. 9998 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 9999 10000 // We only want the FixIts if all the arguments can be corrected. 10001 bool Unfixable = false; 10002 // Use a implicit copy initialization to check conversion fixes. 10003 Cand->Fix.setConversionChecker(TryCopyInitialization); 10004 10005 // Skip forward to the first bad conversion. 10006 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 10007 unsigned ConvCount = Cand->NumConversions; 10008 while (true) { 10009 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 10010 ConvIdx++; 10011 if (Cand->Conversions[ConvIdx - 1].isBad()) { 10012 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 10013 break; 10014 } 10015 } 10016 10017 if (ConvIdx == ConvCount) 10018 return; 10019 10020 assert(!Cand->Conversions[ConvIdx].isInitialized() && 10021 "remaining conversion is initialized?"); 10022 10023 // FIXME: this should probably be preserved from the overload 10024 // operation somehow. 10025 bool SuppressUserConversions = false; 10026 10027 const FunctionProtoType* Proto; 10028 unsigned ArgIdx = ConvIdx; 10029 10030 if (Cand->IsSurrogate) { 10031 QualType ConvType 10032 = Cand->Surrogate->getConversionType().getNonReferenceType(); 10033 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10034 ConvType = ConvPtrType->getPointeeType(); 10035 Proto = ConvType->getAs<FunctionProtoType>(); 10036 ArgIdx--; 10037 } else if (Cand->Function) { 10038 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 10039 if (isa<CXXMethodDecl>(Cand->Function) && 10040 !isa<CXXConstructorDecl>(Cand->Function)) 10041 ArgIdx--; 10042 } else { 10043 // Builtin binary operator with a bad first conversion. 10044 assert(ConvCount <= 3); 10045 for (; ConvIdx != ConvCount; ++ConvIdx) 10046 Cand->Conversions[ConvIdx] 10047 = TryCopyInitialization(S, Args[ConvIdx], 10048 Cand->BuiltinTypes.ParamTypes[ConvIdx], 10049 SuppressUserConversions, 10050 /*InOverloadResolution*/ true, 10051 /*AllowObjCWritebackConversion=*/ 10052 S.getLangOpts().ObjCAutoRefCount); 10053 return; 10054 } 10055 10056 // Fill in the rest of the conversions. 10057 unsigned NumParams = Proto->getNumParams(); 10058 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 10059 if (ArgIdx < NumParams) { 10060 Cand->Conversions[ConvIdx] = TryCopyInitialization( 10061 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 10062 /*InOverloadResolution=*/true, 10063 /*AllowObjCWritebackConversion=*/ 10064 S.getLangOpts().ObjCAutoRefCount); 10065 // Store the FixIt in the candidate if it exists. 10066 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 10067 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10068 } 10069 else 10070 Cand->Conversions[ConvIdx].setEllipsis(); 10071 } 10072 } 10073 10074 /// PrintOverloadCandidates - When overload resolution fails, prints 10075 /// diagnostic messages containing the candidates in the candidate 10076 /// set. 10077 void OverloadCandidateSet::NoteCandidates(Sema &S, 10078 OverloadCandidateDisplayKind OCD, 10079 ArrayRef<Expr *> Args, 10080 StringRef Opc, 10081 SourceLocation OpLoc) { 10082 // Sort the candidates by viability and position. Sorting directly would 10083 // be prohibitive, so we make a set of pointers and sort those. 10084 SmallVector<OverloadCandidate*, 32> Cands; 10085 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10086 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10087 if (Cand->Viable) 10088 Cands.push_back(Cand); 10089 else if (OCD == OCD_AllCandidates) { 10090 CompleteNonViableCandidate(S, Cand, Args); 10091 if (Cand->Function || Cand->IsSurrogate) 10092 Cands.push_back(Cand); 10093 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10094 // want to list every possible builtin candidate. 10095 } 10096 } 10097 10098 std::sort(Cands.begin(), Cands.end(), 10099 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size())); 10100 10101 bool ReportedAmbiguousConversions = false; 10102 10103 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 10104 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10105 unsigned CandsShown = 0; 10106 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10107 OverloadCandidate *Cand = *I; 10108 10109 // Set an arbitrary limit on the number of candidate functions we'll spam 10110 // the user with. FIXME: This limit should depend on details of the 10111 // candidate list. 10112 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10113 break; 10114 } 10115 ++CandsShown; 10116 10117 if (Cand->Function) 10118 NoteFunctionCandidate(S, Cand, Args.size(), 10119 /*TakingCandidateAddress=*/false); 10120 else if (Cand->IsSurrogate) 10121 NoteSurrogateCandidate(S, Cand); 10122 else { 10123 assert(Cand->Viable && 10124 "Non-viable built-in candidates are not added to Cands."); 10125 // Generally we only see ambiguities including viable builtin 10126 // operators if overload resolution got screwed up by an 10127 // ambiguous user-defined conversion. 10128 // 10129 // FIXME: It's quite possible for different conversions to see 10130 // different ambiguities, though. 10131 if (!ReportedAmbiguousConversions) { 10132 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10133 ReportedAmbiguousConversions = true; 10134 } 10135 10136 // If this is a viable builtin, print it. 10137 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10138 } 10139 } 10140 10141 if (I != E) 10142 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10143 } 10144 10145 static SourceLocation 10146 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10147 return Cand->Specialization ? Cand->Specialization->getLocation() 10148 : SourceLocation(); 10149 } 10150 10151 namespace { 10152 struct CompareTemplateSpecCandidatesForDisplay { 10153 Sema &S; 10154 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10155 10156 bool operator()(const TemplateSpecCandidate *L, 10157 const TemplateSpecCandidate *R) { 10158 // Fast-path this check. 10159 if (L == R) 10160 return false; 10161 10162 // Assuming that both candidates are not matches... 10163 10164 // Sort by the ranking of deduction failures. 10165 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10166 return RankDeductionFailure(L->DeductionFailure) < 10167 RankDeductionFailure(R->DeductionFailure); 10168 10169 // Sort everything else by location. 10170 SourceLocation LLoc = GetLocationForCandidate(L); 10171 SourceLocation RLoc = GetLocationForCandidate(R); 10172 10173 // Put candidates without locations (e.g. builtins) at the end. 10174 if (LLoc.isInvalid()) 10175 return false; 10176 if (RLoc.isInvalid()) 10177 return true; 10178 10179 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10180 } 10181 }; 10182 } 10183 10184 /// Diagnose a template argument deduction failure. 10185 /// We are treating these failures as overload failures due to bad 10186 /// deductions. 10187 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10188 bool ForTakingAddress) { 10189 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 10190 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10191 } 10192 10193 void TemplateSpecCandidateSet::destroyCandidates() { 10194 for (iterator i = begin(), e = end(); i != e; ++i) { 10195 i->DeductionFailure.Destroy(); 10196 } 10197 } 10198 10199 void TemplateSpecCandidateSet::clear() { 10200 destroyCandidates(); 10201 Candidates.clear(); 10202 } 10203 10204 /// NoteCandidates - When no template specialization match is found, prints 10205 /// diagnostic messages containing the non-matching specializations that form 10206 /// the candidate set. 10207 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10208 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10209 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10210 // Sort the candidates by position (assuming no candidate is a match). 10211 // Sorting directly would be prohibitive, so we make a set of pointers 10212 // and sort those. 10213 SmallVector<TemplateSpecCandidate *, 32> Cands; 10214 Cands.reserve(size()); 10215 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10216 if (Cand->Specialization) 10217 Cands.push_back(Cand); 10218 // Otherwise, this is a non-matching builtin candidate. We do not, 10219 // in general, want to list every possible builtin candidate. 10220 } 10221 10222 std::sort(Cands.begin(), Cands.end(), 10223 CompareTemplateSpecCandidatesForDisplay(S)); 10224 10225 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10226 // for generalization purposes (?). 10227 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10228 10229 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10230 unsigned CandsShown = 0; 10231 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10232 TemplateSpecCandidate *Cand = *I; 10233 10234 // Set an arbitrary limit on the number of candidates we'll spam 10235 // the user with. FIXME: This limit should depend on details of the 10236 // candidate list. 10237 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10238 break; 10239 ++CandsShown; 10240 10241 assert(Cand->Specialization && 10242 "Non-matching built-in candidates are not added to Cands."); 10243 Cand->NoteDeductionFailure(S, ForTakingAddress); 10244 } 10245 10246 if (I != E) 10247 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10248 } 10249 10250 // [PossiblyAFunctionType] --> [Return] 10251 // NonFunctionType --> NonFunctionType 10252 // R (A) --> R(A) 10253 // R (*)(A) --> R (A) 10254 // R (&)(A) --> R (A) 10255 // R (S::*)(A) --> R (A) 10256 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10257 QualType Ret = PossiblyAFunctionType; 10258 if (const PointerType *ToTypePtr = 10259 PossiblyAFunctionType->getAs<PointerType>()) 10260 Ret = ToTypePtr->getPointeeType(); 10261 else if (const ReferenceType *ToTypeRef = 10262 PossiblyAFunctionType->getAs<ReferenceType>()) 10263 Ret = ToTypeRef->getPointeeType(); 10264 else if (const MemberPointerType *MemTypePtr = 10265 PossiblyAFunctionType->getAs<MemberPointerType>()) 10266 Ret = MemTypePtr->getPointeeType(); 10267 Ret = 10268 Context.getCanonicalType(Ret).getUnqualifiedType(); 10269 return Ret; 10270 } 10271 10272 namespace { 10273 // A helper class to help with address of function resolution 10274 // - allows us to avoid passing around all those ugly parameters 10275 class AddressOfFunctionResolver { 10276 Sema& S; 10277 Expr* SourceExpr; 10278 const QualType& TargetType; 10279 QualType TargetFunctionType; // Extracted function type from target type 10280 10281 bool Complain; 10282 //DeclAccessPair& ResultFunctionAccessPair; 10283 ASTContext& Context; 10284 10285 bool TargetTypeIsNonStaticMemberFunction; 10286 bool FoundNonTemplateFunction; 10287 bool StaticMemberFunctionFromBoundPointer; 10288 bool HasComplained; 10289 10290 OverloadExpr::FindResult OvlExprInfo; 10291 OverloadExpr *OvlExpr; 10292 TemplateArgumentListInfo OvlExplicitTemplateArgs; 10293 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 10294 TemplateSpecCandidateSet FailedCandidates; 10295 10296 public: 10297 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 10298 const QualType &TargetType, bool Complain) 10299 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 10300 Complain(Complain), Context(S.getASTContext()), 10301 TargetTypeIsNonStaticMemberFunction( 10302 !!TargetType->getAs<MemberPointerType>()), 10303 FoundNonTemplateFunction(false), 10304 StaticMemberFunctionFromBoundPointer(false), 10305 HasComplained(false), 10306 OvlExprInfo(OverloadExpr::find(SourceExpr)), 10307 OvlExpr(OvlExprInfo.Expression), 10308 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 10309 ExtractUnqualifiedFunctionTypeFromTargetType(); 10310 10311 if (TargetFunctionType->isFunctionType()) { 10312 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 10313 if (!UME->isImplicitAccess() && 10314 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 10315 StaticMemberFunctionFromBoundPointer = true; 10316 } else if (OvlExpr->hasExplicitTemplateArgs()) { 10317 DeclAccessPair dap; 10318 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 10319 OvlExpr, false, &dap)) { 10320 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 10321 if (!Method->isStatic()) { 10322 // If the target type is a non-function type and the function found 10323 // is a non-static member function, pretend as if that was the 10324 // target, it's the only possible type to end up with. 10325 TargetTypeIsNonStaticMemberFunction = true; 10326 10327 // And skip adding the function if its not in the proper form. 10328 // We'll diagnose this due to an empty set of functions. 10329 if (!OvlExprInfo.HasFormOfMemberPointer) 10330 return; 10331 } 10332 10333 Matches.push_back(std::make_pair(dap, Fn)); 10334 } 10335 return; 10336 } 10337 10338 if (OvlExpr->hasExplicitTemplateArgs()) 10339 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 10340 10341 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 10342 // C++ [over.over]p4: 10343 // If more than one function is selected, [...] 10344 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 10345 if (FoundNonTemplateFunction) 10346 EliminateAllTemplateMatches(); 10347 else 10348 EliminateAllExceptMostSpecializedTemplate(); 10349 } 10350 } 10351 10352 if (S.getLangOpts().CUDA && Matches.size() > 1) 10353 EliminateSuboptimalCudaMatches(); 10354 } 10355 10356 bool hasComplained() const { return HasComplained; } 10357 10358 private: 10359 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 10360 QualType Discard; 10361 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 10362 S.IsNoReturnConversion(FD->getType(), TargetFunctionType, Discard); 10363 } 10364 10365 /// \return true if A is considered a better overload candidate for the 10366 /// desired type than B. 10367 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 10368 // If A doesn't have exactly the correct type, we don't want to classify it 10369 // as "better" than anything else. This way, the user is required to 10370 // disambiguate for us if there are multiple candidates and no exact match. 10371 return candidateHasExactlyCorrectType(A) && 10372 (!candidateHasExactlyCorrectType(B) || 10373 compareEnableIfAttrs(S, A, B) == Comparison::Better); 10374 } 10375 10376 /// \return true if we were able to eliminate all but one overload candidate, 10377 /// false otherwise. 10378 bool eliminiateSuboptimalOverloadCandidates() { 10379 // Same algorithm as overload resolution -- one pass to pick the "best", 10380 // another pass to be sure that nothing is better than the best. 10381 auto Best = Matches.begin(); 10382 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 10383 if (isBetterCandidate(I->second, Best->second)) 10384 Best = I; 10385 10386 const FunctionDecl *BestFn = Best->second; 10387 auto IsBestOrInferiorToBest = [this, BestFn]( 10388 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 10389 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 10390 }; 10391 10392 // Note: We explicitly leave Matches unmodified if there isn't a clear best 10393 // option, so we can potentially give the user a better error 10394 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest)) 10395 return false; 10396 Matches[0] = *Best; 10397 Matches.resize(1); 10398 return true; 10399 } 10400 10401 bool isTargetTypeAFunction() const { 10402 return TargetFunctionType->isFunctionType(); 10403 } 10404 10405 // [ToType] [Return] 10406 10407 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 10408 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 10409 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 10410 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 10411 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 10412 } 10413 10414 // return true if any matching specializations were found 10415 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 10416 const DeclAccessPair& CurAccessFunPair) { 10417 if (CXXMethodDecl *Method 10418 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 10419 // Skip non-static function templates when converting to pointer, and 10420 // static when converting to member pointer. 10421 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10422 return false; 10423 } 10424 else if (TargetTypeIsNonStaticMemberFunction) 10425 return false; 10426 10427 // C++ [over.over]p2: 10428 // If the name is a function template, template argument deduction is 10429 // done (14.8.2.2), and if the argument deduction succeeds, the 10430 // resulting template argument list is used to generate a single 10431 // function template specialization, which is added to the set of 10432 // overloaded functions considered. 10433 FunctionDecl *Specialization = nullptr; 10434 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10435 if (Sema::TemplateDeductionResult Result 10436 = S.DeduceTemplateArguments(FunctionTemplate, 10437 &OvlExplicitTemplateArgs, 10438 TargetFunctionType, Specialization, 10439 Info, /*InOverloadResolution=*/true)) { 10440 // Make a note of the failed deduction for diagnostics. 10441 FailedCandidates.addCandidate() 10442 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 10443 MakeDeductionFailureInfo(Context, Result, Info)); 10444 return false; 10445 } 10446 10447 // Template argument deduction ensures that we have an exact match or 10448 // compatible pointer-to-function arguments that would be adjusted by ICS. 10449 // This function template specicalization works. 10450 assert(S.isSameOrCompatibleFunctionType( 10451 Context.getCanonicalType(Specialization->getType()), 10452 Context.getCanonicalType(TargetFunctionType))); 10453 10454 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 10455 return false; 10456 10457 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 10458 return true; 10459 } 10460 10461 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 10462 const DeclAccessPair& CurAccessFunPair) { 10463 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 10464 // Skip non-static functions when converting to pointer, and static 10465 // when converting to member pointer. 10466 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10467 return false; 10468 } 10469 else if (TargetTypeIsNonStaticMemberFunction) 10470 return false; 10471 10472 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 10473 if (S.getLangOpts().CUDA) 10474 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 10475 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl)) 10476 return false; 10477 10478 // If any candidate has a placeholder return type, trigger its deduction 10479 // now. 10480 if (S.getLangOpts().CPlusPlus14 && 10481 FunDecl->getReturnType()->isUndeducedType() && 10482 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) { 10483 HasComplained |= Complain; 10484 return false; 10485 } 10486 10487 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 10488 return false; 10489 10490 // If we're in C, we need to support types that aren't exactly identical. 10491 if (!S.getLangOpts().CPlusPlus || 10492 candidateHasExactlyCorrectType(FunDecl)) { 10493 Matches.push_back(std::make_pair( 10494 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 10495 FoundNonTemplateFunction = true; 10496 return true; 10497 } 10498 } 10499 10500 return false; 10501 } 10502 10503 bool FindAllFunctionsThatMatchTargetTypeExactly() { 10504 bool Ret = false; 10505 10506 // If the overload expression doesn't have the form of a pointer to 10507 // member, don't try to convert it to a pointer-to-member type. 10508 if (IsInvalidFormOfPointerToMemberFunction()) 10509 return false; 10510 10511 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10512 E = OvlExpr->decls_end(); 10513 I != E; ++I) { 10514 // Look through any using declarations to find the underlying function. 10515 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 10516 10517 // C++ [over.over]p3: 10518 // Non-member functions and static member functions match 10519 // targets of type "pointer-to-function" or "reference-to-function." 10520 // Nonstatic member functions match targets of 10521 // type "pointer-to-member-function." 10522 // Note that according to DR 247, the containing class does not matter. 10523 if (FunctionTemplateDecl *FunctionTemplate 10524 = dyn_cast<FunctionTemplateDecl>(Fn)) { 10525 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 10526 Ret = true; 10527 } 10528 // If we have explicit template arguments supplied, skip non-templates. 10529 else if (!OvlExpr->hasExplicitTemplateArgs() && 10530 AddMatchingNonTemplateFunction(Fn, I.getPair())) 10531 Ret = true; 10532 } 10533 assert(Ret || Matches.empty()); 10534 return Ret; 10535 } 10536 10537 void EliminateAllExceptMostSpecializedTemplate() { 10538 // [...] and any given function template specialization F1 is 10539 // eliminated if the set contains a second function template 10540 // specialization whose function template is more specialized 10541 // than the function template of F1 according to the partial 10542 // ordering rules of 14.5.5.2. 10543 10544 // The algorithm specified above is quadratic. We instead use a 10545 // two-pass algorithm (similar to the one used to identify the 10546 // best viable function in an overload set) that identifies the 10547 // best function template (if it exists). 10548 10549 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 10550 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 10551 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 10552 10553 // TODO: It looks like FailedCandidates does not serve much purpose 10554 // here, since the no_viable diagnostic has index 0. 10555 UnresolvedSetIterator Result = S.getMostSpecialized( 10556 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 10557 SourceExpr->getLocStart(), S.PDiag(), 10558 S.PDiag(diag::err_addr_ovl_ambiguous) 10559 << Matches[0].second->getDeclName(), 10560 S.PDiag(diag::note_ovl_candidate) 10561 << (unsigned)oc_function_template, 10562 Complain, TargetFunctionType); 10563 10564 if (Result != MatchesCopy.end()) { 10565 // Make it the first and only element 10566 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 10567 Matches[0].second = cast<FunctionDecl>(*Result); 10568 Matches.resize(1); 10569 } else 10570 HasComplained |= Complain; 10571 } 10572 10573 void EliminateAllTemplateMatches() { 10574 // [...] any function template specializations in the set are 10575 // eliminated if the set also contains a non-template function, [...] 10576 for (unsigned I = 0, N = Matches.size(); I != N; ) { 10577 if (Matches[I].second->getPrimaryTemplate() == nullptr) 10578 ++I; 10579 else { 10580 Matches[I] = Matches[--N]; 10581 Matches.resize(N); 10582 } 10583 } 10584 } 10585 10586 void EliminateSuboptimalCudaMatches() { 10587 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 10588 } 10589 10590 public: 10591 void ComplainNoMatchesFound() const { 10592 assert(Matches.empty()); 10593 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 10594 << OvlExpr->getName() << TargetFunctionType 10595 << OvlExpr->getSourceRange(); 10596 if (FailedCandidates.empty()) 10597 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10598 /*TakingAddress=*/true); 10599 else { 10600 // We have some deduction failure messages. Use them to diagnose 10601 // the function templates, and diagnose the non-template candidates 10602 // normally. 10603 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10604 IEnd = OvlExpr->decls_end(); 10605 I != IEnd; ++I) 10606 if (FunctionDecl *Fun = 10607 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 10608 if (!functionHasPassObjectSizeParams(Fun)) 10609 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType, 10610 /*TakingAddress=*/true); 10611 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 10612 } 10613 } 10614 10615 bool IsInvalidFormOfPointerToMemberFunction() const { 10616 return TargetTypeIsNonStaticMemberFunction && 10617 !OvlExprInfo.HasFormOfMemberPointer; 10618 } 10619 10620 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 10621 // TODO: Should we condition this on whether any functions might 10622 // have matched, or is it more appropriate to do that in callers? 10623 // TODO: a fixit wouldn't hurt. 10624 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 10625 << TargetType << OvlExpr->getSourceRange(); 10626 } 10627 10628 bool IsStaticMemberFunctionFromBoundPointer() const { 10629 return StaticMemberFunctionFromBoundPointer; 10630 } 10631 10632 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 10633 S.Diag(OvlExpr->getLocStart(), 10634 diag::err_invalid_form_pointer_member_function) 10635 << OvlExpr->getSourceRange(); 10636 } 10637 10638 void ComplainOfInvalidConversion() const { 10639 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 10640 << OvlExpr->getName() << TargetType; 10641 } 10642 10643 void ComplainMultipleMatchesFound() const { 10644 assert(Matches.size() > 1); 10645 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 10646 << OvlExpr->getName() 10647 << OvlExpr->getSourceRange(); 10648 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10649 /*TakingAddress=*/true); 10650 } 10651 10652 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 10653 10654 int getNumMatches() const { return Matches.size(); } 10655 10656 FunctionDecl* getMatchingFunctionDecl() const { 10657 if (Matches.size() != 1) return nullptr; 10658 return Matches[0].second; 10659 } 10660 10661 const DeclAccessPair* getMatchingFunctionAccessPair() const { 10662 if (Matches.size() != 1) return nullptr; 10663 return &Matches[0].first; 10664 } 10665 }; 10666 } 10667 10668 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 10669 /// an overloaded function (C++ [over.over]), where @p From is an 10670 /// expression with overloaded function type and @p ToType is the type 10671 /// we're trying to resolve to. For example: 10672 /// 10673 /// @code 10674 /// int f(double); 10675 /// int f(int); 10676 /// 10677 /// int (*pfd)(double) = f; // selects f(double) 10678 /// @endcode 10679 /// 10680 /// This routine returns the resulting FunctionDecl if it could be 10681 /// resolved, and NULL otherwise. When @p Complain is true, this 10682 /// routine will emit diagnostics if there is an error. 10683 FunctionDecl * 10684 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 10685 QualType TargetType, 10686 bool Complain, 10687 DeclAccessPair &FoundResult, 10688 bool *pHadMultipleCandidates) { 10689 assert(AddressOfExpr->getType() == Context.OverloadTy); 10690 10691 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 10692 Complain); 10693 int NumMatches = Resolver.getNumMatches(); 10694 FunctionDecl *Fn = nullptr; 10695 bool ShouldComplain = Complain && !Resolver.hasComplained(); 10696 if (NumMatches == 0 && ShouldComplain) { 10697 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 10698 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 10699 else 10700 Resolver.ComplainNoMatchesFound(); 10701 } 10702 else if (NumMatches > 1 && ShouldComplain) 10703 Resolver.ComplainMultipleMatchesFound(); 10704 else if (NumMatches == 1) { 10705 Fn = Resolver.getMatchingFunctionDecl(); 10706 assert(Fn); 10707 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 10708 if (Complain) { 10709 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 10710 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 10711 else 10712 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 10713 } 10714 } 10715 10716 if (pHadMultipleCandidates) 10717 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 10718 return Fn; 10719 } 10720 10721 /// \brief Given an expression that refers to an overloaded function, try to 10722 /// resolve that function to a single function that can have its address taken. 10723 /// This will modify `Pair` iff it returns non-null. 10724 /// 10725 /// This routine can only realistically succeed if all but one candidates in the 10726 /// overload set for SrcExpr cannot have their addresses taken. 10727 FunctionDecl * 10728 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 10729 DeclAccessPair &Pair) { 10730 OverloadExpr::FindResult R = OverloadExpr::find(E); 10731 OverloadExpr *Ovl = R.Expression; 10732 FunctionDecl *Result = nullptr; 10733 DeclAccessPair DAP; 10734 // Don't use the AddressOfResolver because we're specifically looking for 10735 // cases where we have one overload candidate that lacks 10736 // enable_if/pass_object_size/... 10737 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 10738 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 10739 if (!FD) 10740 return nullptr; 10741 10742 if (!checkAddressOfFunctionIsAvailable(FD)) 10743 continue; 10744 10745 // We have more than one result; quit. 10746 if (Result) 10747 return nullptr; 10748 DAP = I.getPair(); 10749 Result = FD; 10750 } 10751 10752 if (Result) 10753 Pair = DAP; 10754 return Result; 10755 } 10756 10757 /// \brief Given an overloaded function, tries to turn it into a non-overloaded 10758 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 10759 /// will perform access checks, diagnose the use of the resultant decl, and, if 10760 /// necessary, perform a function-to-pointer decay. 10761 /// 10762 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 10763 /// Otherwise, returns true. This may emit diagnostics and return true. 10764 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 10765 ExprResult &SrcExpr) { 10766 Expr *E = SrcExpr.get(); 10767 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 10768 10769 DeclAccessPair DAP; 10770 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 10771 if (!Found) 10772 return false; 10773 10774 // Emitting multiple diagnostics for a function that is both inaccessible and 10775 // unavailable is consistent with our behavior elsewhere. So, always check 10776 // for both. 10777 DiagnoseUseOfDecl(Found, E->getExprLoc()); 10778 CheckAddressOfMemberAccess(E, DAP); 10779 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 10780 if (Fixed->getType()->isFunctionType()) 10781 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 10782 else 10783 SrcExpr = Fixed; 10784 return true; 10785 } 10786 10787 /// \brief Given an expression that refers to an overloaded function, try to 10788 /// resolve that overloaded function expression down to a single function. 10789 /// 10790 /// This routine can only resolve template-ids that refer to a single function 10791 /// template, where that template-id refers to a single template whose template 10792 /// arguments are either provided by the template-id or have defaults, 10793 /// as described in C++0x [temp.arg.explicit]p3. 10794 /// 10795 /// If no template-ids are found, no diagnostics are emitted and NULL is 10796 /// returned. 10797 FunctionDecl * 10798 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 10799 bool Complain, 10800 DeclAccessPair *FoundResult) { 10801 // C++ [over.over]p1: 10802 // [...] [Note: any redundant set of parentheses surrounding the 10803 // overloaded function name is ignored (5.1). ] 10804 // C++ [over.over]p1: 10805 // [...] The overloaded function name can be preceded by the & 10806 // operator. 10807 10808 // If we didn't actually find any template-ids, we're done. 10809 if (!ovl->hasExplicitTemplateArgs()) 10810 return nullptr; 10811 10812 TemplateArgumentListInfo ExplicitTemplateArgs; 10813 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 10814 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 10815 10816 // Look through all of the overloaded functions, searching for one 10817 // whose type matches exactly. 10818 FunctionDecl *Matched = nullptr; 10819 for (UnresolvedSetIterator I = ovl->decls_begin(), 10820 E = ovl->decls_end(); I != E; ++I) { 10821 // C++0x [temp.arg.explicit]p3: 10822 // [...] In contexts where deduction is done and fails, or in contexts 10823 // where deduction is not done, if a template argument list is 10824 // specified and it, along with any default template arguments, 10825 // identifies a single function template specialization, then the 10826 // template-id is an lvalue for the function template specialization. 10827 FunctionTemplateDecl *FunctionTemplate 10828 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 10829 10830 // C++ [over.over]p2: 10831 // If the name is a function template, template argument deduction is 10832 // done (14.8.2.2), and if the argument deduction succeeds, the 10833 // resulting template argument list is used to generate a single 10834 // function template specialization, which is added to the set of 10835 // overloaded functions considered. 10836 FunctionDecl *Specialization = nullptr; 10837 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10838 if (TemplateDeductionResult Result 10839 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 10840 Specialization, Info, 10841 /*InOverloadResolution=*/true)) { 10842 // Make a note of the failed deduction for diagnostics. 10843 // TODO: Actually use the failed-deduction info? 10844 FailedCandidates.addCandidate() 10845 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 10846 MakeDeductionFailureInfo(Context, Result, Info)); 10847 continue; 10848 } 10849 10850 assert(Specialization && "no specialization and no error?"); 10851 10852 // Multiple matches; we can't resolve to a single declaration. 10853 if (Matched) { 10854 if (Complain) { 10855 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 10856 << ovl->getName(); 10857 NoteAllOverloadCandidates(ovl); 10858 } 10859 return nullptr; 10860 } 10861 10862 Matched = Specialization; 10863 if (FoundResult) *FoundResult = I.getPair(); 10864 } 10865 10866 if (Matched && getLangOpts().CPlusPlus14 && 10867 Matched->getReturnType()->isUndeducedType() && 10868 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 10869 return nullptr; 10870 10871 return Matched; 10872 } 10873 10874 10875 10876 10877 // Resolve and fix an overloaded expression that can be resolved 10878 // because it identifies a single function template specialization. 10879 // 10880 // Last three arguments should only be supplied if Complain = true 10881 // 10882 // Return true if it was logically possible to so resolve the 10883 // expression, regardless of whether or not it succeeded. Always 10884 // returns true if 'complain' is set. 10885 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 10886 ExprResult &SrcExpr, bool doFunctionPointerConverion, 10887 bool complain, SourceRange OpRangeForComplaining, 10888 QualType DestTypeForComplaining, 10889 unsigned DiagIDForComplaining) { 10890 assert(SrcExpr.get()->getType() == Context.OverloadTy); 10891 10892 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 10893 10894 DeclAccessPair found; 10895 ExprResult SingleFunctionExpression; 10896 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 10897 ovl.Expression, /*complain*/ false, &found)) { 10898 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 10899 SrcExpr = ExprError(); 10900 return true; 10901 } 10902 10903 // It is only correct to resolve to an instance method if we're 10904 // resolving a form that's permitted to be a pointer to member. 10905 // Otherwise we'll end up making a bound member expression, which 10906 // is illegal in all the contexts we resolve like this. 10907 if (!ovl.HasFormOfMemberPointer && 10908 isa<CXXMethodDecl>(fn) && 10909 cast<CXXMethodDecl>(fn)->isInstance()) { 10910 if (!complain) return false; 10911 10912 Diag(ovl.Expression->getExprLoc(), 10913 diag::err_bound_member_function) 10914 << 0 << ovl.Expression->getSourceRange(); 10915 10916 // TODO: I believe we only end up here if there's a mix of 10917 // static and non-static candidates (otherwise the expression 10918 // would have 'bound member' type, not 'overload' type). 10919 // Ideally we would note which candidate was chosen and why 10920 // the static candidates were rejected. 10921 SrcExpr = ExprError(); 10922 return true; 10923 } 10924 10925 // Fix the expression to refer to 'fn'. 10926 SingleFunctionExpression = 10927 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 10928 10929 // If desired, do function-to-pointer decay. 10930 if (doFunctionPointerConverion) { 10931 SingleFunctionExpression = 10932 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 10933 if (SingleFunctionExpression.isInvalid()) { 10934 SrcExpr = ExprError(); 10935 return true; 10936 } 10937 } 10938 } 10939 10940 if (!SingleFunctionExpression.isUsable()) { 10941 if (complain) { 10942 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 10943 << ovl.Expression->getName() 10944 << DestTypeForComplaining 10945 << OpRangeForComplaining 10946 << ovl.Expression->getQualifierLoc().getSourceRange(); 10947 NoteAllOverloadCandidates(SrcExpr.get()); 10948 10949 SrcExpr = ExprError(); 10950 return true; 10951 } 10952 10953 return false; 10954 } 10955 10956 SrcExpr = SingleFunctionExpression; 10957 return true; 10958 } 10959 10960 /// \brief Add a single candidate to the overload set. 10961 static void AddOverloadedCallCandidate(Sema &S, 10962 DeclAccessPair FoundDecl, 10963 TemplateArgumentListInfo *ExplicitTemplateArgs, 10964 ArrayRef<Expr *> Args, 10965 OverloadCandidateSet &CandidateSet, 10966 bool PartialOverloading, 10967 bool KnownValid) { 10968 NamedDecl *Callee = FoundDecl.getDecl(); 10969 if (isa<UsingShadowDecl>(Callee)) 10970 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 10971 10972 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 10973 if (ExplicitTemplateArgs) { 10974 assert(!KnownValid && "Explicit template arguments?"); 10975 return; 10976 } 10977 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 10978 /*SuppressUsedConversions=*/false, 10979 PartialOverloading); 10980 return; 10981 } 10982 10983 if (FunctionTemplateDecl *FuncTemplate 10984 = dyn_cast<FunctionTemplateDecl>(Callee)) { 10985 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 10986 ExplicitTemplateArgs, Args, CandidateSet, 10987 /*SuppressUsedConversions=*/false, 10988 PartialOverloading); 10989 return; 10990 } 10991 10992 assert(!KnownValid && "unhandled case in overloaded call candidate"); 10993 } 10994 10995 /// \brief Add the overload candidates named by callee and/or found by argument 10996 /// dependent lookup to the given overload set. 10997 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 10998 ArrayRef<Expr *> Args, 10999 OverloadCandidateSet &CandidateSet, 11000 bool PartialOverloading) { 11001 11002 #ifndef NDEBUG 11003 // Verify that ArgumentDependentLookup is consistent with the rules 11004 // in C++0x [basic.lookup.argdep]p3: 11005 // 11006 // Let X be the lookup set produced by unqualified lookup (3.4.1) 11007 // and let Y be the lookup set produced by argument dependent 11008 // lookup (defined as follows). If X contains 11009 // 11010 // -- a declaration of a class member, or 11011 // 11012 // -- a block-scope function declaration that is not a 11013 // using-declaration, or 11014 // 11015 // -- a declaration that is neither a function or a function 11016 // template 11017 // 11018 // then Y is empty. 11019 11020 if (ULE->requiresADL()) { 11021 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11022 E = ULE->decls_end(); I != E; ++I) { 11023 assert(!(*I)->getDeclContext()->isRecord()); 11024 assert(isa<UsingShadowDecl>(*I) || 11025 !(*I)->getDeclContext()->isFunctionOrMethod()); 11026 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 11027 } 11028 } 11029 #endif 11030 11031 // It would be nice to avoid this copy. 11032 TemplateArgumentListInfo TABuffer; 11033 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11034 if (ULE->hasExplicitTemplateArgs()) { 11035 ULE->copyTemplateArgumentsInto(TABuffer); 11036 ExplicitTemplateArgs = &TABuffer; 11037 } 11038 11039 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11040 E = ULE->decls_end(); I != E; ++I) 11041 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 11042 CandidateSet, PartialOverloading, 11043 /*KnownValid*/ true); 11044 11045 if (ULE->requiresADL()) 11046 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 11047 Args, ExplicitTemplateArgs, 11048 CandidateSet, PartialOverloading); 11049 } 11050 11051 /// Determine whether a declaration with the specified name could be moved into 11052 /// a different namespace. 11053 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 11054 switch (Name.getCXXOverloadedOperator()) { 11055 case OO_New: case OO_Array_New: 11056 case OO_Delete: case OO_Array_Delete: 11057 return false; 11058 11059 default: 11060 return true; 11061 } 11062 } 11063 11064 /// Attempt to recover from an ill-formed use of a non-dependent name in a 11065 /// template, where the non-dependent name was declared after the template 11066 /// was defined. This is common in code written for a compilers which do not 11067 /// correctly implement two-stage name lookup. 11068 /// 11069 /// Returns true if a viable candidate was found and a diagnostic was issued. 11070 static bool 11071 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 11072 const CXXScopeSpec &SS, LookupResult &R, 11073 OverloadCandidateSet::CandidateSetKind CSK, 11074 TemplateArgumentListInfo *ExplicitTemplateArgs, 11075 ArrayRef<Expr *> Args, 11076 bool *DoDiagnoseEmptyLookup = nullptr) { 11077 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 11078 return false; 11079 11080 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 11081 if (DC->isTransparentContext()) 11082 continue; 11083 11084 SemaRef.LookupQualifiedName(R, DC); 11085 11086 if (!R.empty()) { 11087 R.suppressDiagnostics(); 11088 11089 if (isa<CXXRecordDecl>(DC)) { 11090 // Don't diagnose names we find in classes; we get much better 11091 // diagnostics for these from DiagnoseEmptyLookup. 11092 R.clear(); 11093 if (DoDiagnoseEmptyLookup) 11094 *DoDiagnoseEmptyLookup = true; 11095 return false; 11096 } 11097 11098 OverloadCandidateSet Candidates(FnLoc, CSK); 11099 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11100 AddOverloadedCallCandidate(SemaRef, I.getPair(), 11101 ExplicitTemplateArgs, Args, 11102 Candidates, false, /*KnownValid*/ false); 11103 11104 OverloadCandidateSet::iterator Best; 11105 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 11106 // No viable functions. Don't bother the user with notes for functions 11107 // which don't work and shouldn't be found anyway. 11108 R.clear(); 11109 return false; 11110 } 11111 11112 // Find the namespaces where ADL would have looked, and suggest 11113 // declaring the function there instead. 11114 Sema::AssociatedNamespaceSet AssociatedNamespaces; 11115 Sema::AssociatedClassSet AssociatedClasses; 11116 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 11117 AssociatedNamespaces, 11118 AssociatedClasses); 11119 Sema::AssociatedNamespaceSet SuggestedNamespaces; 11120 if (canBeDeclaredInNamespace(R.getLookupName())) { 11121 DeclContext *Std = SemaRef.getStdNamespace(); 11122 for (Sema::AssociatedNamespaceSet::iterator 11123 it = AssociatedNamespaces.begin(), 11124 end = AssociatedNamespaces.end(); it != end; ++it) { 11125 // Never suggest declaring a function within namespace 'std'. 11126 if (Std && Std->Encloses(*it)) 11127 continue; 11128 11129 // Never suggest declaring a function within a namespace with a 11130 // reserved name, like __gnu_cxx. 11131 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 11132 if (NS && 11133 NS->getQualifiedNameAsString().find("__") != std::string::npos) 11134 continue; 11135 11136 SuggestedNamespaces.insert(*it); 11137 } 11138 } 11139 11140 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 11141 << R.getLookupName(); 11142 if (SuggestedNamespaces.empty()) { 11143 SemaRef.Diag(Best->Function->getLocation(), 11144 diag::note_not_found_by_two_phase_lookup) 11145 << R.getLookupName() << 0; 11146 } else if (SuggestedNamespaces.size() == 1) { 11147 SemaRef.Diag(Best->Function->getLocation(), 11148 diag::note_not_found_by_two_phase_lookup) 11149 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11150 } else { 11151 // FIXME: It would be useful to list the associated namespaces here, 11152 // but the diagnostics infrastructure doesn't provide a way to produce 11153 // a localized representation of a list of items. 11154 SemaRef.Diag(Best->Function->getLocation(), 11155 diag::note_not_found_by_two_phase_lookup) 11156 << R.getLookupName() << 2; 11157 } 11158 11159 // Try to recover by calling this function. 11160 return true; 11161 } 11162 11163 R.clear(); 11164 } 11165 11166 return false; 11167 } 11168 11169 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11170 /// template, where the non-dependent operator was declared after the template 11171 /// was defined. 11172 /// 11173 /// Returns true if a viable candidate was found and a diagnostic was issued. 11174 static bool 11175 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11176 SourceLocation OpLoc, 11177 ArrayRef<Expr *> Args) { 11178 DeclarationName OpName = 11179 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11180 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11181 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11182 OverloadCandidateSet::CSK_Operator, 11183 /*ExplicitTemplateArgs=*/nullptr, Args); 11184 } 11185 11186 namespace { 11187 class BuildRecoveryCallExprRAII { 11188 Sema &SemaRef; 11189 public: 11190 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11191 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11192 SemaRef.IsBuildingRecoveryCallExpr = true; 11193 } 11194 11195 ~BuildRecoveryCallExprRAII() { 11196 SemaRef.IsBuildingRecoveryCallExpr = false; 11197 } 11198 }; 11199 11200 } 11201 11202 static std::unique_ptr<CorrectionCandidateCallback> 11203 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 11204 bool HasTemplateArgs, bool AllowTypoCorrection) { 11205 if (!AllowTypoCorrection) 11206 return llvm::make_unique<NoTypoCorrectionCCC>(); 11207 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 11208 HasTemplateArgs, ME); 11209 } 11210 11211 /// Attempts to recover from a call where no functions were found. 11212 /// 11213 /// Returns true if new candidates were found. 11214 static ExprResult 11215 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11216 UnresolvedLookupExpr *ULE, 11217 SourceLocation LParenLoc, 11218 MutableArrayRef<Expr *> Args, 11219 SourceLocation RParenLoc, 11220 bool EmptyLookup, bool AllowTypoCorrection) { 11221 // Do not try to recover if it is already building a recovery call. 11222 // This stops infinite loops for template instantiations like 11223 // 11224 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 11225 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 11226 // 11227 if (SemaRef.IsBuildingRecoveryCallExpr) 11228 return ExprError(); 11229 BuildRecoveryCallExprRAII RCE(SemaRef); 11230 11231 CXXScopeSpec SS; 11232 SS.Adopt(ULE->getQualifierLoc()); 11233 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11234 11235 TemplateArgumentListInfo TABuffer; 11236 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11237 if (ULE->hasExplicitTemplateArgs()) { 11238 ULE->copyTemplateArgumentsInto(TABuffer); 11239 ExplicitTemplateArgs = &TABuffer; 11240 } 11241 11242 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 11243 Sema::LookupOrdinaryName); 11244 bool DoDiagnoseEmptyLookup = EmptyLookup; 11245 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 11246 OverloadCandidateSet::CSK_Normal, 11247 ExplicitTemplateArgs, Args, 11248 &DoDiagnoseEmptyLookup) && 11249 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 11250 S, SS, R, 11251 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 11252 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 11253 ExplicitTemplateArgs, Args))) 11254 return ExprError(); 11255 11256 assert(!R.empty() && "lookup results empty despite recovery"); 11257 11258 // Build an implicit member call if appropriate. Just drop the 11259 // casts and such from the call, we don't really care. 11260 ExprResult NewFn = ExprError(); 11261 if ((*R.begin())->isCXXClassMember()) 11262 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 11263 ExplicitTemplateArgs, S); 11264 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 11265 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 11266 ExplicitTemplateArgs); 11267 else 11268 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 11269 11270 if (NewFn.isInvalid()) 11271 return ExprError(); 11272 11273 // This shouldn't cause an infinite loop because we're giving it 11274 // an expression with viable lookup results, which should never 11275 // end up here. 11276 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 11277 MultiExprArg(Args.data(), Args.size()), 11278 RParenLoc); 11279 } 11280 11281 /// \brief Constructs and populates an OverloadedCandidateSet from 11282 /// the given function. 11283 /// \returns true when an the ExprResult output parameter has been set. 11284 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 11285 UnresolvedLookupExpr *ULE, 11286 MultiExprArg Args, 11287 SourceLocation RParenLoc, 11288 OverloadCandidateSet *CandidateSet, 11289 ExprResult *Result) { 11290 #ifndef NDEBUG 11291 if (ULE->requiresADL()) { 11292 // To do ADL, we must have found an unqualified name. 11293 assert(!ULE->getQualifier() && "qualified name with ADL"); 11294 11295 // We don't perform ADL for implicit declarations of builtins. 11296 // Verify that this was correctly set up. 11297 FunctionDecl *F; 11298 if (ULE->decls_begin() + 1 == ULE->decls_end() && 11299 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 11300 F->getBuiltinID() && F->isImplicit()) 11301 llvm_unreachable("performing ADL for builtin"); 11302 11303 // We don't perform ADL in C. 11304 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 11305 } 11306 #endif 11307 11308 UnbridgedCastsSet UnbridgedCasts; 11309 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 11310 *Result = ExprError(); 11311 return true; 11312 } 11313 11314 // Add the functions denoted by the callee to the set of candidate 11315 // functions, including those from argument-dependent lookup. 11316 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 11317 11318 if (getLangOpts().MSVCCompat && 11319 CurContext->isDependentContext() && !isSFINAEContext() && 11320 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 11321 11322 OverloadCandidateSet::iterator Best; 11323 if (CandidateSet->empty() || 11324 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) == 11325 OR_No_Viable_Function) { 11326 // In Microsoft mode, if we are inside a template class member function then 11327 // create a type dependent CallExpr. The goal is to postpone name lookup 11328 // to instantiation time to be able to search into type dependent base 11329 // classes. 11330 CallExpr *CE = new (Context) CallExpr( 11331 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 11332 CE->setTypeDependent(true); 11333 CE->setValueDependent(true); 11334 CE->setInstantiationDependent(true); 11335 *Result = CE; 11336 return true; 11337 } 11338 } 11339 11340 if (CandidateSet->empty()) 11341 return false; 11342 11343 UnbridgedCasts.restore(); 11344 return false; 11345 } 11346 11347 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 11348 /// the completed call expression. If overload resolution fails, emits 11349 /// diagnostics and returns ExprError() 11350 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11351 UnresolvedLookupExpr *ULE, 11352 SourceLocation LParenLoc, 11353 MultiExprArg Args, 11354 SourceLocation RParenLoc, 11355 Expr *ExecConfig, 11356 OverloadCandidateSet *CandidateSet, 11357 OverloadCandidateSet::iterator *Best, 11358 OverloadingResult OverloadResult, 11359 bool AllowTypoCorrection) { 11360 if (CandidateSet->empty()) 11361 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 11362 RParenLoc, /*EmptyLookup=*/true, 11363 AllowTypoCorrection); 11364 11365 switch (OverloadResult) { 11366 case OR_Success: { 11367 FunctionDecl *FDecl = (*Best)->Function; 11368 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 11369 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 11370 return ExprError(); 11371 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11372 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11373 ExecConfig); 11374 } 11375 11376 case OR_No_Viable_Function: { 11377 // Try to recover by looking for viable functions which the user might 11378 // have meant to call. 11379 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 11380 Args, RParenLoc, 11381 /*EmptyLookup=*/false, 11382 AllowTypoCorrection); 11383 if (!Recovery.isInvalid()) 11384 return Recovery; 11385 11386 // If the user passes in a function that we can't take the address of, we 11387 // generally end up emitting really bad error messages. Here, we attempt to 11388 // emit better ones. 11389 for (const Expr *Arg : Args) { 11390 if (!Arg->getType()->isFunctionType()) 11391 continue; 11392 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 11393 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 11394 if (FD && 11395 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11396 Arg->getExprLoc())) 11397 return ExprError(); 11398 } 11399 } 11400 11401 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call) 11402 << ULE->getName() << Fn->getSourceRange(); 11403 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11404 break; 11405 } 11406 11407 case OR_Ambiguous: 11408 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 11409 << ULE->getName() << Fn->getSourceRange(); 11410 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 11411 break; 11412 11413 case OR_Deleted: { 11414 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 11415 << (*Best)->Function->isDeleted() 11416 << ULE->getName() 11417 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 11418 << Fn->getSourceRange(); 11419 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11420 11421 // We emitted an error for the unvailable/deleted function call but keep 11422 // the call in the AST. 11423 FunctionDecl *FDecl = (*Best)->Function; 11424 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11425 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11426 ExecConfig); 11427 } 11428 } 11429 11430 // Overload resolution failed. 11431 return ExprError(); 11432 } 11433 11434 static void markUnaddressableCandidatesUnviable(Sema &S, 11435 OverloadCandidateSet &CS) { 11436 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 11437 if (I->Viable && 11438 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 11439 I->Viable = false; 11440 I->FailureKind = ovl_fail_addr_not_available; 11441 } 11442 } 11443 } 11444 11445 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 11446 /// (which eventually refers to the declaration Func) and the call 11447 /// arguments Args/NumArgs, attempt to resolve the function call down 11448 /// to a specific function. If overload resolution succeeds, returns 11449 /// the call expression produced by overload resolution. 11450 /// Otherwise, emits diagnostics and returns ExprError. 11451 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 11452 UnresolvedLookupExpr *ULE, 11453 SourceLocation LParenLoc, 11454 MultiExprArg Args, 11455 SourceLocation RParenLoc, 11456 Expr *ExecConfig, 11457 bool AllowTypoCorrection, 11458 bool CalleesAddressIsTaken) { 11459 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 11460 OverloadCandidateSet::CSK_Normal); 11461 ExprResult result; 11462 11463 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 11464 &result)) 11465 return result; 11466 11467 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 11468 // functions that aren't addressible are considered unviable. 11469 if (CalleesAddressIsTaken) 11470 markUnaddressableCandidatesUnviable(*this, CandidateSet); 11471 11472 OverloadCandidateSet::iterator Best; 11473 OverloadingResult OverloadResult = 11474 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 11475 11476 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 11477 RParenLoc, ExecConfig, &CandidateSet, 11478 &Best, OverloadResult, 11479 AllowTypoCorrection); 11480 } 11481 11482 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 11483 return Functions.size() > 1 || 11484 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 11485 } 11486 11487 /// \brief Create a unary operation that may resolve to an overloaded 11488 /// operator. 11489 /// 11490 /// \param OpLoc The location of the operator itself (e.g., '*'). 11491 /// 11492 /// \param Opc The UnaryOperatorKind that describes this operator. 11493 /// 11494 /// \param Fns The set of non-member functions that will be 11495 /// considered by overload resolution. The caller needs to build this 11496 /// set based on the context using, e.g., 11497 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11498 /// set should not contain any member functions; those will be added 11499 /// by CreateOverloadedUnaryOp(). 11500 /// 11501 /// \param Input The input argument. 11502 ExprResult 11503 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 11504 const UnresolvedSetImpl &Fns, 11505 Expr *Input) { 11506 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 11507 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 11508 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11509 // TODO: provide better source location info. 11510 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11511 11512 if (checkPlaceholderForOverload(*this, Input)) 11513 return ExprError(); 11514 11515 Expr *Args[2] = { Input, nullptr }; 11516 unsigned NumArgs = 1; 11517 11518 // For post-increment and post-decrement, add the implicit '0' as 11519 // the second argument, so that we know this is a post-increment or 11520 // post-decrement. 11521 if (Opc == UO_PostInc || Opc == UO_PostDec) { 11522 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 11523 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 11524 SourceLocation()); 11525 NumArgs = 2; 11526 } 11527 11528 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 11529 11530 if (Input->isTypeDependent()) { 11531 if (Fns.empty()) 11532 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 11533 VK_RValue, OK_Ordinary, OpLoc); 11534 11535 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11536 UnresolvedLookupExpr *Fn 11537 = UnresolvedLookupExpr::Create(Context, NamingClass, 11538 NestedNameSpecifierLoc(), OpNameInfo, 11539 /*ADL*/ true, IsOverloaded(Fns), 11540 Fns.begin(), Fns.end()); 11541 return new (Context) 11542 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 11543 VK_RValue, OpLoc, false); 11544 } 11545 11546 // Build an empty overload set. 11547 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11548 11549 // Add the candidates from the given function set. 11550 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 11551 11552 // Add operator candidates that are member functions. 11553 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11554 11555 // Add candidates from ADL. 11556 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 11557 /*ExplicitTemplateArgs*/nullptr, 11558 CandidateSet); 11559 11560 // Add builtin operator candidates. 11561 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11562 11563 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11564 11565 // Perform overload resolution. 11566 OverloadCandidateSet::iterator Best; 11567 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11568 case OR_Success: { 11569 // We found a built-in operator or an overloaded operator. 11570 FunctionDecl *FnDecl = Best->Function; 11571 11572 if (FnDecl) { 11573 // We matched an overloaded operator. Build a call to that 11574 // operator. 11575 11576 // Convert the arguments. 11577 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11578 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 11579 11580 ExprResult InputRes = 11581 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 11582 Best->FoundDecl, Method); 11583 if (InputRes.isInvalid()) 11584 return ExprError(); 11585 Input = InputRes.get(); 11586 } else { 11587 // Convert the arguments. 11588 ExprResult InputInit 11589 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11590 Context, 11591 FnDecl->getParamDecl(0)), 11592 SourceLocation(), 11593 Input); 11594 if (InputInit.isInvalid()) 11595 return ExprError(); 11596 Input = InputInit.get(); 11597 } 11598 11599 // Build the actual expression node. 11600 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 11601 HadMultipleCandidates, OpLoc); 11602 if (FnExpr.isInvalid()) 11603 return ExprError(); 11604 11605 // Determine the result type. 11606 QualType ResultTy = FnDecl->getReturnType(); 11607 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11608 ResultTy = ResultTy.getNonLValueExprType(Context); 11609 11610 Args[0] = Input; 11611 CallExpr *TheCall = 11612 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 11613 ResultTy, VK, OpLoc, false); 11614 11615 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 11616 return ExprError(); 11617 11618 return MaybeBindToTemporary(TheCall); 11619 } else { 11620 // We matched a built-in operator. Convert the arguments, then 11621 // break out so that we will build the appropriate built-in 11622 // operator node. 11623 ExprResult InputRes = 11624 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 11625 Best->Conversions[0], AA_Passing); 11626 if (InputRes.isInvalid()) 11627 return ExprError(); 11628 Input = InputRes.get(); 11629 break; 11630 } 11631 } 11632 11633 case OR_No_Viable_Function: 11634 // This is an erroneous use of an operator which can be overloaded by 11635 // a non-member function. Check for non-member operators which were 11636 // defined too late to be candidates. 11637 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 11638 // FIXME: Recover by calling the found function. 11639 return ExprError(); 11640 11641 // No viable function; fall through to handling this as a 11642 // built-in operator, which will produce an error message for us. 11643 break; 11644 11645 case OR_Ambiguous: 11646 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11647 << UnaryOperator::getOpcodeStr(Opc) 11648 << Input->getType() 11649 << Input->getSourceRange(); 11650 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 11651 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11652 return ExprError(); 11653 11654 case OR_Deleted: 11655 Diag(OpLoc, diag::err_ovl_deleted_oper) 11656 << Best->Function->isDeleted() 11657 << UnaryOperator::getOpcodeStr(Opc) 11658 << getDeletedOrUnavailableSuffix(Best->Function) 11659 << Input->getSourceRange(); 11660 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 11661 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11662 return ExprError(); 11663 } 11664 11665 // Either we found no viable overloaded operator or we matched a 11666 // built-in operator. In either case, fall through to trying to 11667 // build a built-in operation. 11668 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11669 } 11670 11671 /// \brief Create a binary operation that may resolve to an overloaded 11672 /// operator. 11673 /// 11674 /// \param OpLoc The location of the operator itself (e.g., '+'). 11675 /// 11676 /// \param Opc The BinaryOperatorKind that describes this operator. 11677 /// 11678 /// \param Fns The set of non-member functions that will be 11679 /// considered by overload resolution. The caller needs to build this 11680 /// set based on the context using, e.g., 11681 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11682 /// set should not contain any member functions; those will be added 11683 /// by CreateOverloadedBinOp(). 11684 /// 11685 /// \param LHS Left-hand argument. 11686 /// \param RHS Right-hand argument. 11687 ExprResult 11688 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 11689 BinaryOperatorKind Opc, 11690 const UnresolvedSetImpl &Fns, 11691 Expr *LHS, Expr *RHS) { 11692 Expr *Args[2] = { LHS, RHS }; 11693 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 11694 11695 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 11696 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11697 11698 // If either side is type-dependent, create an appropriate dependent 11699 // expression. 11700 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11701 if (Fns.empty()) { 11702 // If there are no functions to store, just build a dependent 11703 // BinaryOperator or CompoundAssignment. 11704 if (Opc <= BO_Assign || Opc > BO_OrAssign) 11705 return new (Context) BinaryOperator( 11706 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 11707 OpLoc, FPFeatures.fp_contract); 11708 11709 return new (Context) CompoundAssignOperator( 11710 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 11711 Context.DependentTy, Context.DependentTy, OpLoc, 11712 FPFeatures.fp_contract); 11713 } 11714 11715 // FIXME: save results of ADL from here? 11716 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11717 // TODO: provide better source location info in DNLoc component. 11718 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11719 UnresolvedLookupExpr *Fn 11720 = UnresolvedLookupExpr::Create(Context, NamingClass, 11721 NestedNameSpecifierLoc(), OpNameInfo, 11722 /*ADL*/ true, IsOverloaded(Fns), 11723 Fns.begin(), Fns.end()); 11724 return new (Context) 11725 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 11726 VK_RValue, OpLoc, FPFeatures.fp_contract); 11727 } 11728 11729 // Always do placeholder-like conversions on the RHS. 11730 if (checkPlaceholderForOverload(*this, Args[1])) 11731 return ExprError(); 11732 11733 // Do placeholder-like conversion on the LHS; note that we should 11734 // not get here with a PseudoObject LHS. 11735 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 11736 if (checkPlaceholderForOverload(*this, Args[0])) 11737 return ExprError(); 11738 11739 // If this is the assignment operator, we only perform overload resolution 11740 // if the left-hand side is a class or enumeration type. This is actually 11741 // a hack. The standard requires that we do overload resolution between the 11742 // various built-in candidates, but as DR507 points out, this can lead to 11743 // problems. So we do it this way, which pretty much follows what GCC does. 11744 // Note that we go the traditional code path for compound assignment forms. 11745 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 11746 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11747 11748 // If this is the .* operator, which is not overloadable, just 11749 // create a built-in binary operator. 11750 if (Opc == BO_PtrMemD) 11751 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11752 11753 // Build an empty overload set. 11754 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11755 11756 // Add the candidates from the given function set. 11757 AddFunctionCandidates(Fns, Args, CandidateSet); 11758 11759 // Add operator candidates that are member functions. 11760 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11761 11762 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 11763 // performed for an assignment operator (nor for operator[] nor operator->, 11764 // which don't get here). 11765 if (Opc != BO_Assign) 11766 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 11767 /*ExplicitTemplateArgs*/ nullptr, 11768 CandidateSet); 11769 11770 // Add builtin operator candidates. 11771 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11772 11773 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11774 11775 // Perform overload resolution. 11776 OverloadCandidateSet::iterator Best; 11777 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11778 case OR_Success: { 11779 // We found a built-in operator or an overloaded operator. 11780 FunctionDecl *FnDecl = Best->Function; 11781 11782 if (FnDecl) { 11783 // We matched an overloaded operator. Build a call to that 11784 // operator. 11785 11786 // Convert the arguments. 11787 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11788 // Best->Access is only meaningful for class members. 11789 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 11790 11791 ExprResult Arg1 = 11792 PerformCopyInitialization( 11793 InitializedEntity::InitializeParameter(Context, 11794 FnDecl->getParamDecl(0)), 11795 SourceLocation(), Args[1]); 11796 if (Arg1.isInvalid()) 11797 return ExprError(); 11798 11799 ExprResult Arg0 = 11800 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11801 Best->FoundDecl, Method); 11802 if (Arg0.isInvalid()) 11803 return ExprError(); 11804 Args[0] = Arg0.getAs<Expr>(); 11805 Args[1] = RHS = Arg1.getAs<Expr>(); 11806 } else { 11807 // Convert the arguments. 11808 ExprResult Arg0 = PerformCopyInitialization( 11809 InitializedEntity::InitializeParameter(Context, 11810 FnDecl->getParamDecl(0)), 11811 SourceLocation(), Args[0]); 11812 if (Arg0.isInvalid()) 11813 return ExprError(); 11814 11815 ExprResult Arg1 = 11816 PerformCopyInitialization( 11817 InitializedEntity::InitializeParameter(Context, 11818 FnDecl->getParamDecl(1)), 11819 SourceLocation(), Args[1]); 11820 if (Arg1.isInvalid()) 11821 return ExprError(); 11822 Args[0] = LHS = Arg0.getAs<Expr>(); 11823 Args[1] = RHS = Arg1.getAs<Expr>(); 11824 } 11825 11826 // Build the actual expression node. 11827 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11828 Best->FoundDecl, 11829 HadMultipleCandidates, OpLoc); 11830 if (FnExpr.isInvalid()) 11831 return ExprError(); 11832 11833 // Determine the result type. 11834 QualType ResultTy = FnDecl->getReturnType(); 11835 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11836 ResultTy = ResultTy.getNonLValueExprType(Context); 11837 11838 CXXOperatorCallExpr *TheCall = 11839 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 11840 Args, ResultTy, VK, OpLoc, 11841 FPFeatures.fp_contract); 11842 11843 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 11844 FnDecl)) 11845 return ExprError(); 11846 11847 ArrayRef<const Expr *> ArgsArray(Args, 2); 11848 // Cut off the implicit 'this'. 11849 if (isa<CXXMethodDecl>(FnDecl)) 11850 ArgsArray = ArgsArray.slice(1); 11851 11852 // Check for a self move. 11853 if (Op == OO_Equal) 11854 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 11855 11856 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc, 11857 TheCall->getSourceRange(), VariadicDoesNotApply); 11858 11859 return MaybeBindToTemporary(TheCall); 11860 } else { 11861 // We matched a built-in operator. Convert the arguments, then 11862 // break out so that we will build the appropriate built-in 11863 // operator node. 11864 ExprResult ArgsRes0 = 11865 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11866 Best->Conversions[0], AA_Passing); 11867 if (ArgsRes0.isInvalid()) 11868 return ExprError(); 11869 Args[0] = ArgsRes0.get(); 11870 11871 ExprResult ArgsRes1 = 11872 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11873 Best->Conversions[1], AA_Passing); 11874 if (ArgsRes1.isInvalid()) 11875 return ExprError(); 11876 Args[1] = ArgsRes1.get(); 11877 break; 11878 } 11879 } 11880 11881 case OR_No_Viable_Function: { 11882 // C++ [over.match.oper]p9: 11883 // If the operator is the operator , [...] and there are no 11884 // viable functions, then the operator is assumed to be the 11885 // built-in operator and interpreted according to clause 5. 11886 if (Opc == BO_Comma) 11887 break; 11888 11889 // For class as left operand for assignment or compound assigment 11890 // operator do not fall through to handling in built-in, but report that 11891 // no overloaded assignment operator found 11892 ExprResult Result = ExprError(); 11893 if (Args[0]->getType()->isRecordType() && 11894 Opc >= BO_Assign && Opc <= BO_OrAssign) { 11895 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11896 << BinaryOperator::getOpcodeStr(Opc) 11897 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11898 if (Args[0]->getType()->isIncompleteType()) { 11899 Diag(OpLoc, diag::note_assign_lhs_incomplete) 11900 << Args[0]->getType() 11901 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11902 } 11903 } else { 11904 // This is an erroneous use of an operator which can be overloaded by 11905 // a non-member function. Check for non-member operators which were 11906 // defined too late to be candidates. 11907 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 11908 // FIXME: Recover by calling the found function. 11909 return ExprError(); 11910 11911 // No viable function; try to create a built-in operation, which will 11912 // produce an error. Then, show the non-viable candidates. 11913 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11914 } 11915 assert(Result.isInvalid() && 11916 "C++ binary operator overloading is missing candidates!"); 11917 if (Result.isInvalid()) 11918 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11919 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11920 return Result; 11921 } 11922 11923 case OR_Ambiguous: 11924 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 11925 << BinaryOperator::getOpcodeStr(Opc) 11926 << Args[0]->getType() << Args[1]->getType() 11927 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11928 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11929 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11930 return ExprError(); 11931 11932 case OR_Deleted: 11933 if (isImplicitlyDeleted(Best->Function)) { 11934 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11935 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 11936 << Context.getRecordType(Method->getParent()) 11937 << getSpecialMember(Method); 11938 11939 // The user probably meant to call this special member. Just 11940 // explain why it's deleted. 11941 NoteDeletedFunction(Method); 11942 return ExprError(); 11943 } else { 11944 Diag(OpLoc, diag::err_ovl_deleted_oper) 11945 << Best->Function->isDeleted() 11946 << BinaryOperator::getOpcodeStr(Opc) 11947 << getDeletedOrUnavailableSuffix(Best->Function) 11948 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11949 } 11950 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11951 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11952 return ExprError(); 11953 } 11954 11955 // We matched a built-in operator; build it. 11956 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11957 } 11958 11959 ExprResult 11960 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 11961 SourceLocation RLoc, 11962 Expr *Base, Expr *Idx) { 11963 Expr *Args[2] = { Base, Idx }; 11964 DeclarationName OpName = 11965 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 11966 11967 // If either side is type-dependent, create an appropriate dependent 11968 // expression. 11969 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11970 11971 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11972 // CHECKME: no 'operator' keyword? 11973 DeclarationNameInfo OpNameInfo(OpName, LLoc); 11974 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11975 UnresolvedLookupExpr *Fn 11976 = UnresolvedLookupExpr::Create(Context, NamingClass, 11977 NestedNameSpecifierLoc(), OpNameInfo, 11978 /*ADL*/ true, /*Overloaded*/ false, 11979 UnresolvedSetIterator(), 11980 UnresolvedSetIterator()); 11981 // Can't add any actual overloads yet 11982 11983 return new (Context) 11984 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 11985 Context.DependentTy, VK_RValue, RLoc, false); 11986 } 11987 11988 // Handle placeholders on both operands. 11989 if (checkPlaceholderForOverload(*this, Args[0])) 11990 return ExprError(); 11991 if (checkPlaceholderForOverload(*this, Args[1])) 11992 return ExprError(); 11993 11994 // Build an empty overload set. 11995 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 11996 11997 // Subscript can only be overloaded as a member function. 11998 11999 // Add operator candidates that are member functions. 12000 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12001 12002 // Add builtin operator candidates. 12003 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12004 12005 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12006 12007 // Perform overload resolution. 12008 OverloadCandidateSet::iterator Best; 12009 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 12010 case OR_Success: { 12011 // We found a built-in operator or an overloaded operator. 12012 FunctionDecl *FnDecl = Best->Function; 12013 12014 if (FnDecl) { 12015 // We matched an overloaded operator. Build a call to that 12016 // operator. 12017 12018 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 12019 12020 // Convert the arguments. 12021 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 12022 ExprResult Arg0 = 12023 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12024 Best->FoundDecl, Method); 12025 if (Arg0.isInvalid()) 12026 return ExprError(); 12027 Args[0] = Arg0.get(); 12028 12029 // Convert the arguments. 12030 ExprResult InputInit 12031 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12032 Context, 12033 FnDecl->getParamDecl(0)), 12034 SourceLocation(), 12035 Args[1]); 12036 if (InputInit.isInvalid()) 12037 return ExprError(); 12038 12039 Args[1] = InputInit.getAs<Expr>(); 12040 12041 // Build the actual expression node. 12042 DeclarationNameInfo OpLocInfo(OpName, LLoc); 12043 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12044 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12045 Best->FoundDecl, 12046 HadMultipleCandidates, 12047 OpLocInfo.getLoc(), 12048 OpLocInfo.getInfo()); 12049 if (FnExpr.isInvalid()) 12050 return ExprError(); 12051 12052 // Determine the result type 12053 QualType ResultTy = FnDecl->getReturnType(); 12054 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12055 ResultTy = ResultTy.getNonLValueExprType(Context); 12056 12057 CXXOperatorCallExpr *TheCall = 12058 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 12059 FnExpr.get(), Args, 12060 ResultTy, VK, RLoc, 12061 false); 12062 12063 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 12064 return ExprError(); 12065 12066 return MaybeBindToTemporary(TheCall); 12067 } else { 12068 // We matched a built-in operator. Convert the arguments, then 12069 // break out so that we will build the appropriate built-in 12070 // operator node. 12071 ExprResult ArgsRes0 = 12072 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 12073 Best->Conversions[0], AA_Passing); 12074 if (ArgsRes0.isInvalid()) 12075 return ExprError(); 12076 Args[0] = ArgsRes0.get(); 12077 12078 ExprResult ArgsRes1 = 12079 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 12080 Best->Conversions[1], AA_Passing); 12081 if (ArgsRes1.isInvalid()) 12082 return ExprError(); 12083 Args[1] = ArgsRes1.get(); 12084 12085 break; 12086 } 12087 } 12088 12089 case OR_No_Viable_Function: { 12090 if (CandidateSet.empty()) 12091 Diag(LLoc, diag::err_ovl_no_oper) 12092 << Args[0]->getType() << /*subscript*/ 0 12093 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12094 else 12095 Diag(LLoc, diag::err_ovl_no_viable_subscript) 12096 << Args[0]->getType() 12097 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12098 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12099 "[]", LLoc); 12100 return ExprError(); 12101 } 12102 12103 case OR_Ambiguous: 12104 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 12105 << "[]" 12106 << Args[0]->getType() << Args[1]->getType() 12107 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12108 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12109 "[]", LLoc); 12110 return ExprError(); 12111 12112 case OR_Deleted: 12113 Diag(LLoc, diag::err_ovl_deleted_oper) 12114 << Best->Function->isDeleted() << "[]" 12115 << getDeletedOrUnavailableSuffix(Best->Function) 12116 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12117 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12118 "[]", LLoc); 12119 return ExprError(); 12120 } 12121 12122 // We matched a built-in operator; build it. 12123 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 12124 } 12125 12126 /// BuildCallToMemberFunction - Build a call to a member 12127 /// function. MemExpr is the expression that refers to the member 12128 /// function (and includes the object parameter), Args/NumArgs are the 12129 /// arguments to the function call (not including the object 12130 /// parameter). The caller needs to validate that the member 12131 /// expression refers to a non-static member function or an overloaded 12132 /// member function. 12133 ExprResult 12134 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 12135 SourceLocation LParenLoc, 12136 MultiExprArg Args, 12137 SourceLocation RParenLoc) { 12138 assert(MemExprE->getType() == Context.BoundMemberTy || 12139 MemExprE->getType() == Context.OverloadTy); 12140 12141 // Dig out the member expression. This holds both the object 12142 // argument and the member function we're referring to. 12143 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12144 12145 // Determine whether this is a call to a pointer-to-member function. 12146 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12147 assert(op->getType() == Context.BoundMemberTy); 12148 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12149 12150 QualType fnType = 12151 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12152 12153 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12154 QualType resultType = proto->getCallResultType(Context); 12155 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12156 12157 // Check that the object type isn't more qualified than the 12158 // member function we're calling. 12159 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 12160 12161 QualType objectType = op->getLHS()->getType(); 12162 if (op->getOpcode() == BO_PtrMemI) 12163 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12164 Qualifiers objectQuals = objectType.getQualifiers(); 12165 12166 Qualifiers difference = objectQuals - funcQuals; 12167 difference.removeObjCGCAttr(); 12168 difference.removeAddressSpace(); 12169 if (difference) { 12170 std::string qualsString = difference.getAsString(); 12171 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12172 << fnType.getUnqualifiedType() 12173 << qualsString 12174 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12175 } 12176 12177 CXXMemberCallExpr *call 12178 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12179 resultType, valueKind, RParenLoc); 12180 12181 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 12182 call, nullptr)) 12183 return ExprError(); 12184 12185 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12186 return ExprError(); 12187 12188 if (CheckOtherCall(call, proto)) 12189 return ExprError(); 12190 12191 return MaybeBindToTemporary(call); 12192 } 12193 12194 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 12195 return new (Context) 12196 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 12197 12198 UnbridgedCastsSet UnbridgedCasts; 12199 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12200 return ExprError(); 12201 12202 MemberExpr *MemExpr; 12203 CXXMethodDecl *Method = nullptr; 12204 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 12205 NestedNameSpecifier *Qualifier = nullptr; 12206 if (isa<MemberExpr>(NakedMemExpr)) { 12207 MemExpr = cast<MemberExpr>(NakedMemExpr); 12208 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 12209 FoundDecl = MemExpr->getFoundDecl(); 12210 Qualifier = MemExpr->getQualifier(); 12211 UnbridgedCasts.restore(); 12212 } else { 12213 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 12214 Qualifier = UnresExpr->getQualifier(); 12215 12216 QualType ObjectType = UnresExpr->getBaseType(); 12217 Expr::Classification ObjectClassification 12218 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 12219 : UnresExpr->getBase()->Classify(Context); 12220 12221 // Add overload candidates 12222 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 12223 OverloadCandidateSet::CSK_Normal); 12224 12225 // FIXME: avoid copy. 12226 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12227 if (UnresExpr->hasExplicitTemplateArgs()) { 12228 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12229 TemplateArgs = &TemplateArgsBuffer; 12230 } 12231 12232 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 12233 E = UnresExpr->decls_end(); I != E; ++I) { 12234 12235 NamedDecl *Func = *I; 12236 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 12237 if (isa<UsingShadowDecl>(Func)) 12238 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 12239 12240 12241 // Microsoft supports direct constructor calls. 12242 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 12243 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 12244 Args, CandidateSet); 12245 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 12246 // If explicit template arguments were provided, we can't call a 12247 // non-template member function. 12248 if (TemplateArgs) 12249 continue; 12250 12251 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 12252 ObjectClassification, Args, CandidateSet, 12253 /*SuppressUserConversions=*/false); 12254 } else { 12255 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 12256 I.getPair(), ActingDC, TemplateArgs, 12257 ObjectType, ObjectClassification, 12258 Args, CandidateSet, 12259 /*SuppressUsedConversions=*/false); 12260 } 12261 } 12262 12263 DeclarationName DeclName = UnresExpr->getMemberName(); 12264 12265 UnbridgedCasts.restore(); 12266 12267 OverloadCandidateSet::iterator Best; 12268 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 12269 Best)) { 12270 case OR_Success: 12271 Method = cast<CXXMethodDecl>(Best->Function); 12272 FoundDecl = Best->FoundDecl; 12273 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 12274 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 12275 return ExprError(); 12276 // If FoundDecl is different from Method (such as if one is a template 12277 // and the other a specialization), make sure DiagnoseUseOfDecl is 12278 // called on both. 12279 // FIXME: This would be more comprehensively addressed by modifying 12280 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 12281 // being used. 12282 if (Method != FoundDecl.getDecl() && 12283 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 12284 return ExprError(); 12285 break; 12286 12287 case OR_No_Viable_Function: 12288 Diag(UnresExpr->getMemberLoc(), 12289 diag::err_ovl_no_viable_member_function_in_call) 12290 << DeclName << MemExprE->getSourceRange(); 12291 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12292 // FIXME: Leaking incoming expressions! 12293 return ExprError(); 12294 12295 case OR_Ambiguous: 12296 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 12297 << DeclName << MemExprE->getSourceRange(); 12298 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12299 // FIXME: Leaking incoming expressions! 12300 return ExprError(); 12301 12302 case OR_Deleted: 12303 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 12304 << Best->Function->isDeleted() 12305 << DeclName 12306 << getDeletedOrUnavailableSuffix(Best->Function) 12307 << MemExprE->getSourceRange(); 12308 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12309 // FIXME: Leaking incoming expressions! 12310 return ExprError(); 12311 } 12312 12313 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 12314 12315 // If overload resolution picked a static member, build a 12316 // non-member call based on that function. 12317 if (Method->isStatic()) { 12318 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 12319 RParenLoc); 12320 } 12321 12322 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 12323 } 12324 12325 QualType ResultType = Method->getReturnType(); 12326 ExprValueKind VK = Expr::getValueKindForType(ResultType); 12327 ResultType = ResultType.getNonLValueExprType(Context); 12328 12329 assert(Method && "Member call to something that isn't a method?"); 12330 CXXMemberCallExpr *TheCall = 12331 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12332 ResultType, VK, RParenLoc); 12333 12334 // (CUDA B.1): Check for invalid calls between targets. 12335 if (getLangOpts().CUDA) { 12336 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) { 12337 if (CheckCUDATarget(Caller, Method)) { 12338 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target) 12339 << IdentifyCUDATarget(Method) << Method->getIdentifier() 12340 << IdentifyCUDATarget(Caller); 12341 return ExprError(); 12342 } 12343 } 12344 } 12345 12346 // Check for a valid return type. 12347 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 12348 TheCall, Method)) 12349 return ExprError(); 12350 12351 // Convert the object argument (for a non-static member function call). 12352 // We only need to do this if there was actually an overload; otherwise 12353 // it was done at lookup. 12354 if (!Method->isStatic()) { 12355 ExprResult ObjectArg = 12356 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 12357 FoundDecl, Method); 12358 if (ObjectArg.isInvalid()) 12359 return ExprError(); 12360 MemExpr->setBase(ObjectArg.get()); 12361 } 12362 12363 // Convert the rest of the arguments 12364 const FunctionProtoType *Proto = 12365 Method->getType()->getAs<FunctionProtoType>(); 12366 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 12367 RParenLoc)) 12368 return ExprError(); 12369 12370 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12371 12372 if (CheckFunctionCall(Method, TheCall, Proto)) 12373 return ExprError(); 12374 12375 // In the case the method to call was not selected by the overloading 12376 // resolution process, we still need to handle the enable_if attribute. Do 12377 // that here, so it will not hide previous -- and more relevant -- errors 12378 if (isa<MemberExpr>(NakedMemExpr)) { 12379 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 12380 Diag(MemExprE->getLocStart(), 12381 diag::err_ovl_no_viable_member_function_in_call) 12382 << Method << Method->getSourceRange(); 12383 Diag(Method->getLocation(), 12384 diag::note_ovl_candidate_disabled_by_enable_if_attr) 12385 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 12386 return ExprError(); 12387 } 12388 } 12389 12390 if ((isa<CXXConstructorDecl>(CurContext) || 12391 isa<CXXDestructorDecl>(CurContext)) && 12392 TheCall->getMethodDecl()->isPure()) { 12393 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 12394 12395 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 12396 MemExpr->performsVirtualDispatch(getLangOpts())) { 12397 Diag(MemExpr->getLocStart(), 12398 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 12399 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 12400 << MD->getParent()->getDeclName(); 12401 12402 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 12403 if (getLangOpts().AppleKext) 12404 Diag(MemExpr->getLocStart(), 12405 diag::note_pure_qualified_call_kext) 12406 << MD->getParent()->getDeclName() 12407 << MD->getDeclName(); 12408 } 12409 } 12410 12411 if (CXXDestructorDecl *DD = 12412 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 12413 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 12414 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 12415 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false, 12416 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 12417 MemExpr->getMemberLoc()); 12418 } 12419 12420 return MaybeBindToTemporary(TheCall); 12421 } 12422 12423 /// BuildCallToObjectOfClassType - Build a call to an object of class 12424 /// type (C++ [over.call.object]), which can end up invoking an 12425 /// overloaded function call operator (@c operator()) or performing a 12426 /// user-defined conversion on the object argument. 12427 ExprResult 12428 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 12429 SourceLocation LParenLoc, 12430 MultiExprArg Args, 12431 SourceLocation RParenLoc) { 12432 if (checkPlaceholderForOverload(*this, Obj)) 12433 return ExprError(); 12434 ExprResult Object = Obj; 12435 12436 UnbridgedCastsSet UnbridgedCasts; 12437 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12438 return ExprError(); 12439 12440 assert(Object.get()->getType()->isRecordType() && 12441 "Requires object type argument"); 12442 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 12443 12444 // C++ [over.call.object]p1: 12445 // If the primary-expression E in the function call syntax 12446 // evaluates to a class object of type "cv T", then the set of 12447 // candidate functions includes at least the function call 12448 // operators of T. The function call operators of T are obtained by 12449 // ordinary lookup of the name operator() in the context of 12450 // (E).operator(). 12451 OverloadCandidateSet CandidateSet(LParenLoc, 12452 OverloadCandidateSet::CSK_Operator); 12453 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 12454 12455 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 12456 diag::err_incomplete_object_call, Object.get())) 12457 return true; 12458 12459 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 12460 LookupQualifiedName(R, Record->getDecl()); 12461 R.suppressDiagnostics(); 12462 12463 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12464 Oper != OperEnd; ++Oper) { 12465 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 12466 Object.get()->Classify(Context), 12467 Args, CandidateSet, 12468 /*SuppressUserConversions=*/ false); 12469 } 12470 12471 // C++ [over.call.object]p2: 12472 // In addition, for each (non-explicit in C++0x) conversion function 12473 // declared in T of the form 12474 // 12475 // operator conversion-type-id () cv-qualifier; 12476 // 12477 // where cv-qualifier is the same cv-qualification as, or a 12478 // greater cv-qualification than, cv, and where conversion-type-id 12479 // denotes the type "pointer to function of (P1,...,Pn) returning 12480 // R", or the type "reference to pointer to function of 12481 // (P1,...,Pn) returning R", or the type "reference to function 12482 // of (P1,...,Pn) returning R", a surrogate call function [...] 12483 // is also considered as a candidate function. Similarly, 12484 // surrogate call functions are added to the set of candidate 12485 // functions for each conversion function declared in an 12486 // accessible base class provided the function is not hidden 12487 // within T by another intervening declaration. 12488 const auto &Conversions = 12489 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 12490 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 12491 NamedDecl *D = *I; 12492 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 12493 if (isa<UsingShadowDecl>(D)) 12494 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 12495 12496 // Skip over templated conversion functions; they aren't 12497 // surrogates. 12498 if (isa<FunctionTemplateDecl>(D)) 12499 continue; 12500 12501 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 12502 if (!Conv->isExplicit()) { 12503 // Strip the reference type (if any) and then the pointer type (if 12504 // any) to get down to what might be a function type. 12505 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 12506 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 12507 ConvType = ConvPtrType->getPointeeType(); 12508 12509 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 12510 { 12511 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 12512 Object.get(), Args, CandidateSet); 12513 } 12514 } 12515 } 12516 12517 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12518 12519 // Perform overload resolution. 12520 OverloadCandidateSet::iterator Best; 12521 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 12522 Best)) { 12523 case OR_Success: 12524 // Overload resolution succeeded; we'll build the appropriate call 12525 // below. 12526 break; 12527 12528 case OR_No_Viable_Function: 12529 if (CandidateSet.empty()) 12530 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 12531 << Object.get()->getType() << /*call*/ 1 12532 << Object.get()->getSourceRange(); 12533 else 12534 Diag(Object.get()->getLocStart(), 12535 diag::err_ovl_no_viable_object_call) 12536 << Object.get()->getType() << Object.get()->getSourceRange(); 12537 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12538 break; 12539 12540 case OR_Ambiguous: 12541 Diag(Object.get()->getLocStart(), 12542 diag::err_ovl_ambiguous_object_call) 12543 << Object.get()->getType() << Object.get()->getSourceRange(); 12544 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12545 break; 12546 12547 case OR_Deleted: 12548 Diag(Object.get()->getLocStart(), 12549 diag::err_ovl_deleted_object_call) 12550 << Best->Function->isDeleted() 12551 << Object.get()->getType() 12552 << getDeletedOrUnavailableSuffix(Best->Function) 12553 << Object.get()->getSourceRange(); 12554 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12555 break; 12556 } 12557 12558 if (Best == CandidateSet.end()) 12559 return true; 12560 12561 UnbridgedCasts.restore(); 12562 12563 if (Best->Function == nullptr) { 12564 // Since there is no function declaration, this is one of the 12565 // surrogate candidates. Dig out the conversion function. 12566 CXXConversionDecl *Conv 12567 = cast<CXXConversionDecl>( 12568 Best->Conversions[0].UserDefined.ConversionFunction); 12569 12570 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 12571 Best->FoundDecl); 12572 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 12573 return ExprError(); 12574 assert(Conv == Best->FoundDecl.getDecl() && 12575 "Found Decl & conversion-to-functionptr should be same, right?!"); 12576 // We selected one of the surrogate functions that converts the 12577 // object parameter to a function pointer. Perform the conversion 12578 // on the object argument, then let ActOnCallExpr finish the job. 12579 12580 // Create an implicit member expr to refer to the conversion operator. 12581 // and then call it. 12582 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 12583 Conv, HadMultipleCandidates); 12584 if (Call.isInvalid()) 12585 return ExprError(); 12586 // Record usage of conversion in an implicit cast. 12587 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 12588 CK_UserDefinedConversion, Call.get(), 12589 nullptr, VK_RValue); 12590 12591 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 12592 } 12593 12594 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 12595 12596 // We found an overloaded operator(). Build a CXXOperatorCallExpr 12597 // that calls this method, using Object for the implicit object 12598 // parameter and passing along the remaining arguments. 12599 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12600 12601 // An error diagnostic has already been printed when parsing the declaration. 12602 if (Method->isInvalidDecl()) 12603 return ExprError(); 12604 12605 const FunctionProtoType *Proto = 12606 Method->getType()->getAs<FunctionProtoType>(); 12607 12608 unsigned NumParams = Proto->getNumParams(); 12609 12610 DeclarationNameInfo OpLocInfo( 12611 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 12612 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 12613 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12614 HadMultipleCandidates, 12615 OpLocInfo.getLoc(), 12616 OpLocInfo.getInfo()); 12617 if (NewFn.isInvalid()) 12618 return true; 12619 12620 // Build the full argument list for the method call (the implicit object 12621 // parameter is placed at the beginning of the list). 12622 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]); 12623 MethodArgs[0] = Object.get(); 12624 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 12625 12626 // Once we've built TheCall, all of the expressions are properly 12627 // owned. 12628 QualType ResultTy = Method->getReturnType(); 12629 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12630 ResultTy = ResultTy.getNonLValueExprType(Context); 12631 12632 CXXOperatorCallExpr *TheCall = new (Context) 12633 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), 12634 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 12635 ResultTy, VK, RParenLoc, false); 12636 MethodArgs.reset(); 12637 12638 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 12639 return true; 12640 12641 // We may have default arguments. If so, we need to allocate more 12642 // slots in the call for them. 12643 if (Args.size() < NumParams) 12644 TheCall->setNumArgs(Context, NumParams + 1); 12645 12646 bool IsError = false; 12647 12648 // Initialize the implicit object parameter. 12649 ExprResult ObjRes = 12650 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 12651 Best->FoundDecl, Method); 12652 if (ObjRes.isInvalid()) 12653 IsError = true; 12654 else 12655 Object = ObjRes; 12656 TheCall->setArg(0, Object.get()); 12657 12658 // Check the argument types. 12659 for (unsigned i = 0; i != NumParams; i++) { 12660 Expr *Arg; 12661 if (i < Args.size()) { 12662 Arg = Args[i]; 12663 12664 // Pass the argument. 12665 12666 ExprResult InputInit 12667 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12668 Context, 12669 Method->getParamDecl(i)), 12670 SourceLocation(), Arg); 12671 12672 IsError |= InputInit.isInvalid(); 12673 Arg = InputInit.getAs<Expr>(); 12674 } else { 12675 ExprResult DefArg 12676 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 12677 if (DefArg.isInvalid()) { 12678 IsError = true; 12679 break; 12680 } 12681 12682 Arg = DefArg.getAs<Expr>(); 12683 } 12684 12685 TheCall->setArg(i + 1, Arg); 12686 } 12687 12688 // If this is a variadic call, handle args passed through "...". 12689 if (Proto->isVariadic()) { 12690 // Promote the arguments (C99 6.5.2.2p7). 12691 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 12692 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 12693 nullptr); 12694 IsError |= Arg.isInvalid(); 12695 TheCall->setArg(i + 1, Arg.get()); 12696 } 12697 } 12698 12699 if (IsError) return true; 12700 12701 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12702 12703 if (CheckFunctionCall(Method, TheCall, Proto)) 12704 return true; 12705 12706 return MaybeBindToTemporary(TheCall); 12707 } 12708 12709 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 12710 /// (if one exists), where @c Base is an expression of class type and 12711 /// @c Member is the name of the member we're trying to find. 12712 ExprResult 12713 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 12714 bool *NoArrowOperatorFound) { 12715 assert(Base->getType()->isRecordType() && 12716 "left-hand side must have class type"); 12717 12718 if (checkPlaceholderForOverload(*this, Base)) 12719 return ExprError(); 12720 12721 SourceLocation Loc = Base->getExprLoc(); 12722 12723 // C++ [over.ref]p1: 12724 // 12725 // [...] An expression x->m is interpreted as (x.operator->())->m 12726 // for a class object x of type T if T::operator->() exists and if 12727 // the operator is selected as the best match function by the 12728 // overload resolution mechanism (13.3). 12729 DeclarationName OpName = 12730 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 12731 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 12732 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 12733 12734 if (RequireCompleteType(Loc, Base->getType(), 12735 diag::err_typecheck_incomplete_tag, Base)) 12736 return ExprError(); 12737 12738 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 12739 LookupQualifiedName(R, BaseRecord->getDecl()); 12740 R.suppressDiagnostics(); 12741 12742 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12743 Oper != OperEnd; ++Oper) { 12744 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 12745 None, CandidateSet, /*SuppressUserConversions=*/false); 12746 } 12747 12748 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12749 12750 // Perform overload resolution. 12751 OverloadCandidateSet::iterator Best; 12752 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12753 case OR_Success: 12754 // Overload resolution succeeded; we'll build the call below. 12755 break; 12756 12757 case OR_No_Viable_Function: 12758 if (CandidateSet.empty()) { 12759 QualType BaseType = Base->getType(); 12760 if (NoArrowOperatorFound) { 12761 // Report this specific error to the caller instead of emitting a 12762 // diagnostic, as requested. 12763 *NoArrowOperatorFound = true; 12764 return ExprError(); 12765 } 12766 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 12767 << BaseType << Base->getSourceRange(); 12768 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 12769 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 12770 << FixItHint::CreateReplacement(OpLoc, "."); 12771 } 12772 } else 12773 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12774 << "operator->" << Base->getSourceRange(); 12775 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12776 return ExprError(); 12777 12778 case OR_Ambiguous: 12779 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12780 << "->" << Base->getType() << Base->getSourceRange(); 12781 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 12782 return ExprError(); 12783 12784 case OR_Deleted: 12785 Diag(OpLoc, diag::err_ovl_deleted_oper) 12786 << Best->Function->isDeleted() 12787 << "->" 12788 << getDeletedOrUnavailableSuffix(Best->Function) 12789 << Base->getSourceRange(); 12790 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12791 return ExprError(); 12792 } 12793 12794 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 12795 12796 // Convert the object parameter. 12797 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12798 ExprResult BaseResult = 12799 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 12800 Best->FoundDecl, Method); 12801 if (BaseResult.isInvalid()) 12802 return ExprError(); 12803 Base = BaseResult.get(); 12804 12805 // Build the operator call. 12806 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12807 HadMultipleCandidates, OpLoc); 12808 if (FnExpr.isInvalid()) 12809 return ExprError(); 12810 12811 QualType ResultTy = Method->getReturnType(); 12812 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12813 ResultTy = ResultTy.getNonLValueExprType(Context); 12814 CXXOperatorCallExpr *TheCall = 12815 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 12816 Base, ResultTy, VK, OpLoc, false); 12817 12818 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 12819 return ExprError(); 12820 12821 return MaybeBindToTemporary(TheCall); 12822 } 12823 12824 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 12825 /// a literal operator described by the provided lookup results. 12826 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 12827 DeclarationNameInfo &SuffixInfo, 12828 ArrayRef<Expr*> Args, 12829 SourceLocation LitEndLoc, 12830 TemplateArgumentListInfo *TemplateArgs) { 12831 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 12832 12833 OverloadCandidateSet CandidateSet(UDSuffixLoc, 12834 OverloadCandidateSet::CSK_Normal); 12835 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 12836 /*SuppressUserConversions=*/true); 12837 12838 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12839 12840 // Perform overload resolution. This will usually be trivial, but might need 12841 // to perform substitutions for a literal operator template. 12842 OverloadCandidateSet::iterator Best; 12843 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 12844 case OR_Success: 12845 case OR_Deleted: 12846 break; 12847 12848 case OR_No_Viable_Function: 12849 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 12850 << R.getLookupName(); 12851 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12852 return ExprError(); 12853 12854 case OR_Ambiguous: 12855 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 12856 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12857 return ExprError(); 12858 } 12859 12860 FunctionDecl *FD = Best->Function; 12861 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 12862 HadMultipleCandidates, 12863 SuffixInfo.getLoc(), 12864 SuffixInfo.getInfo()); 12865 if (Fn.isInvalid()) 12866 return true; 12867 12868 // Check the argument types. This should almost always be a no-op, except 12869 // that array-to-pointer decay is applied to string literals. 12870 Expr *ConvArgs[2]; 12871 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 12872 ExprResult InputInit = PerformCopyInitialization( 12873 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 12874 SourceLocation(), Args[ArgIdx]); 12875 if (InputInit.isInvalid()) 12876 return true; 12877 ConvArgs[ArgIdx] = InputInit.get(); 12878 } 12879 12880 QualType ResultTy = FD->getReturnType(); 12881 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12882 ResultTy = ResultTy.getNonLValueExprType(Context); 12883 12884 UserDefinedLiteral *UDL = 12885 new (Context) UserDefinedLiteral(Context, Fn.get(), 12886 llvm::makeArrayRef(ConvArgs, Args.size()), 12887 ResultTy, VK, LitEndLoc, UDSuffixLoc); 12888 12889 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 12890 return ExprError(); 12891 12892 if (CheckFunctionCall(FD, UDL, nullptr)) 12893 return ExprError(); 12894 12895 return MaybeBindToTemporary(UDL); 12896 } 12897 12898 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 12899 /// given LookupResult is non-empty, it is assumed to describe a member which 12900 /// will be invoked. Otherwise, the function will be found via argument 12901 /// dependent lookup. 12902 /// CallExpr is set to a valid expression and FRS_Success returned on success, 12903 /// otherwise CallExpr is set to ExprError() and some non-success value 12904 /// is returned. 12905 Sema::ForRangeStatus 12906 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 12907 SourceLocation RangeLoc, 12908 const DeclarationNameInfo &NameInfo, 12909 LookupResult &MemberLookup, 12910 OverloadCandidateSet *CandidateSet, 12911 Expr *Range, ExprResult *CallExpr) { 12912 Scope *S = nullptr; 12913 12914 CandidateSet->clear(); 12915 if (!MemberLookup.empty()) { 12916 ExprResult MemberRef = 12917 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 12918 /*IsPtr=*/false, CXXScopeSpec(), 12919 /*TemplateKWLoc=*/SourceLocation(), 12920 /*FirstQualifierInScope=*/nullptr, 12921 MemberLookup, 12922 /*TemplateArgs=*/nullptr, S); 12923 if (MemberRef.isInvalid()) { 12924 *CallExpr = ExprError(); 12925 return FRS_DiagnosticIssued; 12926 } 12927 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 12928 if (CallExpr->isInvalid()) { 12929 *CallExpr = ExprError(); 12930 return FRS_DiagnosticIssued; 12931 } 12932 } else { 12933 UnresolvedSet<0> FoundNames; 12934 UnresolvedLookupExpr *Fn = 12935 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 12936 NestedNameSpecifierLoc(), NameInfo, 12937 /*NeedsADL=*/true, /*Overloaded=*/false, 12938 FoundNames.begin(), FoundNames.end()); 12939 12940 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 12941 CandidateSet, CallExpr); 12942 if (CandidateSet->empty() || CandidateSetError) { 12943 *CallExpr = ExprError(); 12944 return FRS_NoViableFunction; 12945 } 12946 OverloadCandidateSet::iterator Best; 12947 OverloadingResult OverloadResult = 12948 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 12949 12950 if (OverloadResult == OR_No_Viable_Function) { 12951 *CallExpr = ExprError(); 12952 return FRS_NoViableFunction; 12953 } 12954 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 12955 Loc, nullptr, CandidateSet, &Best, 12956 OverloadResult, 12957 /*AllowTypoCorrection=*/false); 12958 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 12959 *CallExpr = ExprError(); 12960 return FRS_DiagnosticIssued; 12961 } 12962 } 12963 return FRS_Success; 12964 } 12965 12966 12967 /// FixOverloadedFunctionReference - E is an expression that refers to 12968 /// a C++ overloaded function (possibly with some parentheses and 12969 /// perhaps a '&' around it). We have resolved the overloaded function 12970 /// to the function declaration Fn, so patch up the expression E to 12971 /// refer (possibly indirectly) to Fn. Returns the new expr. 12972 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 12973 FunctionDecl *Fn) { 12974 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 12975 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 12976 Found, Fn); 12977 if (SubExpr == PE->getSubExpr()) 12978 return PE; 12979 12980 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 12981 } 12982 12983 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 12984 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 12985 Found, Fn); 12986 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 12987 SubExpr->getType()) && 12988 "Implicit cast type cannot be determined from overload"); 12989 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 12990 if (SubExpr == ICE->getSubExpr()) 12991 return ICE; 12992 12993 return ImplicitCastExpr::Create(Context, ICE->getType(), 12994 ICE->getCastKind(), 12995 SubExpr, nullptr, 12996 ICE->getValueKind()); 12997 } 12998 12999 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 13000 assert(UnOp->getOpcode() == UO_AddrOf && 13001 "Can only take the address of an overloaded function"); 13002 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 13003 if (Method->isStatic()) { 13004 // Do nothing: static member functions aren't any different 13005 // from non-member functions. 13006 } else { 13007 // Fix the subexpression, which really has to be an 13008 // UnresolvedLookupExpr holding an overloaded member function 13009 // or template. 13010 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13011 Found, Fn); 13012 if (SubExpr == UnOp->getSubExpr()) 13013 return UnOp; 13014 13015 assert(isa<DeclRefExpr>(SubExpr) 13016 && "fixed to something other than a decl ref"); 13017 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 13018 && "fixed to a member ref with no nested name qualifier"); 13019 13020 // We have taken the address of a pointer to member 13021 // function. Perform the computation here so that we get the 13022 // appropriate pointer to member type. 13023 QualType ClassType 13024 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 13025 QualType MemPtrType 13026 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 13027 // Under the MS ABI, lock down the inheritance model now. 13028 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13029 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 13030 13031 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 13032 VK_RValue, OK_Ordinary, 13033 UnOp->getOperatorLoc()); 13034 } 13035 } 13036 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13037 Found, Fn); 13038 if (SubExpr == UnOp->getSubExpr()) 13039 return UnOp; 13040 13041 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 13042 Context.getPointerType(SubExpr->getType()), 13043 VK_RValue, OK_Ordinary, 13044 UnOp->getOperatorLoc()); 13045 } 13046 13047 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13048 // FIXME: avoid copy. 13049 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13050 if (ULE->hasExplicitTemplateArgs()) { 13051 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 13052 TemplateArgs = &TemplateArgsBuffer; 13053 } 13054 13055 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13056 ULE->getQualifierLoc(), 13057 ULE->getTemplateKeywordLoc(), 13058 Fn, 13059 /*enclosing*/ false, // FIXME? 13060 ULE->getNameLoc(), 13061 Fn->getType(), 13062 VK_LValue, 13063 Found.getDecl(), 13064 TemplateArgs); 13065 MarkDeclRefReferenced(DRE); 13066 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 13067 return DRE; 13068 } 13069 13070 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 13071 // FIXME: avoid copy. 13072 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13073 if (MemExpr->hasExplicitTemplateArgs()) { 13074 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13075 TemplateArgs = &TemplateArgsBuffer; 13076 } 13077 13078 Expr *Base; 13079 13080 // If we're filling in a static method where we used to have an 13081 // implicit member access, rewrite to a simple decl ref. 13082 if (MemExpr->isImplicitAccess()) { 13083 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13084 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13085 MemExpr->getQualifierLoc(), 13086 MemExpr->getTemplateKeywordLoc(), 13087 Fn, 13088 /*enclosing*/ false, 13089 MemExpr->getMemberLoc(), 13090 Fn->getType(), 13091 VK_LValue, 13092 Found.getDecl(), 13093 TemplateArgs); 13094 MarkDeclRefReferenced(DRE); 13095 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 13096 return DRE; 13097 } else { 13098 SourceLocation Loc = MemExpr->getMemberLoc(); 13099 if (MemExpr->getQualifier()) 13100 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 13101 CheckCXXThisCapture(Loc); 13102 Base = new (Context) CXXThisExpr(Loc, 13103 MemExpr->getBaseType(), 13104 /*isImplicit=*/true); 13105 } 13106 } else 13107 Base = MemExpr->getBase(); 13108 13109 ExprValueKind valueKind; 13110 QualType type; 13111 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13112 valueKind = VK_LValue; 13113 type = Fn->getType(); 13114 } else { 13115 valueKind = VK_RValue; 13116 type = Context.BoundMemberTy; 13117 } 13118 13119 MemberExpr *ME = MemberExpr::Create( 13120 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 13121 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 13122 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 13123 OK_Ordinary); 13124 ME->setHadMultipleCandidates(true); 13125 MarkMemberReferenced(ME); 13126 return ME; 13127 } 13128 13129 llvm_unreachable("Invalid reference to overloaded function"); 13130 } 13131 13132 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 13133 DeclAccessPair Found, 13134 FunctionDecl *Fn) { 13135 return FixOverloadedFunctionReference(E.get(), Found, Fn); 13136 } 13137