1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file provides Sema routines for C++ overloading. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/Overload.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/CXXInheritance.h" 17 #include "clang/AST/DeclObjC.h" 18 #include "clang/AST/Expr.h" 19 #include "clang/AST/ExprCXX.h" 20 #include "clang/AST/ExprObjC.h" 21 #include "clang/AST/TypeOrdering.h" 22 #include "clang/Basic/Diagnostic.h" 23 #include "clang/Basic/DiagnosticOptions.h" 24 #include "clang/Basic/PartialDiagnostic.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/SemaInternal.h" 29 #include "clang/Sema/Template.h" 30 #include "clang/Sema/TemplateDeduction.h" 31 #include "llvm/ADT/DenseSet.h" 32 #include "llvm/ADT/STLExtras.h" 33 #include "llvm/ADT/SmallPtrSet.h" 34 #include "llvm/ADT/SmallString.h" 35 #include <algorithm> 36 #include <cstdlib> 37 38 using namespace clang; 39 using namespace sema; 40 41 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 42 return std::any_of(FD->param_begin(), FD->param_end(), 43 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>)); 44 } 45 46 /// A convenience routine for creating a decayed reference to a function. 47 static ExprResult 48 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 49 bool HadMultipleCandidates, 50 SourceLocation Loc = SourceLocation(), 51 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 52 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 53 return ExprError(); 54 // If FoundDecl is different from Fn (such as if one is a template 55 // and the other a specialization), make sure DiagnoseUseOfDecl is 56 // called on both. 57 // FIXME: This would be more comprehensively addressed by modifying 58 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 59 // being used. 60 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 61 return ExprError(); 62 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 63 VK_LValue, Loc, LocInfo); 64 if (HadMultipleCandidates) 65 DRE->setHadMultipleCandidates(true); 66 67 S.MarkDeclRefReferenced(DRE); 68 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 69 CK_FunctionToPointerDecay); 70 } 71 72 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 73 bool InOverloadResolution, 74 StandardConversionSequence &SCS, 75 bool CStyle, 76 bool AllowObjCWritebackConversion); 77 78 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 79 QualType &ToType, 80 bool InOverloadResolution, 81 StandardConversionSequence &SCS, 82 bool CStyle); 83 static OverloadingResult 84 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 85 UserDefinedConversionSequence& User, 86 OverloadCandidateSet& Conversions, 87 bool AllowExplicit, 88 bool AllowObjCConversionOnExplicit); 89 90 91 static ImplicitConversionSequence::CompareKind 92 CompareStandardConversionSequences(Sema &S, 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, 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_FloatingToIntegral: 262 case CK_FloatingToBoolean: 263 case CK_FloatingCast: 264 Converted = ICE->getSubExpr(); 265 continue; 266 267 default: 268 return Converted; 269 } 270 } 271 272 return Converted; 273 } 274 275 /// Check if this standard conversion sequence represents a narrowing 276 /// conversion, according to C++11 [dcl.init.list]p7. 277 /// 278 /// \param Ctx The AST context. 279 /// \param Converted The result of applying this standard conversion sequence. 280 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 281 /// value of the expression prior to the narrowing conversion. 282 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 283 /// type of the expression prior to the narrowing conversion. 284 NarrowingKind 285 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 286 const Expr *Converted, 287 APValue &ConstantValue, 288 QualType &ConstantType) const { 289 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 290 291 // C++11 [dcl.init.list]p7: 292 // A narrowing conversion is an implicit conversion ... 293 QualType FromType = getToType(0); 294 QualType ToType = getToType(1); 295 switch (Second) { 296 // 'bool' is an integral type; dispatch to the right place to handle it. 297 case ICK_Boolean_Conversion: 298 if (FromType->isRealFloatingType()) 299 goto FloatingIntegralConversion; 300 if (FromType->isIntegralOrUnscopedEnumerationType()) 301 goto IntegralConversion; 302 // Boolean conversions can be from pointers and pointers to members 303 // [conv.bool], and those aren't considered narrowing conversions. 304 return NK_Not_Narrowing; 305 306 // -- from a floating-point type to an integer type, or 307 // 308 // -- from an integer type or unscoped enumeration type to a floating-point 309 // type, except where the source is a constant expression and the actual 310 // value after conversion will fit into the target type and will produce 311 // the original value when converted back to the original type, or 312 case ICK_Floating_Integral: 313 FloatingIntegralConversion: 314 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 315 return NK_Type_Narrowing; 316 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 317 llvm::APSInt IntConstantValue; 318 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 319 if (Initializer && 320 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 321 // Convert the integer to the floating type. 322 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 323 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 324 llvm::APFloat::rmNearestTiesToEven); 325 // And back. 326 llvm::APSInt ConvertedValue = IntConstantValue; 327 bool ignored; 328 Result.convertToInteger(ConvertedValue, 329 llvm::APFloat::rmTowardZero, &ignored); 330 // If the resulting value is different, this was a narrowing conversion. 331 if (IntConstantValue != ConvertedValue) { 332 ConstantValue = APValue(IntConstantValue); 333 ConstantType = Initializer->getType(); 334 return NK_Constant_Narrowing; 335 } 336 } else { 337 // Variables are always narrowings. 338 return NK_Variable_Narrowing; 339 } 340 } 341 return NK_Not_Narrowing; 342 343 // -- from long double to double or float, or from double to float, except 344 // where the source is a constant expression and the actual value after 345 // conversion is within the range of values that can be represented (even 346 // if it cannot be represented exactly), or 347 case ICK_Floating_Conversion: 348 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 349 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 350 // FromType is larger than ToType. 351 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 352 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 353 // Constant! 354 assert(ConstantValue.isFloat()); 355 llvm::APFloat FloatVal = ConstantValue.getFloat(); 356 // Convert the source value into the target type. 357 bool ignored; 358 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 359 Ctx.getFloatTypeSemantics(ToType), 360 llvm::APFloat::rmNearestTiesToEven, &ignored); 361 // If there was no overflow, the source value is within the range of 362 // values that can be represented. 363 if (ConvertStatus & llvm::APFloat::opOverflow) { 364 ConstantType = Initializer->getType(); 365 return NK_Constant_Narrowing; 366 } 367 } else { 368 return NK_Variable_Narrowing; 369 } 370 } 371 return NK_Not_Narrowing; 372 373 // -- from an integer type or unscoped enumeration type to an integer type 374 // that cannot represent all the values of the original type, except where 375 // the source is a constant expression and the actual value after 376 // conversion will fit into the target type and will produce the original 377 // value when converted back to the original type. 378 case ICK_Integral_Conversion: 379 IntegralConversion: { 380 assert(FromType->isIntegralOrUnscopedEnumerationType()); 381 assert(ToType->isIntegralOrUnscopedEnumerationType()); 382 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 383 const unsigned FromWidth = Ctx.getIntWidth(FromType); 384 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 385 const unsigned ToWidth = Ctx.getIntWidth(ToType); 386 387 if (FromWidth > ToWidth || 388 (FromWidth == ToWidth && FromSigned != ToSigned) || 389 (FromSigned && !ToSigned)) { 390 // Not all values of FromType can be represented in ToType. 391 llvm::APSInt InitializerValue; 392 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 393 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 394 // Such conversions on variables are always narrowing. 395 return NK_Variable_Narrowing; 396 } 397 bool Narrowing = false; 398 if (FromWidth < ToWidth) { 399 // Negative -> unsigned is narrowing. Otherwise, more bits is never 400 // narrowing. 401 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 402 Narrowing = true; 403 } else { 404 // Add a bit to the InitializerValue so we don't have to worry about 405 // signed vs. unsigned comparisons. 406 InitializerValue = InitializerValue.extend( 407 InitializerValue.getBitWidth() + 1); 408 // Convert the initializer to and from the target width and signed-ness. 409 llvm::APSInt ConvertedValue = InitializerValue; 410 ConvertedValue = ConvertedValue.trunc(ToWidth); 411 ConvertedValue.setIsSigned(ToSigned); 412 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 413 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 414 // If the result is different, this was a narrowing conversion. 415 if (ConvertedValue != InitializerValue) 416 Narrowing = true; 417 } 418 if (Narrowing) { 419 ConstantType = Initializer->getType(); 420 ConstantValue = APValue(InitializerValue); 421 return NK_Constant_Narrowing; 422 } 423 } 424 return NK_Not_Narrowing; 425 } 426 427 default: 428 // Other kinds of conversions are not narrowings. 429 return NK_Not_Narrowing; 430 } 431 } 432 433 /// dump - Print this standard conversion sequence to standard 434 /// error. Useful for debugging overloading issues. 435 void StandardConversionSequence::dump() const { 436 raw_ostream &OS = llvm::errs(); 437 bool PrintedSomething = false; 438 if (First != ICK_Identity) { 439 OS << GetImplicitConversionName(First); 440 PrintedSomething = true; 441 } 442 443 if (Second != ICK_Identity) { 444 if (PrintedSomething) { 445 OS << " -> "; 446 } 447 OS << GetImplicitConversionName(Second); 448 449 if (CopyConstructor) { 450 OS << " (by copy constructor)"; 451 } else if (DirectBinding) { 452 OS << " (direct reference binding)"; 453 } else if (ReferenceBinding) { 454 OS << " (reference binding)"; 455 } 456 PrintedSomething = true; 457 } 458 459 if (Third != ICK_Identity) { 460 if (PrintedSomething) { 461 OS << " -> "; 462 } 463 OS << GetImplicitConversionName(Third); 464 PrintedSomething = true; 465 } 466 467 if (!PrintedSomething) { 468 OS << "No conversions required"; 469 } 470 } 471 472 /// dump - Print this user-defined conversion sequence to standard 473 /// error. Useful for debugging overloading issues. 474 void UserDefinedConversionSequence::dump() const { 475 raw_ostream &OS = llvm::errs(); 476 if (Before.First || Before.Second || Before.Third) { 477 Before.dump(); 478 OS << " -> "; 479 } 480 if (ConversionFunction) 481 OS << '\'' << *ConversionFunction << '\''; 482 else 483 OS << "aggregate initialization"; 484 if (After.First || After.Second || After.Third) { 485 OS << " -> "; 486 After.dump(); 487 } 488 } 489 490 /// dump - Print this implicit conversion sequence to standard 491 /// error. Useful for debugging overloading issues. 492 void ImplicitConversionSequence::dump() const { 493 raw_ostream &OS = llvm::errs(); 494 if (isStdInitializerListElement()) 495 OS << "Worst std::initializer_list element conversion: "; 496 switch (ConversionKind) { 497 case StandardConversion: 498 OS << "Standard conversion: "; 499 Standard.dump(); 500 break; 501 case UserDefinedConversion: 502 OS << "User-defined conversion: "; 503 UserDefined.dump(); 504 break; 505 case EllipsisConversion: 506 OS << "Ellipsis conversion"; 507 break; 508 case AmbiguousConversion: 509 OS << "Ambiguous conversion"; 510 break; 511 case BadConversion: 512 OS << "Bad conversion"; 513 break; 514 } 515 516 OS << "\n"; 517 } 518 519 void AmbiguousConversionSequence::construct() { 520 new (&conversions()) ConversionSet(); 521 } 522 523 void AmbiguousConversionSequence::destruct() { 524 conversions().~ConversionSet(); 525 } 526 527 void 528 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 529 FromTypePtr = O.FromTypePtr; 530 ToTypePtr = O.ToTypePtr; 531 new (&conversions()) ConversionSet(O.conversions()); 532 } 533 534 namespace { 535 // Structure used by DeductionFailureInfo to store 536 // template argument information. 537 struct DFIArguments { 538 TemplateArgument FirstArg; 539 TemplateArgument SecondArg; 540 }; 541 // Structure used by DeductionFailureInfo to store 542 // template parameter and template argument information. 543 struct DFIParamWithArguments : DFIArguments { 544 TemplateParameter Param; 545 }; 546 } 547 548 /// \brief Convert from Sema's representation of template deduction information 549 /// to the form used in overload-candidate information. 550 DeductionFailureInfo 551 clang::MakeDeductionFailureInfo(ASTContext &Context, 552 Sema::TemplateDeductionResult TDK, 553 TemplateDeductionInfo &Info) { 554 DeductionFailureInfo Result; 555 Result.Result = static_cast<unsigned>(TDK); 556 Result.HasDiagnostic = false; 557 Result.Data = nullptr; 558 switch (TDK) { 559 case Sema::TDK_Success: 560 case Sema::TDK_Invalid: 561 case Sema::TDK_InstantiationDepth: 562 case Sema::TDK_TooManyArguments: 563 case Sema::TDK_TooFewArguments: 564 break; 565 566 case Sema::TDK_Incomplete: 567 case Sema::TDK_InvalidExplicitArguments: 568 Result.Data = Info.Param.getOpaqueValue(); 569 break; 570 571 case Sema::TDK_NonDeducedMismatch: { 572 // FIXME: Should allocate from normal heap so that we can free this later. 573 DFIArguments *Saved = new (Context) DFIArguments; 574 Saved->FirstArg = Info.FirstArg; 575 Saved->SecondArg = Info.SecondArg; 576 Result.Data = Saved; 577 break; 578 } 579 580 case Sema::TDK_Inconsistent: 581 case Sema::TDK_Underqualified: { 582 // FIXME: Should allocate from normal heap so that we can free this later. 583 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 584 Saved->Param = Info.Param; 585 Saved->FirstArg = Info.FirstArg; 586 Saved->SecondArg = Info.SecondArg; 587 Result.Data = Saved; 588 break; 589 } 590 591 case Sema::TDK_SubstitutionFailure: 592 Result.Data = Info.take(); 593 if (Info.hasSFINAEDiagnostic()) { 594 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 595 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 596 Info.takeSFINAEDiagnostic(*Diag); 597 Result.HasDiagnostic = true; 598 } 599 break; 600 601 case Sema::TDK_FailedOverloadResolution: 602 Result.Data = Info.Expression; 603 break; 604 605 case Sema::TDK_MiscellaneousDeductionFailure: 606 break; 607 } 608 609 return Result; 610 } 611 612 void DeductionFailureInfo::Destroy() { 613 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 614 case Sema::TDK_Success: 615 case Sema::TDK_Invalid: 616 case Sema::TDK_InstantiationDepth: 617 case Sema::TDK_Incomplete: 618 case Sema::TDK_TooManyArguments: 619 case Sema::TDK_TooFewArguments: 620 case Sema::TDK_InvalidExplicitArguments: 621 case Sema::TDK_FailedOverloadResolution: 622 break; 623 624 case Sema::TDK_Inconsistent: 625 case Sema::TDK_Underqualified: 626 case Sema::TDK_NonDeducedMismatch: 627 // FIXME: Destroy the data? 628 Data = nullptr; 629 break; 630 631 case Sema::TDK_SubstitutionFailure: 632 // FIXME: Destroy the template argument list? 633 Data = nullptr; 634 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 635 Diag->~PartialDiagnosticAt(); 636 HasDiagnostic = false; 637 } 638 break; 639 640 // Unhandled 641 case Sema::TDK_MiscellaneousDeductionFailure: 642 break; 643 } 644 } 645 646 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 647 if (HasDiagnostic) 648 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 649 return nullptr; 650 } 651 652 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 653 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 654 case Sema::TDK_Success: 655 case Sema::TDK_Invalid: 656 case Sema::TDK_InstantiationDepth: 657 case Sema::TDK_TooManyArguments: 658 case Sema::TDK_TooFewArguments: 659 case Sema::TDK_SubstitutionFailure: 660 case Sema::TDK_NonDeducedMismatch: 661 case Sema::TDK_FailedOverloadResolution: 662 return TemplateParameter(); 663 664 case Sema::TDK_Incomplete: 665 case Sema::TDK_InvalidExplicitArguments: 666 return TemplateParameter::getFromOpaqueValue(Data); 667 668 case Sema::TDK_Inconsistent: 669 case Sema::TDK_Underqualified: 670 return static_cast<DFIParamWithArguments*>(Data)->Param; 671 672 // Unhandled 673 case Sema::TDK_MiscellaneousDeductionFailure: 674 break; 675 } 676 677 return TemplateParameter(); 678 } 679 680 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 681 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 682 case Sema::TDK_Success: 683 case Sema::TDK_Invalid: 684 case Sema::TDK_InstantiationDepth: 685 case Sema::TDK_TooManyArguments: 686 case Sema::TDK_TooFewArguments: 687 case Sema::TDK_Incomplete: 688 case Sema::TDK_InvalidExplicitArguments: 689 case Sema::TDK_Inconsistent: 690 case Sema::TDK_Underqualified: 691 case Sema::TDK_NonDeducedMismatch: 692 case Sema::TDK_FailedOverloadResolution: 693 return nullptr; 694 695 case Sema::TDK_SubstitutionFailure: 696 return static_cast<TemplateArgumentList*>(Data); 697 698 // Unhandled 699 case Sema::TDK_MiscellaneousDeductionFailure: 700 break; 701 } 702 703 return nullptr; 704 } 705 706 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 707 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 708 case Sema::TDK_Success: 709 case Sema::TDK_Invalid: 710 case Sema::TDK_InstantiationDepth: 711 case Sema::TDK_Incomplete: 712 case Sema::TDK_TooManyArguments: 713 case Sema::TDK_TooFewArguments: 714 case Sema::TDK_InvalidExplicitArguments: 715 case Sema::TDK_SubstitutionFailure: 716 case Sema::TDK_FailedOverloadResolution: 717 return nullptr; 718 719 case Sema::TDK_Inconsistent: 720 case Sema::TDK_Underqualified: 721 case Sema::TDK_NonDeducedMismatch: 722 return &static_cast<DFIArguments*>(Data)->FirstArg; 723 724 // Unhandled 725 case Sema::TDK_MiscellaneousDeductionFailure: 726 break; 727 } 728 729 return nullptr; 730 } 731 732 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 733 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 734 case Sema::TDK_Success: 735 case Sema::TDK_Invalid: 736 case Sema::TDK_InstantiationDepth: 737 case Sema::TDK_Incomplete: 738 case Sema::TDK_TooManyArguments: 739 case Sema::TDK_TooFewArguments: 740 case Sema::TDK_InvalidExplicitArguments: 741 case Sema::TDK_SubstitutionFailure: 742 case Sema::TDK_FailedOverloadResolution: 743 return nullptr; 744 745 case Sema::TDK_Inconsistent: 746 case Sema::TDK_Underqualified: 747 case Sema::TDK_NonDeducedMismatch: 748 return &static_cast<DFIArguments*>(Data)->SecondArg; 749 750 // Unhandled 751 case Sema::TDK_MiscellaneousDeductionFailure: 752 break; 753 } 754 755 return nullptr; 756 } 757 758 Expr *DeductionFailureInfo::getExpr() { 759 if (static_cast<Sema::TemplateDeductionResult>(Result) == 760 Sema::TDK_FailedOverloadResolution) 761 return static_cast<Expr*>(Data); 762 763 return nullptr; 764 } 765 766 void OverloadCandidateSet::destroyCandidates() { 767 for (iterator i = begin(), e = end(); i != e; ++i) { 768 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 769 i->Conversions[ii].~ImplicitConversionSequence(); 770 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 771 i->DeductionFailure.Destroy(); 772 } 773 } 774 775 void OverloadCandidateSet::clear() { 776 destroyCandidates(); 777 NumInlineSequences = 0; 778 Candidates.clear(); 779 Functions.clear(); 780 } 781 782 namespace { 783 class UnbridgedCastsSet { 784 struct Entry { 785 Expr **Addr; 786 Expr *Saved; 787 }; 788 SmallVector<Entry, 2> Entries; 789 790 public: 791 void save(Sema &S, Expr *&E) { 792 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 793 Entry entry = { &E, E }; 794 Entries.push_back(entry); 795 E = S.stripARCUnbridgedCast(E); 796 } 797 798 void restore() { 799 for (SmallVectorImpl<Entry>::iterator 800 i = Entries.begin(), e = Entries.end(); i != e; ++i) 801 *i->Addr = i->Saved; 802 } 803 }; 804 } 805 806 /// checkPlaceholderForOverload - Do any interesting placeholder-like 807 /// preprocessing on the given expression. 808 /// 809 /// \param unbridgedCasts a collection to which to add unbridged casts; 810 /// without this, they will be immediately diagnosed as errors 811 /// 812 /// Return true on unrecoverable error. 813 static bool 814 checkPlaceholderForOverload(Sema &S, Expr *&E, 815 UnbridgedCastsSet *unbridgedCasts = nullptr) { 816 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 817 // We can't handle overloaded expressions here because overload 818 // resolution might reasonably tweak them. 819 if (placeholder->getKind() == BuiltinType::Overload) return false; 820 821 // If the context potentially accepts unbridged ARC casts, strip 822 // the unbridged cast and add it to the collection for later restoration. 823 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 824 unbridgedCasts) { 825 unbridgedCasts->save(S, E); 826 return false; 827 } 828 829 // Go ahead and check everything else. 830 ExprResult result = S.CheckPlaceholderExpr(E); 831 if (result.isInvalid()) 832 return true; 833 834 E = result.get(); 835 return false; 836 } 837 838 // Nothing to do. 839 return false; 840 } 841 842 /// checkArgPlaceholdersForOverload - Check a set of call operands for 843 /// placeholders. 844 static bool checkArgPlaceholdersForOverload(Sema &S, 845 MultiExprArg Args, 846 UnbridgedCastsSet &unbridged) { 847 for (unsigned i = 0, e = Args.size(); i != e; ++i) 848 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 849 return true; 850 851 return false; 852 } 853 854 // IsOverload - Determine whether the given New declaration is an 855 // overload of the declarations in Old. This routine returns false if 856 // New and Old cannot be overloaded, e.g., if New has the same 857 // signature as some function in Old (C++ 1.3.10) or if the Old 858 // declarations aren't functions (or function templates) at all. When 859 // it does return false, MatchedDecl will point to the decl that New 860 // cannot be overloaded with. This decl may be a UsingShadowDecl on 861 // top of the underlying declaration. 862 // 863 // Example: Given the following input: 864 // 865 // void f(int, float); // #1 866 // void f(int, int); // #2 867 // int f(int, int); // #3 868 // 869 // When we process #1, there is no previous declaration of "f", 870 // so IsOverload will not be used. 871 // 872 // When we process #2, Old contains only the FunctionDecl for #1. By 873 // comparing the parameter types, we see that #1 and #2 are overloaded 874 // (since they have different signatures), so this routine returns 875 // false; MatchedDecl is unchanged. 876 // 877 // When we process #3, Old is an overload set containing #1 and #2. We 878 // compare the signatures of #3 to #1 (they're overloaded, so we do 879 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 880 // identical (return types of functions are not part of the 881 // signature), IsOverload returns false and MatchedDecl will be set to 882 // point to the FunctionDecl for #2. 883 // 884 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 885 // into a class by a using declaration. The rules for whether to hide 886 // shadow declarations ignore some properties which otherwise figure 887 // into a function template's signature. 888 Sema::OverloadKind 889 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 890 NamedDecl *&Match, bool NewIsUsingDecl) { 891 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 892 I != E; ++I) { 893 NamedDecl *OldD = *I; 894 895 bool OldIsUsingDecl = false; 896 if (isa<UsingShadowDecl>(OldD)) { 897 OldIsUsingDecl = true; 898 899 // We can always introduce two using declarations into the same 900 // context, even if they have identical signatures. 901 if (NewIsUsingDecl) continue; 902 903 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 904 } 905 906 // A using-declaration does not conflict with another declaration 907 // if one of them is hidden. 908 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 909 continue; 910 911 // If either declaration was introduced by a using declaration, 912 // we'll need to use slightly different rules for matching. 913 // Essentially, these rules are the normal rules, except that 914 // function templates hide function templates with different 915 // return types or template parameter lists. 916 bool UseMemberUsingDeclRules = 917 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 918 !New->getFriendObjectKind(); 919 920 if (FunctionDecl *OldF = OldD->getAsFunction()) { 921 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 922 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 923 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 924 continue; 925 } 926 927 if (!isa<FunctionTemplateDecl>(OldD) && 928 !shouldLinkPossiblyHiddenDecl(*I, New)) 929 continue; 930 931 Match = *I; 932 return Ovl_Match; 933 } 934 } else if (isa<UsingDecl>(OldD)) { 935 // We can overload with these, which can show up when doing 936 // redeclaration checks for UsingDecls. 937 assert(Old.getLookupKind() == LookupUsingDeclName); 938 } else if (isa<TagDecl>(OldD)) { 939 // We can always overload with tags by hiding them. 940 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 941 // Optimistically assume that an unresolved using decl will 942 // overload; if it doesn't, we'll have to diagnose during 943 // template instantiation. 944 } else { 945 // (C++ 13p1): 946 // Only function declarations can be overloaded; object and type 947 // declarations cannot be overloaded. 948 Match = *I; 949 return Ovl_NonFunction; 950 } 951 } 952 953 return Ovl_Overload; 954 } 955 956 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 957 bool UseUsingDeclRules) { 958 // C++ [basic.start.main]p2: This function shall not be overloaded. 959 if (New->isMain()) 960 return false; 961 962 // MSVCRT user defined entry points cannot be overloaded. 963 if (New->isMSVCRTEntryPoint()) 964 return false; 965 966 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 967 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 968 969 // C++ [temp.fct]p2: 970 // A function template can be overloaded with other function templates 971 // and with normal (non-template) functions. 972 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 973 return true; 974 975 // Is the function New an overload of the function Old? 976 QualType OldQType = Context.getCanonicalType(Old->getType()); 977 QualType NewQType = Context.getCanonicalType(New->getType()); 978 979 // Compare the signatures (C++ 1.3.10) of the two functions to 980 // determine whether they are overloads. If we find any mismatch 981 // in the signature, they are overloads. 982 983 // If either of these functions is a K&R-style function (no 984 // prototype), then we consider them to have matching signatures. 985 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 986 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 987 return false; 988 989 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 990 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 991 992 // The signature of a function includes the types of its 993 // parameters (C++ 1.3.10), which includes the presence or absence 994 // of the ellipsis; see C++ DR 357). 995 if (OldQType != NewQType && 996 (OldType->getNumParams() != NewType->getNumParams() || 997 OldType->isVariadic() != NewType->isVariadic() || 998 !FunctionParamTypesAreEqual(OldType, NewType))) 999 return true; 1000 1001 // C++ [temp.over.link]p4: 1002 // The signature of a function template consists of its function 1003 // signature, its return type and its template parameter list. The names 1004 // of the template parameters are significant only for establishing the 1005 // relationship between the template parameters and the rest of the 1006 // signature. 1007 // 1008 // We check the return type and template parameter lists for function 1009 // templates first; the remaining checks follow. 1010 // 1011 // However, we don't consider either of these when deciding whether 1012 // a member introduced by a shadow declaration is hidden. 1013 if (!UseUsingDeclRules && NewTemplate && 1014 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1015 OldTemplate->getTemplateParameters(), 1016 false, TPL_TemplateMatch) || 1017 OldType->getReturnType() != NewType->getReturnType())) 1018 return true; 1019 1020 // If the function is a class member, its signature includes the 1021 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1022 // 1023 // As part of this, also check whether one of the member functions 1024 // is static, in which case they are not overloads (C++ 1025 // 13.1p2). While not part of the definition of the signature, 1026 // this check is important to determine whether these functions 1027 // can be overloaded. 1028 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1029 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1030 if (OldMethod && NewMethod && 1031 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1032 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1033 if (!UseUsingDeclRules && 1034 (OldMethod->getRefQualifier() == RQ_None || 1035 NewMethod->getRefQualifier() == RQ_None)) { 1036 // C++0x [over.load]p2: 1037 // - Member function declarations with the same name and the same 1038 // parameter-type-list as well as member function template 1039 // declarations with the same name, the same parameter-type-list, and 1040 // the same template parameter lists cannot be overloaded if any of 1041 // them, but not all, have a ref-qualifier (8.3.5). 1042 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1043 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1044 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1045 } 1046 return true; 1047 } 1048 1049 // We may not have applied the implicit const for a constexpr member 1050 // function yet (because we haven't yet resolved whether this is a static 1051 // or non-static member function). Add it now, on the assumption that this 1052 // is a redeclaration of OldMethod. 1053 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1054 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1055 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1056 !isa<CXXConstructorDecl>(NewMethod)) 1057 NewQuals |= Qualifiers::Const; 1058 1059 // We do not allow overloading based off of '__restrict'. 1060 OldQuals &= ~Qualifiers::Restrict; 1061 NewQuals &= ~Qualifiers::Restrict; 1062 if (OldQuals != NewQuals) 1063 return true; 1064 } 1065 1066 // Though pass_object_size is placed on parameters and takes an argument, we 1067 // consider it to be a function-level modifier for the sake of function 1068 // identity. Either the function has one or more parameters with 1069 // pass_object_size or it doesn't. 1070 if (functionHasPassObjectSizeParams(New) != 1071 functionHasPassObjectSizeParams(Old)) 1072 return true; 1073 1074 // enable_if attributes are an order-sensitive part of the signature. 1075 for (specific_attr_iterator<EnableIfAttr> 1076 NewI = New->specific_attr_begin<EnableIfAttr>(), 1077 NewE = New->specific_attr_end<EnableIfAttr>(), 1078 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1079 OldE = Old->specific_attr_end<EnableIfAttr>(); 1080 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1081 if (NewI == NewE || OldI == OldE) 1082 return true; 1083 llvm::FoldingSetNodeID NewID, OldID; 1084 NewI->getCond()->Profile(NewID, Context, true); 1085 OldI->getCond()->Profile(OldID, Context, true); 1086 if (NewID != OldID) 1087 return true; 1088 } 1089 1090 if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads) { 1091 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1092 OldTarget = IdentifyCUDATarget(Old); 1093 if (NewTarget == CFT_InvalidTarget || NewTarget == CFT_Global) 1094 return false; 1095 1096 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1097 1098 // Don't allow mixing of HD with other kinds. This guarantees that 1099 // we have only one viable function with this signature on any 1100 // side of CUDA compilation . 1101 if ((NewTarget == CFT_HostDevice) || (OldTarget == CFT_HostDevice)) 1102 return false; 1103 1104 // Allow overloading of functions with same signature, but 1105 // different CUDA target attributes. 1106 return NewTarget != OldTarget; 1107 } 1108 1109 // The signatures match; this is not an overload. 1110 return false; 1111 } 1112 1113 /// \brief Checks availability of the function depending on the current 1114 /// function context. Inside an unavailable function, unavailability is ignored. 1115 /// 1116 /// \returns true if \arg FD is unavailable and current context is inside 1117 /// an available function, false otherwise. 1118 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1119 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 1120 } 1121 1122 /// \brief Tries a user-defined conversion from From to ToType. 1123 /// 1124 /// Produces an implicit conversion sequence for when a standard conversion 1125 /// is not an option. See TryImplicitConversion for more information. 1126 static ImplicitConversionSequence 1127 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1128 bool SuppressUserConversions, 1129 bool AllowExplicit, 1130 bool InOverloadResolution, 1131 bool CStyle, 1132 bool AllowObjCWritebackConversion, 1133 bool AllowObjCConversionOnExplicit) { 1134 ImplicitConversionSequence ICS; 1135 1136 if (SuppressUserConversions) { 1137 // We're not in the case above, so there is no conversion that 1138 // we can perform. 1139 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1140 return ICS; 1141 } 1142 1143 // Attempt user-defined conversion. 1144 OverloadCandidateSet Conversions(From->getExprLoc(), 1145 OverloadCandidateSet::CSK_Normal); 1146 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1147 Conversions, AllowExplicit, 1148 AllowObjCConversionOnExplicit)) { 1149 case OR_Success: 1150 case OR_Deleted: 1151 ICS.setUserDefined(); 1152 ICS.UserDefined.Before.setAsIdentityConversion(); 1153 // C++ [over.ics.user]p4: 1154 // A conversion of an expression of class type to the same class 1155 // type is given Exact Match rank, and a conversion of an 1156 // expression of class type to a base class of that type is 1157 // given Conversion rank, in spite of the fact that a copy 1158 // constructor (i.e., a user-defined conversion function) is 1159 // called for those cases. 1160 if (CXXConstructorDecl *Constructor 1161 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1162 QualType FromCanon 1163 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1164 QualType ToCanon 1165 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1166 if (Constructor->isCopyConstructor() && 1167 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1168 // Turn this into a "standard" conversion sequence, so that it 1169 // gets ranked with standard conversion sequences. 1170 ICS.setStandard(); 1171 ICS.Standard.setAsIdentityConversion(); 1172 ICS.Standard.setFromType(From->getType()); 1173 ICS.Standard.setAllToTypes(ToType); 1174 ICS.Standard.CopyConstructor = Constructor; 1175 if (ToCanon != FromCanon) 1176 ICS.Standard.Second = ICK_Derived_To_Base; 1177 } 1178 } 1179 break; 1180 1181 case OR_Ambiguous: 1182 ICS.setAmbiguous(); 1183 ICS.Ambiguous.setFromType(From->getType()); 1184 ICS.Ambiguous.setToType(ToType); 1185 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1186 Cand != Conversions.end(); ++Cand) 1187 if (Cand->Viable) 1188 ICS.Ambiguous.addConversion(Cand->Function); 1189 break; 1190 1191 // Fall through. 1192 case OR_No_Viable_Function: 1193 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1194 break; 1195 } 1196 1197 return ICS; 1198 } 1199 1200 /// TryImplicitConversion - Attempt to perform an implicit conversion 1201 /// from the given expression (Expr) to the given type (ToType). This 1202 /// function returns an implicit conversion sequence that can be used 1203 /// to perform the initialization. Given 1204 /// 1205 /// void f(float f); 1206 /// void g(int i) { f(i); } 1207 /// 1208 /// this routine would produce an implicit conversion sequence to 1209 /// describe the initialization of f from i, which will be a standard 1210 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1211 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1212 // 1213 /// Note that this routine only determines how the conversion can be 1214 /// performed; it does not actually perform the conversion. As such, 1215 /// it will not produce any diagnostics if no conversion is available, 1216 /// but will instead return an implicit conversion sequence of kind 1217 /// "BadConversion". 1218 /// 1219 /// If @p SuppressUserConversions, then user-defined conversions are 1220 /// not permitted. 1221 /// If @p AllowExplicit, then explicit user-defined conversions are 1222 /// permitted. 1223 /// 1224 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1225 /// writeback conversion, which allows __autoreleasing id* parameters to 1226 /// be initialized with __strong id* or __weak id* arguments. 1227 static ImplicitConversionSequence 1228 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1229 bool SuppressUserConversions, 1230 bool AllowExplicit, 1231 bool InOverloadResolution, 1232 bool CStyle, 1233 bool AllowObjCWritebackConversion, 1234 bool AllowObjCConversionOnExplicit) { 1235 ImplicitConversionSequence ICS; 1236 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1237 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1238 ICS.setStandard(); 1239 return ICS; 1240 } 1241 1242 if (!S.getLangOpts().CPlusPlus) { 1243 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1244 return ICS; 1245 } 1246 1247 // C++ [over.ics.user]p4: 1248 // A conversion of an expression of class type to the same class 1249 // type is given Exact Match rank, and a conversion of an 1250 // expression of class type to a base class of that type is 1251 // given Conversion rank, in spite of the fact that a copy/move 1252 // constructor (i.e., a user-defined conversion function) is 1253 // called for those cases. 1254 QualType FromType = From->getType(); 1255 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1256 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1257 S.IsDerivedFrom(FromType, ToType))) { 1258 ICS.setStandard(); 1259 ICS.Standard.setAsIdentityConversion(); 1260 ICS.Standard.setFromType(FromType); 1261 ICS.Standard.setAllToTypes(ToType); 1262 1263 // We don't actually check at this point whether there is a valid 1264 // copy/move constructor, since overloading just assumes that it 1265 // exists. When we actually perform initialization, we'll find the 1266 // appropriate constructor to copy the returned object, if needed. 1267 ICS.Standard.CopyConstructor = nullptr; 1268 1269 // Determine whether this is considered a derived-to-base conversion. 1270 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1271 ICS.Standard.Second = ICK_Derived_To_Base; 1272 1273 return ICS; 1274 } 1275 1276 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1277 AllowExplicit, InOverloadResolution, CStyle, 1278 AllowObjCWritebackConversion, 1279 AllowObjCConversionOnExplicit); 1280 } 1281 1282 ImplicitConversionSequence 1283 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1284 bool SuppressUserConversions, 1285 bool AllowExplicit, 1286 bool InOverloadResolution, 1287 bool CStyle, 1288 bool AllowObjCWritebackConversion) { 1289 return ::TryImplicitConversion(*this, From, ToType, 1290 SuppressUserConversions, AllowExplicit, 1291 InOverloadResolution, CStyle, 1292 AllowObjCWritebackConversion, 1293 /*AllowObjCConversionOnExplicit=*/false); 1294 } 1295 1296 /// PerformImplicitConversion - Perform an implicit conversion of the 1297 /// expression From to the type ToType. Returns the 1298 /// converted expression. Flavor is the kind of conversion we're 1299 /// performing, used in the error message. If @p AllowExplicit, 1300 /// explicit user-defined conversions are permitted. 1301 ExprResult 1302 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1303 AssignmentAction Action, bool AllowExplicit) { 1304 ImplicitConversionSequence ICS; 1305 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1306 } 1307 1308 ExprResult 1309 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1310 AssignmentAction Action, bool AllowExplicit, 1311 ImplicitConversionSequence& ICS) { 1312 if (checkPlaceholderForOverload(*this, From)) 1313 return ExprError(); 1314 1315 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1316 bool AllowObjCWritebackConversion 1317 = getLangOpts().ObjCAutoRefCount && 1318 (Action == AA_Passing || Action == AA_Sending); 1319 if (getLangOpts().ObjC1) 1320 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1321 ToType, From->getType(), From); 1322 ICS = ::TryImplicitConversion(*this, From, ToType, 1323 /*SuppressUserConversions=*/false, 1324 AllowExplicit, 1325 /*InOverloadResolution=*/false, 1326 /*CStyle=*/false, 1327 AllowObjCWritebackConversion, 1328 /*AllowObjCConversionOnExplicit=*/false); 1329 return PerformImplicitConversion(From, ToType, ICS, Action); 1330 } 1331 1332 /// \brief Determine whether the conversion from FromType to ToType is a valid 1333 /// conversion that strips "noreturn" off the nested function type. 1334 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1335 QualType &ResultTy) { 1336 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1337 return false; 1338 1339 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1340 // where F adds one of the following at most once: 1341 // - a pointer 1342 // - a member pointer 1343 // - a block pointer 1344 CanQualType CanTo = Context.getCanonicalType(ToType); 1345 CanQualType CanFrom = Context.getCanonicalType(FromType); 1346 Type::TypeClass TyClass = CanTo->getTypeClass(); 1347 if (TyClass != CanFrom->getTypeClass()) return false; 1348 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1349 if (TyClass == Type::Pointer) { 1350 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1351 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1352 } else if (TyClass == Type::BlockPointer) { 1353 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1354 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1355 } else if (TyClass == Type::MemberPointer) { 1356 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1357 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1358 } else { 1359 return false; 1360 } 1361 1362 TyClass = CanTo->getTypeClass(); 1363 if (TyClass != CanFrom->getTypeClass()) return false; 1364 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1365 return false; 1366 } 1367 1368 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1369 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1370 if (!EInfo.getNoReturn()) return false; 1371 1372 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1373 assert(QualType(FromFn, 0).isCanonical()); 1374 if (QualType(FromFn, 0) != CanTo) return false; 1375 1376 ResultTy = ToType; 1377 return true; 1378 } 1379 1380 /// \brief Determine whether the conversion from FromType to ToType is a valid 1381 /// vector conversion. 1382 /// 1383 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1384 /// conversion. 1385 static bool IsVectorConversion(Sema &S, QualType FromType, 1386 QualType ToType, ImplicitConversionKind &ICK) { 1387 // We need at least one of these types to be a vector type to have a vector 1388 // conversion. 1389 if (!ToType->isVectorType() && !FromType->isVectorType()) 1390 return false; 1391 1392 // Identical types require no conversions. 1393 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1394 return false; 1395 1396 // There are no conversions between extended vector types, only identity. 1397 if (ToType->isExtVectorType()) { 1398 // There are no conversions between extended vector types other than the 1399 // identity conversion. 1400 if (FromType->isExtVectorType()) 1401 return false; 1402 1403 // Vector splat from any arithmetic type to a vector. 1404 if (FromType->isArithmeticType()) { 1405 ICK = ICK_Vector_Splat; 1406 return true; 1407 } 1408 } 1409 1410 // We can perform the conversion between vector types in the following cases: 1411 // 1)vector types are equivalent AltiVec and GCC vector types 1412 // 2)lax vector conversions are permitted and the vector types are of the 1413 // same size 1414 if (ToType->isVectorType() && FromType->isVectorType()) { 1415 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1416 S.isLaxVectorConversion(FromType, ToType)) { 1417 ICK = ICK_Vector_Conversion; 1418 return true; 1419 } 1420 } 1421 1422 return false; 1423 } 1424 1425 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1426 bool InOverloadResolution, 1427 StandardConversionSequence &SCS, 1428 bool CStyle); 1429 1430 /// IsStandardConversion - Determines whether there is a standard 1431 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1432 /// expression From to the type ToType. Standard conversion sequences 1433 /// only consider non-class types; for conversions that involve class 1434 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1435 /// contain the standard conversion sequence required to perform this 1436 /// conversion and this routine will return true. Otherwise, this 1437 /// routine will return false and the value of SCS is unspecified. 1438 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1439 bool InOverloadResolution, 1440 StandardConversionSequence &SCS, 1441 bool CStyle, 1442 bool AllowObjCWritebackConversion) { 1443 QualType FromType = From->getType(); 1444 1445 // Standard conversions (C++ [conv]) 1446 SCS.setAsIdentityConversion(); 1447 SCS.IncompatibleObjC = false; 1448 SCS.setFromType(FromType); 1449 SCS.CopyConstructor = nullptr; 1450 1451 // There are no standard conversions for class types in C++, so 1452 // abort early. When overloading in C, however, we do permit them. 1453 if (S.getLangOpts().CPlusPlus && 1454 (FromType->isRecordType() || ToType->isRecordType())) 1455 return false; 1456 1457 // The first conversion can be an lvalue-to-rvalue conversion, 1458 // array-to-pointer conversion, or function-to-pointer conversion 1459 // (C++ 4p1). 1460 1461 if (FromType == S.Context.OverloadTy) { 1462 DeclAccessPair AccessPair; 1463 if (FunctionDecl *Fn 1464 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1465 AccessPair)) { 1466 // We were able to resolve the address of the overloaded function, 1467 // so we can convert to the type of that function. 1468 FromType = Fn->getType(); 1469 SCS.setFromType(FromType); 1470 1471 // we can sometimes resolve &foo<int> regardless of ToType, so check 1472 // if the type matches (identity) or we are converting to bool 1473 if (!S.Context.hasSameUnqualifiedType( 1474 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1475 QualType resultTy; 1476 // if the function type matches except for [[noreturn]], it's ok 1477 if (!S.IsNoReturnConversion(FromType, 1478 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1479 // otherwise, only a boolean conversion is standard 1480 if (!ToType->isBooleanType()) 1481 return false; 1482 } 1483 1484 // Check if the "from" expression is taking the address of an overloaded 1485 // function and recompute the FromType accordingly. Take advantage of the 1486 // fact that non-static member functions *must* have such an address-of 1487 // expression. 1488 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1489 if (Method && !Method->isStatic()) { 1490 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1491 "Non-unary operator on non-static member address"); 1492 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1493 == UO_AddrOf && 1494 "Non-address-of operator on non-static member address"); 1495 const Type *ClassType 1496 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1497 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1498 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1499 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1500 UO_AddrOf && 1501 "Non-address-of operator for overloaded function expression"); 1502 FromType = S.Context.getPointerType(FromType); 1503 } 1504 1505 // Check that we've computed the proper type after overload resolution. 1506 assert(S.Context.hasSameType( 1507 FromType, 1508 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1509 } else { 1510 return false; 1511 } 1512 } 1513 // Lvalue-to-rvalue conversion (C++11 4.1): 1514 // A glvalue (3.10) of a non-function, non-array type T can 1515 // be converted to a prvalue. 1516 bool argIsLValue = From->isGLValue(); 1517 if (argIsLValue && 1518 !FromType->isFunctionType() && !FromType->isArrayType() && 1519 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1520 SCS.First = ICK_Lvalue_To_Rvalue; 1521 1522 // C11 6.3.2.1p2: 1523 // ... if the lvalue has atomic type, the value has the non-atomic version 1524 // of the type of the lvalue ... 1525 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1526 FromType = Atomic->getValueType(); 1527 1528 // If T is a non-class type, the type of the rvalue is the 1529 // cv-unqualified version of T. Otherwise, the type of the rvalue 1530 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1531 // just strip the qualifiers because they don't matter. 1532 FromType = FromType.getUnqualifiedType(); 1533 } else if (FromType->isArrayType()) { 1534 // Array-to-pointer conversion (C++ 4.2) 1535 SCS.First = ICK_Array_To_Pointer; 1536 1537 // An lvalue or rvalue of type "array of N T" or "array of unknown 1538 // bound of T" can be converted to an rvalue of type "pointer to 1539 // T" (C++ 4.2p1). 1540 FromType = S.Context.getArrayDecayedType(FromType); 1541 1542 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1543 // This conversion is deprecated in C++03 (D.4) 1544 SCS.DeprecatedStringLiteralToCharPtr = true; 1545 1546 // For the purpose of ranking in overload resolution 1547 // (13.3.3.1.1), this conversion is considered an 1548 // array-to-pointer conversion followed by a qualification 1549 // conversion (4.4). (C++ 4.2p2) 1550 SCS.Second = ICK_Identity; 1551 SCS.Third = ICK_Qualification; 1552 SCS.QualificationIncludesObjCLifetime = false; 1553 SCS.setAllToTypes(FromType); 1554 return true; 1555 } 1556 } else if (FromType->isFunctionType() && argIsLValue) { 1557 // Function-to-pointer conversion (C++ 4.3). 1558 SCS.First = ICK_Function_To_Pointer; 1559 1560 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1561 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1562 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1563 return false; 1564 1565 // An lvalue of function type T can be converted to an rvalue of 1566 // type "pointer to T." The result is a pointer to the 1567 // function. (C++ 4.3p1). 1568 FromType = S.Context.getPointerType(FromType); 1569 } else { 1570 // We don't require any conversions for the first step. 1571 SCS.First = ICK_Identity; 1572 } 1573 SCS.setToType(0, FromType); 1574 1575 // The second conversion can be an integral promotion, floating 1576 // point promotion, integral conversion, floating point conversion, 1577 // floating-integral conversion, pointer conversion, 1578 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1579 // For overloading in C, this can also be a "compatible-type" 1580 // conversion. 1581 bool IncompatibleObjC = false; 1582 ImplicitConversionKind SecondICK = ICK_Identity; 1583 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1584 // The unqualified versions of the types are the same: there's no 1585 // conversion to do. 1586 SCS.Second = ICK_Identity; 1587 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1588 // Integral promotion (C++ 4.5). 1589 SCS.Second = ICK_Integral_Promotion; 1590 FromType = ToType.getUnqualifiedType(); 1591 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1592 // Floating point promotion (C++ 4.6). 1593 SCS.Second = ICK_Floating_Promotion; 1594 FromType = ToType.getUnqualifiedType(); 1595 } else if (S.IsComplexPromotion(FromType, ToType)) { 1596 // Complex promotion (Clang extension) 1597 SCS.Second = ICK_Complex_Promotion; 1598 FromType = ToType.getUnqualifiedType(); 1599 } else if (ToType->isBooleanType() && 1600 (FromType->isArithmeticType() || 1601 FromType->isAnyPointerType() || 1602 FromType->isBlockPointerType() || 1603 FromType->isMemberPointerType() || 1604 FromType->isNullPtrType())) { 1605 // Boolean conversions (C++ 4.12). 1606 SCS.Second = ICK_Boolean_Conversion; 1607 FromType = S.Context.BoolTy; 1608 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1609 ToType->isIntegralType(S.Context)) { 1610 // Integral conversions (C++ 4.7). 1611 SCS.Second = ICK_Integral_Conversion; 1612 FromType = ToType.getUnqualifiedType(); 1613 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1614 // Complex conversions (C99 6.3.1.6) 1615 SCS.Second = ICK_Complex_Conversion; 1616 FromType = ToType.getUnqualifiedType(); 1617 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1618 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1619 // Complex-real conversions (C99 6.3.1.7) 1620 SCS.Second = ICK_Complex_Real; 1621 FromType = ToType.getUnqualifiedType(); 1622 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1623 // Floating point conversions (C++ 4.8). 1624 SCS.Second = ICK_Floating_Conversion; 1625 FromType = ToType.getUnqualifiedType(); 1626 } else if ((FromType->isRealFloatingType() && 1627 ToType->isIntegralType(S.Context)) || 1628 (FromType->isIntegralOrUnscopedEnumerationType() && 1629 ToType->isRealFloatingType())) { 1630 // Floating-integral conversions (C++ 4.9). 1631 SCS.Second = ICK_Floating_Integral; 1632 FromType = ToType.getUnqualifiedType(); 1633 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1634 SCS.Second = ICK_Block_Pointer_Conversion; 1635 } else if (AllowObjCWritebackConversion && 1636 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1637 SCS.Second = ICK_Writeback_Conversion; 1638 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1639 FromType, IncompatibleObjC)) { 1640 // Pointer conversions (C++ 4.10). 1641 SCS.Second = ICK_Pointer_Conversion; 1642 SCS.IncompatibleObjC = IncompatibleObjC; 1643 FromType = FromType.getUnqualifiedType(); 1644 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1645 InOverloadResolution, FromType)) { 1646 // Pointer to member conversions (4.11). 1647 SCS.Second = ICK_Pointer_Member; 1648 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1649 SCS.Second = SecondICK; 1650 FromType = ToType.getUnqualifiedType(); 1651 } else if (!S.getLangOpts().CPlusPlus && 1652 S.Context.typesAreCompatible(ToType, FromType)) { 1653 // Compatible conversions (Clang extension for C function overloading) 1654 SCS.Second = ICK_Compatible_Conversion; 1655 FromType = ToType.getUnqualifiedType(); 1656 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1657 // Treat a conversion that strips "noreturn" as an identity conversion. 1658 SCS.Second = ICK_NoReturn_Adjustment; 1659 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1660 InOverloadResolution, 1661 SCS, CStyle)) { 1662 SCS.Second = ICK_TransparentUnionConversion; 1663 FromType = ToType; 1664 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1665 CStyle)) { 1666 // tryAtomicConversion has updated the standard conversion sequence 1667 // appropriately. 1668 return true; 1669 } else if (ToType->isEventT() && 1670 From->isIntegerConstantExpr(S.getASTContext()) && 1671 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1672 SCS.Second = ICK_Zero_Event_Conversion; 1673 FromType = ToType; 1674 } else { 1675 // No second conversion required. 1676 SCS.Second = ICK_Identity; 1677 } 1678 SCS.setToType(1, FromType); 1679 1680 QualType CanonFrom; 1681 QualType CanonTo; 1682 // The third conversion can be a qualification conversion (C++ 4p1). 1683 bool ObjCLifetimeConversion; 1684 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1685 ObjCLifetimeConversion)) { 1686 SCS.Third = ICK_Qualification; 1687 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1688 FromType = ToType; 1689 CanonFrom = S.Context.getCanonicalType(FromType); 1690 CanonTo = S.Context.getCanonicalType(ToType); 1691 } else { 1692 // No conversion required 1693 SCS.Third = ICK_Identity; 1694 1695 // C++ [over.best.ics]p6: 1696 // [...] Any difference in top-level cv-qualification is 1697 // subsumed by the initialization itself and does not constitute 1698 // a conversion. [...] 1699 CanonFrom = S.Context.getCanonicalType(FromType); 1700 CanonTo = S.Context.getCanonicalType(ToType); 1701 if (CanonFrom.getLocalUnqualifiedType() 1702 == CanonTo.getLocalUnqualifiedType() && 1703 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1704 FromType = ToType; 1705 CanonFrom = CanonTo; 1706 } 1707 } 1708 SCS.setToType(2, FromType); 1709 1710 if (CanonFrom == CanonTo) 1711 return true; 1712 1713 // If we have not converted the argument type to the parameter type, 1714 // this is a bad conversion sequence, unless we're resolving an overload in C. 1715 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1716 return false; 1717 1718 ExprResult ER = ExprResult{From}; 1719 auto Conv = S.CheckSingleAssignmentConstraints(ToType, ER, 1720 /*Diagnose=*/false, 1721 /*DiagnoseCFAudited=*/false, 1722 /*ConvertRHS=*/false); 1723 if (Conv != Sema::Compatible) 1724 return false; 1725 1726 SCS.setAllToTypes(ToType); 1727 // We need to set all three because we want this conversion to rank terribly, 1728 // and we don't know what conversions it may overlap with. 1729 SCS.First = ICK_C_Only_Conversion; 1730 SCS.Second = ICK_C_Only_Conversion; 1731 SCS.Third = ICK_C_Only_Conversion; 1732 return true; 1733 } 1734 1735 static bool 1736 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1737 QualType &ToType, 1738 bool InOverloadResolution, 1739 StandardConversionSequence &SCS, 1740 bool CStyle) { 1741 1742 const RecordType *UT = ToType->getAsUnionType(); 1743 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1744 return false; 1745 // The field to initialize within the transparent union. 1746 RecordDecl *UD = UT->getDecl(); 1747 // It's compatible if the expression matches any of the fields. 1748 for (const auto *it : UD->fields()) { 1749 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1750 CStyle, /*ObjCWritebackConversion=*/false)) { 1751 ToType = it->getType(); 1752 return true; 1753 } 1754 } 1755 return false; 1756 } 1757 1758 /// IsIntegralPromotion - Determines whether the conversion from the 1759 /// expression From (whose potentially-adjusted type is FromType) to 1760 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1761 /// sets PromotedType to the promoted type. 1762 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1763 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1764 // All integers are built-in. 1765 if (!To) { 1766 return false; 1767 } 1768 1769 // An rvalue of type char, signed char, unsigned char, short int, or 1770 // unsigned short int can be converted to an rvalue of type int if 1771 // int can represent all the values of the source type; otherwise, 1772 // the source rvalue can be converted to an rvalue of type unsigned 1773 // int (C++ 4.5p1). 1774 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1775 !FromType->isEnumeralType()) { 1776 if (// We can promote any signed, promotable integer type to an int 1777 (FromType->isSignedIntegerType() || 1778 // We can promote any unsigned integer type whose size is 1779 // less than int to an int. 1780 (!FromType->isSignedIntegerType() && 1781 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1782 return To->getKind() == BuiltinType::Int; 1783 } 1784 1785 return To->getKind() == BuiltinType::UInt; 1786 } 1787 1788 // C++11 [conv.prom]p3: 1789 // A prvalue of an unscoped enumeration type whose underlying type is not 1790 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1791 // following types that can represent all the values of the enumeration 1792 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1793 // unsigned int, long int, unsigned long int, long long int, or unsigned 1794 // long long int. If none of the types in that list can represent all the 1795 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1796 // type can be converted to an rvalue a prvalue of the extended integer type 1797 // with lowest integer conversion rank (4.13) greater than the rank of long 1798 // long in which all the values of the enumeration can be represented. If 1799 // there are two such extended types, the signed one is chosen. 1800 // C++11 [conv.prom]p4: 1801 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1802 // can be converted to a prvalue of its underlying type. Moreover, if 1803 // integral promotion can be applied to its underlying type, a prvalue of an 1804 // unscoped enumeration type whose underlying type is fixed can also be 1805 // converted to a prvalue of the promoted underlying type. 1806 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1807 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1808 // provided for a scoped enumeration. 1809 if (FromEnumType->getDecl()->isScoped()) 1810 return false; 1811 1812 // We can perform an integral promotion to the underlying type of the enum, 1813 // even if that's not the promoted type. Note that the check for promoting 1814 // the underlying type is based on the type alone, and does not consider 1815 // the bitfield-ness of the actual source expression. 1816 if (FromEnumType->getDecl()->isFixed()) { 1817 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1818 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1819 IsIntegralPromotion(nullptr, Underlying, ToType); 1820 } 1821 1822 // We have already pre-calculated the promotion type, so this is trivial. 1823 if (ToType->isIntegerType() && 1824 !RequireCompleteType(From->getLocStart(), FromType, 0)) 1825 return Context.hasSameUnqualifiedType( 1826 ToType, FromEnumType->getDecl()->getPromotionType()); 1827 } 1828 1829 // C++0x [conv.prom]p2: 1830 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1831 // to an rvalue a prvalue of the first of the following types that can 1832 // represent all the values of its underlying type: int, unsigned int, 1833 // long int, unsigned long int, long long int, or unsigned long long int. 1834 // If none of the types in that list can represent all the values of its 1835 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1836 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1837 // type. 1838 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1839 ToType->isIntegerType()) { 1840 // Determine whether the type we're converting from is signed or 1841 // unsigned. 1842 bool FromIsSigned = FromType->isSignedIntegerType(); 1843 uint64_t FromSize = Context.getTypeSize(FromType); 1844 1845 // The types we'll try to promote to, in the appropriate 1846 // order. Try each of these types. 1847 QualType PromoteTypes[6] = { 1848 Context.IntTy, Context.UnsignedIntTy, 1849 Context.LongTy, Context.UnsignedLongTy , 1850 Context.LongLongTy, Context.UnsignedLongLongTy 1851 }; 1852 for (int Idx = 0; Idx < 6; ++Idx) { 1853 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1854 if (FromSize < ToSize || 1855 (FromSize == ToSize && 1856 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1857 // We found the type that we can promote to. If this is the 1858 // type we wanted, we have a promotion. Otherwise, no 1859 // promotion. 1860 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1861 } 1862 } 1863 } 1864 1865 // An rvalue for an integral bit-field (9.6) can be converted to an 1866 // rvalue of type int if int can represent all the values of the 1867 // bit-field; otherwise, it can be converted to unsigned int if 1868 // unsigned int can represent all the values of the bit-field. If 1869 // the bit-field is larger yet, no integral promotion applies to 1870 // it. If the bit-field has an enumerated type, it is treated as any 1871 // other value of that type for promotion purposes (C++ 4.5p3). 1872 // FIXME: We should delay checking of bit-fields until we actually perform the 1873 // conversion. 1874 if (From) { 1875 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 1876 llvm::APSInt BitWidth; 1877 if (FromType->isIntegralType(Context) && 1878 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1879 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1880 ToSize = Context.getTypeSize(ToType); 1881 1882 // Are we promoting to an int from a bitfield that fits in an int? 1883 if (BitWidth < ToSize || 1884 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1885 return To->getKind() == BuiltinType::Int; 1886 } 1887 1888 // Are we promoting to an unsigned int from an unsigned bitfield 1889 // that fits into an unsigned int? 1890 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1891 return To->getKind() == BuiltinType::UInt; 1892 } 1893 1894 return false; 1895 } 1896 } 1897 } 1898 1899 // An rvalue of type bool can be converted to an rvalue of type int, 1900 // with false becoming zero and true becoming one (C++ 4.5p4). 1901 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1902 return true; 1903 } 1904 1905 return false; 1906 } 1907 1908 /// IsFloatingPointPromotion - Determines whether the conversion from 1909 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1910 /// returns true and sets PromotedType to the promoted type. 1911 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1912 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1913 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1914 /// An rvalue of type float can be converted to an rvalue of type 1915 /// double. (C++ 4.6p1). 1916 if (FromBuiltin->getKind() == BuiltinType::Float && 1917 ToBuiltin->getKind() == BuiltinType::Double) 1918 return true; 1919 1920 // C99 6.3.1.5p1: 1921 // When a float is promoted to double or long double, or a 1922 // double is promoted to long double [...]. 1923 if (!getLangOpts().CPlusPlus && 1924 (FromBuiltin->getKind() == BuiltinType::Float || 1925 FromBuiltin->getKind() == BuiltinType::Double) && 1926 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1927 return true; 1928 1929 // Half can be promoted to float. 1930 if (!getLangOpts().NativeHalfType && 1931 FromBuiltin->getKind() == BuiltinType::Half && 1932 ToBuiltin->getKind() == BuiltinType::Float) 1933 return true; 1934 } 1935 1936 return false; 1937 } 1938 1939 /// \brief Determine if a conversion is a complex promotion. 1940 /// 1941 /// A complex promotion is defined as a complex -> complex conversion 1942 /// where the conversion between the underlying real types is a 1943 /// floating-point or integral promotion. 1944 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1945 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1946 if (!FromComplex) 1947 return false; 1948 1949 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1950 if (!ToComplex) 1951 return false; 1952 1953 return IsFloatingPointPromotion(FromComplex->getElementType(), 1954 ToComplex->getElementType()) || 1955 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 1956 ToComplex->getElementType()); 1957 } 1958 1959 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1960 /// the pointer type FromPtr to a pointer to type ToPointee, with the 1961 /// same type qualifiers as FromPtr has on its pointee type. ToType, 1962 /// if non-empty, will be a pointer to ToType that may or may not have 1963 /// the right set of qualifiers on its pointee. 1964 /// 1965 static QualType 1966 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1967 QualType ToPointee, QualType ToType, 1968 ASTContext &Context, 1969 bool StripObjCLifetime = false) { 1970 assert((FromPtr->getTypeClass() == Type::Pointer || 1971 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1972 "Invalid similarly-qualified pointer type"); 1973 1974 /// Conversions to 'id' subsume cv-qualifier conversions. 1975 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1976 return ToType.getUnqualifiedType(); 1977 1978 QualType CanonFromPointee 1979 = Context.getCanonicalType(FromPtr->getPointeeType()); 1980 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1981 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1982 1983 if (StripObjCLifetime) 1984 Quals.removeObjCLifetime(); 1985 1986 // Exact qualifier match -> return the pointer type we're converting to. 1987 if (CanonToPointee.getLocalQualifiers() == Quals) { 1988 // ToType is exactly what we need. Return it. 1989 if (!ToType.isNull()) 1990 return ToType.getUnqualifiedType(); 1991 1992 // Build a pointer to ToPointee. It has the right qualifiers 1993 // already. 1994 if (isa<ObjCObjectPointerType>(ToType)) 1995 return Context.getObjCObjectPointerType(ToPointee); 1996 return Context.getPointerType(ToPointee); 1997 } 1998 1999 // Just build a canonical type that has the right qualifiers. 2000 QualType QualifiedCanonToPointee 2001 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2002 2003 if (isa<ObjCObjectPointerType>(ToType)) 2004 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2005 return Context.getPointerType(QualifiedCanonToPointee); 2006 } 2007 2008 static bool isNullPointerConstantForConversion(Expr *Expr, 2009 bool InOverloadResolution, 2010 ASTContext &Context) { 2011 // Handle value-dependent integral null pointer constants correctly. 2012 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2013 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2014 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2015 return !InOverloadResolution; 2016 2017 return Expr->isNullPointerConstant(Context, 2018 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2019 : Expr::NPC_ValueDependentIsNull); 2020 } 2021 2022 /// IsPointerConversion - Determines whether the conversion of the 2023 /// expression From, which has the (possibly adjusted) type FromType, 2024 /// can be converted to the type ToType via a pointer conversion (C++ 2025 /// 4.10). If so, returns true and places the converted type (that 2026 /// might differ from ToType in its cv-qualifiers at some level) into 2027 /// ConvertedType. 2028 /// 2029 /// This routine also supports conversions to and from block pointers 2030 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2031 /// pointers to interfaces. FIXME: Once we've determined the 2032 /// appropriate overloading rules for Objective-C, we may want to 2033 /// split the Objective-C checks into a different routine; however, 2034 /// GCC seems to consider all of these conversions to be pointer 2035 /// conversions, so for now they live here. IncompatibleObjC will be 2036 /// set if the conversion is an allowed Objective-C conversion that 2037 /// should result in a warning. 2038 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2039 bool InOverloadResolution, 2040 QualType& ConvertedType, 2041 bool &IncompatibleObjC) { 2042 IncompatibleObjC = false; 2043 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2044 IncompatibleObjC)) 2045 return true; 2046 2047 // Conversion from a null pointer constant to any Objective-C pointer type. 2048 if (ToType->isObjCObjectPointerType() && 2049 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2050 ConvertedType = ToType; 2051 return true; 2052 } 2053 2054 // Blocks: Block pointers can be converted to void*. 2055 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2056 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2057 ConvertedType = ToType; 2058 return true; 2059 } 2060 // Blocks: A null pointer constant can be converted to a block 2061 // pointer type. 2062 if (ToType->isBlockPointerType() && 2063 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2064 ConvertedType = ToType; 2065 return true; 2066 } 2067 2068 // If the left-hand-side is nullptr_t, the right side can be a null 2069 // pointer constant. 2070 if (ToType->isNullPtrType() && 2071 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2072 ConvertedType = ToType; 2073 return true; 2074 } 2075 2076 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2077 if (!ToTypePtr) 2078 return false; 2079 2080 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2081 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2082 ConvertedType = ToType; 2083 return true; 2084 } 2085 2086 // Beyond this point, both types need to be pointers 2087 // , including objective-c pointers. 2088 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2089 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2090 !getLangOpts().ObjCAutoRefCount) { 2091 ConvertedType = BuildSimilarlyQualifiedPointerType( 2092 FromType->getAs<ObjCObjectPointerType>(), 2093 ToPointeeType, 2094 ToType, Context); 2095 return true; 2096 } 2097 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2098 if (!FromTypePtr) 2099 return false; 2100 2101 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2102 2103 // If the unqualified pointee types are the same, this can't be a 2104 // pointer conversion, so don't do all of the work below. 2105 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2106 return false; 2107 2108 // An rvalue of type "pointer to cv T," where T is an object type, 2109 // can be converted to an rvalue of type "pointer to cv void" (C++ 2110 // 4.10p2). 2111 if (FromPointeeType->isIncompleteOrObjectType() && 2112 ToPointeeType->isVoidType()) { 2113 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2114 ToPointeeType, 2115 ToType, Context, 2116 /*StripObjCLifetime=*/true); 2117 return true; 2118 } 2119 2120 // MSVC allows implicit function to void* type conversion. 2121 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2122 ToPointeeType->isVoidType()) { 2123 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2124 ToPointeeType, 2125 ToType, Context); 2126 return true; 2127 } 2128 2129 // When we're overloading in C, we allow a special kind of pointer 2130 // conversion for compatible-but-not-identical pointee types. 2131 if (!getLangOpts().CPlusPlus && 2132 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2133 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2134 ToPointeeType, 2135 ToType, Context); 2136 return true; 2137 } 2138 2139 // C++ [conv.ptr]p3: 2140 // 2141 // An rvalue of type "pointer to cv D," where D is a class type, 2142 // can be converted to an rvalue of type "pointer to cv B," where 2143 // B is a base class (clause 10) of D. If B is an inaccessible 2144 // (clause 11) or ambiguous (10.2) base class of D, a program that 2145 // necessitates this conversion is ill-formed. The result of the 2146 // conversion is a pointer to the base class sub-object of the 2147 // derived class object. The null pointer value is converted to 2148 // the null pointer value of the destination type. 2149 // 2150 // Note that we do not check for ambiguity or inaccessibility 2151 // here. That is handled by CheckPointerConversion. 2152 if (getLangOpts().CPlusPlus && 2153 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2154 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2155 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) && 2156 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 2157 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2158 ToPointeeType, 2159 ToType, Context); 2160 return true; 2161 } 2162 2163 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2164 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2165 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2166 ToPointeeType, 2167 ToType, Context); 2168 return true; 2169 } 2170 2171 return false; 2172 } 2173 2174 /// \brief Adopt the given qualifiers for the given type. 2175 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2176 Qualifiers TQs = T.getQualifiers(); 2177 2178 // Check whether qualifiers already match. 2179 if (TQs == Qs) 2180 return T; 2181 2182 if (Qs.compatiblyIncludes(TQs)) 2183 return Context.getQualifiedType(T, Qs); 2184 2185 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2186 } 2187 2188 /// isObjCPointerConversion - Determines whether this is an 2189 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2190 /// with the same arguments and return values. 2191 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2192 QualType& ConvertedType, 2193 bool &IncompatibleObjC) { 2194 if (!getLangOpts().ObjC1) 2195 return false; 2196 2197 // The set of qualifiers on the type we're converting from. 2198 Qualifiers FromQualifiers = FromType.getQualifiers(); 2199 2200 // First, we handle all conversions on ObjC object pointer types. 2201 const ObjCObjectPointerType* ToObjCPtr = 2202 ToType->getAs<ObjCObjectPointerType>(); 2203 const ObjCObjectPointerType *FromObjCPtr = 2204 FromType->getAs<ObjCObjectPointerType>(); 2205 2206 if (ToObjCPtr && FromObjCPtr) { 2207 // If the pointee types are the same (ignoring qualifications), 2208 // then this is not a pointer conversion. 2209 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2210 FromObjCPtr->getPointeeType())) 2211 return false; 2212 2213 // Conversion between Objective-C pointers. 2214 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2215 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2216 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2217 if (getLangOpts().CPlusPlus && LHS && RHS && 2218 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2219 FromObjCPtr->getPointeeType())) 2220 return false; 2221 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2222 ToObjCPtr->getPointeeType(), 2223 ToType, Context); 2224 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2225 return true; 2226 } 2227 2228 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2229 // Okay: this is some kind of implicit downcast of Objective-C 2230 // interfaces, which is permitted. However, we're going to 2231 // complain about it. 2232 IncompatibleObjC = true; 2233 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2234 ToObjCPtr->getPointeeType(), 2235 ToType, Context); 2236 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2237 return true; 2238 } 2239 } 2240 // Beyond this point, both types need to be C pointers or block pointers. 2241 QualType ToPointeeType; 2242 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2243 ToPointeeType = ToCPtr->getPointeeType(); 2244 else if (const BlockPointerType *ToBlockPtr = 2245 ToType->getAs<BlockPointerType>()) { 2246 // Objective C++: We're able to convert from a pointer to any object 2247 // to a block pointer type. 2248 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2249 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2250 return true; 2251 } 2252 ToPointeeType = ToBlockPtr->getPointeeType(); 2253 } 2254 else if (FromType->getAs<BlockPointerType>() && 2255 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2256 // Objective C++: We're able to convert from a block pointer type to a 2257 // pointer to any object. 2258 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2259 return true; 2260 } 2261 else 2262 return false; 2263 2264 QualType FromPointeeType; 2265 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2266 FromPointeeType = FromCPtr->getPointeeType(); 2267 else if (const BlockPointerType *FromBlockPtr = 2268 FromType->getAs<BlockPointerType>()) 2269 FromPointeeType = FromBlockPtr->getPointeeType(); 2270 else 2271 return false; 2272 2273 // If we have pointers to pointers, recursively check whether this 2274 // is an Objective-C conversion. 2275 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2276 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2277 IncompatibleObjC)) { 2278 // We always complain about this conversion. 2279 IncompatibleObjC = true; 2280 ConvertedType = Context.getPointerType(ConvertedType); 2281 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2282 return true; 2283 } 2284 // Allow conversion of pointee being objective-c pointer to another one; 2285 // as in I* to id. 2286 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2287 ToPointeeType->getAs<ObjCObjectPointerType>() && 2288 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2289 IncompatibleObjC)) { 2290 2291 ConvertedType = Context.getPointerType(ConvertedType); 2292 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2293 return true; 2294 } 2295 2296 // If we have pointers to functions or blocks, check whether the only 2297 // differences in the argument and result types are in Objective-C 2298 // pointer conversions. If so, we permit the conversion (but 2299 // complain about it). 2300 const FunctionProtoType *FromFunctionType 2301 = FromPointeeType->getAs<FunctionProtoType>(); 2302 const FunctionProtoType *ToFunctionType 2303 = ToPointeeType->getAs<FunctionProtoType>(); 2304 if (FromFunctionType && ToFunctionType) { 2305 // If the function types are exactly the same, this isn't an 2306 // Objective-C pointer conversion. 2307 if (Context.getCanonicalType(FromPointeeType) 2308 == Context.getCanonicalType(ToPointeeType)) 2309 return false; 2310 2311 // Perform the quick checks that will tell us whether these 2312 // function types are obviously different. 2313 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2314 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2315 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2316 return false; 2317 2318 bool HasObjCConversion = false; 2319 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2320 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2321 // Okay, the types match exactly. Nothing to do. 2322 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2323 ToFunctionType->getReturnType(), 2324 ConvertedType, IncompatibleObjC)) { 2325 // Okay, we have an Objective-C pointer conversion. 2326 HasObjCConversion = true; 2327 } else { 2328 // Function types are too different. Abort. 2329 return false; 2330 } 2331 2332 // Check argument types. 2333 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2334 ArgIdx != NumArgs; ++ArgIdx) { 2335 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2336 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2337 if (Context.getCanonicalType(FromArgType) 2338 == Context.getCanonicalType(ToArgType)) { 2339 // Okay, the types match exactly. Nothing to do. 2340 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2341 ConvertedType, IncompatibleObjC)) { 2342 // Okay, we have an Objective-C pointer conversion. 2343 HasObjCConversion = true; 2344 } else { 2345 // Argument types are too different. Abort. 2346 return false; 2347 } 2348 } 2349 2350 if (HasObjCConversion) { 2351 // We had an Objective-C conversion. Allow this pointer 2352 // conversion, but complain about it. 2353 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2354 IncompatibleObjC = true; 2355 return true; 2356 } 2357 } 2358 2359 return false; 2360 } 2361 2362 /// \brief Determine whether this is an Objective-C writeback conversion, 2363 /// used for parameter passing when performing automatic reference counting. 2364 /// 2365 /// \param FromType The type we're converting form. 2366 /// 2367 /// \param ToType The type we're converting to. 2368 /// 2369 /// \param ConvertedType The type that will be produced after applying 2370 /// this conversion. 2371 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2372 QualType &ConvertedType) { 2373 if (!getLangOpts().ObjCAutoRefCount || 2374 Context.hasSameUnqualifiedType(FromType, ToType)) 2375 return false; 2376 2377 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2378 QualType ToPointee; 2379 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2380 ToPointee = ToPointer->getPointeeType(); 2381 else 2382 return false; 2383 2384 Qualifiers ToQuals = ToPointee.getQualifiers(); 2385 if (!ToPointee->isObjCLifetimeType() || 2386 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2387 !ToQuals.withoutObjCLifetime().empty()) 2388 return false; 2389 2390 // Argument must be a pointer to __strong to __weak. 2391 QualType FromPointee; 2392 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2393 FromPointee = FromPointer->getPointeeType(); 2394 else 2395 return false; 2396 2397 Qualifiers FromQuals = FromPointee.getQualifiers(); 2398 if (!FromPointee->isObjCLifetimeType() || 2399 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2400 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2401 return false; 2402 2403 // Make sure that we have compatible qualifiers. 2404 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2405 if (!ToQuals.compatiblyIncludes(FromQuals)) 2406 return false; 2407 2408 // Remove qualifiers from the pointee type we're converting from; they 2409 // aren't used in the compatibility check belong, and we'll be adding back 2410 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2411 FromPointee = FromPointee.getUnqualifiedType(); 2412 2413 // The unqualified form of the pointee types must be compatible. 2414 ToPointee = ToPointee.getUnqualifiedType(); 2415 bool IncompatibleObjC; 2416 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2417 FromPointee = ToPointee; 2418 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2419 IncompatibleObjC)) 2420 return false; 2421 2422 /// \brief Construct the type we're converting to, which is a pointer to 2423 /// __autoreleasing pointee. 2424 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2425 ConvertedType = Context.getPointerType(FromPointee); 2426 return true; 2427 } 2428 2429 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2430 QualType& ConvertedType) { 2431 QualType ToPointeeType; 2432 if (const BlockPointerType *ToBlockPtr = 2433 ToType->getAs<BlockPointerType>()) 2434 ToPointeeType = ToBlockPtr->getPointeeType(); 2435 else 2436 return false; 2437 2438 QualType FromPointeeType; 2439 if (const BlockPointerType *FromBlockPtr = 2440 FromType->getAs<BlockPointerType>()) 2441 FromPointeeType = FromBlockPtr->getPointeeType(); 2442 else 2443 return false; 2444 // We have pointer to blocks, check whether the only 2445 // differences in the argument and result types are in Objective-C 2446 // pointer conversions. If so, we permit the conversion. 2447 2448 const FunctionProtoType *FromFunctionType 2449 = FromPointeeType->getAs<FunctionProtoType>(); 2450 const FunctionProtoType *ToFunctionType 2451 = ToPointeeType->getAs<FunctionProtoType>(); 2452 2453 if (!FromFunctionType || !ToFunctionType) 2454 return false; 2455 2456 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2457 return true; 2458 2459 // Perform the quick checks that will tell us whether these 2460 // function types are obviously different. 2461 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2462 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2463 return false; 2464 2465 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2466 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2467 if (FromEInfo != ToEInfo) 2468 return false; 2469 2470 bool IncompatibleObjC = false; 2471 if (Context.hasSameType(FromFunctionType->getReturnType(), 2472 ToFunctionType->getReturnType())) { 2473 // Okay, the types match exactly. Nothing to do. 2474 } else { 2475 QualType RHS = FromFunctionType->getReturnType(); 2476 QualType LHS = ToFunctionType->getReturnType(); 2477 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2478 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2479 LHS = LHS.getUnqualifiedType(); 2480 2481 if (Context.hasSameType(RHS,LHS)) { 2482 // OK exact match. 2483 } else if (isObjCPointerConversion(RHS, LHS, 2484 ConvertedType, IncompatibleObjC)) { 2485 if (IncompatibleObjC) 2486 return false; 2487 // Okay, we have an Objective-C pointer conversion. 2488 } 2489 else 2490 return false; 2491 } 2492 2493 // Check argument types. 2494 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2495 ArgIdx != NumArgs; ++ArgIdx) { 2496 IncompatibleObjC = false; 2497 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2498 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2499 if (Context.hasSameType(FromArgType, ToArgType)) { 2500 // Okay, the types match exactly. Nothing to do. 2501 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2502 ConvertedType, IncompatibleObjC)) { 2503 if (IncompatibleObjC) 2504 return false; 2505 // Okay, we have an Objective-C pointer conversion. 2506 } else 2507 // Argument types are too different. Abort. 2508 return false; 2509 } 2510 if (LangOpts.ObjCAutoRefCount && 2511 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2512 ToFunctionType)) 2513 return false; 2514 2515 ConvertedType = ToType; 2516 return true; 2517 } 2518 2519 enum { 2520 ft_default, 2521 ft_different_class, 2522 ft_parameter_arity, 2523 ft_parameter_mismatch, 2524 ft_return_type, 2525 ft_qualifer_mismatch 2526 }; 2527 2528 /// Attempts to get the FunctionProtoType from a Type. Handles 2529 /// MemberFunctionPointers properly. 2530 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2531 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2532 return FPT; 2533 2534 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2535 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2536 2537 return nullptr; 2538 } 2539 2540 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2541 /// function types. Catches different number of parameter, mismatch in 2542 /// parameter types, and different return types. 2543 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2544 QualType FromType, QualType ToType) { 2545 // If either type is not valid, include no extra info. 2546 if (FromType.isNull() || ToType.isNull()) { 2547 PDiag << ft_default; 2548 return; 2549 } 2550 2551 // Get the function type from the pointers. 2552 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2553 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2554 *ToMember = ToType->getAs<MemberPointerType>(); 2555 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2556 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2557 << QualType(FromMember->getClass(), 0); 2558 return; 2559 } 2560 FromType = FromMember->getPointeeType(); 2561 ToType = ToMember->getPointeeType(); 2562 } 2563 2564 if (FromType->isPointerType()) 2565 FromType = FromType->getPointeeType(); 2566 if (ToType->isPointerType()) 2567 ToType = ToType->getPointeeType(); 2568 2569 // Remove references. 2570 FromType = FromType.getNonReferenceType(); 2571 ToType = ToType.getNonReferenceType(); 2572 2573 // Don't print extra info for non-specialized template functions. 2574 if (FromType->isInstantiationDependentType() && 2575 !FromType->getAs<TemplateSpecializationType>()) { 2576 PDiag << ft_default; 2577 return; 2578 } 2579 2580 // No extra info for same types. 2581 if (Context.hasSameType(FromType, ToType)) { 2582 PDiag << ft_default; 2583 return; 2584 } 2585 2586 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2587 *ToFunction = tryGetFunctionProtoType(ToType); 2588 2589 // Both types need to be function types. 2590 if (!FromFunction || !ToFunction) { 2591 PDiag << ft_default; 2592 return; 2593 } 2594 2595 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2596 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2597 << FromFunction->getNumParams(); 2598 return; 2599 } 2600 2601 // Handle different parameter types. 2602 unsigned ArgPos; 2603 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2604 PDiag << ft_parameter_mismatch << ArgPos + 1 2605 << ToFunction->getParamType(ArgPos) 2606 << FromFunction->getParamType(ArgPos); 2607 return; 2608 } 2609 2610 // Handle different return type. 2611 if (!Context.hasSameType(FromFunction->getReturnType(), 2612 ToFunction->getReturnType())) { 2613 PDiag << ft_return_type << ToFunction->getReturnType() 2614 << FromFunction->getReturnType(); 2615 return; 2616 } 2617 2618 unsigned FromQuals = FromFunction->getTypeQuals(), 2619 ToQuals = ToFunction->getTypeQuals(); 2620 if (FromQuals != ToQuals) { 2621 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2622 return; 2623 } 2624 2625 // Unable to find a difference, so add no extra info. 2626 PDiag << ft_default; 2627 } 2628 2629 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2630 /// for equality of their argument types. Caller has already checked that 2631 /// they have same number of arguments. If the parameters are different, 2632 /// ArgPos will have the parameter index of the first different parameter. 2633 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2634 const FunctionProtoType *NewType, 2635 unsigned *ArgPos) { 2636 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2637 N = NewType->param_type_begin(), 2638 E = OldType->param_type_end(); 2639 O && (O != E); ++O, ++N) { 2640 if (!Context.hasSameType(O->getUnqualifiedType(), 2641 N->getUnqualifiedType())) { 2642 if (ArgPos) 2643 *ArgPos = O - OldType->param_type_begin(); 2644 return false; 2645 } 2646 } 2647 return true; 2648 } 2649 2650 /// CheckPointerConversion - Check the pointer conversion from the 2651 /// expression From to the type ToType. This routine checks for 2652 /// ambiguous or inaccessible derived-to-base pointer 2653 /// conversions for which IsPointerConversion has already returned 2654 /// true. It returns true and produces a diagnostic if there was an 2655 /// error, or returns false otherwise. 2656 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2657 CastKind &Kind, 2658 CXXCastPath& BasePath, 2659 bool IgnoreBaseAccess) { 2660 QualType FromType = From->getType(); 2661 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2662 2663 Kind = CK_BitCast; 2664 2665 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2666 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2667 Expr::NPCK_ZeroExpression) { 2668 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2669 DiagRuntimeBehavior(From->getExprLoc(), From, 2670 PDiag(diag::warn_impcast_bool_to_null_pointer) 2671 << ToType << From->getSourceRange()); 2672 else if (!isUnevaluatedContext()) 2673 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2674 << ToType << From->getSourceRange(); 2675 } 2676 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2677 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2678 QualType FromPointeeType = FromPtrType->getPointeeType(), 2679 ToPointeeType = ToPtrType->getPointeeType(); 2680 2681 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2682 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2683 // We must have a derived-to-base conversion. Check an 2684 // ambiguous or inaccessible conversion. 2685 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2686 From->getExprLoc(), 2687 From->getSourceRange(), &BasePath, 2688 IgnoreBaseAccess)) 2689 return true; 2690 2691 // The conversion was successful. 2692 Kind = CK_DerivedToBase; 2693 } 2694 2695 if (!IsCStyleOrFunctionalCast && FromPointeeType->isFunctionType() && 2696 ToPointeeType->isVoidType()) { 2697 assert(getLangOpts().MSVCCompat && 2698 "this should only be possible with MSVCCompat!"); 2699 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2700 << From->getSourceRange(); 2701 } 2702 } 2703 } else if (const ObjCObjectPointerType *ToPtrType = 2704 ToType->getAs<ObjCObjectPointerType>()) { 2705 if (const ObjCObjectPointerType *FromPtrType = 2706 FromType->getAs<ObjCObjectPointerType>()) { 2707 // Objective-C++ conversions are always okay. 2708 // FIXME: We should have a different class of conversions for the 2709 // Objective-C++ implicit conversions. 2710 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2711 return false; 2712 } else if (FromType->isBlockPointerType()) { 2713 Kind = CK_BlockPointerToObjCPointerCast; 2714 } else { 2715 Kind = CK_CPointerToObjCPointerCast; 2716 } 2717 } else if (ToType->isBlockPointerType()) { 2718 if (!FromType->isBlockPointerType()) 2719 Kind = CK_AnyPointerToBlockPointerCast; 2720 } 2721 2722 // We shouldn't fall into this case unless it's valid for other 2723 // reasons. 2724 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2725 Kind = CK_NullToPointer; 2726 2727 return false; 2728 } 2729 2730 /// IsMemberPointerConversion - Determines whether the conversion of the 2731 /// expression From, which has the (possibly adjusted) type FromType, can be 2732 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2733 /// If so, returns true and places the converted type (that might differ from 2734 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2735 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2736 QualType ToType, 2737 bool InOverloadResolution, 2738 QualType &ConvertedType) { 2739 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2740 if (!ToTypePtr) 2741 return false; 2742 2743 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2744 if (From->isNullPointerConstant(Context, 2745 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2746 : Expr::NPC_ValueDependentIsNull)) { 2747 ConvertedType = ToType; 2748 return true; 2749 } 2750 2751 // Otherwise, both types have to be member pointers. 2752 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2753 if (!FromTypePtr) 2754 return false; 2755 2756 // A pointer to member of B can be converted to a pointer to member of D, 2757 // where D is derived from B (C++ 4.11p2). 2758 QualType FromClass(FromTypePtr->getClass(), 0); 2759 QualType ToClass(ToTypePtr->getClass(), 0); 2760 2761 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2762 !RequireCompleteType(From->getLocStart(), ToClass, 0) && 2763 IsDerivedFrom(ToClass, FromClass)) { 2764 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2765 ToClass.getTypePtr()); 2766 return true; 2767 } 2768 2769 return false; 2770 } 2771 2772 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2773 /// expression From to the type ToType. This routine checks for ambiguous or 2774 /// virtual or inaccessible base-to-derived member pointer conversions 2775 /// for which IsMemberPointerConversion has already returned true. It returns 2776 /// true and produces a diagnostic if there was an error, or returns false 2777 /// otherwise. 2778 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2779 CastKind &Kind, 2780 CXXCastPath &BasePath, 2781 bool IgnoreBaseAccess) { 2782 QualType FromType = From->getType(); 2783 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2784 if (!FromPtrType) { 2785 // This must be a null pointer to member pointer conversion 2786 assert(From->isNullPointerConstant(Context, 2787 Expr::NPC_ValueDependentIsNull) && 2788 "Expr must be null pointer constant!"); 2789 Kind = CK_NullToMemberPointer; 2790 return false; 2791 } 2792 2793 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2794 assert(ToPtrType && "No member pointer cast has a target type " 2795 "that is not a member pointer."); 2796 2797 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2798 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2799 2800 // FIXME: What about dependent types? 2801 assert(FromClass->isRecordType() && "Pointer into non-class."); 2802 assert(ToClass->isRecordType() && "Pointer into non-class."); 2803 2804 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2805 /*DetectVirtual=*/true); 2806 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2807 assert(DerivationOkay && 2808 "Should not have been called if derivation isn't OK."); 2809 (void)DerivationOkay; 2810 2811 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2812 getUnqualifiedType())) { 2813 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2814 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2815 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2816 return true; 2817 } 2818 2819 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2820 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2821 << FromClass << ToClass << QualType(VBase, 0) 2822 << From->getSourceRange(); 2823 return true; 2824 } 2825 2826 if (!IgnoreBaseAccess) 2827 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2828 Paths.front(), 2829 diag::err_downcast_from_inaccessible_base); 2830 2831 // Must be a base to derived member conversion. 2832 BuildBasePathArray(Paths, BasePath); 2833 Kind = CK_BaseToDerivedMemberPointer; 2834 return false; 2835 } 2836 2837 /// Determine whether the lifetime conversion between the two given 2838 /// qualifiers sets is nontrivial. 2839 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 2840 Qualifiers ToQuals) { 2841 // Converting anything to const __unsafe_unretained is trivial. 2842 if (ToQuals.hasConst() && 2843 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 2844 return false; 2845 2846 return true; 2847 } 2848 2849 /// IsQualificationConversion - Determines whether the conversion from 2850 /// an rvalue of type FromType to ToType is a qualification conversion 2851 /// (C++ 4.4). 2852 /// 2853 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2854 /// when the qualification conversion involves a change in the Objective-C 2855 /// object lifetime. 2856 bool 2857 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2858 bool CStyle, bool &ObjCLifetimeConversion) { 2859 FromType = Context.getCanonicalType(FromType); 2860 ToType = Context.getCanonicalType(ToType); 2861 ObjCLifetimeConversion = false; 2862 2863 // If FromType and ToType are the same type, this is not a 2864 // qualification conversion. 2865 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2866 return false; 2867 2868 // (C++ 4.4p4): 2869 // A conversion can add cv-qualifiers at levels other than the first 2870 // in multi-level pointers, subject to the following rules: [...] 2871 bool PreviousToQualsIncludeConst = true; 2872 bool UnwrappedAnyPointer = false; 2873 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2874 // Within each iteration of the loop, we check the qualifiers to 2875 // determine if this still looks like a qualification 2876 // conversion. Then, if all is well, we unwrap one more level of 2877 // pointers or pointers-to-members and do it all again 2878 // until there are no more pointers or pointers-to-members left to 2879 // unwrap. 2880 UnwrappedAnyPointer = true; 2881 2882 Qualifiers FromQuals = FromType.getQualifiers(); 2883 Qualifiers ToQuals = ToType.getQualifiers(); 2884 2885 // Objective-C ARC: 2886 // Check Objective-C lifetime conversions. 2887 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2888 UnwrappedAnyPointer) { 2889 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2890 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 2891 ObjCLifetimeConversion = true; 2892 FromQuals.removeObjCLifetime(); 2893 ToQuals.removeObjCLifetime(); 2894 } else { 2895 // Qualification conversions cannot cast between different 2896 // Objective-C lifetime qualifiers. 2897 return false; 2898 } 2899 } 2900 2901 // Allow addition/removal of GC attributes but not changing GC attributes. 2902 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2903 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2904 FromQuals.removeObjCGCAttr(); 2905 ToQuals.removeObjCGCAttr(); 2906 } 2907 2908 // -- for every j > 0, if const is in cv 1,j then const is in cv 2909 // 2,j, and similarly for volatile. 2910 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2911 return false; 2912 2913 // -- if the cv 1,j and cv 2,j are different, then const is in 2914 // every cv for 0 < k < j. 2915 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2916 && !PreviousToQualsIncludeConst) 2917 return false; 2918 2919 // Keep track of whether all prior cv-qualifiers in the "to" type 2920 // include const. 2921 PreviousToQualsIncludeConst 2922 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2923 } 2924 2925 // We are left with FromType and ToType being the pointee types 2926 // after unwrapping the original FromType and ToType the same number 2927 // of types. If we unwrapped any pointers, and if FromType and 2928 // ToType have the same unqualified type (since we checked 2929 // qualifiers above), then this is a qualification conversion. 2930 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2931 } 2932 2933 /// \brief - Determine whether this is a conversion from a scalar type to an 2934 /// atomic type. 2935 /// 2936 /// If successful, updates \c SCS's second and third steps in the conversion 2937 /// sequence to finish the conversion. 2938 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2939 bool InOverloadResolution, 2940 StandardConversionSequence &SCS, 2941 bool CStyle) { 2942 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2943 if (!ToAtomic) 2944 return false; 2945 2946 StandardConversionSequence InnerSCS; 2947 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2948 InOverloadResolution, InnerSCS, 2949 CStyle, /*AllowObjCWritebackConversion=*/false)) 2950 return false; 2951 2952 SCS.Second = InnerSCS.Second; 2953 SCS.setToType(1, InnerSCS.getToType(1)); 2954 SCS.Third = InnerSCS.Third; 2955 SCS.QualificationIncludesObjCLifetime 2956 = InnerSCS.QualificationIncludesObjCLifetime; 2957 SCS.setToType(2, InnerSCS.getToType(2)); 2958 return true; 2959 } 2960 2961 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2962 CXXConstructorDecl *Constructor, 2963 QualType Type) { 2964 const FunctionProtoType *CtorType = 2965 Constructor->getType()->getAs<FunctionProtoType>(); 2966 if (CtorType->getNumParams() > 0) { 2967 QualType FirstArg = CtorType->getParamType(0); 2968 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2969 return true; 2970 } 2971 return false; 2972 } 2973 2974 static OverloadingResult 2975 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2976 CXXRecordDecl *To, 2977 UserDefinedConversionSequence &User, 2978 OverloadCandidateSet &CandidateSet, 2979 bool AllowExplicit) { 2980 DeclContext::lookup_result R = S.LookupConstructors(To); 2981 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 2982 Con != ConEnd; ++Con) { 2983 NamedDecl *D = *Con; 2984 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2985 2986 // Find the constructor (which may be a template). 2987 CXXConstructorDecl *Constructor = nullptr; 2988 FunctionTemplateDecl *ConstructorTmpl 2989 = dyn_cast<FunctionTemplateDecl>(D); 2990 if (ConstructorTmpl) 2991 Constructor 2992 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2993 else 2994 Constructor = cast<CXXConstructorDecl>(D); 2995 2996 bool Usable = !Constructor->isInvalidDecl() && 2997 S.isInitListConstructor(Constructor) && 2998 (AllowExplicit || !Constructor->isExplicit()); 2999 if (Usable) { 3000 // If the first argument is (a reference to) the target type, 3001 // suppress conversions. 3002 bool SuppressUserConversions = 3003 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 3004 if (ConstructorTmpl) 3005 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3006 /*ExplicitArgs*/ nullptr, 3007 From, CandidateSet, 3008 SuppressUserConversions); 3009 else 3010 S.AddOverloadCandidate(Constructor, FoundDecl, 3011 From, CandidateSet, 3012 SuppressUserConversions); 3013 } 3014 } 3015 3016 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3017 3018 OverloadCandidateSet::iterator Best; 3019 switch (auto Result = 3020 CandidateSet.BestViableFunction(S, From->getLocStart(), 3021 Best, true)) { 3022 case OR_Deleted: 3023 case OR_Success: { 3024 // Record the standard conversion we used and the conversion function. 3025 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3026 QualType ThisType = Constructor->getThisType(S.Context); 3027 // Initializer lists don't have conversions as such. 3028 User.Before.setAsIdentityConversion(); 3029 User.HadMultipleCandidates = HadMultipleCandidates; 3030 User.ConversionFunction = Constructor; 3031 User.FoundConversionFunction = Best->FoundDecl; 3032 User.After.setAsIdentityConversion(); 3033 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3034 User.After.setAllToTypes(ToType); 3035 return Result; 3036 } 3037 3038 case OR_No_Viable_Function: 3039 return OR_No_Viable_Function; 3040 case OR_Ambiguous: 3041 return OR_Ambiguous; 3042 } 3043 3044 llvm_unreachable("Invalid OverloadResult!"); 3045 } 3046 3047 /// Determines whether there is a user-defined conversion sequence 3048 /// (C++ [over.ics.user]) that converts expression From to the type 3049 /// ToType. If such a conversion exists, User will contain the 3050 /// user-defined conversion sequence that performs such a conversion 3051 /// and this routine will return true. Otherwise, this routine returns 3052 /// false and User is unspecified. 3053 /// 3054 /// \param AllowExplicit true if the conversion should consider C++0x 3055 /// "explicit" conversion functions as well as non-explicit conversion 3056 /// functions (C++0x [class.conv.fct]p2). 3057 /// 3058 /// \param AllowObjCConversionOnExplicit true if the conversion should 3059 /// allow an extra Objective-C pointer conversion on uses of explicit 3060 /// constructors. Requires \c AllowExplicit to also be set. 3061 static OverloadingResult 3062 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3063 UserDefinedConversionSequence &User, 3064 OverloadCandidateSet &CandidateSet, 3065 bool AllowExplicit, 3066 bool AllowObjCConversionOnExplicit) { 3067 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3068 3069 // Whether we will only visit constructors. 3070 bool ConstructorsOnly = false; 3071 3072 // If the type we are conversion to is a class type, enumerate its 3073 // constructors. 3074 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3075 // C++ [over.match.ctor]p1: 3076 // When objects of class type are direct-initialized (8.5), or 3077 // copy-initialized from an expression of the same or a 3078 // derived class type (8.5), overload resolution selects the 3079 // constructor. [...] For copy-initialization, the candidate 3080 // functions are all the converting constructors (12.3.1) of 3081 // that class. The argument list is the expression-list within 3082 // the parentheses of the initializer. 3083 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3084 (From->getType()->getAs<RecordType>() && 3085 S.IsDerivedFrom(From->getType(), ToType))) 3086 ConstructorsOnly = true; 3087 3088 S.RequireCompleteType(From->getExprLoc(), ToType, 0); 3089 // RequireCompleteType may have returned true due to some invalid decl 3090 // during template instantiation, but ToType may be complete enough now 3091 // to try to recover. 3092 if (ToType->isIncompleteType()) { 3093 // We're not going to find any constructors. 3094 } else if (CXXRecordDecl *ToRecordDecl 3095 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3096 3097 Expr **Args = &From; 3098 unsigned NumArgs = 1; 3099 bool ListInitializing = false; 3100 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3101 // But first, see if there is an init-list-constructor that will work. 3102 OverloadingResult Result = IsInitializerListConstructorConversion( 3103 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3104 if (Result != OR_No_Viable_Function) 3105 return Result; 3106 // Never mind. 3107 CandidateSet.clear(); 3108 3109 // If we're list-initializing, we pass the individual elements as 3110 // arguments, not the entire list. 3111 Args = InitList->getInits(); 3112 NumArgs = InitList->getNumInits(); 3113 ListInitializing = true; 3114 } 3115 3116 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl); 3117 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end(); 3118 Con != ConEnd; ++Con) { 3119 NamedDecl *D = *Con; 3120 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 3121 3122 // Find the constructor (which may be a template). 3123 CXXConstructorDecl *Constructor = nullptr; 3124 FunctionTemplateDecl *ConstructorTmpl 3125 = dyn_cast<FunctionTemplateDecl>(D); 3126 if (ConstructorTmpl) 3127 Constructor 3128 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 3129 else 3130 Constructor = cast<CXXConstructorDecl>(D); 3131 3132 bool Usable = !Constructor->isInvalidDecl(); 3133 if (ListInitializing) 3134 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 3135 else 3136 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 3137 if (Usable) { 3138 bool SuppressUserConversions = !ConstructorsOnly; 3139 if (SuppressUserConversions && ListInitializing) { 3140 SuppressUserConversions = false; 3141 if (NumArgs == 1) { 3142 // If the first argument is (a reference to) the target type, 3143 // suppress conversions. 3144 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3145 S.Context, Constructor, ToType); 3146 } 3147 } 3148 if (ConstructorTmpl) 3149 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 3150 /*ExplicitArgs*/ nullptr, 3151 llvm::makeArrayRef(Args, NumArgs), 3152 CandidateSet, SuppressUserConversions); 3153 else 3154 // Allow one user-defined conversion when user specifies a 3155 // From->ToType conversion via an static cast (c-style, etc). 3156 S.AddOverloadCandidate(Constructor, FoundDecl, 3157 llvm::makeArrayRef(Args, NumArgs), 3158 CandidateSet, SuppressUserConversions); 3159 } 3160 } 3161 } 3162 } 3163 3164 // Enumerate conversion functions, if we're allowed to. 3165 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3166 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) { 3167 // No conversion functions from incomplete types. 3168 } else if (const RecordType *FromRecordType 3169 = From->getType()->getAs<RecordType>()) { 3170 if (CXXRecordDecl *FromRecordDecl 3171 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3172 // Add all of the conversion functions as candidates. 3173 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3174 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3175 DeclAccessPair FoundDecl = I.getPair(); 3176 NamedDecl *D = FoundDecl.getDecl(); 3177 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3178 if (isa<UsingShadowDecl>(D)) 3179 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3180 3181 CXXConversionDecl *Conv; 3182 FunctionTemplateDecl *ConvTemplate; 3183 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3184 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3185 else 3186 Conv = cast<CXXConversionDecl>(D); 3187 3188 if (AllowExplicit || !Conv->isExplicit()) { 3189 if (ConvTemplate) 3190 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3191 ActingContext, From, ToType, 3192 CandidateSet, 3193 AllowObjCConversionOnExplicit); 3194 else 3195 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3196 From, ToType, CandidateSet, 3197 AllowObjCConversionOnExplicit); 3198 } 3199 } 3200 } 3201 } 3202 3203 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3204 3205 OverloadCandidateSet::iterator Best; 3206 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(), 3207 Best, true)) { 3208 case OR_Success: 3209 case OR_Deleted: 3210 // Record the standard conversion we used and the conversion function. 3211 if (CXXConstructorDecl *Constructor 3212 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3213 // C++ [over.ics.user]p1: 3214 // If the user-defined conversion is specified by a 3215 // constructor (12.3.1), the initial standard conversion 3216 // sequence converts the source type to the type required by 3217 // the argument of the constructor. 3218 // 3219 QualType ThisType = Constructor->getThisType(S.Context); 3220 if (isa<InitListExpr>(From)) { 3221 // Initializer lists don't have conversions as such. 3222 User.Before.setAsIdentityConversion(); 3223 } else { 3224 if (Best->Conversions[0].isEllipsis()) 3225 User.EllipsisConversion = true; 3226 else { 3227 User.Before = Best->Conversions[0].Standard; 3228 User.EllipsisConversion = false; 3229 } 3230 } 3231 User.HadMultipleCandidates = HadMultipleCandidates; 3232 User.ConversionFunction = Constructor; 3233 User.FoundConversionFunction = Best->FoundDecl; 3234 User.After.setAsIdentityConversion(); 3235 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3236 User.After.setAllToTypes(ToType); 3237 return Result; 3238 } 3239 if (CXXConversionDecl *Conversion 3240 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3241 // C++ [over.ics.user]p1: 3242 // 3243 // [...] If the user-defined conversion is specified by a 3244 // conversion function (12.3.2), the initial standard 3245 // conversion sequence converts the source type to the 3246 // implicit object parameter of the conversion function. 3247 User.Before = Best->Conversions[0].Standard; 3248 User.HadMultipleCandidates = HadMultipleCandidates; 3249 User.ConversionFunction = Conversion; 3250 User.FoundConversionFunction = Best->FoundDecl; 3251 User.EllipsisConversion = false; 3252 3253 // C++ [over.ics.user]p2: 3254 // The second standard conversion sequence converts the 3255 // result of the user-defined conversion to the target type 3256 // for the sequence. Since an implicit conversion sequence 3257 // is an initialization, the special rules for 3258 // initialization by user-defined conversion apply when 3259 // selecting the best user-defined conversion for a 3260 // user-defined conversion sequence (see 13.3.3 and 3261 // 13.3.3.1). 3262 User.After = Best->FinalConversion; 3263 return Result; 3264 } 3265 llvm_unreachable("Not a constructor or conversion function?"); 3266 3267 case OR_No_Viable_Function: 3268 return OR_No_Viable_Function; 3269 3270 case OR_Ambiguous: 3271 return OR_Ambiguous; 3272 } 3273 3274 llvm_unreachable("Invalid OverloadResult!"); 3275 } 3276 3277 bool 3278 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3279 ImplicitConversionSequence ICS; 3280 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3281 OverloadCandidateSet::CSK_Normal); 3282 OverloadingResult OvResult = 3283 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3284 CandidateSet, false, false); 3285 if (OvResult == OR_Ambiguous) 3286 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3287 << From->getType() << ToType << From->getSourceRange(); 3288 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3289 if (!RequireCompleteType(From->getLocStart(), ToType, 3290 diag::err_typecheck_nonviable_condition_incomplete, 3291 From->getType(), From->getSourceRange())) 3292 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3293 << false << From->getType() << From->getSourceRange() << ToType; 3294 } else 3295 return false; 3296 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3297 return true; 3298 } 3299 3300 /// \brief Compare the user-defined conversion functions or constructors 3301 /// of two user-defined conversion sequences to determine whether any ordering 3302 /// is possible. 3303 static ImplicitConversionSequence::CompareKind 3304 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3305 FunctionDecl *Function2) { 3306 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3307 return ImplicitConversionSequence::Indistinguishable; 3308 3309 // Objective-C++: 3310 // If both conversion functions are implicitly-declared conversions from 3311 // a lambda closure type to a function pointer and a block pointer, 3312 // respectively, always prefer the conversion to a function pointer, 3313 // because the function pointer is more lightweight and is more likely 3314 // to keep code working. 3315 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3316 if (!Conv1) 3317 return ImplicitConversionSequence::Indistinguishable; 3318 3319 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3320 if (!Conv2) 3321 return ImplicitConversionSequence::Indistinguishable; 3322 3323 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3324 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3325 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3326 if (Block1 != Block2) 3327 return Block1 ? ImplicitConversionSequence::Worse 3328 : ImplicitConversionSequence::Better; 3329 } 3330 3331 return ImplicitConversionSequence::Indistinguishable; 3332 } 3333 3334 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3335 const ImplicitConversionSequence &ICS) { 3336 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3337 (ICS.isUserDefined() && 3338 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3339 } 3340 3341 /// CompareImplicitConversionSequences - Compare two implicit 3342 /// conversion sequences to determine whether one is better than the 3343 /// other or if they are indistinguishable (C++ 13.3.3.2). 3344 static ImplicitConversionSequence::CompareKind 3345 CompareImplicitConversionSequences(Sema &S, 3346 const ImplicitConversionSequence& ICS1, 3347 const ImplicitConversionSequence& ICS2) 3348 { 3349 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3350 // conversion sequences (as defined in 13.3.3.1) 3351 // -- a standard conversion sequence (13.3.3.1.1) is a better 3352 // conversion sequence than a user-defined conversion sequence or 3353 // an ellipsis conversion sequence, and 3354 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3355 // conversion sequence than an ellipsis conversion sequence 3356 // (13.3.3.1.3). 3357 // 3358 // C++0x [over.best.ics]p10: 3359 // For the purpose of ranking implicit conversion sequences as 3360 // described in 13.3.3.2, the ambiguous conversion sequence is 3361 // treated as a user-defined sequence that is indistinguishable 3362 // from any other user-defined conversion sequence. 3363 3364 // String literal to 'char *' conversion has been deprecated in C++03. It has 3365 // been removed from C++11. We still accept this conversion, if it happens at 3366 // the best viable function. Otherwise, this conversion is considered worse 3367 // than ellipsis conversion. Consider this as an extension; this is not in the 3368 // standard. For example: 3369 // 3370 // int &f(...); // #1 3371 // void f(char*); // #2 3372 // void g() { int &r = f("foo"); } 3373 // 3374 // In C++03, we pick #2 as the best viable function. 3375 // In C++11, we pick #1 as the best viable function, because ellipsis 3376 // conversion is better than string-literal to char* conversion (since there 3377 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3378 // convert arguments, #2 would be the best viable function in C++11. 3379 // If the best viable function has this conversion, a warning will be issued 3380 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3381 3382 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3383 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3384 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3385 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3386 ? ImplicitConversionSequence::Worse 3387 : ImplicitConversionSequence::Better; 3388 3389 if (ICS1.getKindRank() < ICS2.getKindRank()) 3390 return ImplicitConversionSequence::Better; 3391 if (ICS2.getKindRank() < ICS1.getKindRank()) 3392 return ImplicitConversionSequence::Worse; 3393 3394 // The following checks require both conversion sequences to be of 3395 // the same kind. 3396 if (ICS1.getKind() != ICS2.getKind()) 3397 return ImplicitConversionSequence::Indistinguishable; 3398 3399 ImplicitConversionSequence::CompareKind Result = 3400 ImplicitConversionSequence::Indistinguishable; 3401 3402 // Two implicit conversion sequences of the same form are 3403 // indistinguishable conversion sequences unless one of the 3404 // following rules apply: (C++ 13.3.3.2p3): 3405 3406 // List-initialization sequence L1 is a better conversion sequence than 3407 // list-initialization sequence L2 if: 3408 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3409 // if not that, 3410 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3411 // and N1 is smaller than N2., 3412 // even if one of the other rules in this paragraph would otherwise apply. 3413 if (!ICS1.isBad()) { 3414 if (ICS1.isStdInitializerListElement() && 3415 !ICS2.isStdInitializerListElement()) 3416 return ImplicitConversionSequence::Better; 3417 if (!ICS1.isStdInitializerListElement() && 3418 ICS2.isStdInitializerListElement()) 3419 return ImplicitConversionSequence::Worse; 3420 } 3421 3422 if (ICS1.isStandard()) 3423 // Standard conversion sequence S1 is a better conversion sequence than 3424 // standard conversion sequence S2 if [...] 3425 Result = CompareStandardConversionSequences(S, 3426 ICS1.Standard, ICS2.Standard); 3427 else if (ICS1.isUserDefined()) { 3428 // User-defined conversion sequence U1 is a better conversion 3429 // sequence than another user-defined conversion sequence U2 if 3430 // they contain the same user-defined conversion function or 3431 // constructor and if the second standard conversion sequence of 3432 // U1 is better than the second standard conversion sequence of 3433 // U2 (C++ 13.3.3.2p3). 3434 if (ICS1.UserDefined.ConversionFunction == 3435 ICS2.UserDefined.ConversionFunction) 3436 Result = CompareStandardConversionSequences(S, 3437 ICS1.UserDefined.After, 3438 ICS2.UserDefined.After); 3439 else 3440 Result = compareConversionFunctions(S, 3441 ICS1.UserDefined.ConversionFunction, 3442 ICS2.UserDefined.ConversionFunction); 3443 } 3444 3445 return Result; 3446 } 3447 3448 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3449 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3450 Qualifiers Quals; 3451 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3452 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3453 } 3454 3455 return Context.hasSameUnqualifiedType(T1, T2); 3456 } 3457 3458 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3459 // determine if one is a proper subset of the other. 3460 static ImplicitConversionSequence::CompareKind 3461 compareStandardConversionSubsets(ASTContext &Context, 3462 const StandardConversionSequence& SCS1, 3463 const StandardConversionSequence& SCS2) { 3464 ImplicitConversionSequence::CompareKind Result 3465 = ImplicitConversionSequence::Indistinguishable; 3466 3467 // the identity conversion sequence is considered to be a subsequence of 3468 // any non-identity conversion sequence 3469 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3470 return ImplicitConversionSequence::Better; 3471 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3472 return ImplicitConversionSequence::Worse; 3473 3474 if (SCS1.Second != SCS2.Second) { 3475 if (SCS1.Second == ICK_Identity) 3476 Result = ImplicitConversionSequence::Better; 3477 else if (SCS2.Second == ICK_Identity) 3478 Result = ImplicitConversionSequence::Worse; 3479 else 3480 return ImplicitConversionSequence::Indistinguishable; 3481 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3482 return ImplicitConversionSequence::Indistinguishable; 3483 3484 if (SCS1.Third == SCS2.Third) { 3485 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3486 : ImplicitConversionSequence::Indistinguishable; 3487 } 3488 3489 if (SCS1.Third == ICK_Identity) 3490 return Result == ImplicitConversionSequence::Worse 3491 ? ImplicitConversionSequence::Indistinguishable 3492 : ImplicitConversionSequence::Better; 3493 3494 if (SCS2.Third == ICK_Identity) 3495 return Result == ImplicitConversionSequence::Better 3496 ? ImplicitConversionSequence::Indistinguishable 3497 : ImplicitConversionSequence::Worse; 3498 3499 return ImplicitConversionSequence::Indistinguishable; 3500 } 3501 3502 /// \brief Determine whether one of the given reference bindings is better 3503 /// than the other based on what kind of bindings they are. 3504 static bool 3505 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3506 const StandardConversionSequence &SCS2) { 3507 // C++0x [over.ics.rank]p3b4: 3508 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3509 // implicit object parameter of a non-static member function declared 3510 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3511 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3512 // lvalue reference to a function lvalue and S2 binds an rvalue 3513 // reference*. 3514 // 3515 // FIXME: Rvalue references. We're going rogue with the above edits, 3516 // because the semantics in the current C++0x working paper (N3225 at the 3517 // time of this writing) break the standard definition of std::forward 3518 // and std::reference_wrapper when dealing with references to functions. 3519 // Proposed wording changes submitted to CWG for consideration. 3520 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3521 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3522 return false; 3523 3524 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3525 SCS2.IsLvalueReference) || 3526 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3527 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3528 } 3529 3530 /// CompareStandardConversionSequences - Compare two standard 3531 /// conversion sequences to determine whether one is better than the 3532 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3533 static ImplicitConversionSequence::CompareKind 3534 CompareStandardConversionSequences(Sema &S, 3535 const StandardConversionSequence& SCS1, 3536 const StandardConversionSequence& SCS2) 3537 { 3538 // Standard conversion sequence S1 is a better conversion sequence 3539 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3540 3541 // -- S1 is a proper subsequence of S2 (comparing the conversion 3542 // sequences in the canonical form defined by 13.3.3.1.1, 3543 // excluding any Lvalue Transformation; the identity conversion 3544 // sequence is considered to be a subsequence of any 3545 // non-identity conversion sequence) or, if not that, 3546 if (ImplicitConversionSequence::CompareKind CK 3547 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3548 return CK; 3549 3550 // -- the rank of S1 is better than the rank of S2 (by the rules 3551 // defined below), or, if not that, 3552 ImplicitConversionRank Rank1 = SCS1.getRank(); 3553 ImplicitConversionRank Rank2 = SCS2.getRank(); 3554 if (Rank1 < Rank2) 3555 return ImplicitConversionSequence::Better; 3556 else if (Rank2 < Rank1) 3557 return ImplicitConversionSequence::Worse; 3558 3559 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3560 // are indistinguishable unless one of the following rules 3561 // applies: 3562 3563 // A conversion that is not a conversion of a pointer, or 3564 // pointer to member, to bool is better than another conversion 3565 // that is such a conversion. 3566 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3567 return SCS2.isPointerConversionToBool() 3568 ? ImplicitConversionSequence::Better 3569 : ImplicitConversionSequence::Worse; 3570 3571 // C++ [over.ics.rank]p4b2: 3572 // 3573 // If class B is derived directly or indirectly from class A, 3574 // conversion of B* to A* is better than conversion of B* to 3575 // void*, and conversion of A* to void* is better than conversion 3576 // of B* to void*. 3577 bool SCS1ConvertsToVoid 3578 = SCS1.isPointerConversionToVoidPointer(S.Context); 3579 bool SCS2ConvertsToVoid 3580 = SCS2.isPointerConversionToVoidPointer(S.Context); 3581 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3582 // Exactly one of the conversion sequences is a conversion to 3583 // a void pointer; it's the worse conversion. 3584 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3585 : ImplicitConversionSequence::Worse; 3586 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3587 // Neither conversion sequence converts to a void pointer; compare 3588 // their derived-to-base conversions. 3589 if (ImplicitConversionSequence::CompareKind DerivedCK 3590 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3591 return DerivedCK; 3592 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3593 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3594 // Both conversion sequences are conversions to void 3595 // pointers. Compare the source types to determine if there's an 3596 // inheritance relationship in their sources. 3597 QualType FromType1 = SCS1.getFromType(); 3598 QualType FromType2 = SCS2.getFromType(); 3599 3600 // Adjust the types we're converting from via the array-to-pointer 3601 // conversion, if we need to. 3602 if (SCS1.First == ICK_Array_To_Pointer) 3603 FromType1 = S.Context.getArrayDecayedType(FromType1); 3604 if (SCS2.First == ICK_Array_To_Pointer) 3605 FromType2 = S.Context.getArrayDecayedType(FromType2); 3606 3607 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3608 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3609 3610 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3611 return ImplicitConversionSequence::Better; 3612 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3613 return ImplicitConversionSequence::Worse; 3614 3615 // Objective-C++: If one interface is more specific than the 3616 // other, it is the better one. 3617 const ObjCObjectPointerType* FromObjCPtr1 3618 = FromType1->getAs<ObjCObjectPointerType>(); 3619 const ObjCObjectPointerType* FromObjCPtr2 3620 = FromType2->getAs<ObjCObjectPointerType>(); 3621 if (FromObjCPtr1 && FromObjCPtr2) { 3622 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3623 FromObjCPtr2); 3624 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3625 FromObjCPtr1); 3626 if (AssignLeft != AssignRight) { 3627 return AssignLeft? ImplicitConversionSequence::Better 3628 : ImplicitConversionSequence::Worse; 3629 } 3630 } 3631 } 3632 3633 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3634 // bullet 3). 3635 if (ImplicitConversionSequence::CompareKind QualCK 3636 = CompareQualificationConversions(S, SCS1, SCS2)) 3637 return QualCK; 3638 3639 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3640 // Check for a better reference binding based on the kind of bindings. 3641 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3642 return ImplicitConversionSequence::Better; 3643 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3644 return ImplicitConversionSequence::Worse; 3645 3646 // C++ [over.ics.rank]p3b4: 3647 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3648 // which the references refer are the same type except for 3649 // top-level cv-qualifiers, and the type to which the reference 3650 // initialized by S2 refers is more cv-qualified than the type 3651 // to which the reference initialized by S1 refers. 3652 QualType T1 = SCS1.getToType(2); 3653 QualType T2 = SCS2.getToType(2); 3654 T1 = S.Context.getCanonicalType(T1); 3655 T2 = S.Context.getCanonicalType(T2); 3656 Qualifiers T1Quals, T2Quals; 3657 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3658 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3659 if (UnqualT1 == UnqualT2) { 3660 // Objective-C++ ARC: If the references refer to objects with different 3661 // lifetimes, prefer bindings that don't change lifetime. 3662 if (SCS1.ObjCLifetimeConversionBinding != 3663 SCS2.ObjCLifetimeConversionBinding) { 3664 return SCS1.ObjCLifetimeConversionBinding 3665 ? ImplicitConversionSequence::Worse 3666 : ImplicitConversionSequence::Better; 3667 } 3668 3669 // If the type is an array type, promote the element qualifiers to the 3670 // type for comparison. 3671 if (isa<ArrayType>(T1) && T1Quals) 3672 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3673 if (isa<ArrayType>(T2) && T2Quals) 3674 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3675 if (T2.isMoreQualifiedThan(T1)) 3676 return ImplicitConversionSequence::Better; 3677 else if (T1.isMoreQualifiedThan(T2)) 3678 return ImplicitConversionSequence::Worse; 3679 } 3680 } 3681 3682 // In Microsoft mode, prefer an integral conversion to a 3683 // floating-to-integral conversion if the integral conversion 3684 // is between types of the same size. 3685 // For example: 3686 // void f(float); 3687 // void f(int); 3688 // int main { 3689 // long a; 3690 // f(a); 3691 // } 3692 // Here, MSVC will call f(int) instead of generating a compile error 3693 // as clang will do in standard mode. 3694 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3695 SCS2.Second == ICK_Floating_Integral && 3696 S.Context.getTypeSize(SCS1.getFromType()) == 3697 S.Context.getTypeSize(SCS1.getToType(2))) 3698 return ImplicitConversionSequence::Better; 3699 3700 return ImplicitConversionSequence::Indistinguishable; 3701 } 3702 3703 /// CompareQualificationConversions - Compares two standard conversion 3704 /// sequences to determine whether they can be ranked based on their 3705 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3706 static ImplicitConversionSequence::CompareKind 3707 CompareQualificationConversions(Sema &S, 3708 const StandardConversionSequence& SCS1, 3709 const StandardConversionSequence& SCS2) { 3710 // C++ 13.3.3.2p3: 3711 // -- S1 and S2 differ only in their qualification conversion and 3712 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3713 // cv-qualification signature of type T1 is a proper subset of 3714 // the cv-qualification signature of type T2, and S1 is not the 3715 // deprecated string literal array-to-pointer conversion (4.2). 3716 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3717 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3718 return ImplicitConversionSequence::Indistinguishable; 3719 3720 // FIXME: the example in the standard doesn't use a qualification 3721 // conversion (!) 3722 QualType T1 = SCS1.getToType(2); 3723 QualType T2 = SCS2.getToType(2); 3724 T1 = S.Context.getCanonicalType(T1); 3725 T2 = S.Context.getCanonicalType(T2); 3726 Qualifiers T1Quals, T2Quals; 3727 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3728 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3729 3730 // If the types are the same, we won't learn anything by unwrapped 3731 // them. 3732 if (UnqualT1 == UnqualT2) 3733 return ImplicitConversionSequence::Indistinguishable; 3734 3735 // If the type is an array type, promote the element qualifiers to the type 3736 // for comparison. 3737 if (isa<ArrayType>(T1) && T1Quals) 3738 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3739 if (isa<ArrayType>(T2) && T2Quals) 3740 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3741 3742 ImplicitConversionSequence::CompareKind Result 3743 = ImplicitConversionSequence::Indistinguishable; 3744 3745 // Objective-C++ ARC: 3746 // Prefer qualification conversions not involving a change in lifetime 3747 // to qualification conversions that do not change lifetime. 3748 if (SCS1.QualificationIncludesObjCLifetime != 3749 SCS2.QualificationIncludesObjCLifetime) { 3750 Result = SCS1.QualificationIncludesObjCLifetime 3751 ? ImplicitConversionSequence::Worse 3752 : ImplicitConversionSequence::Better; 3753 } 3754 3755 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3756 // Within each iteration of the loop, we check the qualifiers to 3757 // determine if this still looks like a qualification 3758 // conversion. Then, if all is well, we unwrap one more level of 3759 // pointers or pointers-to-members and do it all again 3760 // until there are no more pointers or pointers-to-members left 3761 // to unwrap. This essentially mimics what 3762 // IsQualificationConversion does, but here we're checking for a 3763 // strict subset of qualifiers. 3764 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3765 // The qualifiers are the same, so this doesn't tell us anything 3766 // about how the sequences rank. 3767 ; 3768 else if (T2.isMoreQualifiedThan(T1)) { 3769 // T1 has fewer qualifiers, so it could be the better sequence. 3770 if (Result == ImplicitConversionSequence::Worse) 3771 // Neither has qualifiers that are a subset of the other's 3772 // qualifiers. 3773 return ImplicitConversionSequence::Indistinguishable; 3774 3775 Result = ImplicitConversionSequence::Better; 3776 } else if (T1.isMoreQualifiedThan(T2)) { 3777 // T2 has fewer qualifiers, so it could be the better sequence. 3778 if (Result == ImplicitConversionSequence::Better) 3779 // Neither has qualifiers that are a subset of the other's 3780 // qualifiers. 3781 return ImplicitConversionSequence::Indistinguishable; 3782 3783 Result = ImplicitConversionSequence::Worse; 3784 } else { 3785 // Qualifiers are disjoint. 3786 return ImplicitConversionSequence::Indistinguishable; 3787 } 3788 3789 // If the types after this point are equivalent, we're done. 3790 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3791 break; 3792 } 3793 3794 // Check that the winning standard conversion sequence isn't using 3795 // the deprecated string literal array to pointer conversion. 3796 switch (Result) { 3797 case ImplicitConversionSequence::Better: 3798 if (SCS1.DeprecatedStringLiteralToCharPtr) 3799 Result = ImplicitConversionSequence::Indistinguishable; 3800 break; 3801 3802 case ImplicitConversionSequence::Indistinguishable: 3803 break; 3804 3805 case ImplicitConversionSequence::Worse: 3806 if (SCS2.DeprecatedStringLiteralToCharPtr) 3807 Result = ImplicitConversionSequence::Indistinguishable; 3808 break; 3809 } 3810 3811 return Result; 3812 } 3813 3814 /// CompareDerivedToBaseConversions - Compares two standard conversion 3815 /// sequences to determine whether they can be ranked based on their 3816 /// various kinds of derived-to-base conversions (C++ 3817 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3818 /// conversions between Objective-C interface types. 3819 static ImplicitConversionSequence::CompareKind 3820 CompareDerivedToBaseConversions(Sema &S, 3821 const StandardConversionSequence& SCS1, 3822 const StandardConversionSequence& SCS2) { 3823 QualType FromType1 = SCS1.getFromType(); 3824 QualType ToType1 = SCS1.getToType(1); 3825 QualType FromType2 = SCS2.getFromType(); 3826 QualType ToType2 = SCS2.getToType(1); 3827 3828 // Adjust the types we're converting from via the array-to-pointer 3829 // conversion, if we need to. 3830 if (SCS1.First == ICK_Array_To_Pointer) 3831 FromType1 = S.Context.getArrayDecayedType(FromType1); 3832 if (SCS2.First == ICK_Array_To_Pointer) 3833 FromType2 = S.Context.getArrayDecayedType(FromType2); 3834 3835 // Canonicalize all of the types. 3836 FromType1 = S.Context.getCanonicalType(FromType1); 3837 ToType1 = S.Context.getCanonicalType(ToType1); 3838 FromType2 = S.Context.getCanonicalType(FromType2); 3839 ToType2 = S.Context.getCanonicalType(ToType2); 3840 3841 // C++ [over.ics.rank]p4b3: 3842 // 3843 // If class B is derived directly or indirectly from class A and 3844 // class C is derived directly or indirectly from B, 3845 // 3846 // Compare based on pointer conversions. 3847 if (SCS1.Second == ICK_Pointer_Conversion && 3848 SCS2.Second == ICK_Pointer_Conversion && 3849 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3850 FromType1->isPointerType() && FromType2->isPointerType() && 3851 ToType1->isPointerType() && ToType2->isPointerType()) { 3852 QualType FromPointee1 3853 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3854 QualType ToPointee1 3855 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3856 QualType FromPointee2 3857 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3858 QualType ToPointee2 3859 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3860 3861 // -- conversion of C* to B* is better than conversion of C* to A*, 3862 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3863 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3864 return ImplicitConversionSequence::Better; 3865 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3866 return ImplicitConversionSequence::Worse; 3867 } 3868 3869 // -- conversion of B* to A* is better than conversion of C* to A*, 3870 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3871 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3872 return ImplicitConversionSequence::Better; 3873 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3874 return ImplicitConversionSequence::Worse; 3875 } 3876 } else if (SCS1.Second == ICK_Pointer_Conversion && 3877 SCS2.Second == ICK_Pointer_Conversion) { 3878 const ObjCObjectPointerType *FromPtr1 3879 = FromType1->getAs<ObjCObjectPointerType>(); 3880 const ObjCObjectPointerType *FromPtr2 3881 = FromType2->getAs<ObjCObjectPointerType>(); 3882 const ObjCObjectPointerType *ToPtr1 3883 = ToType1->getAs<ObjCObjectPointerType>(); 3884 const ObjCObjectPointerType *ToPtr2 3885 = ToType2->getAs<ObjCObjectPointerType>(); 3886 3887 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3888 // Apply the same conversion ranking rules for Objective-C pointer types 3889 // that we do for C++ pointers to class types. However, we employ the 3890 // Objective-C pseudo-subtyping relationship used for assignment of 3891 // Objective-C pointer types. 3892 bool FromAssignLeft 3893 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3894 bool FromAssignRight 3895 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3896 bool ToAssignLeft 3897 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3898 bool ToAssignRight 3899 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3900 3901 // A conversion to an a non-id object pointer type or qualified 'id' 3902 // type is better than a conversion to 'id'. 3903 if (ToPtr1->isObjCIdType() && 3904 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3905 return ImplicitConversionSequence::Worse; 3906 if (ToPtr2->isObjCIdType() && 3907 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3908 return ImplicitConversionSequence::Better; 3909 3910 // A conversion to a non-id object pointer type is better than a 3911 // conversion to a qualified 'id' type 3912 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3913 return ImplicitConversionSequence::Worse; 3914 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3915 return ImplicitConversionSequence::Better; 3916 3917 // A conversion to an a non-Class object pointer type or qualified 'Class' 3918 // type is better than a conversion to 'Class'. 3919 if (ToPtr1->isObjCClassType() && 3920 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3921 return ImplicitConversionSequence::Worse; 3922 if (ToPtr2->isObjCClassType() && 3923 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3924 return ImplicitConversionSequence::Better; 3925 3926 // A conversion to a non-Class object pointer type is better than a 3927 // conversion to a qualified 'Class' type. 3928 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3929 return ImplicitConversionSequence::Worse; 3930 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3931 return ImplicitConversionSequence::Better; 3932 3933 // -- "conversion of C* to B* is better than conversion of C* to A*," 3934 if (S.Context.hasSameType(FromType1, FromType2) && 3935 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3936 (ToAssignLeft != ToAssignRight)) 3937 return ToAssignLeft? ImplicitConversionSequence::Worse 3938 : ImplicitConversionSequence::Better; 3939 3940 // -- "conversion of B* to A* is better than conversion of C* to A*," 3941 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3942 (FromAssignLeft != FromAssignRight)) 3943 return FromAssignLeft? ImplicitConversionSequence::Better 3944 : ImplicitConversionSequence::Worse; 3945 } 3946 } 3947 3948 // Ranking of member-pointer types. 3949 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3950 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3951 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3952 const MemberPointerType * FromMemPointer1 = 3953 FromType1->getAs<MemberPointerType>(); 3954 const MemberPointerType * ToMemPointer1 = 3955 ToType1->getAs<MemberPointerType>(); 3956 const MemberPointerType * FromMemPointer2 = 3957 FromType2->getAs<MemberPointerType>(); 3958 const MemberPointerType * ToMemPointer2 = 3959 ToType2->getAs<MemberPointerType>(); 3960 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3961 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3962 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3963 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3964 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3965 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3966 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3967 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3968 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3969 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3970 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3971 return ImplicitConversionSequence::Worse; 3972 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3973 return ImplicitConversionSequence::Better; 3974 } 3975 // conversion of B::* to C::* is better than conversion of A::* to C::* 3976 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3977 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3978 return ImplicitConversionSequence::Better; 3979 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3980 return ImplicitConversionSequence::Worse; 3981 } 3982 } 3983 3984 if (SCS1.Second == ICK_Derived_To_Base) { 3985 // -- conversion of C to B is better than conversion of C to A, 3986 // -- binding of an expression of type C to a reference of type 3987 // B& is better than binding an expression of type C to a 3988 // reference of type A&, 3989 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3990 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3991 if (S.IsDerivedFrom(ToType1, ToType2)) 3992 return ImplicitConversionSequence::Better; 3993 else if (S.IsDerivedFrom(ToType2, ToType1)) 3994 return ImplicitConversionSequence::Worse; 3995 } 3996 3997 // -- conversion of B to A is better than conversion of C to A. 3998 // -- binding of an expression of type B to a reference of type 3999 // A& is better than binding an expression of type C to a 4000 // reference of type A&, 4001 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4002 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4003 if (S.IsDerivedFrom(FromType2, FromType1)) 4004 return ImplicitConversionSequence::Better; 4005 else if (S.IsDerivedFrom(FromType1, FromType2)) 4006 return ImplicitConversionSequence::Worse; 4007 } 4008 } 4009 4010 return ImplicitConversionSequence::Indistinguishable; 4011 } 4012 4013 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 4014 /// C++ class. 4015 static bool isTypeValid(QualType T) { 4016 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4017 return !Record->isInvalidDecl(); 4018 4019 return true; 4020 } 4021 4022 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4023 /// determine whether they are reference-related, 4024 /// reference-compatible, reference-compatible with added 4025 /// qualification, or incompatible, for use in C++ initialization by 4026 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4027 /// type, and the first type (T1) is the pointee type of the reference 4028 /// type being initialized. 4029 Sema::ReferenceCompareResult 4030 Sema::CompareReferenceRelationship(SourceLocation Loc, 4031 QualType OrigT1, QualType OrigT2, 4032 bool &DerivedToBase, 4033 bool &ObjCConversion, 4034 bool &ObjCLifetimeConversion) { 4035 assert(!OrigT1->isReferenceType() && 4036 "T1 must be the pointee type of the reference type"); 4037 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4038 4039 QualType T1 = Context.getCanonicalType(OrigT1); 4040 QualType T2 = Context.getCanonicalType(OrigT2); 4041 Qualifiers T1Quals, T2Quals; 4042 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4043 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4044 4045 // C++ [dcl.init.ref]p4: 4046 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4047 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4048 // T1 is a base class of T2. 4049 DerivedToBase = false; 4050 ObjCConversion = false; 4051 ObjCLifetimeConversion = false; 4052 if (UnqualT1 == UnqualT2) { 4053 // Nothing to do. 4054 } else if (!RequireCompleteType(Loc, OrigT2, 0) && 4055 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4056 IsDerivedFrom(UnqualT2, UnqualT1)) 4057 DerivedToBase = true; 4058 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4059 UnqualT2->isObjCObjectOrInterfaceType() && 4060 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4061 ObjCConversion = true; 4062 else 4063 return Ref_Incompatible; 4064 4065 // At this point, we know that T1 and T2 are reference-related (at 4066 // least). 4067 4068 // If the type is an array type, promote the element qualifiers to the type 4069 // for comparison. 4070 if (isa<ArrayType>(T1) && T1Quals) 4071 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4072 if (isa<ArrayType>(T2) && T2Quals) 4073 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4074 4075 // C++ [dcl.init.ref]p4: 4076 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4077 // reference-related to T2 and cv1 is the same cv-qualification 4078 // as, or greater cv-qualification than, cv2. For purposes of 4079 // overload resolution, cases for which cv1 is greater 4080 // cv-qualification than cv2 are identified as 4081 // reference-compatible with added qualification (see 13.3.3.2). 4082 // 4083 // Note that we also require equivalence of Objective-C GC and address-space 4084 // qualifiers when performing these computations, so that e.g., an int in 4085 // address space 1 is not reference-compatible with an int in address 4086 // space 2. 4087 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4088 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4089 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4090 ObjCLifetimeConversion = true; 4091 4092 T1Quals.removeObjCLifetime(); 4093 T2Quals.removeObjCLifetime(); 4094 } 4095 4096 if (T1Quals == T2Quals) 4097 return Ref_Compatible; 4098 else if (T1Quals.compatiblyIncludes(T2Quals)) 4099 return Ref_Compatible_With_Added_Qualification; 4100 else 4101 return Ref_Related; 4102 } 4103 4104 /// \brief Look for a user-defined conversion to an value reference-compatible 4105 /// with DeclType. Return true if something definite is found. 4106 static bool 4107 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4108 QualType DeclType, SourceLocation DeclLoc, 4109 Expr *Init, QualType T2, bool AllowRvalues, 4110 bool AllowExplicit) { 4111 assert(T2->isRecordType() && "Can only find conversions of record types."); 4112 CXXRecordDecl *T2RecordDecl 4113 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4114 4115 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4116 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4117 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4118 NamedDecl *D = *I; 4119 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4120 if (isa<UsingShadowDecl>(D)) 4121 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4122 4123 FunctionTemplateDecl *ConvTemplate 4124 = dyn_cast<FunctionTemplateDecl>(D); 4125 CXXConversionDecl *Conv; 4126 if (ConvTemplate) 4127 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4128 else 4129 Conv = cast<CXXConversionDecl>(D); 4130 4131 // If this is an explicit conversion, and we're not allowed to consider 4132 // explicit conversions, skip it. 4133 if (!AllowExplicit && Conv->isExplicit()) 4134 continue; 4135 4136 if (AllowRvalues) { 4137 bool DerivedToBase = false; 4138 bool ObjCConversion = false; 4139 bool ObjCLifetimeConversion = false; 4140 4141 // If we are initializing an rvalue reference, don't permit conversion 4142 // functions that return lvalues. 4143 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4144 const ReferenceType *RefType 4145 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4146 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4147 continue; 4148 } 4149 4150 if (!ConvTemplate && 4151 S.CompareReferenceRelationship( 4152 DeclLoc, 4153 Conv->getConversionType().getNonReferenceType() 4154 .getUnqualifiedType(), 4155 DeclType.getNonReferenceType().getUnqualifiedType(), 4156 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4157 Sema::Ref_Incompatible) 4158 continue; 4159 } else { 4160 // If the conversion function doesn't return a reference type, 4161 // it can't be considered for this conversion. An rvalue reference 4162 // is only acceptable if its referencee is a function type. 4163 4164 const ReferenceType *RefType = 4165 Conv->getConversionType()->getAs<ReferenceType>(); 4166 if (!RefType || 4167 (!RefType->isLValueReferenceType() && 4168 !RefType->getPointeeType()->isFunctionType())) 4169 continue; 4170 } 4171 4172 if (ConvTemplate) 4173 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4174 Init, DeclType, CandidateSet, 4175 /*AllowObjCConversionOnExplicit=*/false); 4176 else 4177 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4178 DeclType, CandidateSet, 4179 /*AllowObjCConversionOnExplicit=*/false); 4180 } 4181 4182 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4183 4184 OverloadCandidateSet::iterator Best; 4185 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4186 case OR_Success: 4187 // C++ [over.ics.ref]p1: 4188 // 4189 // [...] If the parameter binds directly to the result of 4190 // applying a conversion function to the argument 4191 // expression, the implicit conversion sequence is a 4192 // user-defined conversion sequence (13.3.3.1.2), with the 4193 // second standard conversion sequence either an identity 4194 // conversion or, if the conversion function returns an 4195 // entity of a type that is a derived class of the parameter 4196 // type, a derived-to-base Conversion. 4197 if (!Best->FinalConversion.DirectBinding) 4198 return false; 4199 4200 ICS.setUserDefined(); 4201 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4202 ICS.UserDefined.After = Best->FinalConversion; 4203 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4204 ICS.UserDefined.ConversionFunction = Best->Function; 4205 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4206 ICS.UserDefined.EllipsisConversion = false; 4207 assert(ICS.UserDefined.After.ReferenceBinding && 4208 ICS.UserDefined.After.DirectBinding && 4209 "Expected a direct reference binding!"); 4210 return true; 4211 4212 case OR_Ambiguous: 4213 ICS.setAmbiguous(); 4214 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4215 Cand != CandidateSet.end(); ++Cand) 4216 if (Cand->Viable) 4217 ICS.Ambiguous.addConversion(Cand->Function); 4218 return true; 4219 4220 case OR_No_Viable_Function: 4221 case OR_Deleted: 4222 // There was no suitable conversion, or we found a deleted 4223 // conversion; continue with other checks. 4224 return false; 4225 } 4226 4227 llvm_unreachable("Invalid OverloadResult!"); 4228 } 4229 4230 /// \brief Compute an implicit conversion sequence for reference 4231 /// initialization. 4232 static ImplicitConversionSequence 4233 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4234 SourceLocation DeclLoc, 4235 bool SuppressUserConversions, 4236 bool AllowExplicit) { 4237 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4238 4239 // Most paths end in a failed conversion. 4240 ImplicitConversionSequence ICS; 4241 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4242 4243 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4244 QualType T2 = Init->getType(); 4245 4246 // If the initializer is the address of an overloaded function, try 4247 // to resolve the overloaded function. If all goes well, T2 is the 4248 // type of the resulting function. 4249 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4250 DeclAccessPair Found; 4251 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4252 false, Found)) 4253 T2 = Fn->getType(); 4254 } 4255 4256 // Compute some basic properties of the types and the initializer. 4257 bool isRValRef = DeclType->isRValueReferenceType(); 4258 bool DerivedToBase = false; 4259 bool ObjCConversion = false; 4260 bool ObjCLifetimeConversion = false; 4261 Expr::Classification InitCategory = Init->Classify(S.Context); 4262 Sema::ReferenceCompareResult RefRelationship 4263 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4264 ObjCConversion, ObjCLifetimeConversion); 4265 4266 4267 // C++0x [dcl.init.ref]p5: 4268 // A reference to type "cv1 T1" is initialized by an expression 4269 // of type "cv2 T2" as follows: 4270 4271 // -- If reference is an lvalue reference and the initializer expression 4272 if (!isRValRef) { 4273 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4274 // reference-compatible with "cv2 T2," or 4275 // 4276 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4277 if (InitCategory.isLValue() && 4278 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4279 // C++ [over.ics.ref]p1: 4280 // When a parameter of reference type binds directly (8.5.3) 4281 // to an argument expression, the implicit conversion sequence 4282 // is the identity conversion, unless the argument expression 4283 // has a type that is a derived class of the parameter type, 4284 // in which case the implicit conversion sequence is a 4285 // derived-to-base Conversion (13.3.3.1). 4286 ICS.setStandard(); 4287 ICS.Standard.First = ICK_Identity; 4288 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4289 : ObjCConversion? ICK_Compatible_Conversion 4290 : ICK_Identity; 4291 ICS.Standard.Third = ICK_Identity; 4292 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4293 ICS.Standard.setToType(0, T2); 4294 ICS.Standard.setToType(1, T1); 4295 ICS.Standard.setToType(2, T1); 4296 ICS.Standard.ReferenceBinding = true; 4297 ICS.Standard.DirectBinding = true; 4298 ICS.Standard.IsLvalueReference = !isRValRef; 4299 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4300 ICS.Standard.BindsToRvalue = false; 4301 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4302 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4303 ICS.Standard.CopyConstructor = nullptr; 4304 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4305 4306 // Nothing more to do: the inaccessibility/ambiguity check for 4307 // derived-to-base conversions is suppressed when we're 4308 // computing the implicit conversion sequence (C++ 4309 // [over.best.ics]p2). 4310 return ICS; 4311 } 4312 4313 // -- has a class type (i.e., T2 is a class type), where T1 is 4314 // not reference-related to T2, and can be implicitly 4315 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4316 // is reference-compatible with "cv3 T3" 92) (this 4317 // conversion is selected by enumerating the applicable 4318 // conversion functions (13.3.1.6) and choosing the best 4319 // one through overload resolution (13.3)), 4320 if (!SuppressUserConversions && T2->isRecordType() && 4321 !S.RequireCompleteType(DeclLoc, T2, 0) && 4322 RefRelationship == Sema::Ref_Incompatible) { 4323 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4324 Init, T2, /*AllowRvalues=*/false, 4325 AllowExplicit)) 4326 return ICS; 4327 } 4328 } 4329 4330 // -- Otherwise, the reference shall be an lvalue reference to a 4331 // non-volatile const type (i.e., cv1 shall be const), or the reference 4332 // shall be an rvalue reference. 4333 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4334 return ICS; 4335 4336 // -- If the initializer expression 4337 // 4338 // -- is an xvalue, class prvalue, array prvalue or function 4339 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4340 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4341 (InitCategory.isXValue() || 4342 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4343 (InitCategory.isLValue() && T2->isFunctionType()))) { 4344 ICS.setStandard(); 4345 ICS.Standard.First = ICK_Identity; 4346 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4347 : ObjCConversion? ICK_Compatible_Conversion 4348 : ICK_Identity; 4349 ICS.Standard.Third = ICK_Identity; 4350 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4351 ICS.Standard.setToType(0, T2); 4352 ICS.Standard.setToType(1, T1); 4353 ICS.Standard.setToType(2, T1); 4354 ICS.Standard.ReferenceBinding = true; 4355 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4356 // binding unless we're binding to a class prvalue. 4357 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4358 // allow the use of rvalue references in C++98/03 for the benefit of 4359 // standard library implementors; therefore, we need the xvalue check here. 4360 ICS.Standard.DirectBinding = 4361 S.getLangOpts().CPlusPlus11 || 4362 !(InitCategory.isPRValue() || T2->isRecordType()); 4363 ICS.Standard.IsLvalueReference = !isRValRef; 4364 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4365 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4366 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4367 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4368 ICS.Standard.CopyConstructor = nullptr; 4369 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4370 return ICS; 4371 } 4372 4373 // -- has a class type (i.e., T2 is a class type), where T1 is not 4374 // reference-related to T2, and can be implicitly converted to 4375 // an xvalue, class prvalue, or function lvalue of type 4376 // "cv3 T3", where "cv1 T1" is reference-compatible with 4377 // "cv3 T3", 4378 // 4379 // then the reference is bound to the value of the initializer 4380 // expression in the first case and to the result of the conversion 4381 // in the second case (or, in either case, to an appropriate base 4382 // class subobject). 4383 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4384 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4385 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4386 Init, T2, /*AllowRvalues=*/true, 4387 AllowExplicit)) { 4388 // In the second case, if the reference is an rvalue reference 4389 // and the second standard conversion sequence of the 4390 // user-defined conversion sequence includes an lvalue-to-rvalue 4391 // conversion, the program is ill-formed. 4392 if (ICS.isUserDefined() && isRValRef && 4393 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4394 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4395 4396 return ICS; 4397 } 4398 4399 // A temporary of function type cannot be created; don't even try. 4400 if (T1->isFunctionType()) 4401 return ICS; 4402 4403 // -- Otherwise, a temporary of type "cv1 T1" is created and 4404 // initialized from the initializer expression using the 4405 // rules for a non-reference copy initialization (8.5). The 4406 // reference is then bound to the temporary. If T1 is 4407 // reference-related to T2, cv1 must be the same 4408 // cv-qualification as, or greater cv-qualification than, 4409 // cv2; otherwise, the program is ill-formed. 4410 if (RefRelationship == Sema::Ref_Related) { 4411 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4412 // we would be reference-compatible or reference-compatible with 4413 // added qualification. But that wasn't the case, so the reference 4414 // initialization fails. 4415 // 4416 // Note that we only want to check address spaces and cvr-qualifiers here. 4417 // ObjC GC and lifetime qualifiers aren't important. 4418 Qualifiers T1Quals = T1.getQualifiers(); 4419 Qualifiers T2Quals = T2.getQualifiers(); 4420 T1Quals.removeObjCGCAttr(); 4421 T1Quals.removeObjCLifetime(); 4422 T2Quals.removeObjCGCAttr(); 4423 T2Quals.removeObjCLifetime(); 4424 if (!T1Quals.compatiblyIncludes(T2Quals)) 4425 return ICS; 4426 } 4427 4428 // If at least one of the types is a class type, the types are not 4429 // related, and we aren't allowed any user conversions, the 4430 // reference binding fails. This case is important for breaking 4431 // recursion, since TryImplicitConversion below will attempt to 4432 // create a temporary through the use of a copy constructor. 4433 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4434 (T1->isRecordType() || T2->isRecordType())) 4435 return ICS; 4436 4437 // If T1 is reference-related to T2 and the reference is an rvalue 4438 // reference, the initializer expression shall not be an lvalue. 4439 if (RefRelationship >= Sema::Ref_Related && 4440 isRValRef && Init->Classify(S.Context).isLValue()) 4441 return ICS; 4442 4443 // C++ [over.ics.ref]p2: 4444 // When a parameter of reference type is not bound directly to 4445 // an argument expression, the conversion sequence is the one 4446 // required to convert the argument expression to the 4447 // underlying type of the reference according to 4448 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4449 // to copy-initializing a temporary of the underlying type with 4450 // the argument expression. Any difference in top-level 4451 // cv-qualification is subsumed by the initialization itself 4452 // and does not constitute a conversion. 4453 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4454 /*AllowExplicit=*/false, 4455 /*InOverloadResolution=*/false, 4456 /*CStyle=*/false, 4457 /*AllowObjCWritebackConversion=*/false, 4458 /*AllowObjCConversionOnExplicit=*/false); 4459 4460 // Of course, that's still a reference binding. 4461 if (ICS.isStandard()) { 4462 ICS.Standard.ReferenceBinding = true; 4463 ICS.Standard.IsLvalueReference = !isRValRef; 4464 ICS.Standard.BindsToFunctionLvalue = false; 4465 ICS.Standard.BindsToRvalue = true; 4466 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4467 ICS.Standard.ObjCLifetimeConversionBinding = false; 4468 } else if (ICS.isUserDefined()) { 4469 const ReferenceType *LValRefType = 4470 ICS.UserDefined.ConversionFunction->getReturnType() 4471 ->getAs<LValueReferenceType>(); 4472 4473 // C++ [over.ics.ref]p3: 4474 // Except for an implicit object parameter, for which see 13.3.1, a 4475 // standard conversion sequence cannot be formed if it requires [...] 4476 // binding an rvalue reference to an lvalue other than a function 4477 // lvalue. 4478 // Note that the function case is not possible here. 4479 if (DeclType->isRValueReferenceType() && LValRefType) { 4480 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4481 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4482 // reference to an rvalue! 4483 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4484 return ICS; 4485 } 4486 4487 ICS.UserDefined.Before.setAsIdentityConversion(); 4488 ICS.UserDefined.After.ReferenceBinding = true; 4489 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4490 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4491 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4492 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4493 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4494 } 4495 4496 return ICS; 4497 } 4498 4499 static ImplicitConversionSequence 4500 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4501 bool SuppressUserConversions, 4502 bool InOverloadResolution, 4503 bool AllowObjCWritebackConversion, 4504 bool AllowExplicit = false); 4505 4506 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4507 /// initializer list From. 4508 static ImplicitConversionSequence 4509 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4510 bool SuppressUserConversions, 4511 bool InOverloadResolution, 4512 bool AllowObjCWritebackConversion) { 4513 // C++11 [over.ics.list]p1: 4514 // When an argument is an initializer list, it is not an expression and 4515 // special rules apply for converting it to a parameter type. 4516 4517 ImplicitConversionSequence Result; 4518 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4519 4520 // We need a complete type for what follows. Incomplete types can never be 4521 // initialized from init lists. 4522 if (S.RequireCompleteType(From->getLocStart(), ToType, 0)) 4523 return Result; 4524 4525 // Per DR1467: 4526 // If the parameter type is a class X and the initializer list has a single 4527 // element of type cv U, where U is X or a class derived from X, the 4528 // implicit conversion sequence is the one required to convert the element 4529 // to the parameter type. 4530 // 4531 // Otherwise, if the parameter type is a character array [... ] 4532 // and the initializer list has a single element that is an 4533 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4534 // implicit conversion sequence is the identity conversion. 4535 if (From->getNumInits() == 1) { 4536 if (ToType->isRecordType()) { 4537 QualType InitType = From->getInit(0)->getType(); 4538 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4539 S.IsDerivedFrom(InitType, ToType)) 4540 return TryCopyInitialization(S, From->getInit(0), ToType, 4541 SuppressUserConversions, 4542 InOverloadResolution, 4543 AllowObjCWritebackConversion); 4544 } 4545 // FIXME: Check the other conditions here: array of character type, 4546 // initializer is a string literal. 4547 if (ToType->isArrayType()) { 4548 InitializedEntity Entity = 4549 InitializedEntity::InitializeParameter(S.Context, ToType, 4550 /*Consumed=*/false); 4551 if (S.CanPerformCopyInitialization(Entity, From)) { 4552 Result.setStandard(); 4553 Result.Standard.setAsIdentityConversion(); 4554 Result.Standard.setFromType(ToType); 4555 Result.Standard.setAllToTypes(ToType); 4556 return Result; 4557 } 4558 } 4559 } 4560 4561 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4562 // C++11 [over.ics.list]p2: 4563 // If the parameter type is std::initializer_list<X> or "array of X" and 4564 // all the elements can be implicitly converted to X, the implicit 4565 // conversion sequence is the worst conversion necessary to convert an 4566 // element of the list to X. 4567 // 4568 // C++14 [over.ics.list]p3: 4569 // Otherwise, if the parameter type is "array of N X", if the initializer 4570 // list has exactly N elements or if it has fewer than N elements and X is 4571 // default-constructible, and if all the elements of the initializer list 4572 // can be implicitly converted to X, the implicit conversion sequence is 4573 // the worst conversion necessary to convert an element of the list to X. 4574 // 4575 // FIXME: We're missing a lot of these checks. 4576 bool toStdInitializerList = false; 4577 QualType X; 4578 if (ToType->isArrayType()) 4579 X = S.Context.getAsArrayType(ToType)->getElementType(); 4580 else 4581 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4582 if (!X.isNull()) { 4583 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4584 Expr *Init = From->getInit(i); 4585 ImplicitConversionSequence ICS = 4586 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4587 InOverloadResolution, 4588 AllowObjCWritebackConversion); 4589 // If a single element isn't convertible, fail. 4590 if (ICS.isBad()) { 4591 Result = ICS; 4592 break; 4593 } 4594 // Otherwise, look for the worst conversion. 4595 if (Result.isBad() || 4596 CompareImplicitConversionSequences(S, ICS, Result) == 4597 ImplicitConversionSequence::Worse) 4598 Result = ICS; 4599 } 4600 4601 // For an empty list, we won't have computed any conversion sequence. 4602 // Introduce the identity conversion sequence. 4603 if (From->getNumInits() == 0) { 4604 Result.setStandard(); 4605 Result.Standard.setAsIdentityConversion(); 4606 Result.Standard.setFromType(ToType); 4607 Result.Standard.setAllToTypes(ToType); 4608 } 4609 4610 Result.setStdInitializerListElement(toStdInitializerList); 4611 return Result; 4612 } 4613 4614 // C++14 [over.ics.list]p4: 4615 // C++11 [over.ics.list]p3: 4616 // Otherwise, if the parameter is a non-aggregate class X and overload 4617 // resolution chooses a single best constructor [...] the implicit 4618 // conversion sequence is a user-defined conversion sequence. If multiple 4619 // constructors are viable but none is better than the others, the 4620 // implicit conversion sequence is a user-defined conversion sequence. 4621 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4622 // This function can deal with initializer lists. 4623 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4624 /*AllowExplicit=*/false, 4625 InOverloadResolution, /*CStyle=*/false, 4626 AllowObjCWritebackConversion, 4627 /*AllowObjCConversionOnExplicit=*/false); 4628 } 4629 4630 // C++14 [over.ics.list]p5: 4631 // C++11 [over.ics.list]p4: 4632 // Otherwise, if the parameter has an aggregate type which can be 4633 // initialized from the initializer list [...] the implicit conversion 4634 // sequence is a user-defined conversion sequence. 4635 if (ToType->isAggregateType()) { 4636 // Type is an aggregate, argument is an init list. At this point it comes 4637 // down to checking whether the initialization works. 4638 // FIXME: Find out whether this parameter is consumed or not. 4639 InitializedEntity Entity = 4640 InitializedEntity::InitializeParameter(S.Context, ToType, 4641 /*Consumed=*/false); 4642 if (S.CanPerformCopyInitialization(Entity, From)) { 4643 Result.setUserDefined(); 4644 Result.UserDefined.Before.setAsIdentityConversion(); 4645 // Initializer lists don't have a type. 4646 Result.UserDefined.Before.setFromType(QualType()); 4647 Result.UserDefined.Before.setAllToTypes(QualType()); 4648 4649 Result.UserDefined.After.setAsIdentityConversion(); 4650 Result.UserDefined.After.setFromType(ToType); 4651 Result.UserDefined.After.setAllToTypes(ToType); 4652 Result.UserDefined.ConversionFunction = nullptr; 4653 } 4654 return Result; 4655 } 4656 4657 // C++14 [over.ics.list]p6: 4658 // C++11 [over.ics.list]p5: 4659 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4660 if (ToType->isReferenceType()) { 4661 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4662 // mention initializer lists in any way. So we go by what list- 4663 // initialization would do and try to extrapolate from that. 4664 4665 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4666 4667 // If the initializer list has a single element that is reference-related 4668 // to the parameter type, we initialize the reference from that. 4669 if (From->getNumInits() == 1) { 4670 Expr *Init = From->getInit(0); 4671 4672 QualType T2 = Init->getType(); 4673 4674 // If the initializer is the address of an overloaded function, try 4675 // to resolve the overloaded function. If all goes well, T2 is the 4676 // type of the resulting function. 4677 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4678 DeclAccessPair Found; 4679 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4680 Init, ToType, false, Found)) 4681 T2 = Fn->getType(); 4682 } 4683 4684 // Compute some basic properties of the types and the initializer. 4685 bool dummy1 = false; 4686 bool dummy2 = false; 4687 bool dummy3 = false; 4688 Sema::ReferenceCompareResult RefRelationship 4689 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4690 dummy2, dummy3); 4691 4692 if (RefRelationship >= Sema::Ref_Related) { 4693 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4694 SuppressUserConversions, 4695 /*AllowExplicit=*/false); 4696 } 4697 } 4698 4699 // Otherwise, we bind the reference to a temporary created from the 4700 // initializer list. 4701 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4702 InOverloadResolution, 4703 AllowObjCWritebackConversion); 4704 if (Result.isFailure()) 4705 return Result; 4706 assert(!Result.isEllipsis() && 4707 "Sub-initialization cannot result in ellipsis conversion."); 4708 4709 // Can we even bind to a temporary? 4710 if (ToType->isRValueReferenceType() || 4711 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4712 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4713 Result.UserDefined.After; 4714 SCS.ReferenceBinding = true; 4715 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4716 SCS.BindsToRvalue = true; 4717 SCS.BindsToFunctionLvalue = false; 4718 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4719 SCS.ObjCLifetimeConversionBinding = false; 4720 } else 4721 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4722 From, ToType); 4723 return Result; 4724 } 4725 4726 // C++14 [over.ics.list]p7: 4727 // C++11 [over.ics.list]p6: 4728 // Otherwise, if the parameter type is not a class: 4729 if (!ToType->isRecordType()) { 4730 // - if the initializer list has one element that is not itself an 4731 // initializer list, the implicit conversion sequence is the one 4732 // required to convert the element to the parameter type. 4733 unsigned NumInits = From->getNumInits(); 4734 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4735 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4736 SuppressUserConversions, 4737 InOverloadResolution, 4738 AllowObjCWritebackConversion); 4739 // - if the initializer list has no elements, the implicit conversion 4740 // sequence is the identity conversion. 4741 else if (NumInits == 0) { 4742 Result.setStandard(); 4743 Result.Standard.setAsIdentityConversion(); 4744 Result.Standard.setFromType(ToType); 4745 Result.Standard.setAllToTypes(ToType); 4746 } 4747 return Result; 4748 } 4749 4750 // C++14 [over.ics.list]p8: 4751 // C++11 [over.ics.list]p7: 4752 // In all cases other than those enumerated above, no conversion is possible 4753 return Result; 4754 } 4755 4756 /// TryCopyInitialization - Try to copy-initialize a value of type 4757 /// ToType from the expression From. Return the implicit conversion 4758 /// sequence required to pass this argument, which may be a bad 4759 /// conversion sequence (meaning that the argument cannot be passed to 4760 /// a parameter of this type). If @p SuppressUserConversions, then we 4761 /// do not permit any user-defined conversion sequences. 4762 static ImplicitConversionSequence 4763 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4764 bool SuppressUserConversions, 4765 bool InOverloadResolution, 4766 bool AllowObjCWritebackConversion, 4767 bool AllowExplicit) { 4768 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4769 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4770 InOverloadResolution,AllowObjCWritebackConversion); 4771 4772 if (ToType->isReferenceType()) 4773 return TryReferenceInit(S, From, ToType, 4774 /*FIXME:*/From->getLocStart(), 4775 SuppressUserConversions, 4776 AllowExplicit); 4777 4778 return TryImplicitConversion(S, From, ToType, 4779 SuppressUserConversions, 4780 /*AllowExplicit=*/false, 4781 InOverloadResolution, 4782 /*CStyle=*/false, 4783 AllowObjCWritebackConversion, 4784 /*AllowObjCConversionOnExplicit=*/false); 4785 } 4786 4787 static bool TryCopyInitialization(const CanQualType FromQTy, 4788 const CanQualType ToQTy, 4789 Sema &S, 4790 SourceLocation Loc, 4791 ExprValueKind FromVK) { 4792 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4793 ImplicitConversionSequence ICS = 4794 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4795 4796 return !ICS.isBad(); 4797 } 4798 4799 /// TryObjectArgumentInitialization - Try to initialize the object 4800 /// parameter of the given member function (@c Method) from the 4801 /// expression @p From. 4802 static ImplicitConversionSequence 4803 TryObjectArgumentInitialization(Sema &S, QualType FromType, 4804 Expr::Classification FromClassification, 4805 CXXMethodDecl *Method, 4806 CXXRecordDecl *ActingContext) { 4807 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4808 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4809 // const volatile object. 4810 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4811 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4812 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4813 4814 // Set up the conversion sequence as a "bad" conversion, to allow us 4815 // to exit early. 4816 ImplicitConversionSequence ICS; 4817 4818 // We need to have an object of class type. 4819 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4820 FromType = PT->getPointeeType(); 4821 4822 // When we had a pointer, it's implicitly dereferenced, so we 4823 // better have an lvalue. 4824 assert(FromClassification.isLValue()); 4825 } 4826 4827 assert(FromType->isRecordType()); 4828 4829 // C++0x [over.match.funcs]p4: 4830 // For non-static member functions, the type of the implicit object 4831 // parameter is 4832 // 4833 // - "lvalue reference to cv X" for functions declared without a 4834 // ref-qualifier or with the & ref-qualifier 4835 // - "rvalue reference to cv X" for functions declared with the && 4836 // ref-qualifier 4837 // 4838 // where X is the class of which the function is a member and cv is the 4839 // cv-qualification on the member function declaration. 4840 // 4841 // However, when finding an implicit conversion sequence for the argument, we 4842 // are not allowed to create temporaries or perform user-defined conversions 4843 // (C++ [over.match.funcs]p5). We perform a simplified version of 4844 // reference binding here, that allows class rvalues to bind to 4845 // non-constant references. 4846 4847 // First check the qualifiers. 4848 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4849 if (ImplicitParamType.getCVRQualifiers() 4850 != FromTypeCanon.getLocalCVRQualifiers() && 4851 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 4852 ICS.setBad(BadConversionSequence::bad_qualifiers, 4853 FromType, ImplicitParamType); 4854 return ICS; 4855 } 4856 4857 // Check that we have either the same type or a derived type. It 4858 // affects the conversion rank. 4859 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 4860 ImplicitConversionKind SecondKind; 4861 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 4862 SecondKind = ICK_Identity; 4863 } else if (S.IsDerivedFrom(FromType, ClassType)) 4864 SecondKind = ICK_Derived_To_Base; 4865 else { 4866 ICS.setBad(BadConversionSequence::unrelated_class, 4867 FromType, ImplicitParamType); 4868 return ICS; 4869 } 4870 4871 // Check the ref-qualifier. 4872 switch (Method->getRefQualifier()) { 4873 case RQ_None: 4874 // Do nothing; we don't care about lvalueness or rvalueness. 4875 break; 4876 4877 case RQ_LValue: 4878 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 4879 // non-const lvalue reference cannot bind to an rvalue 4880 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 4881 ImplicitParamType); 4882 return ICS; 4883 } 4884 break; 4885 4886 case RQ_RValue: 4887 if (!FromClassification.isRValue()) { 4888 // rvalue reference cannot bind to an lvalue 4889 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 4890 ImplicitParamType); 4891 return ICS; 4892 } 4893 break; 4894 } 4895 4896 // Success. Mark this as a reference binding. 4897 ICS.setStandard(); 4898 ICS.Standard.setAsIdentityConversion(); 4899 ICS.Standard.Second = SecondKind; 4900 ICS.Standard.setFromType(FromType); 4901 ICS.Standard.setAllToTypes(ImplicitParamType); 4902 ICS.Standard.ReferenceBinding = true; 4903 ICS.Standard.DirectBinding = true; 4904 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 4905 ICS.Standard.BindsToFunctionLvalue = false; 4906 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 4907 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 4908 = (Method->getRefQualifier() == RQ_None); 4909 return ICS; 4910 } 4911 4912 /// PerformObjectArgumentInitialization - Perform initialization of 4913 /// the implicit object parameter for the given Method with the given 4914 /// expression. 4915 ExprResult 4916 Sema::PerformObjectArgumentInitialization(Expr *From, 4917 NestedNameSpecifier *Qualifier, 4918 NamedDecl *FoundDecl, 4919 CXXMethodDecl *Method) { 4920 QualType FromRecordType, DestType; 4921 QualType ImplicitParamRecordType = 4922 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 4923 4924 Expr::Classification FromClassification; 4925 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 4926 FromRecordType = PT->getPointeeType(); 4927 DestType = Method->getThisType(Context); 4928 FromClassification = Expr::Classification::makeSimpleLValue(); 4929 } else { 4930 FromRecordType = From->getType(); 4931 DestType = ImplicitParamRecordType; 4932 FromClassification = From->Classify(Context); 4933 } 4934 4935 // Note that we always use the true parent context when performing 4936 // the actual argument initialization. 4937 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 4938 *this, From->getType(), FromClassification, Method, Method->getParent()); 4939 if (ICS.isBad()) { 4940 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 4941 Qualifiers FromQs = FromRecordType.getQualifiers(); 4942 Qualifiers ToQs = DestType.getQualifiers(); 4943 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 4944 if (CVR) { 4945 Diag(From->getLocStart(), 4946 diag::err_member_function_call_bad_cvr) 4947 << Method->getDeclName() << FromRecordType << (CVR - 1) 4948 << From->getSourceRange(); 4949 Diag(Method->getLocation(), diag::note_previous_decl) 4950 << Method->getDeclName(); 4951 return ExprError(); 4952 } 4953 } 4954 4955 return Diag(From->getLocStart(), 4956 diag::err_implicit_object_parameter_init) 4957 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 4958 } 4959 4960 if (ICS.Standard.Second == ICK_Derived_To_Base) { 4961 ExprResult FromRes = 4962 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 4963 if (FromRes.isInvalid()) 4964 return ExprError(); 4965 From = FromRes.get(); 4966 } 4967 4968 if (!Context.hasSameType(From->getType(), DestType)) 4969 From = ImpCastExprToType(From, DestType, CK_NoOp, 4970 From->getValueKind()).get(); 4971 return From; 4972 } 4973 4974 /// TryContextuallyConvertToBool - Attempt to contextually convert the 4975 /// expression From to bool (C++0x [conv]p3). 4976 static ImplicitConversionSequence 4977 TryContextuallyConvertToBool(Sema &S, Expr *From) { 4978 return TryImplicitConversion(S, From, S.Context.BoolTy, 4979 /*SuppressUserConversions=*/false, 4980 /*AllowExplicit=*/true, 4981 /*InOverloadResolution=*/false, 4982 /*CStyle=*/false, 4983 /*AllowObjCWritebackConversion=*/false, 4984 /*AllowObjCConversionOnExplicit=*/false); 4985 } 4986 4987 /// PerformContextuallyConvertToBool - Perform a contextual conversion 4988 /// of the expression From to bool (C++0x [conv]p3). 4989 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 4990 if (checkPlaceholderForOverload(*this, From)) 4991 return ExprError(); 4992 4993 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 4994 if (!ICS.isBad()) 4995 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 4996 4997 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 4998 return Diag(From->getLocStart(), 4999 diag::err_typecheck_bool_condition) 5000 << From->getType() << From->getSourceRange(); 5001 return ExprError(); 5002 } 5003 5004 /// Check that the specified conversion is permitted in a converted constant 5005 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5006 /// is acceptable. 5007 static bool CheckConvertedConstantConversions(Sema &S, 5008 StandardConversionSequence &SCS) { 5009 // Since we know that the target type is an integral or unscoped enumeration 5010 // type, most conversion kinds are impossible. All possible First and Third 5011 // conversions are fine. 5012 switch (SCS.Second) { 5013 case ICK_Identity: 5014 case ICK_NoReturn_Adjustment: 5015 case ICK_Integral_Promotion: 5016 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5017 return true; 5018 5019 case ICK_Boolean_Conversion: 5020 // Conversion from an integral or unscoped enumeration type to bool is 5021 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5022 // conversion, so we allow it in a converted constant expression. 5023 // 5024 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5025 // a lot of popular code. We should at least add a warning for this 5026 // (non-conforming) extension. 5027 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5028 SCS.getToType(2)->isBooleanType(); 5029 5030 case ICK_Pointer_Conversion: 5031 case ICK_Pointer_Member: 5032 // C++1z: null pointer conversions and null member pointer conversions are 5033 // only permitted if the source type is std::nullptr_t. 5034 return SCS.getFromType()->isNullPtrType(); 5035 5036 case ICK_Floating_Promotion: 5037 case ICK_Complex_Promotion: 5038 case ICK_Floating_Conversion: 5039 case ICK_Complex_Conversion: 5040 case ICK_Floating_Integral: 5041 case ICK_Compatible_Conversion: 5042 case ICK_Derived_To_Base: 5043 case ICK_Vector_Conversion: 5044 case ICK_Vector_Splat: 5045 case ICK_Complex_Real: 5046 case ICK_Block_Pointer_Conversion: 5047 case ICK_TransparentUnionConversion: 5048 case ICK_Writeback_Conversion: 5049 case ICK_Zero_Event_Conversion: 5050 case ICK_C_Only_Conversion: 5051 return false; 5052 5053 case ICK_Lvalue_To_Rvalue: 5054 case ICK_Array_To_Pointer: 5055 case ICK_Function_To_Pointer: 5056 llvm_unreachable("found a first conversion kind in Second"); 5057 5058 case ICK_Qualification: 5059 llvm_unreachable("found a third conversion kind in Second"); 5060 5061 case ICK_Num_Conversion_Kinds: 5062 break; 5063 } 5064 5065 llvm_unreachable("unknown conversion kind"); 5066 } 5067 5068 /// CheckConvertedConstantExpression - Check that the expression From is a 5069 /// converted constant expression of type T, perform the conversion and produce 5070 /// the converted expression, per C++11 [expr.const]p3. 5071 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5072 QualType T, APValue &Value, 5073 Sema::CCEKind CCE, 5074 bool RequireInt) { 5075 assert(S.getLangOpts().CPlusPlus11 && 5076 "converted constant expression outside C++11"); 5077 5078 if (checkPlaceholderForOverload(S, From)) 5079 return ExprError(); 5080 5081 // C++1z [expr.const]p3: 5082 // A converted constant expression of type T is an expression, 5083 // implicitly converted to type T, where the converted 5084 // expression is a constant expression and the implicit conversion 5085 // sequence contains only [... list of conversions ...]. 5086 ImplicitConversionSequence ICS = 5087 TryCopyInitialization(S, From, T, 5088 /*SuppressUserConversions=*/false, 5089 /*InOverloadResolution=*/false, 5090 /*AllowObjcWritebackConversion=*/false, 5091 /*AllowExplicit=*/false); 5092 StandardConversionSequence *SCS = nullptr; 5093 switch (ICS.getKind()) { 5094 case ImplicitConversionSequence::StandardConversion: 5095 SCS = &ICS.Standard; 5096 break; 5097 case ImplicitConversionSequence::UserDefinedConversion: 5098 // We are converting to a non-class type, so the Before sequence 5099 // must be trivial. 5100 SCS = &ICS.UserDefined.After; 5101 break; 5102 case ImplicitConversionSequence::AmbiguousConversion: 5103 case ImplicitConversionSequence::BadConversion: 5104 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5105 return S.Diag(From->getLocStart(), 5106 diag::err_typecheck_converted_constant_expression) 5107 << From->getType() << From->getSourceRange() << T; 5108 return ExprError(); 5109 5110 case ImplicitConversionSequence::EllipsisConversion: 5111 llvm_unreachable("ellipsis conversion in converted constant expression"); 5112 } 5113 5114 // Check that we would only use permitted conversions. 5115 if (!CheckConvertedConstantConversions(S, *SCS)) { 5116 return S.Diag(From->getLocStart(), 5117 diag::err_typecheck_converted_constant_expression_disallowed) 5118 << From->getType() << From->getSourceRange() << T; 5119 } 5120 // [...] and where the reference binding (if any) binds directly. 5121 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5122 return S.Diag(From->getLocStart(), 5123 diag::err_typecheck_converted_constant_expression_indirect) 5124 << From->getType() << From->getSourceRange() << T; 5125 } 5126 5127 ExprResult Result = 5128 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5129 if (Result.isInvalid()) 5130 return Result; 5131 5132 // Check for a narrowing implicit conversion. 5133 APValue PreNarrowingValue; 5134 QualType PreNarrowingType; 5135 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5136 PreNarrowingType)) { 5137 case NK_Variable_Narrowing: 5138 // Implicit conversion to a narrower type, and the value is not a constant 5139 // expression. We'll diagnose this in a moment. 5140 case NK_Not_Narrowing: 5141 break; 5142 5143 case NK_Constant_Narrowing: 5144 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5145 << CCE << /*Constant*/1 5146 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5147 break; 5148 5149 case NK_Type_Narrowing: 5150 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5151 << CCE << /*Constant*/0 << From->getType() << T; 5152 break; 5153 } 5154 5155 // Check the expression is a constant expression. 5156 SmallVector<PartialDiagnosticAt, 8> Notes; 5157 Expr::EvalResult Eval; 5158 Eval.Diag = &Notes; 5159 5160 if ((T->isReferenceType() 5161 ? !Result.get()->EvaluateAsLValue(Eval, S.Context) 5162 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) || 5163 (RequireInt && !Eval.Val.isInt())) { 5164 // The expression can't be folded, so we can't keep it at this position in 5165 // the AST. 5166 Result = ExprError(); 5167 } else { 5168 Value = Eval.Val; 5169 5170 if (Notes.empty()) { 5171 // It's a constant expression. 5172 return Result; 5173 } 5174 } 5175 5176 // It's not a constant expression. Produce an appropriate diagnostic. 5177 if (Notes.size() == 1 && 5178 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5179 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5180 else { 5181 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5182 << CCE << From->getSourceRange(); 5183 for (unsigned I = 0; I < Notes.size(); ++I) 5184 S.Diag(Notes[I].first, Notes[I].second); 5185 } 5186 return ExprError(); 5187 } 5188 5189 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5190 APValue &Value, CCEKind CCE) { 5191 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5192 } 5193 5194 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5195 llvm::APSInt &Value, 5196 CCEKind CCE) { 5197 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5198 5199 APValue V; 5200 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5201 if (!R.isInvalid()) 5202 Value = V.getInt(); 5203 return R; 5204 } 5205 5206 5207 /// dropPointerConversions - If the given standard conversion sequence 5208 /// involves any pointer conversions, remove them. This may change 5209 /// the result type of the conversion sequence. 5210 static void dropPointerConversion(StandardConversionSequence &SCS) { 5211 if (SCS.Second == ICK_Pointer_Conversion) { 5212 SCS.Second = ICK_Identity; 5213 SCS.Third = ICK_Identity; 5214 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5215 } 5216 } 5217 5218 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5219 /// convert the expression From to an Objective-C pointer type. 5220 static ImplicitConversionSequence 5221 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5222 // Do an implicit conversion to 'id'. 5223 QualType Ty = S.Context.getObjCIdType(); 5224 ImplicitConversionSequence ICS 5225 = TryImplicitConversion(S, From, Ty, 5226 // FIXME: Are these flags correct? 5227 /*SuppressUserConversions=*/false, 5228 /*AllowExplicit=*/true, 5229 /*InOverloadResolution=*/false, 5230 /*CStyle=*/false, 5231 /*AllowObjCWritebackConversion=*/false, 5232 /*AllowObjCConversionOnExplicit=*/true); 5233 5234 // Strip off any final conversions to 'id'. 5235 switch (ICS.getKind()) { 5236 case ImplicitConversionSequence::BadConversion: 5237 case ImplicitConversionSequence::AmbiguousConversion: 5238 case ImplicitConversionSequence::EllipsisConversion: 5239 break; 5240 5241 case ImplicitConversionSequence::UserDefinedConversion: 5242 dropPointerConversion(ICS.UserDefined.After); 5243 break; 5244 5245 case ImplicitConversionSequence::StandardConversion: 5246 dropPointerConversion(ICS.Standard); 5247 break; 5248 } 5249 5250 return ICS; 5251 } 5252 5253 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5254 /// conversion of the expression From to an Objective-C pointer type. 5255 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5256 if (checkPlaceholderForOverload(*this, From)) 5257 return ExprError(); 5258 5259 QualType Ty = Context.getObjCIdType(); 5260 ImplicitConversionSequence ICS = 5261 TryContextuallyConvertToObjCPointer(*this, From); 5262 if (!ICS.isBad()) 5263 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5264 return ExprError(); 5265 } 5266 5267 /// Determine whether the provided type is an integral type, or an enumeration 5268 /// type of a permitted flavor. 5269 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5270 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5271 : T->isIntegralOrUnscopedEnumerationType(); 5272 } 5273 5274 static ExprResult 5275 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5276 Sema::ContextualImplicitConverter &Converter, 5277 QualType T, UnresolvedSetImpl &ViableConversions) { 5278 5279 if (Converter.Suppress) 5280 return ExprError(); 5281 5282 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5283 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5284 CXXConversionDecl *Conv = 5285 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5286 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5287 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5288 } 5289 return From; 5290 } 5291 5292 static bool 5293 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5294 Sema::ContextualImplicitConverter &Converter, 5295 QualType T, bool HadMultipleCandidates, 5296 UnresolvedSetImpl &ExplicitConversions) { 5297 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5298 DeclAccessPair Found = ExplicitConversions[0]; 5299 CXXConversionDecl *Conversion = 5300 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5301 5302 // The user probably meant to invoke the given explicit 5303 // conversion; use it. 5304 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5305 std::string TypeStr; 5306 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5307 5308 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5309 << FixItHint::CreateInsertion(From->getLocStart(), 5310 "static_cast<" + TypeStr + ">(") 5311 << FixItHint::CreateInsertion( 5312 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5313 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5314 5315 // If we aren't in a SFINAE context, build a call to the 5316 // explicit conversion function. 5317 if (SemaRef.isSFINAEContext()) 5318 return true; 5319 5320 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5321 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5322 HadMultipleCandidates); 5323 if (Result.isInvalid()) 5324 return true; 5325 // Record usage of conversion in an implicit cast. 5326 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5327 CK_UserDefinedConversion, Result.get(), 5328 nullptr, Result.get()->getValueKind()); 5329 } 5330 return false; 5331 } 5332 5333 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5334 Sema::ContextualImplicitConverter &Converter, 5335 QualType T, bool HadMultipleCandidates, 5336 DeclAccessPair &Found) { 5337 CXXConversionDecl *Conversion = 5338 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5339 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5340 5341 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5342 if (!Converter.SuppressConversion) { 5343 if (SemaRef.isSFINAEContext()) 5344 return true; 5345 5346 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5347 << From->getSourceRange(); 5348 } 5349 5350 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5351 HadMultipleCandidates); 5352 if (Result.isInvalid()) 5353 return true; 5354 // Record usage of conversion in an implicit cast. 5355 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5356 CK_UserDefinedConversion, Result.get(), 5357 nullptr, Result.get()->getValueKind()); 5358 return false; 5359 } 5360 5361 static ExprResult finishContextualImplicitConversion( 5362 Sema &SemaRef, SourceLocation Loc, Expr *From, 5363 Sema::ContextualImplicitConverter &Converter) { 5364 if (!Converter.match(From->getType()) && !Converter.Suppress) 5365 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5366 << From->getSourceRange(); 5367 5368 return SemaRef.DefaultLvalueConversion(From); 5369 } 5370 5371 static void 5372 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5373 UnresolvedSetImpl &ViableConversions, 5374 OverloadCandidateSet &CandidateSet) { 5375 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5376 DeclAccessPair FoundDecl = ViableConversions[I]; 5377 NamedDecl *D = FoundDecl.getDecl(); 5378 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5379 if (isa<UsingShadowDecl>(D)) 5380 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5381 5382 CXXConversionDecl *Conv; 5383 FunctionTemplateDecl *ConvTemplate; 5384 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5385 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5386 else 5387 Conv = cast<CXXConversionDecl>(D); 5388 5389 if (ConvTemplate) 5390 SemaRef.AddTemplateConversionCandidate( 5391 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5392 /*AllowObjCConversionOnExplicit=*/false); 5393 else 5394 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5395 ToType, CandidateSet, 5396 /*AllowObjCConversionOnExplicit=*/false); 5397 } 5398 } 5399 5400 /// \brief Attempt to convert the given expression to a type which is accepted 5401 /// by the given converter. 5402 /// 5403 /// This routine will attempt to convert an expression of class type to a 5404 /// type accepted by the specified converter. In C++11 and before, the class 5405 /// must have a single non-explicit conversion function converting to a matching 5406 /// type. In C++1y, there can be multiple such conversion functions, but only 5407 /// one target type. 5408 /// 5409 /// \param Loc The source location of the construct that requires the 5410 /// conversion. 5411 /// 5412 /// \param From The expression we're converting from. 5413 /// 5414 /// \param Converter Used to control and diagnose the conversion process. 5415 /// 5416 /// \returns The expression, converted to an integral or enumeration type if 5417 /// successful. 5418 ExprResult Sema::PerformContextualImplicitConversion( 5419 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5420 // We can't perform any more checking for type-dependent expressions. 5421 if (From->isTypeDependent()) 5422 return From; 5423 5424 // Process placeholders immediately. 5425 if (From->hasPlaceholderType()) { 5426 ExprResult result = CheckPlaceholderExpr(From); 5427 if (result.isInvalid()) 5428 return result; 5429 From = result.get(); 5430 } 5431 5432 // If the expression already has a matching type, we're golden. 5433 QualType T = From->getType(); 5434 if (Converter.match(T)) 5435 return DefaultLvalueConversion(From); 5436 5437 // FIXME: Check for missing '()' if T is a function type? 5438 5439 // We can only perform contextual implicit conversions on objects of class 5440 // type. 5441 const RecordType *RecordTy = T->getAs<RecordType>(); 5442 if (!RecordTy || !getLangOpts().CPlusPlus) { 5443 if (!Converter.Suppress) 5444 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5445 return From; 5446 } 5447 5448 // We must have a complete class type. 5449 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5450 ContextualImplicitConverter &Converter; 5451 Expr *From; 5452 5453 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5454 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {} 5455 5456 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5457 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5458 } 5459 } IncompleteDiagnoser(Converter, From); 5460 5461 if (RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5462 return From; 5463 5464 // Look for a conversion to an integral or enumeration type. 5465 UnresolvedSet<4> 5466 ViableConversions; // These are *potentially* viable in C++1y. 5467 UnresolvedSet<4> ExplicitConversions; 5468 const auto &Conversions = 5469 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5470 5471 bool HadMultipleCandidates = 5472 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5473 5474 // To check that there is only one target type, in C++1y: 5475 QualType ToType; 5476 bool HasUniqueTargetType = true; 5477 5478 // Collect explicit or viable (potentially in C++1y) conversions. 5479 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5480 NamedDecl *D = (*I)->getUnderlyingDecl(); 5481 CXXConversionDecl *Conversion; 5482 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5483 if (ConvTemplate) { 5484 if (getLangOpts().CPlusPlus14) 5485 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5486 else 5487 continue; // C++11 does not consider conversion operator templates(?). 5488 } else 5489 Conversion = cast<CXXConversionDecl>(D); 5490 5491 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5492 "Conversion operator templates are considered potentially " 5493 "viable in C++1y"); 5494 5495 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5496 if (Converter.match(CurToType) || ConvTemplate) { 5497 5498 if (Conversion->isExplicit()) { 5499 // FIXME: For C++1y, do we need this restriction? 5500 // cf. diagnoseNoViableConversion() 5501 if (!ConvTemplate) 5502 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5503 } else { 5504 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5505 if (ToType.isNull()) 5506 ToType = CurToType.getUnqualifiedType(); 5507 else if (HasUniqueTargetType && 5508 (CurToType.getUnqualifiedType() != ToType)) 5509 HasUniqueTargetType = false; 5510 } 5511 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5512 } 5513 } 5514 } 5515 5516 if (getLangOpts().CPlusPlus14) { 5517 // C++1y [conv]p6: 5518 // ... An expression e of class type E appearing in such a context 5519 // is said to be contextually implicitly converted to a specified 5520 // type T and is well-formed if and only if e can be implicitly 5521 // converted to a type T that is determined as follows: E is searched 5522 // for conversion functions whose return type is cv T or reference to 5523 // cv T such that T is allowed by the context. There shall be 5524 // exactly one such T. 5525 5526 // If no unique T is found: 5527 if (ToType.isNull()) { 5528 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5529 HadMultipleCandidates, 5530 ExplicitConversions)) 5531 return ExprError(); 5532 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5533 } 5534 5535 // If more than one unique Ts are found: 5536 if (!HasUniqueTargetType) 5537 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5538 ViableConversions); 5539 5540 // If one unique T is found: 5541 // First, build a candidate set from the previously recorded 5542 // potentially viable conversions. 5543 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5544 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5545 CandidateSet); 5546 5547 // Then, perform overload resolution over the candidate set. 5548 OverloadCandidateSet::iterator Best; 5549 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5550 case OR_Success: { 5551 // Apply this conversion. 5552 DeclAccessPair Found = 5553 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5554 if (recordConversion(*this, Loc, From, Converter, T, 5555 HadMultipleCandidates, Found)) 5556 return ExprError(); 5557 break; 5558 } 5559 case OR_Ambiguous: 5560 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5561 ViableConversions); 5562 case OR_No_Viable_Function: 5563 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5564 HadMultipleCandidates, 5565 ExplicitConversions)) 5566 return ExprError(); 5567 // fall through 'OR_Deleted' case. 5568 case OR_Deleted: 5569 // We'll complain below about a non-integral condition type. 5570 break; 5571 } 5572 } else { 5573 switch (ViableConversions.size()) { 5574 case 0: { 5575 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5576 HadMultipleCandidates, 5577 ExplicitConversions)) 5578 return ExprError(); 5579 5580 // We'll complain below about a non-integral condition type. 5581 break; 5582 } 5583 case 1: { 5584 // Apply this conversion. 5585 DeclAccessPair Found = ViableConversions[0]; 5586 if (recordConversion(*this, Loc, From, Converter, T, 5587 HadMultipleCandidates, Found)) 5588 return ExprError(); 5589 break; 5590 } 5591 default: 5592 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5593 ViableConversions); 5594 } 5595 } 5596 5597 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5598 } 5599 5600 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5601 /// an acceptable non-member overloaded operator for a call whose 5602 /// arguments have types T1 (and, if non-empty, T2). This routine 5603 /// implements the check in C++ [over.match.oper]p3b2 concerning 5604 /// enumeration types. 5605 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5606 FunctionDecl *Fn, 5607 ArrayRef<Expr *> Args) { 5608 QualType T1 = Args[0]->getType(); 5609 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5610 5611 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5612 return true; 5613 5614 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5615 return true; 5616 5617 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5618 if (Proto->getNumParams() < 1) 5619 return false; 5620 5621 if (T1->isEnumeralType()) { 5622 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5623 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5624 return true; 5625 } 5626 5627 if (Proto->getNumParams() < 2) 5628 return false; 5629 5630 if (!T2.isNull() && T2->isEnumeralType()) { 5631 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5632 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5633 return true; 5634 } 5635 5636 return false; 5637 } 5638 5639 /// AddOverloadCandidate - Adds the given function to the set of 5640 /// candidate functions, using the given function call arguments. If 5641 /// @p SuppressUserConversions, then don't allow user-defined 5642 /// conversions via constructors or conversion operators. 5643 /// 5644 /// \param PartialOverloading true if we are performing "partial" overloading 5645 /// based on an incomplete set of function arguments. This feature is used by 5646 /// code completion. 5647 void 5648 Sema::AddOverloadCandidate(FunctionDecl *Function, 5649 DeclAccessPair FoundDecl, 5650 ArrayRef<Expr *> Args, 5651 OverloadCandidateSet &CandidateSet, 5652 bool SuppressUserConversions, 5653 bool PartialOverloading, 5654 bool AllowExplicit) { 5655 const FunctionProtoType *Proto 5656 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5657 assert(Proto && "Functions without a prototype cannot be overloaded"); 5658 assert(!Function->getDescribedFunctionTemplate() && 5659 "Use AddTemplateOverloadCandidate for function templates"); 5660 5661 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5662 if (!isa<CXXConstructorDecl>(Method)) { 5663 // If we get here, it's because we're calling a member function 5664 // that is named without a member access expression (e.g., 5665 // "this->f") that was either written explicitly or created 5666 // implicitly. This can happen with a qualified call to a member 5667 // function, e.g., X::f(). We use an empty type for the implied 5668 // object argument (C++ [over.call.func]p3), and the acting context 5669 // is irrelevant. 5670 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5671 QualType(), Expr::Classification::makeSimpleLValue(), 5672 Args, CandidateSet, SuppressUserConversions, 5673 PartialOverloading); 5674 return; 5675 } 5676 // We treat a constructor like a non-member function, since its object 5677 // argument doesn't participate in overload resolution. 5678 } 5679 5680 if (!CandidateSet.isNewCandidate(Function)) 5681 return; 5682 5683 // C++ [over.match.oper]p3: 5684 // if no operand has a class type, only those non-member functions in the 5685 // lookup set that have a first parameter of type T1 or "reference to 5686 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5687 // is a right operand) a second parameter of type T2 or "reference to 5688 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5689 // candidate functions. 5690 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5691 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5692 return; 5693 5694 // C++11 [class.copy]p11: [DR1402] 5695 // A defaulted move constructor that is defined as deleted is ignored by 5696 // overload resolution. 5697 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5698 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5699 Constructor->isMoveConstructor()) 5700 return; 5701 5702 // Overload resolution is always an unevaluated context. 5703 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5704 5705 // Add this candidate 5706 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5707 Candidate.FoundDecl = FoundDecl; 5708 Candidate.Function = Function; 5709 Candidate.Viable = true; 5710 Candidate.IsSurrogate = false; 5711 Candidate.IgnoreObjectArgument = false; 5712 Candidate.ExplicitCallArguments = Args.size(); 5713 5714 if (Constructor) { 5715 // C++ [class.copy]p3: 5716 // A member function template is never instantiated to perform the copy 5717 // of a class object to an object of its class type. 5718 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5719 if (Args.size() == 1 && 5720 Constructor->isSpecializationCopyingObject() && 5721 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5722 IsDerivedFrom(Args[0]->getType(), ClassType))) { 5723 Candidate.Viable = false; 5724 Candidate.FailureKind = ovl_fail_illegal_constructor; 5725 return; 5726 } 5727 } 5728 5729 unsigned NumParams = Proto->getNumParams(); 5730 5731 // (C++ 13.3.2p2): A candidate function having fewer than m 5732 // parameters is viable only if it has an ellipsis in its parameter 5733 // list (8.3.5). 5734 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 5735 !Proto->isVariadic()) { 5736 Candidate.Viable = false; 5737 Candidate.FailureKind = ovl_fail_too_many_arguments; 5738 return; 5739 } 5740 5741 // (C++ 13.3.2p2): A candidate function having more than m parameters 5742 // is viable only if the (m+1)st parameter has a default argument 5743 // (8.3.6). For the purposes of overload resolution, the 5744 // parameter list is truncated on the right, so that there are 5745 // exactly m parameters. 5746 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5747 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5748 // Not enough arguments. 5749 Candidate.Viable = false; 5750 Candidate.FailureKind = ovl_fail_too_few_arguments; 5751 return; 5752 } 5753 5754 // (CUDA B.1): Check for invalid calls between targets. 5755 if (getLangOpts().CUDA) 5756 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5757 // Skip the check for callers that are implicit members, because in this 5758 // case we may not yet know what the member's target is; the target is 5759 // inferred for the member automatically, based on the bases and fields of 5760 // the class. 5761 if (!Caller->isImplicit() && CheckCUDATarget(Caller, Function)) { 5762 Candidate.Viable = false; 5763 Candidate.FailureKind = ovl_fail_bad_target; 5764 return; 5765 } 5766 5767 // Determine the implicit conversion sequences for each of the 5768 // arguments. 5769 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5770 if (ArgIdx < NumParams) { 5771 // (C++ 13.3.2p3): for F to be a viable function, there shall 5772 // exist for each argument an implicit conversion sequence 5773 // (13.3.3.1) that converts that argument to the corresponding 5774 // parameter of F. 5775 QualType ParamType = Proto->getParamType(ArgIdx); 5776 Candidate.Conversions[ArgIdx] 5777 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5778 SuppressUserConversions, 5779 /*InOverloadResolution=*/true, 5780 /*AllowObjCWritebackConversion=*/ 5781 getLangOpts().ObjCAutoRefCount, 5782 AllowExplicit); 5783 if (Candidate.Conversions[ArgIdx].isBad()) { 5784 Candidate.Viable = false; 5785 Candidate.FailureKind = ovl_fail_bad_conversion; 5786 return; 5787 } 5788 } else { 5789 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5790 // argument for which there is no corresponding parameter is 5791 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5792 Candidate.Conversions[ArgIdx].setEllipsis(); 5793 } 5794 } 5795 5796 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5797 Candidate.Viable = false; 5798 Candidate.FailureKind = ovl_fail_enable_if; 5799 Candidate.DeductionFailure.Data = FailedAttr; 5800 return; 5801 } 5802 } 5803 5804 ObjCMethodDecl *Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, 5805 bool IsInstance) { 5806 SmallVector<ObjCMethodDecl*, 4> Methods; 5807 if (!CollectMultipleMethodsInGlobalPool(Sel, Methods, IsInstance)) 5808 return nullptr; 5809 5810 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5811 bool Match = true; 5812 ObjCMethodDecl *Method = Methods[b]; 5813 unsigned NumNamedArgs = Sel.getNumArgs(); 5814 // Method might have more arguments than selector indicates. This is due 5815 // to addition of c-style arguments in method. 5816 if (Method->param_size() > NumNamedArgs) 5817 NumNamedArgs = Method->param_size(); 5818 if (Args.size() < NumNamedArgs) 5819 continue; 5820 5821 for (unsigned i = 0; i < NumNamedArgs; i++) { 5822 // We can't do any type-checking on a type-dependent argument. 5823 if (Args[i]->isTypeDependent()) { 5824 Match = false; 5825 break; 5826 } 5827 5828 ParmVarDecl *param = Method->parameters()[i]; 5829 Expr *argExpr = Args[i]; 5830 assert(argExpr && "SelectBestMethod(): missing expression"); 5831 5832 // Strip the unbridged-cast placeholder expression off unless it's 5833 // a consumed argument. 5834 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 5835 !param->hasAttr<CFConsumedAttr>()) 5836 argExpr = stripARCUnbridgedCast(argExpr); 5837 5838 // If the parameter is __unknown_anytype, move on to the next method. 5839 if (param->getType() == Context.UnknownAnyTy) { 5840 Match = false; 5841 break; 5842 } 5843 5844 ImplicitConversionSequence ConversionState 5845 = TryCopyInitialization(*this, argExpr, param->getType(), 5846 /*SuppressUserConversions*/false, 5847 /*InOverloadResolution=*/true, 5848 /*AllowObjCWritebackConversion=*/ 5849 getLangOpts().ObjCAutoRefCount, 5850 /*AllowExplicit*/false); 5851 if (ConversionState.isBad()) { 5852 Match = false; 5853 break; 5854 } 5855 } 5856 // Promote additional arguments to variadic methods. 5857 if (Match && Method->isVariadic()) { 5858 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 5859 if (Args[i]->isTypeDependent()) { 5860 Match = false; 5861 break; 5862 } 5863 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 5864 nullptr); 5865 if (Arg.isInvalid()) { 5866 Match = false; 5867 break; 5868 } 5869 } 5870 } else { 5871 // Check for extra arguments to non-variadic methods. 5872 if (Args.size() != NumNamedArgs) 5873 Match = false; 5874 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 5875 // Special case when selectors have no argument. In this case, select 5876 // one with the most general result type of 'id'. 5877 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5878 QualType ReturnT = Methods[b]->getReturnType(); 5879 if (ReturnT->isObjCIdType()) 5880 return Methods[b]; 5881 } 5882 } 5883 } 5884 5885 if (Match) 5886 return Method; 5887 } 5888 return nullptr; 5889 } 5890 5891 // specific_attr_iterator iterates over enable_if attributes in reverse, and 5892 // enable_if is order-sensitive. As a result, we need to reverse things 5893 // sometimes. Size of 4 elements is arbitrary. 5894 static SmallVector<EnableIfAttr *, 4> 5895 getOrderedEnableIfAttrs(const FunctionDecl *Function) { 5896 SmallVector<EnableIfAttr *, 4> Result; 5897 if (!Function->hasAttrs()) 5898 return Result; 5899 5900 const auto &FuncAttrs = Function->getAttrs(); 5901 for (Attr *Attr : FuncAttrs) 5902 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr)) 5903 Result.push_back(EnableIf); 5904 5905 std::reverse(Result.begin(), Result.end()); 5906 return Result; 5907 } 5908 5909 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 5910 bool MissingImplicitThis) { 5911 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function); 5912 if (EnableIfAttrs.empty()) 5913 return nullptr; 5914 5915 SFINAETrap Trap(*this); 5916 SmallVector<Expr *, 16> ConvertedArgs; 5917 bool InitializationFailed = false; 5918 bool ContainsValueDependentExpr = false; 5919 5920 // Convert the arguments. 5921 for (unsigned i = 0, e = Args.size(); i != e; ++i) { 5922 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 5923 !cast<CXXMethodDecl>(Function)->isStatic() && 5924 !isa<CXXConstructorDecl>(Function)) { 5925 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 5926 ExprResult R = 5927 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 5928 Method, Method); 5929 if (R.isInvalid()) { 5930 InitializationFailed = true; 5931 break; 5932 } 5933 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5934 ConvertedArgs.push_back(R.get()); 5935 } else { 5936 ExprResult R = 5937 PerformCopyInitialization(InitializedEntity::InitializeParameter( 5938 Context, 5939 Function->getParamDecl(i)), 5940 SourceLocation(), 5941 Args[i]); 5942 if (R.isInvalid()) { 5943 InitializationFailed = true; 5944 break; 5945 } 5946 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5947 ConvertedArgs.push_back(R.get()); 5948 } 5949 } 5950 5951 if (InitializationFailed || Trap.hasErrorOccurred()) 5952 return EnableIfAttrs[0]; 5953 5954 // Push default arguments if needed. 5955 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 5956 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 5957 ParmVarDecl *P = Function->getParamDecl(i); 5958 ExprResult R = PerformCopyInitialization( 5959 InitializedEntity::InitializeParameter(Context, 5960 Function->getParamDecl(i)), 5961 SourceLocation(), 5962 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg() 5963 : P->getDefaultArg()); 5964 if (R.isInvalid()) { 5965 InitializationFailed = true; 5966 break; 5967 } 5968 ContainsValueDependentExpr |= R.get()->isValueDependent(); 5969 ConvertedArgs.push_back(R.get()); 5970 } 5971 5972 if (InitializationFailed || Trap.hasErrorOccurred()) 5973 return EnableIfAttrs[0]; 5974 } 5975 5976 for (auto *EIA : EnableIfAttrs) { 5977 APValue Result; 5978 if (EIA->getCond()->isValueDependent()) { 5979 // Don't even try now, we'll examine it after instantiation. 5980 continue; 5981 } 5982 5983 if (!EIA->getCond()->EvaluateWithSubstitution( 5984 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) { 5985 if (!ContainsValueDependentExpr) 5986 return EIA; 5987 } else if (!Result.isInt() || !Result.getInt().getBoolValue()) { 5988 return EIA; 5989 } 5990 } 5991 return nullptr; 5992 } 5993 5994 /// \brief Add all of the function declarations in the given function set to 5995 /// the overload candidate set. 5996 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 5997 ArrayRef<Expr *> Args, 5998 OverloadCandidateSet& CandidateSet, 5999 TemplateArgumentListInfo *ExplicitTemplateArgs, 6000 bool SuppressUserConversions, 6001 bool PartialOverloading) { 6002 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6003 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6004 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6005 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 6006 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6007 cast<CXXMethodDecl>(FD)->getParent(), 6008 Args[0]->getType(), Args[0]->Classify(Context), 6009 Args.slice(1), CandidateSet, 6010 SuppressUserConversions, PartialOverloading); 6011 else 6012 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 6013 SuppressUserConversions, PartialOverloading); 6014 } else { 6015 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 6016 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 6017 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 6018 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 6019 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6020 ExplicitTemplateArgs, 6021 Args[0]->getType(), 6022 Args[0]->Classify(Context), Args.slice(1), 6023 CandidateSet, SuppressUserConversions, 6024 PartialOverloading); 6025 else 6026 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6027 ExplicitTemplateArgs, Args, 6028 CandidateSet, SuppressUserConversions, 6029 PartialOverloading); 6030 } 6031 } 6032 } 6033 6034 /// AddMethodCandidate - Adds a named decl (which is some kind of 6035 /// method) as a method candidate to the given overload set. 6036 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6037 QualType ObjectType, 6038 Expr::Classification ObjectClassification, 6039 ArrayRef<Expr *> Args, 6040 OverloadCandidateSet& CandidateSet, 6041 bool SuppressUserConversions) { 6042 NamedDecl *Decl = FoundDecl.getDecl(); 6043 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6044 6045 if (isa<UsingShadowDecl>(Decl)) 6046 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6047 6048 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6049 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6050 "Expected a member function template"); 6051 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6052 /*ExplicitArgs*/ nullptr, 6053 ObjectType, ObjectClassification, 6054 Args, CandidateSet, 6055 SuppressUserConversions); 6056 } else { 6057 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6058 ObjectType, ObjectClassification, 6059 Args, 6060 CandidateSet, SuppressUserConversions); 6061 } 6062 } 6063 6064 /// AddMethodCandidate - Adds the given C++ member function to the set 6065 /// of candidate functions, using the given function call arguments 6066 /// and the object argument (@c Object). For example, in a call 6067 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6068 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6069 /// allow user-defined conversions via constructors or conversion 6070 /// operators. 6071 void 6072 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6073 CXXRecordDecl *ActingContext, QualType ObjectType, 6074 Expr::Classification ObjectClassification, 6075 ArrayRef<Expr *> Args, 6076 OverloadCandidateSet &CandidateSet, 6077 bool SuppressUserConversions, 6078 bool PartialOverloading) { 6079 const FunctionProtoType *Proto 6080 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6081 assert(Proto && "Methods without a prototype cannot be overloaded"); 6082 assert(!isa<CXXConstructorDecl>(Method) && 6083 "Use AddOverloadCandidate for constructors"); 6084 6085 if (!CandidateSet.isNewCandidate(Method)) 6086 return; 6087 6088 // C++11 [class.copy]p23: [DR1402] 6089 // A defaulted move assignment operator that is defined as deleted is 6090 // ignored by overload resolution. 6091 if (Method->isDefaulted() && Method->isDeleted() && 6092 Method->isMoveAssignmentOperator()) 6093 return; 6094 6095 // Overload resolution is always an unevaluated context. 6096 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6097 6098 // Add this candidate 6099 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6100 Candidate.FoundDecl = FoundDecl; 6101 Candidate.Function = Method; 6102 Candidate.IsSurrogate = false; 6103 Candidate.IgnoreObjectArgument = false; 6104 Candidate.ExplicitCallArguments = Args.size(); 6105 6106 unsigned NumParams = Proto->getNumParams(); 6107 6108 // (C++ 13.3.2p2): A candidate function having fewer than m 6109 // parameters is viable only if it has an ellipsis in its parameter 6110 // list (8.3.5). 6111 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6112 !Proto->isVariadic()) { 6113 Candidate.Viable = false; 6114 Candidate.FailureKind = ovl_fail_too_many_arguments; 6115 return; 6116 } 6117 6118 // (C++ 13.3.2p2): A candidate function having more than m parameters 6119 // is viable only if the (m+1)st parameter has a default argument 6120 // (8.3.6). For the purposes of overload resolution, the 6121 // parameter list is truncated on the right, so that there are 6122 // exactly m parameters. 6123 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6124 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6125 // Not enough arguments. 6126 Candidate.Viable = false; 6127 Candidate.FailureKind = ovl_fail_too_few_arguments; 6128 return; 6129 } 6130 6131 Candidate.Viable = true; 6132 6133 if (Method->isStatic() || ObjectType.isNull()) 6134 // The implicit object argument is ignored. 6135 Candidate.IgnoreObjectArgument = true; 6136 else { 6137 // Determine the implicit conversion sequence for the object 6138 // parameter. 6139 Candidate.Conversions[0] 6140 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification, 6141 Method, ActingContext); 6142 if (Candidate.Conversions[0].isBad()) { 6143 Candidate.Viable = false; 6144 Candidate.FailureKind = ovl_fail_bad_conversion; 6145 return; 6146 } 6147 } 6148 6149 // (CUDA B.1): Check for invalid calls between targets. 6150 if (getLangOpts().CUDA) 6151 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6152 if (CheckCUDATarget(Caller, Method)) { 6153 Candidate.Viable = false; 6154 Candidate.FailureKind = ovl_fail_bad_target; 6155 return; 6156 } 6157 6158 // Determine the implicit conversion sequences for each of the 6159 // arguments. 6160 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6161 if (ArgIdx < NumParams) { 6162 // (C++ 13.3.2p3): for F to be a viable function, there shall 6163 // exist for each argument an implicit conversion sequence 6164 // (13.3.3.1) that converts that argument to the corresponding 6165 // parameter of F. 6166 QualType ParamType = Proto->getParamType(ArgIdx); 6167 Candidate.Conversions[ArgIdx + 1] 6168 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6169 SuppressUserConversions, 6170 /*InOverloadResolution=*/true, 6171 /*AllowObjCWritebackConversion=*/ 6172 getLangOpts().ObjCAutoRefCount); 6173 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6174 Candidate.Viable = false; 6175 Candidate.FailureKind = ovl_fail_bad_conversion; 6176 return; 6177 } 6178 } else { 6179 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6180 // argument for which there is no corresponding parameter is 6181 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6182 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6183 } 6184 } 6185 6186 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6187 Candidate.Viable = false; 6188 Candidate.FailureKind = ovl_fail_enable_if; 6189 Candidate.DeductionFailure.Data = FailedAttr; 6190 return; 6191 } 6192 } 6193 6194 /// \brief Add a C++ member function template as a candidate to the candidate 6195 /// set, using template argument deduction to produce an appropriate member 6196 /// function template specialization. 6197 void 6198 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6199 DeclAccessPair FoundDecl, 6200 CXXRecordDecl *ActingContext, 6201 TemplateArgumentListInfo *ExplicitTemplateArgs, 6202 QualType ObjectType, 6203 Expr::Classification ObjectClassification, 6204 ArrayRef<Expr *> Args, 6205 OverloadCandidateSet& CandidateSet, 6206 bool SuppressUserConversions, 6207 bool PartialOverloading) { 6208 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6209 return; 6210 6211 // C++ [over.match.funcs]p7: 6212 // In each case where a candidate is a function template, candidate 6213 // function template specializations are generated using template argument 6214 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6215 // candidate functions in the usual way.113) A given name can refer to one 6216 // or more function templates and also to a set of overloaded non-template 6217 // functions. In such a case, the candidate functions generated from each 6218 // function template are combined with the set of non-template candidate 6219 // functions. 6220 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6221 FunctionDecl *Specialization = nullptr; 6222 if (TemplateDeductionResult Result 6223 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 6224 Specialization, Info, PartialOverloading)) { 6225 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6226 Candidate.FoundDecl = FoundDecl; 6227 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6228 Candidate.Viable = false; 6229 Candidate.FailureKind = ovl_fail_bad_deduction; 6230 Candidate.IsSurrogate = false; 6231 Candidate.IgnoreObjectArgument = false; 6232 Candidate.ExplicitCallArguments = Args.size(); 6233 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6234 Info); 6235 return; 6236 } 6237 6238 // Add the function template specialization produced by template argument 6239 // deduction as a candidate. 6240 assert(Specialization && "Missing member function template specialization?"); 6241 assert(isa<CXXMethodDecl>(Specialization) && 6242 "Specialization is not a member function?"); 6243 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6244 ActingContext, ObjectType, ObjectClassification, Args, 6245 CandidateSet, SuppressUserConversions, PartialOverloading); 6246 } 6247 6248 /// \brief Add a C++ function template specialization as a candidate 6249 /// in the candidate set, using template argument deduction to produce 6250 /// an appropriate function template specialization. 6251 void 6252 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6253 DeclAccessPair FoundDecl, 6254 TemplateArgumentListInfo *ExplicitTemplateArgs, 6255 ArrayRef<Expr *> Args, 6256 OverloadCandidateSet& CandidateSet, 6257 bool SuppressUserConversions, 6258 bool PartialOverloading) { 6259 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6260 return; 6261 6262 // C++ [over.match.funcs]p7: 6263 // In each case where a candidate is a function template, candidate 6264 // function template specializations are generated using template argument 6265 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6266 // candidate functions in the usual way.113) A given name can refer to one 6267 // or more function templates and also to a set of overloaded non-template 6268 // functions. In such a case, the candidate functions generated from each 6269 // function template are combined with the set of non-template candidate 6270 // functions. 6271 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6272 FunctionDecl *Specialization = nullptr; 6273 if (TemplateDeductionResult Result 6274 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 6275 Specialization, Info, PartialOverloading)) { 6276 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6277 Candidate.FoundDecl = FoundDecl; 6278 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6279 Candidate.Viable = false; 6280 Candidate.FailureKind = ovl_fail_bad_deduction; 6281 Candidate.IsSurrogate = false; 6282 Candidate.IgnoreObjectArgument = false; 6283 Candidate.ExplicitCallArguments = Args.size(); 6284 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6285 Info); 6286 return; 6287 } 6288 6289 // Add the function template specialization produced by template argument 6290 // deduction as a candidate. 6291 assert(Specialization && "Missing function template specialization?"); 6292 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6293 SuppressUserConversions, PartialOverloading); 6294 } 6295 6296 /// Determine whether this is an allowable conversion from the result 6297 /// of an explicit conversion operator to the expected type, per C++ 6298 /// [over.match.conv]p1 and [over.match.ref]p1. 6299 /// 6300 /// \param ConvType The return type of the conversion function. 6301 /// 6302 /// \param ToType The type we are converting to. 6303 /// 6304 /// \param AllowObjCPointerConversion Allow a conversion from one 6305 /// Objective-C pointer to another. 6306 /// 6307 /// \returns true if the conversion is allowable, false otherwise. 6308 static bool isAllowableExplicitConversion(Sema &S, 6309 QualType ConvType, QualType ToType, 6310 bool AllowObjCPointerConversion) { 6311 QualType ToNonRefType = ToType.getNonReferenceType(); 6312 6313 // Easy case: the types are the same. 6314 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6315 return true; 6316 6317 // Allow qualification conversions. 6318 bool ObjCLifetimeConversion; 6319 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6320 ObjCLifetimeConversion)) 6321 return true; 6322 6323 // If we're not allowed to consider Objective-C pointer conversions, 6324 // we're done. 6325 if (!AllowObjCPointerConversion) 6326 return false; 6327 6328 // Is this an Objective-C pointer conversion? 6329 bool IncompatibleObjC = false; 6330 QualType ConvertedType; 6331 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6332 IncompatibleObjC); 6333 } 6334 6335 /// AddConversionCandidate - Add a C++ conversion function as a 6336 /// candidate in the candidate set (C++ [over.match.conv], 6337 /// C++ [over.match.copy]). From is the expression we're converting from, 6338 /// and ToType is the type that we're eventually trying to convert to 6339 /// (which may or may not be the same type as the type that the 6340 /// conversion function produces). 6341 void 6342 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6343 DeclAccessPair FoundDecl, 6344 CXXRecordDecl *ActingContext, 6345 Expr *From, QualType ToType, 6346 OverloadCandidateSet& CandidateSet, 6347 bool AllowObjCConversionOnExplicit) { 6348 assert(!Conversion->getDescribedFunctionTemplate() && 6349 "Conversion function templates use AddTemplateConversionCandidate"); 6350 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6351 if (!CandidateSet.isNewCandidate(Conversion)) 6352 return; 6353 6354 // If the conversion function has an undeduced return type, trigger its 6355 // deduction now. 6356 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6357 if (DeduceReturnType(Conversion, From->getExprLoc())) 6358 return; 6359 ConvType = Conversion->getConversionType().getNonReferenceType(); 6360 } 6361 6362 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6363 // operator is only a candidate if its return type is the target type or 6364 // can be converted to the target type with a qualification conversion. 6365 if (Conversion->isExplicit() && 6366 !isAllowableExplicitConversion(*this, ConvType, ToType, 6367 AllowObjCConversionOnExplicit)) 6368 return; 6369 6370 // Overload resolution is always an unevaluated context. 6371 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6372 6373 // Add this candidate 6374 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6375 Candidate.FoundDecl = FoundDecl; 6376 Candidate.Function = Conversion; 6377 Candidate.IsSurrogate = false; 6378 Candidate.IgnoreObjectArgument = false; 6379 Candidate.FinalConversion.setAsIdentityConversion(); 6380 Candidate.FinalConversion.setFromType(ConvType); 6381 Candidate.FinalConversion.setAllToTypes(ToType); 6382 Candidate.Viable = true; 6383 Candidate.ExplicitCallArguments = 1; 6384 6385 // C++ [over.match.funcs]p4: 6386 // For conversion functions, the function is considered to be a member of 6387 // the class of the implicit implied object argument for the purpose of 6388 // defining the type of the implicit object parameter. 6389 // 6390 // Determine the implicit conversion sequence for the implicit 6391 // object parameter. 6392 QualType ImplicitParamType = From->getType(); 6393 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6394 ImplicitParamType = FromPtrType->getPointeeType(); 6395 CXXRecordDecl *ConversionContext 6396 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6397 6398 Candidate.Conversions[0] 6399 = TryObjectArgumentInitialization(*this, From->getType(), 6400 From->Classify(Context), 6401 Conversion, ConversionContext); 6402 6403 if (Candidate.Conversions[0].isBad()) { 6404 Candidate.Viable = false; 6405 Candidate.FailureKind = ovl_fail_bad_conversion; 6406 return; 6407 } 6408 6409 // We won't go through a user-defined type conversion function to convert a 6410 // derived to base as such conversions are given Conversion Rank. They only 6411 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6412 QualType FromCanon 6413 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6414 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6415 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) { 6416 Candidate.Viable = false; 6417 Candidate.FailureKind = ovl_fail_trivial_conversion; 6418 return; 6419 } 6420 6421 // To determine what the conversion from the result of calling the 6422 // conversion function to the type we're eventually trying to 6423 // convert to (ToType), we need to synthesize a call to the 6424 // conversion function and attempt copy initialization from it. This 6425 // makes sure that we get the right semantics with respect to 6426 // lvalues/rvalues and the type. Fortunately, we can allocate this 6427 // call on the stack and we don't need its arguments to be 6428 // well-formed. 6429 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6430 VK_LValue, From->getLocStart()); 6431 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6432 Context.getPointerType(Conversion->getType()), 6433 CK_FunctionToPointerDecay, 6434 &ConversionRef, VK_RValue); 6435 6436 QualType ConversionType = Conversion->getConversionType(); 6437 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) { 6438 Candidate.Viable = false; 6439 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6440 return; 6441 } 6442 6443 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6444 6445 // Note that it is safe to allocate CallExpr on the stack here because 6446 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6447 // allocator). 6448 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6449 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6450 From->getLocStart()); 6451 ImplicitConversionSequence ICS = 6452 TryCopyInitialization(*this, &Call, ToType, 6453 /*SuppressUserConversions=*/true, 6454 /*InOverloadResolution=*/false, 6455 /*AllowObjCWritebackConversion=*/false); 6456 6457 switch (ICS.getKind()) { 6458 case ImplicitConversionSequence::StandardConversion: 6459 Candidate.FinalConversion = ICS.Standard; 6460 6461 // C++ [over.ics.user]p3: 6462 // If the user-defined conversion is specified by a specialization of a 6463 // conversion function template, the second standard conversion sequence 6464 // shall have exact match rank. 6465 if (Conversion->getPrimaryTemplate() && 6466 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6467 Candidate.Viable = false; 6468 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6469 return; 6470 } 6471 6472 // C++0x [dcl.init.ref]p5: 6473 // In the second case, if the reference is an rvalue reference and 6474 // the second standard conversion sequence of the user-defined 6475 // conversion sequence includes an lvalue-to-rvalue conversion, the 6476 // program is ill-formed. 6477 if (ToType->isRValueReferenceType() && 6478 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6479 Candidate.Viable = false; 6480 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6481 return; 6482 } 6483 break; 6484 6485 case ImplicitConversionSequence::BadConversion: 6486 Candidate.Viable = false; 6487 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6488 return; 6489 6490 default: 6491 llvm_unreachable( 6492 "Can only end up with a standard conversion sequence or failure"); 6493 } 6494 6495 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6496 Candidate.Viable = false; 6497 Candidate.FailureKind = ovl_fail_enable_if; 6498 Candidate.DeductionFailure.Data = FailedAttr; 6499 return; 6500 } 6501 } 6502 6503 /// \brief Adds a conversion function template specialization 6504 /// candidate to the overload set, using template argument deduction 6505 /// to deduce the template arguments of the conversion function 6506 /// template from the type that we are converting to (C++ 6507 /// [temp.deduct.conv]). 6508 void 6509 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6510 DeclAccessPair FoundDecl, 6511 CXXRecordDecl *ActingDC, 6512 Expr *From, QualType ToType, 6513 OverloadCandidateSet &CandidateSet, 6514 bool AllowObjCConversionOnExplicit) { 6515 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6516 "Only conversion function templates permitted here"); 6517 6518 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6519 return; 6520 6521 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6522 CXXConversionDecl *Specialization = nullptr; 6523 if (TemplateDeductionResult Result 6524 = DeduceTemplateArguments(FunctionTemplate, ToType, 6525 Specialization, Info)) { 6526 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6527 Candidate.FoundDecl = FoundDecl; 6528 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6529 Candidate.Viable = false; 6530 Candidate.FailureKind = ovl_fail_bad_deduction; 6531 Candidate.IsSurrogate = false; 6532 Candidate.IgnoreObjectArgument = false; 6533 Candidate.ExplicitCallArguments = 1; 6534 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6535 Info); 6536 return; 6537 } 6538 6539 // Add the conversion function template specialization produced by 6540 // template argument deduction as a candidate. 6541 assert(Specialization && "Missing function template specialization?"); 6542 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6543 CandidateSet, AllowObjCConversionOnExplicit); 6544 } 6545 6546 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6547 /// converts the given @c Object to a function pointer via the 6548 /// conversion function @c Conversion, and then attempts to call it 6549 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6550 /// the type of function that we'll eventually be calling. 6551 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6552 DeclAccessPair FoundDecl, 6553 CXXRecordDecl *ActingContext, 6554 const FunctionProtoType *Proto, 6555 Expr *Object, 6556 ArrayRef<Expr *> Args, 6557 OverloadCandidateSet& CandidateSet) { 6558 if (!CandidateSet.isNewCandidate(Conversion)) 6559 return; 6560 6561 // Overload resolution is always an unevaluated context. 6562 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6563 6564 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6565 Candidate.FoundDecl = FoundDecl; 6566 Candidate.Function = nullptr; 6567 Candidate.Surrogate = Conversion; 6568 Candidate.Viable = true; 6569 Candidate.IsSurrogate = true; 6570 Candidate.IgnoreObjectArgument = false; 6571 Candidate.ExplicitCallArguments = Args.size(); 6572 6573 // Determine the implicit conversion sequence for the implicit 6574 // object parameter. 6575 ImplicitConversionSequence ObjectInit 6576 = TryObjectArgumentInitialization(*this, Object->getType(), 6577 Object->Classify(Context), 6578 Conversion, ActingContext); 6579 if (ObjectInit.isBad()) { 6580 Candidate.Viable = false; 6581 Candidate.FailureKind = ovl_fail_bad_conversion; 6582 Candidate.Conversions[0] = ObjectInit; 6583 return; 6584 } 6585 6586 // The first conversion is actually a user-defined conversion whose 6587 // first conversion is ObjectInit's standard conversion (which is 6588 // effectively a reference binding). Record it as such. 6589 Candidate.Conversions[0].setUserDefined(); 6590 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6591 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6592 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6593 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6594 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6595 Candidate.Conversions[0].UserDefined.After 6596 = Candidate.Conversions[0].UserDefined.Before; 6597 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6598 6599 // Find the 6600 unsigned NumParams = Proto->getNumParams(); 6601 6602 // (C++ 13.3.2p2): A candidate function having fewer than m 6603 // parameters is viable only if it has an ellipsis in its parameter 6604 // list (8.3.5). 6605 if (Args.size() > NumParams && !Proto->isVariadic()) { 6606 Candidate.Viable = false; 6607 Candidate.FailureKind = ovl_fail_too_many_arguments; 6608 return; 6609 } 6610 6611 // Function types don't have any default arguments, so just check if 6612 // we have enough arguments. 6613 if (Args.size() < NumParams) { 6614 // Not enough arguments. 6615 Candidate.Viable = false; 6616 Candidate.FailureKind = ovl_fail_too_few_arguments; 6617 return; 6618 } 6619 6620 // Determine the implicit conversion sequences for each of the 6621 // arguments. 6622 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6623 if (ArgIdx < NumParams) { 6624 // (C++ 13.3.2p3): for F to be a viable function, there shall 6625 // exist for each argument an implicit conversion sequence 6626 // (13.3.3.1) that converts that argument to the corresponding 6627 // parameter of F. 6628 QualType ParamType = Proto->getParamType(ArgIdx); 6629 Candidate.Conversions[ArgIdx + 1] 6630 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6631 /*SuppressUserConversions=*/false, 6632 /*InOverloadResolution=*/false, 6633 /*AllowObjCWritebackConversion=*/ 6634 getLangOpts().ObjCAutoRefCount); 6635 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6636 Candidate.Viable = false; 6637 Candidate.FailureKind = ovl_fail_bad_conversion; 6638 return; 6639 } 6640 } else { 6641 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6642 // argument for which there is no corresponding parameter is 6643 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6644 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6645 } 6646 } 6647 6648 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6649 Candidate.Viable = false; 6650 Candidate.FailureKind = ovl_fail_enable_if; 6651 Candidate.DeductionFailure.Data = FailedAttr; 6652 return; 6653 } 6654 } 6655 6656 /// \brief Add overload candidates for overloaded operators that are 6657 /// member functions. 6658 /// 6659 /// Add the overloaded operator candidates that are member functions 6660 /// for the operator Op that was used in an operator expression such 6661 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6662 /// CandidateSet will store the added overload candidates. (C++ 6663 /// [over.match.oper]). 6664 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6665 SourceLocation OpLoc, 6666 ArrayRef<Expr *> Args, 6667 OverloadCandidateSet& CandidateSet, 6668 SourceRange OpRange) { 6669 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6670 6671 // C++ [over.match.oper]p3: 6672 // For a unary operator @ with an operand of a type whose 6673 // cv-unqualified version is T1, and for a binary operator @ with 6674 // a left operand of a type whose cv-unqualified version is T1 and 6675 // a right operand of a type whose cv-unqualified version is T2, 6676 // three sets of candidate functions, designated member 6677 // candidates, non-member candidates and built-in candidates, are 6678 // constructed as follows: 6679 QualType T1 = Args[0]->getType(); 6680 6681 // -- If T1 is a complete class type or a class currently being 6682 // defined, the set of member candidates is the result of the 6683 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6684 // the set of member candidates is empty. 6685 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6686 // Complete the type if it can be completed. 6687 RequireCompleteType(OpLoc, T1, 0); 6688 // If the type is neither complete nor being defined, bail out now. 6689 if (!T1Rec->getDecl()->getDefinition()) 6690 return; 6691 6692 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6693 LookupQualifiedName(Operators, T1Rec->getDecl()); 6694 Operators.suppressDiagnostics(); 6695 6696 for (LookupResult::iterator Oper = Operators.begin(), 6697 OperEnd = Operators.end(); 6698 Oper != OperEnd; 6699 ++Oper) 6700 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6701 Args[0]->Classify(Context), 6702 Args.slice(1), 6703 CandidateSet, 6704 /* SuppressUserConversions = */ false); 6705 } 6706 } 6707 6708 /// AddBuiltinCandidate - Add a candidate for a built-in 6709 /// operator. ResultTy and ParamTys are the result and parameter types 6710 /// of the built-in candidate, respectively. Args and NumArgs are the 6711 /// arguments being passed to the candidate. IsAssignmentOperator 6712 /// should be true when this built-in candidate is an assignment 6713 /// operator. NumContextualBoolArguments is the number of arguments 6714 /// (at the beginning of the argument list) that will be contextually 6715 /// converted to bool. 6716 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6717 ArrayRef<Expr *> Args, 6718 OverloadCandidateSet& CandidateSet, 6719 bool IsAssignmentOperator, 6720 unsigned NumContextualBoolArguments) { 6721 // Overload resolution is always an unevaluated context. 6722 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6723 6724 // Add this candidate 6725 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6726 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 6727 Candidate.Function = nullptr; 6728 Candidate.IsSurrogate = false; 6729 Candidate.IgnoreObjectArgument = false; 6730 Candidate.BuiltinTypes.ResultTy = ResultTy; 6731 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6732 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6733 6734 // Determine the implicit conversion sequences for each of the 6735 // arguments. 6736 Candidate.Viable = true; 6737 Candidate.ExplicitCallArguments = Args.size(); 6738 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6739 // C++ [over.match.oper]p4: 6740 // For the built-in assignment operators, conversions of the 6741 // left operand are restricted as follows: 6742 // -- no temporaries are introduced to hold the left operand, and 6743 // -- no user-defined conversions are applied to the left 6744 // operand to achieve a type match with the left-most 6745 // parameter of a built-in candidate. 6746 // 6747 // We block these conversions by turning off user-defined 6748 // conversions, since that is the only way that initialization of 6749 // a reference to a non-class type can occur from something that 6750 // is not of the same type. 6751 if (ArgIdx < NumContextualBoolArguments) { 6752 assert(ParamTys[ArgIdx] == Context.BoolTy && 6753 "Contextual conversion to bool requires bool type"); 6754 Candidate.Conversions[ArgIdx] 6755 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6756 } else { 6757 Candidate.Conversions[ArgIdx] 6758 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6759 ArgIdx == 0 && IsAssignmentOperator, 6760 /*InOverloadResolution=*/false, 6761 /*AllowObjCWritebackConversion=*/ 6762 getLangOpts().ObjCAutoRefCount); 6763 } 6764 if (Candidate.Conversions[ArgIdx].isBad()) { 6765 Candidate.Viable = false; 6766 Candidate.FailureKind = ovl_fail_bad_conversion; 6767 break; 6768 } 6769 } 6770 } 6771 6772 namespace { 6773 6774 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6775 /// candidate operator functions for built-in operators (C++ 6776 /// [over.built]). The types are separated into pointer types and 6777 /// enumeration types. 6778 class BuiltinCandidateTypeSet { 6779 /// TypeSet - A set of types. 6780 typedef llvm::SmallPtrSet<QualType, 8> TypeSet; 6781 6782 /// PointerTypes - The set of pointer types that will be used in the 6783 /// built-in candidates. 6784 TypeSet PointerTypes; 6785 6786 /// MemberPointerTypes - The set of member pointer types that will be 6787 /// used in the built-in candidates. 6788 TypeSet MemberPointerTypes; 6789 6790 /// EnumerationTypes - The set of enumeration types that will be 6791 /// used in the built-in candidates. 6792 TypeSet EnumerationTypes; 6793 6794 /// \brief The set of vector types that will be used in the built-in 6795 /// candidates. 6796 TypeSet VectorTypes; 6797 6798 /// \brief A flag indicating non-record types are viable candidates 6799 bool HasNonRecordTypes; 6800 6801 /// \brief A flag indicating whether either arithmetic or enumeration types 6802 /// were present in the candidate set. 6803 bool HasArithmeticOrEnumeralTypes; 6804 6805 /// \brief A flag indicating whether the nullptr type was present in the 6806 /// candidate set. 6807 bool HasNullPtrType; 6808 6809 /// Sema - The semantic analysis instance where we are building the 6810 /// candidate type set. 6811 Sema &SemaRef; 6812 6813 /// Context - The AST context in which we will build the type sets. 6814 ASTContext &Context; 6815 6816 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6817 const Qualifiers &VisibleQuals); 6818 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6819 6820 public: 6821 /// iterator - Iterates through the types that are part of the set. 6822 typedef TypeSet::iterator iterator; 6823 6824 BuiltinCandidateTypeSet(Sema &SemaRef) 6825 : HasNonRecordTypes(false), 6826 HasArithmeticOrEnumeralTypes(false), 6827 HasNullPtrType(false), 6828 SemaRef(SemaRef), 6829 Context(SemaRef.Context) { } 6830 6831 void AddTypesConvertedFrom(QualType Ty, 6832 SourceLocation Loc, 6833 bool AllowUserConversions, 6834 bool AllowExplicitConversions, 6835 const Qualifiers &VisibleTypeConversionsQuals); 6836 6837 /// pointer_begin - First pointer type found; 6838 iterator pointer_begin() { return PointerTypes.begin(); } 6839 6840 /// pointer_end - Past the last pointer type found; 6841 iterator pointer_end() { return PointerTypes.end(); } 6842 6843 /// member_pointer_begin - First member pointer type found; 6844 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 6845 6846 /// member_pointer_end - Past the last member pointer type found; 6847 iterator member_pointer_end() { return MemberPointerTypes.end(); } 6848 6849 /// enumeration_begin - First enumeration type found; 6850 iterator enumeration_begin() { return EnumerationTypes.begin(); } 6851 6852 /// enumeration_end - Past the last enumeration type found; 6853 iterator enumeration_end() { return EnumerationTypes.end(); } 6854 6855 iterator vector_begin() { return VectorTypes.begin(); } 6856 iterator vector_end() { return VectorTypes.end(); } 6857 6858 bool hasNonRecordTypes() { return HasNonRecordTypes; } 6859 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 6860 bool hasNullPtrType() const { return HasNullPtrType; } 6861 }; 6862 6863 } // end anonymous namespace 6864 6865 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 6866 /// the set of pointer types along with any more-qualified variants of 6867 /// that type. For example, if @p Ty is "int const *", this routine 6868 /// will add "int const *", "int const volatile *", "int const 6869 /// restrict *", and "int const volatile restrict *" to the set of 6870 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6871 /// false otherwise. 6872 /// 6873 /// FIXME: what to do about extended qualifiers? 6874 bool 6875 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6876 const Qualifiers &VisibleQuals) { 6877 6878 // Insert this type. 6879 if (!PointerTypes.insert(Ty).second) 6880 return false; 6881 6882 QualType PointeeTy; 6883 const PointerType *PointerTy = Ty->getAs<PointerType>(); 6884 bool buildObjCPtr = false; 6885 if (!PointerTy) { 6886 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 6887 PointeeTy = PTy->getPointeeType(); 6888 buildObjCPtr = true; 6889 } else { 6890 PointeeTy = PointerTy->getPointeeType(); 6891 } 6892 6893 // Don't add qualified variants of arrays. For one, they're not allowed 6894 // (the qualifier would sink to the element type), and for another, the 6895 // only overload situation where it matters is subscript or pointer +- int, 6896 // and those shouldn't have qualifier variants anyway. 6897 if (PointeeTy->isArrayType()) 6898 return true; 6899 6900 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6901 bool hasVolatile = VisibleQuals.hasVolatile(); 6902 bool hasRestrict = VisibleQuals.hasRestrict(); 6903 6904 // Iterate through all strict supersets of BaseCVR. 6905 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6906 if ((CVR | BaseCVR) != CVR) continue; 6907 // Skip over volatile if no volatile found anywhere in the types. 6908 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 6909 6910 // Skip over restrict if no restrict found anywhere in the types, or if 6911 // the type cannot be restrict-qualified. 6912 if ((CVR & Qualifiers::Restrict) && 6913 (!hasRestrict || 6914 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 6915 continue; 6916 6917 // Build qualified pointee type. 6918 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6919 6920 // Build qualified pointer type. 6921 QualType QPointerTy; 6922 if (!buildObjCPtr) 6923 QPointerTy = Context.getPointerType(QPointeeTy); 6924 else 6925 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 6926 6927 // Insert qualified pointer type. 6928 PointerTypes.insert(QPointerTy); 6929 } 6930 6931 return true; 6932 } 6933 6934 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 6935 /// to the set of pointer types along with any more-qualified variants of 6936 /// that type. For example, if @p Ty is "int const *", this routine 6937 /// will add "int const *", "int const volatile *", "int const 6938 /// restrict *", and "int const volatile restrict *" to the set of 6939 /// pointer types. Returns true if the add of @p Ty itself succeeded, 6940 /// false otherwise. 6941 /// 6942 /// FIXME: what to do about extended qualifiers? 6943 bool 6944 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 6945 QualType Ty) { 6946 // Insert this type. 6947 if (!MemberPointerTypes.insert(Ty).second) 6948 return false; 6949 6950 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 6951 assert(PointerTy && "type was not a member pointer type!"); 6952 6953 QualType PointeeTy = PointerTy->getPointeeType(); 6954 // Don't add qualified variants of arrays. For one, they're not allowed 6955 // (the qualifier would sink to the element type), and for another, the 6956 // only overload situation where it matters is subscript or pointer +- int, 6957 // and those shouldn't have qualifier variants anyway. 6958 if (PointeeTy->isArrayType()) 6959 return true; 6960 const Type *ClassTy = PointerTy->getClass(); 6961 6962 // Iterate through all strict supersets of the pointee type's CVR 6963 // qualifiers. 6964 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 6965 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 6966 if ((CVR | BaseCVR) != CVR) continue; 6967 6968 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 6969 MemberPointerTypes.insert( 6970 Context.getMemberPointerType(QPointeeTy, ClassTy)); 6971 } 6972 6973 return true; 6974 } 6975 6976 /// AddTypesConvertedFrom - Add each of the types to which the type @p 6977 /// Ty can be implicit converted to the given set of @p Types. We're 6978 /// primarily interested in pointer types and enumeration types. We also 6979 /// take member pointer types, for the conditional operator. 6980 /// AllowUserConversions is true if we should look at the conversion 6981 /// functions of a class type, and AllowExplicitConversions if we 6982 /// should also include the explicit conversion functions of a class 6983 /// type. 6984 void 6985 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 6986 SourceLocation Loc, 6987 bool AllowUserConversions, 6988 bool AllowExplicitConversions, 6989 const Qualifiers &VisibleQuals) { 6990 // Only deal with canonical types. 6991 Ty = Context.getCanonicalType(Ty); 6992 6993 // Look through reference types; they aren't part of the type of an 6994 // expression for the purposes of conversions. 6995 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 6996 Ty = RefTy->getPointeeType(); 6997 6998 // If we're dealing with an array type, decay to the pointer. 6999 if (Ty->isArrayType()) 7000 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7001 7002 // Otherwise, we don't care about qualifiers on the type. 7003 Ty = Ty.getLocalUnqualifiedType(); 7004 7005 // Flag if we ever add a non-record type. 7006 const RecordType *TyRec = Ty->getAs<RecordType>(); 7007 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7008 7009 // Flag if we encounter an arithmetic type. 7010 HasArithmeticOrEnumeralTypes = 7011 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7012 7013 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7014 PointerTypes.insert(Ty); 7015 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7016 // Insert our type, and its more-qualified variants, into the set 7017 // of types. 7018 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7019 return; 7020 } else if (Ty->isMemberPointerType()) { 7021 // Member pointers are far easier, since the pointee can't be converted. 7022 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7023 return; 7024 } else if (Ty->isEnumeralType()) { 7025 HasArithmeticOrEnumeralTypes = true; 7026 EnumerationTypes.insert(Ty); 7027 } else if (Ty->isVectorType()) { 7028 // We treat vector types as arithmetic types in many contexts as an 7029 // extension. 7030 HasArithmeticOrEnumeralTypes = true; 7031 VectorTypes.insert(Ty); 7032 } else if (Ty->isNullPtrType()) { 7033 HasNullPtrType = true; 7034 } else if (AllowUserConversions && TyRec) { 7035 // No conversion functions in incomplete types. 7036 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) 7037 return; 7038 7039 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7040 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7041 if (isa<UsingShadowDecl>(D)) 7042 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7043 7044 // Skip conversion function templates; they don't tell us anything 7045 // about which builtin types we can convert to. 7046 if (isa<FunctionTemplateDecl>(D)) 7047 continue; 7048 7049 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7050 if (AllowExplicitConversions || !Conv->isExplicit()) { 7051 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7052 VisibleQuals); 7053 } 7054 } 7055 } 7056 } 7057 7058 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 7059 /// the volatile- and non-volatile-qualified assignment operators for the 7060 /// given type to the candidate set. 7061 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7062 QualType T, 7063 ArrayRef<Expr *> Args, 7064 OverloadCandidateSet &CandidateSet) { 7065 QualType ParamTypes[2]; 7066 7067 // T& operator=(T&, T) 7068 ParamTypes[0] = S.Context.getLValueReferenceType(T); 7069 ParamTypes[1] = T; 7070 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7071 /*IsAssignmentOperator=*/true); 7072 7073 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7074 // volatile T& operator=(volatile T&, T) 7075 ParamTypes[0] 7076 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 7077 ParamTypes[1] = T; 7078 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7079 /*IsAssignmentOperator=*/true); 7080 } 7081 } 7082 7083 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7084 /// if any, found in visible type conversion functions found in ArgExpr's type. 7085 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7086 Qualifiers VRQuals; 7087 const RecordType *TyRec; 7088 if (const MemberPointerType *RHSMPType = 7089 ArgExpr->getType()->getAs<MemberPointerType>()) 7090 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7091 else 7092 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7093 if (!TyRec) { 7094 // Just to be safe, assume the worst case. 7095 VRQuals.addVolatile(); 7096 VRQuals.addRestrict(); 7097 return VRQuals; 7098 } 7099 7100 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7101 if (!ClassDecl->hasDefinition()) 7102 return VRQuals; 7103 7104 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7105 if (isa<UsingShadowDecl>(D)) 7106 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7107 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7108 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7109 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7110 CanTy = ResTypeRef->getPointeeType(); 7111 // Need to go down the pointer/mempointer chain and add qualifiers 7112 // as see them. 7113 bool done = false; 7114 while (!done) { 7115 if (CanTy.isRestrictQualified()) 7116 VRQuals.addRestrict(); 7117 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7118 CanTy = ResTypePtr->getPointeeType(); 7119 else if (const MemberPointerType *ResTypeMPtr = 7120 CanTy->getAs<MemberPointerType>()) 7121 CanTy = ResTypeMPtr->getPointeeType(); 7122 else 7123 done = true; 7124 if (CanTy.isVolatileQualified()) 7125 VRQuals.addVolatile(); 7126 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7127 return VRQuals; 7128 } 7129 } 7130 } 7131 return VRQuals; 7132 } 7133 7134 namespace { 7135 7136 /// \brief Helper class to manage the addition of builtin operator overload 7137 /// candidates. It provides shared state and utility methods used throughout 7138 /// the process, as well as a helper method to add each group of builtin 7139 /// operator overloads from the standard to a candidate set. 7140 class BuiltinOperatorOverloadBuilder { 7141 // Common instance state available to all overload candidate addition methods. 7142 Sema &S; 7143 ArrayRef<Expr *> Args; 7144 Qualifiers VisibleTypeConversionsQuals; 7145 bool HasArithmeticOrEnumeralCandidateType; 7146 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7147 OverloadCandidateSet &CandidateSet; 7148 7149 // Define some constants used to index and iterate over the arithemetic types 7150 // provided via the getArithmeticType() method below. 7151 // The "promoted arithmetic types" are the arithmetic 7152 // types are that preserved by promotion (C++ [over.built]p2). 7153 static const unsigned FirstIntegralType = 3; 7154 static const unsigned LastIntegralType = 20; 7155 static const unsigned FirstPromotedIntegralType = 3, 7156 LastPromotedIntegralType = 11; 7157 static const unsigned FirstPromotedArithmeticType = 0, 7158 LastPromotedArithmeticType = 11; 7159 static const unsigned NumArithmeticTypes = 20; 7160 7161 /// \brief Get the canonical type for a given arithmetic type index. 7162 CanQualType getArithmeticType(unsigned index) { 7163 assert(index < NumArithmeticTypes); 7164 static CanQualType ASTContext::* const 7165 ArithmeticTypes[NumArithmeticTypes] = { 7166 // Start of promoted types. 7167 &ASTContext::FloatTy, 7168 &ASTContext::DoubleTy, 7169 &ASTContext::LongDoubleTy, 7170 7171 // Start of integral types. 7172 &ASTContext::IntTy, 7173 &ASTContext::LongTy, 7174 &ASTContext::LongLongTy, 7175 &ASTContext::Int128Ty, 7176 &ASTContext::UnsignedIntTy, 7177 &ASTContext::UnsignedLongTy, 7178 &ASTContext::UnsignedLongLongTy, 7179 &ASTContext::UnsignedInt128Ty, 7180 // End of promoted types. 7181 7182 &ASTContext::BoolTy, 7183 &ASTContext::CharTy, 7184 &ASTContext::WCharTy, 7185 &ASTContext::Char16Ty, 7186 &ASTContext::Char32Ty, 7187 &ASTContext::SignedCharTy, 7188 &ASTContext::ShortTy, 7189 &ASTContext::UnsignedCharTy, 7190 &ASTContext::UnsignedShortTy, 7191 // End of integral types. 7192 // FIXME: What about complex? What about half? 7193 }; 7194 return S.Context.*ArithmeticTypes[index]; 7195 } 7196 7197 /// \brief Gets the canonical type resulting from the usual arithemetic 7198 /// converions for the given arithmetic types. 7199 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 7200 // Accelerator table for performing the usual arithmetic conversions. 7201 // The rules are basically: 7202 // - if either is floating-point, use the wider floating-point 7203 // - if same signedness, use the higher rank 7204 // - if same size, use unsigned of the higher rank 7205 // - use the larger type 7206 // These rules, together with the axiom that higher ranks are 7207 // never smaller, are sufficient to precompute all of these results 7208 // *except* when dealing with signed types of higher rank. 7209 // (we could precompute SLL x UI for all known platforms, but it's 7210 // better not to make any assumptions). 7211 // We assume that int128 has a higher rank than long long on all platforms. 7212 enum PromotedType { 7213 Dep=-1, 7214 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 7215 }; 7216 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 7217 [LastPromotedArithmeticType] = { 7218 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 7219 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 7220 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 7221 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 7222 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 7223 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 7224 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 7225 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 7226 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 7227 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 7228 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 7229 }; 7230 7231 assert(L < LastPromotedArithmeticType); 7232 assert(R < LastPromotedArithmeticType); 7233 int Idx = ConversionsTable[L][R]; 7234 7235 // Fast path: the table gives us a concrete answer. 7236 if (Idx != Dep) return getArithmeticType(Idx); 7237 7238 // Slow path: we need to compare widths. 7239 // An invariant is that the signed type has higher rank. 7240 CanQualType LT = getArithmeticType(L), 7241 RT = getArithmeticType(R); 7242 unsigned LW = S.Context.getIntWidth(LT), 7243 RW = S.Context.getIntWidth(RT); 7244 7245 // If they're different widths, use the signed type. 7246 if (LW > RW) return LT; 7247 else if (LW < RW) return RT; 7248 7249 // Otherwise, use the unsigned type of the signed type's rank. 7250 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 7251 assert(L == SLL || R == SLL); 7252 return S.Context.UnsignedLongLongTy; 7253 } 7254 7255 /// \brief Helper method to factor out the common pattern of adding overloads 7256 /// for '++' and '--' builtin operators. 7257 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7258 bool HasVolatile, 7259 bool HasRestrict) { 7260 QualType ParamTypes[2] = { 7261 S.Context.getLValueReferenceType(CandidateTy), 7262 S.Context.IntTy 7263 }; 7264 7265 // Non-volatile version. 7266 if (Args.size() == 1) 7267 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7268 else 7269 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7270 7271 // Use a heuristic to reduce number of builtin candidates in the set: 7272 // add volatile version only if there are conversions to a volatile type. 7273 if (HasVolatile) { 7274 ParamTypes[0] = 7275 S.Context.getLValueReferenceType( 7276 S.Context.getVolatileType(CandidateTy)); 7277 if (Args.size() == 1) 7278 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7279 else 7280 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7281 } 7282 7283 // Add restrict version only if there are conversions to a restrict type 7284 // and our candidate type is a non-restrict-qualified pointer. 7285 if (HasRestrict && CandidateTy->isAnyPointerType() && 7286 !CandidateTy.isRestrictQualified()) { 7287 ParamTypes[0] 7288 = S.Context.getLValueReferenceType( 7289 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7290 if (Args.size() == 1) 7291 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7292 else 7293 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7294 7295 if (HasVolatile) { 7296 ParamTypes[0] 7297 = S.Context.getLValueReferenceType( 7298 S.Context.getCVRQualifiedType(CandidateTy, 7299 (Qualifiers::Volatile | 7300 Qualifiers::Restrict))); 7301 if (Args.size() == 1) 7302 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7303 else 7304 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7305 } 7306 } 7307 7308 } 7309 7310 public: 7311 BuiltinOperatorOverloadBuilder( 7312 Sema &S, ArrayRef<Expr *> Args, 7313 Qualifiers VisibleTypeConversionsQuals, 7314 bool HasArithmeticOrEnumeralCandidateType, 7315 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7316 OverloadCandidateSet &CandidateSet) 7317 : S(S), Args(Args), 7318 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7319 HasArithmeticOrEnumeralCandidateType( 7320 HasArithmeticOrEnumeralCandidateType), 7321 CandidateTypes(CandidateTypes), 7322 CandidateSet(CandidateSet) { 7323 // Validate some of our static helper constants in debug builds. 7324 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7325 "Invalid first promoted integral type"); 7326 assert(getArithmeticType(LastPromotedIntegralType - 1) 7327 == S.Context.UnsignedInt128Ty && 7328 "Invalid last promoted integral type"); 7329 assert(getArithmeticType(FirstPromotedArithmeticType) 7330 == S.Context.FloatTy && 7331 "Invalid first promoted arithmetic type"); 7332 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7333 == S.Context.UnsignedInt128Ty && 7334 "Invalid last promoted arithmetic type"); 7335 } 7336 7337 // C++ [over.built]p3: 7338 // 7339 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7340 // is either volatile or empty, there exist candidate operator 7341 // functions of the form 7342 // 7343 // VQ T& operator++(VQ T&); 7344 // T operator++(VQ T&, int); 7345 // 7346 // C++ [over.built]p4: 7347 // 7348 // For every pair (T, VQ), where T is an arithmetic type other 7349 // than bool, and VQ is either volatile or empty, there exist 7350 // candidate operator functions of the form 7351 // 7352 // VQ T& operator--(VQ T&); 7353 // T operator--(VQ T&, int); 7354 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7355 if (!HasArithmeticOrEnumeralCandidateType) 7356 return; 7357 7358 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7359 Arith < NumArithmeticTypes; ++Arith) { 7360 addPlusPlusMinusMinusStyleOverloads( 7361 getArithmeticType(Arith), 7362 VisibleTypeConversionsQuals.hasVolatile(), 7363 VisibleTypeConversionsQuals.hasRestrict()); 7364 } 7365 } 7366 7367 // C++ [over.built]p5: 7368 // 7369 // For every pair (T, VQ), where T is a cv-qualified or 7370 // cv-unqualified object type, and VQ is either volatile or 7371 // empty, there exist candidate operator functions of the form 7372 // 7373 // T*VQ& operator++(T*VQ&); 7374 // T*VQ& operator--(T*VQ&); 7375 // T* operator++(T*VQ&, int); 7376 // T* operator--(T*VQ&, int); 7377 void addPlusPlusMinusMinusPointerOverloads() { 7378 for (BuiltinCandidateTypeSet::iterator 7379 Ptr = CandidateTypes[0].pointer_begin(), 7380 PtrEnd = CandidateTypes[0].pointer_end(); 7381 Ptr != PtrEnd; ++Ptr) { 7382 // Skip pointer types that aren't pointers to object types. 7383 if (!(*Ptr)->getPointeeType()->isObjectType()) 7384 continue; 7385 7386 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7387 (!(*Ptr).isVolatileQualified() && 7388 VisibleTypeConversionsQuals.hasVolatile()), 7389 (!(*Ptr).isRestrictQualified() && 7390 VisibleTypeConversionsQuals.hasRestrict())); 7391 } 7392 } 7393 7394 // C++ [over.built]p6: 7395 // For every cv-qualified or cv-unqualified object type T, there 7396 // exist candidate operator functions of the form 7397 // 7398 // T& operator*(T*); 7399 // 7400 // C++ [over.built]p7: 7401 // For every function type T that does not have cv-qualifiers or a 7402 // ref-qualifier, there exist candidate operator functions of the form 7403 // T& operator*(T*); 7404 void addUnaryStarPointerOverloads() { 7405 for (BuiltinCandidateTypeSet::iterator 7406 Ptr = CandidateTypes[0].pointer_begin(), 7407 PtrEnd = CandidateTypes[0].pointer_end(); 7408 Ptr != PtrEnd; ++Ptr) { 7409 QualType ParamTy = *Ptr; 7410 QualType PointeeTy = ParamTy->getPointeeType(); 7411 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7412 continue; 7413 7414 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7415 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7416 continue; 7417 7418 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7419 &ParamTy, Args, CandidateSet); 7420 } 7421 } 7422 7423 // C++ [over.built]p9: 7424 // For every promoted arithmetic type T, there exist candidate 7425 // operator functions of the form 7426 // 7427 // T operator+(T); 7428 // T operator-(T); 7429 void addUnaryPlusOrMinusArithmeticOverloads() { 7430 if (!HasArithmeticOrEnumeralCandidateType) 7431 return; 7432 7433 for (unsigned Arith = FirstPromotedArithmeticType; 7434 Arith < LastPromotedArithmeticType; ++Arith) { 7435 QualType ArithTy = getArithmeticType(Arith); 7436 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7437 } 7438 7439 // Extension: We also add these operators for vector types. 7440 for (BuiltinCandidateTypeSet::iterator 7441 Vec = CandidateTypes[0].vector_begin(), 7442 VecEnd = CandidateTypes[0].vector_end(); 7443 Vec != VecEnd; ++Vec) { 7444 QualType VecTy = *Vec; 7445 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7446 } 7447 } 7448 7449 // C++ [over.built]p8: 7450 // For every type T, there exist candidate operator functions of 7451 // the form 7452 // 7453 // T* operator+(T*); 7454 void addUnaryPlusPointerOverloads() { 7455 for (BuiltinCandidateTypeSet::iterator 7456 Ptr = CandidateTypes[0].pointer_begin(), 7457 PtrEnd = CandidateTypes[0].pointer_end(); 7458 Ptr != PtrEnd; ++Ptr) { 7459 QualType ParamTy = *Ptr; 7460 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7461 } 7462 } 7463 7464 // C++ [over.built]p10: 7465 // For every promoted integral type T, there exist candidate 7466 // operator functions of the form 7467 // 7468 // T operator~(T); 7469 void addUnaryTildePromotedIntegralOverloads() { 7470 if (!HasArithmeticOrEnumeralCandidateType) 7471 return; 7472 7473 for (unsigned Int = FirstPromotedIntegralType; 7474 Int < LastPromotedIntegralType; ++Int) { 7475 QualType IntTy = getArithmeticType(Int); 7476 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7477 } 7478 7479 // Extension: We also add this operator for vector types. 7480 for (BuiltinCandidateTypeSet::iterator 7481 Vec = CandidateTypes[0].vector_begin(), 7482 VecEnd = CandidateTypes[0].vector_end(); 7483 Vec != VecEnd; ++Vec) { 7484 QualType VecTy = *Vec; 7485 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7486 } 7487 } 7488 7489 // C++ [over.match.oper]p16: 7490 // For every pointer to member type T, there exist candidate operator 7491 // functions of the form 7492 // 7493 // bool operator==(T,T); 7494 // bool operator!=(T,T); 7495 void addEqualEqualOrNotEqualMemberPointerOverloads() { 7496 /// Set of (canonical) types that we've already handled. 7497 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7498 7499 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7500 for (BuiltinCandidateTypeSet::iterator 7501 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7502 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7503 MemPtr != MemPtrEnd; 7504 ++MemPtr) { 7505 // Don't add the same builtin candidate twice. 7506 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7507 continue; 7508 7509 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7510 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7511 } 7512 } 7513 } 7514 7515 // C++ [over.built]p15: 7516 // 7517 // For every T, where T is an enumeration type, a pointer type, or 7518 // std::nullptr_t, there exist candidate operator functions of the form 7519 // 7520 // bool operator<(T, T); 7521 // bool operator>(T, T); 7522 // bool operator<=(T, T); 7523 // bool operator>=(T, T); 7524 // bool operator==(T, T); 7525 // bool operator!=(T, T); 7526 void addRelationalPointerOrEnumeralOverloads() { 7527 // C++ [over.match.oper]p3: 7528 // [...]the built-in candidates include all of the candidate operator 7529 // functions defined in 13.6 that, compared to the given operator, [...] 7530 // do not have the same parameter-type-list as any non-template non-member 7531 // candidate. 7532 // 7533 // Note that in practice, this only affects enumeration types because there 7534 // aren't any built-in candidates of record type, and a user-defined operator 7535 // must have an operand of record or enumeration type. Also, the only other 7536 // overloaded operator with enumeration arguments, operator=, 7537 // cannot be overloaded for enumeration types, so this is the only place 7538 // where we must suppress candidates like this. 7539 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7540 UserDefinedBinaryOperators; 7541 7542 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7543 if (CandidateTypes[ArgIdx].enumeration_begin() != 7544 CandidateTypes[ArgIdx].enumeration_end()) { 7545 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7546 CEnd = CandidateSet.end(); 7547 C != CEnd; ++C) { 7548 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7549 continue; 7550 7551 if (C->Function->isFunctionTemplateSpecialization()) 7552 continue; 7553 7554 QualType FirstParamType = 7555 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7556 QualType SecondParamType = 7557 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7558 7559 // Skip if either parameter isn't of enumeral type. 7560 if (!FirstParamType->isEnumeralType() || 7561 !SecondParamType->isEnumeralType()) 7562 continue; 7563 7564 // Add this operator to the set of known user-defined operators. 7565 UserDefinedBinaryOperators.insert( 7566 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7567 S.Context.getCanonicalType(SecondParamType))); 7568 } 7569 } 7570 } 7571 7572 /// Set of (canonical) types that we've already handled. 7573 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7574 7575 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7576 for (BuiltinCandidateTypeSet::iterator 7577 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7578 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7579 Ptr != PtrEnd; ++Ptr) { 7580 // Don't add the same builtin candidate twice. 7581 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7582 continue; 7583 7584 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7585 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7586 } 7587 for (BuiltinCandidateTypeSet::iterator 7588 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7589 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7590 Enum != EnumEnd; ++Enum) { 7591 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7592 7593 // Don't add the same builtin candidate twice, or if a user defined 7594 // candidate exists. 7595 if (!AddedTypes.insert(CanonType).second || 7596 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7597 CanonType))) 7598 continue; 7599 7600 QualType ParamTypes[2] = { *Enum, *Enum }; 7601 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7602 } 7603 7604 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7605 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7606 if (AddedTypes.insert(NullPtrTy).second && 7607 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy, 7608 NullPtrTy))) { 7609 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7610 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7611 CandidateSet); 7612 } 7613 } 7614 } 7615 } 7616 7617 // C++ [over.built]p13: 7618 // 7619 // For every cv-qualified or cv-unqualified object type T 7620 // there exist candidate operator functions of the form 7621 // 7622 // T* operator+(T*, ptrdiff_t); 7623 // T& operator[](T*, ptrdiff_t); [BELOW] 7624 // T* operator-(T*, ptrdiff_t); 7625 // T* operator+(ptrdiff_t, T*); 7626 // T& operator[](ptrdiff_t, T*); [BELOW] 7627 // 7628 // C++ [over.built]p14: 7629 // 7630 // For every T, where T is a pointer to object type, there 7631 // exist candidate operator functions of the form 7632 // 7633 // ptrdiff_t operator-(T, T); 7634 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7635 /// Set of (canonical) types that we've already handled. 7636 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7637 7638 for (int Arg = 0; Arg < 2; ++Arg) { 7639 QualType AsymmetricParamTypes[2] = { 7640 S.Context.getPointerDiffType(), 7641 S.Context.getPointerDiffType(), 7642 }; 7643 for (BuiltinCandidateTypeSet::iterator 7644 Ptr = CandidateTypes[Arg].pointer_begin(), 7645 PtrEnd = CandidateTypes[Arg].pointer_end(); 7646 Ptr != PtrEnd; ++Ptr) { 7647 QualType PointeeTy = (*Ptr)->getPointeeType(); 7648 if (!PointeeTy->isObjectType()) 7649 continue; 7650 7651 AsymmetricParamTypes[Arg] = *Ptr; 7652 if (Arg == 0 || Op == OO_Plus) { 7653 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7654 // T* operator+(ptrdiff_t, T*); 7655 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet); 7656 } 7657 if (Op == OO_Minus) { 7658 // ptrdiff_t operator-(T, T); 7659 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7660 continue; 7661 7662 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7663 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7664 Args, CandidateSet); 7665 } 7666 } 7667 } 7668 } 7669 7670 // C++ [over.built]p12: 7671 // 7672 // For every pair of promoted arithmetic types L and R, there 7673 // exist candidate operator functions of the form 7674 // 7675 // LR operator*(L, R); 7676 // LR operator/(L, R); 7677 // LR operator+(L, R); 7678 // LR operator-(L, R); 7679 // bool operator<(L, R); 7680 // bool operator>(L, R); 7681 // bool operator<=(L, R); 7682 // bool operator>=(L, R); 7683 // bool operator==(L, R); 7684 // bool operator!=(L, R); 7685 // 7686 // where LR is the result of the usual arithmetic conversions 7687 // between types L and R. 7688 // 7689 // C++ [over.built]p24: 7690 // 7691 // For every pair of promoted arithmetic types L and R, there exist 7692 // candidate operator functions of the form 7693 // 7694 // LR operator?(bool, L, R); 7695 // 7696 // where LR is the result of the usual arithmetic conversions 7697 // between types L and R. 7698 // Our candidates ignore the first parameter. 7699 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7700 if (!HasArithmeticOrEnumeralCandidateType) 7701 return; 7702 7703 for (unsigned Left = FirstPromotedArithmeticType; 7704 Left < LastPromotedArithmeticType; ++Left) { 7705 for (unsigned Right = FirstPromotedArithmeticType; 7706 Right < LastPromotedArithmeticType; ++Right) { 7707 QualType LandR[2] = { getArithmeticType(Left), 7708 getArithmeticType(Right) }; 7709 QualType Result = 7710 isComparison ? S.Context.BoolTy 7711 : getUsualArithmeticConversions(Left, Right); 7712 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7713 } 7714 } 7715 7716 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7717 // conditional operator for vector types. 7718 for (BuiltinCandidateTypeSet::iterator 7719 Vec1 = CandidateTypes[0].vector_begin(), 7720 Vec1End = CandidateTypes[0].vector_end(); 7721 Vec1 != Vec1End; ++Vec1) { 7722 for (BuiltinCandidateTypeSet::iterator 7723 Vec2 = CandidateTypes[1].vector_begin(), 7724 Vec2End = CandidateTypes[1].vector_end(); 7725 Vec2 != Vec2End; ++Vec2) { 7726 QualType LandR[2] = { *Vec1, *Vec2 }; 7727 QualType Result = S.Context.BoolTy; 7728 if (!isComparison) { 7729 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7730 Result = *Vec1; 7731 else 7732 Result = *Vec2; 7733 } 7734 7735 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7736 } 7737 } 7738 } 7739 7740 // C++ [over.built]p17: 7741 // 7742 // For every pair of promoted integral types L and R, there 7743 // exist candidate operator functions of the form 7744 // 7745 // LR operator%(L, R); 7746 // LR operator&(L, R); 7747 // LR operator^(L, R); 7748 // LR operator|(L, R); 7749 // L operator<<(L, R); 7750 // L operator>>(L, R); 7751 // 7752 // where LR is the result of the usual arithmetic conversions 7753 // between types L and R. 7754 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7755 if (!HasArithmeticOrEnumeralCandidateType) 7756 return; 7757 7758 for (unsigned Left = FirstPromotedIntegralType; 7759 Left < LastPromotedIntegralType; ++Left) { 7760 for (unsigned Right = FirstPromotedIntegralType; 7761 Right < LastPromotedIntegralType; ++Right) { 7762 QualType LandR[2] = { getArithmeticType(Left), 7763 getArithmeticType(Right) }; 7764 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7765 ? LandR[0] 7766 : getUsualArithmeticConversions(Left, Right); 7767 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7768 } 7769 } 7770 } 7771 7772 // C++ [over.built]p20: 7773 // 7774 // For every pair (T, VQ), where T is an enumeration or 7775 // pointer to member type and VQ is either volatile or 7776 // empty, there exist candidate operator functions of the form 7777 // 7778 // VQ T& operator=(VQ T&, T); 7779 void addAssignmentMemberPointerOrEnumeralOverloads() { 7780 /// Set of (canonical) types that we've already handled. 7781 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7782 7783 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7784 for (BuiltinCandidateTypeSet::iterator 7785 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7786 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7787 Enum != EnumEnd; ++Enum) { 7788 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 7789 continue; 7790 7791 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7792 } 7793 7794 for (BuiltinCandidateTypeSet::iterator 7795 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7796 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7797 MemPtr != MemPtrEnd; ++MemPtr) { 7798 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7799 continue; 7800 7801 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7802 } 7803 } 7804 } 7805 7806 // C++ [over.built]p19: 7807 // 7808 // For every pair (T, VQ), where T is any type and VQ is either 7809 // volatile or empty, there exist candidate operator functions 7810 // of the form 7811 // 7812 // T*VQ& operator=(T*VQ&, T*); 7813 // 7814 // C++ [over.built]p21: 7815 // 7816 // For every pair (T, VQ), where T is a cv-qualified or 7817 // cv-unqualified object type and VQ is either volatile or 7818 // empty, there exist candidate operator functions of the form 7819 // 7820 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7821 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7822 void addAssignmentPointerOverloads(bool isEqualOp) { 7823 /// Set of (canonical) types that we've already handled. 7824 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7825 7826 for (BuiltinCandidateTypeSet::iterator 7827 Ptr = CandidateTypes[0].pointer_begin(), 7828 PtrEnd = CandidateTypes[0].pointer_end(); 7829 Ptr != PtrEnd; ++Ptr) { 7830 // If this is operator=, keep track of the builtin candidates we added. 7831 if (isEqualOp) 7832 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 7833 else if (!(*Ptr)->getPointeeType()->isObjectType()) 7834 continue; 7835 7836 // non-volatile version 7837 QualType ParamTypes[2] = { 7838 S.Context.getLValueReferenceType(*Ptr), 7839 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 7840 }; 7841 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7842 /*IsAssigmentOperator=*/ isEqualOp); 7843 7844 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7845 VisibleTypeConversionsQuals.hasVolatile(); 7846 if (NeedVolatile) { 7847 // volatile version 7848 ParamTypes[0] = 7849 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7850 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7851 /*IsAssigmentOperator=*/isEqualOp); 7852 } 7853 7854 if (!(*Ptr).isRestrictQualified() && 7855 VisibleTypeConversionsQuals.hasRestrict()) { 7856 // restrict version 7857 ParamTypes[0] 7858 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7859 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7860 /*IsAssigmentOperator=*/isEqualOp); 7861 7862 if (NeedVolatile) { 7863 // volatile restrict version 7864 ParamTypes[0] 7865 = S.Context.getLValueReferenceType( 7866 S.Context.getCVRQualifiedType(*Ptr, 7867 (Qualifiers::Volatile | 7868 Qualifiers::Restrict))); 7869 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7870 /*IsAssigmentOperator=*/isEqualOp); 7871 } 7872 } 7873 } 7874 7875 if (isEqualOp) { 7876 for (BuiltinCandidateTypeSet::iterator 7877 Ptr = CandidateTypes[1].pointer_begin(), 7878 PtrEnd = CandidateTypes[1].pointer_end(); 7879 Ptr != PtrEnd; ++Ptr) { 7880 // Make sure we don't add the same candidate twice. 7881 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7882 continue; 7883 7884 QualType ParamTypes[2] = { 7885 S.Context.getLValueReferenceType(*Ptr), 7886 *Ptr, 7887 }; 7888 7889 // non-volatile version 7890 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7891 /*IsAssigmentOperator=*/true); 7892 7893 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 7894 VisibleTypeConversionsQuals.hasVolatile(); 7895 if (NeedVolatile) { 7896 // volatile version 7897 ParamTypes[0] = 7898 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 7899 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7900 /*IsAssigmentOperator=*/true); 7901 } 7902 7903 if (!(*Ptr).isRestrictQualified() && 7904 VisibleTypeConversionsQuals.hasRestrict()) { 7905 // restrict version 7906 ParamTypes[0] 7907 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 7908 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7909 /*IsAssigmentOperator=*/true); 7910 7911 if (NeedVolatile) { 7912 // volatile restrict version 7913 ParamTypes[0] 7914 = S.Context.getLValueReferenceType( 7915 S.Context.getCVRQualifiedType(*Ptr, 7916 (Qualifiers::Volatile | 7917 Qualifiers::Restrict))); 7918 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7919 /*IsAssigmentOperator=*/true); 7920 } 7921 } 7922 } 7923 } 7924 } 7925 7926 // C++ [over.built]p18: 7927 // 7928 // For every triple (L, VQ, R), where L is an arithmetic type, 7929 // VQ is either volatile or empty, and R is a promoted 7930 // arithmetic type, there exist candidate operator functions of 7931 // the form 7932 // 7933 // VQ L& operator=(VQ L&, R); 7934 // VQ L& operator*=(VQ L&, R); 7935 // VQ L& operator/=(VQ L&, R); 7936 // VQ L& operator+=(VQ L&, R); 7937 // VQ L& operator-=(VQ L&, R); 7938 void addAssignmentArithmeticOverloads(bool isEqualOp) { 7939 if (!HasArithmeticOrEnumeralCandidateType) 7940 return; 7941 7942 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 7943 for (unsigned Right = FirstPromotedArithmeticType; 7944 Right < LastPromotedArithmeticType; ++Right) { 7945 QualType ParamTypes[2]; 7946 ParamTypes[1] = getArithmeticType(Right); 7947 7948 // Add this built-in operator as a candidate (VQ is empty). 7949 ParamTypes[0] = 7950 S.Context.getLValueReferenceType(getArithmeticType(Left)); 7951 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7952 /*IsAssigmentOperator=*/isEqualOp); 7953 7954 // Add this built-in operator as a candidate (VQ is 'volatile'). 7955 if (VisibleTypeConversionsQuals.hasVolatile()) { 7956 ParamTypes[0] = 7957 S.Context.getVolatileType(getArithmeticType(Left)); 7958 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7959 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7960 /*IsAssigmentOperator=*/isEqualOp); 7961 } 7962 } 7963 } 7964 7965 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 7966 for (BuiltinCandidateTypeSet::iterator 7967 Vec1 = CandidateTypes[0].vector_begin(), 7968 Vec1End = CandidateTypes[0].vector_end(); 7969 Vec1 != Vec1End; ++Vec1) { 7970 for (BuiltinCandidateTypeSet::iterator 7971 Vec2 = CandidateTypes[1].vector_begin(), 7972 Vec2End = CandidateTypes[1].vector_end(); 7973 Vec2 != Vec2End; ++Vec2) { 7974 QualType ParamTypes[2]; 7975 ParamTypes[1] = *Vec2; 7976 // Add this built-in operator as a candidate (VQ is empty). 7977 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 7978 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7979 /*IsAssigmentOperator=*/isEqualOp); 7980 7981 // Add this built-in operator as a candidate (VQ is 'volatile'). 7982 if (VisibleTypeConversionsQuals.hasVolatile()) { 7983 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 7984 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 7985 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7986 /*IsAssigmentOperator=*/isEqualOp); 7987 } 7988 } 7989 } 7990 } 7991 7992 // C++ [over.built]p22: 7993 // 7994 // For every triple (L, VQ, R), where L is an integral type, VQ 7995 // is either volatile or empty, and R is a promoted integral 7996 // type, there exist candidate operator functions of the form 7997 // 7998 // VQ L& operator%=(VQ L&, R); 7999 // VQ L& operator<<=(VQ L&, R); 8000 // VQ L& operator>>=(VQ L&, R); 8001 // VQ L& operator&=(VQ L&, R); 8002 // VQ L& operator^=(VQ L&, R); 8003 // VQ L& operator|=(VQ L&, R); 8004 void addAssignmentIntegralOverloads() { 8005 if (!HasArithmeticOrEnumeralCandidateType) 8006 return; 8007 8008 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8009 for (unsigned Right = FirstPromotedIntegralType; 8010 Right < LastPromotedIntegralType; ++Right) { 8011 QualType ParamTypes[2]; 8012 ParamTypes[1] = getArithmeticType(Right); 8013 8014 // Add this built-in operator as a candidate (VQ is empty). 8015 ParamTypes[0] = 8016 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8017 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8018 if (VisibleTypeConversionsQuals.hasVolatile()) { 8019 // Add this built-in operator as a candidate (VQ is 'volatile'). 8020 ParamTypes[0] = getArithmeticType(Left); 8021 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8022 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8023 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8024 } 8025 } 8026 } 8027 } 8028 8029 // C++ [over.operator]p23: 8030 // 8031 // There also exist candidate operator functions of the form 8032 // 8033 // bool operator!(bool); 8034 // bool operator&&(bool, bool); 8035 // bool operator||(bool, bool); 8036 void addExclaimOverload() { 8037 QualType ParamTy = S.Context.BoolTy; 8038 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 8039 /*IsAssignmentOperator=*/false, 8040 /*NumContextualBoolArguments=*/1); 8041 } 8042 void addAmpAmpOrPipePipeOverload() { 8043 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8044 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 8045 /*IsAssignmentOperator=*/false, 8046 /*NumContextualBoolArguments=*/2); 8047 } 8048 8049 // C++ [over.built]p13: 8050 // 8051 // For every cv-qualified or cv-unqualified object type T there 8052 // exist candidate operator functions of the form 8053 // 8054 // T* operator+(T*, ptrdiff_t); [ABOVE] 8055 // T& operator[](T*, ptrdiff_t); 8056 // T* operator-(T*, ptrdiff_t); [ABOVE] 8057 // T* operator+(ptrdiff_t, T*); [ABOVE] 8058 // T& operator[](ptrdiff_t, T*); 8059 void addSubscriptOverloads() { 8060 for (BuiltinCandidateTypeSet::iterator 8061 Ptr = CandidateTypes[0].pointer_begin(), 8062 PtrEnd = CandidateTypes[0].pointer_end(); 8063 Ptr != PtrEnd; ++Ptr) { 8064 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8065 QualType PointeeType = (*Ptr)->getPointeeType(); 8066 if (!PointeeType->isObjectType()) 8067 continue; 8068 8069 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8070 8071 // T& operator[](T*, ptrdiff_t) 8072 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8073 } 8074 8075 for (BuiltinCandidateTypeSet::iterator 8076 Ptr = CandidateTypes[1].pointer_begin(), 8077 PtrEnd = CandidateTypes[1].pointer_end(); 8078 Ptr != PtrEnd; ++Ptr) { 8079 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8080 QualType PointeeType = (*Ptr)->getPointeeType(); 8081 if (!PointeeType->isObjectType()) 8082 continue; 8083 8084 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8085 8086 // T& operator[](ptrdiff_t, T*) 8087 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8088 } 8089 } 8090 8091 // C++ [over.built]p11: 8092 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8093 // C1 is the same type as C2 or is a derived class of C2, T is an object 8094 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8095 // there exist candidate operator functions of the form 8096 // 8097 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8098 // 8099 // where CV12 is the union of CV1 and CV2. 8100 void addArrowStarOverloads() { 8101 for (BuiltinCandidateTypeSet::iterator 8102 Ptr = CandidateTypes[0].pointer_begin(), 8103 PtrEnd = CandidateTypes[0].pointer_end(); 8104 Ptr != PtrEnd; ++Ptr) { 8105 QualType C1Ty = (*Ptr); 8106 QualType C1; 8107 QualifierCollector Q1; 8108 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8109 if (!isa<RecordType>(C1)) 8110 continue; 8111 // heuristic to reduce number of builtin candidates in the set. 8112 // Add volatile/restrict version only if there are conversions to a 8113 // volatile/restrict type. 8114 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8115 continue; 8116 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8117 continue; 8118 for (BuiltinCandidateTypeSet::iterator 8119 MemPtr = CandidateTypes[1].member_pointer_begin(), 8120 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8121 MemPtr != MemPtrEnd; ++MemPtr) { 8122 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8123 QualType C2 = QualType(mptr->getClass(), 0); 8124 C2 = C2.getUnqualifiedType(); 8125 if (C1 != C2 && !S.IsDerivedFrom(C1, C2)) 8126 break; 8127 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8128 // build CV12 T& 8129 QualType T = mptr->getPointeeType(); 8130 if (!VisibleTypeConversionsQuals.hasVolatile() && 8131 T.isVolatileQualified()) 8132 continue; 8133 if (!VisibleTypeConversionsQuals.hasRestrict() && 8134 T.isRestrictQualified()) 8135 continue; 8136 T = Q1.apply(S.Context, T); 8137 QualType ResultTy = S.Context.getLValueReferenceType(T); 8138 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8139 } 8140 } 8141 } 8142 8143 // Note that we don't consider the first argument, since it has been 8144 // contextually converted to bool long ago. The candidates below are 8145 // therefore added as binary. 8146 // 8147 // C++ [over.built]p25: 8148 // For every type T, where T is a pointer, pointer-to-member, or scoped 8149 // enumeration type, there exist candidate operator functions of the form 8150 // 8151 // T operator?(bool, T, T); 8152 // 8153 void addConditionalOperatorOverloads() { 8154 /// Set of (canonical) types that we've already handled. 8155 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8156 8157 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8158 for (BuiltinCandidateTypeSet::iterator 8159 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8160 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8161 Ptr != PtrEnd; ++Ptr) { 8162 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8163 continue; 8164 8165 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8166 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 8167 } 8168 8169 for (BuiltinCandidateTypeSet::iterator 8170 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8171 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8172 MemPtr != MemPtrEnd; ++MemPtr) { 8173 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8174 continue; 8175 8176 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8177 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 8178 } 8179 8180 if (S.getLangOpts().CPlusPlus11) { 8181 for (BuiltinCandidateTypeSet::iterator 8182 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8183 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8184 Enum != EnumEnd; ++Enum) { 8185 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8186 continue; 8187 8188 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8189 continue; 8190 8191 QualType ParamTypes[2] = { *Enum, *Enum }; 8192 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 8193 } 8194 } 8195 } 8196 } 8197 }; 8198 8199 } // end anonymous namespace 8200 8201 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8202 /// operator overloads to the candidate set (C++ [over.built]), based 8203 /// on the operator @p Op and the arguments given. For example, if the 8204 /// operator is a binary '+', this routine might add "int 8205 /// operator+(int, int)" to cover integer addition. 8206 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8207 SourceLocation OpLoc, 8208 ArrayRef<Expr *> Args, 8209 OverloadCandidateSet &CandidateSet) { 8210 // Find all of the types that the arguments can convert to, but only 8211 // if the operator we're looking at has built-in operator candidates 8212 // that make use of these types. Also record whether we encounter non-record 8213 // candidate types or either arithmetic or enumeral candidate types. 8214 Qualifiers VisibleTypeConversionsQuals; 8215 VisibleTypeConversionsQuals.addConst(); 8216 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8217 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8218 8219 bool HasNonRecordCandidateType = false; 8220 bool HasArithmeticOrEnumeralCandidateType = false; 8221 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8222 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8223 CandidateTypes.emplace_back(*this); 8224 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8225 OpLoc, 8226 true, 8227 (Op == OO_Exclaim || 8228 Op == OO_AmpAmp || 8229 Op == OO_PipePipe), 8230 VisibleTypeConversionsQuals); 8231 HasNonRecordCandidateType = HasNonRecordCandidateType || 8232 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8233 HasArithmeticOrEnumeralCandidateType = 8234 HasArithmeticOrEnumeralCandidateType || 8235 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8236 } 8237 8238 // Exit early when no non-record types have been added to the candidate set 8239 // for any of the arguments to the operator. 8240 // 8241 // We can't exit early for !, ||, or &&, since there we have always have 8242 // 'bool' overloads. 8243 if (!HasNonRecordCandidateType && 8244 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8245 return; 8246 8247 // Setup an object to manage the common state for building overloads. 8248 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8249 VisibleTypeConversionsQuals, 8250 HasArithmeticOrEnumeralCandidateType, 8251 CandidateTypes, CandidateSet); 8252 8253 // Dispatch over the operation to add in only those overloads which apply. 8254 switch (Op) { 8255 case OO_None: 8256 case NUM_OVERLOADED_OPERATORS: 8257 llvm_unreachable("Expected an overloaded operator"); 8258 8259 case OO_New: 8260 case OO_Delete: 8261 case OO_Array_New: 8262 case OO_Array_Delete: 8263 case OO_Call: 8264 llvm_unreachable( 8265 "Special operators don't use AddBuiltinOperatorCandidates"); 8266 8267 case OO_Comma: 8268 case OO_Arrow: 8269 case OO_Coawait: 8270 // C++ [over.match.oper]p3: 8271 // -- For the operator ',', the unary operator '&', the 8272 // operator '->', or the operator 'co_await', the 8273 // built-in candidates set is empty. 8274 break; 8275 8276 case OO_Plus: // '+' is either unary or binary 8277 if (Args.size() == 1) 8278 OpBuilder.addUnaryPlusPointerOverloads(); 8279 // Fall through. 8280 8281 case OO_Minus: // '-' is either unary or binary 8282 if (Args.size() == 1) { 8283 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8284 } else { 8285 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8286 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8287 } 8288 break; 8289 8290 case OO_Star: // '*' is either unary or binary 8291 if (Args.size() == 1) 8292 OpBuilder.addUnaryStarPointerOverloads(); 8293 else 8294 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8295 break; 8296 8297 case OO_Slash: 8298 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8299 break; 8300 8301 case OO_PlusPlus: 8302 case OO_MinusMinus: 8303 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8304 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8305 break; 8306 8307 case OO_EqualEqual: 8308 case OO_ExclaimEqual: 8309 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads(); 8310 // Fall through. 8311 8312 case OO_Less: 8313 case OO_Greater: 8314 case OO_LessEqual: 8315 case OO_GreaterEqual: 8316 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8317 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8318 break; 8319 8320 case OO_Percent: 8321 case OO_Caret: 8322 case OO_Pipe: 8323 case OO_LessLess: 8324 case OO_GreaterGreater: 8325 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8326 break; 8327 8328 case OO_Amp: // '&' is either unary or binary 8329 if (Args.size() == 1) 8330 // C++ [over.match.oper]p3: 8331 // -- For the operator ',', the unary operator '&', or the 8332 // operator '->', the built-in candidates set is empty. 8333 break; 8334 8335 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8336 break; 8337 8338 case OO_Tilde: 8339 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8340 break; 8341 8342 case OO_Equal: 8343 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8344 // Fall through. 8345 8346 case OO_PlusEqual: 8347 case OO_MinusEqual: 8348 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8349 // Fall through. 8350 8351 case OO_StarEqual: 8352 case OO_SlashEqual: 8353 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8354 break; 8355 8356 case OO_PercentEqual: 8357 case OO_LessLessEqual: 8358 case OO_GreaterGreaterEqual: 8359 case OO_AmpEqual: 8360 case OO_CaretEqual: 8361 case OO_PipeEqual: 8362 OpBuilder.addAssignmentIntegralOverloads(); 8363 break; 8364 8365 case OO_Exclaim: 8366 OpBuilder.addExclaimOverload(); 8367 break; 8368 8369 case OO_AmpAmp: 8370 case OO_PipePipe: 8371 OpBuilder.addAmpAmpOrPipePipeOverload(); 8372 break; 8373 8374 case OO_Subscript: 8375 OpBuilder.addSubscriptOverloads(); 8376 break; 8377 8378 case OO_ArrowStar: 8379 OpBuilder.addArrowStarOverloads(); 8380 break; 8381 8382 case OO_Conditional: 8383 OpBuilder.addConditionalOperatorOverloads(); 8384 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8385 break; 8386 } 8387 } 8388 8389 /// \brief Add function candidates found via argument-dependent lookup 8390 /// to the set of overloading candidates. 8391 /// 8392 /// This routine performs argument-dependent name lookup based on the 8393 /// given function name (which may also be an operator name) and adds 8394 /// all of the overload candidates found by ADL to the overload 8395 /// candidate set (C++ [basic.lookup.argdep]). 8396 void 8397 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8398 SourceLocation Loc, 8399 ArrayRef<Expr *> Args, 8400 TemplateArgumentListInfo *ExplicitTemplateArgs, 8401 OverloadCandidateSet& CandidateSet, 8402 bool PartialOverloading) { 8403 ADLResult Fns; 8404 8405 // FIXME: This approach for uniquing ADL results (and removing 8406 // redundant candidates from the set) relies on pointer-equality, 8407 // which means we need to key off the canonical decl. However, 8408 // always going back to the canonical decl might not get us the 8409 // right set of default arguments. What default arguments are 8410 // we supposed to consider on ADL candidates, anyway? 8411 8412 // FIXME: Pass in the explicit template arguments? 8413 ArgumentDependentLookup(Name, Loc, Args, Fns); 8414 8415 // Erase all of the candidates we already knew about. 8416 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8417 CandEnd = CandidateSet.end(); 8418 Cand != CandEnd; ++Cand) 8419 if (Cand->Function) { 8420 Fns.erase(Cand->Function); 8421 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8422 Fns.erase(FunTmpl); 8423 } 8424 8425 // For each of the ADL candidates we found, add it to the overload 8426 // set. 8427 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8428 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8429 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8430 if (ExplicitTemplateArgs) 8431 continue; 8432 8433 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8434 PartialOverloading); 8435 } else 8436 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8437 FoundDecl, ExplicitTemplateArgs, 8438 Args, CandidateSet, PartialOverloading); 8439 } 8440 } 8441 8442 // Determines whether Cand1 is "better" in terms of its enable_if attrs than 8443 // Cand2 for overloading. This function assumes that all of the enable_if attrs 8444 // on Cand1 and Cand2 have conditions that evaluate to true. 8445 // 8446 // Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 8447 // Cand1's first N enable_if attributes have precisely the same conditions as 8448 // Cand2's first N enable_if attributes (where N = the number of enable_if 8449 // attributes on Cand2), and Cand1 has more than N enable_if attributes. 8450 static bool hasBetterEnableIfAttrs(Sema &S, const FunctionDecl *Cand1, 8451 const FunctionDecl *Cand2) { 8452 8453 // FIXME: The next several lines are just 8454 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8455 // instead of reverse order which is how they're stored in the AST. 8456 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1); 8457 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2); 8458 8459 // Candidate 1 is better if it has strictly more attributes and 8460 // the common sequence is identical. 8461 if (Cand1Attrs.size() <= Cand2Attrs.size()) 8462 return false; 8463 8464 auto Cand1I = Cand1Attrs.begin(); 8465 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8466 for (auto &Cand2A : Cand2Attrs) { 8467 Cand1ID.clear(); 8468 Cand2ID.clear(); 8469 8470 auto &Cand1A = *Cand1I++; 8471 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true); 8472 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true); 8473 if (Cand1ID != Cand2ID) 8474 return false; 8475 } 8476 8477 return true; 8478 } 8479 8480 /// isBetterOverloadCandidate - Determines whether the first overload 8481 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8482 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, 8483 const OverloadCandidate &Cand2, 8484 SourceLocation Loc, 8485 bool UserDefinedConversion) { 8486 // Define viable functions to be better candidates than non-viable 8487 // functions. 8488 if (!Cand2.Viable) 8489 return Cand1.Viable; 8490 else if (!Cand1.Viable) 8491 return false; 8492 8493 // C++ [over.match.best]p1: 8494 // 8495 // -- if F is a static member function, ICS1(F) is defined such 8496 // that ICS1(F) is neither better nor worse than ICS1(G) for 8497 // any function G, and, symmetrically, ICS1(G) is neither 8498 // better nor worse than ICS1(F). 8499 unsigned StartArg = 0; 8500 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8501 StartArg = 1; 8502 8503 // C++ [over.match.best]p1: 8504 // A viable function F1 is defined to be a better function than another 8505 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8506 // conversion sequence than ICSi(F2), and then... 8507 unsigned NumArgs = Cand1.NumConversions; 8508 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8509 bool HasBetterConversion = false; 8510 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8511 switch (CompareImplicitConversionSequences(S, 8512 Cand1.Conversions[ArgIdx], 8513 Cand2.Conversions[ArgIdx])) { 8514 case ImplicitConversionSequence::Better: 8515 // Cand1 has a better conversion sequence. 8516 HasBetterConversion = true; 8517 break; 8518 8519 case ImplicitConversionSequence::Worse: 8520 // Cand1 can't be better than Cand2. 8521 return false; 8522 8523 case ImplicitConversionSequence::Indistinguishable: 8524 // Do nothing. 8525 break; 8526 } 8527 } 8528 8529 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8530 // ICSj(F2), or, if not that, 8531 if (HasBetterConversion) 8532 return true; 8533 8534 // -- the context is an initialization by user-defined conversion 8535 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8536 // from the return type of F1 to the destination type (i.e., 8537 // the type of the entity being initialized) is a better 8538 // conversion sequence than the standard conversion sequence 8539 // from the return type of F2 to the destination type. 8540 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8541 isa<CXXConversionDecl>(Cand1.Function) && 8542 isa<CXXConversionDecl>(Cand2.Function)) { 8543 // First check whether we prefer one of the conversion functions over the 8544 // other. This only distinguishes the results in non-standard, extension 8545 // cases such as the conversion from a lambda closure type to a function 8546 // pointer or block. 8547 ImplicitConversionSequence::CompareKind Result = 8548 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8549 if (Result == ImplicitConversionSequence::Indistinguishable) 8550 Result = CompareStandardConversionSequences(S, 8551 Cand1.FinalConversion, 8552 Cand2.FinalConversion); 8553 8554 if (Result != ImplicitConversionSequence::Indistinguishable) 8555 return Result == ImplicitConversionSequence::Better; 8556 8557 // FIXME: Compare kind of reference binding if conversion functions 8558 // convert to a reference type used in direct reference binding, per 8559 // C++14 [over.match.best]p1 section 2 bullet 3. 8560 } 8561 8562 // -- F1 is a non-template function and F2 is a function template 8563 // specialization, or, if not that, 8564 bool Cand1IsSpecialization = Cand1.Function && 8565 Cand1.Function->getPrimaryTemplate(); 8566 bool Cand2IsSpecialization = Cand2.Function && 8567 Cand2.Function->getPrimaryTemplate(); 8568 if (Cand1IsSpecialization != Cand2IsSpecialization) 8569 return Cand2IsSpecialization; 8570 8571 // -- F1 and F2 are function template specializations, and the function 8572 // template for F1 is more specialized than the template for F2 8573 // according to the partial ordering rules described in 14.5.5.2, or, 8574 // if not that, 8575 if (Cand1IsSpecialization && Cand2IsSpecialization) { 8576 if (FunctionTemplateDecl *BetterTemplate 8577 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8578 Cand2.Function->getPrimaryTemplate(), 8579 Loc, 8580 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8581 : TPOC_Call, 8582 Cand1.ExplicitCallArguments, 8583 Cand2.ExplicitCallArguments)) 8584 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8585 } 8586 8587 // Check for enable_if value-based overload resolution. 8588 if (Cand1.Function && Cand2.Function && 8589 (Cand1.Function->hasAttr<EnableIfAttr>() || 8590 Cand2.Function->hasAttr<EnableIfAttr>())) 8591 return hasBetterEnableIfAttrs(S, Cand1.Function, Cand2.Function); 8592 8593 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads && 8594 Cand1.Function && Cand2.Function) { 8595 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8596 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 8597 S.IdentifyCUDAPreference(Caller, Cand2.Function); 8598 } 8599 8600 bool HasPS1 = Cand1.Function != nullptr && 8601 functionHasPassObjectSizeParams(Cand1.Function); 8602 bool HasPS2 = Cand2.Function != nullptr && 8603 functionHasPassObjectSizeParams(Cand2.Function); 8604 return HasPS1 != HasPS2 && HasPS1; 8605 } 8606 8607 /// Determine whether two declarations are "equivalent" for the purposes of 8608 /// name lookup and overload resolution. This applies when the same internal/no 8609 /// linkage entity is defined by two modules (probably by textually including 8610 /// the same header). In such a case, we don't consider the declarations to 8611 /// declare the same entity, but we also don't want lookups with both 8612 /// declarations visible to be ambiguous in some cases (this happens when using 8613 /// a modularized libstdc++). 8614 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 8615 const NamedDecl *B) { 8616 auto *VA = dyn_cast_or_null<ValueDecl>(A); 8617 auto *VB = dyn_cast_or_null<ValueDecl>(B); 8618 if (!VA || !VB) 8619 return false; 8620 8621 // The declarations must be declaring the same name as an internal linkage 8622 // entity in different modules. 8623 if (!VA->getDeclContext()->getRedeclContext()->Equals( 8624 VB->getDeclContext()->getRedeclContext()) || 8625 getOwningModule(const_cast<ValueDecl *>(VA)) == 8626 getOwningModule(const_cast<ValueDecl *>(VB)) || 8627 VA->isExternallyVisible() || VB->isExternallyVisible()) 8628 return false; 8629 8630 // Check that the declarations appear to be equivalent. 8631 // 8632 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 8633 // For constants and functions, we should check the initializer or body is 8634 // the same. For non-constant variables, we shouldn't allow it at all. 8635 if (Context.hasSameType(VA->getType(), VB->getType())) 8636 return true; 8637 8638 // Enum constants within unnamed enumerations will have different types, but 8639 // may still be similar enough to be interchangeable for our purposes. 8640 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 8641 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 8642 // Only handle anonymous enums. If the enumerations were named and 8643 // equivalent, they would have been merged to the same type. 8644 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 8645 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 8646 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 8647 !Context.hasSameType(EnumA->getIntegerType(), 8648 EnumB->getIntegerType())) 8649 return false; 8650 // Allow this only if the value is the same for both enumerators. 8651 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 8652 } 8653 } 8654 8655 // Nothing else is sufficiently similar. 8656 return false; 8657 } 8658 8659 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 8660 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 8661 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 8662 8663 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 8664 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 8665 << !M << (M ? M->getFullModuleName() : ""); 8666 8667 for (auto *E : Equiv) { 8668 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 8669 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 8670 << !M << (M ? M->getFullModuleName() : ""); 8671 } 8672 } 8673 8674 /// \brief Computes the best viable function (C++ 13.3.3) 8675 /// within an overload candidate set. 8676 /// 8677 /// \param Loc The location of the function name (or operator symbol) for 8678 /// which overload resolution occurs. 8679 /// 8680 /// \param Best If overload resolution was successful or found a deleted 8681 /// function, \p Best points to the candidate function found. 8682 /// 8683 /// \returns The result of overload resolution. 8684 OverloadingResult 8685 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8686 iterator &Best, 8687 bool UserDefinedConversion) { 8688 // Find the best viable function. 8689 Best = end(); 8690 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8691 if (Cand->Viable) 8692 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8693 UserDefinedConversion)) 8694 Best = Cand; 8695 } 8696 8697 // If we didn't find any viable functions, abort. 8698 if (Best == end()) 8699 return OR_No_Viable_Function; 8700 8701 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 8702 8703 // Make sure that this function is better than every other viable 8704 // function. If not, we have an ambiguity. 8705 for (iterator Cand = begin(); Cand != end(); ++Cand) { 8706 if (Cand->Viable && 8707 Cand != Best && 8708 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8709 UserDefinedConversion)) { 8710 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 8711 Cand->Function)) { 8712 EquivalentCands.push_back(Cand->Function); 8713 continue; 8714 } 8715 8716 Best = end(); 8717 return OR_Ambiguous; 8718 } 8719 } 8720 8721 // Best is the best viable function. 8722 if (Best->Function && 8723 (Best->Function->isDeleted() || 8724 S.isFunctionConsideredUnavailable(Best->Function))) 8725 return OR_Deleted; 8726 8727 if (!EquivalentCands.empty()) 8728 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 8729 EquivalentCands); 8730 8731 return OR_Success; 8732 } 8733 8734 namespace { 8735 8736 enum OverloadCandidateKind { 8737 oc_function, 8738 oc_method, 8739 oc_constructor, 8740 oc_function_template, 8741 oc_method_template, 8742 oc_constructor_template, 8743 oc_implicit_default_constructor, 8744 oc_implicit_copy_constructor, 8745 oc_implicit_move_constructor, 8746 oc_implicit_copy_assignment, 8747 oc_implicit_move_assignment, 8748 oc_implicit_inherited_constructor 8749 }; 8750 8751 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S, 8752 FunctionDecl *Fn, 8753 std::string &Description) { 8754 bool isTemplate = false; 8755 8756 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 8757 isTemplate = true; 8758 Description = S.getTemplateArgumentBindingsText( 8759 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 8760 } 8761 8762 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 8763 if (!Ctor->isImplicit()) 8764 return isTemplate ? oc_constructor_template : oc_constructor; 8765 8766 if (Ctor->getInheritedConstructor()) 8767 return oc_implicit_inherited_constructor; 8768 8769 if (Ctor->isDefaultConstructor()) 8770 return oc_implicit_default_constructor; 8771 8772 if (Ctor->isMoveConstructor()) 8773 return oc_implicit_move_constructor; 8774 8775 assert(Ctor->isCopyConstructor() && 8776 "unexpected sort of implicit constructor"); 8777 return oc_implicit_copy_constructor; 8778 } 8779 8780 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 8781 // This actually gets spelled 'candidate function' for now, but 8782 // it doesn't hurt to split it out. 8783 if (!Meth->isImplicit()) 8784 return isTemplate ? oc_method_template : oc_method; 8785 8786 if (Meth->isMoveAssignmentOperator()) 8787 return oc_implicit_move_assignment; 8788 8789 if (Meth->isCopyAssignmentOperator()) 8790 return oc_implicit_copy_assignment; 8791 8792 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 8793 return oc_method; 8794 } 8795 8796 return isTemplate ? oc_function_template : oc_function; 8797 } 8798 8799 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) { 8800 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn); 8801 if (!Ctor) return; 8802 8803 Ctor = Ctor->getInheritedConstructor(); 8804 if (!Ctor) return; 8805 8806 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor); 8807 } 8808 8809 } // end anonymous namespace 8810 8811 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 8812 const FunctionDecl *FD) { 8813 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 8814 bool AlwaysTrue; 8815 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 8816 return false; 8817 if (!AlwaysTrue) 8818 return false; 8819 } 8820 return true; 8821 } 8822 8823 /// \brief Returns true if we can take the address of the function. 8824 /// 8825 /// \param Complain - If true, we'll emit a diagnostic 8826 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 8827 /// we in overload resolution? 8828 /// \param Loc - The location of the statement we're complaining about. Ignored 8829 /// if we're not complaining, or if we're in overload resolution. 8830 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 8831 bool Complain, 8832 bool InOverloadResolution, 8833 SourceLocation Loc) { 8834 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 8835 if (Complain) { 8836 if (InOverloadResolution) 8837 S.Diag(FD->getLocStart(), 8838 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 8839 else 8840 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 8841 } 8842 return false; 8843 } 8844 8845 auto I = std::find_if(FD->param_begin(), FD->param_end(), 8846 std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>)); 8847 if (I == FD->param_end()) 8848 return true; 8849 8850 if (Complain) { 8851 // Add one to ParamNo because it's user-facing 8852 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 8853 if (InOverloadResolution) 8854 S.Diag(FD->getLocation(), 8855 diag::note_ovl_candidate_has_pass_object_size_params) 8856 << ParamNo; 8857 else 8858 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 8859 << FD << ParamNo; 8860 } 8861 return false; 8862 } 8863 8864 static bool checkAddressOfCandidateIsAvailable(Sema &S, 8865 const FunctionDecl *FD) { 8866 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 8867 /*InOverloadResolution=*/true, 8868 /*Loc=*/SourceLocation()); 8869 } 8870 8871 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 8872 bool Complain, 8873 SourceLocation Loc) { 8874 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 8875 /*InOverloadResolution=*/false, 8876 Loc); 8877 } 8878 8879 // Notes the location of an overload candidate. 8880 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType, 8881 bool TakingAddress) { 8882 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 8883 return; 8884 8885 std::string FnDesc; 8886 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc); 8887 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 8888 << (unsigned) K << FnDesc; 8889 8890 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 8891 Diag(Fn->getLocation(), PD); 8892 MaybeEmitInheritedConstructorNote(*this, Fn); 8893 } 8894 8895 // Notes the location of all overload candidates designated through 8896 // OverloadedExpr 8897 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 8898 bool TakingAddress) { 8899 assert(OverloadedExpr->getType() == Context.OverloadTy); 8900 8901 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 8902 OverloadExpr *OvlExpr = Ovl.Expression; 8903 8904 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 8905 IEnd = OvlExpr->decls_end(); 8906 I != IEnd; ++I) { 8907 if (FunctionTemplateDecl *FunTmpl = 8908 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 8909 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType, 8910 TakingAddress); 8911 } else if (FunctionDecl *Fun 8912 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 8913 NoteOverloadCandidate(Fun, DestType, TakingAddress); 8914 } 8915 } 8916 } 8917 8918 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 8919 /// "lead" diagnostic; it will be given two arguments, the source and 8920 /// target types of the conversion. 8921 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 8922 Sema &S, 8923 SourceLocation CaretLoc, 8924 const PartialDiagnostic &PDiag) const { 8925 S.Diag(CaretLoc, PDiag) 8926 << Ambiguous.getFromType() << Ambiguous.getToType(); 8927 // FIXME: The note limiting machinery is borrowed from 8928 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 8929 // refactoring here. 8930 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 8931 unsigned CandsShown = 0; 8932 AmbiguousConversionSequence::const_iterator I, E; 8933 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 8934 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 8935 break; 8936 ++CandsShown; 8937 S.NoteOverloadCandidate(*I); 8938 } 8939 if (I != E) 8940 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 8941 } 8942 8943 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 8944 unsigned I, bool TakingCandidateAddress) { 8945 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 8946 assert(Conv.isBad()); 8947 assert(Cand->Function && "for now, candidate must be a function"); 8948 FunctionDecl *Fn = Cand->Function; 8949 8950 // There's a conversion slot for the object argument if this is a 8951 // non-constructor method. Note that 'I' corresponds the 8952 // conversion-slot index. 8953 bool isObjectArgument = false; 8954 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 8955 if (I == 0) 8956 isObjectArgument = true; 8957 else 8958 I--; 8959 } 8960 8961 std::string FnDesc; 8962 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 8963 8964 Expr *FromExpr = Conv.Bad.FromExpr; 8965 QualType FromTy = Conv.Bad.getFromType(); 8966 QualType ToTy = Conv.Bad.getToType(); 8967 8968 if (FromTy == S.Context.OverloadTy) { 8969 assert(FromExpr && "overload set argument came from implicit argument?"); 8970 Expr *E = FromExpr->IgnoreParens(); 8971 if (isa<UnaryOperator>(E)) 8972 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 8973 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 8974 8975 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 8976 << (unsigned) FnKind << FnDesc 8977 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 8978 << ToTy << Name << I+1; 8979 MaybeEmitInheritedConstructorNote(S, Fn); 8980 return; 8981 } 8982 8983 // Do some hand-waving analysis to see if the non-viability is due 8984 // to a qualifier mismatch. 8985 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 8986 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 8987 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 8988 CToTy = RT->getPointeeType(); 8989 else { 8990 // TODO: detect and diagnose the full richness of const mismatches. 8991 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 8992 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) 8993 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType(); 8994 } 8995 8996 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 8997 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 8998 Qualifiers FromQs = CFromTy.getQualifiers(); 8999 Qualifiers ToQs = CToTy.getQualifiers(); 9000 9001 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9002 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9003 << (unsigned) FnKind << FnDesc 9004 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9005 << FromTy 9006 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 9007 << (unsigned) isObjectArgument << I+1; 9008 MaybeEmitInheritedConstructorNote(S, Fn); 9009 return; 9010 } 9011 9012 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9013 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9014 << (unsigned) FnKind << FnDesc 9015 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9016 << FromTy 9017 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9018 << (unsigned) isObjectArgument << I+1; 9019 MaybeEmitInheritedConstructorNote(S, Fn); 9020 return; 9021 } 9022 9023 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9024 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9025 << (unsigned) FnKind << FnDesc 9026 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9027 << FromTy 9028 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9029 << (unsigned) isObjectArgument << I+1; 9030 MaybeEmitInheritedConstructorNote(S, Fn); 9031 return; 9032 } 9033 9034 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9035 assert(CVR && "unexpected qualifiers mismatch"); 9036 9037 if (isObjectArgument) { 9038 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9039 << (unsigned) FnKind << FnDesc 9040 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9041 << FromTy << (CVR - 1); 9042 } else { 9043 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9044 << (unsigned) FnKind << FnDesc 9045 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9046 << FromTy << (CVR - 1) << I+1; 9047 } 9048 MaybeEmitInheritedConstructorNote(S, Fn); 9049 return; 9050 } 9051 9052 // Special diagnostic for failure to convert an initializer list, since 9053 // telling the user that it has type void is not useful. 9054 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9055 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9056 << (unsigned) FnKind << FnDesc 9057 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9058 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9059 MaybeEmitInheritedConstructorNote(S, Fn); 9060 return; 9061 } 9062 9063 // Diagnose references or pointers to incomplete types differently, 9064 // since it's far from impossible that the incompleteness triggered 9065 // the failure. 9066 QualType TempFromTy = FromTy.getNonReferenceType(); 9067 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9068 TempFromTy = PTy->getPointeeType(); 9069 if (TempFromTy->isIncompleteType()) { 9070 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9071 << (unsigned) FnKind << FnDesc 9072 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9073 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9074 MaybeEmitInheritedConstructorNote(S, Fn); 9075 return; 9076 } 9077 9078 // Diagnose base -> derived pointer conversions. 9079 unsigned BaseToDerivedConversion = 0; 9080 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9081 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9082 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9083 FromPtrTy->getPointeeType()) && 9084 !FromPtrTy->getPointeeType()->isIncompleteType() && 9085 !ToPtrTy->getPointeeType()->isIncompleteType() && 9086 S.IsDerivedFrom(ToPtrTy->getPointeeType(), 9087 FromPtrTy->getPointeeType())) 9088 BaseToDerivedConversion = 1; 9089 } 9090 } else if (const ObjCObjectPointerType *FromPtrTy 9091 = FromTy->getAs<ObjCObjectPointerType>()) { 9092 if (const ObjCObjectPointerType *ToPtrTy 9093 = ToTy->getAs<ObjCObjectPointerType>()) 9094 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9095 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9096 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9097 FromPtrTy->getPointeeType()) && 9098 FromIface->isSuperClassOf(ToIface)) 9099 BaseToDerivedConversion = 2; 9100 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9101 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9102 !FromTy->isIncompleteType() && 9103 !ToRefTy->getPointeeType()->isIncompleteType() && 9104 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) { 9105 BaseToDerivedConversion = 3; 9106 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9107 ToTy.getNonReferenceType().getCanonicalType() == 9108 FromTy.getNonReferenceType().getCanonicalType()) { 9109 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9110 << (unsigned) FnKind << FnDesc 9111 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9112 << (unsigned) isObjectArgument << I + 1; 9113 MaybeEmitInheritedConstructorNote(S, Fn); 9114 return; 9115 } 9116 } 9117 9118 if (BaseToDerivedConversion) { 9119 S.Diag(Fn->getLocation(), 9120 diag::note_ovl_candidate_bad_base_to_derived_conv) 9121 << (unsigned) FnKind << FnDesc 9122 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9123 << (BaseToDerivedConversion - 1) 9124 << FromTy << ToTy << I+1; 9125 MaybeEmitInheritedConstructorNote(S, Fn); 9126 return; 9127 } 9128 9129 if (isa<ObjCObjectPointerType>(CFromTy) && 9130 isa<PointerType>(CToTy)) { 9131 Qualifiers FromQs = CFromTy.getQualifiers(); 9132 Qualifiers ToQs = CToTy.getQualifiers(); 9133 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9134 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9135 << (unsigned) FnKind << FnDesc 9136 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9137 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9138 MaybeEmitInheritedConstructorNote(S, Fn); 9139 return; 9140 } 9141 } 9142 9143 if (TakingCandidateAddress && 9144 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9145 return; 9146 9147 // Emit the generic diagnostic and, optionally, add the hints to it. 9148 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9149 FDiag << (unsigned) FnKind << FnDesc 9150 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9151 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 9152 << (unsigned) (Cand->Fix.Kind); 9153 9154 // If we can fix the conversion, suggest the FixIts. 9155 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9156 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9157 FDiag << *HI; 9158 S.Diag(Fn->getLocation(), FDiag); 9159 9160 MaybeEmitInheritedConstructorNote(S, Fn); 9161 } 9162 9163 /// Additional arity mismatch diagnosis specific to a function overload 9164 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9165 /// over a candidate in any candidate set. 9166 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9167 unsigned NumArgs) { 9168 FunctionDecl *Fn = Cand->Function; 9169 unsigned MinParams = Fn->getMinRequiredArguments(); 9170 9171 // With invalid overloaded operators, it's possible that we think we 9172 // have an arity mismatch when in fact it looks like we have the 9173 // right number of arguments, because only overloaded operators have 9174 // the weird behavior of overloading member and non-member functions. 9175 // Just don't report anything. 9176 if (Fn->isInvalidDecl() && 9177 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9178 return true; 9179 9180 if (NumArgs < MinParams) { 9181 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9182 (Cand->FailureKind == ovl_fail_bad_deduction && 9183 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9184 } else { 9185 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9186 (Cand->FailureKind == ovl_fail_bad_deduction && 9187 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9188 } 9189 9190 return false; 9191 } 9192 9193 /// General arity mismatch diagnosis over a candidate in a candidate set. 9194 static void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) { 9195 assert(isa<FunctionDecl>(D) && 9196 "The templated declaration should at least be a function" 9197 " when diagnosing bad template argument deduction due to too many" 9198 " or too few arguments"); 9199 9200 FunctionDecl *Fn = cast<FunctionDecl>(D); 9201 9202 // TODO: treat calls to a missing default constructor as a special case 9203 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9204 unsigned MinParams = Fn->getMinRequiredArguments(); 9205 9206 // at least / at most / exactly 9207 unsigned mode, modeCount; 9208 if (NumFormalArgs < MinParams) { 9209 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9210 FnTy->isTemplateVariadic()) 9211 mode = 0; // "at least" 9212 else 9213 mode = 2; // "exactly" 9214 modeCount = MinParams; 9215 } else { 9216 if (MinParams != FnTy->getNumParams()) 9217 mode = 1; // "at most" 9218 else 9219 mode = 2; // "exactly" 9220 modeCount = FnTy->getNumParams(); 9221 } 9222 9223 std::string Description; 9224 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description); 9225 9226 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9227 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9228 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9229 << mode << Fn->getParamDecl(0) << NumFormalArgs; 9230 else 9231 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9232 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9233 << mode << modeCount << NumFormalArgs; 9234 MaybeEmitInheritedConstructorNote(S, Fn); 9235 } 9236 9237 /// Arity mismatch diagnosis specific to a function overload candidate. 9238 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9239 unsigned NumFormalArgs) { 9240 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9241 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs); 9242 } 9243 9244 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9245 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated)) 9246 return FD->getDescribedFunctionTemplate(); 9247 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated)) 9248 return RD->getDescribedClassTemplate(); 9249 9250 llvm_unreachable("Unsupported: Getting the described template declaration" 9251 " for bad deduction diagnosis"); 9252 } 9253 9254 /// Diagnose a failed template-argument deduction. 9255 static void DiagnoseBadDeduction(Sema &S, Decl *Templated, 9256 DeductionFailureInfo &DeductionFailure, 9257 unsigned NumArgs, 9258 bool TakingCandidateAddress) { 9259 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9260 NamedDecl *ParamD; 9261 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9262 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9263 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9264 switch (DeductionFailure.Result) { 9265 case Sema::TDK_Success: 9266 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9267 9268 case Sema::TDK_Incomplete: { 9269 assert(ParamD && "no parameter found for incomplete deduction result"); 9270 S.Diag(Templated->getLocation(), 9271 diag::note_ovl_candidate_incomplete_deduction) 9272 << ParamD->getDeclName(); 9273 MaybeEmitInheritedConstructorNote(S, Templated); 9274 return; 9275 } 9276 9277 case Sema::TDK_Underqualified: { 9278 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9279 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9280 9281 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9282 9283 // Param will have been canonicalized, but it should just be a 9284 // qualified version of ParamD, so move the qualifiers to that. 9285 QualifierCollector Qs; 9286 Qs.strip(Param); 9287 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9288 assert(S.Context.hasSameType(Param, NonCanonParam)); 9289 9290 // Arg has also been canonicalized, but there's nothing we can do 9291 // about that. It also doesn't matter as much, because it won't 9292 // have any template parameters in it (because deduction isn't 9293 // done on dependent types). 9294 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9295 9296 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9297 << ParamD->getDeclName() << Arg << NonCanonParam; 9298 MaybeEmitInheritedConstructorNote(S, Templated); 9299 return; 9300 } 9301 9302 case Sema::TDK_Inconsistent: { 9303 assert(ParamD && "no parameter found for inconsistent deduction result"); 9304 int which = 0; 9305 if (isa<TemplateTypeParmDecl>(ParamD)) 9306 which = 0; 9307 else if (isa<NonTypeTemplateParmDecl>(ParamD)) 9308 which = 1; 9309 else { 9310 which = 2; 9311 } 9312 9313 S.Diag(Templated->getLocation(), 9314 diag::note_ovl_candidate_inconsistent_deduction) 9315 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 9316 << *DeductionFailure.getSecondArg(); 9317 MaybeEmitInheritedConstructorNote(S, Templated); 9318 return; 9319 } 9320 9321 case Sema::TDK_InvalidExplicitArguments: 9322 assert(ParamD && "no parameter found for invalid explicit arguments"); 9323 if (ParamD->getDeclName()) 9324 S.Diag(Templated->getLocation(), 9325 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9326 << ParamD->getDeclName(); 9327 else { 9328 int index = 0; 9329 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9330 index = TTP->getIndex(); 9331 else if (NonTypeTemplateParmDecl *NTTP 9332 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9333 index = NTTP->getIndex(); 9334 else 9335 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9336 S.Diag(Templated->getLocation(), 9337 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9338 << (index + 1); 9339 } 9340 MaybeEmitInheritedConstructorNote(S, Templated); 9341 return; 9342 9343 case Sema::TDK_TooManyArguments: 9344 case Sema::TDK_TooFewArguments: 9345 DiagnoseArityMismatch(S, Templated, NumArgs); 9346 return; 9347 9348 case Sema::TDK_InstantiationDepth: 9349 S.Diag(Templated->getLocation(), 9350 diag::note_ovl_candidate_instantiation_depth); 9351 MaybeEmitInheritedConstructorNote(S, Templated); 9352 return; 9353 9354 case Sema::TDK_SubstitutionFailure: { 9355 // Format the template argument list into the argument string. 9356 SmallString<128> TemplateArgString; 9357 if (TemplateArgumentList *Args = 9358 DeductionFailure.getTemplateArgumentList()) { 9359 TemplateArgString = " "; 9360 TemplateArgString += S.getTemplateArgumentBindingsText( 9361 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9362 } 9363 9364 // If this candidate was disabled by enable_if, say so. 9365 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9366 if (PDiag && PDiag->second.getDiagID() == 9367 diag::err_typename_nested_not_found_enable_if) { 9368 // FIXME: Use the source range of the condition, and the fully-qualified 9369 // name of the enable_if template. These are both present in PDiag. 9370 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9371 << "'enable_if'" << TemplateArgString; 9372 return; 9373 } 9374 9375 // Format the SFINAE diagnostic into the argument string. 9376 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9377 // formatted message in another diagnostic. 9378 SmallString<128> SFINAEArgString; 9379 SourceRange R; 9380 if (PDiag) { 9381 SFINAEArgString = ": "; 9382 R = SourceRange(PDiag->first, PDiag->first); 9383 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9384 } 9385 9386 S.Diag(Templated->getLocation(), 9387 diag::note_ovl_candidate_substitution_failure) 9388 << TemplateArgString << SFINAEArgString << R; 9389 MaybeEmitInheritedConstructorNote(S, Templated); 9390 return; 9391 } 9392 9393 case Sema::TDK_FailedOverloadResolution: { 9394 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr()); 9395 S.Diag(Templated->getLocation(), 9396 diag::note_ovl_candidate_failed_overload_resolution) 9397 << R.Expression->getName(); 9398 return; 9399 } 9400 9401 case Sema::TDK_NonDeducedMismatch: { 9402 // FIXME: Provide a source location to indicate what we couldn't match. 9403 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9404 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9405 if (FirstTA.getKind() == TemplateArgument::Template && 9406 SecondTA.getKind() == TemplateArgument::Template) { 9407 TemplateName FirstTN = FirstTA.getAsTemplate(); 9408 TemplateName SecondTN = SecondTA.getAsTemplate(); 9409 if (FirstTN.getKind() == TemplateName::Template && 9410 SecondTN.getKind() == TemplateName::Template) { 9411 if (FirstTN.getAsTemplateDecl()->getName() == 9412 SecondTN.getAsTemplateDecl()->getName()) { 9413 // FIXME: This fixes a bad diagnostic where both templates are named 9414 // the same. This particular case is a bit difficult since: 9415 // 1) It is passed as a string to the diagnostic printer. 9416 // 2) The diagnostic printer only attempts to find a better 9417 // name for types, not decls. 9418 // Ideally, this should folded into the diagnostic printer. 9419 S.Diag(Templated->getLocation(), 9420 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 9421 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 9422 return; 9423 } 9424 } 9425 } 9426 9427 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 9428 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 9429 return; 9430 9431 // FIXME: For generic lambda parameters, check if the function is a lambda 9432 // call operator, and if so, emit a prettier and more informative 9433 // diagnostic that mentions 'auto' and lambda in addition to 9434 // (or instead of?) the canonical template type parameters. 9435 S.Diag(Templated->getLocation(), 9436 diag::note_ovl_candidate_non_deduced_mismatch) 9437 << FirstTA << SecondTA; 9438 return; 9439 } 9440 // TODO: diagnose these individually, then kill off 9441 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9442 case Sema::TDK_MiscellaneousDeductionFailure: 9443 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9444 MaybeEmitInheritedConstructorNote(S, Templated); 9445 return; 9446 } 9447 } 9448 9449 /// Diagnose a failed template-argument deduction, for function calls. 9450 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 9451 unsigned NumArgs, 9452 bool TakingCandidateAddress) { 9453 unsigned TDK = Cand->DeductionFailure.Result; 9454 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9455 if (CheckArityMismatch(S, Cand, NumArgs)) 9456 return; 9457 } 9458 DiagnoseBadDeduction(S, Cand->Function, // pattern 9459 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 9460 } 9461 9462 /// CUDA: diagnose an invalid call across targets. 9463 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9464 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 9465 FunctionDecl *Callee = Cand->Function; 9466 9467 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 9468 CalleeTarget = S.IdentifyCUDATarget(Callee); 9469 9470 std::string FnDesc; 9471 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc); 9472 9473 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 9474 << (unsigned)FnKind << CalleeTarget << CallerTarget; 9475 9476 // This could be an implicit constructor for which we could not infer the 9477 // target due to a collsion. Diagnose that case. 9478 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 9479 if (Meth != nullptr && Meth->isImplicit()) { 9480 CXXRecordDecl *ParentClass = Meth->getParent(); 9481 Sema::CXXSpecialMember CSM; 9482 9483 switch (FnKind) { 9484 default: 9485 return; 9486 case oc_implicit_default_constructor: 9487 CSM = Sema::CXXDefaultConstructor; 9488 break; 9489 case oc_implicit_copy_constructor: 9490 CSM = Sema::CXXCopyConstructor; 9491 break; 9492 case oc_implicit_move_constructor: 9493 CSM = Sema::CXXMoveConstructor; 9494 break; 9495 case oc_implicit_copy_assignment: 9496 CSM = Sema::CXXCopyAssignment; 9497 break; 9498 case oc_implicit_move_assignment: 9499 CSM = Sema::CXXMoveAssignment; 9500 break; 9501 }; 9502 9503 bool ConstRHS = false; 9504 if (Meth->getNumParams()) { 9505 if (const ReferenceType *RT = 9506 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 9507 ConstRHS = RT->getPointeeType().isConstQualified(); 9508 } 9509 } 9510 9511 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 9512 /* ConstRHS */ ConstRHS, 9513 /* Diagnose */ true); 9514 } 9515 } 9516 9517 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 9518 FunctionDecl *Callee = Cand->Function; 9519 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 9520 9521 S.Diag(Callee->getLocation(), 9522 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9523 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9524 } 9525 9526 /// Generates a 'note' diagnostic for an overload candidate. We've 9527 /// already generated a primary error at the call site. 9528 /// 9529 /// It really does need to be a single diagnostic with its caret 9530 /// pointed at the candidate declaration. Yes, this creates some 9531 /// major challenges of technical writing. Yes, this makes pointing 9532 /// out problems with specific arguments quite awkward. It's still 9533 /// better than generating twenty screens of text for every failed 9534 /// overload. 9535 /// 9536 /// It would be great to be able to express per-candidate problems 9537 /// more richly for those diagnostic clients that cared, but we'd 9538 /// still have to be just as careful with the default diagnostics. 9539 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9540 unsigned NumArgs, 9541 bool TakingCandidateAddress) { 9542 FunctionDecl *Fn = Cand->Function; 9543 9544 // Note deleted candidates, but only if they're viable. 9545 if (Cand->Viable && (Fn->isDeleted() || 9546 S.isFunctionConsideredUnavailable(Fn))) { 9547 std::string FnDesc; 9548 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc); 9549 9550 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9551 << FnKind << FnDesc 9552 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9553 MaybeEmitInheritedConstructorNote(S, Fn); 9554 return; 9555 } 9556 9557 // We don't really have anything else to say about viable candidates. 9558 if (Cand->Viable) { 9559 S.NoteOverloadCandidate(Fn); 9560 return; 9561 } 9562 9563 switch (Cand->FailureKind) { 9564 case ovl_fail_too_many_arguments: 9565 case ovl_fail_too_few_arguments: 9566 return DiagnoseArityMismatch(S, Cand, NumArgs); 9567 9568 case ovl_fail_bad_deduction: 9569 return DiagnoseBadDeduction(S, Cand, NumArgs, TakingCandidateAddress); 9570 9571 case ovl_fail_illegal_constructor: { 9572 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 9573 << (Fn->getPrimaryTemplate() ? 1 : 0); 9574 MaybeEmitInheritedConstructorNote(S, Fn); 9575 return; 9576 } 9577 9578 case ovl_fail_trivial_conversion: 9579 case ovl_fail_bad_final_conversion: 9580 case ovl_fail_final_conversion_not_exact: 9581 return S.NoteOverloadCandidate(Fn); 9582 9583 case ovl_fail_bad_conversion: { 9584 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9585 for (unsigned N = Cand->NumConversions; I != N; ++I) 9586 if (Cand->Conversions[I].isBad()) 9587 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 9588 9589 // FIXME: this currently happens when we're called from SemaInit 9590 // when user-conversion overload fails. Figure out how to handle 9591 // those conditions and diagnose them well. 9592 return S.NoteOverloadCandidate(Fn); 9593 } 9594 9595 case ovl_fail_bad_target: 9596 return DiagnoseBadTarget(S, Cand); 9597 9598 case ovl_fail_enable_if: 9599 return DiagnoseFailedEnableIfAttr(S, Cand); 9600 } 9601 } 9602 9603 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9604 // Desugar the type of the surrogate down to a function type, 9605 // retaining as many typedefs as possible while still showing 9606 // the function type (and, therefore, its parameter types). 9607 QualType FnType = Cand->Surrogate->getConversionType(); 9608 bool isLValueReference = false; 9609 bool isRValueReference = false; 9610 bool isPointer = false; 9611 if (const LValueReferenceType *FnTypeRef = 9612 FnType->getAs<LValueReferenceType>()) { 9613 FnType = FnTypeRef->getPointeeType(); 9614 isLValueReference = true; 9615 } else if (const RValueReferenceType *FnTypeRef = 9616 FnType->getAs<RValueReferenceType>()) { 9617 FnType = FnTypeRef->getPointeeType(); 9618 isRValueReference = true; 9619 } 9620 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9621 FnType = FnTypePtr->getPointeeType(); 9622 isPointer = true; 9623 } 9624 // Desugar down to a function type. 9625 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9626 // Reconstruct the pointer/reference as appropriate. 9627 if (isPointer) FnType = S.Context.getPointerType(FnType); 9628 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9629 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9630 9631 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9632 << FnType; 9633 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate); 9634 } 9635 9636 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 9637 SourceLocation OpLoc, 9638 OverloadCandidate *Cand) { 9639 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9640 std::string TypeStr("operator"); 9641 TypeStr += Opc; 9642 TypeStr += "("; 9643 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9644 if (Cand->NumConversions == 1) { 9645 TypeStr += ")"; 9646 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9647 } else { 9648 TypeStr += ", "; 9649 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9650 TypeStr += ")"; 9651 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9652 } 9653 } 9654 9655 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9656 OverloadCandidate *Cand) { 9657 unsigned NoOperands = Cand->NumConversions; 9658 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9659 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9660 if (ICS.isBad()) break; // all meaningless after first invalid 9661 if (!ICS.isAmbiguous()) continue; 9662 9663 ICS.DiagnoseAmbiguousConversion(S, OpLoc, 9664 S.PDiag(diag::note_ambiguous_type_conversion)); 9665 } 9666 } 9667 9668 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9669 if (Cand->Function) 9670 return Cand->Function->getLocation(); 9671 if (Cand->IsSurrogate) 9672 return Cand->Surrogate->getLocation(); 9673 return SourceLocation(); 9674 } 9675 9676 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 9677 switch ((Sema::TemplateDeductionResult)DFI.Result) { 9678 case Sema::TDK_Success: 9679 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9680 9681 case Sema::TDK_Invalid: 9682 case Sema::TDK_Incomplete: 9683 return 1; 9684 9685 case Sema::TDK_Underqualified: 9686 case Sema::TDK_Inconsistent: 9687 return 2; 9688 9689 case Sema::TDK_SubstitutionFailure: 9690 case Sema::TDK_NonDeducedMismatch: 9691 case Sema::TDK_MiscellaneousDeductionFailure: 9692 return 3; 9693 9694 case Sema::TDK_InstantiationDepth: 9695 case Sema::TDK_FailedOverloadResolution: 9696 return 4; 9697 9698 case Sema::TDK_InvalidExplicitArguments: 9699 return 5; 9700 9701 case Sema::TDK_TooManyArguments: 9702 case Sema::TDK_TooFewArguments: 9703 return 6; 9704 } 9705 llvm_unreachable("Unhandled deduction result"); 9706 } 9707 9708 namespace { 9709 struct CompareOverloadCandidatesForDisplay { 9710 Sema &S; 9711 size_t NumArgs; 9712 9713 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs) 9714 : S(S), NumArgs(nArgs) {} 9715 9716 bool operator()(const OverloadCandidate *L, 9717 const OverloadCandidate *R) { 9718 // Fast-path this check. 9719 if (L == R) return false; 9720 9721 // Order first by viability. 9722 if (L->Viable) { 9723 if (!R->Viable) return true; 9724 9725 // TODO: introduce a tri-valued comparison for overload 9726 // candidates. Would be more worthwhile if we had a sort 9727 // that could exploit it. 9728 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 9729 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 9730 } else if (R->Viable) 9731 return false; 9732 9733 assert(L->Viable == R->Viable); 9734 9735 // Criteria by which we can sort non-viable candidates: 9736 if (!L->Viable) { 9737 // 1. Arity mismatches come after other candidates. 9738 if (L->FailureKind == ovl_fail_too_many_arguments || 9739 L->FailureKind == ovl_fail_too_few_arguments) { 9740 if (R->FailureKind == ovl_fail_too_many_arguments || 9741 R->FailureKind == ovl_fail_too_few_arguments) { 9742 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 9743 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 9744 if (LDist == RDist) { 9745 if (L->FailureKind == R->FailureKind) 9746 // Sort non-surrogates before surrogates. 9747 return !L->IsSurrogate && R->IsSurrogate; 9748 // Sort candidates requiring fewer parameters than there were 9749 // arguments given after candidates requiring more parameters 9750 // than there were arguments given. 9751 return L->FailureKind == ovl_fail_too_many_arguments; 9752 } 9753 return LDist < RDist; 9754 } 9755 return false; 9756 } 9757 if (R->FailureKind == ovl_fail_too_many_arguments || 9758 R->FailureKind == ovl_fail_too_few_arguments) 9759 return true; 9760 9761 // 2. Bad conversions come first and are ordered by the number 9762 // of bad conversions and quality of good conversions. 9763 if (L->FailureKind == ovl_fail_bad_conversion) { 9764 if (R->FailureKind != ovl_fail_bad_conversion) 9765 return true; 9766 9767 // The conversion that can be fixed with a smaller number of changes, 9768 // comes first. 9769 unsigned numLFixes = L->Fix.NumConversionsFixed; 9770 unsigned numRFixes = R->Fix.NumConversionsFixed; 9771 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 9772 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 9773 if (numLFixes != numRFixes) { 9774 return numLFixes < numRFixes; 9775 } 9776 9777 // If there's any ordering between the defined conversions... 9778 // FIXME: this might not be transitive. 9779 assert(L->NumConversions == R->NumConversions); 9780 9781 int leftBetter = 0; 9782 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 9783 for (unsigned E = L->NumConversions; I != E; ++I) { 9784 switch (CompareImplicitConversionSequences(S, 9785 L->Conversions[I], 9786 R->Conversions[I])) { 9787 case ImplicitConversionSequence::Better: 9788 leftBetter++; 9789 break; 9790 9791 case ImplicitConversionSequence::Worse: 9792 leftBetter--; 9793 break; 9794 9795 case ImplicitConversionSequence::Indistinguishable: 9796 break; 9797 } 9798 } 9799 if (leftBetter > 0) return true; 9800 if (leftBetter < 0) return false; 9801 9802 } else if (R->FailureKind == ovl_fail_bad_conversion) 9803 return false; 9804 9805 if (L->FailureKind == ovl_fail_bad_deduction) { 9806 if (R->FailureKind != ovl_fail_bad_deduction) 9807 return true; 9808 9809 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 9810 return RankDeductionFailure(L->DeductionFailure) 9811 < RankDeductionFailure(R->DeductionFailure); 9812 } else if (R->FailureKind == ovl_fail_bad_deduction) 9813 return false; 9814 9815 // TODO: others? 9816 } 9817 9818 // Sort everything else by location. 9819 SourceLocation LLoc = GetLocationForCandidate(L); 9820 SourceLocation RLoc = GetLocationForCandidate(R); 9821 9822 // Put candidates without locations (e.g. builtins) at the end. 9823 if (LLoc.isInvalid()) return false; 9824 if (RLoc.isInvalid()) return true; 9825 9826 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 9827 } 9828 }; 9829 } 9830 9831 /// CompleteNonViableCandidate - Normally, overload resolution only 9832 /// computes up to the first. Produces the FixIt set if possible. 9833 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 9834 ArrayRef<Expr *> Args) { 9835 assert(!Cand->Viable); 9836 9837 // Don't do anything on failures other than bad conversion. 9838 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 9839 9840 // We only want the FixIts if all the arguments can be corrected. 9841 bool Unfixable = false; 9842 // Use a implicit copy initialization to check conversion fixes. 9843 Cand->Fix.setConversionChecker(TryCopyInitialization); 9844 9845 // Skip forward to the first bad conversion. 9846 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 9847 unsigned ConvCount = Cand->NumConversions; 9848 while (true) { 9849 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 9850 ConvIdx++; 9851 if (Cand->Conversions[ConvIdx - 1].isBad()) { 9852 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 9853 break; 9854 } 9855 } 9856 9857 if (ConvIdx == ConvCount) 9858 return; 9859 9860 assert(!Cand->Conversions[ConvIdx].isInitialized() && 9861 "remaining conversion is initialized?"); 9862 9863 // FIXME: this should probably be preserved from the overload 9864 // operation somehow. 9865 bool SuppressUserConversions = false; 9866 9867 const FunctionProtoType* Proto; 9868 unsigned ArgIdx = ConvIdx; 9869 9870 if (Cand->IsSurrogate) { 9871 QualType ConvType 9872 = Cand->Surrogate->getConversionType().getNonReferenceType(); 9873 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 9874 ConvType = ConvPtrType->getPointeeType(); 9875 Proto = ConvType->getAs<FunctionProtoType>(); 9876 ArgIdx--; 9877 } else if (Cand->Function) { 9878 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 9879 if (isa<CXXMethodDecl>(Cand->Function) && 9880 !isa<CXXConstructorDecl>(Cand->Function)) 9881 ArgIdx--; 9882 } else { 9883 // Builtin binary operator with a bad first conversion. 9884 assert(ConvCount <= 3); 9885 for (; ConvIdx != ConvCount; ++ConvIdx) 9886 Cand->Conversions[ConvIdx] 9887 = TryCopyInitialization(S, Args[ConvIdx], 9888 Cand->BuiltinTypes.ParamTypes[ConvIdx], 9889 SuppressUserConversions, 9890 /*InOverloadResolution*/ true, 9891 /*AllowObjCWritebackConversion=*/ 9892 S.getLangOpts().ObjCAutoRefCount); 9893 return; 9894 } 9895 9896 // Fill in the rest of the conversions. 9897 unsigned NumParams = Proto->getNumParams(); 9898 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 9899 if (ArgIdx < NumParams) { 9900 Cand->Conversions[ConvIdx] = TryCopyInitialization( 9901 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 9902 /*InOverloadResolution=*/true, 9903 /*AllowObjCWritebackConversion=*/ 9904 S.getLangOpts().ObjCAutoRefCount); 9905 // Store the FixIt in the candidate if it exists. 9906 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 9907 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 9908 } 9909 else 9910 Cand->Conversions[ConvIdx].setEllipsis(); 9911 } 9912 } 9913 9914 /// PrintOverloadCandidates - When overload resolution fails, prints 9915 /// diagnostic messages containing the candidates in the candidate 9916 /// set. 9917 void OverloadCandidateSet::NoteCandidates(Sema &S, 9918 OverloadCandidateDisplayKind OCD, 9919 ArrayRef<Expr *> Args, 9920 StringRef Opc, 9921 SourceLocation OpLoc) { 9922 // Sort the candidates by viability and position. Sorting directly would 9923 // be prohibitive, so we make a set of pointers and sort those. 9924 SmallVector<OverloadCandidate*, 32> Cands; 9925 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 9926 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 9927 if (Cand->Viable) 9928 Cands.push_back(Cand); 9929 else if (OCD == OCD_AllCandidates) { 9930 CompleteNonViableCandidate(S, Cand, Args); 9931 if (Cand->Function || Cand->IsSurrogate) 9932 Cands.push_back(Cand); 9933 // Otherwise, this a non-viable builtin candidate. We do not, in general, 9934 // want to list every possible builtin candidate. 9935 } 9936 } 9937 9938 std::sort(Cands.begin(), Cands.end(), 9939 CompareOverloadCandidatesForDisplay(S, Args.size())); 9940 9941 bool ReportedAmbiguousConversions = false; 9942 9943 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 9944 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9945 unsigned CandsShown = 0; 9946 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 9947 OverloadCandidate *Cand = *I; 9948 9949 // Set an arbitrary limit on the number of candidate functions we'll spam 9950 // the user with. FIXME: This limit should depend on details of the 9951 // candidate list. 9952 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 9953 break; 9954 } 9955 ++CandsShown; 9956 9957 if (Cand->Function) 9958 NoteFunctionCandidate(S, Cand, Args.size(), 9959 /*TakingCandidateAddress=*/false); 9960 else if (Cand->IsSurrogate) 9961 NoteSurrogateCandidate(S, Cand); 9962 else { 9963 assert(Cand->Viable && 9964 "Non-viable built-in candidates are not added to Cands."); 9965 // Generally we only see ambiguities including viable builtin 9966 // operators if overload resolution got screwed up by an 9967 // ambiguous user-defined conversion. 9968 // 9969 // FIXME: It's quite possible for different conversions to see 9970 // different ambiguities, though. 9971 if (!ReportedAmbiguousConversions) { 9972 NoteAmbiguousUserConversions(S, OpLoc, Cand); 9973 ReportedAmbiguousConversions = true; 9974 } 9975 9976 // If this is a viable builtin, print it. 9977 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 9978 } 9979 } 9980 9981 if (I != E) 9982 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 9983 } 9984 9985 static SourceLocation 9986 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 9987 return Cand->Specialization ? Cand->Specialization->getLocation() 9988 : SourceLocation(); 9989 } 9990 9991 namespace { 9992 struct CompareTemplateSpecCandidatesForDisplay { 9993 Sema &S; 9994 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 9995 9996 bool operator()(const TemplateSpecCandidate *L, 9997 const TemplateSpecCandidate *R) { 9998 // Fast-path this check. 9999 if (L == R) 10000 return false; 10001 10002 // Assuming that both candidates are not matches... 10003 10004 // Sort by the ranking of deduction failures. 10005 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10006 return RankDeductionFailure(L->DeductionFailure) < 10007 RankDeductionFailure(R->DeductionFailure); 10008 10009 // Sort everything else by location. 10010 SourceLocation LLoc = GetLocationForCandidate(L); 10011 SourceLocation RLoc = GetLocationForCandidate(R); 10012 10013 // Put candidates without locations (e.g. builtins) at the end. 10014 if (LLoc.isInvalid()) 10015 return false; 10016 if (RLoc.isInvalid()) 10017 return true; 10018 10019 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10020 } 10021 }; 10022 } 10023 10024 /// Diagnose a template argument deduction failure. 10025 /// We are treating these failures as overload failures due to bad 10026 /// deductions. 10027 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10028 bool ForTakingAddress) { 10029 DiagnoseBadDeduction(S, Specialization, // pattern 10030 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10031 } 10032 10033 void TemplateSpecCandidateSet::destroyCandidates() { 10034 for (iterator i = begin(), e = end(); i != e; ++i) { 10035 i->DeductionFailure.Destroy(); 10036 } 10037 } 10038 10039 void TemplateSpecCandidateSet::clear() { 10040 destroyCandidates(); 10041 Candidates.clear(); 10042 } 10043 10044 /// NoteCandidates - When no template specialization match is found, prints 10045 /// diagnostic messages containing the non-matching specializations that form 10046 /// the candidate set. 10047 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10048 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10049 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10050 // Sort the candidates by position (assuming no candidate is a match). 10051 // Sorting directly would be prohibitive, so we make a set of pointers 10052 // and sort those. 10053 SmallVector<TemplateSpecCandidate *, 32> Cands; 10054 Cands.reserve(size()); 10055 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10056 if (Cand->Specialization) 10057 Cands.push_back(Cand); 10058 // Otherwise, this is a non-matching builtin candidate. We do not, 10059 // in general, want to list every possible builtin candidate. 10060 } 10061 10062 std::sort(Cands.begin(), Cands.end(), 10063 CompareTemplateSpecCandidatesForDisplay(S)); 10064 10065 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10066 // for generalization purposes (?). 10067 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10068 10069 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10070 unsigned CandsShown = 0; 10071 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10072 TemplateSpecCandidate *Cand = *I; 10073 10074 // Set an arbitrary limit on the number of candidates we'll spam 10075 // the user with. FIXME: This limit should depend on details of the 10076 // candidate list. 10077 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10078 break; 10079 ++CandsShown; 10080 10081 assert(Cand->Specialization && 10082 "Non-matching built-in candidates are not added to Cands."); 10083 Cand->NoteDeductionFailure(S, ForTakingAddress); 10084 } 10085 10086 if (I != E) 10087 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10088 } 10089 10090 // [PossiblyAFunctionType] --> [Return] 10091 // NonFunctionType --> NonFunctionType 10092 // R (A) --> R(A) 10093 // R (*)(A) --> R (A) 10094 // R (&)(A) --> R (A) 10095 // R (S::*)(A) --> R (A) 10096 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10097 QualType Ret = PossiblyAFunctionType; 10098 if (const PointerType *ToTypePtr = 10099 PossiblyAFunctionType->getAs<PointerType>()) 10100 Ret = ToTypePtr->getPointeeType(); 10101 else if (const ReferenceType *ToTypeRef = 10102 PossiblyAFunctionType->getAs<ReferenceType>()) 10103 Ret = ToTypeRef->getPointeeType(); 10104 else if (const MemberPointerType *MemTypePtr = 10105 PossiblyAFunctionType->getAs<MemberPointerType>()) 10106 Ret = MemTypePtr->getPointeeType(); 10107 Ret = 10108 Context.getCanonicalType(Ret).getUnqualifiedType(); 10109 return Ret; 10110 } 10111 10112 namespace { 10113 // A helper class to help with address of function resolution 10114 // - allows us to avoid passing around all those ugly parameters 10115 class AddressOfFunctionResolver { 10116 Sema& S; 10117 Expr* SourceExpr; 10118 const QualType& TargetType; 10119 QualType TargetFunctionType; // Extracted function type from target type 10120 10121 bool Complain; 10122 //DeclAccessPair& ResultFunctionAccessPair; 10123 ASTContext& Context; 10124 10125 bool TargetTypeIsNonStaticMemberFunction; 10126 bool FoundNonTemplateFunction; 10127 bool StaticMemberFunctionFromBoundPointer; 10128 bool HasComplained; 10129 10130 OverloadExpr::FindResult OvlExprInfo; 10131 OverloadExpr *OvlExpr; 10132 TemplateArgumentListInfo OvlExplicitTemplateArgs; 10133 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 10134 TemplateSpecCandidateSet FailedCandidates; 10135 10136 public: 10137 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 10138 const QualType &TargetType, bool Complain) 10139 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 10140 Complain(Complain), Context(S.getASTContext()), 10141 TargetTypeIsNonStaticMemberFunction( 10142 !!TargetType->getAs<MemberPointerType>()), 10143 FoundNonTemplateFunction(false), 10144 StaticMemberFunctionFromBoundPointer(false), 10145 HasComplained(false), 10146 OvlExprInfo(OverloadExpr::find(SourceExpr)), 10147 OvlExpr(OvlExprInfo.Expression), 10148 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 10149 ExtractUnqualifiedFunctionTypeFromTargetType(); 10150 10151 if (TargetFunctionType->isFunctionType()) { 10152 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 10153 if (!UME->isImplicitAccess() && 10154 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 10155 StaticMemberFunctionFromBoundPointer = true; 10156 } else if (OvlExpr->hasExplicitTemplateArgs()) { 10157 DeclAccessPair dap; 10158 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 10159 OvlExpr, false, &dap)) { 10160 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 10161 if (!Method->isStatic()) { 10162 // If the target type is a non-function type and the function found 10163 // is a non-static member function, pretend as if that was the 10164 // target, it's the only possible type to end up with. 10165 TargetTypeIsNonStaticMemberFunction = true; 10166 10167 // And skip adding the function if its not in the proper form. 10168 // We'll diagnose this due to an empty set of functions. 10169 if (!OvlExprInfo.HasFormOfMemberPointer) 10170 return; 10171 } 10172 10173 Matches.push_back(std::make_pair(dap, Fn)); 10174 } 10175 return; 10176 } 10177 10178 if (OvlExpr->hasExplicitTemplateArgs()) 10179 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs); 10180 10181 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 10182 // C++ [over.over]p4: 10183 // If more than one function is selected, [...] 10184 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 10185 if (FoundNonTemplateFunction) 10186 EliminateAllTemplateMatches(); 10187 else 10188 EliminateAllExceptMostSpecializedTemplate(); 10189 } 10190 } 10191 10192 if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads && 10193 Matches.size() > 1) 10194 EliminateSuboptimalCudaMatches(); 10195 } 10196 10197 bool hasComplained() const { return HasComplained; } 10198 10199 private: 10200 // Is A considered a better overload candidate for the desired type than B? 10201 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 10202 return hasBetterEnableIfAttrs(S, A, B); 10203 } 10204 10205 // Returns true if we've eliminated any (read: all but one) candidates, false 10206 // otherwise. 10207 bool eliminiateSuboptimalOverloadCandidates() { 10208 // Same algorithm as overload resolution -- one pass to pick the "best", 10209 // another pass to be sure that nothing is better than the best. 10210 auto Best = Matches.begin(); 10211 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 10212 if (isBetterCandidate(I->second, Best->second)) 10213 Best = I; 10214 10215 const FunctionDecl *BestFn = Best->second; 10216 auto IsBestOrInferiorToBest = [this, BestFn]( 10217 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 10218 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 10219 }; 10220 10221 // Note: We explicitly leave Matches unmodified if there isn't a clear best 10222 // option, so we can potentially give the user a better error 10223 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest)) 10224 return false; 10225 Matches[0] = *Best; 10226 Matches.resize(1); 10227 return true; 10228 } 10229 10230 bool isTargetTypeAFunction() const { 10231 return TargetFunctionType->isFunctionType(); 10232 } 10233 10234 // [ToType] [Return] 10235 10236 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 10237 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 10238 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 10239 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 10240 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 10241 } 10242 10243 // return true if any matching specializations were found 10244 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 10245 const DeclAccessPair& CurAccessFunPair) { 10246 if (CXXMethodDecl *Method 10247 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 10248 // Skip non-static function templates when converting to pointer, and 10249 // static when converting to member pointer. 10250 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10251 return false; 10252 } 10253 else if (TargetTypeIsNonStaticMemberFunction) 10254 return false; 10255 10256 // C++ [over.over]p2: 10257 // If the name is a function template, template argument deduction is 10258 // done (14.8.2.2), and if the argument deduction succeeds, the 10259 // resulting template argument list is used to generate a single 10260 // function template specialization, which is added to the set of 10261 // overloaded functions considered. 10262 FunctionDecl *Specialization = nullptr; 10263 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10264 if (Sema::TemplateDeductionResult Result 10265 = S.DeduceTemplateArguments(FunctionTemplate, 10266 &OvlExplicitTemplateArgs, 10267 TargetFunctionType, Specialization, 10268 Info, /*InOverloadResolution=*/true)) { 10269 // Make a note of the failed deduction for diagnostics. 10270 FailedCandidates.addCandidate() 10271 .set(FunctionTemplate->getTemplatedDecl(), 10272 MakeDeductionFailureInfo(Context, Result, Info)); 10273 return false; 10274 } 10275 10276 // Template argument deduction ensures that we have an exact match or 10277 // compatible pointer-to-function arguments that would be adjusted by ICS. 10278 // This function template specicalization works. 10279 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl()); 10280 assert(S.isSameOrCompatibleFunctionType( 10281 Context.getCanonicalType(Specialization->getType()), 10282 Context.getCanonicalType(TargetFunctionType))); 10283 10284 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 10285 return false; 10286 10287 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 10288 return true; 10289 } 10290 10291 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 10292 const DeclAccessPair& CurAccessFunPair) { 10293 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 10294 // Skip non-static functions when converting to pointer, and static 10295 // when converting to member pointer. 10296 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10297 return false; 10298 } 10299 else if (TargetTypeIsNonStaticMemberFunction) 10300 return false; 10301 10302 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 10303 if (S.getLangOpts().CUDA) 10304 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 10305 if (!Caller->isImplicit() && S.CheckCUDATarget(Caller, FunDecl)) 10306 return false; 10307 10308 // If any candidate has a placeholder return type, trigger its deduction 10309 // now. 10310 if (S.getLangOpts().CPlusPlus14 && 10311 FunDecl->getReturnType()->isUndeducedType() && 10312 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain)) { 10313 HasComplained |= Complain; 10314 return false; 10315 } 10316 10317 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 10318 return false; 10319 10320 QualType ResultTy; 10321 if (Context.hasSameUnqualifiedType(TargetFunctionType, 10322 FunDecl->getType()) || 10323 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType, 10324 ResultTy) || 10325 (!S.getLangOpts().CPlusPlus && TargetType->isVoidPointerType())) { 10326 Matches.push_back(std::make_pair( 10327 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 10328 FoundNonTemplateFunction = true; 10329 return true; 10330 } 10331 } 10332 10333 return false; 10334 } 10335 10336 bool FindAllFunctionsThatMatchTargetTypeExactly() { 10337 bool Ret = false; 10338 10339 // If the overload expression doesn't have the form of a pointer to 10340 // member, don't try to convert it to a pointer-to-member type. 10341 if (IsInvalidFormOfPointerToMemberFunction()) 10342 return false; 10343 10344 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10345 E = OvlExpr->decls_end(); 10346 I != E; ++I) { 10347 // Look through any using declarations to find the underlying function. 10348 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 10349 10350 // C++ [over.over]p3: 10351 // Non-member functions and static member functions match 10352 // targets of type "pointer-to-function" or "reference-to-function." 10353 // Nonstatic member functions match targets of 10354 // type "pointer-to-member-function." 10355 // Note that according to DR 247, the containing class does not matter. 10356 if (FunctionTemplateDecl *FunctionTemplate 10357 = dyn_cast<FunctionTemplateDecl>(Fn)) { 10358 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 10359 Ret = true; 10360 } 10361 // If we have explicit template arguments supplied, skip non-templates. 10362 else if (!OvlExpr->hasExplicitTemplateArgs() && 10363 AddMatchingNonTemplateFunction(Fn, I.getPair())) 10364 Ret = true; 10365 } 10366 assert(Ret || Matches.empty()); 10367 return Ret; 10368 } 10369 10370 void EliminateAllExceptMostSpecializedTemplate() { 10371 // [...] and any given function template specialization F1 is 10372 // eliminated if the set contains a second function template 10373 // specialization whose function template is more specialized 10374 // than the function template of F1 according to the partial 10375 // ordering rules of 14.5.5.2. 10376 10377 // The algorithm specified above is quadratic. We instead use a 10378 // two-pass algorithm (similar to the one used to identify the 10379 // best viable function in an overload set) that identifies the 10380 // best function template (if it exists). 10381 10382 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 10383 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 10384 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 10385 10386 // TODO: It looks like FailedCandidates does not serve much purpose 10387 // here, since the no_viable diagnostic has index 0. 10388 UnresolvedSetIterator Result = S.getMostSpecialized( 10389 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 10390 SourceExpr->getLocStart(), S.PDiag(), 10391 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0] 10392 .second->getDeclName(), 10393 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template, 10394 Complain, TargetFunctionType); 10395 10396 if (Result != MatchesCopy.end()) { 10397 // Make it the first and only element 10398 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 10399 Matches[0].second = cast<FunctionDecl>(*Result); 10400 Matches.resize(1); 10401 } else 10402 HasComplained |= Complain; 10403 } 10404 10405 void EliminateAllTemplateMatches() { 10406 // [...] any function template specializations in the set are 10407 // eliminated if the set also contains a non-template function, [...] 10408 for (unsigned I = 0, N = Matches.size(); I != N; ) { 10409 if (Matches[I].second->getPrimaryTemplate() == nullptr) 10410 ++I; 10411 else { 10412 Matches[I] = Matches[--N]; 10413 Matches.resize(N); 10414 } 10415 } 10416 } 10417 10418 void EliminateSuboptimalCudaMatches() { 10419 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 10420 } 10421 10422 public: 10423 void ComplainNoMatchesFound() const { 10424 assert(Matches.empty()); 10425 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 10426 << OvlExpr->getName() << TargetFunctionType 10427 << OvlExpr->getSourceRange(); 10428 if (FailedCandidates.empty()) 10429 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10430 /*TakingAddress=*/true); 10431 else { 10432 // We have some deduction failure messages. Use them to diagnose 10433 // the function templates, and diagnose the non-template candidates 10434 // normally. 10435 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10436 IEnd = OvlExpr->decls_end(); 10437 I != IEnd; ++I) 10438 if (FunctionDecl *Fun = 10439 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 10440 if (!functionHasPassObjectSizeParams(Fun)) 10441 S.NoteOverloadCandidate(Fun, TargetFunctionType, 10442 /*TakingAddress=*/true); 10443 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 10444 } 10445 } 10446 10447 bool IsInvalidFormOfPointerToMemberFunction() const { 10448 return TargetTypeIsNonStaticMemberFunction && 10449 !OvlExprInfo.HasFormOfMemberPointer; 10450 } 10451 10452 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 10453 // TODO: Should we condition this on whether any functions might 10454 // have matched, or is it more appropriate to do that in callers? 10455 // TODO: a fixit wouldn't hurt. 10456 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 10457 << TargetType << OvlExpr->getSourceRange(); 10458 } 10459 10460 bool IsStaticMemberFunctionFromBoundPointer() const { 10461 return StaticMemberFunctionFromBoundPointer; 10462 } 10463 10464 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 10465 S.Diag(OvlExpr->getLocStart(), 10466 diag::err_invalid_form_pointer_member_function) 10467 << OvlExpr->getSourceRange(); 10468 } 10469 10470 void ComplainOfInvalidConversion() const { 10471 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 10472 << OvlExpr->getName() << TargetType; 10473 } 10474 10475 void ComplainMultipleMatchesFound() const { 10476 assert(Matches.size() > 1); 10477 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 10478 << OvlExpr->getName() 10479 << OvlExpr->getSourceRange(); 10480 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10481 /*TakingAddress=*/true); 10482 } 10483 10484 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 10485 10486 int getNumMatches() const { return Matches.size(); } 10487 10488 FunctionDecl* getMatchingFunctionDecl() const { 10489 if (Matches.size() != 1) return nullptr; 10490 return Matches[0].second; 10491 } 10492 10493 const DeclAccessPair* getMatchingFunctionAccessPair() const { 10494 if (Matches.size() != 1) return nullptr; 10495 return &Matches[0].first; 10496 } 10497 }; 10498 } 10499 10500 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 10501 /// an overloaded function (C++ [over.over]), where @p From is an 10502 /// expression with overloaded function type and @p ToType is the type 10503 /// we're trying to resolve to. For example: 10504 /// 10505 /// @code 10506 /// int f(double); 10507 /// int f(int); 10508 /// 10509 /// int (*pfd)(double) = f; // selects f(double) 10510 /// @endcode 10511 /// 10512 /// This routine returns the resulting FunctionDecl if it could be 10513 /// resolved, and NULL otherwise. When @p Complain is true, this 10514 /// routine will emit diagnostics if there is an error. 10515 FunctionDecl * 10516 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 10517 QualType TargetType, 10518 bool Complain, 10519 DeclAccessPair &FoundResult, 10520 bool *pHadMultipleCandidates) { 10521 assert(AddressOfExpr->getType() == Context.OverloadTy); 10522 10523 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 10524 Complain); 10525 int NumMatches = Resolver.getNumMatches(); 10526 FunctionDecl *Fn = nullptr; 10527 bool ShouldComplain = Complain && !Resolver.hasComplained(); 10528 if (NumMatches == 0 && ShouldComplain) { 10529 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 10530 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 10531 else 10532 Resolver.ComplainNoMatchesFound(); 10533 } 10534 else if (NumMatches > 1 && ShouldComplain) 10535 Resolver.ComplainMultipleMatchesFound(); 10536 else if (NumMatches == 1) { 10537 Fn = Resolver.getMatchingFunctionDecl(); 10538 assert(Fn); 10539 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 10540 if (Complain) { 10541 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 10542 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 10543 else 10544 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 10545 } 10546 } 10547 10548 if (pHadMultipleCandidates) 10549 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 10550 return Fn; 10551 } 10552 10553 /// \brief Given an expression that refers to an overloaded function, try to 10554 /// resolve that overloaded function expression down to a single function. 10555 /// 10556 /// This routine can only resolve template-ids that refer to a single function 10557 /// template, where that template-id refers to a single template whose template 10558 /// arguments are either provided by the template-id or have defaults, 10559 /// as described in C++0x [temp.arg.explicit]p3. 10560 /// 10561 /// If no template-ids are found, no diagnostics are emitted and NULL is 10562 /// returned. 10563 FunctionDecl * 10564 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 10565 bool Complain, 10566 DeclAccessPair *FoundResult) { 10567 // C++ [over.over]p1: 10568 // [...] [Note: any redundant set of parentheses surrounding the 10569 // overloaded function name is ignored (5.1). ] 10570 // C++ [over.over]p1: 10571 // [...] The overloaded function name can be preceded by the & 10572 // operator. 10573 10574 // If we didn't actually find any template-ids, we're done. 10575 if (!ovl->hasExplicitTemplateArgs()) 10576 return nullptr; 10577 10578 TemplateArgumentListInfo ExplicitTemplateArgs; 10579 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs); 10580 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 10581 10582 // Look through all of the overloaded functions, searching for one 10583 // whose type matches exactly. 10584 FunctionDecl *Matched = nullptr; 10585 for (UnresolvedSetIterator I = ovl->decls_begin(), 10586 E = ovl->decls_end(); I != E; ++I) { 10587 // C++0x [temp.arg.explicit]p3: 10588 // [...] In contexts where deduction is done and fails, or in contexts 10589 // where deduction is not done, if a template argument list is 10590 // specified and it, along with any default template arguments, 10591 // identifies a single function template specialization, then the 10592 // template-id is an lvalue for the function template specialization. 10593 FunctionTemplateDecl *FunctionTemplate 10594 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 10595 10596 // C++ [over.over]p2: 10597 // If the name is a function template, template argument deduction is 10598 // done (14.8.2.2), and if the argument deduction succeeds, the 10599 // resulting template argument list is used to generate a single 10600 // function template specialization, which is added to the set of 10601 // overloaded functions considered. 10602 FunctionDecl *Specialization = nullptr; 10603 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10604 if (TemplateDeductionResult Result 10605 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 10606 Specialization, Info, 10607 /*InOverloadResolution=*/true)) { 10608 // Make a note of the failed deduction for diagnostics. 10609 // TODO: Actually use the failed-deduction info? 10610 FailedCandidates.addCandidate() 10611 .set(FunctionTemplate->getTemplatedDecl(), 10612 MakeDeductionFailureInfo(Context, Result, Info)); 10613 continue; 10614 } 10615 10616 assert(Specialization && "no specialization and no error?"); 10617 10618 // Multiple matches; we can't resolve to a single declaration. 10619 if (Matched) { 10620 if (Complain) { 10621 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 10622 << ovl->getName(); 10623 NoteAllOverloadCandidates(ovl); 10624 } 10625 return nullptr; 10626 } 10627 10628 Matched = Specialization; 10629 if (FoundResult) *FoundResult = I.getPair(); 10630 } 10631 10632 if (Matched && getLangOpts().CPlusPlus14 && 10633 Matched->getReturnType()->isUndeducedType() && 10634 DeduceReturnType(Matched, ovl->getExprLoc(), Complain)) 10635 return nullptr; 10636 10637 return Matched; 10638 } 10639 10640 10641 10642 10643 // Resolve and fix an overloaded expression that can be resolved 10644 // because it identifies a single function template specialization. 10645 // 10646 // Last three arguments should only be supplied if Complain = true 10647 // 10648 // Return true if it was logically possible to so resolve the 10649 // expression, regardless of whether or not it succeeded. Always 10650 // returns true if 'complain' is set. 10651 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 10652 ExprResult &SrcExpr, bool doFunctionPointerConverion, 10653 bool complain, SourceRange OpRangeForComplaining, 10654 QualType DestTypeForComplaining, 10655 unsigned DiagIDForComplaining) { 10656 assert(SrcExpr.get()->getType() == Context.OverloadTy); 10657 10658 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 10659 10660 DeclAccessPair found; 10661 ExprResult SingleFunctionExpression; 10662 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 10663 ovl.Expression, /*complain*/ false, &found)) { 10664 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 10665 SrcExpr = ExprError(); 10666 return true; 10667 } 10668 10669 // It is only correct to resolve to an instance method if we're 10670 // resolving a form that's permitted to be a pointer to member. 10671 // Otherwise we'll end up making a bound member expression, which 10672 // is illegal in all the contexts we resolve like this. 10673 if (!ovl.HasFormOfMemberPointer && 10674 isa<CXXMethodDecl>(fn) && 10675 cast<CXXMethodDecl>(fn)->isInstance()) { 10676 if (!complain) return false; 10677 10678 Diag(ovl.Expression->getExprLoc(), 10679 diag::err_bound_member_function) 10680 << 0 << ovl.Expression->getSourceRange(); 10681 10682 // TODO: I believe we only end up here if there's a mix of 10683 // static and non-static candidates (otherwise the expression 10684 // would have 'bound member' type, not 'overload' type). 10685 // Ideally we would note which candidate was chosen and why 10686 // the static candidates were rejected. 10687 SrcExpr = ExprError(); 10688 return true; 10689 } 10690 10691 // Fix the expression to refer to 'fn'. 10692 SingleFunctionExpression = 10693 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 10694 10695 // If desired, do function-to-pointer decay. 10696 if (doFunctionPointerConverion) { 10697 SingleFunctionExpression = 10698 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 10699 if (SingleFunctionExpression.isInvalid()) { 10700 SrcExpr = ExprError(); 10701 return true; 10702 } 10703 } 10704 } 10705 10706 if (!SingleFunctionExpression.isUsable()) { 10707 if (complain) { 10708 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 10709 << ovl.Expression->getName() 10710 << DestTypeForComplaining 10711 << OpRangeForComplaining 10712 << ovl.Expression->getQualifierLoc().getSourceRange(); 10713 NoteAllOverloadCandidates(SrcExpr.get()); 10714 10715 SrcExpr = ExprError(); 10716 return true; 10717 } 10718 10719 return false; 10720 } 10721 10722 SrcExpr = SingleFunctionExpression; 10723 return true; 10724 } 10725 10726 /// \brief Add a single candidate to the overload set. 10727 static void AddOverloadedCallCandidate(Sema &S, 10728 DeclAccessPair FoundDecl, 10729 TemplateArgumentListInfo *ExplicitTemplateArgs, 10730 ArrayRef<Expr *> Args, 10731 OverloadCandidateSet &CandidateSet, 10732 bool PartialOverloading, 10733 bool KnownValid) { 10734 NamedDecl *Callee = FoundDecl.getDecl(); 10735 if (isa<UsingShadowDecl>(Callee)) 10736 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 10737 10738 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 10739 if (ExplicitTemplateArgs) { 10740 assert(!KnownValid && "Explicit template arguments?"); 10741 return; 10742 } 10743 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 10744 /*SuppressUsedConversions=*/false, 10745 PartialOverloading); 10746 return; 10747 } 10748 10749 if (FunctionTemplateDecl *FuncTemplate 10750 = dyn_cast<FunctionTemplateDecl>(Callee)) { 10751 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 10752 ExplicitTemplateArgs, Args, CandidateSet, 10753 /*SuppressUsedConversions=*/false, 10754 PartialOverloading); 10755 return; 10756 } 10757 10758 assert(!KnownValid && "unhandled case in overloaded call candidate"); 10759 } 10760 10761 /// \brief Add the overload candidates named by callee and/or found by argument 10762 /// dependent lookup to the given overload set. 10763 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 10764 ArrayRef<Expr *> Args, 10765 OverloadCandidateSet &CandidateSet, 10766 bool PartialOverloading) { 10767 10768 #ifndef NDEBUG 10769 // Verify that ArgumentDependentLookup is consistent with the rules 10770 // in C++0x [basic.lookup.argdep]p3: 10771 // 10772 // Let X be the lookup set produced by unqualified lookup (3.4.1) 10773 // and let Y be the lookup set produced by argument dependent 10774 // lookup (defined as follows). If X contains 10775 // 10776 // -- a declaration of a class member, or 10777 // 10778 // -- a block-scope function declaration that is not a 10779 // using-declaration, or 10780 // 10781 // -- a declaration that is neither a function or a function 10782 // template 10783 // 10784 // then Y is empty. 10785 10786 if (ULE->requiresADL()) { 10787 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10788 E = ULE->decls_end(); I != E; ++I) { 10789 assert(!(*I)->getDeclContext()->isRecord()); 10790 assert(isa<UsingShadowDecl>(*I) || 10791 !(*I)->getDeclContext()->isFunctionOrMethod()); 10792 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 10793 } 10794 } 10795 #endif 10796 10797 // It would be nice to avoid this copy. 10798 TemplateArgumentListInfo TABuffer; 10799 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 10800 if (ULE->hasExplicitTemplateArgs()) { 10801 ULE->copyTemplateArgumentsInto(TABuffer); 10802 ExplicitTemplateArgs = &TABuffer; 10803 } 10804 10805 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 10806 E = ULE->decls_end(); I != E; ++I) 10807 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 10808 CandidateSet, PartialOverloading, 10809 /*KnownValid*/ true); 10810 10811 if (ULE->requiresADL()) 10812 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 10813 Args, ExplicitTemplateArgs, 10814 CandidateSet, PartialOverloading); 10815 } 10816 10817 /// Determine whether a declaration with the specified name could be moved into 10818 /// a different namespace. 10819 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 10820 switch (Name.getCXXOverloadedOperator()) { 10821 case OO_New: case OO_Array_New: 10822 case OO_Delete: case OO_Array_Delete: 10823 return false; 10824 10825 default: 10826 return true; 10827 } 10828 } 10829 10830 /// Attempt to recover from an ill-formed use of a non-dependent name in a 10831 /// template, where the non-dependent name was declared after the template 10832 /// was defined. This is common in code written for a compilers which do not 10833 /// correctly implement two-stage name lookup. 10834 /// 10835 /// Returns true if a viable candidate was found and a diagnostic was issued. 10836 static bool 10837 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 10838 const CXXScopeSpec &SS, LookupResult &R, 10839 OverloadCandidateSet::CandidateSetKind CSK, 10840 TemplateArgumentListInfo *ExplicitTemplateArgs, 10841 ArrayRef<Expr *> Args, 10842 bool *DoDiagnoseEmptyLookup = nullptr) { 10843 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 10844 return false; 10845 10846 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 10847 if (DC->isTransparentContext()) 10848 continue; 10849 10850 SemaRef.LookupQualifiedName(R, DC); 10851 10852 if (!R.empty()) { 10853 R.suppressDiagnostics(); 10854 10855 if (isa<CXXRecordDecl>(DC)) { 10856 // Don't diagnose names we find in classes; we get much better 10857 // diagnostics for these from DiagnoseEmptyLookup. 10858 R.clear(); 10859 if (DoDiagnoseEmptyLookup) 10860 *DoDiagnoseEmptyLookup = true; 10861 return false; 10862 } 10863 10864 OverloadCandidateSet Candidates(FnLoc, CSK); 10865 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 10866 AddOverloadedCallCandidate(SemaRef, I.getPair(), 10867 ExplicitTemplateArgs, Args, 10868 Candidates, false, /*KnownValid*/ false); 10869 10870 OverloadCandidateSet::iterator Best; 10871 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 10872 // No viable functions. Don't bother the user with notes for functions 10873 // which don't work and shouldn't be found anyway. 10874 R.clear(); 10875 return false; 10876 } 10877 10878 // Find the namespaces where ADL would have looked, and suggest 10879 // declaring the function there instead. 10880 Sema::AssociatedNamespaceSet AssociatedNamespaces; 10881 Sema::AssociatedClassSet AssociatedClasses; 10882 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 10883 AssociatedNamespaces, 10884 AssociatedClasses); 10885 Sema::AssociatedNamespaceSet SuggestedNamespaces; 10886 if (canBeDeclaredInNamespace(R.getLookupName())) { 10887 DeclContext *Std = SemaRef.getStdNamespace(); 10888 for (Sema::AssociatedNamespaceSet::iterator 10889 it = AssociatedNamespaces.begin(), 10890 end = AssociatedNamespaces.end(); it != end; ++it) { 10891 // Never suggest declaring a function within namespace 'std'. 10892 if (Std && Std->Encloses(*it)) 10893 continue; 10894 10895 // Never suggest declaring a function within a namespace with a 10896 // reserved name, like __gnu_cxx. 10897 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 10898 if (NS && 10899 NS->getQualifiedNameAsString().find("__") != std::string::npos) 10900 continue; 10901 10902 SuggestedNamespaces.insert(*it); 10903 } 10904 } 10905 10906 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 10907 << R.getLookupName(); 10908 if (SuggestedNamespaces.empty()) { 10909 SemaRef.Diag(Best->Function->getLocation(), 10910 diag::note_not_found_by_two_phase_lookup) 10911 << R.getLookupName() << 0; 10912 } else if (SuggestedNamespaces.size() == 1) { 10913 SemaRef.Diag(Best->Function->getLocation(), 10914 diag::note_not_found_by_two_phase_lookup) 10915 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 10916 } else { 10917 // FIXME: It would be useful to list the associated namespaces here, 10918 // but the diagnostics infrastructure doesn't provide a way to produce 10919 // a localized representation of a list of items. 10920 SemaRef.Diag(Best->Function->getLocation(), 10921 diag::note_not_found_by_two_phase_lookup) 10922 << R.getLookupName() << 2; 10923 } 10924 10925 // Try to recover by calling this function. 10926 return true; 10927 } 10928 10929 R.clear(); 10930 } 10931 10932 return false; 10933 } 10934 10935 /// Attempt to recover from ill-formed use of a non-dependent operator in a 10936 /// template, where the non-dependent operator was declared after the template 10937 /// was defined. 10938 /// 10939 /// Returns true if a viable candidate was found and a diagnostic was issued. 10940 static bool 10941 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 10942 SourceLocation OpLoc, 10943 ArrayRef<Expr *> Args) { 10944 DeclarationName OpName = 10945 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 10946 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 10947 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 10948 OverloadCandidateSet::CSK_Operator, 10949 /*ExplicitTemplateArgs=*/nullptr, Args); 10950 } 10951 10952 namespace { 10953 class BuildRecoveryCallExprRAII { 10954 Sema &SemaRef; 10955 public: 10956 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 10957 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 10958 SemaRef.IsBuildingRecoveryCallExpr = true; 10959 } 10960 10961 ~BuildRecoveryCallExprRAII() { 10962 SemaRef.IsBuildingRecoveryCallExpr = false; 10963 } 10964 }; 10965 10966 } 10967 10968 static std::unique_ptr<CorrectionCandidateCallback> 10969 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 10970 bool HasTemplateArgs, bool AllowTypoCorrection) { 10971 if (!AllowTypoCorrection) 10972 return llvm::make_unique<NoTypoCorrectionCCC>(); 10973 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 10974 HasTemplateArgs, ME); 10975 } 10976 10977 /// Attempts to recover from a call where no functions were found. 10978 /// 10979 /// Returns true if new candidates were found. 10980 static ExprResult 10981 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 10982 UnresolvedLookupExpr *ULE, 10983 SourceLocation LParenLoc, 10984 MutableArrayRef<Expr *> Args, 10985 SourceLocation RParenLoc, 10986 bool EmptyLookup, bool AllowTypoCorrection) { 10987 // Do not try to recover if it is already building a recovery call. 10988 // This stops infinite loops for template instantiations like 10989 // 10990 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 10991 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 10992 // 10993 if (SemaRef.IsBuildingRecoveryCallExpr) 10994 return ExprError(); 10995 BuildRecoveryCallExprRAII RCE(SemaRef); 10996 10997 CXXScopeSpec SS; 10998 SS.Adopt(ULE->getQualifierLoc()); 10999 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11000 11001 TemplateArgumentListInfo TABuffer; 11002 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11003 if (ULE->hasExplicitTemplateArgs()) { 11004 ULE->copyTemplateArgumentsInto(TABuffer); 11005 ExplicitTemplateArgs = &TABuffer; 11006 } 11007 11008 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 11009 Sema::LookupOrdinaryName); 11010 bool DoDiagnoseEmptyLookup = EmptyLookup; 11011 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 11012 OverloadCandidateSet::CSK_Normal, 11013 ExplicitTemplateArgs, Args, 11014 &DoDiagnoseEmptyLookup) && 11015 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 11016 S, SS, R, 11017 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 11018 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 11019 ExplicitTemplateArgs, Args))) 11020 return ExprError(); 11021 11022 assert(!R.empty() && "lookup results empty despite recovery"); 11023 11024 // Build an implicit member call if appropriate. Just drop the 11025 // casts and such from the call, we don't really care. 11026 ExprResult NewFn = ExprError(); 11027 if ((*R.begin())->isCXXClassMember()) 11028 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 11029 ExplicitTemplateArgs, S); 11030 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 11031 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 11032 ExplicitTemplateArgs); 11033 else 11034 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 11035 11036 if (NewFn.isInvalid()) 11037 return ExprError(); 11038 11039 // This shouldn't cause an infinite loop because we're giving it 11040 // an expression with viable lookup results, which should never 11041 // end up here. 11042 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 11043 MultiExprArg(Args.data(), Args.size()), 11044 RParenLoc); 11045 } 11046 11047 /// \brief Constructs and populates an OverloadedCandidateSet from 11048 /// the given function. 11049 /// \returns true when an the ExprResult output parameter has been set. 11050 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 11051 UnresolvedLookupExpr *ULE, 11052 MultiExprArg Args, 11053 SourceLocation RParenLoc, 11054 OverloadCandidateSet *CandidateSet, 11055 ExprResult *Result) { 11056 #ifndef NDEBUG 11057 if (ULE->requiresADL()) { 11058 // To do ADL, we must have found an unqualified name. 11059 assert(!ULE->getQualifier() && "qualified name with ADL"); 11060 11061 // We don't perform ADL for implicit declarations of builtins. 11062 // Verify that this was correctly set up. 11063 FunctionDecl *F; 11064 if (ULE->decls_begin() + 1 == ULE->decls_end() && 11065 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 11066 F->getBuiltinID() && F->isImplicit()) 11067 llvm_unreachable("performing ADL for builtin"); 11068 11069 // We don't perform ADL in C. 11070 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 11071 } 11072 #endif 11073 11074 UnbridgedCastsSet UnbridgedCasts; 11075 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 11076 *Result = ExprError(); 11077 return true; 11078 } 11079 11080 // Add the functions denoted by the callee to the set of candidate 11081 // functions, including those from argument-dependent lookup. 11082 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 11083 11084 if (getLangOpts().MSVCCompat && 11085 CurContext->isDependentContext() && !isSFINAEContext() && 11086 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 11087 11088 OverloadCandidateSet::iterator Best; 11089 if (CandidateSet->empty() || 11090 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) == 11091 OR_No_Viable_Function) { 11092 // In Microsoft mode, if we are inside a template class member function then 11093 // create a type dependent CallExpr. The goal is to postpone name lookup 11094 // to instantiation time to be able to search into type dependent base 11095 // classes. 11096 CallExpr *CE = new (Context) CallExpr( 11097 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 11098 CE->setTypeDependent(true); 11099 CE->setValueDependent(true); 11100 CE->setInstantiationDependent(true); 11101 *Result = CE; 11102 return true; 11103 } 11104 } 11105 11106 if (CandidateSet->empty()) 11107 return false; 11108 11109 UnbridgedCasts.restore(); 11110 return false; 11111 } 11112 11113 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 11114 /// the completed call expression. If overload resolution fails, emits 11115 /// diagnostics and returns ExprError() 11116 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11117 UnresolvedLookupExpr *ULE, 11118 SourceLocation LParenLoc, 11119 MultiExprArg Args, 11120 SourceLocation RParenLoc, 11121 Expr *ExecConfig, 11122 OverloadCandidateSet *CandidateSet, 11123 OverloadCandidateSet::iterator *Best, 11124 OverloadingResult OverloadResult, 11125 bool AllowTypoCorrection) { 11126 if (CandidateSet->empty()) 11127 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 11128 RParenLoc, /*EmptyLookup=*/true, 11129 AllowTypoCorrection); 11130 11131 switch (OverloadResult) { 11132 case OR_Success: { 11133 FunctionDecl *FDecl = (*Best)->Function; 11134 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 11135 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 11136 return ExprError(); 11137 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11138 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11139 ExecConfig); 11140 } 11141 11142 case OR_No_Viable_Function: { 11143 // Try to recover by looking for viable functions which the user might 11144 // have meant to call. 11145 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 11146 Args, RParenLoc, 11147 /*EmptyLookup=*/false, 11148 AllowTypoCorrection); 11149 if (!Recovery.isInvalid()) 11150 return Recovery; 11151 11152 // If the user passes in a function that we can't take the address of, we 11153 // generally end up emitting really bad error messages. Here, we attempt to 11154 // emit better ones. 11155 for (const Expr *Arg : Args) { 11156 if (!Arg->getType()->isFunctionType()) 11157 continue; 11158 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 11159 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 11160 if (FD && 11161 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11162 Arg->getExprLoc())) 11163 return ExprError(); 11164 } 11165 } 11166 11167 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call) 11168 << ULE->getName() << Fn->getSourceRange(); 11169 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11170 break; 11171 } 11172 11173 case OR_Ambiguous: 11174 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 11175 << ULE->getName() << Fn->getSourceRange(); 11176 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 11177 break; 11178 11179 case OR_Deleted: { 11180 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 11181 << (*Best)->Function->isDeleted() 11182 << ULE->getName() 11183 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 11184 << Fn->getSourceRange(); 11185 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11186 11187 // We emitted an error for the unvailable/deleted function call but keep 11188 // the call in the AST. 11189 FunctionDecl *FDecl = (*Best)->Function; 11190 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11191 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11192 ExecConfig); 11193 } 11194 } 11195 11196 // Overload resolution failed. 11197 return ExprError(); 11198 } 11199 11200 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 11201 /// (which eventually refers to the declaration Func) and the call 11202 /// arguments Args/NumArgs, attempt to resolve the function call down 11203 /// to a specific function. If overload resolution succeeds, returns 11204 /// the call expression produced by overload resolution. 11205 /// Otherwise, emits diagnostics and returns ExprError. 11206 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 11207 UnresolvedLookupExpr *ULE, 11208 SourceLocation LParenLoc, 11209 MultiExprArg Args, 11210 SourceLocation RParenLoc, 11211 Expr *ExecConfig, 11212 bool AllowTypoCorrection) { 11213 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 11214 OverloadCandidateSet::CSK_Normal); 11215 ExprResult result; 11216 11217 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 11218 &result)) 11219 return result; 11220 11221 OverloadCandidateSet::iterator Best; 11222 OverloadingResult OverloadResult = 11223 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 11224 11225 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 11226 RParenLoc, ExecConfig, &CandidateSet, 11227 &Best, OverloadResult, 11228 AllowTypoCorrection); 11229 } 11230 11231 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 11232 return Functions.size() > 1 || 11233 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 11234 } 11235 11236 /// \brief Create a unary operation that may resolve to an overloaded 11237 /// operator. 11238 /// 11239 /// \param OpLoc The location of the operator itself (e.g., '*'). 11240 /// 11241 /// \param OpcIn The UnaryOperator::Opcode that describes this 11242 /// operator. 11243 /// 11244 /// \param Fns The set of non-member functions that will be 11245 /// considered by overload resolution. The caller needs to build this 11246 /// set based on the context using, e.g., 11247 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11248 /// set should not contain any member functions; those will be added 11249 /// by CreateOverloadedUnaryOp(). 11250 /// 11251 /// \param Input The input argument. 11252 ExprResult 11253 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn, 11254 const UnresolvedSetImpl &Fns, 11255 Expr *Input) { 11256 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn); 11257 11258 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 11259 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 11260 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11261 // TODO: provide better source location info. 11262 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11263 11264 if (checkPlaceholderForOverload(*this, Input)) 11265 return ExprError(); 11266 11267 Expr *Args[2] = { Input, nullptr }; 11268 unsigned NumArgs = 1; 11269 11270 // For post-increment and post-decrement, add the implicit '0' as 11271 // the second argument, so that we know this is a post-increment or 11272 // post-decrement. 11273 if (Opc == UO_PostInc || Opc == UO_PostDec) { 11274 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 11275 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 11276 SourceLocation()); 11277 NumArgs = 2; 11278 } 11279 11280 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 11281 11282 if (Input->isTypeDependent()) { 11283 if (Fns.empty()) 11284 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 11285 VK_RValue, OK_Ordinary, OpLoc); 11286 11287 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11288 UnresolvedLookupExpr *Fn 11289 = UnresolvedLookupExpr::Create(Context, NamingClass, 11290 NestedNameSpecifierLoc(), OpNameInfo, 11291 /*ADL*/ true, IsOverloaded(Fns), 11292 Fns.begin(), Fns.end()); 11293 return new (Context) 11294 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 11295 VK_RValue, OpLoc, false); 11296 } 11297 11298 // Build an empty overload set. 11299 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11300 11301 // Add the candidates from the given function set. 11302 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 11303 11304 // Add operator candidates that are member functions. 11305 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11306 11307 // Add candidates from ADL. 11308 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 11309 /*ExplicitTemplateArgs*/nullptr, 11310 CandidateSet); 11311 11312 // Add builtin operator candidates. 11313 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11314 11315 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11316 11317 // Perform overload resolution. 11318 OverloadCandidateSet::iterator Best; 11319 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11320 case OR_Success: { 11321 // We found a built-in operator or an overloaded operator. 11322 FunctionDecl *FnDecl = Best->Function; 11323 11324 if (FnDecl) { 11325 // We matched an overloaded operator. Build a call to that 11326 // operator. 11327 11328 // Convert the arguments. 11329 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11330 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 11331 11332 ExprResult InputRes = 11333 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 11334 Best->FoundDecl, Method); 11335 if (InputRes.isInvalid()) 11336 return ExprError(); 11337 Input = InputRes.get(); 11338 } else { 11339 // Convert the arguments. 11340 ExprResult InputInit 11341 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11342 Context, 11343 FnDecl->getParamDecl(0)), 11344 SourceLocation(), 11345 Input); 11346 if (InputInit.isInvalid()) 11347 return ExprError(); 11348 Input = InputInit.get(); 11349 } 11350 11351 // Build the actual expression node. 11352 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 11353 HadMultipleCandidates, OpLoc); 11354 if (FnExpr.isInvalid()) 11355 return ExprError(); 11356 11357 // Determine the result type. 11358 QualType ResultTy = FnDecl->getReturnType(); 11359 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11360 ResultTy = ResultTy.getNonLValueExprType(Context); 11361 11362 Args[0] = Input; 11363 CallExpr *TheCall = 11364 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 11365 ResultTy, VK, OpLoc, false); 11366 11367 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 11368 return ExprError(); 11369 11370 return MaybeBindToTemporary(TheCall); 11371 } else { 11372 // We matched a built-in operator. Convert the arguments, then 11373 // break out so that we will build the appropriate built-in 11374 // operator node. 11375 ExprResult InputRes = 11376 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 11377 Best->Conversions[0], AA_Passing); 11378 if (InputRes.isInvalid()) 11379 return ExprError(); 11380 Input = InputRes.get(); 11381 break; 11382 } 11383 } 11384 11385 case OR_No_Viable_Function: 11386 // This is an erroneous use of an operator which can be overloaded by 11387 // a non-member function. Check for non-member operators which were 11388 // defined too late to be candidates. 11389 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 11390 // FIXME: Recover by calling the found function. 11391 return ExprError(); 11392 11393 // No viable function; fall through to handling this as a 11394 // built-in operator, which will produce an error message for us. 11395 break; 11396 11397 case OR_Ambiguous: 11398 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11399 << UnaryOperator::getOpcodeStr(Opc) 11400 << Input->getType() 11401 << Input->getSourceRange(); 11402 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 11403 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11404 return ExprError(); 11405 11406 case OR_Deleted: 11407 Diag(OpLoc, diag::err_ovl_deleted_oper) 11408 << Best->Function->isDeleted() 11409 << UnaryOperator::getOpcodeStr(Opc) 11410 << getDeletedOrUnavailableSuffix(Best->Function) 11411 << Input->getSourceRange(); 11412 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 11413 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11414 return ExprError(); 11415 } 11416 11417 // Either we found no viable overloaded operator or we matched a 11418 // built-in operator. In either case, fall through to trying to 11419 // build a built-in operation. 11420 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11421 } 11422 11423 /// \brief Create a binary operation that may resolve to an overloaded 11424 /// operator. 11425 /// 11426 /// \param OpLoc The location of the operator itself (e.g., '+'). 11427 /// 11428 /// \param OpcIn The BinaryOperator::Opcode that describes this 11429 /// operator. 11430 /// 11431 /// \param Fns The set of non-member functions that will be 11432 /// considered by overload resolution. The caller needs to build this 11433 /// set based on the context using, e.g., 11434 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11435 /// set should not contain any member functions; those will be added 11436 /// by CreateOverloadedBinOp(). 11437 /// 11438 /// \param LHS Left-hand argument. 11439 /// \param RHS Right-hand argument. 11440 ExprResult 11441 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 11442 unsigned OpcIn, 11443 const UnresolvedSetImpl &Fns, 11444 Expr *LHS, Expr *RHS) { 11445 Expr *Args[2] = { LHS, RHS }; 11446 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 11447 11448 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn); 11449 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 11450 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11451 11452 // If either side is type-dependent, create an appropriate dependent 11453 // expression. 11454 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11455 if (Fns.empty()) { 11456 // If there are no functions to store, just build a dependent 11457 // BinaryOperator or CompoundAssignment. 11458 if (Opc <= BO_Assign || Opc > BO_OrAssign) 11459 return new (Context) BinaryOperator( 11460 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 11461 OpLoc, FPFeatures.fp_contract); 11462 11463 return new (Context) CompoundAssignOperator( 11464 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 11465 Context.DependentTy, Context.DependentTy, OpLoc, 11466 FPFeatures.fp_contract); 11467 } 11468 11469 // FIXME: save results of ADL from here? 11470 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11471 // TODO: provide better source location info in DNLoc component. 11472 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11473 UnresolvedLookupExpr *Fn 11474 = UnresolvedLookupExpr::Create(Context, NamingClass, 11475 NestedNameSpecifierLoc(), OpNameInfo, 11476 /*ADL*/ true, IsOverloaded(Fns), 11477 Fns.begin(), Fns.end()); 11478 return new (Context) 11479 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 11480 VK_RValue, OpLoc, FPFeatures.fp_contract); 11481 } 11482 11483 // Always do placeholder-like conversions on the RHS. 11484 if (checkPlaceholderForOverload(*this, Args[1])) 11485 return ExprError(); 11486 11487 // Do placeholder-like conversion on the LHS; note that we should 11488 // not get here with a PseudoObject LHS. 11489 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 11490 if (checkPlaceholderForOverload(*this, Args[0])) 11491 return ExprError(); 11492 11493 // If this is the assignment operator, we only perform overload resolution 11494 // if the left-hand side is a class or enumeration type. This is actually 11495 // a hack. The standard requires that we do overload resolution between the 11496 // various built-in candidates, but as DR507 points out, this can lead to 11497 // problems. So we do it this way, which pretty much follows what GCC does. 11498 // Note that we go the traditional code path for compound assignment forms. 11499 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 11500 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11501 11502 // If this is the .* operator, which is not overloadable, just 11503 // create a built-in binary operator. 11504 if (Opc == BO_PtrMemD) 11505 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11506 11507 // Build an empty overload set. 11508 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11509 11510 // Add the candidates from the given function set. 11511 AddFunctionCandidates(Fns, Args, CandidateSet); 11512 11513 // Add operator candidates that are member functions. 11514 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11515 11516 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 11517 // performed for an assignment operator (nor for operator[] nor operator->, 11518 // which don't get here). 11519 if (Opc != BO_Assign) 11520 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 11521 /*ExplicitTemplateArgs*/ nullptr, 11522 CandidateSet); 11523 11524 // Add builtin operator candidates. 11525 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11526 11527 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11528 11529 // Perform overload resolution. 11530 OverloadCandidateSet::iterator Best; 11531 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11532 case OR_Success: { 11533 // We found a built-in operator or an overloaded operator. 11534 FunctionDecl *FnDecl = Best->Function; 11535 11536 if (FnDecl) { 11537 // We matched an overloaded operator. Build a call to that 11538 // operator. 11539 11540 // Convert the arguments. 11541 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11542 // Best->Access is only meaningful for class members. 11543 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 11544 11545 ExprResult Arg1 = 11546 PerformCopyInitialization( 11547 InitializedEntity::InitializeParameter(Context, 11548 FnDecl->getParamDecl(0)), 11549 SourceLocation(), Args[1]); 11550 if (Arg1.isInvalid()) 11551 return ExprError(); 11552 11553 ExprResult Arg0 = 11554 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11555 Best->FoundDecl, Method); 11556 if (Arg0.isInvalid()) 11557 return ExprError(); 11558 Args[0] = Arg0.getAs<Expr>(); 11559 Args[1] = RHS = Arg1.getAs<Expr>(); 11560 } else { 11561 // Convert the arguments. 11562 ExprResult Arg0 = PerformCopyInitialization( 11563 InitializedEntity::InitializeParameter(Context, 11564 FnDecl->getParamDecl(0)), 11565 SourceLocation(), Args[0]); 11566 if (Arg0.isInvalid()) 11567 return ExprError(); 11568 11569 ExprResult Arg1 = 11570 PerformCopyInitialization( 11571 InitializedEntity::InitializeParameter(Context, 11572 FnDecl->getParamDecl(1)), 11573 SourceLocation(), Args[1]); 11574 if (Arg1.isInvalid()) 11575 return ExprError(); 11576 Args[0] = LHS = Arg0.getAs<Expr>(); 11577 Args[1] = RHS = Arg1.getAs<Expr>(); 11578 } 11579 11580 // Build the actual expression node. 11581 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11582 Best->FoundDecl, 11583 HadMultipleCandidates, OpLoc); 11584 if (FnExpr.isInvalid()) 11585 return ExprError(); 11586 11587 // Determine the result type. 11588 QualType ResultTy = FnDecl->getReturnType(); 11589 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11590 ResultTy = ResultTy.getNonLValueExprType(Context); 11591 11592 CXXOperatorCallExpr *TheCall = 11593 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 11594 Args, ResultTy, VK, OpLoc, 11595 FPFeatures.fp_contract); 11596 11597 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 11598 FnDecl)) 11599 return ExprError(); 11600 11601 ArrayRef<const Expr *> ArgsArray(Args, 2); 11602 // Cut off the implicit 'this'. 11603 if (isa<CXXMethodDecl>(FnDecl)) 11604 ArgsArray = ArgsArray.slice(1); 11605 11606 // Check for a self move. 11607 if (Op == OO_Equal) 11608 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 11609 11610 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc, 11611 TheCall->getSourceRange(), VariadicDoesNotApply); 11612 11613 return MaybeBindToTemporary(TheCall); 11614 } else { 11615 // We matched a built-in operator. Convert the arguments, then 11616 // break out so that we will build the appropriate built-in 11617 // operator node. 11618 ExprResult ArgsRes0 = 11619 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11620 Best->Conversions[0], AA_Passing); 11621 if (ArgsRes0.isInvalid()) 11622 return ExprError(); 11623 Args[0] = ArgsRes0.get(); 11624 11625 ExprResult ArgsRes1 = 11626 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11627 Best->Conversions[1], AA_Passing); 11628 if (ArgsRes1.isInvalid()) 11629 return ExprError(); 11630 Args[1] = ArgsRes1.get(); 11631 break; 11632 } 11633 } 11634 11635 case OR_No_Viable_Function: { 11636 // C++ [over.match.oper]p9: 11637 // If the operator is the operator , [...] and there are no 11638 // viable functions, then the operator is assumed to be the 11639 // built-in operator and interpreted according to clause 5. 11640 if (Opc == BO_Comma) 11641 break; 11642 11643 // For class as left operand for assignment or compound assigment 11644 // operator do not fall through to handling in built-in, but report that 11645 // no overloaded assignment operator found 11646 ExprResult Result = ExprError(); 11647 if (Args[0]->getType()->isRecordType() && 11648 Opc >= BO_Assign && Opc <= BO_OrAssign) { 11649 Diag(OpLoc, diag::err_ovl_no_viable_oper) 11650 << BinaryOperator::getOpcodeStr(Opc) 11651 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11652 if (Args[0]->getType()->isIncompleteType()) { 11653 Diag(OpLoc, diag::note_assign_lhs_incomplete) 11654 << Args[0]->getType() 11655 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11656 } 11657 } else { 11658 // This is an erroneous use of an operator which can be overloaded by 11659 // a non-member function. Check for non-member operators which were 11660 // defined too late to be candidates. 11661 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 11662 // FIXME: Recover by calling the found function. 11663 return ExprError(); 11664 11665 // No viable function; try to create a built-in operation, which will 11666 // produce an error. Then, show the non-viable candidates. 11667 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11668 } 11669 assert(Result.isInvalid() && 11670 "C++ binary operator overloading is missing candidates!"); 11671 if (Result.isInvalid()) 11672 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11673 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11674 return Result; 11675 } 11676 11677 case OR_Ambiguous: 11678 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 11679 << BinaryOperator::getOpcodeStr(Opc) 11680 << Args[0]->getType() << Args[1]->getType() 11681 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11682 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11683 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11684 return ExprError(); 11685 11686 case OR_Deleted: 11687 if (isImplicitlyDeleted(Best->Function)) { 11688 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 11689 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 11690 << Context.getRecordType(Method->getParent()) 11691 << getSpecialMember(Method); 11692 11693 // The user probably meant to call this special member. Just 11694 // explain why it's deleted. 11695 NoteDeletedFunction(Method); 11696 return ExprError(); 11697 } else { 11698 Diag(OpLoc, diag::err_ovl_deleted_oper) 11699 << Best->Function->isDeleted() 11700 << BinaryOperator::getOpcodeStr(Opc) 11701 << getDeletedOrUnavailableSuffix(Best->Function) 11702 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11703 } 11704 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11705 BinaryOperator::getOpcodeStr(Opc), OpLoc); 11706 return ExprError(); 11707 } 11708 11709 // We matched a built-in operator; build it. 11710 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11711 } 11712 11713 ExprResult 11714 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 11715 SourceLocation RLoc, 11716 Expr *Base, Expr *Idx) { 11717 Expr *Args[2] = { Base, Idx }; 11718 DeclarationName OpName = 11719 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 11720 11721 // If either side is type-dependent, create an appropriate dependent 11722 // expression. 11723 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11724 11725 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11726 // CHECKME: no 'operator' keyword? 11727 DeclarationNameInfo OpNameInfo(OpName, LLoc); 11728 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11729 UnresolvedLookupExpr *Fn 11730 = UnresolvedLookupExpr::Create(Context, NamingClass, 11731 NestedNameSpecifierLoc(), OpNameInfo, 11732 /*ADL*/ true, /*Overloaded*/ false, 11733 UnresolvedSetIterator(), 11734 UnresolvedSetIterator()); 11735 // Can't add any actual overloads yet 11736 11737 return new (Context) 11738 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 11739 Context.DependentTy, VK_RValue, RLoc, false); 11740 } 11741 11742 // Handle placeholders on both operands. 11743 if (checkPlaceholderForOverload(*this, Args[0])) 11744 return ExprError(); 11745 if (checkPlaceholderForOverload(*this, Args[1])) 11746 return ExprError(); 11747 11748 // Build an empty overload set. 11749 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 11750 11751 // Subscript can only be overloaded as a member function. 11752 11753 // Add operator candidates that are member functions. 11754 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11755 11756 // Add builtin operator candidates. 11757 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 11758 11759 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11760 11761 // Perform overload resolution. 11762 OverloadCandidateSet::iterator Best; 11763 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 11764 case OR_Success: { 11765 // We found a built-in operator or an overloaded operator. 11766 FunctionDecl *FnDecl = Best->Function; 11767 11768 if (FnDecl) { 11769 // We matched an overloaded operator. Build a call to that 11770 // operator. 11771 11772 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 11773 11774 // Convert the arguments. 11775 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 11776 ExprResult Arg0 = 11777 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11778 Best->FoundDecl, Method); 11779 if (Arg0.isInvalid()) 11780 return ExprError(); 11781 Args[0] = Arg0.get(); 11782 11783 // Convert the arguments. 11784 ExprResult InputInit 11785 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11786 Context, 11787 FnDecl->getParamDecl(0)), 11788 SourceLocation(), 11789 Args[1]); 11790 if (InputInit.isInvalid()) 11791 return ExprError(); 11792 11793 Args[1] = InputInit.getAs<Expr>(); 11794 11795 // Build the actual expression node. 11796 DeclarationNameInfo OpLocInfo(OpName, LLoc); 11797 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 11798 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 11799 Best->FoundDecl, 11800 HadMultipleCandidates, 11801 OpLocInfo.getLoc(), 11802 OpLocInfo.getInfo()); 11803 if (FnExpr.isInvalid()) 11804 return ExprError(); 11805 11806 // Determine the result type 11807 QualType ResultTy = FnDecl->getReturnType(); 11808 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11809 ResultTy = ResultTy.getNonLValueExprType(Context); 11810 11811 CXXOperatorCallExpr *TheCall = 11812 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 11813 FnExpr.get(), Args, 11814 ResultTy, VK, RLoc, 11815 false); 11816 11817 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 11818 return ExprError(); 11819 11820 return MaybeBindToTemporary(TheCall); 11821 } else { 11822 // We matched a built-in operator. Convert the arguments, then 11823 // break out so that we will build the appropriate built-in 11824 // operator node. 11825 ExprResult ArgsRes0 = 11826 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 11827 Best->Conversions[0], AA_Passing); 11828 if (ArgsRes0.isInvalid()) 11829 return ExprError(); 11830 Args[0] = ArgsRes0.get(); 11831 11832 ExprResult ArgsRes1 = 11833 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 11834 Best->Conversions[1], AA_Passing); 11835 if (ArgsRes1.isInvalid()) 11836 return ExprError(); 11837 Args[1] = ArgsRes1.get(); 11838 11839 break; 11840 } 11841 } 11842 11843 case OR_No_Viable_Function: { 11844 if (CandidateSet.empty()) 11845 Diag(LLoc, diag::err_ovl_no_oper) 11846 << Args[0]->getType() << /*subscript*/ 0 11847 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11848 else 11849 Diag(LLoc, diag::err_ovl_no_viable_subscript) 11850 << Args[0]->getType() 11851 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11852 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11853 "[]", LLoc); 11854 return ExprError(); 11855 } 11856 11857 case OR_Ambiguous: 11858 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 11859 << "[]" 11860 << Args[0]->getType() << Args[1]->getType() 11861 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11862 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 11863 "[]", LLoc); 11864 return ExprError(); 11865 11866 case OR_Deleted: 11867 Diag(LLoc, diag::err_ovl_deleted_oper) 11868 << Best->Function->isDeleted() << "[]" 11869 << getDeletedOrUnavailableSuffix(Best->Function) 11870 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 11871 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 11872 "[]", LLoc); 11873 return ExprError(); 11874 } 11875 11876 // We matched a built-in operator; build it. 11877 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 11878 } 11879 11880 /// BuildCallToMemberFunction - Build a call to a member 11881 /// function. MemExpr is the expression that refers to the member 11882 /// function (and includes the object parameter), Args/NumArgs are the 11883 /// arguments to the function call (not including the object 11884 /// parameter). The caller needs to validate that the member 11885 /// expression refers to a non-static member function or an overloaded 11886 /// member function. 11887 ExprResult 11888 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 11889 SourceLocation LParenLoc, 11890 MultiExprArg Args, 11891 SourceLocation RParenLoc) { 11892 assert(MemExprE->getType() == Context.BoundMemberTy || 11893 MemExprE->getType() == Context.OverloadTy); 11894 11895 // Dig out the member expression. This holds both the object 11896 // argument and the member function we're referring to. 11897 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 11898 11899 // Determine whether this is a call to a pointer-to-member function. 11900 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 11901 assert(op->getType() == Context.BoundMemberTy); 11902 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 11903 11904 QualType fnType = 11905 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 11906 11907 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 11908 QualType resultType = proto->getCallResultType(Context); 11909 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 11910 11911 // Check that the object type isn't more qualified than the 11912 // member function we're calling. 11913 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 11914 11915 QualType objectType = op->getLHS()->getType(); 11916 if (op->getOpcode() == BO_PtrMemI) 11917 objectType = objectType->castAs<PointerType>()->getPointeeType(); 11918 Qualifiers objectQuals = objectType.getQualifiers(); 11919 11920 Qualifiers difference = objectQuals - funcQuals; 11921 difference.removeObjCGCAttr(); 11922 difference.removeAddressSpace(); 11923 if (difference) { 11924 std::string qualsString = difference.getAsString(); 11925 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 11926 << fnType.getUnqualifiedType() 11927 << qualsString 11928 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 11929 } 11930 11931 CXXMemberCallExpr *call 11932 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 11933 resultType, valueKind, RParenLoc); 11934 11935 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 11936 call, nullptr)) 11937 return ExprError(); 11938 11939 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 11940 return ExprError(); 11941 11942 if (CheckOtherCall(call, proto)) 11943 return ExprError(); 11944 11945 return MaybeBindToTemporary(call); 11946 } 11947 11948 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 11949 return new (Context) 11950 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 11951 11952 UnbridgedCastsSet UnbridgedCasts; 11953 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 11954 return ExprError(); 11955 11956 MemberExpr *MemExpr; 11957 CXXMethodDecl *Method = nullptr; 11958 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 11959 NestedNameSpecifier *Qualifier = nullptr; 11960 if (isa<MemberExpr>(NakedMemExpr)) { 11961 MemExpr = cast<MemberExpr>(NakedMemExpr); 11962 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 11963 FoundDecl = MemExpr->getFoundDecl(); 11964 Qualifier = MemExpr->getQualifier(); 11965 UnbridgedCasts.restore(); 11966 } else { 11967 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 11968 Qualifier = UnresExpr->getQualifier(); 11969 11970 QualType ObjectType = UnresExpr->getBaseType(); 11971 Expr::Classification ObjectClassification 11972 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 11973 : UnresExpr->getBase()->Classify(Context); 11974 11975 // Add overload candidates 11976 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 11977 OverloadCandidateSet::CSK_Normal); 11978 11979 // FIXME: avoid copy. 11980 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 11981 if (UnresExpr->hasExplicitTemplateArgs()) { 11982 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 11983 TemplateArgs = &TemplateArgsBuffer; 11984 } 11985 11986 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 11987 E = UnresExpr->decls_end(); I != E; ++I) { 11988 11989 NamedDecl *Func = *I; 11990 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 11991 if (isa<UsingShadowDecl>(Func)) 11992 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 11993 11994 11995 // Microsoft supports direct constructor calls. 11996 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 11997 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 11998 Args, CandidateSet); 11999 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 12000 // If explicit template arguments were provided, we can't call a 12001 // non-template member function. 12002 if (TemplateArgs) 12003 continue; 12004 12005 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 12006 ObjectClassification, Args, CandidateSet, 12007 /*SuppressUserConversions=*/false); 12008 } else { 12009 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 12010 I.getPair(), ActingDC, TemplateArgs, 12011 ObjectType, ObjectClassification, 12012 Args, CandidateSet, 12013 /*SuppressUsedConversions=*/false); 12014 } 12015 } 12016 12017 DeclarationName DeclName = UnresExpr->getMemberName(); 12018 12019 UnbridgedCasts.restore(); 12020 12021 OverloadCandidateSet::iterator Best; 12022 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 12023 Best)) { 12024 case OR_Success: 12025 Method = cast<CXXMethodDecl>(Best->Function); 12026 FoundDecl = Best->FoundDecl; 12027 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 12028 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 12029 return ExprError(); 12030 // If FoundDecl is different from Method (such as if one is a template 12031 // and the other a specialization), make sure DiagnoseUseOfDecl is 12032 // called on both. 12033 // FIXME: This would be more comprehensively addressed by modifying 12034 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 12035 // being used. 12036 if (Method != FoundDecl.getDecl() && 12037 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 12038 return ExprError(); 12039 break; 12040 12041 case OR_No_Viable_Function: 12042 Diag(UnresExpr->getMemberLoc(), 12043 diag::err_ovl_no_viable_member_function_in_call) 12044 << DeclName << MemExprE->getSourceRange(); 12045 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12046 // FIXME: Leaking incoming expressions! 12047 return ExprError(); 12048 12049 case OR_Ambiguous: 12050 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 12051 << DeclName << MemExprE->getSourceRange(); 12052 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12053 // FIXME: Leaking incoming expressions! 12054 return ExprError(); 12055 12056 case OR_Deleted: 12057 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 12058 << Best->Function->isDeleted() 12059 << DeclName 12060 << getDeletedOrUnavailableSuffix(Best->Function) 12061 << MemExprE->getSourceRange(); 12062 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12063 // FIXME: Leaking incoming expressions! 12064 return ExprError(); 12065 } 12066 12067 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 12068 12069 // If overload resolution picked a static member, build a 12070 // non-member call based on that function. 12071 if (Method->isStatic()) { 12072 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 12073 RParenLoc); 12074 } 12075 12076 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 12077 } 12078 12079 QualType ResultType = Method->getReturnType(); 12080 ExprValueKind VK = Expr::getValueKindForType(ResultType); 12081 ResultType = ResultType.getNonLValueExprType(Context); 12082 12083 assert(Method && "Member call to something that isn't a method?"); 12084 CXXMemberCallExpr *TheCall = 12085 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12086 ResultType, VK, RParenLoc); 12087 12088 // (CUDA B.1): Check for invalid calls between targets. 12089 if (getLangOpts().CUDA) { 12090 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) { 12091 if (CheckCUDATarget(Caller, Method)) { 12092 Diag(MemExpr->getMemberLoc(), diag::err_ref_bad_target) 12093 << IdentifyCUDATarget(Method) << Method->getIdentifier() 12094 << IdentifyCUDATarget(Caller); 12095 return ExprError(); 12096 } 12097 } 12098 } 12099 12100 // Check for a valid return type. 12101 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 12102 TheCall, Method)) 12103 return ExprError(); 12104 12105 // Convert the object argument (for a non-static member function call). 12106 // We only need to do this if there was actually an overload; otherwise 12107 // it was done at lookup. 12108 if (!Method->isStatic()) { 12109 ExprResult ObjectArg = 12110 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 12111 FoundDecl, Method); 12112 if (ObjectArg.isInvalid()) 12113 return ExprError(); 12114 MemExpr->setBase(ObjectArg.get()); 12115 } 12116 12117 // Convert the rest of the arguments 12118 const FunctionProtoType *Proto = 12119 Method->getType()->getAs<FunctionProtoType>(); 12120 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 12121 RParenLoc)) 12122 return ExprError(); 12123 12124 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12125 12126 if (CheckFunctionCall(Method, TheCall, Proto)) 12127 return ExprError(); 12128 12129 // In the case the method to call was not selected by the overloading 12130 // resolution process, we still need to handle the enable_if attribute. Do 12131 // that here, so it will not hide previous -- and more relevant -- errors 12132 if (isa<MemberExpr>(NakedMemExpr)) { 12133 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 12134 Diag(MemExprE->getLocStart(), 12135 diag::err_ovl_no_viable_member_function_in_call) 12136 << Method << Method->getSourceRange(); 12137 Diag(Method->getLocation(), 12138 diag::note_ovl_candidate_disabled_by_enable_if_attr) 12139 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 12140 return ExprError(); 12141 } 12142 } 12143 12144 if ((isa<CXXConstructorDecl>(CurContext) || 12145 isa<CXXDestructorDecl>(CurContext)) && 12146 TheCall->getMethodDecl()->isPure()) { 12147 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 12148 12149 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 12150 MemExpr->performsVirtualDispatch(getLangOpts())) { 12151 Diag(MemExpr->getLocStart(), 12152 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 12153 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 12154 << MD->getParent()->getDeclName(); 12155 12156 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 12157 if (getLangOpts().AppleKext) 12158 Diag(MemExpr->getLocStart(), 12159 diag::note_pure_qualified_call_kext) 12160 << MD->getParent()->getDeclName() 12161 << MD->getDeclName(); 12162 } 12163 } 12164 return MaybeBindToTemporary(TheCall); 12165 } 12166 12167 /// BuildCallToObjectOfClassType - Build a call to an object of class 12168 /// type (C++ [over.call.object]), which can end up invoking an 12169 /// overloaded function call operator (@c operator()) or performing a 12170 /// user-defined conversion on the object argument. 12171 ExprResult 12172 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 12173 SourceLocation LParenLoc, 12174 MultiExprArg Args, 12175 SourceLocation RParenLoc) { 12176 if (checkPlaceholderForOverload(*this, Obj)) 12177 return ExprError(); 12178 ExprResult Object = Obj; 12179 12180 UnbridgedCastsSet UnbridgedCasts; 12181 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12182 return ExprError(); 12183 12184 assert(Object.get()->getType()->isRecordType() && 12185 "Requires object type argument"); 12186 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 12187 12188 // C++ [over.call.object]p1: 12189 // If the primary-expression E in the function call syntax 12190 // evaluates to a class object of type "cv T", then the set of 12191 // candidate functions includes at least the function call 12192 // operators of T. The function call operators of T are obtained by 12193 // ordinary lookup of the name operator() in the context of 12194 // (E).operator(). 12195 OverloadCandidateSet CandidateSet(LParenLoc, 12196 OverloadCandidateSet::CSK_Operator); 12197 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 12198 12199 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 12200 diag::err_incomplete_object_call, Object.get())) 12201 return true; 12202 12203 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 12204 LookupQualifiedName(R, Record->getDecl()); 12205 R.suppressDiagnostics(); 12206 12207 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12208 Oper != OperEnd; ++Oper) { 12209 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 12210 Object.get()->Classify(Context), 12211 Args, CandidateSet, 12212 /*SuppressUserConversions=*/ false); 12213 } 12214 12215 // C++ [over.call.object]p2: 12216 // In addition, for each (non-explicit in C++0x) conversion function 12217 // declared in T of the form 12218 // 12219 // operator conversion-type-id () cv-qualifier; 12220 // 12221 // where cv-qualifier is the same cv-qualification as, or a 12222 // greater cv-qualification than, cv, and where conversion-type-id 12223 // denotes the type "pointer to function of (P1,...,Pn) returning 12224 // R", or the type "reference to pointer to function of 12225 // (P1,...,Pn) returning R", or the type "reference to function 12226 // of (P1,...,Pn) returning R", a surrogate call function [...] 12227 // is also considered as a candidate function. Similarly, 12228 // surrogate call functions are added to the set of candidate 12229 // functions for each conversion function declared in an 12230 // accessible base class provided the function is not hidden 12231 // within T by another intervening declaration. 12232 const auto &Conversions = 12233 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 12234 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 12235 NamedDecl *D = *I; 12236 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 12237 if (isa<UsingShadowDecl>(D)) 12238 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 12239 12240 // Skip over templated conversion functions; they aren't 12241 // surrogates. 12242 if (isa<FunctionTemplateDecl>(D)) 12243 continue; 12244 12245 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 12246 if (!Conv->isExplicit()) { 12247 // Strip the reference type (if any) and then the pointer type (if 12248 // any) to get down to what might be a function type. 12249 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 12250 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 12251 ConvType = ConvPtrType->getPointeeType(); 12252 12253 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 12254 { 12255 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 12256 Object.get(), Args, CandidateSet); 12257 } 12258 } 12259 } 12260 12261 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12262 12263 // Perform overload resolution. 12264 OverloadCandidateSet::iterator Best; 12265 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 12266 Best)) { 12267 case OR_Success: 12268 // Overload resolution succeeded; we'll build the appropriate call 12269 // below. 12270 break; 12271 12272 case OR_No_Viable_Function: 12273 if (CandidateSet.empty()) 12274 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 12275 << Object.get()->getType() << /*call*/ 1 12276 << Object.get()->getSourceRange(); 12277 else 12278 Diag(Object.get()->getLocStart(), 12279 diag::err_ovl_no_viable_object_call) 12280 << Object.get()->getType() << Object.get()->getSourceRange(); 12281 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12282 break; 12283 12284 case OR_Ambiguous: 12285 Diag(Object.get()->getLocStart(), 12286 diag::err_ovl_ambiguous_object_call) 12287 << Object.get()->getType() << Object.get()->getSourceRange(); 12288 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12289 break; 12290 12291 case OR_Deleted: 12292 Diag(Object.get()->getLocStart(), 12293 diag::err_ovl_deleted_object_call) 12294 << Best->Function->isDeleted() 12295 << Object.get()->getType() 12296 << getDeletedOrUnavailableSuffix(Best->Function) 12297 << Object.get()->getSourceRange(); 12298 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12299 break; 12300 } 12301 12302 if (Best == CandidateSet.end()) 12303 return true; 12304 12305 UnbridgedCasts.restore(); 12306 12307 if (Best->Function == nullptr) { 12308 // Since there is no function declaration, this is one of the 12309 // surrogate candidates. Dig out the conversion function. 12310 CXXConversionDecl *Conv 12311 = cast<CXXConversionDecl>( 12312 Best->Conversions[0].UserDefined.ConversionFunction); 12313 12314 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 12315 Best->FoundDecl); 12316 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 12317 return ExprError(); 12318 assert(Conv == Best->FoundDecl.getDecl() && 12319 "Found Decl & conversion-to-functionptr should be same, right?!"); 12320 // We selected one of the surrogate functions that converts the 12321 // object parameter to a function pointer. Perform the conversion 12322 // on the object argument, then let ActOnCallExpr finish the job. 12323 12324 // Create an implicit member expr to refer to the conversion operator. 12325 // and then call it. 12326 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 12327 Conv, HadMultipleCandidates); 12328 if (Call.isInvalid()) 12329 return ExprError(); 12330 // Record usage of conversion in an implicit cast. 12331 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 12332 CK_UserDefinedConversion, Call.get(), 12333 nullptr, VK_RValue); 12334 12335 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 12336 } 12337 12338 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 12339 12340 // We found an overloaded operator(). Build a CXXOperatorCallExpr 12341 // that calls this method, using Object for the implicit object 12342 // parameter and passing along the remaining arguments. 12343 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12344 12345 // An error diagnostic has already been printed when parsing the declaration. 12346 if (Method->isInvalidDecl()) 12347 return ExprError(); 12348 12349 const FunctionProtoType *Proto = 12350 Method->getType()->getAs<FunctionProtoType>(); 12351 12352 unsigned NumParams = Proto->getNumParams(); 12353 12354 DeclarationNameInfo OpLocInfo( 12355 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 12356 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 12357 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12358 HadMultipleCandidates, 12359 OpLocInfo.getLoc(), 12360 OpLocInfo.getInfo()); 12361 if (NewFn.isInvalid()) 12362 return true; 12363 12364 // Build the full argument list for the method call (the implicit object 12365 // parameter is placed at the beginning of the list). 12366 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]); 12367 MethodArgs[0] = Object.get(); 12368 std::copy(Args.begin(), Args.end(), &MethodArgs[1]); 12369 12370 // Once we've built TheCall, all of the expressions are properly 12371 // owned. 12372 QualType ResultTy = Method->getReturnType(); 12373 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12374 ResultTy = ResultTy.getNonLValueExprType(Context); 12375 12376 CXXOperatorCallExpr *TheCall = new (Context) 12377 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), 12378 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1), 12379 ResultTy, VK, RParenLoc, false); 12380 MethodArgs.reset(); 12381 12382 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 12383 return true; 12384 12385 // We may have default arguments. If so, we need to allocate more 12386 // slots in the call for them. 12387 if (Args.size() < NumParams) 12388 TheCall->setNumArgs(Context, NumParams + 1); 12389 12390 bool IsError = false; 12391 12392 // Initialize the implicit object parameter. 12393 ExprResult ObjRes = 12394 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 12395 Best->FoundDecl, Method); 12396 if (ObjRes.isInvalid()) 12397 IsError = true; 12398 else 12399 Object = ObjRes; 12400 TheCall->setArg(0, Object.get()); 12401 12402 // Check the argument types. 12403 for (unsigned i = 0; i != NumParams; i++) { 12404 Expr *Arg; 12405 if (i < Args.size()) { 12406 Arg = Args[i]; 12407 12408 // Pass the argument. 12409 12410 ExprResult InputInit 12411 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12412 Context, 12413 Method->getParamDecl(i)), 12414 SourceLocation(), Arg); 12415 12416 IsError |= InputInit.isInvalid(); 12417 Arg = InputInit.getAs<Expr>(); 12418 } else { 12419 ExprResult DefArg 12420 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 12421 if (DefArg.isInvalid()) { 12422 IsError = true; 12423 break; 12424 } 12425 12426 Arg = DefArg.getAs<Expr>(); 12427 } 12428 12429 TheCall->setArg(i + 1, Arg); 12430 } 12431 12432 // If this is a variadic call, handle args passed through "...". 12433 if (Proto->isVariadic()) { 12434 // Promote the arguments (C99 6.5.2.2p7). 12435 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 12436 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 12437 nullptr); 12438 IsError |= Arg.isInvalid(); 12439 TheCall->setArg(i + 1, Arg.get()); 12440 } 12441 } 12442 12443 if (IsError) return true; 12444 12445 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12446 12447 if (CheckFunctionCall(Method, TheCall, Proto)) 12448 return true; 12449 12450 return MaybeBindToTemporary(TheCall); 12451 } 12452 12453 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 12454 /// (if one exists), where @c Base is an expression of class type and 12455 /// @c Member is the name of the member we're trying to find. 12456 ExprResult 12457 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 12458 bool *NoArrowOperatorFound) { 12459 assert(Base->getType()->isRecordType() && 12460 "left-hand side must have class type"); 12461 12462 if (checkPlaceholderForOverload(*this, Base)) 12463 return ExprError(); 12464 12465 SourceLocation Loc = Base->getExprLoc(); 12466 12467 // C++ [over.ref]p1: 12468 // 12469 // [...] An expression x->m is interpreted as (x.operator->())->m 12470 // for a class object x of type T if T::operator->() exists and if 12471 // the operator is selected as the best match function by the 12472 // overload resolution mechanism (13.3). 12473 DeclarationName OpName = 12474 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 12475 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 12476 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 12477 12478 if (RequireCompleteType(Loc, Base->getType(), 12479 diag::err_typecheck_incomplete_tag, Base)) 12480 return ExprError(); 12481 12482 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 12483 LookupQualifiedName(R, BaseRecord->getDecl()); 12484 R.suppressDiagnostics(); 12485 12486 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12487 Oper != OperEnd; ++Oper) { 12488 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 12489 None, CandidateSet, /*SuppressUserConversions=*/false); 12490 } 12491 12492 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12493 12494 // Perform overload resolution. 12495 OverloadCandidateSet::iterator Best; 12496 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12497 case OR_Success: 12498 // Overload resolution succeeded; we'll build the call below. 12499 break; 12500 12501 case OR_No_Viable_Function: 12502 if (CandidateSet.empty()) { 12503 QualType BaseType = Base->getType(); 12504 if (NoArrowOperatorFound) { 12505 // Report this specific error to the caller instead of emitting a 12506 // diagnostic, as requested. 12507 *NoArrowOperatorFound = true; 12508 return ExprError(); 12509 } 12510 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 12511 << BaseType << Base->getSourceRange(); 12512 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 12513 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 12514 << FixItHint::CreateReplacement(OpLoc, "."); 12515 } 12516 } else 12517 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12518 << "operator->" << Base->getSourceRange(); 12519 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12520 return ExprError(); 12521 12522 case OR_Ambiguous: 12523 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12524 << "->" << Base->getType() << Base->getSourceRange(); 12525 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 12526 return ExprError(); 12527 12528 case OR_Deleted: 12529 Diag(OpLoc, diag::err_ovl_deleted_oper) 12530 << Best->Function->isDeleted() 12531 << "->" 12532 << getDeletedOrUnavailableSuffix(Best->Function) 12533 << Base->getSourceRange(); 12534 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12535 return ExprError(); 12536 } 12537 12538 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 12539 12540 // Convert the object parameter. 12541 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12542 ExprResult BaseResult = 12543 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 12544 Best->FoundDecl, Method); 12545 if (BaseResult.isInvalid()) 12546 return ExprError(); 12547 Base = BaseResult.get(); 12548 12549 // Build the operator call. 12550 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12551 HadMultipleCandidates, OpLoc); 12552 if (FnExpr.isInvalid()) 12553 return ExprError(); 12554 12555 QualType ResultTy = Method->getReturnType(); 12556 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12557 ResultTy = ResultTy.getNonLValueExprType(Context); 12558 CXXOperatorCallExpr *TheCall = 12559 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 12560 Base, ResultTy, VK, OpLoc, false); 12561 12562 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 12563 return ExprError(); 12564 12565 return MaybeBindToTemporary(TheCall); 12566 } 12567 12568 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 12569 /// a literal operator described by the provided lookup results. 12570 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 12571 DeclarationNameInfo &SuffixInfo, 12572 ArrayRef<Expr*> Args, 12573 SourceLocation LitEndLoc, 12574 TemplateArgumentListInfo *TemplateArgs) { 12575 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 12576 12577 OverloadCandidateSet CandidateSet(UDSuffixLoc, 12578 OverloadCandidateSet::CSK_Normal); 12579 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 12580 /*SuppressUserConversions=*/true); 12581 12582 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12583 12584 // Perform overload resolution. This will usually be trivial, but might need 12585 // to perform substitutions for a literal operator template. 12586 OverloadCandidateSet::iterator Best; 12587 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 12588 case OR_Success: 12589 case OR_Deleted: 12590 break; 12591 12592 case OR_No_Viable_Function: 12593 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 12594 << R.getLookupName(); 12595 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12596 return ExprError(); 12597 12598 case OR_Ambiguous: 12599 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 12600 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12601 return ExprError(); 12602 } 12603 12604 FunctionDecl *FD = Best->Function; 12605 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 12606 HadMultipleCandidates, 12607 SuffixInfo.getLoc(), 12608 SuffixInfo.getInfo()); 12609 if (Fn.isInvalid()) 12610 return true; 12611 12612 // Check the argument types. This should almost always be a no-op, except 12613 // that array-to-pointer decay is applied to string literals. 12614 Expr *ConvArgs[2]; 12615 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 12616 ExprResult InputInit = PerformCopyInitialization( 12617 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 12618 SourceLocation(), Args[ArgIdx]); 12619 if (InputInit.isInvalid()) 12620 return true; 12621 ConvArgs[ArgIdx] = InputInit.get(); 12622 } 12623 12624 QualType ResultTy = FD->getReturnType(); 12625 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12626 ResultTy = ResultTy.getNonLValueExprType(Context); 12627 12628 UserDefinedLiteral *UDL = 12629 new (Context) UserDefinedLiteral(Context, Fn.get(), 12630 llvm::makeArrayRef(ConvArgs, Args.size()), 12631 ResultTy, VK, LitEndLoc, UDSuffixLoc); 12632 12633 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 12634 return ExprError(); 12635 12636 if (CheckFunctionCall(FD, UDL, nullptr)) 12637 return ExprError(); 12638 12639 return MaybeBindToTemporary(UDL); 12640 } 12641 12642 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 12643 /// given LookupResult is non-empty, it is assumed to describe a member which 12644 /// will be invoked. Otherwise, the function will be found via argument 12645 /// dependent lookup. 12646 /// CallExpr is set to a valid expression and FRS_Success returned on success, 12647 /// otherwise CallExpr is set to ExprError() and some non-success value 12648 /// is returned. 12649 Sema::ForRangeStatus 12650 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 12651 SourceLocation RangeLoc, 12652 const DeclarationNameInfo &NameInfo, 12653 LookupResult &MemberLookup, 12654 OverloadCandidateSet *CandidateSet, 12655 Expr *Range, ExprResult *CallExpr) { 12656 Scope *S = nullptr; 12657 12658 CandidateSet->clear(); 12659 if (!MemberLookup.empty()) { 12660 ExprResult MemberRef = 12661 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 12662 /*IsPtr=*/false, CXXScopeSpec(), 12663 /*TemplateKWLoc=*/SourceLocation(), 12664 /*FirstQualifierInScope=*/nullptr, 12665 MemberLookup, 12666 /*TemplateArgs=*/nullptr, S); 12667 if (MemberRef.isInvalid()) { 12668 *CallExpr = ExprError(); 12669 return FRS_DiagnosticIssued; 12670 } 12671 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 12672 if (CallExpr->isInvalid()) { 12673 *CallExpr = ExprError(); 12674 return FRS_DiagnosticIssued; 12675 } 12676 } else { 12677 UnresolvedSet<0> FoundNames; 12678 UnresolvedLookupExpr *Fn = 12679 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 12680 NestedNameSpecifierLoc(), NameInfo, 12681 /*NeedsADL=*/true, /*Overloaded=*/false, 12682 FoundNames.begin(), FoundNames.end()); 12683 12684 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 12685 CandidateSet, CallExpr); 12686 if (CandidateSet->empty() || CandidateSetError) { 12687 *CallExpr = ExprError(); 12688 return FRS_NoViableFunction; 12689 } 12690 OverloadCandidateSet::iterator Best; 12691 OverloadingResult OverloadResult = 12692 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 12693 12694 if (OverloadResult == OR_No_Viable_Function) { 12695 *CallExpr = ExprError(); 12696 return FRS_NoViableFunction; 12697 } 12698 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 12699 Loc, nullptr, CandidateSet, &Best, 12700 OverloadResult, 12701 /*AllowTypoCorrection=*/false); 12702 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 12703 *CallExpr = ExprError(); 12704 return FRS_DiagnosticIssued; 12705 } 12706 } 12707 return FRS_Success; 12708 } 12709 12710 12711 /// FixOverloadedFunctionReference - E is an expression that refers to 12712 /// a C++ overloaded function (possibly with some parentheses and 12713 /// perhaps a '&' around it). We have resolved the overloaded function 12714 /// to the function declaration Fn, so patch up the expression E to 12715 /// refer (possibly indirectly) to Fn. Returns the new expr. 12716 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 12717 FunctionDecl *Fn) { 12718 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 12719 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 12720 Found, Fn); 12721 if (SubExpr == PE->getSubExpr()) 12722 return PE; 12723 12724 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 12725 } 12726 12727 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 12728 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 12729 Found, Fn); 12730 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 12731 SubExpr->getType()) && 12732 "Implicit cast type cannot be determined from overload"); 12733 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 12734 if (SubExpr == ICE->getSubExpr()) 12735 return ICE; 12736 12737 return ImplicitCastExpr::Create(Context, ICE->getType(), 12738 ICE->getCastKind(), 12739 SubExpr, nullptr, 12740 ICE->getValueKind()); 12741 } 12742 12743 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 12744 assert(UnOp->getOpcode() == UO_AddrOf && 12745 "Can only take the address of an overloaded function"); 12746 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 12747 if (Method->isStatic()) { 12748 // Do nothing: static member functions aren't any different 12749 // from non-member functions. 12750 } else { 12751 // Fix the subexpression, which really has to be an 12752 // UnresolvedLookupExpr holding an overloaded member function 12753 // or template. 12754 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12755 Found, Fn); 12756 if (SubExpr == UnOp->getSubExpr()) 12757 return UnOp; 12758 12759 assert(isa<DeclRefExpr>(SubExpr) 12760 && "fixed to something other than a decl ref"); 12761 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 12762 && "fixed to a member ref with no nested name qualifier"); 12763 12764 // We have taken the address of a pointer to member 12765 // function. Perform the computation here so that we get the 12766 // appropriate pointer to member type. 12767 QualType ClassType 12768 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 12769 QualType MemPtrType 12770 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 12771 12772 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 12773 VK_RValue, OK_Ordinary, 12774 UnOp->getOperatorLoc()); 12775 } 12776 } 12777 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 12778 Found, Fn); 12779 if (SubExpr == UnOp->getSubExpr()) 12780 return UnOp; 12781 12782 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 12783 Context.getPointerType(SubExpr->getType()), 12784 VK_RValue, OK_Ordinary, 12785 UnOp->getOperatorLoc()); 12786 } 12787 12788 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 12789 // FIXME: avoid copy. 12790 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12791 if (ULE->hasExplicitTemplateArgs()) { 12792 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 12793 TemplateArgs = &TemplateArgsBuffer; 12794 } 12795 12796 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12797 ULE->getQualifierLoc(), 12798 ULE->getTemplateKeywordLoc(), 12799 Fn, 12800 /*enclosing*/ false, // FIXME? 12801 ULE->getNameLoc(), 12802 Fn->getType(), 12803 VK_LValue, 12804 Found.getDecl(), 12805 TemplateArgs); 12806 MarkDeclRefReferenced(DRE); 12807 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 12808 return DRE; 12809 } 12810 12811 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 12812 // FIXME: avoid copy. 12813 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12814 if (MemExpr->hasExplicitTemplateArgs()) { 12815 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12816 TemplateArgs = &TemplateArgsBuffer; 12817 } 12818 12819 Expr *Base; 12820 12821 // If we're filling in a static method where we used to have an 12822 // implicit member access, rewrite to a simple decl ref. 12823 if (MemExpr->isImplicitAccess()) { 12824 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12825 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 12826 MemExpr->getQualifierLoc(), 12827 MemExpr->getTemplateKeywordLoc(), 12828 Fn, 12829 /*enclosing*/ false, 12830 MemExpr->getMemberLoc(), 12831 Fn->getType(), 12832 VK_LValue, 12833 Found.getDecl(), 12834 TemplateArgs); 12835 MarkDeclRefReferenced(DRE); 12836 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 12837 return DRE; 12838 } else { 12839 SourceLocation Loc = MemExpr->getMemberLoc(); 12840 if (MemExpr->getQualifier()) 12841 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 12842 CheckCXXThisCapture(Loc); 12843 Base = new (Context) CXXThisExpr(Loc, 12844 MemExpr->getBaseType(), 12845 /*isImplicit=*/true); 12846 } 12847 } else 12848 Base = MemExpr->getBase(); 12849 12850 ExprValueKind valueKind; 12851 QualType type; 12852 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 12853 valueKind = VK_LValue; 12854 type = Fn->getType(); 12855 } else { 12856 valueKind = VK_RValue; 12857 type = Context.BoundMemberTy; 12858 } 12859 12860 MemberExpr *ME = MemberExpr::Create( 12861 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 12862 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 12863 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 12864 OK_Ordinary); 12865 ME->setHadMultipleCandidates(true); 12866 MarkMemberReferenced(ME); 12867 return ME; 12868 } 12869 12870 llvm_unreachable("Invalid reference to overloaded function"); 12871 } 12872 12873 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 12874 DeclAccessPair Found, 12875 FunctionDecl *Fn) { 12876 return FixOverloadedFunctionReference(E.get(), Found, Fn); 12877 } 12878