1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file provides Sema routines for C++ overloading. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/Sema/Overload.h" 14 #include "clang/AST/ASTContext.h" 15 #include "clang/AST/CXXInheritance.h" 16 #include "clang/AST/DeclObjC.h" 17 #include "clang/AST/Expr.h" 18 #include "clang/AST/ExprCXX.h" 19 #include "clang/AST/ExprObjC.h" 20 #include "clang/AST/TypeOrdering.h" 21 #include "clang/Basic/Diagnostic.h" 22 #include "clang/Basic/DiagnosticOptions.h" 23 #include "clang/Basic/PartialDiagnostic.h" 24 #include "clang/Basic/TargetInfo.h" 25 #include "clang/Sema/Initialization.h" 26 #include "clang/Sema/Lookup.h" 27 #include "clang/Sema/SemaInternal.h" 28 #include "clang/Sema/Template.h" 29 #include "clang/Sema/TemplateDeduction.h" 30 #include "llvm/ADT/DenseSet.h" 31 #include "llvm/ADT/Optional.h" 32 #include "llvm/ADT/STLExtras.h" 33 #include "llvm/ADT/SmallPtrSet.h" 34 #include "llvm/ADT/SmallString.h" 35 #include <algorithm> 36 #include <cstdlib> 37 38 using namespace clang; 39 using namespace sema; 40 41 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 42 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) { 43 return P->hasAttr<PassObjectSizeAttr>(); 44 }); 45 } 46 47 /// A convenience routine for creating a decayed reference to a function. 48 static ExprResult 49 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, 50 const Expr *Base, bool HadMultipleCandidates, 51 SourceLocation Loc = SourceLocation(), 52 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 53 if (S.DiagnoseUseOfDecl(FoundDecl, Loc)) 54 return ExprError(); 55 // If FoundDecl is different from Fn (such as if one is a template 56 // and the other a specialization), make sure DiagnoseUseOfDecl is 57 // called on both. 58 // FIXME: This would be more comprehensively addressed by modifying 59 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 60 // being used. 61 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc)) 62 return ExprError(); 63 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 64 S.ResolveExceptionSpec(Loc, FPT); 65 DeclRefExpr *DRE = new (S.Context) 66 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo); 67 if (HadMultipleCandidates) 68 DRE->setHadMultipleCandidates(true); 69 70 S.MarkDeclRefReferenced(DRE, Base); 71 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()), 72 CK_FunctionToPointerDecay); 73 } 74 75 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 76 bool InOverloadResolution, 77 StandardConversionSequence &SCS, 78 bool CStyle, 79 bool AllowObjCWritebackConversion); 80 81 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 82 QualType &ToType, 83 bool InOverloadResolution, 84 StandardConversionSequence &SCS, 85 bool CStyle); 86 static OverloadingResult 87 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 88 UserDefinedConversionSequence& User, 89 OverloadCandidateSet& Conversions, 90 bool AllowExplicit, 91 bool AllowObjCConversionOnExplicit); 92 93 94 static ImplicitConversionSequence::CompareKind 95 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 96 const StandardConversionSequence& SCS1, 97 const StandardConversionSequence& SCS2); 98 99 static ImplicitConversionSequence::CompareKind 100 CompareQualificationConversions(Sema &S, 101 const StandardConversionSequence& SCS1, 102 const StandardConversionSequence& SCS2); 103 104 static ImplicitConversionSequence::CompareKind 105 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 106 const StandardConversionSequence& SCS1, 107 const StandardConversionSequence& SCS2); 108 109 /// GetConversionRank - Retrieve the implicit conversion rank 110 /// corresponding to the given implicit conversion kind. 111 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) { 112 static const ImplicitConversionRank 113 Rank[(int)ICK_Num_Conversion_Kinds] = { 114 ICR_Exact_Match, 115 ICR_Exact_Match, 116 ICR_Exact_Match, 117 ICR_Exact_Match, 118 ICR_Exact_Match, 119 ICR_Exact_Match, 120 ICR_Promotion, 121 ICR_Promotion, 122 ICR_Promotion, 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_Conversion, 132 ICR_Conversion, 133 ICR_OCL_Scalar_Widening, 134 ICR_Complex_Real_Conversion, 135 ICR_Conversion, 136 ICR_Conversion, 137 ICR_Writeback_Conversion, 138 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right -- 139 // it was omitted by the patch that added 140 // ICK_Zero_Event_Conversion 141 ICR_C_Conversion, 142 ICR_C_Conversion_Extension 143 }; 144 return Rank[(int)Kind]; 145 } 146 147 /// GetImplicitConversionName - Return the name of this kind of 148 /// implicit conversion. 149 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 150 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 151 "No conversion", 152 "Lvalue-to-rvalue", 153 "Array-to-pointer", 154 "Function-to-pointer", 155 "Function pointer conversion", 156 "Qualification", 157 "Integral promotion", 158 "Floating point promotion", 159 "Complex promotion", 160 "Integral conversion", 161 "Floating conversion", 162 "Complex conversion", 163 "Floating-integral conversion", 164 "Pointer conversion", 165 "Pointer-to-member conversion", 166 "Boolean conversion", 167 "Compatible-types conversion", 168 "Derived-to-base conversion", 169 "Vector conversion", 170 "Vector splat", 171 "Complex-real conversion", 172 "Block Pointer conversion", 173 "Transparent Union Conversion", 174 "Writeback conversion", 175 "OpenCL Zero Event Conversion", 176 "C specific type conversion", 177 "Incompatible pointer conversion" 178 }; 179 return Name[Kind]; 180 } 181 182 /// StandardConversionSequence - Set the standard conversion 183 /// sequence to the identity conversion. 184 void StandardConversionSequence::setAsIdentityConversion() { 185 First = ICK_Identity; 186 Second = ICK_Identity; 187 Third = ICK_Identity; 188 DeprecatedStringLiteralToCharPtr = false; 189 QualificationIncludesObjCLifetime = false; 190 ReferenceBinding = false; 191 DirectBinding = false; 192 IsLvalueReference = true; 193 BindsToFunctionLvalue = false; 194 BindsToRvalue = false; 195 BindsImplicitObjectArgumentWithoutRefQualifier = false; 196 ObjCLifetimeConversionBinding = false; 197 CopyConstructor = nullptr; 198 } 199 200 /// getRank - Retrieve the rank of this standard conversion sequence 201 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 202 /// implicit conversions. 203 ImplicitConversionRank StandardConversionSequence::getRank() const { 204 ImplicitConversionRank Rank = ICR_Exact_Match; 205 if (GetConversionRank(First) > Rank) 206 Rank = GetConversionRank(First); 207 if (GetConversionRank(Second) > Rank) 208 Rank = GetConversionRank(Second); 209 if (GetConversionRank(Third) > Rank) 210 Rank = GetConversionRank(Third); 211 return Rank; 212 } 213 214 /// isPointerConversionToBool - Determines whether this conversion is 215 /// a conversion of a pointer or pointer-to-member to bool. This is 216 /// used as part of the ranking of standard conversion sequences 217 /// (C++ 13.3.3.2p4). 218 bool StandardConversionSequence::isPointerConversionToBool() const { 219 // Note that FromType has not necessarily been transformed by the 220 // array-to-pointer or function-to-pointer implicit conversions, so 221 // check for their presence as well as checking whether FromType is 222 // a pointer. 223 if (getToType(1)->isBooleanType() && 224 (getFromType()->isPointerType() || 225 getFromType()->isMemberPointerType() || 226 getFromType()->isObjCObjectPointerType() || 227 getFromType()->isBlockPointerType() || 228 getFromType()->isNullPtrType() || 229 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 230 return true; 231 232 return false; 233 } 234 235 /// isPointerConversionToVoidPointer - Determines whether this 236 /// conversion is a conversion of a pointer to a void pointer. This is 237 /// used as part of the ranking of standard conversion sequences (C++ 238 /// 13.3.3.2p4). 239 bool 240 StandardConversionSequence:: 241 isPointerConversionToVoidPointer(ASTContext& Context) const { 242 QualType FromType = getFromType(); 243 QualType ToType = getToType(1); 244 245 // Note that FromType has not necessarily been transformed by the 246 // array-to-pointer implicit conversion, so check for its presence 247 // and redo the conversion to get a pointer. 248 if (First == ICK_Array_To_Pointer) 249 FromType = Context.getArrayDecayedType(FromType); 250 251 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 252 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 253 return ToPtrType->getPointeeType()->isVoidType(); 254 255 return false; 256 } 257 258 /// Skip any implicit casts which could be either part of a narrowing conversion 259 /// or after one in an implicit conversion. 260 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 261 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 262 switch (ICE->getCastKind()) { 263 case CK_NoOp: 264 case CK_IntegralCast: 265 case CK_IntegralToBoolean: 266 case CK_IntegralToFloating: 267 case CK_BooleanToSignedIntegral: 268 case CK_FloatingToIntegral: 269 case CK_FloatingToBoolean: 270 case CK_FloatingCast: 271 Converted = ICE->getSubExpr(); 272 continue; 273 274 default: 275 return Converted; 276 } 277 } 278 279 return Converted; 280 } 281 282 /// Check if this standard conversion sequence represents a narrowing 283 /// conversion, according to C++11 [dcl.init.list]p7. 284 /// 285 /// \param Ctx The AST context. 286 /// \param Converted The result of applying this standard conversion sequence. 287 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 288 /// value of the expression prior to the narrowing conversion. 289 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 290 /// type of the expression prior to the narrowing conversion. 291 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions 292 /// from floating point types to integral types should be ignored. 293 NarrowingKind StandardConversionSequence::getNarrowingKind( 294 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue, 295 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const { 296 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 297 298 // C++11 [dcl.init.list]p7: 299 // A narrowing conversion is an implicit conversion ... 300 QualType FromType = getToType(0); 301 QualType ToType = getToType(1); 302 303 // A conversion to an enumeration type is narrowing if the conversion to 304 // the underlying type is narrowing. This only arises for expressions of 305 // the form 'Enum{init}'. 306 if (auto *ET = ToType->getAs<EnumType>()) 307 ToType = ET->getDecl()->getIntegerType(); 308 309 switch (Second) { 310 // 'bool' is an integral type; dispatch to the right place to handle it. 311 case ICK_Boolean_Conversion: 312 if (FromType->isRealFloatingType()) 313 goto FloatingIntegralConversion; 314 if (FromType->isIntegralOrUnscopedEnumerationType()) 315 goto IntegralConversion; 316 // Boolean conversions can be from pointers and pointers to members 317 // [conv.bool], and those aren't considered narrowing conversions. 318 return NK_Not_Narrowing; 319 320 // -- from a floating-point type to an integer type, or 321 // 322 // -- from an integer type or unscoped enumeration type to a floating-point 323 // type, except where the source is a constant expression and the actual 324 // value after conversion will fit into the target type and will produce 325 // the original value when converted back to the original type, or 326 case ICK_Floating_Integral: 327 FloatingIntegralConversion: 328 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 329 return NK_Type_Narrowing; 330 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 331 ToType->isRealFloatingType()) { 332 if (IgnoreFloatToIntegralConversion) 333 return NK_Not_Narrowing; 334 llvm::APSInt IntConstantValue; 335 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 336 assert(Initializer && "Unknown conversion expression"); 337 338 // If it's value-dependent, we can't tell whether it's narrowing. 339 if (Initializer->isValueDependent()) 340 return NK_Dependent_Narrowing; 341 342 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 343 // Convert the integer to the floating type. 344 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 345 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 346 llvm::APFloat::rmNearestTiesToEven); 347 // And back. 348 llvm::APSInt ConvertedValue = IntConstantValue; 349 bool ignored; 350 Result.convertToInteger(ConvertedValue, 351 llvm::APFloat::rmTowardZero, &ignored); 352 // If the resulting value is different, this was a narrowing conversion. 353 if (IntConstantValue != ConvertedValue) { 354 ConstantValue = APValue(IntConstantValue); 355 ConstantType = Initializer->getType(); 356 return NK_Constant_Narrowing; 357 } 358 } else { 359 // Variables are always narrowings. 360 return NK_Variable_Narrowing; 361 } 362 } 363 return NK_Not_Narrowing; 364 365 // -- from long double to double or float, or from double to float, except 366 // where the source is a constant expression and the actual value after 367 // conversion is within the range of values that can be represented (even 368 // if it cannot be represented exactly), or 369 case ICK_Floating_Conversion: 370 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 371 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 372 // FromType is larger than ToType. 373 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 374 375 // If it's value-dependent, we can't tell whether it's narrowing. 376 if (Initializer->isValueDependent()) 377 return NK_Dependent_Narrowing; 378 379 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 380 // Constant! 381 assert(ConstantValue.isFloat()); 382 llvm::APFloat FloatVal = ConstantValue.getFloat(); 383 // Convert the source value into the target type. 384 bool ignored; 385 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 386 Ctx.getFloatTypeSemantics(ToType), 387 llvm::APFloat::rmNearestTiesToEven, &ignored); 388 // If there was no overflow, the source value is within the range of 389 // values that can be represented. 390 if (ConvertStatus & llvm::APFloat::opOverflow) { 391 ConstantType = Initializer->getType(); 392 return NK_Constant_Narrowing; 393 } 394 } else { 395 return NK_Variable_Narrowing; 396 } 397 } 398 return NK_Not_Narrowing; 399 400 // -- from an integer type or unscoped enumeration type to an integer type 401 // that cannot represent all the values of the original type, except where 402 // the source is a constant expression and the actual value after 403 // conversion will fit into the target type and will produce the original 404 // value when converted back to the original type. 405 case ICK_Integral_Conversion: 406 IntegralConversion: { 407 assert(FromType->isIntegralOrUnscopedEnumerationType()); 408 assert(ToType->isIntegralOrUnscopedEnumerationType()); 409 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 410 const unsigned FromWidth = Ctx.getIntWidth(FromType); 411 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 412 const unsigned ToWidth = Ctx.getIntWidth(ToType); 413 414 if (FromWidth > ToWidth || 415 (FromWidth == ToWidth && FromSigned != ToSigned) || 416 (FromSigned && !ToSigned)) { 417 // Not all values of FromType can be represented in ToType. 418 llvm::APSInt InitializerValue; 419 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 420 421 // If it's value-dependent, we can't tell whether it's narrowing. 422 if (Initializer->isValueDependent()) 423 return NK_Dependent_Narrowing; 424 425 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 426 // Such conversions on variables are always narrowing. 427 return NK_Variable_Narrowing; 428 } 429 bool Narrowing = false; 430 if (FromWidth < ToWidth) { 431 // Negative -> unsigned is narrowing. Otherwise, more bits is never 432 // narrowing. 433 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 434 Narrowing = true; 435 } else { 436 // Add a bit to the InitializerValue so we don't have to worry about 437 // signed vs. unsigned comparisons. 438 InitializerValue = InitializerValue.extend( 439 InitializerValue.getBitWidth() + 1); 440 // Convert the initializer to and from the target width and signed-ness. 441 llvm::APSInt ConvertedValue = InitializerValue; 442 ConvertedValue = ConvertedValue.trunc(ToWidth); 443 ConvertedValue.setIsSigned(ToSigned); 444 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 445 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 446 // If the result is different, this was a narrowing conversion. 447 if (ConvertedValue != InitializerValue) 448 Narrowing = true; 449 } 450 if (Narrowing) { 451 ConstantType = Initializer->getType(); 452 ConstantValue = APValue(InitializerValue); 453 return NK_Constant_Narrowing; 454 } 455 } 456 return NK_Not_Narrowing; 457 } 458 459 default: 460 // Other kinds of conversions are not narrowings. 461 return NK_Not_Narrowing; 462 } 463 } 464 465 /// dump - Print this standard conversion sequence to standard 466 /// error. Useful for debugging overloading issues. 467 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 468 raw_ostream &OS = llvm::errs(); 469 bool PrintedSomething = false; 470 if (First != ICK_Identity) { 471 OS << GetImplicitConversionName(First); 472 PrintedSomething = true; 473 } 474 475 if (Second != ICK_Identity) { 476 if (PrintedSomething) { 477 OS << " -> "; 478 } 479 OS << GetImplicitConversionName(Second); 480 481 if (CopyConstructor) { 482 OS << " (by copy constructor)"; 483 } else if (DirectBinding) { 484 OS << " (direct reference binding)"; 485 } else if (ReferenceBinding) { 486 OS << " (reference binding)"; 487 } 488 PrintedSomething = true; 489 } 490 491 if (Third != ICK_Identity) { 492 if (PrintedSomething) { 493 OS << " -> "; 494 } 495 OS << GetImplicitConversionName(Third); 496 PrintedSomething = true; 497 } 498 499 if (!PrintedSomething) { 500 OS << "No conversions required"; 501 } 502 } 503 504 /// dump - Print this user-defined conversion sequence to standard 505 /// error. Useful for debugging overloading issues. 506 void UserDefinedConversionSequence::dump() const { 507 raw_ostream &OS = llvm::errs(); 508 if (Before.First || Before.Second || Before.Third) { 509 Before.dump(); 510 OS << " -> "; 511 } 512 if (ConversionFunction) 513 OS << '\'' << *ConversionFunction << '\''; 514 else 515 OS << "aggregate initialization"; 516 if (After.First || After.Second || After.Third) { 517 OS << " -> "; 518 After.dump(); 519 } 520 } 521 522 /// dump - Print this implicit conversion sequence to standard 523 /// error. Useful for debugging overloading issues. 524 void ImplicitConversionSequence::dump() const { 525 raw_ostream &OS = llvm::errs(); 526 if (isStdInitializerListElement()) 527 OS << "Worst std::initializer_list element conversion: "; 528 switch (ConversionKind) { 529 case StandardConversion: 530 OS << "Standard conversion: "; 531 Standard.dump(); 532 break; 533 case UserDefinedConversion: 534 OS << "User-defined conversion: "; 535 UserDefined.dump(); 536 break; 537 case EllipsisConversion: 538 OS << "Ellipsis conversion"; 539 break; 540 case AmbiguousConversion: 541 OS << "Ambiguous conversion"; 542 break; 543 case BadConversion: 544 OS << "Bad conversion"; 545 break; 546 } 547 548 OS << "\n"; 549 } 550 551 void AmbiguousConversionSequence::construct() { 552 new (&conversions()) ConversionSet(); 553 } 554 555 void AmbiguousConversionSequence::destruct() { 556 conversions().~ConversionSet(); 557 } 558 559 void 560 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 561 FromTypePtr = O.FromTypePtr; 562 ToTypePtr = O.ToTypePtr; 563 new (&conversions()) ConversionSet(O.conversions()); 564 } 565 566 namespace { 567 // Structure used by DeductionFailureInfo to store 568 // template argument information. 569 struct DFIArguments { 570 TemplateArgument FirstArg; 571 TemplateArgument SecondArg; 572 }; 573 // Structure used by DeductionFailureInfo to store 574 // template parameter and template argument information. 575 struct DFIParamWithArguments : DFIArguments { 576 TemplateParameter Param; 577 }; 578 // Structure used by DeductionFailureInfo to store template argument 579 // information and the index of the problematic call argument. 580 struct DFIDeducedMismatchArgs : DFIArguments { 581 TemplateArgumentList *TemplateArgs; 582 unsigned CallArgIndex; 583 }; 584 } 585 586 /// Convert from Sema's representation of template deduction information 587 /// to the form used in overload-candidate information. 588 DeductionFailureInfo 589 clang::MakeDeductionFailureInfo(ASTContext &Context, 590 Sema::TemplateDeductionResult TDK, 591 TemplateDeductionInfo &Info) { 592 DeductionFailureInfo Result; 593 Result.Result = static_cast<unsigned>(TDK); 594 Result.HasDiagnostic = false; 595 switch (TDK) { 596 case Sema::TDK_Invalid: 597 case Sema::TDK_InstantiationDepth: 598 case Sema::TDK_TooManyArguments: 599 case Sema::TDK_TooFewArguments: 600 case Sema::TDK_MiscellaneousDeductionFailure: 601 case Sema::TDK_CUDATargetMismatch: 602 Result.Data = nullptr; 603 break; 604 605 case Sema::TDK_Incomplete: 606 case Sema::TDK_InvalidExplicitArguments: 607 Result.Data = Info.Param.getOpaqueValue(); 608 break; 609 610 case Sema::TDK_DeducedMismatch: 611 case Sema::TDK_DeducedMismatchNested: { 612 // FIXME: Should allocate from normal heap so that we can free this later. 613 auto *Saved = new (Context) DFIDeducedMismatchArgs; 614 Saved->FirstArg = Info.FirstArg; 615 Saved->SecondArg = Info.SecondArg; 616 Saved->TemplateArgs = Info.take(); 617 Saved->CallArgIndex = Info.CallArgIndex; 618 Result.Data = Saved; 619 break; 620 } 621 622 case Sema::TDK_NonDeducedMismatch: { 623 // FIXME: Should allocate from normal heap so that we can free this later. 624 DFIArguments *Saved = new (Context) DFIArguments; 625 Saved->FirstArg = Info.FirstArg; 626 Saved->SecondArg = Info.SecondArg; 627 Result.Data = Saved; 628 break; 629 } 630 631 case Sema::TDK_IncompletePack: 632 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this. 633 case Sema::TDK_Inconsistent: 634 case Sema::TDK_Underqualified: { 635 // FIXME: Should allocate from normal heap so that we can free this later. 636 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 637 Saved->Param = Info.Param; 638 Saved->FirstArg = Info.FirstArg; 639 Saved->SecondArg = Info.SecondArg; 640 Result.Data = Saved; 641 break; 642 } 643 644 case Sema::TDK_SubstitutionFailure: 645 Result.Data = Info.take(); 646 if (Info.hasSFINAEDiagnostic()) { 647 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 648 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 649 Info.takeSFINAEDiagnostic(*Diag); 650 Result.HasDiagnostic = true; 651 } 652 break; 653 654 case Sema::TDK_Success: 655 case Sema::TDK_NonDependentConversionFailure: 656 llvm_unreachable("not a deduction failure"); 657 } 658 659 return Result; 660 } 661 662 void DeductionFailureInfo::Destroy() { 663 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 664 case Sema::TDK_Success: 665 case Sema::TDK_Invalid: 666 case Sema::TDK_InstantiationDepth: 667 case Sema::TDK_Incomplete: 668 case Sema::TDK_TooManyArguments: 669 case Sema::TDK_TooFewArguments: 670 case Sema::TDK_InvalidExplicitArguments: 671 case Sema::TDK_CUDATargetMismatch: 672 case Sema::TDK_NonDependentConversionFailure: 673 break; 674 675 case Sema::TDK_IncompletePack: 676 case Sema::TDK_Inconsistent: 677 case Sema::TDK_Underqualified: 678 case Sema::TDK_DeducedMismatch: 679 case Sema::TDK_DeducedMismatchNested: 680 case Sema::TDK_NonDeducedMismatch: 681 // FIXME: Destroy the data? 682 Data = nullptr; 683 break; 684 685 case Sema::TDK_SubstitutionFailure: 686 // FIXME: Destroy the template argument list? 687 Data = nullptr; 688 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 689 Diag->~PartialDiagnosticAt(); 690 HasDiagnostic = false; 691 } 692 break; 693 694 // Unhandled 695 case Sema::TDK_MiscellaneousDeductionFailure: 696 break; 697 } 698 } 699 700 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 701 if (HasDiagnostic) 702 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 703 return nullptr; 704 } 705 706 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 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_TooManyArguments: 712 case Sema::TDK_TooFewArguments: 713 case Sema::TDK_SubstitutionFailure: 714 case Sema::TDK_DeducedMismatch: 715 case Sema::TDK_DeducedMismatchNested: 716 case Sema::TDK_NonDeducedMismatch: 717 case Sema::TDK_CUDATargetMismatch: 718 case Sema::TDK_NonDependentConversionFailure: 719 return TemplateParameter(); 720 721 case Sema::TDK_Incomplete: 722 case Sema::TDK_InvalidExplicitArguments: 723 return TemplateParameter::getFromOpaqueValue(Data); 724 725 case Sema::TDK_IncompletePack: 726 case Sema::TDK_Inconsistent: 727 case Sema::TDK_Underqualified: 728 return static_cast<DFIParamWithArguments*>(Data)->Param; 729 730 // Unhandled 731 case Sema::TDK_MiscellaneousDeductionFailure: 732 break; 733 } 734 735 return TemplateParameter(); 736 } 737 738 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 739 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 740 case Sema::TDK_Success: 741 case Sema::TDK_Invalid: 742 case Sema::TDK_InstantiationDepth: 743 case Sema::TDK_TooManyArguments: 744 case Sema::TDK_TooFewArguments: 745 case Sema::TDK_Incomplete: 746 case Sema::TDK_IncompletePack: 747 case Sema::TDK_InvalidExplicitArguments: 748 case Sema::TDK_Inconsistent: 749 case Sema::TDK_Underqualified: 750 case Sema::TDK_NonDeducedMismatch: 751 case Sema::TDK_CUDATargetMismatch: 752 case Sema::TDK_NonDependentConversionFailure: 753 return nullptr; 754 755 case Sema::TDK_DeducedMismatch: 756 case Sema::TDK_DeducedMismatchNested: 757 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 758 759 case Sema::TDK_SubstitutionFailure: 760 return static_cast<TemplateArgumentList*>(Data); 761 762 // Unhandled 763 case Sema::TDK_MiscellaneousDeductionFailure: 764 break; 765 } 766 767 return nullptr; 768 } 769 770 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 771 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 772 case Sema::TDK_Success: 773 case Sema::TDK_Invalid: 774 case Sema::TDK_InstantiationDepth: 775 case Sema::TDK_Incomplete: 776 case Sema::TDK_TooManyArguments: 777 case Sema::TDK_TooFewArguments: 778 case Sema::TDK_InvalidExplicitArguments: 779 case Sema::TDK_SubstitutionFailure: 780 case Sema::TDK_CUDATargetMismatch: 781 case Sema::TDK_NonDependentConversionFailure: 782 return nullptr; 783 784 case Sema::TDK_IncompletePack: 785 case Sema::TDK_Inconsistent: 786 case Sema::TDK_Underqualified: 787 case Sema::TDK_DeducedMismatch: 788 case Sema::TDK_DeducedMismatchNested: 789 case Sema::TDK_NonDeducedMismatch: 790 return &static_cast<DFIArguments*>(Data)->FirstArg; 791 792 // Unhandled 793 case Sema::TDK_MiscellaneousDeductionFailure: 794 break; 795 } 796 797 return nullptr; 798 } 799 800 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 801 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 802 case Sema::TDK_Success: 803 case Sema::TDK_Invalid: 804 case Sema::TDK_InstantiationDepth: 805 case Sema::TDK_Incomplete: 806 case Sema::TDK_IncompletePack: 807 case Sema::TDK_TooManyArguments: 808 case Sema::TDK_TooFewArguments: 809 case Sema::TDK_InvalidExplicitArguments: 810 case Sema::TDK_SubstitutionFailure: 811 case Sema::TDK_CUDATargetMismatch: 812 case Sema::TDK_NonDependentConversionFailure: 813 return nullptr; 814 815 case Sema::TDK_Inconsistent: 816 case Sema::TDK_Underqualified: 817 case Sema::TDK_DeducedMismatch: 818 case Sema::TDK_DeducedMismatchNested: 819 case Sema::TDK_NonDeducedMismatch: 820 return &static_cast<DFIArguments*>(Data)->SecondArg; 821 822 // Unhandled 823 case Sema::TDK_MiscellaneousDeductionFailure: 824 break; 825 } 826 827 return nullptr; 828 } 829 830 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 831 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 832 case Sema::TDK_DeducedMismatch: 833 case Sema::TDK_DeducedMismatchNested: 834 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 835 836 default: 837 return llvm::None; 838 } 839 } 840 841 void OverloadCandidateSet::destroyCandidates() { 842 for (iterator i = begin(), e = end(); i != e; ++i) { 843 for (auto &C : i->Conversions) 844 C.~ImplicitConversionSequence(); 845 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 846 i->DeductionFailure.Destroy(); 847 } 848 } 849 850 void OverloadCandidateSet::clear(CandidateSetKind CSK) { 851 destroyCandidates(); 852 SlabAllocator.Reset(); 853 NumInlineBytesUsed = 0; 854 Candidates.clear(); 855 Functions.clear(); 856 Kind = CSK; 857 } 858 859 namespace { 860 class UnbridgedCastsSet { 861 struct Entry { 862 Expr **Addr; 863 Expr *Saved; 864 }; 865 SmallVector<Entry, 2> Entries; 866 867 public: 868 void save(Sema &S, Expr *&E) { 869 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 870 Entry entry = { &E, E }; 871 Entries.push_back(entry); 872 E = S.stripARCUnbridgedCast(E); 873 } 874 875 void restore() { 876 for (SmallVectorImpl<Entry>::iterator 877 i = Entries.begin(), e = Entries.end(); i != e; ++i) 878 *i->Addr = i->Saved; 879 } 880 }; 881 } 882 883 /// checkPlaceholderForOverload - Do any interesting placeholder-like 884 /// preprocessing on the given expression. 885 /// 886 /// \param unbridgedCasts a collection to which to add unbridged casts; 887 /// without this, they will be immediately diagnosed as errors 888 /// 889 /// Return true on unrecoverable error. 890 static bool 891 checkPlaceholderForOverload(Sema &S, Expr *&E, 892 UnbridgedCastsSet *unbridgedCasts = nullptr) { 893 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 894 // We can't handle overloaded expressions here because overload 895 // resolution might reasonably tweak them. 896 if (placeholder->getKind() == BuiltinType::Overload) return false; 897 898 // If the context potentially accepts unbridged ARC casts, strip 899 // the unbridged cast and add it to the collection for later restoration. 900 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 901 unbridgedCasts) { 902 unbridgedCasts->save(S, E); 903 return false; 904 } 905 906 // Go ahead and check everything else. 907 ExprResult result = S.CheckPlaceholderExpr(E); 908 if (result.isInvalid()) 909 return true; 910 911 E = result.get(); 912 return false; 913 } 914 915 // Nothing to do. 916 return false; 917 } 918 919 /// checkArgPlaceholdersForOverload - Check a set of call operands for 920 /// placeholders. 921 static bool checkArgPlaceholdersForOverload(Sema &S, 922 MultiExprArg Args, 923 UnbridgedCastsSet &unbridged) { 924 for (unsigned i = 0, e = Args.size(); i != e; ++i) 925 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 926 return true; 927 928 return false; 929 } 930 931 /// Determine whether the given New declaration is an overload of the 932 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if 933 /// New and Old cannot be overloaded, e.g., if New has the same signature as 934 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't 935 /// functions (or function templates) at all. When it does return Ovl_Match or 936 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be 937 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying 938 /// declaration. 939 /// 940 /// Example: Given the following input: 941 /// 942 /// void f(int, float); // #1 943 /// void f(int, int); // #2 944 /// int f(int, int); // #3 945 /// 946 /// When we process #1, there is no previous declaration of "f", so IsOverload 947 /// will not be used. 948 /// 949 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing 950 /// the parameter types, we see that #1 and #2 are overloaded (since they have 951 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is 952 /// unchanged. 953 /// 954 /// When we process #3, Old is an overload set containing #1 and #2. We compare 955 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then 956 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of 957 /// functions are not part of the signature), IsOverload returns Ovl_Match and 958 /// MatchedDecl will be set to point to the FunctionDecl for #2. 959 /// 960 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class 961 /// by a using declaration. The rules for whether to hide shadow declarations 962 /// ignore some properties which otherwise figure into a function template's 963 /// signature. 964 Sema::OverloadKind 965 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 966 NamedDecl *&Match, bool NewIsUsingDecl) { 967 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 968 I != E; ++I) { 969 NamedDecl *OldD = *I; 970 971 bool OldIsUsingDecl = false; 972 if (isa<UsingShadowDecl>(OldD)) { 973 OldIsUsingDecl = true; 974 975 // We can always introduce two using declarations into the same 976 // context, even if they have identical signatures. 977 if (NewIsUsingDecl) continue; 978 979 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 980 } 981 982 // A using-declaration does not conflict with another declaration 983 // if one of them is hidden. 984 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 985 continue; 986 987 // If either declaration was introduced by a using declaration, 988 // we'll need to use slightly different rules for matching. 989 // Essentially, these rules are the normal rules, except that 990 // function templates hide function templates with different 991 // return types or template parameter lists. 992 bool UseMemberUsingDeclRules = 993 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 994 !New->getFriendObjectKind(); 995 996 if (FunctionDecl *OldF = OldD->getAsFunction()) { 997 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 998 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 999 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 1000 continue; 1001 } 1002 1003 if (!isa<FunctionTemplateDecl>(OldD) && 1004 !shouldLinkPossiblyHiddenDecl(*I, New)) 1005 continue; 1006 1007 Match = *I; 1008 return Ovl_Match; 1009 } 1010 1011 // Builtins that have custom typechecking or have a reference should 1012 // not be overloadable or redeclarable. 1013 if (!getASTContext().canBuiltinBeRedeclared(OldF)) { 1014 Match = *I; 1015 return Ovl_NonFunction; 1016 } 1017 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 1018 // We can overload with these, which can show up when doing 1019 // redeclaration checks for UsingDecls. 1020 assert(Old.getLookupKind() == LookupUsingDeclName); 1021 } else if (isa<TagDecl>(OldD)) { 1022 // We can always overload with tags by hiding them. 1023 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 1024 // Optimistically assume that an unresolved using decl will 1025 // overload; if it doesn't, we'll have to diagnose during 1026 // template instantiation. 1027 // 1028 // Exception: if the scope is dependent and this is not a class 1029 // member, the using declaration can only introduce an enumerator. 1030 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 1031 Match = *I; 1032 return Ovl_NonFunction; 1033 } 1034 } else { 1035 // (C++ 13p1): 1036 // Only function declarations can be overloaded; object and type 1037 // declarations cannot be overloaded. 1038 Match = *I; 1039 return Ovl_NonFunction; 1040 } 1041 } 1042 1043 // C++ [temp.friend]p1: 1044 // For a friend function declaration that is not a template declaration: 1045 // -- if the name of the friend is a qualified or unqualified template-id, 1046 // [...], otherwise 1047 // -- if the name of the friend is a qualified-id and a matching 1048 // non-template function is found in the specified class or namespace, 1049 // the friend declaration refers to that function, otherwise, 1050 // -- if the name of the friend is a qualified-id and a matching function 1051 // template is found in the specified class or namespace, the friend 1052 // declaration refers to the deduced specialization of that function 1053 // template, otherwise 1054 // -- the name shall be an unqualified-id [...] 1055 // If we get here for a qualified friend declaration, we've just reached the 1056 // third bullet. If the type of the friend is dependent, skip this lookup 1057 // until instantiation. 1058 if (New->getFriendObjectKind() && New->getQualifier() && 1059 !New->getDependentSpecializationInfo() && 1060 !New->getType()->isDependentType()) { 1061 LookupResult TemplateSpecResult(LookupResult::Temporary, Old); 1062 TemplateSpecResult.addAllDecls(Old); 1063 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult, 1064 /*QualifiedFriend*/true)) { 1065 New->setInvalidDecl(); 1066 return Ovl_Overload; 1067 } 1068 1069 Match = TemplateSpecResult.getAsSingle<FunctionDecl>(); 1070 return Ovl_Match; 1071 } 1072 1073 return Ovl_Overload; 1074 } 1075 1076 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1077 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1078 // C++ [basic.start.main]p2: This function shall not be overloaded. 1079 if (New->isMain()) 1080 return false; 1081 1082 // MSVCRT user defined entry points cannot be overloaded. 1083 if (New->isMSVCRTEntryPoint()) 1084 return false; 1085 1086 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1087 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1088 1089 // C++ [temp.fct]p2: 1090 // A function template can be overloaded with other function templates 1091 // and with normal (non-template) functions. 1092 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1093 return true; 1094 1095 // Is the function New an overload of the function Old? 1096 QualType OldQType = Context.getCanonicalType(Old->getType()); 1097 QualType NewQType = Context.getCanonicalType(New->getType()); 1098 1099 // Compare the signatures (C++ 1.3.10) of the two functions to 1100 // determine whether they are overloads. If we find any mismatch 1101 // in the signature, they are overloads. 1102 1103 // If either of these functions is a K&R-style function (no 1104 // prototype), then we consider them to have matching signatures. 1105 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1106 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1107 return false; 1108 1109 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1110 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1111 1112 // The signature of a function includes the types of its 1113 // parameters (C++ 1.3.10), which includes the presence or absence 1114 // of the ellipsis; see C++ DR 357). 1115 if (OldQType != NewQType && 1116 (OldType->getNumParams() != NewType->getNumParams() || 1117 OldType->isVariadic() != NewType->isVariadic() || 1118 !FunctionParamTypesAreEqual(OldType, NewType))) 1119 return true; 1120 1121 // C++ [temp.over.link]p4: 1122 // The signature of a function template consists of its function 1123 // signature, its return type and its template parameter list. The names 1124 // of the template parameters are significant only for establishing the 1125 // relationship between the template parameters and the rest of the 1126 // signature. 1127 // 1128 // We check the return type and template parameter lists for function 1129 // templates first; the remaining checks follow. 1130 // 1131 // However, we don't consider either of these when deciding whether 1132 // a member introduced by a shadow declaration is hidden. 1133 if (!UseMemberUsingDeclRules && NewTemplate && 1134 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1135 OldTemplate->getTemplateParameters(), 1136 false, TPL_TemplateMatch) || 1137 !Context.hasSameType(Old->getDeclaredReturnType(), 1138 New->getDeclaredReturnType()))) 1139 return true; 1140 1141 // If the function is a class member, its signature includes the 1142 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1143 // 1144 // As part of this, also check whether one of the member functions 1145 // is static, in which case they are not overloads (C++ 1146 // 13.1p2). While not part of the definition of the signature, 1147 // this check is important to determine whether these functions 1148 // can be overloaded. 1149 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1150 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1151 if (OldMethod && NewMethod && 1152 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1153 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1154 if (!UseMemberUsingDeclRules && 1155 (OldMethod->getRefQualifier() == RQ_None || 1156 NewMethod->getRefQualifier() == RQ_None)) { 1157 // C++0x [over.load]p2: 1158 // - Member function declarations with the same name and the same 1159 // parameter-type-list as well as member function template 1160 // declarations with the same name, the same parameter-type-list, and 1161 // the same template parameter lists cannot be overloaded if any of 1162 // them, but not all, have a ref-qualifier (8.3.5). 1163 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1164 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1165 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1166 } 1167 return true; 1168 } 1169 1170 // We may not have applied the implicit const for a constexpr member 1171 // function yet (because we haven't yet resolved whether this is a static 1172 // or non-static member function). Add it now, on the assumption that this 1173 // is a redeclaration of OldMethod. 1174 auto OldQuals = OldMethod->getMethodQualifiers(); 1175 auto NewQuals = NewMethod->getMethodQualifiers(); 1176 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1177 !isa<CXXConstructorDecl>(NewMethod)) 1178 NewQuals.addConst(); 1179 // We do not allow overloading based off of '__restrict'. 1180 OldQuals.removeRestrict(); 1181 NewQuals.removeRestrict(); 1182 if (OldQuals != NewQuals) 1183 return true; 1184 } 1185 1186 // Though pass_object_size is placed on parameters and takes an argument, we 1187 // consider it to be a function-level modifier for the sake of function 1188 // identity. Either the function has one or more parameters with 1189 // pass_object_size or it doesn't. 1190 if (functionHasPassObjectSizeParams(New) != 1191 functionHasPassObjectSizeParams(Old)) 1192 return true; 1193 1194 // enable_if attributes are an order-sensitive part of the signature. 1195 for (specific_attr_iterator<EnableIfAttr> 1196 NewI = New->specific_attr_begin<EnableIfAttr>(), 1197 NewE = New->specific_attr_end<EnableIfAttr>(), 1198 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1199 OldE = Old->specific_attr_end<EnableIfAttr>(); 1200 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1201 if (NewI == NewE || OldI == OldE) 1202 return true; 1203 llvm::FoldingSetNodeID NewID, OldID; 1204 NewI->getCond()->Profile(NewID, Context, true); 1205 OldI->getCond()->Profile(OldID, Context, true); 1206 if (NewID != OldID) 1207 return true; 1208 } 1209 1210 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1211 // Don't allow overloading of destructors. (In theory we could, but it 1212 // would be a giant change to clang.) 1213 if (isa<CXXDestructorDecl>(New)) 1214 return false; 1215 1216 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1217 OldTarget = IdentifyCUDATarget(Old); 1218 if (NewTarget == CFT_InvalidTarget) 1219 return false; 1220 1221 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1222 1223 // Allow overloading of functions with same signature and different CUDA 1224 // target attributes. 1225 return NewTarget != OldTarget; 1226 } 1227 1228 // The signatures match; this is not an overload. 1229 return false; 1230 } 1231 1232 /// Checks availability of the function depending on the current 1233 /// function context. Inside an unavailable function, unavailability is ignored. 1234 /// 1235 /// \returns true if \arg FD is unavailable and current context is inside 1236 /// an available function, false otherwise. 1237 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1238 if (!FD->isUnavailable()) 1239 return false; 1240 1241 // Walk up the context of the caller. 1242 Decl *C = cast<Decl>(CurContext); 1243 do { 1244 if (C->isUnavailable()) 1245 return false; 1246 } while ((C = cast_or_null<Decl>(C->getDeclContext()))); 1247 return true; 1248 } 1249 1250 /// Tries a user-defined conversion from From to ToType. 1251 /// 1252 /// Produces an implicit conversion sequence for when a standard conversion 1253 /// is not an option. See TryImplicitConversion for more information. 1254 static ImplicitConversionSequence 1255 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1256 bool SuppressUserConversions, 1257 bool AllowExplicit, 1258 bool InOverloadResolution, 1259 bool CStyle, 1260 bool AllowObjCWritebackConversion, 1261 bool AllowObjCConversionOnExplicit) { 1262 ImplicitConversionSequence ICS; 1263 1264 if (SuppressUserConversions) { 1265 // We're not in the case above, so there is no conversion that 1266 // we can perform. 1267 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1268 return ICS; 1269 } 1270 1271 // Attempt user-defined conversion. 1272 OverloadCandidateSet Conversions(From->getExprLoc(), 1273 OverloadCandidateSet::CSK_Normal); 1274 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1275 Conversions, AllowExplicit, 1276 AllowObjCConversionOnExplicit)) { 1277 case OR_Success: 1278 case OR_Deleted: 1279 ICS.setUserDefined(); 1280 // C++ [over.ics.user]p4: 1281 // A conversion of an expression of class type to the same class 1282 // type is given Exact Match rank, and a conversion of an 1283 // expression of class type to a base class of that type is 1284 // given Conversion rank, in spite of the fact that a copy 1285 // constructor (i.e., a user-defined conversion function) is 1286 // called for those cases. 1287 if (CXXConstructorDecl *Constructor 1288 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1289 QualType FromCanon 1290 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1291 QualType ToCanon 1292 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1293 if (Constructor->isCopyConstructor() && 1294 (FromCanon == ToCanon || 1295 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) { 1296 // Turn this into a "standard" conversion sequence, so that it 1297 // gets ranked with standard conversion sequences. 1298 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1299 ICS.setStandard(); 1300 ICS.Standard.setAsIdentityConversion(); 1301 ICS.Standard.setFromType(From->getType()); 1302 ICS.Standard.setAllToTypes(ToType); 1303 ICS.Standard.CopyConstructor = Constructor; 1304 ICS.Standard.FoundCopyConstructor = Found; 1305 if (ToCanon != FromCanon) 1306 ICS.Standard.Second = ICK_Derived_To_Base; 1307 } 1308 } 1309 break; 1310 1311 case OR_Ambiguous: 1312 ICS.setAmbiguous(); 1313 ICS.Ambiguous.setFromType(From->getType()); 1314 ICS.Ambiguous.setToType(ToType); 1315 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1316 Cand != Conversions.end(); ++Cand) 1317 if (Cand->Viable) 1318 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1319 break; 1320 1321 // Fall through. 1322 case OR_No_Viable_Function: 1323 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1324 break; 1325 } 1326 1327 return ICS; 1328 } 1329 1330 /// TryImplicitConversion - Attempt to perform an implicit conversion 1331 /// from the given expression (Expr) to the given type (ToType). This 1332 /// function returns an implicit conversion sequence that can be used 1333 /// to perform the initialization. Given 1334 /// 1335 /// void f(float f); 1336 /// void g(int i) { f(i); } 1337 /// 1338 /// this routine would produce an implicit conversion sequence to 1339 /// describe the initialization of f from i, which will be a standard 1340 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1341 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1342 // 1343 /// Note that this routine only determines how the conversion can be 1344 /// performed; it does not actually perform the conversion. As such, 1345 /// it will not produce any diagnostics if no conversion is available, 1346 /// but will instead return an implicit conversion sequence of kind 1347 /// "BadConversion". 1348 /// 1349 /// If @p SuppressUserConversions, then user-defined conversions are 1350 /// not permitted. 1351 /// If @p AllowExplicit, then explicit user-defined conversions are 1352 /// permitted. 1353 /// 1354 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1355 /// writeback conversion, which allows __autoreleasing id* parameters to 1356 /// be initialized with __strong id* or __weak id* arguments. 1357 static ImplicitConversionSequence 1358 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1359 bool SuppressUserConversions, 1360 bool AllowExplicit, 1361 bool InOverloadResolution, 1362 bool CStyle, 1363 bool AllowObjCWritebackConversion, 1364 bool AllowObjCConversionOnExplicit) { 1365 ImplicitConversionSequence ICS; 1366 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1367 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1368 ICS.setStandard(); 1369 return ICS; 1370 } 1371 1372 if (!S.getLangOpts().CPlusPlus) { 1373 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1374 return ICS; 1375 } 1376 1377 // C++ [over.ics.user]p4: 1378 // A conversion of an expression of class type to the same class 1379 // type is given Exact Match rank, and a conversion of an 1380 // expression of class type to a base class of that type is 1381 // given Conversion rank, in spite of the fact that a copy/move 1382 // constructor (i.e., a user-defined conversion function) is 1383 // called for those cases. 1384 QualType FromType = From->getType(); 1385 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1386 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1387 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) { 1388 ICS.setStandard(); 1389 ICS.Standard.setAsIdentityConversion(); 1390 ICS.Standard.setFromType(FromType); 1391 ICS.Standard.setAllToTypes(ToType); 1392 1393 // We don't actually check at this point whether there is a valid 1394 // copy/move constructor, since overloading just assumes that it 1395 // exists. When we actually perform initialization, we'll find the 1396 // appropriate constructor to copy the returned object, if needed. 1397 ICS.Standard.CopyConstructor = nullptr; 1398 1399 // Determine whether this is considered a derived-to-base conversion. 1400 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1401 ICS.Standard.Second = ICK_Derived_To_Base; 1402 1403 return ICS; 1404 } 1405 1406 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1407 AllowExplicit, InOverloadResolution, CStyle, 1408 AllowObjCWritebackConversion, 1409 AllowObjCConversionOnExplicit); 1410 } 1411 1412 ImplicitConversionSequence 1413 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1414 bool SuppressUserConversions, 1415 bool AllowExplicit, 1416 bool InOverloadResolution, 1417 bool CStyle, 1418 bool AllowObjCWritebackConversion) { 1419 return ::TryImplicitConversion(*this, From, ToType, 1420 SuppressUserConversions, AllowExplicit, 1421 InOverloadResolution, CStyle, 1422 AllowObjCWritebackConversion, 1423 /*AllowObjCConversionOnExplicit=*/false); 1424 } 1425 1426 /// PerformImplicitConversion - Perform an implicit conversion of the 1427 /// expression From to the type ToType. Returns the 1428 /// converted expression. Flavor is the kind of conversion we're 1429 /// performing, used in the error message. If @p AllowExplicit, 1430 /// explicit user-defined conversions are permitted. 1431 ExprResult 1432 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1433 AssignmentAction Action, bool AllowExplicit) { 1434 ImplicitConversionSequence ICS; 1435 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1436 } 1437 1438 ExprResult 1439 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1440 AssignmentAction Action, bool AllowExplicit, 1441 ImplicitConversionSequence& ICS) { 1442 if (checkPlaceholderForOverload(*this, From)) 1443 return ExprError(); 1444 1445 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1446 bool AllowObjCWritebackConversion 1447 = getLangOpts().ObjCAutoRefCount && 1448 (Action == AA_Passing || Action == AA_Sending); 1449 if (getLangOpts().ObjC) 1450 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType, 1451 From->getType(), From); 1452 ICS = ::TryImplicitConversion(*this, From, ToType, 1453 /*SuppressUserConversions=*/false, 1454 AllowExplicit, 1455 /*InOverloadResolution=*/false, 1456 /*CStyle=*/false, 1457 AllowObjCWritebackConversion, 1458 /*AllowObjCConversionOnExplicit=*/false); 1459 return PerformImplicitConversion(From, ToType, ICS, Action); 1460 } 1461 1462 /// Determine whether the conversion from FromType to ToType is a valid 1463 /// conversion that strips "noexcept" or "noreturn" off the nested function 1464 /// type. 1465 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1466 QualType &ResultTy) { 1467 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1468 return false; 1469 1470 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1471 // or F(t noexcept) -> F(t) 1472 // where F adds one of the following at most once: 1473 // - a pointer 1474 // - a member pointer 1475 // - a block pointer 1476 // Changes here need matching changes in FindCompositePointerType. 1477 CanQualType CanTo = Context.getCanonicalType(ToType); 1478 CanQualType CanFrom = Context.getCanonicalType(FromType); 1479 Type::TypeClass TyClass = CanTo->getTypeClass(); 1480 if (TyClass != CanFrom->getTypeClass()) return false; 1481 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1482 if (TyClass == Type::Pointer) { 1483 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1484 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1485 } else if (TyClass == Type::BlockPointer) { 1486 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1487 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1488 } else if (TyClass == Type::MemberPointer) { 1489 auto ToMPT = CanTo.getAs<MemberPointerType>(); 1490 auto FromMPT = CanFrom.getAs<MemberPointerType>(); 1491 // A function pointer conversion cannot change the class of the function. 1492 if (ToMPT->getClass() != FromMPT->getClass()) 1493 return false; 1494 CanTo = ToMPT->getPointeeType(); 1495 CanFrom = FromMPT->getPointeeType(); 1496 } else { 1497 return false; 1498 } 1499 1500 TyClass = CanTo->getTypeClass(); 1501 if (TyClass != CanFrom->getTypeClass()) return false; 1502 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1503 return false; 1504 } 1505 1506 const auto *FromFn = cast<FunctionType>(CanFrom); 1507 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1508 1509 const auto *ToFn = cast<FunctionType>(CanTo); 1510 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1511 1512 bool Changed = false; 1513 1514 // Drop 'noreturn' if not present in target type. 1515 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1516 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1517 Changed = true; 1518 } 1519 1520 // Drop 'noexcept' if not present in target type. 1521 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1522 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1523 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) { 1524 FromFn = cast<FunctionType>( 1525 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0), 1526 EST_None) 1527 .getTypePtr()); 1528 Changed = true; 1529 } 1530 1531 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid 1532 // only if the ExtParameterInfo lists of the two function prototypes can be 1533 // merged and the merged list is identical to ToFPT's ExtParameterInfo list. 1534 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 1535 bool CanUseToFPT, CanUseFromFPT; 1536 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT, 1537 CanUseFromFPT, NewParamInfos) && 1538 CanUseToFPT && !CanUseFromFPT) { 1539 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo(); 1540 ExtInfo.ExtParameterInfos = 1541 NewParamInfos.empty() ? nullptr : NewParamInfos.data(); 1542 QualType QT = Context.getFunctionType(FromFPT->getReturnType(), 1543 FromFPT->getParamTypes(), ExtInfo); 1544 FromFn = QT->getAs<FunctionType>(); 1545 Changed = true; 1546 } 1547 } 1548 1549 if (!Changed) 1550 return false; 1551 1552 assert(QualType(FromFn, 0).isCanonical()); 1553 if (QualType(FromFn, 0) != CanTo) return false; 1554 1555 ResultTy = ToType; 1556 return true; 1557 } 1558 1559 /// Determine whether the conversion from FromType to ToType is a valid 1560 /// vector conversion. 1561 /// 1562 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1563 /// conversion. 1564 static bool IsVectorConversion(Sema &S, QualType FromType, 1565 QualType ToType, ImplicitConversionKind &ICK) { 1566 // We need at least one of these types to be a vector type to have a vector 1567 // conversion. 1568 if (!ToType->isVectorType() && !FromType->isVectorType()) 1569 return false; 1570 1571 // Identical types require no conversions. 1572 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1573 return false; 1574 1575 // There are no conversions between extended vector types, only identity. 1576 if (ToType->isExtVectorType()) { 1577 // There are no conversions between extended vector types other than the 1578 // identity conversion. 1579 if (FromType->isExtVectorType()) 1580 return false; 1581 1582 // Vector splat from any arithmetic type to a vector. 1583 if (FromType->isArithmeticType()) { 1584 ICK = ICK_Vector_Splat; 1585 return true; 1586 } 1587 } 1588 1589 // We can perform the conversion between vector types in the following cases: 1590 // 1)vector types are equivalent AltiVec and GCC vector types 1591 // 2)lax vector conversions are permitted and the vector types are of the 1592 // same size 1593 if (ToType->isVectorType() && FromType->isVectorType()) { 1594 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1595 S.isLaxVectorConversion(FromType, ToType)) { 1596 ICK = ICK_Vector_Conversion; 1597 return true; 1598 } 1599 } 1600 1601 return false; 1602 } 1603 1604 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1605 bool InOverloadResolution, 1606 StandardConversionSequence &SCS, 1607 bool CStyle); 1608 1609 /// IsStandardConversion - Determines whether there is a standard 1610 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1611 /// expression From to the type ToType. Standard conversion sequences 1612 /// only consider non-class types; for conversions that involve class 1613 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1614 /// contain the standard conversion sequence required to perform this 1615 /// conversion and this routine will return true. Otherwise, this 1616 /// routine will return false and the value of SCS is unspecified. 1617 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1618 bool InOverloadResolution, 1619 StandardConversionSequence &SCS, 1620 bool CStyle, 1621 bool AllowObjCWritebackConversion) { 1622 QualType FromType = From->getType(); 1623 1624 // Standard conversions (C++ [conv]) 1625 SCS.setAsIdentityConversion(); 1626 SCS.IncompatibleObjC = false; 1627 SCS.setFromType(FromType); 1628 SCS.CopyConstructor = nullptr; 1629 1630 // There are no standard conversions for class types in C++, so 1631 // abort early. When overloading in C, however, we do permit them. 1632 if (S.getLangOpts().CPlusPlus && 1633 (FromType->isRecordType() || ToType->isRecordType())) 1634 return false; 1635 1636 // The first conversion can be an lvalue-to-rvalue conversion, 1637 // array-to-pointer conversion, or function-to-pointer conversion 1638 // (C++ 4p1). 1639 1640 if (FromType == S.Context.OverloadTy) { 1641 DeclAccessPair AccessPair; 1642 if (FunctionDecl *Fn 1643 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1644 AccessPair)) { 1645 // We were able to resolve the address of the overloaded function, 1646 // so we can convert to the type of that function. 1647 FromType = Fn->getType(); 1648 SCS.setFromType(FromType); 1649 1650 // we can sometimes resolve &foo<int> regardless of ToType, so check 1651 // if the type matches (identity) or we are converting to bool 1652 if (!S.Context.hasSameUnqualifiedType( 1653 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1654 QualType resultTy; 1655 // if the function type matches except for [[noreturn]], it's ok 1656 if (!S.IsFunctionConversion(FromType, 1657 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1658 // otherwise, only a boolean conversion is standard 1659 if (!ToType->isBooleanType()) 1660 return false; 1661 } 1662 1663 // Check if the "from" expression is taking the address of an overloaded 1664 // function and recompute the FromType accordingly. Take advantage of the 1665 // fact that non-static member functions *must* have such an address-of 1666 // expression. 1667 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1668 if (Method && !Method->isStatic()) { 1669 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1670 "Non-unary operator on non-static member address"); 1671 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1672 == UO_AddrOf && 1673 "Non-address-of operator on non-static member address"); 1674 const Type *ClassType 1675 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1676 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1677 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1678 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1679 UO_AddrOf && 1680 "Non-address-of operator for overloaded function expression"); 1681 FromType = S.Context.getPointerType(FromType); 1682 } 1683 1684 // Check that we've computed the proper type after overload resolution. 1685 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1686 // be calling it from within an NDEBUG block. 1687 assert(S.Context.hasSameType( 1688 FromType, 1689 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1690 } else { 1691 return false; 1692 } 1693 } 1694 // Lvalue-to-rvalue conversion (C++11 4.1): 1695 // A glvalue (3.10) of a non-function, non-array type T can 1696 // be converted to a prvalue. 1697 bool argIsLValue = From->isGLValue(); 1698 if (argIsLValue && 1699 !FromType->isFunctionType() && !FromType->isArrayType() && 1700 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1701 SCS.First = ICK_Lvalue_To_Rvalue; 1702 1703 // C11 6.3.2.1p2: 1704 // ... if the lvalue has atomic type, the value has the non-atomic version 1705 // of the type of the lvalue ... 1706 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1707 FromType = Atomic->getValueType(); 1708 1709 // If T is a non-class type, the type of the rvalue is the 1710 // cv-unqualified version of T. Otherwise, the type of the rvalue 1711 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1712 // just strip the qualifiers because they don't matter. 1713 FromType = FromType.getUnqualifiedType(); 1714 } else if (FromType->isArrayType()) { 1715 // Array-to-pointer conversion (C++ 4.2) 1716 SCS.First = ICK_Array_To_Pointer; 1717 1718 // An lvalue or rvalue of type "array of N T" or "array of unknown 1719 // bound of T" can be converted to an rvalue of type "pointer to 1720 // T" (C++ 4.2p1). 1721 FromType = S.Context.getArrayDecayedType(FromType); 1722 1723 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1724 // This conversion is deprecated in C++03 (D.4) 1725 SCS.DeprecatedStringLiteralToCharPtr = true; 1726 1727 // For the purpose of ranking in overload resolution 1728 // (13.3.3.1.1), this conversion is considered an 1729 // array-to-pointer conversion followed by a qualification 1730 // conversion (4.4). (C++ 4.2p2) 1731 SCS.Second = ICK_Identity; 1732 SCS.Third = ICK_Qualification; 1733 SCS.QualificationIncludesObjCLifetime = false; 1734 SCS.setAllToTypes(FromType); 1735 return true; 1736 } 1737 } else if (FromType->isFunctionType() && argIsLValue) { 1738 // Function-to-pointer conversion (C++ 4.3). 1739 SCS.First = ICK_Function_To_Pointer; 1740 1741 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1742 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1743 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1744 return false; 1745 1746 // An lvalue of function type T can be converted to an rvalue of 1747 // type "pointer to T." The result is a pointer to the 1748 // function. (C++ 4.3p1). 1749 FromType = S.Context.getPointerType(FromType); 1750 } else { 1751 // We don't require any conversions for the first step. 1752 SCS.First = ICK_Identity; 1753 } 1754 SCS.setToType(0, FromType); 1755 1756 // The second conversion can be an integral promotion, floating 1757 // point promotion, integral conversion, floating point conversion, 1758 // floating-integral conversion, pointer conversion, 1759 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1760 // For overloading in C, this can also be a "compatible-type" 1761 // conversion. 1762 bool IncompatibleObjC = false; 1763 ImplicitConversionKind SecondICK = ICK_Identity; 1764 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1765 // The unqualified versions of the types are the same: there's no 1766 // conversion to do. 1767 SCS.Second = ICK_Identity; 1768 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1769 // Integral promotion (C++ 4.5). 1770 SCS.Second = ICK_Integral_Promotion; 1771 FromType = ToType.getUnqualifiedType(); 1772 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1773 // Floating point promotion (C++ 4.6). 1774 SCS.Second = ICK_Floating_Promotion; 1775 FromType = ToType.getUnqualifiedType(); 1776 } else if (S.IsComplexPromotion(FromType, ToType)) { 1777 // Complex promotion (Clang extension) 1778 SCS.Second = ICK_Complex_Promotion; 1779 FromType = ToType.getUnqualifiedType(); 1780 } else if (ToType->isBooleanType() && 1781 (FromType->isArithmeticType() || 1782 FromType->isAnyPointerType() || 1783 FromType->isBlockPointerType() || 1784 FromType->isMemberPointerType() || 1785 FromType->isNullPtrType())) { 1786 // Boolean conversions (C++ 4.12). 1787 SCS.Second = ICK_Boolean_Conversion; 1788 FromType = S.Context.BoolTy; 1789 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1790 ToType->isIntegralType(S.Context)) { 1791 // Integral conversions (C++ 4.7). 1792 SCS.Second = ICK_Integral_Conversion; 1793 FromType = ToType.getUnqualifiedType(); 1794 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1795 // Complex conversions (C99 6.3.1.6) 1796 SCS.Second = ICK_Complex_Conversion; 1797 FromType = ToType.getUnqualifiedType(); 1798 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1799 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1800 // Complex-real conversions (C99 6.3.1.7) 1801 SCS.Second = ICK_Complex_Real; 1802 FromType = ToType.getUnqualifiedType(); 1803 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1804 // FIXME: disable conversions between long double and __float128 if 1805 // their representation is different until there is back end support 1806 // We of course allow this conversion if long double is really double. 1807 if (&S.Context.getFloatTypeSemantics(FromType) != 1808 &S.Context.getFloatTypeSemantics(ToType)) { 1809 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1810 ToType == S.Context.LongDoubleTy) || 1811 (FromType == S.Context.LongDoubleTy && 1812 ToType == S.Context.Float128Ty)); 1813 if (Float128AndLongDouble && 1814 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) == 1815 &llvm::APFloat::PPCDoubleDouble())) 1816 return false; 1817 } 1818 // Floating point conversions (C++ 4.8). 1819 SCS.Second = ICK_Floating_Conversion; 1820 FromType = ToType.getUnqualifiedType(); 1821 } else if ((FromType->isRealFloatingType() && 1822 ToType->isIntegralType(S.Context)) || 1823 (FromType->isIntegralOrUnscopedEnumerationType() && 1824 ToType->isRealFloatingType())) { 1825 // Floating-integral conversions (C++ 4.9). 1826 SCS.Second = ICK_Floating_Integral; 1827 FromType = ToType.getUnqualifiedType(); 1828 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1829 SCS.Second = ICK_Block_Pointer_Conversion; 1830 } else if (AllowObjCWritebackConversion && 1831 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1832 SCS.Second = ICK_Writeback_Conversion; 1833 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1834 FromType, IncompatibleObjC)) { 1835 // Pointer conversions (C++ 4.10). 1836 SCS.Second = ICK_Pointer_Conversion; 1837 SCS.IncompatibleObjC = IncompatibleObjC; 1838 FromType = FromType.getUnqualifiedType(); 1839 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1840 InOverloadResolution, FromType)) { 1841 // Pointer to member conversions (4.11). 1842 SCS.Second = ICK_Pointer_Member; 1843 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1844 SCS.Second = SecondICK; 1845 FromType = ToType.getUnqualifiedType(); 1846 } else if (!S.getLangOpts().CPlusPlus && 1847 S.Context.typesAreCompatible(ToType, FromType)) { 1848 // Compatible conversions (Clang extension for C function overloading) 1849 SCS.Second = ICK_Compatible_Conversion; 1850 FromType = ToType.getUnqualifiedType(); 1851 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1852 InOverloadResolution, 1853 SCS, CStyle)) { 1854 SCS.Second = ICK_TransparentUnionConversion; 1855 FromType = ToType; 1856 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1857 CStyle)) { 1858 // tryAtomicConversion has updated the standard conversion sequence 1859 // appropriately. 1860 return true; 1861 } else if (ToType->isEventT() && 1862 From->isIntegerConstantExpr(S.getASTContext()) && 1863 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1864 SCS.Second = ICK_Zero_Event_Conversion; 1865 FromType = ToType; 1866 } else if (ToType->isQueueT() && 1867 From->isIntegerConstantExpr(S.getASTContext()) && 1868 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1869 SCS.Second = ICK_Zero_Queue_Conversion; 1870 FromType = ToType; 1871 } else { 1872 // No second conversion required. 1873 SCS.Second = ICK_Identity; 1874 } 1875 SCS.setToType(1, FromType); 1876 1877 // The third conversion can be a function pointer conversion or a 1878 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1879 bool ObjCLifetimeConversion; 1880 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1881 // Function pointer conversions (removing 'noexcept') including removal of 1882 // 'noreturn' (Clang extension). 1883 SCS.Third = ICK_Function_Conversion; 1884 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1885 ObjCLifetimeConversion)) { 1886 SCS.Third = ICK_Qualification; 1887 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1888 FromType = ToType; 1889 } else { 1890 // No conversion required 1891 SCS.Third = ICK_Identity; 1892 } 1893 1894 // C++ [over.best.ics]p6: 1895 // [...] Any difference in top-level cv-qualification is 1896 // subsumed by the initialization itself and does not constitute 1897 // a conversion. [...] 1898 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1899 QualType CanonTo = S.Context.getCanonicalType(ToType); 1900 if (CanonFrom.getLocalUnqualifiedType() 1901 == CanonTo.getLocalUnqualifiedType() && 1902 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1903 FromType = ToType; 1904 CanonFrom = CanonTo; 1905 } 1906 1907 SCS.setToType(2, FromType); 1908 1909 if (CanonFrom == CanonTo) 1910 return true; 1911 1912 // If we have not converted the argument type to the parameter type, 1913 // this is a bad conversion sequence, unless we're resolving an overload in C. 1914 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1915 return false; 1916 1917 ExprResult ER = ExprResult{From}; 1918 Sema::AssignConvertType Conv = 1919 S.CheckSingleAssignmentConstraints(ToType, ER, 1920 /*Diagnose=*/false, 1921 /*DiagnoseCFAudited=*/false, 1922 /*ConvertRHS=*/false); 1923 ImplicitConversionKind SecondConv; 1924 switch (Conv) { 1925 case Sema::Compatible: 1926 SecondConv = ICK_C_Only_Conversion; 1927 break; 1928 // For our purposes, discarding qualifiers is just as bad as using an 1929 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1930 // qualifiers, as well. 1931 case Sema::CompatiblePointerDiscardsQualifiers: 1932 case Sema::IncompatiblePointer: 1933 case Sema::IncompatiblePointerSign: 1934 SecondConv = ICK_Incompatible_Pointer_Conversion; 1935 break; 1936 default: 1937 return false; 1938 } 1939 1940 // First can only be an lvalue conversion, so we pretend that this was the 1941 // second conversion. First should already be valid from earlier in the 1942 // function. 1943 SCS.Second = SecondConv; 1944 SCS.setToType(1, ToType); 1945 1946 // Third is Identity, because Second should rank us worse than any other 1947 // conversion. This could also be ICK_Qualification, but it's simpler to just 1948 // lump everything in with the second conversion, and we don't gain anything 1949 // from making this ICK_Qualification. 1950 SCS.Third = ICK_Identity; 1951 SCS.setToType(2, ToType); 1952 return true; 1953 } 1954 1955 static bool 1956 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1957 QualType &ToType, 1958 bool InOverloadResolution, 1959 StandardConversionSequence &SCS, 1960 bool CStyle) { 1961 1962 const RecordType *UT = ToType->getAsUnionType(); 1963 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1964 return false; 1965 // The field to initialize within the transparent union. 1966 RecordDecl *UD = UT->getDecl(); 1967 // It's compatible if the expression matches any of the fields. 1968 for (const auto *it : UD->fields()) { 1969 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1970 CStyle, /*ObjCWritebackConversion=*/false)) { 1971 ToType = it->getType(); 1972 return true; 1973 } 1974 } 1975 return false; 1976 } 1977 1978 /// IsIntegralPromotion - Determines whether the conversion from the 1979 /// expression From (whose potentially-adjusted type is FromType) to 1980 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1981 /// sets PromotedType to the promoted type. 1982 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1983 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1984 // All integers are built-in. 1985 if (!To) { 1986 return false; 1987 } 1988 1989 // An rvalue of type char, signed char, unsigned char, short int, or 1990 // unsigned short int can be converted to an rvalue of type int if 1991 // int can represent all the values of the source type; otherwise, 1992 // the source rvalue can be converted to an rvalue of type unsigned 1993 // int (C++ 4.5p1). 1994 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1995 !FromType->isEnumeralType()) { 1996 if (// We can promote any signed, promotable integer type to an int 1997 (FromType->isSignedIntegerType() || 1998 // We can promote any unsigned integer type whose size is 1999 // less than int to an int. 2000 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 2001 return To->getKind() == BuiltinType::Int; 2002 } 2003 2004 return To->getKind() == BuiltinType::UInt; 2005 } 2006 2007 // C++11 [conv.prom]p3: 2008 // A prvalue of an unscoped enumeration type whose underlying type is not 2009 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 2010 // following types that can represent all the values of the enumeration 2011 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 2012 // unsigned int, long int, unsigned long int, long long int, or unsigned 2013 // long long int. If none of the types in that list can represent all the 2014 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 2015 // type can be converted to an rvalue a prvalue of the extended integer type 2016 // with lowest integer conversion rank (4.13) greater than the rank of long 2017 // long in which all the values of the enumeration can be represented. If 2018 // there are two such extended types, the signed one is chosen. 2019 // C++11 [conv.prom]p4: 2020 // A prvalue of an unscoped enumeration type whose underlying type is fixed 2021 // can be converted to a prvalue of its underlying type. Moreover, if 2022 // integral promotion can be applied to its underlying type, a prvalue of an 2023 // unscoped enumeration type whose underlying type is fixed can also be 2024 // converted to a prvalue of the promoted underlying type. 2025 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 2026 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 2027 // provided for a scoped enumeration. 2028 if (FromEnumType->getDecl()->isScoped()) 2029 return false; 2030 2031 // We can perform an integral promotion to the underlying type of the enum, 2032 // even if that's not the promoted type. Note that the check for promoting 2033 // the underlying type is based on the type alone, and does not consider 2034 // the bitfield-ness of the actual source expression. 2035 if (FromEnumType->getDecl()->isFixed()) { 2036 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 2037 return Context.hasSameUnqualifiedType(Underlying, ToType) || 2038 IsIntegralPromotion(nullptr, Underlying, ToType); 2039 } 2040 2041 // We have already pre-calculated the promotion type, so this is trivial. 2042 if (ToType->isIntegerType() && 2043 isCompleteType(From->getBeginLoc(), FromType)) 2044 return Context.hasSameUnqualifiedType( 2045 ToType, FromEnumType->getDecl()->getPromotionType()); 2046 2047 // C++ [conv.prom]p5: 2048 // If the bit-field has an enumerated type, it is treated as any other 2049 // value of that type for promotion purposes. 2050 // 2051 // ... so do not fall through into the bit-field checks below in C++. 2052 if (getLangOpts().CPlusPlus) 2053 return false; 2054 } 2055 2056 // C++0x [conv.prom]p2: 2057 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 2058 // to an rvalue a prvalue of the first of the following types that can 2059 // represent all the values of its underlying type: int, unsigned int, 2060 // long int, unsigned long int, long long int, or unsigned long long int. 2061 // If none of the types in that list can represent all the values of its 2062 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 2063 // or wchar_t can be converted to an rvalue a prvalue of its underlying 2064 // type. 2065 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 2066 ToType->isIntegerType()) { 2067 // Determine whether the type we're converting from is signed or 2068 // unsigned. 2069 bool FromIsSigned = FromType->isSignedIntegerType(); 2070 uint64_t FromSize = Context.getTypeSize(FromType); 2071 2072 // The types we'll try to promote to, in the appropriate 2073 // order. Try each of these types. 2074 QualType PromoteTypes[6] = { 2075 Context.IntTy, Context.UnsignedIntTy, 2076 Context.LongTy, Context.UnsignedLongTy , 2077 Context.LongLongTy, Context.UnsignedLongLongTy 2078 }; 2079 for (int Idx = 0; Idx < 6; ++Idx) { 2080 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 2081 if (FromSize < ToSize || 2082 (FromSize == ToSize && 2083 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 2084 // We found the type that we can promote to. If this is the 2085 // type we wanted, we have a promotion. Otherwise, no 2086 // promotion. 2087 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2088 } 2089 } 2090 } 2091 2092 // An rvalue for an integral bit-field (9.6) can be converted to an 2093 // rvalue of type int if int can represent all the values of the 2094 // bit-field; otherwise, it can be converted to unsigned int if 2095 // unsigned int can represent all the values of the bit-field. If 2096 // the bit-field is larger yet, no integral promotion applies to 2097 // it. If the bit-field has an enumerated type, it is treated as any 2098 // other value of that type for promotion purposes (C++ 4.5p3). 2099 // FIXME: We should delay checking of bit-fields until we actually perform the 2100 // conversion. 2101 // 2102 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be 2103 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum 2104 // bit-fields and those whose underlying type is larger than int) for GCC 2105 // compatibility. 2106 if (From) { 2107 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2108 llvm::APSInt BitWidth; 2109 if (FromType->isIntegralType(Context) && 2110 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2111 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2112 ToSize = Context.getTypeSize(ToType); 2113 2114 // Are we promoting to an int from a bitfield that fits in an int? 2115 if (BitWidth < ToSize || 2116 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2117 return To->getKind() == BuiltinType::Int; 2118 } 2119 2120 // Are we promoting to an unsigned int from an unsigned bitfield 2121 // that fits into an unsigned int? 2122 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2123 return To->getKind() == BuiltinType::UInt; 2124 } 2125 2126 return false; 2127 } 2128 } 2129 } 2130 2131 // An rvalue of type bool can be converted to an rvalue of type int, 2132 // with false becoming zero and true becoming one (C++ 4.5p4). 2133 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2134 return true; 2135 } 2136 2137 return false; 2138 } 2139 2140 /// IsFloatingPointPromotion - Determines whether the conversion from 2141 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2142 /// returns true and sets PromotedType to the promoted type. 2143 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2144 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2145 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2146 /// An rvalue of type float can be converted to an rvalue of type 2147 /// double. (C++ 4.6p1). 2148 if (FromBuiltin->getKind() == BuiltinType::Float && 2149 ToBuiltin->getKind() == BuiltinType::Double) 2150 return true; 2151 2152 // C99 6.3.1.5p1: 2153 // When a float is promoted to double or long double, or a 2154 // double is promoted to long double [...]. 2155 if (!getLangOpts().CPlusPlus && 2156 (FromBuiltin->getKind() == BuiltinType::Float || 2157 FromBuiltin->getKind() == BuiltinType::Double) && 2158 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2159 ToBuiltin->getKind() == BuiltinType::Float128)) 2160 return true; 2161 2162 // Half can be promoted to float. 2163 if (!getLangOpts().NativeHalfType && 2164 FromBuiltin->getKind() == BuiltinType::Half && 2165 ToBuiltin->getKind() == BuiltinType::Float) 2166 return true; 2167 } 2168 2169 return false; 2170 } 2171 2172 /// Determine if a conversion is a complex promotion. 2173 /// 2174 /// A complex promotion is defined as a complex -> complex conversion 2175 /// where the conversion between the underlying real types is a 2176 /// floating-point or integral promotion. 2177 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2178 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2179 if (!FromComplex) 2180 return false; 2181 2182 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2183 if (!ToComplex) 2184 return false; 2185 2186 return IsFloatingPointPromotion(FromComplex->getElementType(), 2187 ToComplex->getElementType()) || 2188 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2189 ToComplex->getElementType()); 2190 } 2191 2192 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2193 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2194 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2195 /// if non-empty, will be a pointer to ToType that may or may not have 2196 /// the right set of qualifiers on its pointee. 2197 /// 2198 static QualType 2199 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2200 QualType ToPointee, QualType ToType, 2201 ASTContext &Context, 2202 bool StripObjCLifetime = false) { 2203 assert((FromPtr->getTypeClass() == Type::Pointer || 2204 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2205 "Invalid similarly-qualified pointer type"); 2206 2207 /// Conversions to 'id' subsume cv-qualifier conversions. 2208 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2209 return ToType.getUnqualifiedType(); 2210 2211 QualType CanonFromPointee 2212 = Context.getCanonicalType(FromPtr->getPointeeType()); 2213 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2214 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2215 2216 if (StripObjCLifetime) 2217 Quals.removeObjCLifetime(); 2218 2219 // Exact qualifier match -> return the pointer type we're converting to. 2220 if (CanonToPointee.getLocalQualifiers() == Quals) { 2221 // ToType is exactly what we need. Return it. 2222 if (!ToType.isNull()) 2223 return ToType.getUnqualifiedType(); 2224 2225 // Build a pointer to ToPointee. It has the right qualifiers 2226 // already. 2227 if (isa<ObjCObjectPointerType>(ToType)) 2228 return Context.getObjCObjectPointerType(ToPointee); 2229 return Context.getPointerType(ToPointee); 2230 } 2231 2232 // Just build a canonical type that has the right qualifiers. 2233 QualType QualifiedCanonToPointee 2234 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2235 2236 if (isa<ObjCObjectPointerType>(ToType)) 2237 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2238 return Context.getPointerType(QualifiedCanonToPointee); 2239 } 2240 2241 static bool isNullPointerConstantForConversion(Expr *Expr, 2242 bool InOverloadResolution, 2243 ASTContext &Context) { 2244 // Handle value-dependent integral null pointer constants correctly. 2245 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2246 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2247 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2248 return !InOverloadResolution; 2249 2250 return Expr->isNullPointerConstant(Context, 2251 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2252 : Expr::NPC_ValueDependentIsNull); 2253 } 2254 2255 /// IsPointerConversion - Determines whether the conversion of the 2256 /// expression From, which has the (possibly adjusted) type FromType, 2257 /// can be converted to the type ToType via a pointer conversion (C++ 2258 /// 4.10). If so, returns true and places the converted type (that 2259 /// might differ from ToType in its cv-qualifiers at some level) into 2260 /// ConvertedType. 2261 /// 2262 /// This routine also supports conversions to and from block pointers 2263 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2264 /// pointers to interfaces. FIXME: Once we've determined the 2265 /// appropriate overloading rules for Objective-C, we may want to 2266 /// split the Objective-C checks into a different routine; however, 2267 /// GCC seems to consider all of these conversions to be pointer 2268 /// conversions, so for now they live here. IncompatibleObjC will be 2269 /// set if the conversion is an allowed Objective-C conversion that 2270 /// should result in a warning. 2271 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2272 bool InOverloadResolution, 2273 QualType& ConvertedType, 2274 bool &IncompatibleObjC) { 2275 IncompatibleObjC = false; 2276 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2277 IncompatibleObjC)) 2278 return true; 2279 2280 // Conversion from a null pointer constant to any Objective-C pointer type. 2281 if (ToType->isObjCObjectPointerType() && 2282 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2283 ConvertedType = ToType; 2284 return true; 2285 } 2286 2287 // Blocks: Block pointers can be converted to void*. 2288 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2289 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2290 ConvertedType = ToType; 2291 return true; 2292 } 2293 // Blocks: A null pointer constant can be converted to a block 2294 // pointer type. 2295 if (ToType->isBlockPointerType() && 2296 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2297 ConvertedType = ToType; 2298 return true; 2299 } 2300 2301 // If the left-hand-side is nullptr_t, the right side can be a null 2302 // pointer constant. 2303 if (ToType->isNullPtrType() && 2304 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2305 ConvertedType = ToType; 2306 return true; 2307 } 2308 2309 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2310 if (!ToTypePtr) 2311 return false; 2312 2313 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2314 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2315 ConvertedType = ToType; 2316 return true; 2317 } 2318 2319 // Beyond this point, both types need to be pointers 2320 // , including objective-c pointers. 2321 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2322 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2323 !getLangOpts().ObjCAutoRefCount) { 2324 ConvertedType = BuildSimilarlyQualifiedPointerType( 2325 FromType->getAs<ObjCObjectPointerType>(), 2326 ToPointeeType, 2327 ToType, Context); 2328 return true; 2329 } 2330 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2331 if (!FromTypePtr) 2332 return false; 2333 2334 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2335 2336 // If the unqualified pointee types are the same, this can't be a 2337 // pointer conversion, so don't do all of the work below. 2338 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2339 return false; 2340 2341 // An rvalue of type "pointer to cv T," where T is an object type, 2342 // can be converted to an rvalue of type "pointer to cv void" (C++ 2343 // 4.10p2). 2344 if (FromPointeeType->isIncompleteOrObjectType() && 2345 ToPointeeType->isVoidType()) { 2346 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2347 ToPointeeType, 2348 ToType, Context, 2349 /*StripObjCLifetime=*/true); 2350 return true; 2351 } 2352 2353 // MSVC allows implicit function to void* type conversion. 2354 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2355 ToPointeeType->isVoidType()) { 2356 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2357 ToPointeeType, 2358 ToType, Context); 2359 return true; 2360 } 2361 2362 // When we're overloading in C, we allow a special kind of pointer 2363 // conversion for compatible-but-not-identical pointee types. 2364 if (!getLangOpts().CPlusPlus && 2365 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2366 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2367 ToPointeeType, 2368 ToType, Context); 2369 return true; 2370 } 2371 2372 // C++ [conv.ptr]p3: 2373 // 2374 // An rvalue of type "pointer to cv D," where D is a class type, 2375 // can be converted to an rvalue of type "pointer to cv B," where 2376 // B is a base class (clause 10) of D. If B is an inaccessible 2377 // (clause 11) or ambiguous (10.2) base class of D, a program that 2378 // necessitates this conversion is ill-formed. The result of the 2379 // conversion is a pointer to the base class sub-object of the 2380 // derived class object. The null pointer value is converted to 2381 // the null pointer value of the destination type. 2382 // 2383 // Note that we do not check for ambiguity or inaccessibility 2384 // here. That is handled by CheckPointerConversion. 2385 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() && 2386 ToPointeeType->isRecordType() && 2387 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2388 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) { 2389 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2390 ToPointeeType, 2391 ToType, Context); 2392 return true; 2393 } 2394 2395 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2396 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2397 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2398 ToPointeeType, 2399 ToType, Context); 2400 return true; 2401 } 2402 2403 return false; 2404 } 2405 2406 /// Adopt the given qualifiers for the given type. 2407 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2408 Qualifiers TQs = T.getQualifiers(); 2409 2410 // Check whether qualifiers already match. 2411 if (TQs == Qs) 2412 return T; 2413 2414 if (Qs.compatiblyIncludes(TQs)) 2415 return Context.getQualifiedType(T, Qs); 2416 2417 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2418 } 2419 2420 /// isObjCPointerConversion - Determines whether this is an 2421 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2422 /// with the same arguments and return values. 2423 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2424 QualType& ConvertedType, 2425 bool &IncompatibleObjC) { 2426 if (!getLangOpts().ObjC) 2427 return false; 2428 2429 // The set of qualifiers on the type we're converting from. 2430 Qualifiers FromQualifiers = FromType.getQualifiers(); 2431 2432 // First, we handle all conversions on ObjC object pointer types. 2433 const ObjCObjectPointerType* ToObjCPtr = 2434 ToType->getAs<ObjCObjectPointerType>(); 2435 const ObjCObjectPointerType *FromObjCPtr = 2436 FromType->getAs<ObjCObjectPointerType>(); 2437 2438 if (ToObjCPtr && FromObjCPtr) { 2439 // If the pointee types are the same (ignoring qualifications), 2440 // then this is not a pointer conversion. 2441 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2442 FromObjCPtr->getPointeeType())) 2443 return false; 2444 2445 // Conversion between Objective-C pointers. 2446 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2447 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2448 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2449 if (getLangOpts().CPlusPlus && LHS && RHS && 2450 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2451 FromObjCPtr->getPointeeType())) 2452 return false; 2453 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2454 ToObjCPtr->getPointeeType(), 2455 ToType, Context); 2456 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2457 return true; 2458 } 2459 2460 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2461 // Okay: this is some kind of implicit downcast of Objective-C 2462 // interfaces, which is permitted. However, we're going to 2463 // complain about it. 2464 IncompatibleObjC = true; 2465 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2466 ToObjCPtr->getPointeeType(), 2467 ToType, Context); 2468 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2469 return true; 2470 } 2471 } 2472 // Beyond this point, both types need to be C pointers or block pointers. 2473 QualType ToPointeeType; 2474 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2475 ToPointeeType = ToCPtr->getPointeeType(); 2476 else if (const BlockPointerType *ToBlockPtr = 2477 ToType->getAs<BlockPointerType>()) { 2478 // Objective C++: We're able to convert from a pointer to any object 2479 // to a block pointer type. 2480 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2481 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2482 return true; 2483 } 2484 ToPointeeType = ToBlockPtr->getPointeeType(); 2485 } 2486 else if (FromType->getAs<BlockPointerType>() && 2487 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2488 // Objective C++: We're able to convert from a block pointer type to a 2489 // pointer to any object. 2490 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2491 return true; 2492 } 2493 else 2494 return false; 2495 2496 QualType FromPointeeType; 2497 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2498 FromPointeeType = FromCPtr->getPointeeType(); 2499 else if (const BlockPointerType *FromBlockPtr = 2500 FromType->getAs<BlockPointerType>()) 2501 FromPointeeType = FromBlockPtr->getPointeeType(); 2502 else 2503 return false; 2504 2505 // If we have pointers to pointers, recursively check whether this 2506 // is an Objective-C conversion. 2507 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2508 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2509 IncompatibleObjC)) { 2510 // We always complain about this conversion. 2511 IncompatibleObjC = true; 2512 ConvertedType = Context.getPointerType(ConvertedType); 2513 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2514 return true; 2515 } 2516 // Allow conversion of pointee being objective-c pointer to another one; 2517 // as in I* to id. 2518 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2519 ToPointeeType->getAs<ObjCObjectPointerType>() && 2520 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2521 IncompatibleObjC)) { 2522 2523 ConvertedType = Context.getPointerType(ConvertedType); 2524 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2525 return true; 2526 } 2527 2528 // If we have pointers to functions or blocks, check whether the only 2529 // differences in the argument and result types are in Objective-C 2530 // pointer conversions. If so, we permit the conversion (but 2531 // complain about it). 2532 const FunctionProtoType *FromFunctionType 2533 = FromPointeeType->getAs<FunctionProtoType>(); 2534 const FunctionProtoType *ToFunctionType 2535 = ToPointeeType->getAs<FunctionProtoType>(); 2536 if (FromFunctionType && ToFunctionType) { 2537 // If the function types are exactly the same, this isn't an 2538 // Objective-C pointer conversion. 2539 if (Context.getCanonicalType(FromPointeeType) 2540 == Context.getCanonicalType(ToPointeeType)) 2541 return false; 2542 2543 // Perform the quick checks that will tell us whether these 2544 // function types are obviously different. 2545 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2546 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2547 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals()) 2548 return false; 2549 2550 bool HasObjCConversion = false; 2551 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2552 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2553 // Okay, the types match exactly. Nothing to do. 2554 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2555 ToFunctionType->getReturnType(), 2556 ConvertedType, IncompatibleObjC)) { 2557 // Okay, we have an Objective-C pointer conversion. 2558 HasObjCConversion = true; 2559 } else { 2560 // Function types are too different. Abort. 2561 return false; 2562 } 2563 2564 // Check argument types. 2565 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2566 ArgIdx != NumArgs; ++ArgIdx) { 2567 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2568 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2569 if (Context.getCanonicalType(FromArgType) 2570 == Context.getCanonicalType(ToArgType)) { 2571 // Okay, the types match exactly. Nothing to do. 2572 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2573 ConvertedType, IncompatibleObjC)) { 2574 // Okay, we have an Objective-C pointer conversion. 2575 HasObjCConversion = true; 2576 } else { 2577 // Argument types are too different. Abort. 2578 return false; 2579 } 2580 } 2581 2582 if (HasObjCConversion) { 2583 // We had an Objective-C conversion. Allow this pointer 2584 // conversion, but complain about it. 2585 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2586 IncompatibleObjC = true; 2587 return true; 2588 } 2589 } 2590 2591 return false; 2592 } 2593 2594 /// Determine whether this is an Objective-C writeback conversion, 2595 /// used for parameter passing when performing automatic reference counting. 2596 /// 2597 /// \param FromType The type we're converting form. 2598 /// 2599 /// \param ToType The type we're converting to. 2600 /// 2601 /// \param ConvertedType The type that will be produced after applying 2602 /// this conversion. 2603 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2604 QualType &ConvertedType) { 2605 if (!getLangOpts().ObjCAutoRefCount || 2606 Context.hasSameUnqualifiedType(FromType, ToType)) 2607 return false; 2608 2609 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2610 QualType ToPointee; 2611 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2612 ToPointee = ToPointer->getPointeeType(); 2613 else 2614 return false; 2615 2616 Qualifiers ToQuals = ToPointee.getQualifiers(); 2617 if (!ToPointee->isObjCLifetimeType() || 2618 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2619 !ToQuals.withoutObjCLifetime().empty()) 2620 return false; 2621 2622 // Argument must be a pointer to __strong to __weak. 2623 QualType FromPointee; 2624 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2625 FromPointee = FromPointer->getPointeeType(); 2626 else 2627 return false; 2628 2629 Qualifiers FromQuals = FromPointee.getQualifiers(); 2630 if (!FromPointee->isObjCLifetimeType() || 2631 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2632 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2633 return false; 2634 2635 // Make sure that we have compatible qualifiers. 2636 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2637 if (!ToQuals.compatiblyIncludes(FromQuals)) 2638 return false; 2639 2640 // Remove qualifiers from the pointee type we're converting from; they 2641 // aren't used in the compatibility check belong, and we'll be adding back 2642 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2643 FromPointee = FromPointee.getUnqualifiedType(); 2644 2645 // The unqualified form of the pointee types must be compatible. 2646 ToPointee = ToPointee.getUnqualifiedType(); 2647 bool IncompatibleObjC; 2648 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2649 FromPointee = ToPointee; 2650 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2651 IncompatibleObjC)) 2652 return false; 2653 2654 /// Construct the type we're converting to, which is a pointer to 2655 /// __autoreleasing pointee. 2656 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2657 ConvertedType = Context.getPointerType(FromPointee); 2658 return true; 2659 } 2660 2661 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2662 QualType& ConvertedType) { 2663 QualType ToPointeeType; 2664 if (const BlockPointerType *ToBlockPtr = 2665 ToType->getAs<BlockPointerType>()) 2666 ToPointeeType = ToBlockPtr->getPointeeType(); 2667 else 2668 return false; 2669 2670 QualType FromPointeeType; 2671 if (const BlockPointerType *FromBlockPtr = 2672 FromType->getAs<BlockPointerType>()) 2673 FromPointeeType = FromBlockPtr->getPointeeType(); 2674 else 2675 return false; 2676 // We have pointer to blocks, check whether the only 2677 // differences in the argument and result types are in Objective-C 2678 // pointer conversions. If so, we permit the conversion. 2679 2680 const FunctionProtoType *FromFunctionType 2681 = FromPointeeType->getAs<FunctionProtoType>(); 2682 const FunctionProtoType *ToFunctionType 2683 = ToPointeeType->getAs<FunctionProtoType>(); 2684 2685 if (!FromFunctionType || !ToFunctionType) 2686 return false; 2687 2688 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2689 return true; 2690 2691 // Perform the quick checks that will tell us whether these 2692 // function types are obviously different. 2693 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2694 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2695 return false; 2696 2697 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2698 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2699 if (FromEInfo != ToEInfo) 2700 return false; 2701 2702 bool IncompatibleObjC = false; 2703 if (Context.hasSameType(FromFunctionType->getReturnType(), 2704 ToFunctionType->getReturnType())) { 2705 // Okay, the types match exactly. Nothing to do. 2706 } else { 2707 QualType RHS = FromFunctionType->getReturnType(); 2708 QualType LHS = ToFunctionType->getReturnType(); 2709 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2710 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2711 LHS = LHS.getUnqualifiedType(); 2712 2713 if (Context.hasSameType(RHS,LHS)) { 2714 // OK exact match. 2715 } else if (isObjCPointerConversion(RHS, LHS, 2716 ConvertedType, IncompatibleObjC)) { 2717 if (IncompatibleObjC) 2718 return false; 2719 // Okay, we have an Objective-C pointer conversion. 2720 } 2721 else 2722 return false; 2723 } 2724 2725 // Check argument types. 2726 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2727 ArgIdx != NumArgs; ++ArgIdx) { 2728 IncompatibleObjC = false; 2729 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2730 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2731 if (Context.hasSameType(FromArgType, ToArgType)) { 2732 // Okay, the types match exactly. Nothing to do. 2733 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2734 ConvertedType, IncompatibleObjC)) { 2735 if (IncompatibleObjC) 2736 return false; 2737 // Okay, we have an Objective-C pointer conversion. 2738 } else 2739 // Argument types are too different. Abort. 2740 return false; 2741 } 2742 2743 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos; 2744 bool CanUseToFPT, CanUseFromFPT; 2745 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType, 2746 CanUseToFPT, CanUseFromFPT, 2747 NewParamInfos)) 2748 return false; 2749 2750 ConvertedType = ToType; 2751 return true; 2752 } 2753 2754 enum { 2755 ft_default, 2756 ft_different_class, 2757 ft_parameter_arity, 2758 ft_parameter_mismatch, 2759 ft_return_type, 2760 ft_qualifer_mismatch, 2761 ft_noexcept 2762 }; 2763 2764 /// Attempts to get the FunctionProtoType from a Type. Handles 2765 /// MemberFunctionPointers properly. 2766 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2767 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2768 return FPT; 2769 2770 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2771 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2772 2773 return nullptr; 2774 } 2775 2776 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2777 /// function types. Catches different number of parameter, mismatch in 2778 /// parameter types, and different return types. 2779 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2780 QualType FromType, QualType ToType) { 2781 // If either type is not valid, include no extra info. 2782 if (FromType.isNull() || ToType.isNull()) { 2783 PDiag << ft_default; 2784 return; 2785 } 2786 2787 // Get the function type from the pointers. 2788 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2789 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2790 *ToMember = ToType->getAs<MemberPointerType>(); 2791 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2792 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2793 << QualType(FromMember->getClass(), 0); 2794 return; 2795 } 2796 FromType = FromMember->getPointeeType(); 2797 ToType = ToMember->getPointeeType(); 2798 } 2799 2800 if (FromType->isPointerType()) 2801 FromType = FromType->getPointeeType(); 2802 if (ToType->isPointerType()) 2803 ToType = ToType->getPointeeType(); 2804 2805 // Remove references. 2806 FromType = FromType.getNonReferenceType(); 2807 ToType = ToType.getNonReferenceType(); 2808 2809 // Don't print extra info for non-specialized template functions. 2810 if (FromType->isInstantiationDependentType() && 2811 !FromType->getAs<TemplateSpecializationType>()) { 2812 PDiag << ft_default; 2813 return; 2814 } 2815 2816 // No extra info for same types. 2817 if (Context.hasSameType(FromType, ToType)) { 2818 PDiag << ft_default; 2819 return; 2820 } 2821 2822 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2823 *ToFunction = tryGetFunctionProtoType(ToType); 2824 2825 // Both types need to be function types. 2826 if (!FromFunction || !ToFunction) { 2827 PDiag << ft_default; 2828 return; 2829 } 2830 2831 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2832 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2833 << FromFunction->getNumParams(); 2834 return; 2835 } 2836 2837 // Handle different parameter types. 2838 unsigned ArgPos; 2839 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2840 PDiag << ft_parameter_mismatch << ArgPos + 1 2841 << ToFunction->getParamType(ArgPos) 2842 << FromFunction->getParamType(ArgPos); 2843 return; 2844 } 2845 2846 // Handle different return type. 2847 if (!Context.hasSameType(FromFunction->getReturnType(), 2848 ToFunction->getReturnType())) { 2849 PDiag << ft_return_type << ToFunction->getReturnType() 2850 << FromFunction->getReturnType(); 2851 return; 2852 } 2853 2854 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) { 2855 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals() 2856 << FromFunction->getMethodQuals(); 2857 return; 2858 } 2859 2860 // Handle exception specification differences on canonical type (in C++17 2861 // onwards). 2862 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2863 ->isNothrow() != 2864 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2865 ->isNothrow()) { 2866 PDiag << ft_noexcept; 2867 return; 2868 } 2869 2870 // Unable to find a difference, so add no extra info. 2871 PDiag << ft_default; 2872 } 2873 2874 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2875 /// for equality of their argument types. Caller has already checked that 2876 /// they have same number of arguments. If the parameters are different, 2877 /// ArgPos will have the parameter index of the first different parameter. 2878 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2879 const FunctionProtoType *NewType, 2880 unsigned *ArgPos) { 2881 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2882 N = NewType->param_type_begin(), 2883 E = OldType->param_type_end(); 2884 O && (O != E); ++O, ++N) { 2885 if (!Context.hasSameType(O->getUnqualifiedType(), 2886 N->getUnqualifiedType())) { 2887 if (ArgPos) 2888 *ArgPos = O - OldType->param_type_begin(); 2889 return false; 2890 } 2891 } 2892 return true; 2893 } 2894 2895 /// CheckPointerConversion - Check the pointer conversion from the 2896 /// expression From to the type ToType. This routine checks for 2897 /// ambiguous or inaccessible derived-to-base pointer 2898 /// conversions for which IsPointerConversion has already returned 2899 /// true. It returns true and produces a diagnostic if there was an 2900 /// error, or returns false otherwise. 2901 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2902 CastKind &Kind, 2903 CXXCastPath& BasePath, 2904 bool IgnoreBaseAccess, 2905 bool Diagnose) { 2906 QualType FromType = From->getType(); 2907 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2908 2909 Kind = CK_BitCast; 2910 2911 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2912 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2913 Expr::NPCK_ZeroExpression) { 2914 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2915 DiagRuntimeBehavior(From->getExprLoc(), From, 2916 PDiag(diag::warn_impcast_bool_to_null_pointer) 2917 << ToType << From->getSourceRange()); 2918 else if (!isUnevaluatedContext()) 2919 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2920 << ToType << From->getSourceRange(); 2921 } 2922 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2923 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2924 QualType FromPointeeType = FromPtrType->getPointeeType(), 2925 ToPointeeType = ToPtrType->getPointeeType(); 2926 2927 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2928 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2929 // We must have a derived-to-base conversion. Check an 2930 // ambiguous or inaccessible conversion. 2931 unsigned InaccessibleID = 0; 2932 unsigned AmbigiousID = 0; 2933 if (Diagnose) { 2934 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2935 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2936 } 2937 if (CheckDerivedToBaseConversion( 2938 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2939 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2940 &BasePath, IgnoreBaseAccess)) 2941 return true; 2942 2943 // The conversion was successful. 2944 Kind = CK_DerivedToBase; 2945 } 2946 2947 if (Diagnose && !IsCStyleOrFunctionalCast && 2948 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2949 assert(getLangOpts().MSVCCompat && 2950 "this should only be possible with MSVCCompat!"); 2951 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2952 << From->getSourceRange(); 2953 } 2954 } 2955 } else if (const ObjCObjectPointerType *ToPtrType = 2956 ToType->getAs<ObjCObjectPointerType>()) { 2957 if (const ObjCObjectPointerType *FromPtrType = 2958 FromType->getAs<ObjCObjectPointerType>()) { 2959 // Objective-C++ conversions are always okay. 2960 // FIXME: We should have a different class of conversions for the 2961 // Objective-C++ implicit conversions. 2962 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2963 return false; 2964 } else if (FromType->isBlockPointerType()) { 2965 Kind = CK_BlockPointerToObjCPointerCast; 2966 } else { 2967 Kind = CK_CPointerToObjCPointerCast; 2968 } 2969 } else if (ToType->isBlockPointerType()) { 2970 if (!FromType->isBlockPointerType()) 2971 Kind = CK_AnyPointerToBlockPointerCast; 2972 } 2973 2974 // We shouldn't fall into this case unless it's valid for other 2975 // reasons. 2976 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2977 Kind = CK_NullToPointer; 2978 2979 return false; 2980 } 2981 2982 /// IsMemberPointerConversion - Determines whether the conversion of the 2983 /// expression From, which has the (possibly adjusted) type FromType, can be 2984 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2985 /// If so, returns true and places the converted type (that might differ from 2986 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2987 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2988 QualType ToType, 2989 bool InOverloadResolution, 2990 QualType &ConvertedType) { 2991 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2992 if (!ToTypePtr) 2993 return false; 2994 2995 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2996 if (From->isNullPointerConstant(Context, 2997 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2998 : Expr::NPC_ValueDependentIsNull)) { 2999 ConvertedType = ToType; 3000 return true; 3001 } 3002 3003 // Otherwise, both types have to be member pointers. 3004 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 3005 if (!FromTypePtr) 3006 return false; 3007 3008 // A pointer to member of B can be converted to a pointer to member of D, 3009 // where D is derived from B (C++ 4.11p2). 3010 QualType FromClass(FromTypePtr->getClass(), 0); 3011 QualType ToClass(ToTypePtr->getClass(), 0); 3012 3013 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 3014 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) { 3015 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 3016 ToClass.getTypePtr()); 3017 return true; 3018 } 3019 3020 return false; 3021 } 3022 3023 /// CheckMemberPointerConversion - Check the member pointer conversion from the 3024 /// expression From to the type ToType. This routine checks for ambiguous or 3025 /// virtual or inaccessible base-to-derived member pointer conversions 3026 /// for which IsMemberPointerConversion has already returned true. It returns 3027 /// true and produces a diagnostic if there was an error, or returns false 3028 /// otherwise. 3029 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 3030 CastKind &Kind, 3031 CXXCastPath &BasePath, 3032 bool IgnoreBaseAccess) { 3033 QualType FromType = From->getType(); 3034 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 3035 if (!FromPtrType) { 3036 // This must be a null pointer to member pointer conversion 3037 assert(From->isNullPointerConstant(Context, 3038 Expr::NPC_ValueDependentIsNull) && 3039 "Expr must be null pointer constant!"); 3040 Kind = CK_NullToMemberPointer; 3041 return false; 3042 } 3043 3044 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 3045 assert(ToPtrType && "No member pointer cast has a target type " 3046 "that is not a member pointer."); 3047 3048 QualType FromClass = QualType(FromPtrType->getClass(), 0); 3049 QualType ToClass = QualType(ToPtrType->getClass(), 0); 3050 3051 // FIXME: What about dependent types? 3052 assert(FromClass->isRecordType() && "Pointer into non-class."); 3053 assert(ToClass->isRecordType() && "Pointer into non-class."); 3054 3055 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 3056 /*DetectVirtual=*/true); 3057 bool DerivationOkay = 3058 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths); 3059 assert(DerivationOkay && 3060 "Should not have been called if derivation isn't OK."); 3061 (void)DerivationOkay; 3062 3063 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 3064 getUnqualifiedType())) { 3065 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 3066 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 3067 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 3068 return true; 3069 } 3070 3071 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 3072 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 3073 << FromClass << ToClass << QualType(VBase, 0) 3074 << From->getSourceRange(); 3075 return true; 3076 } 3077 3078 if (!IgnoreBaseAccess) 3079 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 3080 Paths.front(), 3081 diag::err_downcast_from_inaccessible_base); 3082 3083 // Must be a base to derived member conversion. 3084 BuildBasePathArray(Paths, BasePath); 3085 Kind = CK_BaseToDerivedMemberPointer; 3086 return false; 3087 } 3088 3089 /// Determine whether the lifetime conversion between the two given 3090 /// qualifiers sets is nontrivial. 3091 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 3092 Qualifiers ToQuals) { 3093 // Converting anything to const __unsafe_unretained is trivial. 3094 if (ToQuals.hasConst() && 3095 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3096 return false; 3097 3098 return true; 3099 } 3100 3101 /// IsQualificationConversion - Determines whether the conversion from 3102 /// an rvalue of type FromType to ToType is a qualification conversion 3103 /// (C++ 4.4). 3104 /// 3105 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3106 /// when the qualification conversion involves a change in the Objective-C 3107 /// object lifetime. 3108 bool 3109 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3110 bool CStyle, bool &ObjCLifetimeConversion) { 3111 FromType = Context.getCanonicalType(FromType); 3112 ToType = Context.getCanonicalType(ToType); 3113 ObjCLifetimeConversion = false; 3114 3115 // If FromType and ToType are the same type, this is not a 3116 // qualification conversion. 3117 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3118 return false; 3119 3120 // (C++ 4.4p4): 3121 // A conversion can add cv-qualifiers at levels other than the first 3122 // in multi-level pointers, subject to the following rules: [...] 3123 bool PreviousToQualsIncludeConst = true; 3124 bool UnwrappedAnyPointer = false; 3125 while (Context.UnwrapSimilarTypes(FromType, ToType)) { 3126 // Within each iteration of the loop, we check the qualifiers to 3127 // determine if this still looks like a qualification 3128 // conversion. Then, if all is well, we unwrap one more level of 3129 // pointers or pointers-to-members and do it all again 3130 // until there are no more pointers or pointers-to-members left to 3131 // unwrap. 3132 UnwrappedAnyPointer = true; 3133 3134 Qualifiers FromQuals = FromType.getQualifiers(); 3135 Qualifiers ToQuals = ToType.getQualifiers(); 3136 3137 // Ignore __unaligned qualifier if this type is void. 3138 if (ToType.getUnqualifiedType()->isVoidType()) 3139 FromQuals.removeUnaligned(); 3140 3141 // Objective-C ARC: 3142 // Check Objective-C lifetime conversions. 3143 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 3144 UnwrappedAnyPointer) { 3145 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3146 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3147 ObjCLifetimeConversion = true; 3148 FromQuals.removeObjCLifetime(); 3149 ToQuals.removeObjCLifetime(); 3150 } else { 3151 // Qualification conversions cannot cast between different 3152 // Objective-C lifetime qualifiers. 3153 return false; 3154 } 3155 } 3156 3157 // Allow addition/removal of GC attributes but not changing GC attributes. 3158 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3159 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3160 FromQuals.removeObjCGCAttr(); 3161 ToQuals.removeObjCGCAttr(); 3162 } 3163 3164 // -- for every j > 0, if const is in cv 1,j then const is in cv 3165 // 2,j, and similarly for volatile. 3166 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3167 return false; 3168 3169 // -- if the cv 1,j and cv 2,j are different, then const is in 3170 // every cv for 0 < k < j. 3171 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 3172 && !PreviousToQualsIncludeConst) 3173 return false; 3174 3175 // Keep track of whether all prior cv-qualifiers in the "to" type 3176 // include const. 3177 PreviousToQualsIncludeConst 3178 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 3179 } 3180 3181 // Allows address space promotion by language rules implemented in 3182 // Type::Qualifiers::isAddressSpaceSupersetOf. 3183 Qualifiers FromQuals = FromType.getQualifiers(); 3184 Qualifiers ToQuals = ToType.getQualifiers(); 3185 if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) && 3186 !FromQuals.isAddressSpaceSupersetOf(ToQuals)) { 3187 return false; 3188 } 3189 3190 // We are left with FromType and ToType being the pointee types 3191 // after unwrapping the original FromType and ToType the same number 3192 // of types. If we unwrapped any pointers, and if FromType and 3193 // ToType have the same unqualified type (since we checked 3194 // qualifiers above), then this is a qualification conversion. 3195 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3196 } 3197 3198 /// - Determine whether this is a conversion from a scalar type to an 3199 /// atomic type. 3200 /// 3201 /// If successful, updates \c SCS's second and third steps in the conversion 3202 /// sequence to finish the conversion. 3203 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3204 bool InOverloadResolution, 3205 StandardConversionSequence &SCS, 3206 bool CStyle) { 3207 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3208 if (!ToAtomic) 3209 return false; 3210 3211 StandardConversionSequence InnerSCS; 3212 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3213 InOverloadResolution, InnerSCS, 3214 CStyle, /*AllowObjCWritebackConversion=*/false)) 3215 return false; 3216 3217 SCS.Second = InnerSCS.Second; 3218 SCS.setToType(1, InnerSCS.getToType(1)); 3219 SCS.Third = InnerSCS.Third; 3220 SCS.QualificationIncludesObjCLifetime 3221 = InnerSCS.QualificationIncludesObjCLifetime; 3222 SCS.setToType(2, InnerSCS.getToType(2)); 3223 return true; 3224 } 3225 3226 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3227 CXXConstructorDecl *Constructor, 3228 QualType Type) { 3229 const FunctionProtoType *CtorType = 3230 Constructor->getType()->getAs<FunctionProtoType>(); 3231 if (CtorType->getNumParams() > 0) { 3232 QualType FirstArg = CtorType->getParamType(0); 3233 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3234 return true; 3235 } 3236 return false; 3237 } 3238 3239 static OverloadingResult 3240 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3241 CXXRecordDecl *To, 3242 UserDefinedConversionSequence &User, 3243 OverloadCandidateSet &CandidateSet, 3244 bool AllowExplicit) { 3245 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3246 for (auto *D : S.LookupConstructors(To)) { 3247 auto Info = getConstructorInfo(D); 3248 if (!Info) 3249 continue; 3250 3251 bool Usable = !Info.Constructor->isInvalidDecl() && 3252 S.isInitListConstructor(Info.Constructor) && 3253 (AllowExplicit || !Info.Constructor->isExplicit()); 3254 if (Usable) { 3255 // If the first argument is (a reference to) the target type, 3256 // suppress conversions. 3257 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3258 S.Context, Info.Constructor, ToType); 3259 if (Info.ConstructorTmpl) 3260 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3261 /*ExplicitArgs*/ nullptr, From, 3262 CandidateSet, SuppressUserConversions); 3263 else 3264 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3265 CandidateSet, SuppressUserConversions); 3266 } 3267 } 3268 3269 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3270 3271 OverloadCandidateSet::iterator Best; 3272 switch (auto Result = 3273 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3274 case OR_Deleted: 3275 case OR_Success: { 3276 // Record the standard conversion we used and the conversion function. 3277 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3278 QualType ThisType = Constructor->getThisType(); 3279 // Initializer lists don't have conversions as such. 3280 User.Before.setAsIdentityConversion(); 3281 User.HadMultipleCandidates = HadMultipleCandidates; 3282 User.ConversionFunction = Constructor; 3283 User.FoundConversionFunction = Best->FoundDecl; 3284 User.After.setAsIdentityConversion(); 3285 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3286 User.After.setAllToTypes(ToType); 3287 return Result; 3288 } 3289 3290 case OR_No_Viable_Function: 3291 return OR_No_Viable_Function; 3292 case OR_Ambiguous: 3293 return OR_Ambiguous; 3294 } 3295 3296 llvm_unreachable("Invalid OverloadResult!"); 3297 } 3298 3299 /// Determines whether there is a user-defined conversion sequence 3300 /// (C++ [over.ics.user]) that converts expression From to the type 3301 /// ToType. If such a conversion exists, User will contain the 3302 /// user-defined conversion sequence that performs such a conversion 3303 /// and this routine will return true. Otherwise, this routine returns 3304 /// false and User is unspecified. 3305 /// 3306 /// \param AllowExplicit true if the conversion should consider C++0x 3307 /// "explicit" conversion functions as well as non-explicit conversion 3308 /// functions (C++0x [class.conv.fct]p2). 3309 /// 3310 /// \param AllowObjCConversionOnExplicit true if the conversion should 3311 /// allow an extra Objective-C pointer conversion on uses of explicit 3312 /// constructors. Requires \c AllowExplicit to also be set. 3313 static OverloadingResult 3314 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3315 UserDefinedConversionSequence &User, 3316 OverloadCandidateSet &CandidateSet, 3317 bool AllowExplicit, 3318 bool AllowObjCConversionOnExplicit) { 3319 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3320 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3321 3322 // Whether we will only visit constructors. 3323 bool ConstructorsOnly = false; 3324 3325 // If the type we are conversion to is a class type, enumerate its 3326 // constructors. 3327 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3328 // C++ [over.match.ctor]p1: 3329 // When objects of class type are direct-initialized (8.5), or 3330 // copy-initialized from an expression of the same or a 3331 // derived class type (8.5), overload resolution selects the 3332 // constructor. [...] For copy-initialization, the candidate 3333 // functions are all the converting constructors (12.3.1) of 3334 // that class. The argument list is the expression-list within 3335 // the parentheses of the initializer. 3336 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3337 (From->getType()->getAs<RecordType>() && 3338 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType))) 3339 ConstructorsOnly = true; 3340 3341 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3342 // We're not going to find any constructors. 3343 } else if (CXXRecordDecl *ToRecordDecl 3344 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3345 3346 Expr **Args = &From; 3347 unsigned NumArgs = 1; 3348 bool ListInitializing = false; 3349 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3350 // But first, see if there is an init-list-constructor that will work. 3351 OverloadingResult Result = IsInitializerListConstructorConversion( 3352 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3353 if (Result != OR_No_Viable_Function) 3354 return Result; 3355 // Never mind. 3356 CandidateSet.clear( 3357 OverloadCandidateSet::CSK_InitByUserDefinedConversion); 3358 3359 // If we're list-initializing, we pass the individual elements as 3360 // arguments, not the entire list. 3361 Args = InitList->getInits(); 3362 NumArgs = InitList->getNumInits(); 3363 ListInitializing = true; 3364 } 3365 3366 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3367 auto Info = getConstructorInfo(D); 3368 if (!Info) 3369 continue; 3370 3371 bool Usable = !Info.Constructor->isInvalidDecl(); 3372 if (ListInitializing) 3373 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3374 else 3375 Usable = Usable && 3376 Info.Constructor->isConvertingConstructor(AllowExplicit); 3377 if (Usable) { 3378 bool SuppressUserConversions = !ConstructorsOnly; 3379 if (SuppressUserConversions && ListInitializing) { 3380 SuppressUserConversions = false; 3381 if (NumArgs == 1) { 3382 // If the first argument is (a reference to) the target type, 3383 // suppress conversions. 3384 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3385 S.Context, Info.Constructor, ToType); 3386 } 3387 } 3388 if (Info.ConstructorTmpl) 3389 S.AddTemplateOverloadCandidate( 3390 Info.ConstructorTmpl, Info.FoundDecl, 3391 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3392 CandidateSet, SuppressUserConversions); 3393 else 3394 // Allow one user-defined conversion when user specifies a 3395 // From->ToType conversion via an static cast (c-style, etc). 3396 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3397 llvm::makeArrayRef(Args, NumArgs), 3398 CandidateSet, SuppressUserConversions); 3399 } 3400 } 3401 } 3402 } 3403 3404 // Enumerate conversion functions, if we're allowed to. 3405 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3406 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) { 3407 // No conversion functions from incomplete types. 3408 } else if (const RecordType *FromRecordType = 3409 From->getType()->getAs<RecordType>()) { 3410 if (CXXRecordDecl *FromRecordDecl 3411 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3412 // Add all of the conversion functions as candidates. 3413 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3414 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3415 DeclAccessPair FoundDecl = I.getPair(); 3416 NamedDecl *D = FoundDecl.getDecl(); 3417 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3418 if (isa<UsingShadowDecl>(D)) 3419 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3420 3421 CXXConversionDecl *Conv; 3422 FunctionTemplateDecl *ConvTemplate; 3423 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3424 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3425 else 3426 Conv = cast<CXXConversionDecl>(D); 3427 3428 if (AllowExplicit || !Conv->isExplicit()) { 3429 if (ConvTemplate) 3430 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3431 ActingContext, From, ToType, 3432 CandidateSet, 3433 AllowObjCConversionOnExplicit); 3434 else 3435 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3436 From, ToType, CandidateSet, 3437 AllowObjCConversionOnExplicit); 3438 } 3439 } 3440 } 3441 } 3442 3443 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3444 3445 OverloadCandidateSet::iterator Best; 3446 switch (auto Result = 3447 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) { 3448 case OR_Success: 3449 case OR_Deleted: 3450 // Record the standard conversion we used and the conversion function. 3451 if (CXXConstructorDecl *Constructor 3452 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3453 // C++ [over.ics.user]p1: 3454 // If the user-defined conversion is specified by a 3455 // constructor (12.3.1), the initial standard conversion 3456 // sequence converts the source type to the type required by 3457 // the argument of the constructor. 3458 // 3459 QualType ThisType = Constructor->getThisType(); 3460 if (isa<InitListExpr>(From)) { 3461 // Initializer lists don't have conversions as such. 3462 User.Before.setAsIdentityConversion(); 3463 } else { 3464 if (Best->Conversions[0].isEllipsis()) 3465 User.EllipsisConversion = true; 3466 else { 3467 User.Before = Best->Conversions[0].Standard; 3468 User.EllipsisConversion = false; 3469 } 3470 } 3471 User.HadMultipleCandidates = HadMultipleCandidates; 3472 User.ConversionFunction = Constructor; 3473 User.FoundConversionFunction = Best->FoundDecl; 3474 User.After.setAsIdentityConversion(); 3475 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3476 User.After.setAllToTypes(ToType); 3477 return Result; 3478 } 3479 if (CXXConversionDecl *Conversion 3480 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3481 // C++ [over.ics.user]p1: 3482 // 3483 // [...] If the user-defined conversion is specified by a 3484 // conversion function (12.3.2), the initial standard 3485 // conversion sequence converts the source type to the 3486 // implicit object parameter of the conversion function. 3487 User.Before = Best->Conversions[0].Standard; 3488 User.HadMultipleCandidates = HadMultipleCandidates; 3489 User.ConversionFunction = Conversion; 3490 User.FoundConversionFunction = Best->FoundDecl; 3491 User.EllipsisConversion = false; 3492 3493 // C++ [over.ics.user]p2: 3494 // The second standard conversion sequence converts the 3495 // result of the user-defined conversion to the target type 3496 // for the sequence. Since an implicit conversion sequence 3497 // is an initialization, the special rules for 3498 // initialization by user-defined conversion apply when 3499 // selecting the best user-defined conversion for a 3500 // user-defined conversion sequence (see 13.3.3 and 3501 // 13.3.3.1). 3502 User.After = Best->FinalConversion; 3503 return Result; 3504 } 3505 llvm_unreachable("Not a constructor or conversion function?"); 3506 3507 case OR_No_Viable_Function: 3508 return OR_No_Viable_Function; 3509 3510 case OR_Ambiguous: 3511 return OR_Ambiguous; 3512 } 3513 3514 llvm_unreachable("Invalid OverloadResult!"); 3515 } 3516 3517 bool 3518 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3519 ImplicitConversionSequence ICS; 3520 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3521 OverloadCandidateSet::CSK_Normal); 3522 OverloadingResult OvResult = 3523 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3524 CandidateSet, false, false); 3525 if (OvResult == OR_Ambiguous) 3526 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition) 3527 << From->getType() << ToType << From->getSourceRange(); 3528 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3529 if (!RequireCompleteType(From->getBeginLoc(), ToType, 3530 diag::err_typecheck_nonviable_condition_incomplete, 3531 From->getType(), From->getSourceRange())) 3532 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition) 3533 << false << From->getType() << From->getSourceRange() << ToType; 3534 } else 3535 return false; 3536 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3537 return true; 3538 } 3539 3540 /// Compare the user-defined conversion functions or constructors 3541 /// of two user-defined conversion sequences to determine whether any ordering 3542 /// is possible. 3543 static ImplicitConversionSequence::CompareKind 3544 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3545 FunctionDecl *Function2) { 3546 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11) 3547 return ImplicitConversionSequence::Indistinguishable; 3548 3549 // Objective-C++: 3550 // If both conversion functions are implicitly-declared conversions from 3551 // a lambda closure type to a function pointer and a block pointer, 3552 // respectively, always prefer the conversion to a function pointer, 3553 // because the function pointer is more lightweight and is more likely 3554 // to keep code working. 3555 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3556 if (!Conv1) 3557 return ImplicitConversionSequence::Indistinguishable; 3558 3559 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3560 if (!Conv2) 3561 return ImplicitConversionSequence::Indistinguishable; 3562 3563 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3564 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3565 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3566 if (Block1 != Block2) 3567 return Block1 ? ImplicitConversionSequence::Worse 3568 : ImplicitConversionSequence::Better; 3569 } 3570 3571 return ImplicitConversionSequence::Indistinguishable; 3572 } 3573 3574 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3575 const ImplicitConversionSequence &ICS) { 3576 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3577 (ICS.isUserDefined() && 3578 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3579 } 3580 3581 /// CompareImplicitConversionSequences - Compare two implicit 3582 /// conversion sequences to determine whether one is better than the 3583 /// other or if they are indistinguishable (C++ 13.3.3.2). 3584 static ImplicitConversionSequence::CompareKind 3585 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3586 const ImplicitConversionSequence& ICS1, 3587 const ImplicitConversionSequence& ICS2) 3588 { 3589 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3590 // conversion sequences (as defined in 13.3.3.1) 3591 // -- a standard conversion sequence (13.3.3.1.1) is a better 3592 // conversion sequence than a user-defined conversion sequence or 3593 // an ellipsis conversion sequence, and 3594 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3595 // conversion sequence than an ellipsis conversion sequence 3596 // (13.3.3.1.3). 3597 // 3598 // C++0x [over.best.ics]p10: 3599 // For the purpose of ranking implicit conversion sequences as 3600 // described in 13.3.3.2, the ambiguous conversion sequence is 3601 // treated as a user-defined sequence that is indistinguishable 3602 // from any other user-defined conversion sequence. 3603 3604 // String literal to 'char *' conversion has been deprecated in C++03. It has 3605 // been removed from C++11. We still accept this conversion, if it happens at 3606 // the best viable function. Otherwise, this conversion is considered worse 3607 // than ellipsis conversion. Consider this as an extension; this is not in the 3608 // standard. For example: 3609 // 3610 // int &f(...); // #1 3611 // void f(char*); // #2 3612 // void g() { int &r = f("foo"); } 3613 // 3614 // In C++03, we pick #2 as the best viable function. 3615 // In C++11, we pick #1 as the best viable function, because ellipsis 3616 // conversion is better than string-literal to char* conversion (since there 3617 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3618 // convert arguments, #2 would be the best viable function in C++11. 3619 // If the best viable function has this conversion, a warning will be issued 3620 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3621 3622 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3623 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3624 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3625 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3626 ? ImplicitConversionSequence::Worse 3627 : ImplicitConversionSequence::Better; 3628 3629 if (ICS1.getKindRank() < ICS2.getKindRank()) 3630 return ImplicitConversionSequence::Better; 3631 if (ICS2.getKindRank() < ICS1.getKindRank()) 3632 return ImplicitConversionSequence::Worse; 3633 3634 // The following checks require both conversion sequences to be of 3635 // the same kind. 3636 if (ICS1.getKind() != ICS2.getKind()) 3637 return ImplicitConversionSequence::Indistinguishable; 3638 3639 ImplicitConversionSequence::CompareKind Result = 3640 ImplicitConversionSequence::Indistinguishable; 3641 3642 // Two implicit conversion sequences of the same form are 3643 // indistinguishable conversion sequences unless one of the 3644 // following rules apply: (C++ 13.3.3.2p3): 3645 3646 // List-initialization sequence L1 is a better conversion sequence than 3647 // list-initialization sequence L2 if: 3648 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3649 // if not that, 3650 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3651 // and N1 is smaller than N2., 3652 // even if one of the other rules in this paragraph would otherwise apply. 3653 if (!ICS1.isBad()) { 3654 if (ICS1.isStdInitializerListElement() && 3655 !ICS2.isStdInitializerListElement()) 3656 return ImplicitConversionSequence::Better; 3657 if (!ICS1.isStdInitializerListElement() && 3658 ICS2.isStdInitializerListElement()) 3659 return ImplicitConversionSequence::Worse; 3660 } 3661 3662 if (ICS1.isStandard()) 3663 // Standard conversion sequence S1 is a better conversion sequence than 3664 // standard conversion sequence S2 if [...] 3665 Result = CompareStandardConversionSequences(S, Loc, 3666 ICS1.Standard, ICS2.Standard); 3667 else if (ICS1.isUserDefined()) { 3668 // User-defined conversion sequence U1 is a better conversion 3669 // sequence than another user-defined conversion sequence U2 if 3670 // they contain the same user-defined conversion function or 3671 // constructor and if the second standard conversion sequence of 3672 // U1 is better than the second standard conversion sequence of 3673 // U2 (C++ 13.3.3.2p3). 3674 if (ICS1.UserDefined.ConversionFunction == 3675 ICS2.UserDefined.ConversionFunction) 3676 Result = CompareStandardConversionSequences(S, Loc, 3677 ICS1.UserDefined.After, 3678 ICS2.UserDefined.After); 3679 else 3680 Result = compareConversionFunctions(S, 3681 ICS1.UserDefined.ConversionFunction, 3682 ICS2.UserDefined.ConversionFunction); 3683 } 3684 3685 return Result; 3686 } 3687 3688 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3689 // determine if one is a proper subset of the other. 3690 static ImplicitConversionSequence::CompareKind 3691 compareStandardConversionSubsets(ASTContext &Context, 3692 const StandardConversionSequence& SCS1, 3693 const StandardConversionSequence& SCS2) { 3694 ImplicitConversionSequence::CompareKind Result 3695 = ImplicitConversionSequence::Indistinguishable; 3696 3697 // the identity conversion sequence is considered to be a subsequence of 3698 // any non-identity conversion sequence 3699 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3700 return ImplicitConversionSequence::Better; 3701 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3702 return ImplicitConversionSequence::Worse; 3703 3704 if (SCS1.Second != SCS2.Second) { 3705 if (SCS1.Second == ICK_Identity) 3706 Result = ImplicitConversionSequence::Better; 3707 else if (SCS2.Second == ICK_Identity) 3708 Result = ImplicitConversionSequence::Worse; 3709 else 3710 return ImplicitConversionSequence::Indistinguishable; 3711 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1))) 3712 return ImplicitConversionSequence::Indistinguishable; 3713 3714 if (SCS1.Third == SCS2.Third) { 3715 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3716 : ImplicitConversionSequence::Indistinguishable; 3717 } 3718 3719 if (SCS1.Third == ICK_Identity) 3720 return Result == ImplicitConversionSequence::Worse 3721 ? ImplicitConversionSequence::Indistinguishable 3722 : ImplicitConversionSequence::Better; 3723 3724 if (SCS2.Third == ICK_Identity) 3725 return Result == ImplicitConversionSequence::Better 3726 ? ImplicitConversionSequence::Indistinguishable 3727 : ImplicitConversionSequence::Worse; 3728 3729 return ImplicitConversionSequence::Indistinguishable; 3730 } 3731 3732 /// Determine whether one of the given reference bindings is better 3733 /// than the other based on what kind of bindings they are. 3734 static bool 3735 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3736 const StandardConversionSequence &SCS2) { 3737 // C++0x [over.ics.rank]p3b4: 3738 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3739 // implicit object parameter of a non-static member function declared 3740 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3741 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3742 // lvalue reference to a function lvalue and S2 binds an rvalue 3743 // reference*. 3744 // 3745 // FIXME: Rvalue references. We're going rogue with the above edits, 3746 // because the semantics in the current C++0x working paper (N3225 at the 3747 // time of this writing) break the standard definition of std::forward 3748 // and std::reference_wrapper when dealing with references to functions. 3749 // Proposed wording changes submitted to CWG for consideration. 3750 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3751 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3752 return false; 3753 3754 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3755 SCS2.IsLvalueReference) || 3756 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3757 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3758 } 3759 3760 /// CompareStandardConversionSequences - Compare two standard 3761 /// conversion sequences to determine whether one is better than the 3762 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3763 static ImplicitConversionSequence::CompareKind 3764 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3765 const StandardConversionSequence& SCS1, 3766 const StandardConversionSequence& SCS2) 3767 { 3768 // Standard conversion sequence S1 is a better conversion sequence 3769 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3770 3771 // -- S1 is a proper subsequence of S2 (comparing the conversion 3772 // sequences in the canonical form defined by 13.3.3.1.1, 3773 // excluding any Lvalue Transformation; the identity conversion 3774 // sequence is considered to be a subsequence of any 3775 // non-identity conversion sequence) or, if not that, 3776 if (ImplicitConversionSequence::CompareKind CK 3777 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3778 return CK; 3779 3780 // -- the rank of S1 is better than the rank of S2 (by the rules 3781 // defined below), or, if not that, 3782 ImplicitConversionRank Rank1 = SCS1.getRank(); 3783 ImplicitConversionRank Rank2 = SCS2.getRank(); 3784 if (Rank1 < Rank2) 3785 return ImplicitConversionSequence::Better; 3786 else if (Rank2 < Rank1) 3787 return ImplicitConversionSequence::Worse; 3788 3789 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3790 // are indistinguishable unless one of the following rules 3791 // applies: 3792 3793 // A conversion that is not a conversion of a pointer, or 3794 // pointer to member, to bool is better than another conversion 3795 // that is such a conversion. 3796 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3797 return SCS2.isPointerConversionToBool() 3798 ? ImplicitConversionSequence::Better 3799 : ImplicitConversionSequence::Worse; 3800 3801 // C++ [over.ics.rank]p4b2: 3802 // 3803 // If class B is derived directly or indirectly from class A, 3804 // conversion of B* to A* is better than conversion of B* to 3805 // void*, and conversion of A* to void* is better than conversion 3806 // of B* to void*. 3807 bool SCS1ConvertsToVoid 3808 = SCS1.isPointerConversionToVoidPointer(S.Context); 3809 bool SCS2ConvertsToVoid 3810 = SCS2.isPointerConversionToVoidPointer(S.Context); 3811 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3812 // Exactly one of the conversion sequences is a conversion to 3813 // a void pointer; it's the worse conversion. 3814 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3815 : ImplicitConversionSequence::Worse; 3816 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3817 // Neither conversion sequence converts to a void pointer; compare 3818 // their derived-to-base conversions. 3819 if (ImplicitConversionSequence::CompareKind DerivedCK 3820 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3821 return DerivedCK; 3822 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3823 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3824 // Both conversion sequences are conversions to void 3825 // pointers. Compare the source types to determine if there's an 3826 // inheritance relationship in their sources. 3827 QualType FromType1 = SCS1.getFromType(); 3828 QualType FromType2 = SCS2.getFromType(); 3829 3830 // Adjust the types we're converting from via the array-to-pointer 3831 // conversion, if we need to. 3832 if (SCS1.First == ICK_Array_To_Pointer) 3833 FromType1 = S.Context.getArrayDecayedType(FromType1); 3834 if (SCS2.First == ICK_Array_To_Pointer) 3835 FromType2 = S.Context.getArrayDecayedType(FromType2); 3836 3837 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3838 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3839 3840 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3841 return ImplicitConversionSequence::Better; 3842 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3843 return ImplicitConversionSequence::Worse; 3844 3845 // Objective-C++: If one interface is more specific than the 3846 // other, it is the better one. 3847 const ObjCObjectPointerType* FromObjCPtr1 3848 = FromType1->getAs<ObjCObjectPointerType>(); 3849 const ObjCObjectPointerType* FromObjCPtr2 3850 = FromType2->getAs<ObjCObjectPointerType>(); 3851 if (FromObjCPtr1 && FromObjCPtr2) { 3852 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3853 FromObjCPtr2); 3854 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3855 FromObjCPtr1); 3856 if (AssignLeft != AssignRight) { 3857 return AssignLeft? ImplicitConversionSequence::Better 3858 : ImplicitConversionSequence::Worse; 3859 } 3860 } 3861 } 3862 3863 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3864 // bullet 3). 3865 if (ImplicitConversionSequence::CompareKind QualCK 3866 = CompareQualificationConversions(S, SCS1, SCS2)) 3867 return QualCK; 3868 3869 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3870 // Check for a better reference binding based on the kind of bindings. 3871 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3872 return ImplicitConversionSequence::Better; 3873 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3874 return ImplicitConversionSequence::Worse; 3875 3876 // C++ [over.ics.rank]p3b4: 3877 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3878 // which the references refer are the same type except for 3879 // top-level cv-qualifiers, and the type to which the reference 3880 // initialized by S2 refers is more cv-qualified than the type 3881 // to which the reference initialized by S1 refers. 3882 QualType T1 = SCS1.getToType(2); 3883 QualType T2 = SCS2.getToType(2); 3884 T1 = S.Context.getCanonicalType(T1); 3885 T2 = S.Context.getCanonicalType(T2); 3886 Qualifiers T1Quals, T2Quals; 3887 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3888 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3889 if (UnqualT1 == UnqualT2) { 3890 // Objective-C++ ARC: If the references refer to objects with different 3891 // lifetimes, prefer bindings that don't change lifetime. 3892 if (SCS1.ObjCLifetimeConversionBinding != 3893 SCS2.ObjCLifetimeConversionBinding) { 3894 return SCS1.ObjCLifetimeConversionBinding 3895 ? ImplicitConversionSequence::Worse 3896 : ImplicitConversionSequence::Better; 3897 } 3898 3899 // If the type is an array type, promote the element qualifiers to the 3900 // type for comparison. 3901 if (isa<ArrayType>(T1) && T1Quals) 3902 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3903 if (isa<ArrayType>(T2) && T2Quals) 3904 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3905 if (T2.isMoreQualifiedThan(T1)) 3906 return ImplicitConversionSequence::Better; 3907 else if (T1.isMoreQualifiedThan(T2)) 3908 return ImplicitConversionSequence::Worse; 3909 } 3910 } 3911 3912 // In Microsoft mode, prefer an integral conversion to a 3913 // floating-to-integral conversion if the integral conversion 3914 // is between types of the same size. 3915 // For example: 3916 // void f(float); 3917 // void f(int); 3918 // int main { 3919 // long a; 3920 // f(a); 3921 // } 3922 // Here, MSVC will call f(int) instead of generating a compile error 3923 // as clang will do in standard mode. 3924 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3925 SCS2.Second == ICK_Floating_Integral && 3926 S.Context.getTypeSize(SCS1.getFromType()) == 3927 S.Context.getTypeSize(SCS1.getToType(2))) 3928 return ImplicitConversionSequence::Better; 3929 3930 // Prefer a compatible vector conversion over a lax vector conversion 3931 // For example: 3932 // 3933 // typedef float __v4sf __attribute__((__vector_size__(16))); 3934 // void f(vector float); 3935 // void f(vector signed int); 3936 // int main() { 3937 // __v4sf a; 3938 // f(a); 3939 // } 3940 // Here, we'd like to choose f(vector float) and not 3941 // report an ambiguous call error 3942 if (SCS1.Second == ICK_Vector_Conversion && 3943 SCS2.Second == ICK_Vector_Conversion) { 3944 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 3945 SCS1.getFromType(), SCS1.getToType(2)); 3946 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes( 3947 SCS2.getFromType(), SCS2.getToType(2)); 3948 3949 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion) 3950 return SCS1IsCompatibleVectorConversion 3951 ? ImplicitConversionSequence::Better 3952 : ImplicitConversionSequence::Worse; 3953 } 3954 3955 return ImplicitConversionSequence::Indistinguishable; 3956 } 3957 3958 /// CompareQualificationConversions - Compares two standard conversion 3959 /// sequences to determine whether they can be ranked based on their 3960 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3961 static ImplicitConversionSequence::CompareKind 3962 CompareQualificationConversions(Sema &S, 3963 const StandardConversionSequence& SCS1, 3964 const StandardConversionSequence& SCS2) { 3965 // C++ 13.3.3.2p3: 3966 // -- S1 and S2 differ only in their qualification conversion and 3967 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3968 // cv-qualification signature of type T1 is a proper subset of 3969 // the cv-qualification signature of type T2, and S1 is not the 3970 // deprecated string literal array-to-pointer conversion (4.2). 3971 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3972 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3973 return ImplicitConversionSequence::Indistinguishable; 3974 3975 // FIXME: the example in the standard doesn't use a qualification 3976 // conversion (!) 3977 QualType T1 = SCS1.getToType(2); 3978 QualType T2 = SCS2.getToType(2); 3979 T1 = S.Context.getCanonicalType(T1); 3980 T2 = S.Context.getCanonicalType(T2); 3981 Qualifiers T1Quals, T2Quals; 3982 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3983 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3984 3985 // If the types are the same, we won't learn anything by unwrapped 3986 // them. 3987 if (UnqualT1 == UnqualT2) 3988 return ImplicitConversionSequence::Indistinguishable; 3989 3990 // If the type is an array type, promote the element qualifiers to the type 3991 // for comparison. 3992 if (isa<ArrayType>(T1) && T1Quals) 3993 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3994 if (isa<ArrayType>(T2) && T2Quals) 3995 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3996 3997 ImplicitConversionSequence::CompareKind Result 3998 = ImplicitConversionSequence::Indistinguishable; 3999 4000 // Objective-C++ ARC: 4001 // Prefer qualification conversions not involving a change in lifetime 4002 // to qualification conversions that do not change lifetime. 4003 if (SCS1.QualificationIncludesObjCLifetime != 4004 SCS2.QualificationIncludesObjCLifetime) { 4005 Result = SCS1.QualificationIncludesObjCLifetime 4006 ? ImplicitConversionSequence::Worse 4007 : ImplicitConversionSequence::Better; 4008 } 4009 4010 while (S.Context.UnwrapSimilarTypes(T1, T2)) { 4011 // Within each iteration of the loop, we check the qualifiers to 4012 // determine if this still looks like a qualification 4013 // conversion. Then, if all is well, we unwrap one more level of 4014 // pointers or pointers-to-members and do it all again 4015 // until there are no more pointers or pointers-to-members left 4016 // to unwrap. This essentially mimics what 4017 // IsQualificationConversion does, but here we're checking for a 4018 // strict subset of qualifiers. 4019 if (T1.getQualifiers().withoutObjCLifetime() == 4020 T2.getQualifiers().withoutObjCLifetime()) 4021 // The qualifiers are the same, so this doesn't tell us anything 4022 // about how the sequences rank. 4023 // ObjC ownership quals are omitted above as they interfere with 4024 // the ARC overload rule. 4025 ; 4026 else if (T2.isMoreQualifiedThan(T1)) { 4027 // T1 has fewer qualifiers, so it could be the better sequence. 4028 if (Result == ImplicitConversionSequence::Worse) 4029 // Neither has qualifiers that are a subset of the other's 4030 // qualifiers. 4031 return ImplicitConversionSequence::Indistinguishable; 4032 4033 Result = ImplicitConversionSequence::Better; 4034 } else if (T1.isMoreQualifiedThan(T2)) { 4035 // T2 has fewer qualifiers, so it could be the better sequence. 4036 if (Result == ImplicitConversionSequence::Better) 4037 // Neither has qualifiers that are a subset of the other's 4038 // qualifiers. 4039 return ImplicitConversionSequence::Indistinguishable; 4040 4041 Result = ImplicitConversionSequence::Worse; 4042 } else { 4043 // Qualifiers are disjoint. 4044 return ImplicitConversionSequence::Indistinguishable; 4045 } 4046 4047 // If the types after this point are equivalent, we're done. 4048 if (S.Context.hasSameUnqualifiedType(T1, T2)) 4049 break; 4050 } 4051 4052 // Check that the winning standard conversion sequence isn't using 4053 // the deprecated string literal array to pointer conversion. 4054 switch (Result) { 4055 case ImplicitConversionSequence::Better: 4056 if (SCS1.DeprecatedStringLiteralToCharPtr) 4057 Result = ImplicitConversionSequence::Indistinguishable; 4058 break; 4059 4060 case ImplicitConversionSequence::Indistinguishable: 4061 break; 4062 4063 case ImplicitConversionSequence::Worse: 4064 if (SCS2.DeprecatedStringLiteralToCharPtr) 4065 Result = ImplicitConversionSequence::Indistinguishable; 4066 break; 4067 } 4068 4069 return Result; 4070 } 4071 4072 /// CompareDerivedToBaseConversions - Compares two standard conversion 4073 /// sequences to determine whether they can be ranked based on their 4074 /// various kinds of derived-to-base conversions (C++ 4075 /// [over.ics.rank]p4b3). As part of these checks, we also look at 4076 /// conversions between Objective-C interface types. 4077 static ImplicitConversionSequence::CompareKind 4078 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 4079 const StandardConversionSequence& SCS1, 4080 const StandardConversionSequence& SCS2) { 4081 QualType FromType1 = SCS1.getFromType(); 4082 QualType ToType1 = SCS1.getToType(1); 4083 QualType FromType2 = SCS2.getFromType(); 4084 QualType ToType2 = SCS2.getToType(1); 4085 4086 // Adjust the types we're converting from via the array-to-pointer 4087 // conversion, if we need to. 4088 if (SCS1.First == ICK_Array_To_Pointer) 4089 FromType1 = S.Context.getArrayDecayedType(FromType1); 4090 if (SCS2.First == ICK_Array_To_Pointer) 4091 FromType2 = S.Context.getArrayDecayedType(FromType2); 4092 4093 // Canonicalize all of the types. 4094 FromType1 = S.Context.getCanonicalType(FromType1); 4095 ToType1 = S.Context.getCanonicalType(ToType1); 4096 FromType2 = S.Context.getCanonicalType(FromType2); 4097 ToType2 = S.Context.getCanonicalType(ToType2); 4098 4099 // C++ [over.ics.rank]p4b3: 4100 // 4101 // If class B is derived directly or indirectly from class A and 4102 // class C is derived directly or indirectly from B, 4103 // 4104 // Compare based on pointer conversions. 4105 if (SCS1.Second == ICK_Pointer_Conversion && 4106 SCS2.Second == ICK_Pointer_Conversion && 4107 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 4108 FromType1->isPointerType() && FromType2->isPointerType() && 4109 ToType1->isPointerType() && ToType2->isPointerType()) { 4110 QualType FromPointee1 4111 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4112 QualType ToPointee1 4113 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4114 QualType FromPointee2 4115 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4116 QualType ToPointee2 4117 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 4118 4119 // -- conversion of C* to B* is better than conversion of C* to A*, 4120 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4121 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4122 return ImplicitConversionSequence::Better; 4123 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4124 return ImplicitConversionSequence::Worse; 4125 } 4126 4127 // -- conversion of B* to A* is better than conversion of C* to A*, 4128 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4129 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4130 return ImplicitConversionSequence::Better; 4131 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4132 return ImplicitConversionSequence::Worse; 4133 } 4134 } else if (SCS1.Second == ICK_Pointer_Conversion && 4135 SCS2.Second == ICK_Pointer_Conversion) { 4136 const ObjCObjectPointerType *FromPtr1 4137 = FromType1->getAs<ObjCObjectPointerType>(); 4138 const ObjCObjectPointerType *FromPtr2 4139 = FromType2->getAs<ObjCObjectPointerType>(); 4140 const ObjCObjectPointerType *ToPtr1 4141 = ToType1->getAs<ObjCObjectPointerType>(); 4142 const ObjCObjectPointerType *ToPtr2 4143 = ToType2->getAs<ObjCObjectPointerType>(); 4144 4145 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4146 // Apply the same conversion ranking rules for Objective-C pointer types 4147 // that we do for C++ pointers to class types. However, we employ the 4148 // Objective-C pseudo-subtyping relationship used for assignment of 4149 // Objective-C pointer types. 4150 bool FromAssignLeft 4151 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4152 bool FromAssignRight 4153 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4154 bool ToAssignLeft 4155 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4156 bool ToAssignRight 4157 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4158 4159 // A conversion to an a non-id object pointer type or qualified 'id' 4160 // type is better than a conversion to 'id'. 4161 if (ToPtr1->isObjCIdType() && 4162 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4163 return ImplicitConversionSequence::Worse; 4164 if (ToPtr2->isObjCIdType() && 4165 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4166 return ImplicitConversionSequence::Better; 4167 4168 // A conversion to a non-id object pointer type is better than a 4169 // conversion to a qualified 'id' type 4170 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4171 return ImplicitConversionSequence::Worse; 4172 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4173 return ImplicitConversionSequence::Better; 4174 4175 // A conversion to an a non-Class object pointer type or qualified 'Class' 4176 // type is better than a conversion to 'Class'. 4177 if (ToPtr1->isObjCClassType() && 4178 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4179 return ImplicitConversionSequence::Worse; 4180 if (ToPtr2->isObjCClassType() && 4181 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4182 return ImplicitConversionSequence::Better; 4183 4184 // A conversion to a non-Class object pointer type is better than a 4185 // conversion to a qualified 'Class' type. 4186 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4187 return ImplicitConversionSequence::Worse; 4188 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4189 return ImplicitConversionSequence::Better; 4190 4191 // -- "conversion of C* to B* is better than conversion of C* to A*," 4192 if (S.Context.hasSameType(FromType1, FromType2) && 4193 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4194 (ToAssignLeft != ToAssignRight)) { 4195 if (FromPtr1->isSpecialized()) { 4196 // "conversion of B<A> * to B * is better than conversion of B * to 4197 // C *. 4198 bool IsFirstSame = 4199 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl(); 4200 bool IsSecondSame = 4201 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl(); 4202 if (IsFirstSame) { 4203 if (!IsSecondSame) 4204 return ImplicitConversionSequence::Better; 4205 } else if (IsSecondSame) 4206 return ImplicitConversionSequence::Worse; 4207 } 4208 return ToAssignLeft? ImplicitConversionSequence::Worse 4209 : ImplicitConversionSequence::Better; 4210 } 4211 4212 // -- "conversion of B* to A* is better than conversion of C* to A*," 4213 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4214 (FromAssignLeft != FromAssignRight)) 4215 return FromAssignLeft? ImplicitConversionSequence::Better 4216 : ImplicitConversionSequence::Worse; 4217 } 4218 } 4219 4220 // Ranking of member-pointer types. 4221 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4222 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4223 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4224 const MemberPointerType * FromMemPointer1 = 4225 FromType1->getAs<MemberPointerType>(); 4226 const MemberPointerType * ToMemPointer1 = 4227 ToType1->getAs<MemberPointerType>(); 4228 const MemberPointerType * FromMemPointer2 = 4229 FromType2->getAs<MemberPointerType>(); 4230 const MemberPointerType * ToMemPointer2 = 4231 ToType2->getAs<MemberPointerType>(); 4232 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4233 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4234 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4235 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4236 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4237 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4238 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4239 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4240 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4241 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4242 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4243 return ImplicitConversionSequence::Worse; 4244 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4245 return ImplicitConversionSequence::Better; 4246 } 4247 // conversion of B::* to C::* is better than conversion of A::* to C::* 4248 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4249 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4250 return ImplicitConversionSequence::Better; 4251 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4252 return ImplicitConversionSequence::Worse; 4253 } 4254 } 4255 4256 if (SCS1.Second == ICK_Derived_To_Base) { 4257 // -- conversion of C to B is better than conversion of C to A, 4258 // -- binding of an expression of type C to a reference of type 4259 // B& is better than binding an expression of type C to a 4260 // reference of type A&, 4261 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4262 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4263 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4264 return ImplicitConversionSequence::Better; 4265 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4266 return ImplicitConversionSequence::Worse; 4267 } 4268 4269 // -- conversion of B to A is better than conversion of C to A. 4270 // -- binding of an expression of type B to a reference of type 4271 // A& is better than binding an expression of type C to a 4272 // reference of type A&, 4273 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4274 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4275 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4276 return ImplicitConversionSequence::Better; 4277 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4278 return ImplicitConversionSequence::Worse; 4279 } 4280 } 4281 4282 return ImplicitConversionSequence::Indistinguishable; 4283 } 4284 4285 /// Determine whether the given type is valid, e.g., it is not an invalid 4286 /// C++ class. 4287 static bool isTypeValid(QualType T) { 4288 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4289 return !Record->isInvalidDecl(); 4290 4291 return true; 4292 } 4293 4294 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4295 /// determine whether they are reference-related, 4296 /// reference-compatible, reference-compatible with added 4297 /// qualification, or incompatible, for use in C++ initialization by 4298 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4299 /// type, and the first type (T1) is the pointee type of the reference 4300 /// type being initialized. 4301 Sema::ReferenceCompareResult 4302 Sema::CompareReferenceRelationship(SourceLocation Loc, 4303 QualType OrigT1, QualType OrigT2, 4304 bool &DerivedToBase, 4305 bool &ObjCConversion, 4306 bool &ObjCLifetimeConversion) { 4307 assert(!OrigT1->isReferenceType() && 4308 "T1 must be the pointee type of the reference type"); 4309 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4310 4311 QualType T1 = Context.getCanonicalType(OrigT1); 4312 QualType T2 = Context.getCanonicalType(OrigT2); 4313 Qualifiers T1Quals, T2Quals; 4314 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4315 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4316 4317 // C++ [dcl.init.ref]p4: 4318 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4319 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4320 // T1 is a base class of T2. 4321 DerivedToBase = false; 4322 ObjCConversion = false; 4323 ObjCLifetimeConversion = false; 4324 QualType ConvertedT2; 4325 if (UnqualT1 == UnqualT2) { 4326 // Nothing to do. 4327 } else if (isCompleteType(Loc, OrigT2) && 4328 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4329 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4330 DerivedToBase = true; 4331 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4332 UnqualT2->isObjCObjectOrInterfaceType() && 4333 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4334 ObjCConversion = true; 4335 else if (UnqualT2->isFunctionType() && 4336 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) 4337 // C++1z [dcl.init.ref]p4: 4338 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept 4339 // function" and T1 is "function" 4340 // 4341 // We extend this to also apply to 'noreturn', so allow any function 4342 // conversion between function types. 4343 return Ref_Compatible; 4344 else 4345 return Ref_Incompatible; 4346 4347 // At this point, we know that T1 and T2 are reference-related (at 4348 // least). 4349 4350 // If the type is an array type, promote the element qualifiers to the type 4351 // for comparison. 4352 if (isa<ArrayType>(T1) && T1Quals) 4353 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4354 if (isa<ArrayType>(T2) && T2Quals) 4355 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4356 4357 // C++ [dcl.init.ref]p4: 4358 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4359 // reference-related to T2 and cv1 is the same cv-qualification 4360 // as, or greater cv-qualification than, cv2. For purposes of 4361 // overload resolution, cases for which cv1 is greater 4362 // cv-qualification than cv2 are identified as 4363 // reference-compatible with added qualification (see 13.3.3.2). 4364 // 4365 // Note that we also require equivalence of Objective-C GC and address-space 4366 // qualifiers when performing these computations, so that e.g., an int in 4367 // address space 1 is not reference-compatible with an int in address 4368 // space 2. 4369 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4370 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4371 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4372 ObjCLifetimeConversion = true; 4373 4374 T1Quals.removeObjCLifetime(); 4375 T2Quals.removeObjCLifetime(); 4376 } 4377 4378 // MS compiler ignores __unaligned qualifier for references; do the same. 4379 T1Quals.removeUnaligned(); 4380 T2Quals.removeUnaligned(); 4381 4382 if (T1Quals.compatiblyIncludes(T2Quals)) 4383 return Ref_Compatible; 4384 else 4385 return Ref_Related; 4386 } 4387 4388 /// Look for a user-defined conversion to a value reference-compatible 4389 /// with DeclType. Return true if something definite is found. 4390 static bool 4391 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4392 QualType DeclType, SourceLocation DeclLoc, 4393 Expr *Init, QualType T2, bool AllowRvalues, 4394 bool AllowExplicit) { 4395 assert(T2->isRecordType() && "Can only find conversions of record types."); 4396 CXXRecordDecl *T2RecordDecl 4397 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4398 4399 OverloadCandidateSet CandidateSet( 4400 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion); 4401 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4402 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4403 NamedDecl *D = *I; 4404 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4405 if (isa<UsingShadowDecl>(D)) 4406 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4407 4408 FunctionTemplateDecl *ConvTemplate 4409 = dyn_cast<FunctionTemplateDecl>(D); 4410 CXXConversionDecl *Conv; 4411 if (ConvTemplate) 4412 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4413 else 4414 Conv = cast<CXXConversionDecl>(D); 4415 4416 // If this is an explicit conversion, and we're not allowed to consider 4417 // explicit conversions, skip it. 4418 if (!AllowExplicit && Conv->isExplicit()) 4419 continue; 4420 4421 if (AllowRvalues) { 4422 bool DerivedToBase = false; 4423 bool ObjCConversion = false; 4424 bool ObjCLifetimeConversion = false; 4425 4426 // If we are initializing an rvalue reference, don't permit conversion 4427 // functions that return lvalues. 4428 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4429 const ReferenceType *RefType 4430 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4431 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4432 continue; 4433 } 4434 4435 if (!ConvTemplate && 4436 S.CompareReferenceRelationship( 4437 DeclLoc, 4438 Conv->getConversionType().getNonReferenceType() 4439 .getUnqualifiedType(), 4440 DeclType.getNonReferenceType().getUnqualifiedType(), 4441 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4442 Sema::Ref_Incompatible) 4443 continue; 4444 } else { 4445 // If the conversion function doesn't return a reference type, 4446 // it can't be considered for this conversion. An rvalue reference 4447 // is only acceptable if its referencee is a function type. 4448 4449 const ReferenceType *RefType = 4450 Conv->getConversionType()->getAs<ReferenceType>(); 4451 if (!RefType || 4452 (!RefType->isLValueReferenceType() && 4453 !RefType->getPointeeType()->isFunctionType())) 4454 continue; 4455 } 4456 4457 if (ConvTemplate) 4458 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4459 Init, DeclType, CandidateSet, 4460 /*AllowObjCConversionOnExplicit=*/false); 4461 else 4462 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4463 DeclType, CandidateSet, 4464 /*AllowObjCConversionOnExplicit=*/false); 4465 } 4466 4467 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4468 4469 OverloadCandidateSet::iterator Best; 4470 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) { 4471 case OR_Success: 4472 // C++ [over.ics.ref]p1: 4473 // 4474 // [...] If the parameter binds directly to the result of 4475 // applying a conversion function to the argument 4476 // expression, the implicit conversion sequence is a 4477 // user-defined conversion sequence (13.3.3.1.2), with the 4478 // second standard conversion sequence either an identity 4479 // conversion or, if the conversion function returns an 4480 // entity of a type that is a derived class of the parameter 4481 // type, a derived-to-base Conversion. 4482 if (!Best->FinalConversion.DirectBinding) 4483 return false; 4484 4485 ICS.setUserDefined(); 4486 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4487 ICS.UserDefined.After = Best->FinalConversion; 4488 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4489 ICS.UserDefined.ConversionFunction = Best->Function; 4490 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4491 ICS.UserDefined.EllipsisConversion = false; 4492 assert(ICS.UserDefined.After.ReferenceBinding && 4493 ICS.UserDefined.After.DirectBinding && 4494 "Expected a direct reference binding!"); 4495 return true; 4496 4497 case OR_Ambiguous: 4498 ICS.setAmbiguous(); 4499 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4500 Cand != CandidateSet.end(); ++Cand) 4501 if (Cand->Viable) 4502 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4503 return true; 4504 4505 case OR_No_Viable_Function: 4506 case OR_Deleted: 4507 // There was no suitable conversion, or we found a deleted 4508 // conversion; continue with other checks. 4509 return false; 4510 } 4511 4512 llvm_unreachable("Invalid OverloadResult!"); 4513 } 4514 4515 /// Compute an implicit conversion sequence for reference 4516 /// initialization. 4517 static ImplicitConversionSequence 4518 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4519 SourceLocation DeclLoc, 4520 bool SuppressUserConversions, 4521 bool AllowExplicit) { 4522 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4523 4524 // Most paths end in a failed conversion. 4525 ImplicitConversionSequence ICS; 4526 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4527 4528 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4529 QualType T2 = Init->getType(); 4530 4531 // If the initializer is the address of an overloaded function, try 4532 // to resolve the overloaded function. If all goes well, T2 is the 4533 // type of the resulting function. 4534 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4535 DeclAccessPair Found; 4536 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4537 false, Found)) 4538 T2 = Fn->getType(); 4539 } 4540 4541 // Compute some basic properties of the types and the initializer. 4542 bool isRValRef = DeclType->isRValueReferenceType(); 4543 bool DerivedToBase = false; 4544 bool ObjCConversion = false; 4545 bool ObjCLifetimeConversion = false; 4546 Expr::Classification InitCategory = Init->Classify(S.Context); 4547 Sema::ReferenceCompareResult RefRelationship 4548 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4549 ObjCConversion, ObjCLifetimeConversion); 4550 4551 4552 // C++0x [dcl.init.ref]p5: 4553 // A reference to type "cv1 T1" is initialized by an expression 4554 // of type "cv2 T2" as follows: 4555 4556 // -- If reference is an lvalue reference and the initializer expression 4557 if (!isRValRef) { 4558 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4559 // reference-compatible with "cv2 T2," or 4560 // 4561 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4562 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4563 // C++ [over.ics.ref]p1: 4564 // When a parameter of reference type binds directly (8.5.3) 4565 // to an argument expression, the implicit conversion sequence 4566 // is the identity conversion, unless the argument expression 4567 // has a type that is a derived class of the parameter type, 4568 // in which case the implicit conversion sequence is a 4569 // derived-to-base Conversion (13.3.3.1). 4570 ICS.setStandard(); 4571 ICS.Standard.First = ICK_Identity; 4572 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4573 : ObjCConversion? ICK_Compatible_Conversion 4574 : ICK_Identity; 4575 ICS.Standard.Third = ICK_Identity; 4576 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4577 ICS.Standard.setToType(0, T2); 4578 ICS.Standard.setToType(1, T1); 4579 ICS.Standard.setToType(2, T1); 4580 ICS.Standard.ReferenceBinding = true; 4581 ICS.Standard.DirectBinding = true; 4582 ICS.Standard.IsLvalueReference = !isRValRef; 4583 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4584 ICS.Standard.BindsToRvalue = false; 4585 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4586 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4587 ICS.Standard.CopyConstructor = nullptr; 4588 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4589 4590 // Nothing more to do: the inaccessibility/ambiguity check for 4591 // derived-to-base conversions is suppressed when we're 4592 // computing the implicit conversion sequence (C++ 4593 // [over.best.ics]p2). 4594 return ICS; 4595 } 4596 4597 // -- has a class type (i.e., T2 is a class type), where T1 is 4598 // not reference-related to T2, and can be implicitly 4599 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4600 // is reference-compatible with "cv3 T3" 92) (this 4601 // conversion is selected by enumerating the applicable 4602 // conversion functions (13.3.1.6) and choosing the best 4603 // one through overload resolution (13.3)), 4604 if (!SuppressUserConversions && T2->isRecordType() && 4605 S.isCompleteType(DeclLoc, T2) && 4606 RefRelationship == Sema::Ref_Incompatible) { 4607 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4608 Init, T2, /*AllowRvalues=*/false, 4609 AllowExplicit)) 4610 return ICS; 4611 } 4612 } 4613 4614 // -- Otherwise, the reference shall be an lvalue reference to a 4615 // non-volatile const type (i.e., cv1 shall be const), or the reference 4616 // shall be an rvalue reference. 4617 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4618 return ICS; 4619 4620 // -- If the initializer expression 4621 // 4622 // -- is an xvalue, class prvalue, array prvalue or function 4623 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4624 if (RefRelationship == Sema::Ref_Compatible && 4625 (InitCategory.isXValue() || 4626 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4627 (InitCategory.isLValue() && T2->isFunctionType()))) { 4628 ICS.setStandard(); 4629 ICS.Standard.First = ICK_Identity; 4630 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4631 : ObjCConversion? ICK_Compatible_Conversion 4632 : ICK_Identity; 4633 ICS.Standard.Third = ICK_Identity; 4634 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4635 ICS.Standard.setToType(0, T2); 4636 ICS.Standard.setToType(1, T1); 4637 ICS.Standard.setToType(2, T1); 4638 ICS.Standard.ReferenceBinding = true; 4639 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4640 // binding unless we're binding to a class prvalue. 4641 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4642 // allow the use of rvalue references in C++98/03 for the benefit of 4643 // standard library implementors; therefore, we need the xvalue check here. 4644 ICS.Standard.DirectBinding = 4645 S.getLangOpts().CPlusPlus11 || 4646 !(InitCategory.isPRValue() || T2->isRecordType()); 4647 ICS.Standard.IsLvalueReference = !isRValRef; 4648 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4649 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4650 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4651 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4652 ICS.Standard.CopyConstructor = nullptr; 4653 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4654 return ICS; 4655 } 4656 4657 // -- has a class type (i.e., T2 is a class type), where T1 is not 4658 // reference-related to T2, and can be implicitly converted to 4659 // an xvalue, class prvalue, or function lvalue of type 4660 // "cv3 T3", where "cv1 T1" is reference-compatible with 4661 // "cv3 T3", 4662 // 4663 // then the reference is bound to the value of the initializer 4664 // expression in the first case and to the result of the conversion 4665 // in the second case (or, in either case, to an appropriate base 4666 // class subobject). 4667 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4668 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4669 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4670 Init, T2, /*AllowRvalues=*/true, 4671 AllowExplicit)) { 4672 // In the second case, if the reference is an rvalue reference 4673 // and the second standard conversion sequence of the 4674 // user-defined conversion sequence includes an lvalue-to-rvalue 4675 // conversion, the program is ill-formed. 4676 if (ICS.isUserDefined() && isRValRef && 4677 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4678 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4679 4680 return ICS; 4681 } 4682 4683 // A temporary of function type cannot be created; don't even try. 4684 if (T1->isFunctionType()) 4685 return ICS; 4686 4687 // -- Otherwise, a temporary of type "cv1 T1" is created and 4688 // initialized from the initializer expression using the 4689 // rules for a non-reference copy initialization (8.5). The 4690 // reference is then bound to the temporary. If T1 is 4691 // reference-related to T2, cv1 must be the same 4692 // cv-qualification as, or greater cv-qualification than, 4693 // cv2; otherwise, the program is ill-formed. 4694 if (RefRelationship == Sema::Ref_Related) { 4695 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4696 // we would be reference-compatible or reference-compatible with 4697 // added qualification. But that wasn't the case, so the reference 4698 // initialization fails. 4699 // 4700 // Note that we only want to check address spaces and cvr-qualifiers here. 4701 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4702 Qualifiers T1Quals = T1.getQualifiers(); 4703 Qualifiers T2Quals = T2.getQualifiers(); 4704 T1Quals.removeObjCGCAttr(); 4705 T1Quals.removeObjCLifetime(); 4706 T2Quals.removeObjCGCAttr(); 4707 T2Quals.removeObjCLifetime(); 4708 // MS compiler ignores __unaligned qualifier for references; do the same. 4709 T1Quals.removeUnaligned(); 4710 T2Quals.removeUnaligned(); 4711 if (!T1Quals.compatiblyIncludes(T2Quals)) 4712 return ICS; 4713 } 4714 4715 // If at least one of the types is a class type, the types are not 4716 // related, and we aren't allowed any user conversions, the 4717 // reference binding fails. This case is important for breaking 4718 // recursion, since TryImplicitConversion below will attempt to 4719 // create a temporary through the use of a copy constructor. 4720 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4721 (T1->isRecordType() || T2->isRecordType())) 4722 return ICS; 4723 4724 // If T1 is reference-related to T2 and the reference is an rvalue 4725 // reference, the initializer expression shall not be an lvalue. 4726 if (RefRelationship >= Sema::Ref_Related && 4727 isRValRef && Init->Classify(S.Context).isLValue()) 4728 return ICS; 4729 4730 // C++ [over.ics.ref]p2: 4731 // When a parameter of reference type is not bound directly to 4732 // an argument expression, the conversion sequence is the one 4733 // required to convert the argument expression to the 4734 // underlying type of the reference according to 4735 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4736 // to copy-initializing a temporary of the underlying type with 4737 // the argument expression. Any difference in top-level 4738 // cv-qualification is subsumed by the initialization itself 4739 // and does not constitute a conversion. 4740 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4741 /*AllowExplicit=*/false, 4742 /*InOverloadResolution=*/false, 4743 /*CStyle=*/false, 4744 /*AllowObjCWritebackConversion=*/false, 4745 /*AllowObjCConversionOnExplicit=*/false); 4746 4747 // Of course, that's still a reference binding. 4748 if (ICS.isStandard()) { 4749 ICS.Standard.ReferenceBinding = true; 4750 ICS.Standard.IsLvalueReference = !isRValRef; 4751 ICS.Standard.BindsToFunctionLvalue = false; 4752 ICS.Standard.BindsToRvalue = true; 4753 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4754 ICS.Standard.ObjCLifetimeConversionBinding = false; 4755 } else if (ICS.isUserDefined()) { 4756 const ReferenceType *LValRefType = 4757 ICS.UserDefined.ConversionFunction->getReturnType() 4758 ->getAs<LValueReferenceType>(); 4759 4760 // C++ [over.ics.ref]p3: 4761 // Except for an implicit object parameter, for which see 13.3.1, a 4762 // standard conversion sequence cannot be formed if it requires [...] 4763 // binding an rvalue reference to an lvalue other than a function 4764 // lvalue. 4765 // Note that the function case is not possible here. 4766 if (DeclType->isRValueReferenceType() && LValRefType) { 4767 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4768 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4769 // reference to an rvalue! 4770 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4771 return ICS; 4772 } 4773 4774 ICS.UserDefined.After.ReferenceBinding = true; 4775 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4776 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4777 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4778 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4779 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4780 } 4781 4782 return ICS; 4783 } 4784 4785 static ImplicitConversionSequence 4786 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4787 bool SuppressUserConversions, 4788 bool InOverloadResolution, 4789 bool AllowObjCWritebackConversion, 4790 bool AllowExplicit = false); 4791 4792 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4793 /// initializer list From. 4794 static ImplicitConversionSequence 4795 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4796 bool SuppressUserConversions, 4797 bool InOverloadResolution, 4798 bool AllowObjCWritebackConversion) { 4799 // C++11 [over.ics.list]p1: 4800 // When an argument is an initializer list, it is not an expression and 4801 // special rules apply for converting it to a parameter type. 4802 4803 ImplicitConversionSequence Result; 4804 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4805 4806 // We need a complete type for what follows. Incomplete types can never be 4807 // initialized from init lists. 4808 if (!S.isCompleteType(From->getBeginLoc(), ToType)) 4809 return Result; 4810 4811 // Per DR1467: 4812 // If the parameter type is a class X and the initializer list has a single 4813 // element of type cv U, where U is X or a class derived from X, the 4814 // implicit conversion sequence is the one required to convert the element 4815 // to the parameter type. 4816 // 4817 // Otherwise, if the parameter type is a character array [... ] 4818 // and the initializer list has a single element that is an 4819 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4820 // implicit conversion sequence is the identity conversion. 4821 if (From->getNumInits() == 1) { 4822 if (ToType->isRecordType()) { 4823 QualType InitType = From->getInit(0)->getType(); 4824 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4825 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType)) 4826 return TryCopyInitialization(S, From->getInit(0), ToType, 4827 SuppressUserConversions, 4828 InOverloadResolution, 4829 AllowObjCWritebackConversion); 4830 } 4831 // FIXME: Check the other conditions here: array of character type, 4832 // initializer is a string literal. 4833 if (ToType->isArrayType()) { 4834 InitializedEntity Entity = 4835 InitializedEntity::InitializeParameter(S.Context, ToType, 4836 /*Consumed=*/false); 4837 if (S.CanPerformCopyInitialization(Entity, From)) { 4838 Result.setStandard(); 4839 Result.Standard.setAsIdentityConversion(); 4840 Result.Standard.setFromType(ToType); 4841 Result.Standard.setAllToTypes(ToType); 4842 return Result; 4843 } 4844 } 4845 } 4846 4847 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4848 // C++11 [over.ics.list]p2: 4849 // If the parameter type is std::initializer_list<X> or "array of X" and 4850 // all the elements can be implicitly converted to X, the implicit 4851 // conversion sequence is the worst conversion necessary to convert an 4852 // element of the list to X. 4853 // 4854 // C++14 [over.ics.list]p3: 4855 // Otherwise, if the parameter type is "array of N X", if the initializer 4856 // list has exactly N elements or if it has fewer than N elements and X is 4857 // default-constructible, and if all the elements of the initializer list 4858 // can be implicitly converted to X, the implicit conversion sequence is 4859 // the worst conversion necessary to convert an element of the list to X. 4860 // 4861 // FIXME: We're missing a lot of these checks. 4862 bool toStdInitializerList = false; 4863 QualType X; 4864 if (ToType->isArrayType()) 4865 X = S.Context.getAsArrayType(ToType)->getElementType(); 4866 else 4867 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4868 if (!X.isNull()) { 4869 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4870 Expr *Init = From->getInit(i); 4871 ImplicitConversionSequence ICS = 4872 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4873 InOverloadResolution, 4874 AllowObjCWritebackConversion); 4875 // If a single element isn't convertible, fail. 4876 if (ICS.isBad()) { 4877 Result = ICS; 4878 break; 4879 } 4880 // Otherwise, look for the worst conversion. 4881 if (Result.isBad() || CompareImplicitConversionSequences( 4882 S, From->getBeginLoc(), ICS, Result) == 4883 ImplicitConversionSequence::Worse) 4884 Result = ICS; 4885 } 4886 4887 // For an empty list, we won't have computed any conversion sequence. 4888 // Introduce the identity conversion sequence. 4889 if (From->getNumInits() == 0) { 4890 Result.setStandard(); 4891 Result.Standard.setAsIdentityConversion(); 4892 Result.Standard.setFromType(ToType); 4893 Result.Standard.setAllToTypes(ToType); 4894 } 4895 4896 Result.setStdInitializerListElement(toStdInitializerList); 4897 return Result; 4898 } 4899 4900 // C++14 [over.ics.list]p4: 4901 // C++11 [over.ics.list]p3: 4902 // Otherwise, if the parameter is a non-aggregate class X and overload 4903 // resolution chooses a single best constructor [...] the implicit 4904 // conversion sequence is a user-defined conversion sequence. If multiple 4905 // constructors are viable but none is better than the others, the 4906 // implicit conversion sequence is a user-defined conversion sequence. 4907 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4908 // This function can deal with initializer lists. 4909 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4910 /*AllowExplicit=*/false, 4911 InOverloadResolution, /*CStyle=*/false, 4912 AllowObjCWritebackConversion, 4913 /*AllowObjCConversionOnExplicit=*/false); 4914 } 4915 4916 // C++14 [over.ics.list]p5: 4917 // C++11 [over.ics.list]p4: 4918 // Otherwise, if the parameter has an aggregate type which can be 4919 // initialized from the initializer list [...] the implicit conversion 4920 // sequence is a user-defined conversion sequence. 4921 if (ToType->isAggregateType()) { 4922 // Type is an aggregate, argument is an init list. At this point it comes 4923 // down to checking whether the initialization works. 4924 // FIXME: Find out whether this parameter is consumed or not. 4925 // FIXME: Expose SemaInit's aggregate initialization code so that we don't 4926 // need to call into the initialization code here; overload resolution 4927 // should not be doing that. 4928 InitializedEntity Entity = 4929 InitializedEntity::InitializeParameter(S.Context, ToType, 4930 /*Consumed=*/false); 4931 if (S.CanPerformCopyInitialization(Entity, From)) { 4932 Result.setUserDefined(); 4933 Result.UserDefined.Before.setAsIdentityConversion(); 4934 // Initializer lists don't have a type. 4935 Result.UserDefined.Before.setFromType(QualType()); 4936 Result.UserDefined.Before.setAllToTypes(QualType()); 4937 4938 Result.UserDefined.After.setAsIdentityConversion(); 4939 Result.UserDefined.After.setFromType(ToType); 4940 Result.UserDefined.After.setAllToTypes(ToType); 4941 Result.UserDefined.ConversionFunction = nullptr; 4942 } 4943 return Result; 4944 } 4945 4946 // C++14 [over.ics.list]p6: 4947 // C++11 [over.ics.list]p5: 4948 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4949 if (ToType->isReferenceType()) { 4950 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4951 // mention initializer lists in any way. So we go by what list- 4952 // initialization would do and try to extrapolate from that. 4953 4954 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4955 4956 // If the initializer list has a single element that is reference-related 4957 // to the parameter type, we initialize the reference from that. 4958 if (From->getNumInits() == 1) { 4959 Expr *Init = From->getInit(0); 4960 4961 QualType T2 = Init->getType(); 4962 4963 // If the initializer is the address of an overloaded function, try 4964 // to resolve the overloaded function. If all goes well, T2 is the 4965 // type of the resulting function. 4966 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4967 DeclAccessPair Found; 4968 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4969 Init, ToType, false, Found)) 4970 T2 = Fn->getType(); 4971 } 4972 4973 // Compute some basic properties of the types and the initializer. 4974 bool dummy1 = false; 4975 bool dummy2 = false; 4976 bool dummy3 = false; 4977 Sema::ReferenceCompareResult RefRelationship = 4978 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1, 4979 dummy2, dummy3); 4980 4981 if (RefRelationship >= Sema::Ref_Related) { 4982 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(), 4983 SuppressUserConversions, 4984 /*AllowExplicit=*/false); 4985 } 4986 } 4987 4988 // Otherwise, we bind the reference to a temporary created from the 4989 // initializer list. 4990 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4991 InOverloadResolution, 4992 AllowObjCWritebackConversion); 4993 if (Result.isFailure()) 4994 return Result; 4995 assert(!Result.isEllipsis() && 4996 "Sub-initialization cannot result in ellipsis conversion."); 4997 4998 // Can we even bind to a temporary? 4999 if (ToType->isRValueReferenceType() || 5000 (T1.isConstQualified() && !T1.isVolatileQualified())) { 5001 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 5002 Result.UserDefined.After; 5003 SCS.ReferenceBinding = true; 5004 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 5005 SCS.BindsToRvalue = true; 5006 SCS.BindsToFunctionLvalue = false; 5007 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 5008 SCS.ObjCLifetimeConversionBinding = false; 5009 } else 5010 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 5011 From, ToType); 5012 return Result; 5013 } 5014 5015 // C++14 [over.ics.list]p7: 5016 // C++11 [over.ics.list]p6: 5017 // Otherwise, if the parameter type is not a class: 5018 if (!ToType->isRecordType()) { 5019 // - if the initializer list has one element that is not itself an 5020 // initializer list, the implicit conversion sequence is the one 5021 // required to convert the element to the parameter type. 5022 unsigned NumInits = From->getNumInits(); 5023 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 5024 Result = TryCopyInitialization(S, From->getInit(0), ToType, 5025 SuppressUserConversions, 5026 InOverloadResolution, 5027 AllowObjCWritebackConversion); 5028 // - if the initializer list has no elements, the implicit conversion 5029 // sequence is the identity conversion. 5030 else if (NumInits == 0) { 5031 Result.setStandard(); 5032 Result.Standard.setAsIdentityConversion(); 5033 Result.Standard.setFromType(ToType); 5034 Result.Standard.setAllToTypes(ToType); 5035 } 5036 return Result; 5037 } 5038 5039 // C++14 [over.ics.list]p8: 5040 // C++11 [over.ics.list]p7: 5041 // In all cases other than those enumerated above, no conversion is possible 5042 return Result; 5043 } 5044 5045 /// TryCopyInitialization - Try to copy-initialize a value of type 5046 /// ToType from the expression From. Return the implicit conversion 5047 /// sequence required to pass this argument, which may be a bad 5048 /// conversion sequence (meaning that the argument cannot be passed to 5049 /// a parameter of this type). If @p SuppressUserConversions, then we 5050 /// do not permit any user-defined conversion sequences. 5051 static ImplicitConversionSequence 5052 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 5053 bool SuppressUserConversions, 5054 bool InOverloadResolution, 5055 bool AllowObjCWritebackConversion, 5056 bool AllowExplicit) { 5057 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 5058 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 5059 InOverloadResolution,AllowObjCWritebackConversion); 5060 5061 if (ToType->isReferenceType()) 5062 return TryReferenceInit(S, From, ToType, 5063 /*FIXME:*/ From->getBeginLoc(), 5064 SuppressUserConversions, AllowExplicit); 5065 5066 return TryImplicitConversion(S, From, ToType, 5067 SuppressUserConversions, 5068 /*AllowExplicit=*/false, 5069 InOverloadResolution, 5070 /*CStyle=*/false, 5071 AllowObjCWritebackConversion, 5072 /*AllowObjCConversionOnExplicit=*/false); 5073 } 5074 5075 static bool TryCopyInitialization(const CanQualType FromQTy, 5076 const CanQualType ToQTy, 5077 Sema &S, 5078 SourceLocation Loc, 5079 ExprValueKind FromVK) { 5080 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 5081 ImplicitConversionSequence ICS = 5082 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 5083 5084 return !ICS.isBad(); 5085 } 5086 5087 /// TryObjectArgumentInitialization - Try to initialize the object 5088 /// parameter of the given member function (@c Method) from the 5089 /// expression @p From. 5090 static ImplicitConversionSequence 5091 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 5092 Expr::Classification FromClassification, 5093 CXXMethodDecl *Method, 5094 CXXRecordDecl *ActingContext) { 5095 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 5096 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 5097 // const volatile object. 5098 Qualifiers Quals; 5099 if (isa<CXXDestructorDecl>(Method)) { 5100 Quals.addConst(); 5101 Quals.addVolatile(); 5102 } else { 5103 Quals = Method->getMethodQualifiers(); 5104 } 5105 5106 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals); 5107 5108 // Set up the conversion sequence as a "bad" conversion, to allow us 5109 // to exit early. 5110 ImplicitConversionSequence ICS; 5111 5112 // We need to have an object of class type. 5113 if (const PointerType *PT = FromType->getAs<PointerType>()) { 5114 FromType = PT->getPointeeType(); 5115 5116 // When we had a pointer, it's implicitly dereferenced, so we 5117 // better have an lvalue. 5118 assert(FromClassification.isLValue()); 5119 } 5120 5121 assert(FromType->isRecordType()); 5122 5123 // C++0x [over.match.funcs]p4: 5124 // For non-static member functions, the type of the implicit object 5125 // parameter is 5126 // 5127 // - "lvalue reference to cv X" for functions declared without a 5128 // ref-qualifier or with the & ref-qualifier 5129 // - "rvalue reference to cv X" for functions declared with the && 5130 // ref-qualifier 5131 // 5132 // where X is the class of which the function is a member and cv is the 5133 // cv-qualification on the member function declaration. 5134 // 5135 // However, when finding an implicit conversion sequence for the argument, we 5136 // are not allowed to perform user-defined conversions 5137 // (C++ [over.match.funcs]p5). We perform a simplified version of 5138 // reference binding here, that allows class rvalues to bind to 5139 // non-constant references. 5140 5141 // First check the qualifiers. 5142 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 5143 if (ImplicitParamType.getCVRQualifiers() 5144 != FromTypeCanon.getLocalCVRQualifiers() && 5145 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5146 ICS.setBad(BadConversionSequence::bad_qualifiers, 5147 FromType, ImplicitParamType); 5148 return ICS; 5149 } 5150 5151 if (FromTypeCanon.getQualifiers().hasAddressSpace()) { 5152 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers(); 5153 Qualifiers QualsFromType = FromTypeCanon.getQualifiers(); 5154 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) { 5155 ICS.setBad(BadConversionSequence::bad_qualifiers, 5156 FromType, ImplicitParamType); 5157 return ICS; 5158 } 5159 } 5160 5161 // Check that we have either the same type or a derived type. It 5162 // affects the conversion rank. 5163 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5164 ImplicitConversionKind SecondKind; 5165 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5166 SecondKind = ICK_Identity; 5167 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5168 SecondKind = ICK_Derived_To_Base; 5169 else { 5170 ICS.setBad(BadConversionSequence::unrelated_class, 5171 FromType, ImplicitParamType); 5172 return ICS; 5173 } 5174 5175 // Check the ref-qualifier. 5176 switch (Method->getRefQualifier()) { 5177 case RQ_None: 5178 // Do nothing; we don't care about lvalueness or rvalueness. 5179 break; 5180 5181 case RQ_LValue: 5182 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) { 5183 // non-const lvalue reference cannot bind to an rvalue 5184 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5185 ImplicitParamType); 5186 return ICS; 5187 } 5188 break; 5189 5190 case RQ_RValue: 5191 if (!FromClassification.isRValue()) { 5192 // rvalue reference cannot bind to an lvalue 5193 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5194 ImplicitParamType); 5195 return ICS; 5196 } 5197 break; 5198 } 5199 5200 // Success. Mark this as a reference binding. 5201 ICS.setStandard(); 5202 ICS.Standard.setAsIdentityConversion(); 5203 ICS.Standard.Second = SecondKind; 5204 ICS.Standard.setFromType(FromType); 5205 ICS.Standard.setAllToTypes(ImplicitParamType); 5206 ICS.Standard.ReferenceBinding = true; 5207 ICS.Standard.DirectBinding = true; 5208 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5209 ICS.Standard.BindsToFunctionLvalue = false; 5210 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5211 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5212 = (Method->getRefQualifier() == RQ_None); 5213 return ICS; 5214 } 5215 5216 /// PerformObjectArgumentInitialization - Perform initialization of 5217 /// the implicit object parameter for the given Method with the given 5218 /// expression. 5219 ExprResult 5220 Sema::PerformObjectArgumentInitialization(Expr *From, 5221 NestedNameSpecifier *Qualifier, 5222 NamedDecl *FoundDecl, 5223 CXXMethodDecl *Method) { 5224 QualType FromRecordType, DestType; 5225 QualType ImplicitParamRecordType = 5226 Method->getThisType()->getAs<PointerType>()->getPointeeType(); 5227 5228 Expr::Classification FromClassification; 5229 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5230 FromRecordType = PT->getPointeeType(); 5231 DestType = Method->getThisType(); 5232 FromClassification = Expr::Classification::makeSimpleLValue(); 5233 } else { 5234 FromRecordType = From->getType(); 5235 DestType = ImplicitParamRecordType; 5236 FromClassification = From->Classify(Context); 5237 5238 // When performing member access on an rvalue, materialize a temporary. 5239 if (From->isRValue()) { 5240 From = CreateMaterializeTemporaryExpr(FromRecordType, From, 5241 Method->getRefQualifier() != 5242 RefQualifierKind::RQ_RValue); 5243 } 5244 } 5245 5246 // Note that we always use the true parent context when performing 5247 // the actual argument initialization. 5248 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5249 *this, From->getBeginLoc(), From->getType(), FromClassification, Method, 5250 Method->getParent()); 5251 if (ICS.isBad()) { 5252 switch (ICS.Bad.Kind) { 5253 case BadConversionSequence::bad_qualifiers: { 5254 Qualifiers FromQs = FromRecordType.getQualifiers(); 5255 Qualifiers ToQs = DestType.getQualifiers(); 5256 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5257 if (CVR) { 5258 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr) 5259 << Method->getDeclName() << FromRecordType << (CVR - 1) 5260 << From->getSourceRange(); 5261 Diag(Method->getLocation(), diag::note_previous_decl) 5262 << Method->getDeclName(); 5263 return ExprError(); 5264 } 5265 break; 5266 } 5267 5268 case BadConversionSequence::lvalue_ref_to_rvalue: 5269 case BadConversionSequence::rvalue_ref_to_lvalue: { 5270 bool IsRValueQualified = 5271 Method->getRefQualifier() == RefQualifierKind::RQ_RValue; 5272 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref) 5273 << Method->getDeclName() << FromClassification.isRValue() 5274 << IsRValueQualified; 5275 Diag(Method->getLocation(), diag::note_previous_decl) 5276 << Method->getDeclName(); 5277 return ExprError(); 5278 } 5279 5280 case BadConversionSequence::no_conversion: 5281 case BadConversionSequence::unrelated_class: 5282 break; 5283 } 5284 5285 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type) 5286 << ImplicitParamRecordType << FromRecordType 5287 << From->getSourceRange(); 5288 } 5289 5290 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5291 ExprResult FromRes = 5292 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5293 if (FromRes.isInvalid()) 5294 return ExprError(); 5295 From = FromRes.get(); 5296 } 5297 5298 if (!Context.hasSameType(From->getType(), DestType)) { 5299 if (From->getType().getAddressSpace() != DestType.getAddressSpace()) 5300 From = ImpCastExprToType(From, DestType, CK_AddressSpaceConversion, 5301 From->getValueKind()).get(); 5302 else 5303 From = ImpCastExprToType(From, DestType, CK_NoOp, 5304 From->getValueKind()).get(); 5305 } 5306 return From; 5307 } 5308 5309 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5310 /// expression From to bool (C++0x [conv]p3). 5311 static ImplicitConversionSequence 5312 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5313 return TryImplicitConversion(S, From, S.Context.BoolTy, 5314 /*SuppressUserConversions=*/false, 5315 /*AllowExplicit=*/true, 5316 /*InOverloadResolution=*/false, 5317 /*CStyle=*/false, 5318 /*AllowObjCWritebackConversion=*/false, 5319 /*AllowObjCConversionOnExplicit=*/false); 5320 } 5321 5322 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5323 /// of the expression From to bool (C++0x [conv]p3). 5324 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5325 if (checkPlaceholderForOverload(*this, From)) 5326 return ExprError(); 5327 5328 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5329 if (!ICS.isBad()) 5330 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5331 5332 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5333 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition) 5334 << From->getType() << From->getSourceRange(); 5335 return ExprError(); 5336 } 5337 5338 /// Check that the specified conversion is permitted in a converted constant 5339 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5340 /// is acceptable. 5341 static bool CheckConvertedConstantConversions(Sema &S, 5342 StandardConversionSequence &SCS) { 5343 // Since we know that the target type is an integral or unscoped enumeration 5344 // type, most conversion kinds are impossible. All possible First and Third 5345 // conversions are fine. 5346 switch (SCS.Second) { 5347 case ICK_Identity: 5348 case ICK_Function_Conversion: 5349 case ICK_Integral_Promotion: 5350 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5351 case ICK_Zero_Queue_Conversion: 5352 return true; 5353 5354 case ICK_Boolean_Conversion: 5355 // Conversion from an integral or unscoped enumeration type to bool is 5356 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5357 // conversion, so we allow it in a converted constant expression. 5358 // 5359 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5360 // a lot of popular code. We should at least add a warning for this 5361 // (non-conforming) extension. 5362 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5363 SCS.getToType(2)->isBooleanType(); 5364 5365 case ICK_Pointer_Conversion: 5366 case ICK_Pointer_Member: 5367 // C++1z: null pointer conversions and null member pointer conversions are 5368 // only permitted if the source type is std::nullptr_t. 5369 return SCS.getFromType()->isNullPtrType(); 5370 5371 case ICK_Floating_Promotion: 5372 case ICK_Complex_Promotion: 5373 case ICK_Floating_Conversion: 5374 case ICK_Complex_Conversion: 5375 case ICK_Floating_Integral: 5376 case ICK_Compatible_Conversion: 5377 case ICK_Derived_To_Base: 5378 case ICK_Vector_Conversion: 5379 case ICK_Vector_Splat: 5380 case ICK_Complex_Real: 5381 case ICK_Block_Pointer_Conversion: 5382 case ICK_TransparentUnionConversion: 5383 case ICK_Writeback_Conversion: 5384 case ICK_Zero_Event_Conversion: 5385 case ICK_C_Only_Conversion: 5386 case ICK_Incompatible_Pointer_Conversion: 5387 return false; 5388 5389 case ICK_Lvalue_To_Rvalue: 5390 case ICK_Array_To_Pointer: 5391 case ICK_Function_To_Pointer: 5392 llvm_unreachable("found a first conversion kind in Second"); 5393 5394 case ICK_Qualification: 5395 llvm_unreachable("found a third conversion kind in Second"); 5396 5397 case ICK_Num_Conversion_Kinds: 5398 break; 5399 } 5400 5401 llvm_unreachable("unknown conversion kind"); 5402 } 5403 5404 /// CheckConvertedConstantExpression - Check that the expression From is a 5405 /// converted constant expression of type T, perform the conversion and produce 5406 /// the converted expression, per C++11 [expr.const]p3. 5407 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5408 QualType T, APValue &Value, 5409 Sema::CCEKind CCE, 5410 bool RequireInt) { 5411 assert(S.getLangOpts().CPlusPlus11 && 5412 "converted constant expression outside C++11"); 5413 5414 if (checkPlaceholderForOverload(S, From)) 5415 return ExprError(); 5416 5417 // C++1z [expr.const]p3: 5418 // A converted constant expression of type T is an expression, 5419 // implicitly converted to type T, where the converted 5420 // expression is a constant expression and the implicit conversion 5421 // sequence contains only [... list of conversions ...]. 5422 // C++1z [stmt.if]p2: 5423 // If the if statement is of the form if constexpr, the value of the 5424 // condition shall be a contextually converted constant expression of type 5425 // bool. 5426 ImplicitConversionSequence ICS = 5427 CCE == Sema::CCEK_ConstexprIf 5428 ? TryContextuallyConvertToBool(S, From) 5429 : TryCopyInitialization(S, From, T, 5430 /*SuppressUserConversions=*/false, 5431 /*InOverloadResolution=*/false, 5432 /*AllowObjcWritebackConversion=*/false, 5433 /*AllowExplicit=*/false); 5434 StandardConversionSequence *SCS = nullptr; 5435 switch (ICS.getKind()) { 5436 case ImplicitConversionSequence::StandardConversion: 5437 SCS = &ICS.Standard; 5438 break; 5439 case ImplicitConversionSequence::UserDefinedConversion: 5440 // We are converting to a non-class type, so the Before sequence 5441 // must be trivial. 5442 SCS = &ICS.UserDefined.After; 5443 break; 5444 case ImplicitConversionSequence::AmbiguousConversion: 5445 case ImplicitConversionSequence::BadConversion: 5446 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5447 return S.Diag(From->getBeginLoc(), 5448 diag::err_typecheck_converted_constant_expression) 5449 << From->getType() << From->getSourceRange() << T; 5450 return ExprError(); 5451 5452 case ImplicitConversionSequence::EllipsisConversion: 5453 llvm_unreachable("ellipsis conversion in converted constant expression"); 5454 } 5455 5456 // Check that we would only use permitted conversions. 5457 if (!CheckConvertedConstantConversions(S, *SCS)) { 5458 return S.Diag(From->getBeginLoc(), 5459 diag::err_typecheck_converted_constant_expression_disallowed) 5460 << From->getType() << From->getSourceRange() << T; 5461 } 5462 // [...] and where the reference binding (if any) binds directly. 5463 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5464 return S.Diag(From->getBeginLoc(), 5465 diag::err_typecheck_converted_constant_expression_indirect) 5466 << From->getType() << From->getSourceRange() << T; 5467 } 5468 5469 ExprResult Result = 5470 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5471 if (Result.isInvalid()) 5472 return Result; 5473 5474 // Check for a narrowing implicit conversion. 5475 APValue PreNarrowingValue; 5476 QualType PreNarrowingType; 5477 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5478 PreNarrowingType)) { 5479 case NK_Dependent_Narrowing: 5480 // Implicit conversion to a narrower type, but the expression is 5481 // value-dependent so we can't tell whether it's actually narrowing. 5482 case NK_Variable_Narrowing: 5483 // Implicit conversion to a narrower type, and the value is not a constant 5484 // expression. We'll diagnose this in a moment. 5485 case NK_Not_Narrowing: 5486 break; 5487 5488 case NK_Constant_Narrowing: 5489 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5490 << CCE << /*Constant*/ 1 5491 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5492 break; 5493 5494 case NK_Type_Narrowing: 5495 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing) 5496 << CCE << /*Constant*/ 0 << From->getType() << T; 5497 break; 5498 } 5499 5500 if (Result.get()->isValueDependent()) { 5501 Value = APValue(); 5502 return Result; 5503 } 5504 5505 // Check the expression is a constant expression. 5506 SmallVector<PartialDiagnosticAt, 8> Notes; 5507 Expr::EvalResult Eval; 5508 Eval.Diag = &Notes; 5509 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg 5510 ? Expr::EvaluateForMangling 5511 : Expr::EvaluateForCodeGen; 5512 5513 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) || 5514 (RequireInt && !Eval.Val.isInt())) { 5515 // The expression can't be folded, so we can't keep it at this position in 5516 // the AST. 5517 Result = ExprError(); 5518 } else { 5519 Value = Eval.Val; 5520 5521 if (Notes.empty()) { 5522 // It's a constant expression. 5523 return ConstantExpr::Create(S.Context, Result.get()); 5524 } 5525 } 5526 5527 // It's not a constant expression. Produce an appropriate diagnostic. 5528 if (Notes.size() == 1 && 5529 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5530 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5531 else { 5532 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce) 5533 << CCE << From->getSourceRange(); 5534 for (unsigned I = 0; I < Notes.size(); ++I) 5535 S.Diag(Notes[I].first, Notes[I].second); 5536 } 5537 return ExprError(); 5538 } 5539 5540 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5541 APValue &Value, CCEKind CCE) { 5542 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5543 } 5544 5545 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5546 llvm::APSInt &Value, 5547 CCEKind CCE) { 5548 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5549 5550 APValue V; 5551 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5552 if (!R.isInvalid() && !R.get()->isValueDependent()) 5553 Value = V.getInt(); 5554 return R; 5555 } 5556 5557 5558 /// dropPointerConversions - If the given standard conversion sequence 5559 /// involves any pointer conversions, remove them. This may change 5560 /// the result type of the conversion sequence. 5561 static void dropPointerConversion(StandardConversionSequence &SCS) { 5562 if (SCS.Second == ICK_Pointer_Conversion) { 5563 SCS.Second = ICK_Identity; 5564 SCS.Third = ICK_Identity; 5565 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5566 } 5567 } 5568 5569 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5570 /// convert the expression From to an Objective-C pointer type. 5571 static ImplicitConversionSequence 5572 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5573 // Do an implicit conversion to 'id'. 5574 QualType Ty = S.Context.getObjCIdType(); 5575 ImplicitConversionSequence ICS 5576 = TryImplicitConversion(S, From, Ty, 5577 // FIXME: Are these flags correct? 5578 /*SuppressUserConversions=*/false, 5579 /*AllowExplicit=*/true, 5580 /*InOverloadResolution=*/false, 5581 /*CStyle=*/false, 5582 /*AllowObjCWritebackConversion=*/false, 5583 /*AllowObjCConversionOnExplicit=*/true); 5584 5585 // Strip off any final conversions to 'id'. 5586 switch (ICS.getKind()) { 5587 case ImplicitConversionSequence::BadConversion: 5588 case ImplicitConversionSequence::AmbiguousConversion: 5589 case ImplicitConversionSequence::EllipsisConversion: 5590 break; 5591 5592 case ImplicitConversionSequence::UserDefinedConversion: 5593 dropPointerConversion(ICS.UserDefined.After); 5594 break; 5595 5596 case ImplicitConversionSequence::StandardConversion: 5597 dropPointerConversion(ICS.Standard); 5598 break; 5599 } 5600 5601 return ICS; 5602 } 5603 5604 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5605 /// conversion of the expression From to an Objective-C pointer type. 5606 /// Returns a valid but null ExprResult if no conversion sequence exists. 5607 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5608 if (checkPlaceholderForOverload(*this, From)) 5609 return ExprError(); 5610 5611 QualType Ty = Context.getObjCIdType(); 5612 ImplicitConversionSequence ICS = 5613 TryContextuallyConvertToObjCPointer(*this, From); 5614 if (!ICS.isBad()) 5615 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5616 return ExprResult(); 5617 } 5618 5619 /// Determine whether the provided type is an integral type, or an enumeration 5620 /// type of a permitted flavor. 5621 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5622 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5623 : T->isIntegralOrUnscopedEnumerationType(); 5624 } 5625 5626 static ExprResult 5627 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5628 Sema::ContextualImplicitConverter &Converter, 5629 QualType T, UnresolvedSetImpl &ViableConversions) { 5630 5631 if (Converter.Suppress) 5632 return ExprError(); 5633 5634 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5635 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5636 CXXConversionDecl *Conv = 5637 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5638 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5639 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5640 } 5641 return From; 5642 } 5643 5644 static bool 5645 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5646 Sema::ContextualImplicitConverter &Converter, 5647 QualType T, bool HadMultipleCandidates, 5648 UnresolvedSetImpl &ExplicitConversions) { 5649 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5650 DeclAccessPair Found = ExplicitConversions[0]; 5651 CXXConversionDecl *Conversion = 5652 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5653 5654 // The user probably meant to invoke the given explicit 5655 // conversion; use it. 5656 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5657 std::string TypeStr; 5658 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5659 5660 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5661 << FixItHint::CreateInsertion(From->getBeginLoc(), 5662 "static_cast<" + TypeStr + ">(") 5663 << FixItHint::CreateInsertion( 5664 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")"); 5665 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5666 5667 // If we aren't in a SFINAE context, build a call to the 5668 // explicit conversion function. 5669 if (SemaRef.isSFINAEContext()) 5670 return true; 5671 5672 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5673 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5674 HadMultipleCandidates); 5675 if (Result.isInvalid()) 5676 return true; 5677 // Record usage of conversion in an implicit cast. 5678 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5679 CK_UserDefinedConversion, Result.get(), 5680 nullptr, Result.get()->getValueKind()); 5681 } 5682 return false; 5683 } 5684 5685 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5686 Sema::ContextualImplicitConverter &Converter, 5687 QualType T, bool HadMultipleCandidates, 5688 DeclAccessPair &Found) { 5689 CXXConversionDecl *Conversion = 5690 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5691 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5692 5693 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5694 if (!Converter.SuppressConversion) { 5695 if (SemaRef.isSFINAEContext()) 5696 return true; 5697 5698 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5699 << From->getSourceRange(); 5700 } 5701 5702 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5703 HadMultipleCandidates); 5704 if (Result.isInvalid()) 5705 return true; 5706 // Record usage of conversion in an implicit cast. 5707 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5708 CK_UserDefinedConversion, Result.get(), 5709 nullptr, Result.get()->getValueKind()); 5710 return false; 5711 } 5712 5713 static ExprResult finishContextualImplicitConversion( 5714 Sema &SemaRef, SourceLocation Loc, Expr *From, 5715 Sema::ContextualImplicitConverter &Converter) { 5716 if (!Converter.match(From->getType()) && !Converter.Suppress) 5717 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5718 << From->getSourceRange(); 5719 5720 return SemaRef.DefaultLvalueConversion(From); 5721 } 5722 5723 static void 5724 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5725 UnresolvedSetImpl &ViableConversions, 5726 OverloadCandidateSet &CandidateSet) { 5727 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5728 DeclAccessPair FoundDecl = ViableConversions[I]; 5729 NamedDecl *D = FoundDecl.getDecl(); 5730 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5731 if (isa<UsingShadowDecl>(D)) 5732 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5733 5734 CXXConversionDecl *Conv; 5735 FunctionTemplateDecl *ConvTemplate; 5736 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5737 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5738 else 5739 Conv = cast<CXXConversionDecl>(D); 5740 5741 if (ConvTemplate) 5742 SemaRef.AddTemplateConversionCandidate( 5743 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5744 /*AllowObjCConversionOnExplicit=*/false); 5745 else 5746 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5747 ToType, CandidateSet, 5748 /*AllowObjCConversionOnExplicit=*/false); 5749 } 5750 } 5751 5752 /// Attempt to convert the given expression to a type which is accepted 5753 /// by the given converter. 5754 /// 5755 /// This routine will attempt to convert an expression of class type to a 5756 /// type accepted by the specified converter. In C++11 and before, the class 5757 /// must have a single non-explicit conversion function converting to a matching 5758 /// type. In C++1y, there can be multiple such conversion functions, but only 5759 /// one target type. 5760 /// 5761 /// \param Loc The source location of the construct that requires the 5762 /// conversion. 5763 /// 5764 /// \param From The expression we're converting from. 5765 /// 5766 /// \param Converter Used to control and diagnose the conversion process. 5767 /// 5768 /// \returns The expression, converted to an integral or enumeration type if 5769 /// successful. 5770 ExprResult Sema::PerformContextualImplicitConversion( 5771 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5772 // We can't perform any more checking for type-dependent expressions. 5773 if (From->isTypeDependent()) 5774 return From; 5775 5776 // Process placeholders immediately. 5777 if (From->hasPlaceholderType()) { 5778 ExprResult result = CheckPlaceholderExpr(From); 5779 if (result.isInvalid()) 5780 return result; 5781 From = result.get(); 5782 } 5783 5784 // If the expression already has a matching type, we're golden. 5785 QualType T = From->getType(); 5786 if (Converter.match(T)) 5787 return DefaultLvalueConversion(From); 5788 5789 // FIXME: Check for missing '()' if T is a function type? 5790 5791 // We can only perform contextual implicit conversions on objects of class 5792 // type. 5793 const RecordType *RecordTy = T->getAs<RecordType>(); 5794 if (!RecordTy || !getLangOpts().CPlusPlus) { 5795 if (!Converter.Suppress) 5796 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5797 return From; 5798 } 5799 5800 // We must have a complete class type. 5801 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5802 ContextualImplicitConverter &Converter; 5803 Expr *From; 5804 5805 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5806 : Converter(Converter), From(From) {} 5807 5808 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5809 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5810 } 5811 } IncompleteDiagnoser(Converter, From); 5812 5813 if (Converter.Suppress ? !isCompleteType(Loc, T) 5814 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5815 return From; 5816 5817 // Look for a conversion to an integral or enumeration type. 5818 UnresolvedSet<4> 5819 ViableConversions; // These are *potentially* viable in C++1y. 5820 UnresolvedSet<4> ExplicitConversions; 5821 const auto &Conversions = 5822 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5823 5824 bool HadMultipleCandidates = 5825 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5826 5827 // To check that there is only one target type, in C++1y: 5828 QualType ToType; 5829 bool HasUniqueTargetType = true; 5830 5831 // Collect explicit or viable (potentially in C++1y) conversions. 5832 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5833 NamedDecl *D = (*I)->getUnderlyingDecl(); 5834 CXXConversionDecl *Conversion; 5835 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5836 if (ConvTemplate) { 5837 if (getLangOpts().CPlusPlus14) 5838 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5839 else 5840 continue; // C++11 does not consider conversion operator templates(?). 5841 } else 5842 Conversion = cast<CXXConversionDecl>(D); 5843 5844 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5845 "Conversion operator templates are considered potentially " 5846 "viable in C++1y"); 5847 5848 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5849 if (Converter.match(CurToType) || ConvTemplate) { 5850 5851 if (Conversion->isExplicit()) { 5852 // FIXME: For C++1y, do we need this restriction? 5853 // cf. diagnoseNoViableConversion() 5854 if (!ConvTemplate) 5855 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5856 } else { 5857 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5858 if (ToType.isNull()) 5859 ToType = CurToType.getUnqualifiedType(); 5860 else if (HasUniqueTargetType && 5861 (CurToType.getUnqualifiedType() != ToType)) 5862 HasUniqueTargetType = false; 5863 } 5864 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5865 } 5866 } 5867 } 5868 5869 if (getLangOpts().CPlusPlus14) { 5870 // C++1y [conv]p6: 5871 // ... An expression e of class type E appearing in such a context 5872 // is said to be contextually implicitly converted to a specified 5873 // type T and is well-formed if and only if e can be implicitly 5874 // converted to a type T that is determined as follows: E is searched 5875 // for conversion functions whose return type is cv T or reference to 5876 // cv T such that T is allowed by the context. There shall be 5877 // exactly one such T. 5878 5879 // If no unique T is found: 5880 if (ToType.isNull()) { 5881 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5882 HadMultipleCandidates, 5883 ExplicitConversions)) 5884 return ExprError(); 5885 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5886 } 5887 5888 // If more than one unique Ts are found: 5889 if (!HasUniqueTargetType) 5890 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5891 ViableConversions); 5892 5893 // If one unique T is found: 5894 // First, build a candidate set from the previously recorded 5895 // potentially viable conversions. 5896 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5897 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5898 CandidateSet); 5899 5900 // Then, perform overload resolution over the candidate set. 5901 OverloadCandidateSet::iterator Best; 5902 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5903 case OR_Success: { 5904 // Apply this conversion. 5905 DeclAccessPair Found = 5906 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5907 if (recordConversion(*this, Loc, From, Converter, T, 5908 HadMultipleCandidates, Found)) 5909 return ExprError(); 5910 break; 5911 } 5912 case OR_Ambiguous: 5913 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5914 ViableConversions); 5915 case OR_No_Viable_Function: 5916 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5917 HadMultipleCandidates, 5918 ExplicitConversions)) 5919 return ExprError(); 5920 LLVM_FALLTHROUGH; 5921 case OR_Deleted: 5922 // We'll complain below about a non-integral condition type. 5923 break; 5924 } 5925 } else { 5926 switch (ViableConversions.size()) { 5927 case 0: { 5928 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5929 HadMultipleCandidates, 5930 ExplicitConversions)) 5931 return ExprError(); 5932 5933 // We'll complain below about a non-integral condition type. 5934 break; 5935 } 5936 case 1: { 5937 // Apply this conversion. 5938 DeclAccessPair Found = ViableConversions[0]; 5939 if (recordConversion(*this, Loc, From, Converter, T, 5940 HadMultipleCandidates, Found)) 5941 return ExprError(); 5942 break; 5943 } 5944 default: 5945 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5946 ViableConversions); 5947 } 5948 } 5949 5950 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5951 } 5952 5953 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5954 /// an acceptable non-member overloaded operator for a call whose 5955 /// arguments have types T1 (and, if non-empty, T2). This routine 5956 /// implements the check in C++ [over.match.oper]p3b2 concerning 5957 /// enumeration types. 5958 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5959 FunctionDecl *Fn, 5960 ArrayRef<Expr *> Args) { 5961 QualType T1 = Args[0]->getType(); 5962 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5963 5964 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5965 return true; 5966 5967 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5968 return true; 5969 5970 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5971 if (Proto->getNumParams() < 1) 5972 return false; 5973 5974 if (T1->isEnumeralType()) { 5975 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5976 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5977 return true; 5978 } 5979 5980 if (Proto->getNumParams() < 2) 5981 return false; 5982 5983 if (!T2.isNull() && T2->isEnumeralType()) { 5984 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5985 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5986 return true; 5987 } 5988 5989 return false; 5990 } 5991 5992 /// AddOverloadCandidate - Adds the given function to the set of 5993 /// candidate functions, using the given function call arguments. If 5994 /// @p SuppressUserConversions, then don't allow user-defined 5995 /// conversions via constructors or conversion operators. 5996 /// 5997 /// \param PartialOverloading true if we are performing "partial" overloading 5998 /// based on an incomplete set of function arguments. This feature is used by 5999 /// code completion. 6000 void Sema::AddOverloadCandidate(FunctionDecl *Function, 6001 DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, 6002 OverloadCandidateSet &CandidateSet, 6003 bool SuppressUserConversions, 6004 bool PartialOverloading, bool AllowExplicit, 6005 ADLCallKind IsADLCandidate, 6006 ConversionSequenceList EarlyConversions) { 6007 const FunctionProtoType *Proto 6008 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 6009 assert(Proto && "Functions without a prototype cannot be overloaded"); 6010 assert(!Function->getDescribedFunctionTemplate() && 6011 "Use AddTemplateOverloadCandidate for function templates"); 6012 6013 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 6014 if (!isa<CXXConstructorDecl>(Method)) { 6015 // If we get here, it's because we're calling a member function 6016 // that is named without a member access expression (e.g., 6017 // "this->f") that was either written explicitly or created 6018 // implicitly. This can happen with a qualified call to a member 6019 // function, e.g., X::f(). We use an empty type for the implied 6020 // object argument (C++ [over.call.func]p3), and the acting context 6021 // is irrelevant. 6022 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(), 6023 Expr::Classification::makeSimpleLValue(), Args, 6024 CandidateSet, SuppressUserConversions, 6025 PartialOverloading, EarlyConversions); 6026 return; 6027 } 6028 // We treat a constructor like a non-member function, since its object 6029 // argument doesn't participate in overload resolution. 6030 } 6031 6032 if (!CandidateSet.isNewCandidate(Function)) 6033 return; 6034 6035 // C++ [over.match.oper]p3: 6036 // if no operand has a class type, only those non-member functions in the 6037 // lookup set that have a first parameter of type T1 or "reference to 6038 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 6039 // is a right operand) a second parameter of type T2 or "reference to 6040 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 6041 // candidate functions. 6042 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 6043 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 6044 return; 6045 6046 // C++11 [class.copy]p11: [DR1402] 6047 // A defaulted move constructor that is defined as deleted is ignored by 6048 // overload resolution. 6049 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 6050 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 6051 Constructor->isMoveConstructor()) 6052 return; 6053 6054 // Overload resolution is always an unevaluated context. 6055 EnterExpressionEvaluationContext Unevaluated( 6056 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6057 6058 // Add this candidate 6059 OverloadCandidate &Candidate = 6060 CandidateSet.addCandidate(Args.size(), EarlyConversions); 6061 Candidate.FoundDecl = FoundDecl; 6062 Candidate.Function = Function; 6063 Candidate.Viable = true; 6064 Candidate.IsSurrogate = false; 6065 Candidate.IsADLCandidate = IsADLCandidate; 6066 Candidate.IgnoreObjectArgument = false; 6067 Candidate.ExplicitCallArguments = Args.size(); 6068 6069 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() && 6070 !Function->getAttr<TargetAttr>()->isDefaultVersion()) { 6071 Candidate.Viable = false; 6072 Candidate.FailureKind = ovl_non_default_multiversion_function; 6073 return; 6074 } 6075 6076 if (Constructor) { 6077 // C++ [class.copy]p3: 6078 // A member function template is never instantiated to perform the copy 6079 // of a class object to an object of its class type. 6080 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 6081 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 6082 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 6083 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(), 6084 ClassType))) { 6085 Candidate.Viable = false; 6086 Candidate.FailureKind = ovl_fail_illegal_constructor; 6087 return; 6088 } 6089 6090 // C++ [over.match.funcs]p8: (proposed DR resolution) 6091 // A constructor inherited from class type C that has a first parameter 6092 // of type "reference to P" (including such a constructor instantiated 6093 // from a template) is excluded from the set of candidate functions when 6094 // constructing an object of type cv D if the argument list has exactly 6095 // one argument and D is reference-related to P and P is reference-related 6096 // to C. 6097 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl()); 6098 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 && 6099 Constructor->getParamDecl(0)->getType()->isReferenceType()) { 6100 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType(); 6101 QualType C = Context.getRecordType(Constructor->getParent()); 6102 QualType D = Context.getRecordType(Shadow->getParent()); 6103 SourceLocation Loc = Args.front()->getExprLoc(); 6104 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) && 6105 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) { 6106 Candidate.Viable = false; 6107 Candidate.FailureKind = ovl_fail_inhctor_slice; 6108 return; 6109 } 6110 } 6111 } 6112 6113 unsigned NumParams = Proto->getNumParams(); 6114 6115 // (C++ 13.3.2p2): A candidate function having fewer than m 6116 // parameters is viable only if it has an ellipsis in its parameter 6117 // list (8.3.5). 6118 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6119 !Proto->isVariadic()) { 6120 Candidate.Viable = false; 6121 Candidate.FailureKind = ovl_fail_too_many_arguments; 6122 return; 6123 } 6124 6125 // (C++ 13.3.2p2): A candidate function having more than m parameters 6126 // is viable only if the (m+1)st parameter has a default argument 6127 // (8.3.6). For the purposes of overload resolution, the 6128 // parameter list is truncated on the right, so that there are 6129 // exactly m parameters. 6130 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 6131 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6132 // Not enough arguments. 6133 Candidate.Viable = false; 6134 Candidate.FailureKind = ovl_fail_too_few_arguments; 6135 return; 6136 } 6137 6138 // (CUDA B.1): Check for invalid calls between targets. 6139 if (getLangOpts().CUDA) 6140 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6141 // Skip the check for callers that are implicit members, because in this 6142 // case we may not yet know what the member's target is; the target is 6143 // inferred for the member automatically, based on the bases and fields of 6144 // the class. 6145 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 6146 Candidate.Viable = false; 6147 Candidate.FailureKind = ovl_fail_bad_target; 6148 return; 6149 } 6150 6151 // Determine the implicit conversion sequences for each of the 6152 // arguments. 6153 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6154 if (Candidate.Conversions[ArgIdx].isInitialized()) { 6155 // We already formed a conversion sequence for this parameter during 6156 // template argument deduction. 6157 } else if (ArgIdx < NumParams) { 6158 // (C++ 13.3.2p3): for F to be a viable function, there shall 6159 // exist for each argument an implicit conversion sequence 6160 // (13.3.3.1) that converts that argument to the corresponding 6161 // parameter of F. 6162 QualType ParamType = Proto->getParamType(ArgIdx); 6163 Candidate.Conversions[ArgIdx] 6164 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6165 SuppressUserConversions, 6166 /*InOverloadResolution=*/true, 6167 /*AllowObjCWritebackConversion=*/ 6168 getLangOpts().ObjCAutoRefCount, 6169 AllowExplicit); 6170 if (Candidate.Conversions[ArgIdx].isBad()) { 6171 Candidate.Viable = false; 6172 Candidate.FailureKind = ovl_fail_bad_conversion; 6173 return; 6174 } 6175 } else { 6176 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6177 // argument for which there is no corresponding parameter is 6178 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6179 Candidate.Conversions[ArgIdx].setEllipsis(); 6180 } 6181 } 6182 6183 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 6184 Candidate.Viable = false; 6185 Candidate.FailureKind = ovl_fail_enable_if; 6186 Candidate.DeductionFailure.Data = FailedAttr; 6187 return; 6188 } 6189 6190 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 6191 Candidate.Viable = false; 6192 Candidate.FailureKind = ovl_fail_ext_disabled; 6193 return; 6194 } 6195 } 6196 6197 ObjCMethodDecl * 6198 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 6199 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 6200 if (Methods.size() <= 1) 6201 return nullptr; 6202 6203 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6204 bool Match = true; 6205 ObjCMethodDecl *Method = Methods[b]; 6206 unsigned NumNamedArgs = Sel.getNumArgs(); 6207 // Method might have more arguments than selector indicates. This is due 6208 // to addition of c-style arguments in method. 6209 if (Method->param_size() > NumNamedArgs) 6210 NumNamedArgs = Method->param_size(); 6211 if (Args.size() < NumNamedArgs) 6212 continue; 6213 6214 for (unsigned i = 0; i < NumNamedArgs; i++) { 6215 // We can't do any type-checking on a type-dependent argument. 6216 if (Args[i]->isTypeDependent()) { 6217 Match = false; 6218 break; 6219 } 6220 6221 ParmVarDecl *param = Method->parameters()[i]; 6222 Expr *argExpr = Args[i]; 6223 assert(argExpr && "SelectBestMethod(): missing expression"); 6224 6225 // Strip the unbridged-cast placeholder expression off unless it's 6226 // a consumed argument. 6227 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6228 !param->hasAttr<CFConsumedAttr>()) 6229 argExpr = stripARCUnbridgedCast(argExpr); 6230 6231 // If the parameter is __unknown_anytype, move on to the next method. 6232 if (param->getType() == Context.UnknownAnyTy) { 6233 Match = false; 6234 break; 6235 } 6236 6237 ImplicitConversionSequence ConversionState 6238 = TryCopyInitialization(*this, argExpr, param->getType(), 6239 /*SuppressUserConversions*/false, 6240 /*InOverloadResolution=*/true, 6241 /*AllowObjCWritebackConversion=*/ 6242 getLangOpts().ObjCAutoRefCount, 6243 /*AllowExplicit*/false); 6244 // This function looks for a reasonably-exact match, so we consider 6245 // incompatible pointer conversions to be a failure here. 6246 if (ConversionState.isBad() || 6247 (ConversionState.isStandard() && 6248 ConversionState.Standard.Second == 6249 ICK_Incompatible_Pointer_Conversion)) { 6250 Match = false; 6251 break; 6252 } 6253 } 6254 // Promote additional arguments to variadic methods. 6255 if (Match && Method->isVariadic()) { 6256 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6257 if (Args[i]->isTypeDependent()) { 6258 Match = false; 6259 break; 6260 } 6261 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6262 nullptr); 6263 if (Arg.isInvalid()) { 6264 Match = false; 6265 break; 6266 } 6267 } 6268 } else { 6269 // Check for extra arguments to non-variadic methods. 6270 if (Args.size() != NumNamedArgs) 6271 Match = false; 6272 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6273 // Special case when selectors have no argument. In this case, select 6274 // one with the most general result type of 'id'. 6275 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6276 QualType ReturnT = Methods[b]->getReturnType(); 6277 if (ReturnT->isObjCIdType()) 6278 return Methods[b]; 6279 } 6280 } 6281 } 6282 6283 if (Match) 6284 return Method; 6285 } 6286 return nullptr; 6287 } 6288 6289 static bool 6290 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, 6291 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, 6292 bool MissingImplicitThis, Expr *&ConvertedThis, 6293 SmallVectorImpl<Expr *> &ConvertedArgs) { 6294 if (ThisArg) { 6295 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6296 assert(!isa<CXXConstructorDecl>(Method) && 6297 "Shouldn't have `this` for ctors!"); 6298 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!"); 6299 ExprResult R = S.PerformObjectArgumentInitialization( 6300 ThisArg, /*Qualifier=*/nullptr, Method, Method); 6301 if (R.isInvalid()) 6302 return false; 6303 ConvertedThis = R.get(); 6304 } else { 6305 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) { 6306 (void)MD; 6307 assert((MissingImplicitThis || MD->isStatic() || 6308 isa<CXXConstructorDecl>(MD)) && 6309 "Expected `this` for non-ctor instance methods"); 6310 } 6311 ConvertedThis = nullptr; 6312 } 6313 6314 // Ignore any variadic arguments. Converting them is pointless, since the 6315 // user can't refer to them in the function condition. 6316 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6317 6318 // Convert the arguments. 6319 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6320 ExprResult R; 6321 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6322 S.Context, Function->getParamDecl(I)), 6323 SourceLocation(), Args[I]); 6324 6325 if (R.isInvalid()) 6326 return false; 6327 6328 ConvertedArgs.push_back(R.get()); 6329 } 6330 6331 if (Trap.hasErrorOccurred()) 6332 return false; 6333 6334 // Push default arguments if needed. 6335 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6336 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6337 ParmVarDecl *P = Function->getParamDecl(i); 6338 Expr *DefArg = P->hasUninstantiatedDefaultArg() 6339 ? P->getUninstantiatedDefaultArg() 6340 : P->getDefaultArg(); 6341 // This can only happen in code completion, i.e. when PartialOverloading 6342 // is true. 6343 if (!DefArg) 6344 return false; 6345 ExprResult R = 6346 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 6347 S.Context, Function->getParamDecl(i)), 6348 SourceLocation(), DefArg); 6349 if (R.isInvalid()) 6350 return false; 6351 ConvertedArgs.push_back(R.get()); 6352 } 6353 6354 if (Trap.hasErrorOccurred()) 6355 return false; 6356 } 6357 return true; 6358 } 6359 6360 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6361 bool MissingImplicitThis) { 6362 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>(); 6363 if (EnableIfAttrs.begin() == EnableIfAttrs.end()) 6364 return nullptr; 6365 6366 SFINAETrap Trap(*this); 6367 SmallVector<Expr *, 16> ConvertedArgs; 6368 // FIXME: We should look into making enable_if late-parsed. 6369 Expr *DiscardedThis; 6370 if (!convertArgsForAvailabilityChecks( 6371 *this, Function, /*ThisArg=*/nullptr, Args, Trap, 6372 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs)) 6373 return *EnableIfAttrs.begin(); 6374 6375 for (auto *EIA : EnableIfAttrs) { 6376 APValue Result; 6377 // FIXME: This doesn't consider value-dependent cases, because doing so is 6378 // very difficult. Ideally, we should handle them more gracefully. 6379 if (!EIA->getCond()->EvaluateWithSubstitution( 6380 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6381 return EIA; 6382 6383 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6384 return EIA; 6385 } 6386 return nullptr; 6387 } 6388 6389 template <typename CheckFn> 6390 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, 6391 bool ArgDependent, SourceLocation Loc, 6392 CheckFn &&IsSuccessful) { 6393 SmallVector<const DiagnoseIfAttr *, 8> Attrs; 6394 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) { 6395 if (ArgDependent == DIA->getArgDependent()) 6396 Attrs.push_back(DIA); 6397 } 6398 6399 // Common case: No diagnose_if attributes, so we can quit early. 6400 if (Attrs.empty()) 6401 return false; 6402 6403 auto WarningBegin = std::stable_partition( 6404 Attrs.begin(), Attrs.end(), 6405 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); }); 6406 6407 // Note that diagnose_if attributes are late-parsed, so they appear in the 6408 // correct order (unlike enable_if attributes). 6409 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin), 6410 IsSuccessful); 6411 if (ErrAttr != WarningBegin) { 6412 const DiagnoseIfAttr *DIA = *ErrAttr; 6413 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage(); 6414 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6415 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6416 return true; 6417 } 6418 6419 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end())) 6420 if (IsSuccessful(DIA)) { 6421 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage(); 6422 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if) 6423 << DIA->getParent() << DIA->getCond()->getSourceRange(); 6424 } 6425 6426 return false; 6427 } 6428 6429 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, 6430 const Expr *ThisArg, 6431 ArrayRef<const Expr *> Args, 6432 SourceLocation Loc) { 6433 return diagnoseDiagnoseIfAttrsWith( 6434 *this, Function, /*ArgDependent=*/true, Loc, 6435 [&](const DiagnoseIfAttr *DIA) { 6436 APValue Result; 6437 // It's sane to use the same Args for any redecl of this function, since 6438 // EvaluateWithSubstitution only cares about the position of each 6439 // argument in the arg list, not the ParmVarDecl* it maps to. 6440 if (!DIA->getCond()->EvaluateWithSubstitution( 6441 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg)) 6442 return false; 6443 return Result.isInt() && Result.getInt().getBoolValue(); 6444 }); 6445 } 6446 6447 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, 6448 SourceLocation Loc) { 6449 return diagnoseDiagnoseIfAttrsWith( 6450 *this, ND, /*ArgDependent=*/false, Loc, 6451 [&](const DiagnoseIfAttr *DIA) { 6452 bool Result; 6453 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) && 6454 Result; 6455 }); 6456 } 6457 6458 /// Add all of the function declarations in the given function set to 6459 /// the overload candidate set. 6460 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6461 ArrayRef<Expr *> Args, 6462 OverloadCandidateSet &CandidateSet, 6463 TemplateArgumentListInfo *ExplicitTemplateArgs, 6464 bool SuppressUserConversions, 6465 bool PartialOverloading, 6466 bool FirstArgumentIsBase) { 6467 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6468 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6469 ArrayRef<Expr *> FunctionArgs = Args; 6470 6471 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D); 6472 FunctionDecl *FD = 6473 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D); 6474 6475 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) { 6476 QualType ObjectType; 6477 Expr::Classification ObjectClassification; 6478 if (Args.size() > 0) { 6479 if (Expr *E = Args[0]) { 6480 // Use the explicit base to restrict the lookup: 6481 ObjectType = E->getType(); 6482 // Pointers in the object arguments are implicitly dereferenced, so we 6483 // always classify them as l-values. 6484 if (!ObjectType.isNull() && ObjectType->isPointerType()) 6485 ObjectClassification = Expr::Classification::makeSimpleLValue(); 6486 else 6487 ObjectClassification = E->Classify(Context); 6488 } // .. else there is an implicit base. 6489 FunctionArgs = Args.slice(1); 6490 } 6491 if (FunTmpl) { 6492 AddMethodTemplateCandidate( 6493 FunTmpl, F.getPair(), 6494 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6495 ExplicitTemplateArgs, ObjectType, ObjectClassification, 6496 FunctionArgs, CandidateSet, SuppressUserConversions, 6497 PartialOverloading); 6498 } else { 6499 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6500 cast<CXXMethodDecl>(FD)->getParent(), ObjectType, 6501 ObjectClassification, FunctionArgs, CandidateSet, 6502 SuppressUserConversions, PartialOverloading); 6503 } 6504 } else { 6505 // This branch handles both standalone functions and static methods. 6506 6507 // Slice the first argument (which is the base) when we access 6508 // static method as non-static. 6509 if (Args.size() > 0 && 6510 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) && 6511 !isa<CXXConstructorDecl>(FD)))) { 6512 assert(cast<CXXMethodDecl>(FD)->isStatic()); 6513 FunctionArgs = Args.slice(1); 6514 } 6515 if (FunTmpl) { 6516 AddTemplateOverloadCandidate( 6517 FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs, 6518 CandidateSet, SuppressUserConversions, PartialOverloading); 6519 } else { 6520 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet, 6521 SuppressUserConversions, PartialOverloading); 6522 } 6523 } 6524 } 6525 } 6526 6527 /// AddMethodCandidate - Adds a named decl (which is some kind of 6528 /// method) as a method candidate to the given overload set. 6529 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6530 QualType ObjectType, 6531 Expr::Classification ObjectClassification, 6532 ArrayRef<Expr *> Args, 6533 OverloadCandidateSet& CandidateSet, 6534 bool SuppressUserConversions) { 6535 NamedDecl *Decl = FoundDecl.getDecl(); 6536 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6537 6538 if (isa<UsingShadowDecl>(Decl)) 6539 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6540 6541 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6542 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6543 "Expected a member function template"); 6544 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6545 /*ExplicitArgs*/ nullptr, ObjectType, 6546 ObjectClassification, Args, CandidateSet, 6547 SuppressUserConversions); 6548 } else { 6549 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6550 ObjectType, ObjectClassification, Args, CandidateSet, 6551 SuppressUserConversions); 6552 } 6553 } 6554 6555 /// AddMethodCandidate - Adds the given C++ member function to the set 6556 /// of candidate functions, using the given function call arguments 6557 /// and the object argument (@c Object). For example, in a call 6558 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6559 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6560 /// allow user-defined conversions via constructors or conversion 6561 /// operators. 6562 void 6563 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6564 CXXRecordDecl *ActingContext, QualType ObjectType, 6565 Expr::Classification ObjectClassification, 6566 ArrayRef<Expr *> Args, 6567 OverloadCandidateSet &CandidateSet, 6568 bool SuppressUserConversions, 6569 bool PartialOverloading, 6570 ConversionSequenceList EarlyConversions) { 6571 const FunctionProtoType *Proto 6572 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6573 assert(Proto && "Methods without a prototype cannot be overloaded"); 6574 assert(!isa<CXXConstructorDecl>(Method) && 6575 "Use AddOverloadCandidate for constructors"); 6576 6577 if (!CandidateSet.isNewCandidate(Method)) 6578 return; 6579 6580 // C++11 [class.copy]p23: [DR1402] 6581 // A defaulted move assignment operator that is defined as deleted is 6582 // ignored by overload resolution. 6583 if (Method->isDefaulted() && Method->isDeleted() && 6584 Method->isMoveAssignmentOperator()) 6585 return; 6586 6587 // Overload resolution is always an unevaluated context. 6588 EnterExpressionEvaluationContext Unevaluated( 6589 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6590 6591 // Add this candidate 6592 OverloadCandidate &Candidate = 6593 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions); 6594 Candidate.FoundDecl = FoundDecl; 6595 Candidate.Function = Method; 6596 Candidate.IsSurrogate = false; 6597 Candidate.IgnoreObjectArgument = false; 6598 Candidate.ExplicitCallArguments = Args.size(); 6599 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 (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6606 !Proto->isVariadic()) { 6607 Candidate.Viable = false; 6608 Candidate.FailureKind = ovl_fail_too_many_arguments; 6609 return; 6610 } 6611 6612 // (C++ 13.3.2p2): A candidate function having more than m parameters 6613 // is viable only if the (m+1)st parameter has a default argument 6614 // (8.3.6). For the purposes of overload resolution, the 6615 // parameter list is truncated on the right, so that there are 6616 // exactly m parameters. 6617 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6618 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6619 // Not enough arguments. 6620 Candidate.Viable = false; 6621 Candidate.FailureKind = ovl_fail_too_few_arguments; 6622 return; 6623 } 6624 6625 Candidate.Viable = true; 6626 6627 if (Method->isStatic() || ObjectType.isNull()) 6628 // The implicit object argument is ignored. 6629 Candidate.IgnoreObjectArgument = true; 6630 else { 6631 // Determine the implicit conversion sequence for the object 6632 // parameter. 6633 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6634 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6635 Method, ActingContext); 6636 if (Candidate.Conversions[0].isBad()) { 6637 Candidate.Viable = false; 6638 Candidate.FailureKind = ovl_fail_bad_conversion; 6639 return; 6640 } 6641 } 6642 6643 // (CUDA B.1): Check for invalid calls between targets. 6644 if (getLangOpts().CUDA) 6645 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6646 if (!IsAllowedCUDACall(Caller, Method)) { 6647 Candidate.Viable = false; 6648 Candidate.FailureKind = ovl_fail_bad_target; 6649 return; 6650 } 6651 6652 // Determine the implicit conversion sequences for each of the 6653 // arguments. 6654 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6655 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) { 6656 // We already formed a conversion sequence for this parameter during 6657 // template argument deduction. 6658 } else if (ArgIdx < NumParams) { 6659 // (C++ 13.3.2p3): for F to be a viable function, there shall 6660 // exist for each argument an implicit conversion sequence 6661 // (13.3.3.1) that converts that argument to the corresponding 6662 // parameter of F. 6663 QualType ParamType = Proto->getParamType(ArgIdx); 6664 Candidate.Conversions[ArgIdx + 1] 6665 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6666 SuppressUserConversions, 6667 /*InOverloadResolution=*/true, 6668 /*AllowObjCWritebackConversion=*/ 6669 getLangOpts().ObjCAutoRefCount); 6670 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6671 Candidate.Viable = false; 6672 Candidate.FailureKind = ovl_fail_bad_conversion; 6673 return; 6674 } 6675 } else { 6676 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6677 // argument for which there is no corresponding parameter is 6678 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6679 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6680 } 6681 } 6682 6683 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6684 Candidate.Viable = false; 6685 Candidate.FailureKind = ovl_fail_enable_if; 6686 Candidate.DeductionFailure.Data = FailedAttr; 6687 return; 6688 } 6689 6690 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() && 6691 !Method->getAttr<TargetAttr>()->isDefaultVersion()) { 6692 Candidate.Viable = false; 6693 Candidate.FailureKind = ovl_non_default_multiversion_function; 6694 } 6695 } 6696 6697 /// Add a C++ member function template as a candidate to the candidate 6698 /// set, using template argument deduction to produce an appropriate member 6699 /// function template specialization. 6700 void 6701 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6702 DeclAccessPair FoundDecl, 6703 CXXRecordDecl *ActingContext, 6704 TemplateArgumentListInfo *ExplicitTemplateArgs, 6705 QualType ObjectType, 6706 Expr::Classification ObjectClassification, 6707 ArrayRef<Expr *> Args, 6708 OverloadCandidateSet& CandidateSet, 6709 bool SuppressUserConversions, 6710 bool PartialOverloading) { 6711 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6712 return; 6713 6714 // C++ [over.match.funcs]p7: 6715 // In each case where a candidate is a function template, candidate 6716 // function template specializations are generated using template argument 6717 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6718 // candidate functions in the usual way.113) A given name can refer to one 6719 // or more function templates and also to a set of overloaded non-template 6720 // functions. In such a case, the candidate functions generated from each 6721 // function template are combined with the set of non-template candidate 6722 // functions. 6723 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6724 FunctionDecl *Specialization = nullptr; 6725 ConversionSequenceList Conversions; 6726 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6727 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info, 6728 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6729 return CheckNonDependentConversions( 6730 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions, 6731 SuppressUserConversions, ActingContext, ObjectType, 6732 ObjectClassification); 6733 })) { 6734 OverloadCandidate &Candidate = 6735 CandidateSet.addCandidate(Conversions.size(), Conversions); 6736 Candidate.FoundDecl = FoundDecl; 6737 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6738 Candidate.Viable = false; 6739 Candidate.IsSurrogate = false; 6740 Candidate.IgnoreObjectArgument = 6741 cast<CXXMethodDecl>(Candidate.Function)->isStatic() || 6742 ObjectType.isNull(); 6743 Candidate.ExplicitCallArguments = Args.size(); 6744 if (Result == TDK_NonDependentConversionFailure) 6745 Candidate.FailureKind = ovl_fail_bad_conversion; 6746 else { 6747 Candidate.FailureKind = ovl_fail_bad_deduction; 6748 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6749 Info); 6750 } 6751 return; 6752 } 6753 6754 // Add the function template specialization produced by template argument 6755 // deduction as a candidate. 6756 assert(Specialization && "Missing member function template specialization?"); 6757 assert(isa<CXXMethodDecl>(Specialization) && 6758 "Specialization is not a member function?"); 6759 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6760 ActingContext, ObjectType, ObjectClassification, Args, 6761 CandidateSet, SuppressUserConversions, PartialOverloading, 6762 Conversions); 6763 } 6764 6765 /// Add a C++ function template specialization as a candidate 6766 /// in the candidate set, using template argument deduction to produce 6767 /// an appropriate function template specialization. 6768 void Sema::AddTemplateOverloadCandidate( 6769 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, 6770 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, 6771 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions, 6772 bool PartialOverloading, ADLCallKind IsADLCandidate) { 6773 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6774 return; 6775 6776 // C++ [over.match.funcs]p7: 6777 // In each case where a candidate is a function template, candidate 6778 // function template specializations are generated using template argument 6779 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6780 // candidate functions in the usual way.113) A given name can refer to one 6781 // or more function templates and also to a set of overloaded non-template 6782 // functions. In such a case, the candidate functions generated from each 6783 // function template are combined with the set of non-template candidate 6784 // functions. 6785 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6786 FunctionDecl *Specialization = nullptr; 6787 ConversionSequenceList Conversions; 6788 if (TemplateDeductionResult Result = DeduceTemplateArguments( 6789 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info, 6790 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) { 6791 return CheckNonDependentConversions(FunctionTemplate, ParamTypes, 6792 Args, CandidateSet, Conversions, 6793 SuppressUserConversions); 6794 })) { 6795 OverloadCandidate &Candidate = 6796 CandidateSet.addCandidate(Conversions.size(), Conversions); 6797 Candidate.FoundDecl = FoundDecl; 6798 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6799 Candidate.Viable = false; 6800 Candidate.IsSurrogate = false; 6801 Candidate.IsADLCandidate = IsADLCandidate; 6802 // Ignore the object argument if there is one, since we don't have an object 6803 // type. 6804 Candidate.IgnoreObjectArgument = 6805 isa<CXXMethodDecl>(Candidate.Function) && 6806 !isa<CXXConstructorDecl>(Candidate.Function); 6807 Candidate.ExplicitCallArguments = Args.size(); 6808 if (Result == TDK_NonDependentConversionFailure) 6809 Candidate.FailureKind = ovl_fail_bad_conversion; 6810 else { 6811 Candidate.FailureKind = ovl_fail_bad_deduction; 6812 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6813 Info); 6814 } 6815 return; 6816 } 6817 6818 // Add the function template specialization produced by template argument 6819 // deduction as a candidate. 6820 assert(Specialization && "Missing function template specialization?"); 6821 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6822 SuppressUserConversions, PartialOverloading, 6823 /*AllowExplicit*/ false, IsADLCandidate, Conversions); 6824 } 6825 6826 /// Check that implicit conversion sequences can be formed for each argument 6827 /// whose corresponding parameter has a non-dependent type, per DR1391's 6828 /// [temp.deduct.call]p10. 6829 bool Sema::CheckNonDependentConversions( 6830 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, 6831 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, 6832 ConversionSequenceList &Conversions, bool SuppressUserConversions, 6833 CXXRecordDecl *ActingContext, QualType ObjectType, 6834 Expr::Classification ObjectClassification) { 6835 // FIXME: The cases in which we allow explicit conversions for constructor 6836 // arguments never consider calling a constructor template. It's not clear 6837 // that is correct. 6838 const bool AllowExplicit = false; 6839 6840 auto *FD = FunctionTemplate->getTemplatedDecl(); 6841 auto *Method = dyn_cast<CXXMethodDecl>(FD); 6842 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method); 6843 unsigned ThisConversions = HasThisConversion ? 1 : 0; 6844 6845 Conversions = 6846 CandidateSet.allocateConversionSequences(ThisConversions + Args.size()); 6847 6848 // Overload resolution is always an unevaluated context. 6849 EnterExpressionEvaluationContext Unevaluated( 6850 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6851 6852 // For a method call, check the 'this' conversion here too. DR1391 doesn't 6853 // require that, but this check should never result in a hard error, and 6854 // overload resolution is permitted to sidestep instantiations. 6855 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() && 6856 !ObjectType.isNull()) { 6857 Conversions[0] = TryObjectArgumentInitialization( 6858 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6859 Method, ActingContext); 6860 if (Conversions[0].isBad()) 6861 return true; 6862 } 6863 6864 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N; 6865 ++I) { 6866 QualType ParamType = ParamTypes[I]; 6867 if (!ParamType->isDependentType()) { 6868 Conversions[ThisConversions + I] 6869 = TryCopyInitialization(*this, Args[I], ParamType, 6870 SuppressUserConversions, 6871 /*InOverloadResolution=*/true, 6872 /*AllowObjCWritebackConversion=*/ 6873 getLangOpts().ObjCAutoRefCount, 6874 AllowExplicit); 6875 if (Conversions[ThisConversions + I].isBad()) 6876 return true; 6877 } 6878 } 6879 6880 return false; 6881 } 6882 6883 /// Determine whether this is an allowable conversion from the result 6884 /// of an explicit conversion operator to the expected type, per C++ 6885 /// [over.match.conv]p1 and [over.match.ref]p1. 6886 /// 6887 /// \param ConvType The return type of the conversion function. 6888 /// 6889 /// \param ToType The type we are converting to. 6890 /// 6891 /// \param AllowObjCPointerConversion Allow a conversion from one 6892 /// Objective-C pointer to another. 6893 /// 6894 /// \returns true if the conversion is allowable, false otherwise. 6895 static bool isAllowableExplicitConversion(Sema &S, 6896 QualType ConvType, QualType ToType, 6897 bool AllowObjCPointerConversion) { 6898 QualType ToNonRefType = ToType.getNonReferenceType(); 6899 6900 // Easy case: the types are the same. 6901 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6902 return true; 6903 6904 // Allow qualification conversions. 6905 bool ObjCLifetimeConversion; 6906 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6907 ObjCLifetimeConversion)) 6908 return true; 6909 6910 // If we're not allowed to consider Objective-C pointer conversions, 6911 // we're done. 6912 if (!AllowObjCPointerConversion) 6913 return false; 6914 6915 // Is this an Objective-C pointer conversion? 6916 bool IncompatibleObjC = false; 6917 QualType ConvertedType; 6918 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6919 IncompatibleObjC); 6920 } 6921 6922 /// AddConversionCandidate - Add a C++ conversion function as a 6923 /// candidate in the candidate set (C++ [over.match.conv], 6924 /// C++ [over.match.copy]). From is the expression we're converting from, 6925 /// and ToType is the type that we're eventually trying to convert to 6926 /// (which may or may not be the same type as the type that the 6927 /// conversion function produces). 6928 void 6929 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6930 DeclAccessPair FoundDecl, 6931 CXXRecordDecl *ActingContext, 6932 Expr *From, QualType ToType, 6933 OverloadCandidateSet& CandidateSet, 6934 bool AllowObjCConversionOnExplicit, 6935 bool AllowResultConversion) { 6936 assert(!Conversion->getDescribedFunctionTemplate() && 6937 "Conversion function templates use AddTemplateConversionCandidate"); 6938 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6939 if (!CandidateSet.isNewCandidate(Conversion)) 6940 return; 6941 6942 // If the conversion function has an undeduced return type, trigger its 6943 // deduction now. 6944 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6945 if (DeduceReturnType(Conversion, From->getExprLoc())) 6946 return; 6947 ConvType = Conversion->getConversionType().getNonReferenceType(); 6948 } 6949 6950 // If we don't allow any conversion of the result type, ignore conversion 6951 // functions that don't convert to exactly (possibly cv-qualified) T. 6952 if (!AllowResultConversion && 6953 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType)) 6954 return; 6955 6956 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6957 // operator is only a candidate if its return type is the target type or 6958 // can be converted to the target type with a qualification conversion. 6959 if (Conversion->isExplicit() && 6960 !isAllowableExplicitConversion(*this, ConvType, ToType, 6961 AllowObjCConversionOnExplicit)) 6962 return; 6963 6964 // Overload resolution is always an unevaluated context. 6965 EnterExpressionEvaluationContext Unevaluated( 6966 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6967 6968 // Add this candidate 6969 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6970 Candidate.FoundDecl = FoundDecl; 6971 Candidate.Function = Conversion; 6972 Candidate.IsSurrogate = false; 6973 Candidate.IgnoreObjectArgument = false; 6974 Candidate.FinalConversion.setAsIdentityConversion(); 6975 Candidate.FinalConversion.setFromType(ConvType); 6976 Candidate.FinalConversion.setAllToTypes(ToType); 6977 Candidate.Viable = true; 6978 Candidate.ExplicitCallArguments = 1; 6979 6980 // C++ [over.match.funcs]p4: 6981 // For conversion functions, the function is considered to be a member of 6982 // the class of the implicit implied object argument for the purpose of 6983 // defining the type of the implicit object parameter. 6984 // 6985 // Determine the implicit conversion sequence for the implicit 6986 // object parameter. 6987 QualType ImplicitParamType = From->getType(); 6988 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6989 ImplicitParamType = FromPtrType->getPointeeType(); 6990 CXXRecordDecl *ConversionContext 6991 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6992 6993 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6994 *this, CandidateSet.getLocation(), From->getType(), 6995 From->Classify(Context), Conversion, ConversionContext); 6996 6997 if (Candidate.Conversions[0].isBad()) { 6998 Candidate.Viable = false; 6999 Candidate.FailureKind = ovl_fail_bad_conversion; 7000 return; 7001 } 7002 7003 // We won't go through a user-defined type conversion function to convert a 7004 // derived to base as such conversions are given Conversion Rank. They only 7005 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 7006 QualType FromCanon 7007 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 7008 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 7009 if (FromCanon == ToCanon || 7010 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 7011 Candidate.Viable = false; 7012 Candidate.FailureKind = ovl_fail_trivial_conversion; 7013 return; 7014 } 7015 7016 // To determine what the conversion from the result of calling the 7017 // conversion function to the type we're eventually trying to 7018 // convert to (ToType), we need to synthesize a call to the 7019 // conversion function and attempt copy initialization from it. This 7020 // makes sure that we get the right semantics with respect to 7021 // lvalues/rvalues and the type. Fortunately, we can allocate this 7022 // call on the stack and we don't need its arguments to be 7023 // well-formed. 7024 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(), 7025 VK_LValue, From->getBeginLoc()); 7026 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 7027 Context.getPointerType(Conversion->getType()), 7028 CK_FunctionToPointerDecay, 7029 &ConversionRef, VK_RValue); 7030 7031 QualType ConversionType = Conversion->getConversionType(); 7032 if (!isCompleteType(From->getBeginLoc(), ConversionType)) { 7033 Candidate.Viable = false; 7034 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7035 return; 7036 } 7037 7038 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 7039 7040 // Note that it is safe to allocate CallExpr on the stack here because 7041 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 7042 // allocator). 7043 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 7044 7045 llvm::AlignedCharArray<alignof(CallExpr), sizeof(CallExpr) + sizeof(Stmt *)> 7046 Buffer; 7047 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary( 7048 Buffer.buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc()); 7049 7050 ImplicitConversionSequence ICS = 7051 TryCopyInitialization(*this, TheTemporaryCall, ToType, 7052 /*SuppressUserConversions=*/true, 7053 /*InOverloadResolution=*/false, 7054 /*AllowObjCWritebackConversion=*/false); 7055 7056 switch (ICS.getKind()) { 7057 case ImplicitConversionSequence::StandardConversion: 7058 Candidate.FinalConversion = ICS.Standard; 7059 7060 // C++ [over.ics.user]p3: 7061 // If the user-defined conversion is specified by a specialization of a 7062 // conversion function template, the second standard conversion sequence 7063 // shall have exact match rank. 7064 if (Conversion->getPrimaryTemplate() && 7065 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 7066 Candidate.Viable = false; 7067 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 7068 return; 7069 } 7070 7071 // C++0x [dcl.init.ref]p5: 7072 // In the second case, if the reference is an rvalue reference and 7073 // the second standard conversion sequence of the user-defined 7074 // conversion sequence includes an lvalue-to-rvalue conversion, the 7075 // program is ill-formed. 7076 if (ToType->isRValueReferenceType() && 7077 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 7078 Candidate.Viable = false; 7079 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7080 return; 7081 } 7082 break; 7083 7084 case ImplicitConversionSequence::BadConversion: 7085 Candidate.Viable = false; 7086 Candidate.FailureKind = ovl_fail_bad_final_conversion; 7087 return; 7088 7089 default: 7090 llvm_unreachable( 7091 "Can only end up with a standard conversion sequence or failure"); 7092 } 7093 7094 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7095 Candidate.Viable = false; 7096 Candidate.FailureKind = ovl_fail_enable_if; 7097 Candidate.DeductionFailure.Data = FailedAttr; 7098 return; 7099 } 7100 7101 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() && 7102 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) { 7103 Candidate.Viable = false; 7104 Candidate.FailureKind = ovl_non_default_multiversion_function; 7105 } 7106 } 7107 7108 /// Adds a conversion function template specialization 7109 /// candidate to the overload set, using template argument deduction 7110 /// to deduce the template arguments of the conversion function 7111 /// template from the type that we are converting to (C++ 7112 /// [temp.deduct.conv]). 7113 void 7114 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 7115 DeclAccessPair FoundDecl, 7116 CXXRecordDecl *ActingDC, 7117 Expr *From, QualType ToType, 7118 OverloadCandidateSet &CandidateSet, 7119 bool AllowObjCConversionOnExplicit, 7120 bool AllowResultConversion) { 7121 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 7122 "Only conversion function templates permitted here"); 7123 7124 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 7125 return; 7126 7127 TemplateDeductionInfo Info(CandidateSet.getLocation()); 7128 CXXConversionDecl *Specialization = nullptr; 7129 if (TemplateDeductionResult Result 7130 = DeduceTemplateArguments(FunctionTemplate, ToType, 7131 Specialization, Info)) { 7132 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 7133 Candidate.FoundDecl = FoundDecl; 7134 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 7135 Candidate.Viable = false; 7136 Candidate.FailureKind = ovl_fail_bad_deduction; 7137 Candidate.IsSurrogate = false; 7138 Candidate.IgnoreObjectArgument = false; 7139 Candidate.ExplicitCallArguments = 1; 7140 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 7141 Info); 7142 return; 7143 } 7144 7145 // Add the conversion function template specialization produced by 7146 // template argument deduction as a candidate. 7147 assert(Specialization && "Missing function template specialization?"); 7148 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 7149 CandidateSet, AllowObjCConversionOnExplicit, 7150 AllowResultConversion); 7151 } 7152 7153 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 7154 /// converts the given @c Object to a function pointer via the 7155 /// conversion function @c Conversion, and then attempts to call it 7156 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 7157 /// the type of function that we'll eventually be calling. 7158 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 7159 DeclAccessPair FoundDecl, 7160 CXXRecordDecl *ActingContext, 7161 const FunctionProtoType *Proto, 7162 Expr *Object, 7163 ArrayRef<Expr *> Args, 7164 OverloadCandidateSet& CandidateSet) { 7165 if (!CandidateSet.isNewCandidate(Conversion)) 7166 return; 7167 7168 // Overload resolution is always an unevaluated context. 7169 EnterExpressionEvaluationContext Unevaluated( 7170 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7171 7172 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 7173 Candidate.FoundDecl = FoundDecl; 7174 Candidate.Function = nullptr; 7175 Candidate.Surrogate = Conversion; 7176 Candidate.Viable = true; 7177 Candidate.IsSurrogate = true; 7178 Candidate.IgnoreObjectArgument = false; 7179 Candidate.ExplicitCallArguments = Args.size(); 7180 7181 // Determine the implicit conversion sequence for the implicit 7182 // object parameter. 7183 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 7184 *this, CandidateSet.getLocation(), Object->getType(), 7185 Object->Classify(Context), Conversion, ActingContext); 7186 if (ObjectInit.isBad()) { 7187 Candidate.Viable = false; 7188 Candidate.FailureKind = ovl_fail_bad_conversion; 7189 Candidate.Conversions[0] = ObjectInit; 7190 return; 7191 } 7192 7193 // The first conversion is actually a user-defined conversion whose 7194 // first conversion is ObjectInit's standard conversion (which is 7195 // effectively a reference binding). Record it as such. 7196 Candidate.Conversions[0].setUserDefined(); 7197 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 7198 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 7199 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 7200 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 7201 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 7202 Candidate.Conversions[0].UserDefined.After 7203 = Candidate.Conversions[0].UserDefined.Before; 7204 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 7205 7206 // Find the 7207 unsigned NumParams = Proto->getNumParams(); 7208 7209 // (C++ 13.3.2p2): A candidate function having fewer than m 7210 // parameters is viable only if it has an ellipsis in its parameter 7211 // list (8.3.5). 7212 if (Args.size() > NumParams && !Proto->isVariadic()) { 7213 Candidate.Viable = false; 7214 Candidate.FailureKind = ovl_fail_too_many_arguments; 7215 return; 7216 } 7217 7218 // Function types don't have any default arguments, so just check if 7219 // we have enough arguments. 7220 if (Args.size() < NumParams) { 7221 // Not enough arguments. 7222 Candidate.Viable = false; 7223 Candidate.FailureKind = ovl_fail_too_few_arguments; 7224 return; 7225 } 7226 7227 // Determine the implicit conversion sequences for each of the 7228 // arguments. 7229 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7230 if (ArgIdx < NumParams) { 7231 // (C++ 13.3.2p3): for F to be a viable function, there shall 7232 // exist for each argument an implicit conversion sequence 7233 // (13.3.3.1) that converts that argument to the corresponding 7234 // parameter of F. 7235 QualType ParamType = Proto->getParamType(ArgIdx); 7236 Candidate.Conversions[ArgIdx + 1] 7237 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 7238 /*SuppressUserConversions=*/false, 7239 /*InOverloadResolution=*/false, 7240 /*AllowObjCWritebackConversion=*/ 7241 getLangOpts().ObjCAutoRefCount); 7242 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 7243 Candidate.Viable = false; 7244 Candidate.FailureKind = ovl_fail_bad_conversion; 7245 return; 7246 } 7247 } else { 7248 // (C++ 13.3.2p2): For the purposes of overload resolution, any 7249 // argument for which there is no corresponding parameter is 7250 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 7251 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 7252 } 7253 } 7254 7255 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 7256 Candidate.Viable = false; 7257 Candidate.FailureKind = ovl_fail_enable_if; 7258 Candidate.DeductionFailure.Data = FailedAttr; 7259 return; 7260 } 7261 } 7262 7263 /// Add overload candidates for overloaded operators that are 7264 /// member functions. 7265 /// 7266 /// Add the overloaded operator candidates that are member functions 7267 /// for the operator Op that was used in an operator expression such 7268 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 7269 /// CandidateSet will store the added overload candidates. (C++ 7270 /// [over.match.oper]). 7271 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 7272 SourceLocation OpLoc, 7273 ArrayRef<Expr *> Args, 7274 OverloadCandidateSet& CandidateSet, 7275 SourceRange OpRange) { 7276 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 7277 7278 // C++ [over.match.oper]p3: 7279 // For a unary operator @ with an operand of a type whose 7280 // cv-unqualified version is T1, and for a binary operator @ with 7281 // a left operand of a type whose cv-unqualified version is T1 and 7282 // a right operand of a type whose cv-unqualified version is T2, 7283 // three sets of candidate functions, designated member 7284 // candidates, non-member candidates and built-in candidates, are 7285 // constructed as follows: 7286 QualType T1 = Args[0]->getType(); 7287 7288 // -- If T1 is a complete class type or a class currently being 7289 // defined, the set of member candidates is the result of the 7290 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 7291 // the set of member candidates is empty. 7292 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 7293 // Complete the type if it can be completed. 7294 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 7295 return; 7296 // If the type is neither complete nor being defined, bail out now. 7297 if (!T1Rec->getDecl()->getDefinition()) 7298 return; 7299 7300 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 7301 LookupQualifiedName(Operators, T1Rec->getDecl()); 7302 Operators.suppressDiagnostics(); 7303 7304 for (LookupResult::iterator Oper = Operators.begin(), 7305 OperEnd = Operators.end(); 7306 Oper != OperEnd; 7307 ++Oper) 7308 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 7309 Args[0]->Classify(Context), Args.slice(1), 7310 CandidateSet, /*SuppressUserConversions=*/false); 7311 } 7312 } 7313 7314 /// AddBuiltinCandidate - Add a candidate for a built-in 7315 /// operator. ResultTy and ParamTys are the result and parameter types 7316 /// of the built-in candidate, respectively. Args and NumArgs are the 7317 /// arguments being passed to the candidate. IsAssignmentOperator 7318 /// should be true when this built-in candidate is an assignment 7319 /// operator. NumContextualBoolArguments is the number of arguments 7320 /// (at the beginning of the argument list) that will be contextually 7321 /// converted to bool. 7322 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, 7323 OverloadCandidateSet& CandidateSet, 7324 bool IsAssignmentOperator, 7325 unsigned NumContextualBoolArguments) { 7326 // Overload resolution is always an unevaluated context. 7327 EnterExpressionEvaluationContext Unevaluated( 7328 *this, Sema::ExpressionEvaluationContext::Unevaluated); 7329 7330 // Add this candidate 7331 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 7332 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 7333 Candidate.Function = nullptr; 7334 Candidate.IsSurrogate = false; 7335 Candidate.IgnoreObjectArgument = false; 7336 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes); 7337 7338 // Determine the implicit conversion sequences for each of the 7339 // arguments. 7340 Candidate.Viable = true; 7341 Candidate.ExplicitCallArguments = Args.size(); 7342 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7343 // C++ [over.match.oper]p4: 7344 // For the built-in assignment operators, conversions of the 7345 // left operand are restricted as follows: 7346 // -- no temporaries are introduced to hold the left operand, and 7347 // -- no user-defined conversions are applied to the left 7348 // operand to achieve a type match with the left-most 7349 // parameter of a built-in candidate. 7350 // 7351 // We block these conversions by turning off user-defined 7352 // conversions, since that is the only way that initialization of 7353 // a reference to a non-class type can occur from something that 7354 // is not of the same type. 7355 if (ArgIdx < NumContextualBoolArguments) { 7356 assert(ParamTys[ArgIdx] == Context.BoolTy && 7357 "Contextual conversion to bool requires bool type"); 7358 Candidate.Conversions[ArgIdx] 7359 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 7360 } else { 7361 Candidate.Conversions[ArgIdx] 7362 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 7363 ArgIdx == 0 && IsAssignmentOperator, 7364 /*InOverloadResolution=*/false, 7365 /*AllowObjCWritebackConversion=*/ 7366 getLangOpts().ObjCAutoRefCount); 7367 } 7368 if (Candidate.Conversions[ArgIdx].isBad()) { 7369 Candidate.Viable = false; 7370 Candidate.FailureKind = ovl_fail_bad_conversion; 7371 break; 7372 } 7373 } 7374 } 7375 7376 namespace { 7377 7378 /// BuiltinCandidateTypeSet - A set of types that will be used for the 7379 /// candidate operator functions for built-in operators (C++ 7380 /// [over.built]). The types are separated into pointer types and 7381 /// enumeration types. 7382 class BuiltinCandidateTypeSet { 7383 /// TypeSet - A set of types. 7384 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 7385 llvm::SmallPtrSet<QualType, 8>> TypeSet; 7386 7387 /// PointerTypes - The set of pointer types that will be used in the 7388 /// built-in candidates. 7389 TypeSet PointerTypes; 7390 7391 /// MemberPointerTypes - The set of member pointer types that will be 7392 /// used in the built-in candidates. 7393 TypeSet MemberPointerTypes; 7394 7395 /// EnumerationTypes - The set of enumeration types that will be 7396 /// used in the built-in candidates. 7397 TypeSet EnumerationTypes; 7398 7399 /// The set of vector types that will be used in the built-in 7400 /// candidates. 7401 TypeSet VectorTypes; 7402 7403 /// A flag indicating non-record types are viable candidates 7404 bool HasNonRecordTypes; 7405 7406 /// A flag indicating whether either arithmetic or enumeration types 7407 /// were present in the candidate set. 7408 bool HasArithmeticOrEnumeralTypes; 7409 7410 /// A flag indicating whether the nullptr type was present in the 7411 /// candidate set. 7412 bool HasNullPtrType; 7413 7414 /// Sema - The semantic analysis instance where we are building the 7415 /// candidate type set. 7416 Sema &SemaRef; 7417 7418 /// Context - The AST context in which we will build the type sets. 7419 ASTContext &Context; 7420 7421 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7422 const Qualifiers &VisibleQuals); 7423 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 7424 7425 public: 7426 /// iterator - Iterates through the types that are part of the set. 7427 typedef TypeSet::iterator iterator; 7428 7429 BuiltinCandidateTypeSet(Sema &SemaRef) 7430 : HasNonRecordTypes(false), 7431 HasArithmeticOrEnumeralTypes(false), 7432 HasNullPtrType(false), 7433 SemaRef(SemaRef), 7434 Context(SemaRef.Context) { } 7435 7436 void AddTypesConvertedFrom(QualType Ty, 7437 SourceLocation Loc, 7438 bool AllowUserConversions, 7439 bool AllowExplicitConversions, 7440 const Qualifiers &VisibleTypeConversionsQuals); 7441 7442 /// pointer_begin - First pointer type found; 7443 iterator pointer_begin() { return PointerTypes.begin(); } 7444 7445 /// pointer_end - Past the last pointer type found; 7446 iterator pointer_end() { return PointerTypes.end(); } 7447 7448 /// member_pointer_begin - First member pointer type found; 7449 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7450 7451 /// member_pointer_end - Past the last member pointer type found; 7452 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7453 7454 /// enumeration_begin - First enumeration type found; 7455 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7456 7457 /// enumeration_end - Past the last enumeration type found; 7458 iterator enumeration_end() { return EnumerationTypes.end(); } 7459 7460 iterator vector_begin() { return VectorTypes.begin(); } 7461 iterator vector_end() { return VectorTypes.end(); } 7462 7463 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7464 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7465 bool hasNullPtrType() const { return HasNullPtrType; } 7466 }; 7467 7468 } // end anonymous namespace 7469 7470 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7471 /// the set of pointer types along with any more-qualified variants of 7472 /// that type. For example, if @p Ty is "int const *", this routine 7473 /// will add "int const *", "int const volatile *", "int const 7474 /// restrict *", and "int const volatile restrict *" to the set of 7475 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7476 /// false otherwise. 7477 /// 7478 /// FIXME: what to do about extended qualifiers? 7479 bool 7480 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7481 const Qualifiers &VisibleQuals) { 7482 7483 // Insert this type. 7484 if (!PointerTypes.insert(Ty)) 7485 return false; 7486 7487 QualType PointeeTy; 7488 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7489 bool buildObjCPtr = false; 7490 if (!PointerTy) { 7491 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7492 PointeeTy = PTy->getPointeeType(); 7493 buildObjCPtr = true; 7494 } else { 7495 PointeeTy = PointerTy->getPointeeType(); 7496 } 7497 7498 // Don't add qualified variants of arrays. For one, they're not allowed 7499 // (the qualifier would sink to the element type), and for another, the 7500 // only overload situation where it matters is subscript or pointer +- int, 7501 // and those shouldn't have qualifier variants anyway. 7502 if (PointeeTy->isArrayType()) 7503 return true; 7504 7505 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7506 bool hasVolatile = VisibleQuals.hasVolatile(); 7507 bool hasRestrict = VisibleQuals.hasRestrict(); 7508 7509 // Iterate through all strict supersets of BaseCVR. 7510 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7511 if ((CVR | BaseCVR) != CVR) continue; 7512 // Skip over volatile if no volatile found anywhere in the types. 7513 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7514 7515 // Skip over restrict if no restrict found anywhere in the types, or if 7516 // the type cannot be restrict-qualified. 7517 if ((CVR & Qualifiers::Restrict) && 7518 (!hasRestrict || 7519 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7520 continue; 7521 7522 // Build qualified pointee type. 7523 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7524 7525 // Build qualified pointer type. 7526 QualType QPointerTy; 7527 if (!buildObjCPtr) 7528 QPointerTy = Context.getPointerType(QPointeeTy); 7529 else 7530 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7531 7532 // Insert qualified pointer type. 7533 PointerTypes.insert(QPointerTy); 7534 } 7535 7536 return true; 7537 } 7538 7539 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7540 /// to the set of pointer types along with any more-qualified variants of 7541 /// that type. For example, if @p Ty is "int const *", this routine 7542 /// will add "int const *", "int const volatile *", "int const 7543 /// restrict *", and "int const volatile restrict *" to the set of 7544 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7545 /// false otherwise. 7546 /// 7547 /// FIXME: what to do about extended qualifiers? 7548 bool 7549 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7550 QualType Ty) { 7551 // Insert this type. 7552 if (!MemberPointerTypes.insert(Ty)) 7553 return false; 7554 7555 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7556 assert(PointerTy && "type was not a member pointer type!"); 7557 7558 QualType PointeeTy = PointerTy->getPointeeType(); 7559 // Don't add qualified variants of arrays. For one, they're not allowed 7560 // (the qualifier would sink to the element type), and for another, the 7561 // only overload situation where it matters is subscript or pointer +- int, 7562 // and those shouldn't have qualifier variants anyway. 7563 if (PointeeTy->isArrayType()) 7564 return true; 7565 const Type *ClassTy = PointerTy->getClass(); 7566 7567 // Iterate through all strict supersets of the pointee type's CVR 7568 // qualifiers. 7569 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7570 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7571 if ((CVR | BaseCVR) != CVR) continue; 7572 7573 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7574 MemberPointerTypes.insert( 7575 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7576 } 7577 7578 return true; 7579 } 7580 7581 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7582 /// Ty can be implicit converted to the given set of @p Types. We're 7583 /// primarily interested in pointer types and enumeration types. We also 7584 /// take member pointer types, for the conditional operator. 7585 /// AllowUserConversions is true if we should look at the conversion 7586 /// functions of a class type, and AllowExplicitConversions if we 7587 /// should also include the explicit conversion functions of a class 7588 /// type. 7589 void 7590 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7591 SourceLocation Loc, 7592 bool AllowUserConversions, 7593 bool AllowExplicitConversions, 7594 const Qualifiers &VisibleQuals) { 7595 // Only deal with canonical types. 7596 Ty = Context.getCanonicalType(Ty); 7597 7598 // Look through reference types; they aren't part of the type of an 7599 // expression for the purposes of conversions. 7600 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7601 Ty = RefTy->getPointeeType(); 7602 7603 // If we're dealing with an array type, decay to the pointer. 7604 if (Ty->isArrayType()) 7605 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7606 7607 // Otherwise, we don't care about qualifiers on the type. 7608 Ty = Ty.getLocalUnqualifiedType(); 7609 7610 // Flag if we ever add a non-record type. 7611 const RecordType *TyRec = Ty->getAs<RecordType>(); 7612 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7613 7614 // Flag if we encounter an arithmetic type. 7615 HasArithmeticOrEnumeralTypes = 7616 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7617 7618 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7619 PointerTypes.insert(Ty); 7620 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7621 // Insert our type, and its more-qualified variants, into the set 7622 // of types. 7623 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7624 return; 7625 } else if (Ty->isMemberPointerType()) { 7626 // Member pointers are far easier, since the pointee can't be converted. 7627 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7628 return; 7629 } else if (Ty->isEnumeralType()) { 7630 HasArithmeticOrEnumeralTypes = true; 7631 EnumerationTypes.insert(Ty); 7632 } else if (Ty->isVectorType()) { 7633 // We treat vector types as arithmetic types in many contexts as an 7634 // extension. 7635 HasArithmeticOrEnumeralTypes = true; 7636 VectorTypes.insert(Ty); 7637 } else if (Ty->isNullPtrType()) { 7638 HasNullPtrType = true; 7639 } else if (AllowUserConversions && TyRec) { 7640 // No conversion functions in incomplete types. 7641 if (!SemaRef.isCompleteType(Loc, Ty)) 7642 return; 7643 7644 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7645 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7646 if (isa<UsingShadowDecl>(D)) 7647 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7648 7649 // Skip conversion function templates; they don't tell us anything 7650 // about which builtin types we can convert to. 7651 if (isa<FunctionTemplateDecl>(D)) 7652 continue; 7653 7654 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7655 if (AllowExplicitConversions || !Conv->isExplicit()) { 7656 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7657 VisibleQuals); 7658 } 7659 } 7660 } 7661 } 7662 /// Helper function for adjusting address spaces for the pointer or reference 7663 /// operands of builtin operators depending on the argument. 7664 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, 7665 Expr *Arg) { 7666 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace()); 7667 } 7668 7669 /// Helper function for AddBuiltinOperatorCandidates() that adds 7670 /// the volatile- and non-volatile-qualified assignment operators for the 7671 /// given type to the candidate set. 7672 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7673 QualType T, 7674 ArrayRef<Expr *> Args, 7675 OverloadCandidateSet &CandidateSet) { 7676 QualType ParamTypes[2]; 7677 7678 // T& operator=(T&, T) 7679 ParamTypes[0] = S.Context.getLValueReferenceType( 7680 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0])); 7681 ParamTypes[1] = T; 7682 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7683 /*IsAssignmentOperator=*/true); 7684 7685 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7686 // volatile T& operator=(volatile T&, T) 7687 ParamTypes[0] = S.Context.getLValueReferenceType( 7688 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T), 7689 Args[0])); 7690 ParamTypes[1] = T; 7691 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 7692 /*IsAssignmentOperator=*/true); 7693 } 7694 } 7695 7696 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7697 /// if any, found in visible type conversion functions found in ArgExpr's type. 7698 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7699 Qualifiers VRQuals; 7700 const RecordType *TyRec; 7701 if (const MemberPointerType *RHSMPType = 7702 ArgExpr->getType()->getAs<MemberPointerType>()) 7703 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7704 else 7705 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7706 if (!TyRec) { 7707 // Just to be safe, assume the worst case. 7708 VRQuals.addVolatile(); 7709 VRQuals.addRestrict(); 7710 return VRQuals; 7711 } 7712 7713 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7714 if (!ClassDecl->hasDefinition()) 7715 return VRQuals; 7716 7717 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7718 if (isa<UsingShadowDecl>(D)) 7719 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7720 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7721 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7722 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7723 CanTy = ResTypeRef->getPointeeType(); 7724 // Need to go down the pointer/mempointer chain and add qualifiers 7725 // as see them. 7726 bool done = false; 7727 while (!done) { 7728 if (CanTy.isRestrictQualified()) 7729 VRQuals.addRestrict(); 7730 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7731 CanTy = ResTypePtr->getPointeeType(); 7732 else if (const MemberPointerType *ResTypeMPtr = 7733 CanTy->getAs<MemberPointerType>()) 7734 CanTy = ResTypeMPtr->getPointeeType(); 7735 else 7736 done = true; 7737 if (CanTy.isVolatileQualified()) 7738 VRQuals.addVolatile(); 7739 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7740 return VRQuals; 7741 } 7742 } 7743 } 7744 return VRQuals; 7745 } 7746 7747 namespace { 7748 7749 /// Helper class to manage the addition of builtin operator overload 7750 /// candidates. It provides shared state and utility methods used throughout 7751 /// the process, as well as a helper method to add each group of builtin 7752 /// operator overloads from the standard to a candidate set. 7753 class BuiltinOperatorOverloadBuilder { 7754 // Common instance state available to all overload candidate addition methods. 7755 Sema &S; 7756 ArrayRef<Expr *> Args; 7757 Qualifiers VisibleTypeConversionsQuals; 7758 bool HasArithmeticOrEnumeralCandidateType; 7759 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7760 OverloadCandidateSet &CandidateSet; 7761 7762 static constexpr int ArithmeticTypesCap = 24; 7763 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes; 7764 7765 // Define some indices used to iterate over the arithemetic types in 7766 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic 7767 // types are that preserved by promotion (C++ [over.built]p2). 7768 unsigned FirstIntegralType, 7769 LastIntegralType; 7770 unsigned FirstPromotedIntegralType, 7771 LastPromotedIntegralType; 7772 unsigned FirstPromotedArithmeticType, 7773 LastPromotedArithmeticType; 7774 unsigned NumArithmeticTypes; 7775 7776 void InitArithmeticTypes() { 7777 // Start of promoted types. 7778 FirstPromotedArithmeticType = 0; 7779 ArithmeticTypes.push_back(S.Context.FloatTy); 7780 ArithmeticTypes.push_back(S.Context.DoubleTy); 7781 ArithmeticTypes.push_back(S.Context.LongDoubleTy); 7782 if (S.Context.getTargetInfo().hasFloat128Type()) 7783 ArithmeticTypes.push_back(S.Context.Float128Ty); 7784 7785 // Start of integral types. 7786 FirstIntegralType = ArithmeticTypes.size(); 7787 FirstPromotedIntegralType = ArithmeticTypes.size(); 7788 ArithmeticTypes.push_back(S.Context.IntTy); 7789 ArithmeticTypes.push_back(S.Context.LongTy); 7790 ArithmeticTypes.push_back(S.Context.LongLongTy); 7791 if (S.Context.getTargetInfo().hasInt128Type()) 7792 ArithmeticTypes.push_back(S.Context.Int128Ty); 7793 ArithmeticTypes.push_back(S.Context.UnsignedIntTy); 7794 ArithmeticTypes.push_back(S.Context.UnsignedLongTy); 7795 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy); 7796 if (S.Context.getTargetInfo().hasInt128Type()) 7797 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty); 7798 LastPromotedIntegralType = ArithmeticTypes.size(); 7799 LastPromotedArithmeticType = ArithmeticTypes.size(); 7800 // End of promoted types. 7801 7802 ArithmeticTypes.push_back(S.Context.BoolTy); 7803 ArithmeticTypes.push_back(S.Context.CharTy); 7804 ArithmeticTypes.push_back(S.Context.WCharTy); 7805 if (S.Context.getLangOpts().Char8) 7806 ArithmeticTypes.push_back(S.Context.Char8Ty); 7807 ArithmeticTypes.push_back(S.Context.Char16Ty); 7808 ArithmeticTypes.push_back(S.Context.Char32Ty); 7809 ArithmeticTypes.push_back(S.Context.SignedCharTy); 7810 ArithmeticTypes.push_back(S.Context.ShortTy); 7811 ArithmeticTypes.push_back(S.Context.UnsignedCharTy); 7812 ArithmeticTypes.push_back(S.Context.UnsignedShortTy); 7813 LastIntegralType = ArithmeticTypes.size(); 7814 NumArithmeticTypes = ArithmeticTypes.size(); 7815 // End of integral types. 7816 // FIXME: What about complex? What about half? 7817 7818 assert(ArithmeticTypes.size() <= ArithmeticTypesCap && 7819 "Enough inline storage for all arithmetic types."); 7820 } 7821 7822 /// Helper method to factor out the common pattern of adding overloads 7823 /// for '++' and '--' builtin operators. 7824 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7825 bool HasVolatile, 7826 bool HasRestrict) { 7827 QualType ParamTypes[2] = { 7828 S.Context.getLValueReferenceType(CandidateTy), 7829 S.Context.IntTy 7830 }; 7831 7832 // Non-volatile version. 7833 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7834 7835 // Use a heuristic to reduce number of builtin candidates in the set: 7836 // add volatile version only if there are conversions to a volatile type. 7837 if (HasVolatile) { 7838 ParamTypes[0] = 7839 S.Context.getLValueReferenceType( 7840 S.Context.getVolatileType(CandidateTy)); 7841 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7842 } 7843 7844 // Add restrict version only if there are conversions to a restrict type 7845 // and our candidate type is a non-restrict-qualified pointer. 7846 if (HasRestrict && CandidateTy->isAnyPointerType() && 7847 !CandidateTy.isRestrictQualified()) { 7848 ParamTypes[0] 7849 = S.Context.getLValueReferenceType( 7850 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7851 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7852 7853 if (HasVolatile) { 7854 ParamTypes[0] 7855 = S.Context.getLValueReferenceType( 7856 S.Context.getCVRQualifiedType(CandidateTy, 7857 (Qualifiers::Volatile | 7858 Qualifiers::Restrict))); 7859 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 7860 } 7861 } 7862 7863 } 7864 7865 public: 7866 BuiltinOperatorOverloadBuilder( 7867 Sema &S, ArrayRef<Expr *> Args, 7868 Qualifiers VisibleTypeConversionsQuals, 7869 bool HasArithmeticOrEnumeralCandidateType, 7870 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7871 OverloadCandidateSet &CandidateSet) 7872 : S(S), Args(Args), 7873 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7874 HasArithmeticOrEnumeralCandidateType( 7875 HasArithmeticOrEnumeralCandidateType), 7876 CandidateTypes(CandidateTypes), 7877 CandidateSet(CandidateSet) { 7878 7879 InitArithmeticTypes(); 7880 } 7881 7882 // Increment is deprecated for bool since C++17. 7883 // 7884 // C++ [over.built]p3: 7885 // 7886 // For every pair (T, VQ), where T is an arithmetic type other 7887 // than bool, and VQ is either volatile or empty, there exist 7888 // candidate operator functions of the form 7889 // 7890 // VQ T& operator++(VQ T&); 7891 // T operator++(VQ T&, int); 7892 // 7893 // C++ [over.built]p4: 7894 // 7895 // For every pair (T, VQ), where T is an arithmetic type other 7896 // than bool, and VQ is either volatile or empty, there exist 7897 // candidate operator functions of the form 7898 // 7899 // VQ T& operator--(VQ T&); 7900 // T operator--(VQ T&, int); 7901 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7902 if (!HasArithmeticOrEnumeralCandidateType) 7903 return; 7904 7905 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) { 7906 const auto TypeOfT = ArithmeticTypes[Arith]; 7907 if (TypeOfT == S.Context.BoolTy) { 7908 if (Op == OO_MinusMinus) 7909 continue; 7910 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17) 7911 continue; 7912 } 7913 addPlusPlusMinusMinusStyleOverloads( 7914 TypeOfT, 7915 VisibleTypeConversionsQuals.hasVolatile(), 7916 VisibleTypeConversionsQuals.hasRestrict()); 7917 } 7918 } 7919 7920 // C++ [over.built]p5: 7921 // 7922 // For every pair (T, VQ), where T is a cv-qualified or 7923 // cv-unqualified object type, and VQ is either volatile or 7924 // empty, there exist candidate operator functions of the form 7925 // 7926 // T*VQ& operator++(T*VQ&); 7927 // T*VQ& operator--(T*VQ&); 7928 // T* operator++(T*VQ&, int); 7929 // T* operator--(T*VQ&, int); 7930 void addPlusPlusMinusMinusPointerOverloads() { 7931 for (BuiltinCandidateTypeSet::iterator 7932 Ptr = CandidateTypes[0].pointer_begin(), 7933 PtrEnd = CandidateTypes[0].pointer_end(); 7934 Ptr != PtrEnd; ++Ptr) { 7935 // Skip pointer types that aren't pointers to object types. 7936 if (!(*Ptr)->getPointeeType()->isObjectType()) 7937 continue; 7938 7939 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7940 (!(*Ptr).isVolatileQualified() && 7941 VisibleTypeConversionsQuals.hasVolatile()), 7942 (!(*Ptr).isRestrictQualified() && 7943 VisibleTypeConversionsQuals.hasRestrict())); 7944 } 7945 } 7946 7947 // C++ [over.built]p6: 7948 // For every cv-qualified or cv-unqualified object type T, there 7949 // exist candidate operator functions of the form 7950 // 7951 // T& operator*(T*); 7952 // 7953 // C++ [over.built]p7: 7954 // For every function type T that does not have cv-qualifiers or a 7955 // ref-qualifier, there exist candidate operator functions of the form 7956 // T& operator*(T*); 7957 void addUnaryStarPointerOverloads() { 7958 for (BuiltinCandidateTypeSet::iterator 7959 Ptr = CandidateTypes[0].pointer_begin(), 7960 PtrEnd = CandidateTypes[0].pointer_end(); 7961 Ptr != PtrEnd; ++Ptr) { 7962 QualType ParamTy = *Ptr; 7963 QualType PointeeTy = ParamTy->getPointeeType(); 7964 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7965 continue; 7966 7967 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7968 if (Proto->getMethodQuals() || Proto->getRefQualifier()) 7969 continue; 7970 7971 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 7972 } 7973 } 7974 7975 // C++ [over.built]p9: 7976 // For every promoted arithmetic type T, there exist candidate 7977 // operator functions of the form 7978 // 7979 // T operator+(T); 7980 // T operator-(T); 7981 void addUnaryPlusOrMinusArithmeticOverloads() { 7982 if (!HasArithmeticOrEnumeralCandidateType) 7983 return; 7984 7985 for (unsigned Arith = FirstPromotedArithmeticType; 7986 Arith < LastPromotedArithmeticType; ++Arith) { 7987 QualType ArithTy = ArithmeticTypes[Arith]; 7988 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet); 7989 } 7990 7991 // Extension: We also add these operators for vector types. 7992 for (BuiltinCandidateTypeSet::iterator 7993 Vec = CandidateTypes[0].vector_begin(), 7994 VecEnd = CandidateTypes[0].vector_end(); 7995 Vec != VecEnd; ++Vec) { 7996 QualType VecTy = *Vec; 7997 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 7998 } 7999 } 8000 8001 // C++ [over.built]p8: 8002 // For every type T, there exist candidate operator functions of 8003 // the form 8004 // 8005 // T* operator+(T*); 8006 void addUnaryPlusPointerOverloads() { 8007 for (BuiltinCandidateTypeSet::iterator 8008 Ptr = CandidateTypes[0].pointer_begin(), 8009 PtrEnd = CandidateTypes[0].pointer_end(); 8010 Ptr != PtrEnd; ++Ptr) { 8011 QualType ParamTy = *Ptr; 8012 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet); 8013 } 8014 } 8015 8016 // C++ [over.built]p10: 8017 // For every promoted integral type T, there exist candidate 8018 // operator functions of the form 8019 // 8020 // T operator~(T); 8021 void addUnaryTildePromotedIntegralOverloads() { 8022 if (!HasArithmeticOrEnumeralCandidateType) 8023 return; 8024 8025 for (unsigned Int = FirstPromotedIntegralType; 8026 Int < LastPromotedIntegralType; ++Int) { 8027 QualType IntTy = ArithmeticTypes[Int]; 8028 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet); 8029 } 8030 8031 // Extension: We also add this operator for vector types. 8032 for (BuiltinCandidateTypeSet::iterator 8033 Vec = CandidateTypes[0].vector_begin(), 8034 VecEnd = CandidateTypes[0].vector_end(); 8035 Vec != VecEnd; ++Vec) { 8036 QualType VecTy = *Vec; 8037 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet); 8038 } 8039 } 8040 8041 // C++ [over.match.oper]p16: 8042 // For every pointer to member type T or type std::nullptr_t, there 8043 // exist candidate operator functions of the form 8044 // 8045 // bool operator==(T,T); 8046 // bool operator!=(T,T); 8047 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 8048 /// Set of (canonical) types that we've already handled. 8049 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8050 8051 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8052 for (BuiltinCandidateTypeSet::iterator 8053 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8054 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8055 MemPtr != MemPtrEnd; 8056 ++MemPtr) { 8057 // Don't add the same builtin candidate twice. 8058 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8059 continue; 8060 8061 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8062 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8063 } 8064 8065 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 8066 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 8067 if (AddedTypes.insert(NullPtrTy).second) { 8068 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 8069 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8070 } 8071 } 8072 } 8073 } 8074 8075 // C++ [over.built]p15: 8076 // 8077 // For every T, where T is an enumeration type or a pointer type, 8078 // there exist candidate operator functions of the form 8079 // 8080 // bool operator<(T, T); 8081 // bool operator>(T, T); 8082 // bool operator<=(T, T); 8083 // bool operator>=(T, T); 8084 // bool operator==(T, T); 8085 // bool operator!=(T, T); 8086 // R operator<=>(T, T) 8087 void addGenericBinaryPointerOrEnumeralOverloads() { 8088 // C++ [over.match.oper]p3: 8089 // [...]the built-in candidates include all of the candidate operator 8090 // functions defined in 13.6 that, compared to the given operator, [...] 8091 // do not have the same parameter-type-list as any non-template non-member 8092 // candidate. 8093 // 8094 // Note that in practice, this only affects enumeration types because there 8095 // aren't any built-in candidates of record type, and a user-defined operator 8096 // must have an operand of record or enumeration type. Also, the only other 8097 // overloaded operator with enumeration arguments, operator=, 8098 // cannot be overloaded for enumeration types, so this is the only place 8099 // where we must suppress candidates like this. 8100 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 8101 UserDefinedBinaryOperators; 8102 8103 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8104 if (CandidateTypes[ArgIdx].enumeration_begin() != 8105 CandidateTypes[ArgIdx].enumeration_end()) { 8106 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 8107 CEnd = CandidateSet.end(); 8108 C != CEnd; ++C) { 8109 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 8110 continue; 8111 8112 if (C->Function->isFunctionTemplateSpecialization()) 8113 continue; 8114 8115 QualType FirstParamType = 8116 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 8117 QualType SecondParamType = 8118 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 8119 8120 // Skip if either parameter isn't of enumeral type. 8121 if (!FirstParamType->isEnumeralType() || 8122 !SecondParamType->isEnumeralType()) 8123 continue; 8124 8125 // Add this operator to the set of known user-defined operators. 8126 UserDefinedBinaryOperators.insert( 8127 std::make_pair(S.Context.getCanonicalType(FirstParamType), 8128 S.Context.getCanonicalType(SecondParamType))); 8129 } 8130 } 8131 } 8132 8133 /// Set of (canonical) types that we've already handled. 8134 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8135 8136 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8137 for (BuiltinCandidateTypeSet::iterator 8138 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8139 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8140 Ptr != PtrEnd; ++Ptr) { 8141 // Don't add the same builtin candidate twice. 8142 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8143 continue; 8144 8145 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8146 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8147 } 8148 for (BuiltinCandidateTypeSet::iterator 8149 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8150 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8151 Enum != EnumEnd; ++Enum) { 8152 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 8153 8154 // Don't add the same builtin candidate twice, or if a user defined 8155 // candidate exists. 8156 if (!AddedTypes.insert(CanonType).second || 8157 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 8158 CanonType))) 8159 continue; 8160 QualType ParamTypes[2] = { *Enum, *Enum }; 8161 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8162 } 8163 } 8164 } 8165 8166 // C++ [over.built]p13: 8167 // 8168 // For every cv-qualified or cv-unqualified object type T 8169 // there exist candidate operator functions of the form 8170 // 8171 // T* operator+(T*, ptrdiff_t); 8172 // T& operator[](T*, ptrdiff_t); [BELOW] 8173 // T* operator-(T*, ptrdiff_t); 8174 // T* operator+(ptrdiff_t, T*); 8175 // T& operator[](ptrdiff_t, T*); [BELOW] 8176 // 8177 // C++ [over.built]p14: 8178 // 8179 // For every T, where T is a pointer to object type, there 8180 // exist candidate operator functions of the form 8181 // 8182 // ptrdiff_t operator-(T, T); 8183 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 8184 /// Set of (canonical) types that we've already handled. 8185 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8186 8187 for (int Arg = 0; Arg < 2; ++Arg) { 8188 QualType AsymmetricParamTypes[2] = { 8189 S.Context.getPointerDiffType(), 8190 S.Context.getPointerDiffType(), 8191 }; 8192 for (BuiltinCandidateTypeSet::iterator 8193 Ptr = CandidateTypes[Arg].pointer_begin(), 8194 PtrEnd = CandidateTypes[Arg].pointer_end(); 8195 Ptr != PtrEnd; ++Ptr) { 8196 QualType PointeeTy = (*Ptr)->getPointeeType(); 8197 if (!PointeeTy->isObjectType()) 8198 continue; 8199 8200 AsymmetricParamTypes[Arg] = *Ptr; 8201 if (Arg == 0 || Op == OO_Plus) { 8202 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 8203 // T* operator+(ptrdiff_t, T*); 8204 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet); 8205 } 8206 if (Op == OO_Minus) { 8207 // ptrdiff_t operator-(T, T); 8208 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8209 continue; 8210 8211 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8212 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8213 } 8214 } 8215 } 8216 } 8217 8218 // C++ [over.built]p12: 8219 // 8220 // For every pair of promoted arithmetic types L and R, there 8221 // exist candidate operator functions of the form 8222 // 8223 // LR operator*(L, R); 8224 // LR operator/(L, R); 8225 // LR operator+(L, R); 8226 // LR operator-(L, R); 8227 // bool operator<(L, R); 8228 // bool operator>(L, R); 8229 // bool operator<=(L, R); 8230 // bool operator>=(L, R); 8231 // bool operator==(L, R); 8232 // bool operator!=(L, R); 8233 // 8234 // where LR is the result of the usual arithmetic conversions 8235 // between types L and R. 8236 // 8237 // C++ [over.built]p24: 8238 // 8239 // For every pair of promoted arithmetic types L and R, there exist 8240 // candidate operator functions of the form 8241 // 8242 // LR operator?(bool, L, R); 8243 // 8244 // where LR is the result of the usual arithmetic conversions 8245 // between types L and R. 8246 // Our candidates ignore the first parameter. 8247 void addGenericBinaryArithmeticOverloads() { 8248 if (!HasArithmeticOrEnumeralCandidateType) 8249 return; 8250 8251 for (unsigned Left = FirstPromotedArithmeticType; 8252 Left < LastPromotedArithmeticType; ++Left) { 8253 for (unsigned Right = FirstPromotedArithmeticType; 8254 Right < LastPromotedArithmeticType; ++Right) { 8255 QualType LandR[2] = { ArithmeticTypes[Left], 8256 ArithmeticTypes[Right] }; 8257 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8258 } 8259 } 8260 8261 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 8262 // conditional operator for vector types. 8263 for (BuiltinCandidateTypeSet::iterator 8264 Vec1 = CandidateTypes[0].vector_begin(), 8265 Vec1End = CandidateTypes[0].vector_end(); 8266 Vec1 != Vec1End; ++Vec1) { 8267 for (BuiltinCandidateTypeSet::iterator 8268 Vec2 = CandidateTypes[1].vector_begin(), 8269 Vec2End = CandidateTypes[1].vector_end(); 8270 Vec2 != Vec2End; ++Vec2) { 8271 QualType LandR[2] = { *Vec1, *Vec2 }; 8272 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8273 } 8274 } 8275 } 8276 8277 // C++2a [over.built]p14: 8278 // 8279 // For every integral type T there exists a candidate operator function 8280 // of the form 8281 // 8282 // std::strong_ordering operator<=>(T, T) 8283 // 8284 // C++2a [over.built]p15: 8285 // 8286 // For every pair of floating-point types L and R, there exists a candidate 8287 // operator function of the form 8288 // 8289 // std::partial_ordering operator<=>(L, R); 8290 // 8291 // FIXME: The current specification for integral types doesn't play nice with 8292 // the direction of p0946r0, which allows mixed integral and unscoped-enum 8293 // comparisons. Under the current spec this can lead to ambiguity during 8294 // overload resolution. For example: 8295 // 8296 // enum A : int {a}; 8297 // auto x = (a <=> (long)42); 8298 // 8299 // error: call is ambiguous for arguments 'A' and 'long'. 8300 // note: candidate operator<=>(int, int) 8301 // note: candidate operator<=>(long, long) 8302 // 8303 // To avoid this error, this function deviates from the specification and adds 8304 // the mixed overloads `operator<=>(L, R)` where L and R are promoted 8305 // arithmetic types (the same as the generic relational overloads). 8306 // 8307 // For now this function acts as a placeholder. 8308 void addThreeWayArithmeticOverloads() { 8309 addGenericBinaryArithmeticOverloads(); 8310 } 8311 8312 // C++ [over.built]p17: 8313 // 8314 // For every pair of promoted integral types L and R, there 8315 // exist candidate operator functions of the form 8316 // 8317 // LR operator%(L, R); 8318 // LR operator&(L, R); 8319 // LR operator^(L, R); 8320 // LR operator|(L, R); 8321 // L operator<<(L, R); 8322 // L operator>>(L, R); 8323 // 8324 // where LR is the result of the usual arithmetic conversions 8325 // between types L and R. 8326 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 8327 if (!HasArithmeticOrEnumeralCandidateType) 8328 return; 8329 8330 for (unsigned Left = FirstPromotedIntegralType; 8331 Left < LastPromotedIntegralType; ++Left) { 8332 for (unsigned Right = FirstPromotedIntegralType; 8333 Right < LastPromotedIntegralType; ++Right) { 8334 QualType LandR[2] = { ArithmeticTypes[Left], 8335 ArithmeticTypes[Right] }; 8336 S.AddBuiltinCandidate(LandR, Args, CandidateSet); 8337 } 8338 } 8339 } 8340 8341 // C++ [over.built]p20: 8342 // 8343 // For every pair (T, VQ), where T is an enumeration or 8344 // pointer to member type and VQ is either volatile or 8345 // empty, there exist candidate operator functions of the form 8346 // 8347 // VQ T& operator=(VQ T&, T); 8348 void addAssignmentMemberPointerOrEnumeralOverloads() { 8349 /// Set of (canonical) types that we've already handled. 8350 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8351 8352 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8353 for (BuiltinCandidateTypeSet::iterator 8354 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8355 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8356 Enum != EnumEnd; ++Enum) { 8357 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8358 continue; 8359 8360 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 8361 } 8362 8363 for (BuiltinCandidateTypeSet::iterator 8364 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8365 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8366 MemPtr != MemPtrEnd; ++MemPtr) { 8367 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8368 continue; 8369 8370 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 8371 } 8372 } 8373 } 8374 8375 // C++ [over.built]p19: 8376 // 8377 // For every pair (T, VQ), where T is any type and VQ is either 8378 // volatile or empty, there exist candidate operator functions 8379 // of the form 8380 // 8381 // T*VQ& operator=(T*VQ&, T*); 8382 // 8383 // C++ [over.built]p21: 8384 // 8385 // For every pair (T, VQ), where T is a cv-qualified or 8386 // cv-unqualified object type and VQ is either volatile or 8387 // empty, there exist candidate operator functions of the form 8388 // 8389 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 8390 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 8391 void addAssignmentPointerOverloads(bool isEqualOp) { 8392 /// Set of (canonical) types that we've already handled. 8393 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8394 8395 for (BuiltinCandidateTypeSet::iterator 8396 Ptr = CandidateTypes[0].pointer_begin(), 8397 PtrEnd = CandidateTypes[0].pointer_end(); 8398 Ptr != PtrEnd; ++Ptr) { 8399 // If this is operator=, keep track of the builtin candidates we added. 8400 if (isEqualOp) 8401 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8402 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8403 continue; 8404 8405 // non-volatile version 8406 QualType ParamTypes[2] = { 8407 S.Context.getLValueReferenceType(*Ptr), 8408 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8409 }; 8410 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8411 /*IsAssigmentOperator=*/ isEqualOp); 8412 8413 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8414 VisibleTypeConversionsQuals.hasVolatile(); 8415 if (NeedVolatile) { 8416 // volatile version 8417 ParamTypes[0] = 8418 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8419 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8420 /*IsAssigmentOperator=*/isEqualOp); 8421 } 8422 8423 if (!(*Ptr).isRestrictQualified() && 8424 VisibleTypeConversionsQuals.hasRestrict()) { 8425 // restrict version 8426 ParamTypes[0] 8427 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8428 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8429 /*IsAssigmentOperator=*/isEqualOp); 8430 8431 if (NeedVolatile) { 8432 // volatile restrict version 8433 ParamTypes[0] 8434 = S.Context.getLValueReferenceType( 8435 S.Context.getCVRQualifiedType(*Ptr, 8436 (Qualifiers::Volatile | 8437 Qualifiers::Restrict))); 8438 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8439 /*IsAssigmentOperator=*/isEqualOp); 8440 } 8441 } 8442 } 8443 8444 if (isEqualOp) { 8445 for (BuiltinCandidateTypeSet::iterator 8446 Ptr = CandidateTypes[1].pointer_begin(), 8447 PtrEnd = CandidateTypes[1].pointer_end(); 8448 Ptr != PtrEnd; ++Ptr) { 8449 // Make sure we don't add the same candidate twice. 8450 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8451 continue; 8452 8453 QualType ParamTypes[2] = { 8454 S.Context.getLValueReferenceType(*Ptr), 8455 *Ptr, 8456 }; 8457 8458 // non-volatile version 8459 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8460 /*IsAssigmentOperator=*/true); 8461 8462 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8463 VisibleTypeConversionsQuals.hasVolatile(); 8464 if (NeedVolatile) { 8465 // volatile version 8466 ParamTypes[0] = 8467 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8468 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8469 /*IsAssigmentOperator=*/true); 8470 } 8471 8472 if (!(*Ptr).isRestrictQualified() && 8473 VisibleTypeConversionsQuals.hasRestrict()) { 8474 // restrict version 8475 ParamTypes[0] 8476 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8477 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8478 /*IsAssigmentOperator=*/true); 8479 8480 if (NeedVolatile) { 8481 // volatile restrict version 8482 ParamTypes[0] 8483 = S.Context.getLValueReferenceType( 8484 S.Context.getCVRQualifiedType(*Ptr, 8485 (Qualifiers::Volatile | 8486 Qualifiers::Restrict))); 8487 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8488 /*IsAssigmentOperator=*/true); 8489 } 8490 } 8491 } 8492 } 8493 } 8494 8495 // C++ [over.built]p18: 8496 // 8497 // For every triple (L, VQ, R), where L is an arithmetic type, 8498 // VQ is either volatile or empty, and R is a promoted 8499 // arithmetic type, there exist candidate operator functions of 8500 // the form 8501 // 8502 // VQ L& operator=(VQ L&, R); 8503 // VQ L& operator*=(VQ L&, R); 8504 // VQ L& operator/=(VQ L&, R); 8505 // VQ L& operator+=(VQ L&, R); 8506 // VQ L& operator-=(VQ L&, R); 8507 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8508 if (!HasArithmeticOrEnumeralCandidateType) 8509 return; 8510 8511 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8512 for (unsigned Right = FirstPromotedArithmeticType; 8513 Right < LastPromotedArithmeticType; ++Right) { 8514 QualType ParamTypes[2]; 8515 ParamTypes[1] = ArithmeticTypes[Right]; 8516 8517 // Add this built-in operator as a candidate (VQ is empty). 8518 ParamTypes[0] = 8519 S.Context.getLValueReferenceType(ArithmeticTypes[Left]); 8520 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8521 /*IsAssigmentOperator=*/isEqualOp); 8522 8523 // Add this built-in operator as a candidate (VQ is 'volatile'). 8524 if (VisibleTypeConversionsQuals.hasVolatile()) { 8525 ParamTypes[0] = 8526 S.Context.getVolatileType(ArithmeticTypes[Left]); 8527 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8528 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8529 /*IsAssigmentOperator=*/isEqualOp); 8530 } 8531 } 8532 } 8533 8534 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8535 for (BuiltinCandidateTypeSet::iterator 8536 Vec1 = CandidateTypes[0].vector_begin(), 8537 Vec1End = CandidateTypes[0].vector_end(); 8538 Vec1 != Vec1End; ++Vec1) { 8539 for (BuiltinCandidateTypeSet::iterator 8540 Vec2 = CandidateTypes[1].vector_begin(), 8541 Vec2End = CandidateTypes[1].vector_end(); 8542 Vec2 != Vec2End; ++Vec2) { 8543 QualType ParamTypes[2]; 8544 ParamTypes[1] = *Vec2; 8545 // Add this built-in operator as a candidate (VQ is empty). 8546 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8547 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8548 /*IsAssigmentOperator=*/isEqualOp); 8549 8550 // Add this built-in operator as a candidate (VQ is 'volatile'). 8551 if (VisibleTypeConversionsQuals.hasVolatile()) { 8552 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8553 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8554 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8555 /*IsAssigmentOperator=*/isEqualOp); 8556 } 8557 } 8558 } 8559 } 8560 8561 // C++ [over.built]p22: 8562 // 8563 // For every triple (L, VQ, R), where L is an integral type, VQ 8564 // is either volatile or empty, and R is a promoted integral 8565 // type, there exist candidate operator functions of the form 8566 // 8567 // VQ L& operator%=(VQ L&, R); 8568 // VQ L& operator<<=(VQ L&, R); 8569 // VQ L& operator>>=(VQ L&, R); 8570 // VQ L& operator&=(VQ L&, R); 8571 // VQ L& operator^=(VQ L&, R); 8572 // VQ L& operator|=(VQ L&, R); 8573 void addAssignmentIntegralOverloads() { 8574 if (!HasArithmeticOrEnumeralCandidateType) 8575 return; 8576 8577 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8578 for (unsigned Right = FirstPromotedIntegralType; 8579 Right < LastPromotedIntegralType; ++Right) { 8580 QualType ParamTypes[2]; 8581 ParamTypes[1] = ArithmeticTypes[Right]; 8582 8583 // Add this built-in operator as a candidate (VQ is empty). 8584 ParamTypes[0] = S.Context.getLValueReferenceType( 8585 AdjustAddressSpaceForBuiltinOperandType(S, ArithmeticTypes[Left], 8586 Args[0])); 8587 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8588 if (VisibleTypeConversionsQuals.hasVolatile()) { 8589 // Add this built-in operator as a candidate (VQ is 'volatile'). 8590 ParamTypes[0] = ArithmeticTypes[Left]; 8591 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8592 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8593 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8594 } 8595 } 8596 } 8597 } 8598 8599 // C++ [over.operator]p23: 8600 // 8601 // There also exist candidate operator functions of the form 8602 // 8603 // bool operator!(bool); 8604 // bool operator&&(bool, bool); 8605 // bool operator||(bool, bool); 8606 void addExclaimOverload() { 8607 QualType ParamTy = S.Context.BoolTy; 8608 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet, 8609 /*IsAssignmentOperator=*/false, 8610 /*NumContextualBoolArguments=*/1); 8611 } 8612 void addAmpAmpOrPipePipeOverload() { 8613 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8614 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet, 8615 /*IsAssignmentOperator=*/false, 8616 /*NumContextualBoolArguments=*/2); 8617 } 8618 8619 // C++ [over.built]p13: 8620 // 8621 // For every cv-qualified or cv-unqualified object type T there 8622 // exist candidate operator functions of the form 8623 // 8624 // T* operator+(T*, ptrdiff_t); [ABOVE] 8625 // T& operator[](T*, ptrdiff_t); 8626 // T* operator-(T*, ptrdiff_t); [ABOVE] 8627 // T* operator+(ptrdiff_t, T*); [ABOVE] 8628 // T& operator[](ptrdiff_t, T*); 8629 void addSubscriptOverloads() { 8630 for (BuiltinCandidateTypeSet::iterator 8631 Ptr = CandidateTypes[0].pointer_begin(), 8632 PtrEnd = CandidateTypes[0].pointer_end(); 8633 Ptr != PtrEnd; ++Ptr) { 8634 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8635 QualType PointeeType = (*Ptr)->getPointeeType(); 8636 if (!PointeeType->isObjectType()) 8637 continue; 8638 8639 // T& operator[](T*, ptrdiff_t) 8640 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8641 } 8642 8643 for (BuiltinCandidateTypeSet::iterator 8644 Ptr = CandidateTypes[1].pointer_begin(), 8645 PtrEnd = CandidateTypes[1].pointer_end(); 8646 Ptr != PtrEnd; ++Ptr) { 8647 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8648 QualType PointeeType = (*Ptr)->getPointeeType(); 8649 if (!PointeeType->isObjectType()) 8650 continue; 8651 8652 // T& operator[](ptrdiff_t, T*) 8653 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8654 } 8655 } 8656 8657 // C++ [over.built]p11: 8658 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8659 // C1 is the same type as C2 or is a derived class of C2, T is an object 8660 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8661 // there exist candidate operator functions of the form 8662 // 8663 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8664 // 8665 // where CV12 is the union of CV1 and CV2. 8666 void addArrowStarOverloads() { 8667 for (BuiltinCandidateTypeSet::iterator 8668 Ptr = CandidateTypes[0].pointer_begin(), 8669 PtrEnd = CandidateTypes[0].pointer_end(); 8670 Ptr != PtrEnd; ++Ptr) { 8671 QualType C1Ty = (*Ptr); 8672 QualType C1; 8673 QualifierCollector Q1; 8674 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8675 if (!isa<RecordType>(C1)) 8676 continue; 8677 // heuristic to reduce number of builtin candidates in the set. 8678 // Add volatile/restrict version only if there are conversions to a 8679 // volatile/restrict type. 8680 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8681 continue; 8682 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8683 continue; 8684 for (BuiltinCandidateTypeSet::iterator 8685 MemPtr = CandidateTypes[1].member_pointer_begin(), 8686 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8687 MemPtr != MemPtrEnd; ++MemPtr) { 8688 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8689 QualType C2 = QualType(mptr->getClass(), 0); 8690 C2 = C2.getUnqualifiedType(); 8691 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8692 break; 8693 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8694 // build CV12 T& 8695 QualType T = mptr->getPointeeType(); 8696 if (!VisibleTypeConversionsQuals.hasVolatile() && 8697 T.isVolatileQualified()) 8698 continue; 8699 if (!VisibleTypeConversionsQuals.hasRestrict() && 8700 T.isRestrictQualified()) 8701 continue; 8702 T = Q1.apply(S.Context, T); 8703 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8704 } 8705 } 8706 } 8707 8708 // Note that we don't consider the first argument, since it has been 8709 // contextually converted to bool long ago. The candidates below are 8710 // therefore added as binary. 8711 // 8712 // C++ [over.built]p25: 8713 // For every type T, where T is a pointer, pointer-to-member, or scoped 8714 // enumeration type, there exist candidate operator functions of the form 8715 // 8716 // T operator?(bool, T, T); 8717 // 8718 void addConditionalOperatorOverloads() { 8719 /// Set of (canonical) types that we've already handled. 8720 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8721 8722 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8723 for (BuiltinCandidateTypeSet::iterator 8724 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8725 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8726 Ptr != PtrEnd; ++Ptr) { 8727 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8728 continue; 8729 8730 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8731 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8732 } 8733 8734 for (BuiltinCandidateTypeSet::iterator 8735 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8736 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8737 MemPtr != MemPtrEnd; ++MemPtr) { 8738 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8739 continue; 8740 8741 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8742 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8743 } 8744 8745 if (S.getLangOpts().CPlusPlus11) { 8746 for (BuiltinCandidateTypeSet::iterator 8747 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8748 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8749 Enum != EnumEnd; ++Enum) { 8750 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8751 continue; 8752 8753 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8754 continue; 8755 8756 QualType ParamTypes[2] = { *Enum, *Enum }; 8757 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet); 8758 } 8759 } 8760 } 8761 } 8762 }; 8763 8764 } // end anonymous namespace 8765 8766 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8767 /// operator overloads to the candidate set (C++ [over.built]), based 8768 /// on the operator @p Op and the arguments given. For example, if the 8769 /// operator is a binary '+', this routine might add "int 8770 /// operator+(int, int)" to cover integer addition. 8771 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8772 SourceLocation OpLoc, 8773 ArrayRef<Expr *> Args, 8774 OverloadCandidateSet &CandidateSet) { 8775 // Find all of the types that the arguments can convert to, but only 8776 // if the operator we're looking at has built-in operator candidates 8777 // that make use of these types. Also record whether we encounter non-record 8778 // candidate types or either arithmetic or enumeral candidate types. 8779 Qualifiers VisibleTypeConversionsQuals; 8780 VisibleTypeConversionsQuals.addConst(); 8781 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8782 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8783 8784 bool HasNonRecordCandidateType = false; 8785 bool HasArithmeticOrEnumeralCandidateType = false; 8786 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8787 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8788 CandidateTypes.emplace_back(*this); 8789 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8790 OpLoc, 8791 true, 8792 (Op == OO_Exclaim || 8793 Op == OO_AmpAmp || 8794 Op == OO_PipePipe), 8795 VisibleTypeConversionsQuals); 8796 HasNonRecordCandidateType = HasNonRecordCandidateType || 8797 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8798 HasArithmeticOrEnumeralCandidateType = 8799 HasArithmeticOrEnumeralCandidateType || 8800 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8801 } 8802 8803 // Exit early when no non-record types have been added to the candidate set 8804 // for any of the arguments to the operator. 8805 // 8806 // We can't exit early for !, ||, or &&, since there we have always have 8807 // 'bool' overloads. 8808 if (!HasNonRecordCandidateType && 8809 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8810 return; 8811 8812 // Setup an object to manage the common state for building overloads. 8813 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8814 VisibleTypeConversionsQuals, 8815 HasArithmeticOrEnumeralCandidateType, 8816 CandidateTypes, CandidateSet); 8817 8818 // Dispatch over the operation to add in only those overloads which apply. 8819 switch (Op) { 8820 case OO_None: 8821 case NUM_OVERLOADED_OPERATORS: 8822 llvm_unreachable("Expected an overloaded operator"); 8823 8824 case OO_New: 8825 case OO_Delete: 8826 case OO_Array_New: 8827 case OO_Array_Delete: 8828 case OO_Call: 8829 llvm_unreachable( 8830 "Special operators don't use AddBuiltinOperatorCandidates"); 8831 8832 case OO_Comma: 8833 case OO_Arrow: 8834 case OO_Coawait: 8835 // C++ [over.match.oper]p3: 8836 // -- For the operator ',', the unary operator '&', the 8837 // operator '->', or the operator 'co_await', the 8838 // built-in candidates set is empty. 8839 break; 8840 8841 case OO_Plus: // '+' is either unary or binary 8842 if (Args.size() == 1) 8843 OpBuilder.addUnaryPlusPointerOverloads(); 8844 LLVM_FALLTHROUGH; 8845 8846 case OO_Minus: // '-' is either unary or binary 8847 if (Args.size() == 1) { 8848 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8849 } else { 8850 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8851 OpBuilder.addGenericBinaryArithmeticOverloads(); 8852 } 8853 break; 8854 8855 case OO_Star: // '*' is either unary or binary 8856 if (Args.size() == 1) 8857 OpBuilder.addUnaryStarPointerOverloads(); 8858 else 8859 OpBuilder.addGenericBinaryArithmeticOverloads(); 8860 break; 8861 8862 case OO_Slash: 8863 OpBuilder.addGenericBinaryArithmeticOverloads(); 8864 break; 8865 8866 case OO_PlusPlus: 8867 case OO_MinusMinus: 8868 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8869 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8870 break; 8871 8872 case OO_EqualEqual: 8873 case OO_ExclaimEqual: 8874 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 8875 LLVM_FALLTHROUGH; 8876 8877 case OO_Less: 8878 case OO_Greater: 8879 case OO_LessEqual: 8880 case OO_GreaterEqual: 8881 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 8882 OpBuilder.addGenericBinaryArithmeticOverloads(); 8883 break; 8884 8885 case OO_Spaceship: 8886 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(); 8887 OpBuilder.addThreeWayArithmeticOverloads(); 8888 break; 8889 8890 case OO_Percent: 8891 case OO_Caret: 8892 case OO_Pipe: 8893 case OO_LessLess: 8894 case OO_GreaterGreater: 8895 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8896 break; 8897 8898 case OO_Amp: // '&' is either unary or binary 8899 if (Args.size() == 1) 8900 // C++ [over.match.oper]p3: 8901 // -- For the operator ',', the unary operator '&', or the 8902 // operator '->', the built-in candidates set is empty. 8903 break; 8904 8905 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8906 break; 8907 8908 case OO_Tilde: 8909 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8910 break; 8911 8912 case OO_Equal: 8913 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8914 LLVM_FALLTHROUGH; 8915 8916 case OO_PlusEqual: 8917 case OO_MinusEqual: 8918 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8919 LLVM_FALLTHROUGH; 8920 8921 case OO_StarEqual: 8922 case OO_SlashEqual: 8923 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8924 break; 8925 8926 case OO_PercentEqual: 8927 case OO_LessLessEqual: 8928 case OO_GreaterGreaterEqual: 8929 case OO_AmpEqual: 8930 case OO_CaretEqual: 8931 case OO_PipeEqual: 8932 OpBuilder.addAssignmentIntegralOverloads(); 8933 break; 8934 8935 case OO_Exclaim: 8936 OpBuilder.addExclaimOverload(); 8937 break; 8938 8939 case OO_AmpAmp: 8940 case OO_PipePipe: 8941 OpBuilder.addAmpAmpOrPipePipeOverload(); 8942 break; 8943 8944 case OO_Subscript: 8945 OpBuilder.addSubscriptOverloads(); 8946 break; 8947 8948 case OO_ArrowStar: 8949 OpBuilder.addArrowStarOverloads(); 8950 break; 8951 8952 case OO_Conditional: 8953 OpBuilder.addConditionalOperatorOverloads(); 8954 OpBuilder.addGenericBinaryArithmeticOverloads(); 8955 break; 8956 } 8957 } 8958 8959 /// Add function candidates found via argument-dependent lookup 8960 /// to the set of overloading candidates. 8961 /// 8962 /// This routine performs argument-dependent name lookup based on the 8963 /// given function name (which may also be an operator name) and adds 8964 /// all of the overload candidates found by ADL to the overload 8965 /// candidate set (C++ [basic.lookup.argdep]). 8966 void 8967 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8968 SourceLocation Loc, 8969 ArrayRef<Expr *> Args, 8970 TemplateArgumentListInfo *ExplicitTemplateArgs, 8971 OverloadCandidateSet& CandidateSet, 8972 bool PartialOverloading) { 8973 ADLResult Fns; 8974 8975 // FIXME: This approach for uniquing ADL results (and removing 8976 // redundant candidates from the set) relies on pointer-equality, 8977 // which means we need to key off the canonical decl. However, 8978 // always going back to the canonical decl might not get us the 8979 // right set of default arguments. What default arguments are 8980 // we supposed to consider on ADL candidates, anyway? 8981 8982 // FIXME: Pass in the explicit template arguments? 8983 ArgumentDependentLookup(Name, Loc, Args, Fns); 8984 8985 // Erase all of the candidates we already knew about. 8986 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8987 CandEnd = CandidateSet.end(); 8988 Cand != CandEnd; ++Cand) 8989 if (Cand->Function) { 8990 Fns.erase(Cand->Function); 8991 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8992 Fns.erase(FunTmpl); 8993 } 8994 8995 // For each of the ADL candidates we found, add it to the overload 8996 // set. 8997 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8998 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8999 9000 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 9001 if (ExplicitTemplateArgs) 9002 continue; 9003 9004 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, 9005 /*SupressUserConversions=*/false, PartialOverloading, 9006 /*AllowExplicit=*/false, ADLCallKind::UsesADL); 9007 } else { 9008 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), FoundDecl, 9009 ExplicitTemplateArgs, Args, CandidateSet, 9010 /*SupressUserConversions=*/false, 9011 PartialOverloading, ADLCallKind::UsesADL); 9012 } 9013 } 9014 } 9015 9016 namespace { 9017 enum class Comparison { Equal, Better, Worse }; 9018 } 9019 9020 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 9021 /// overload resolution. 9022 /// 9023 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 9024 /// Cand1's first N enable_if attributes have precisely the same conditions as 9025 /// Cand2's first N enable_if attributes (where N = the number of enable_if 9026 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 9027 /// 9028 /// Note that you can have a pair of candidates such that Cand1's enable_if 9029 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 9030 /// worse than Cand1's. 9031 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 9032 const FunctionDecl *Cand2) { 9033 // Common case: One (or both) decls don't have enable_if attrs. 9034 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 9035 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 9036 if (!Cand1Attr || !Cand2Attr) { 9037 if (Cand1Attr == Cand2Attr) 9038 return Comparison::Equal; 9039 return Cand1Attr ? Comparison::Better : Comparison::Worse; 9040 } 9041 9042 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>(); 9043 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>(); 9044 9045 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 9046 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) { 9047 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair); 9048 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair); 9049 9050 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 9051 // has fewer enable_if attributes than Cand2, and vice versa. 9052 if (!Cand1A) 9053 return Comparison::Worse; 9054 if (!Cand2A) 9055 return Comparison::Better; 9056 9057 Cand1ID.clear(); 9058 Cand2ID.clear(); 9059 9060 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true); 9061 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true); 9062 if (Cand1ID != Cand2ID) 9063 return Comparison::Worse; 9064 } 9065 9066 return Comparison::Equal; 9067 } 9068 9069 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1, 9070 const OverloadCandidate &Cand2) { 9071 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function || 9072 !Cand2.Function->isMultiVersion()) 9073 return false; 9074 9075 // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this 9076 // is obviously better. 9077 if (Cand1.Function->isInvalidDecl()) return false; 9078 if (Cand2.Function->isInvalidDecl()) return true; 9079 9080 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer 9081 // cpu_dispatch, else arbitrarily based on the identifiers. 9082 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>(); 9083 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>(); 9084 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>(); 9085 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>(); 9086 9087 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec) 9088 return false; 9089 9090 if (Cand1CPUDisp && !Cand2CPUDisp) 9091 return true; 9092 if (Cand2CPUDisp && !Cand1CPUDisp) 9093 return false; 9094 9095 if (Cand1CPUSpec && Cand2CPUSpec) { 9096 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size()) 9097 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size(); 9098 9099 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator> 9100 FirstDiff = std::mismatch( 9101 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(), 9102 Cand2CPUSpec->cpus_begin(), 9103 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) { 9104 return LHS->getName() == RHS->getName(); 9105 }); 9106 9107 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() && 9108 "Two different cpu-specific versions should not have the same " 9109 "identifier list, otherwise they'd be the same decl!"); 9110 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName(); 9111 } 9112 llvm_unreachable("No way to get here unless both had cpu_dispatch"); 9113 } 9114 9115 /// isBetterOverloadCandidate - Determines whether the first overload 9116 /// candidate is a better candidate than the second (C++ 13.3.3p1). 9117 bool clang::isBetterOverloadCandidate( 9118 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, 9119 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) { 9120 // Define viable functions to be better candidates than non-viable 9121 // functions. 9122 if (!Cand2.Viable) 9123 return Cand1.Viable; 9124 else if (!Cand1.Viable) 9125 return false; 9126 9127 // C++ [over.match.best]p1: 9128 // 9129 // -- if F is a static member function, ICS1(F) is defined such 9130 // that ICS1(F) is neither better nor worse than ICS1(G) for 9131 // any function G, and, symmetrically, ICS1(G) is neither 9132 // better nor worse than ICS1(F). 9133 unsigned StartArg = 0; 9134 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 9135 StartArg = 1; 9136 9137 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 9138 // We don't allow incompatible pointer conversions in C++. 9139 if (!S.getLangOpts().CPlusPlus) 9140 return ICS.isStandard() && 9141 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 9142 9143 // The only ill-formed conversion we allow in C++ is the string literal to 9144 // char* conversion, which is only considered ill-formed after C++11. 9145 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 9146 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 9147 }; 9148 9149 // Define functions that don't require ill-formed conversions for a given 9150 // argument to be better candidates than functions that do. 9151 unsigned NumArgs = Cand1.Conversions.size(); 9152 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 9153 bool HasBetterConversion = false; 9154 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9155 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 9156 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 9157 if (Cand1Bad != Cand2Bad) { 9158 if (Cand1Bad) 9159 return false; 9160 HasBetterConversion = true; 9161 } 9162 } 9163 9164 if (HasBetterConversion) 9165 return true; 9166 9167 // C++ [over.match.best]p1: 9168 // A viable function F1 is defined to be a better function than another 9169 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 9170 // conversion sequence than ICSi(F2), and then... 9171 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 9172 switch (CompareImplicitConversionSequences(S, Loc, 9173 Cand1.Conversions[ArgIdx], 9174 Cand2.Conversions[ArgIdx])) { 9175 case ImplicitConversionSequence::Better: 9176 // Cand1 has a better conversion sequence. 9177 HasBetterConversion = true; 9178 break; 9179 9180 case ImplicitConversionSequence::Worse: 9181 // Cand1 can't be better than Cand2. 9182 return false; 9183 9184 case ImplicitConversionSequence::Indistinguishable: 9185 // Do nothing. 9186 break; 9187 } 9188 } 9189 9190 // -- for some argument j, ICSj(F1) is a better conversion sequence than 9191 // ICSj(F2), or, if not that, 9192 if (HasBetterConversion) 9193 return true; 9194 9195 // -- the context is an initialization by user-defined conversion 9196 // (see 8.5, 13.3.1.5) and the standard conversion sequence 9197 // from the return type of F1 to the destination type (i.e., 9198 // the type of the entity being initialized) is a better 9199 // conversion sequence than the standard conversion sequence 9200 // from the return type of F2 to the destination type. 9201 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion && 9202 Cand1.Function && Cand2.Function && 9203 isa<CXXConversionDecl>(Cand1.Function) && 9204 isa<CXXConversionDecl>(Cand2.Function)) { 9205 // First check whether we prefer one of the conversion functions over the 9206 // other. This only distinguishes the results in non-standard, extension 9207 // cases such as the conversion from a lambda closure type to a function 9208 // pointer or block. 9209 ImplicitConversionSequence::CompareKind Result = 9210 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 9211 if (Result == ImplicitConversionSequence::Indistinguishable) 9212 Result = CompareStandardConversionSequences(S, Loc, 9213 Cand1.FinalConversion, 9214 Cand2.FinalConversion); 9215 9216 if (Result != ImplicitConversionSequence::Indistinguishable) 9217 return Result == ImplicitConversionSequence::Better; 9218 9219 // FIXME: Compare kind of reference binding if conversion functions 9220 // convert to a reference type used in direct reference binding, per 9221 // C++14 [over.match.best]p1 section 2 bullet 3. 9222 } 9223 9224 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording, 9225 // as combined with the resolution to CWG issue 243. 9226 // 9227 // When the context is initialization by constructor ([over.match.ctor] or 9228 // either phase of [over.match.list]), a constructor is preferred over 9229 // a conversion function. 9230 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 && 9231 Cand1.Function && Cand2.Function && 9232 isa<CXXConstructorDecl>(Cand1.Function) != 9233 isa<CXXConstructorDecl>(Cand2.Function)) 9234 return isa<CXXConstructorDecl>(Cand1.Function); 9235 9236 // -- F1 is a non-template function and F2 is a function template 9237 // specialization, or, if not that, 9238 bool Cand1IsSpecialization = Cand1.Function && 9239 Cand1.Function->getPrimaryTemplate(); 9240 bool Cand2IsSpecialization = Cand2.Function && 9241 Cand2.Function->getPrimaryTemplate(); 9242 if (Cand1IsSpecialization != Cand2IsSpecialization) 9243 return Cand2IsSpecialization; 9244 9245 // -- F1 and F2 are function template specializations, and the function 9246 // template for F1 is more specialized than the template for F2 9247 // according to the partial ordering rules described in 14.5.5.2, or, 9248 // if not that, 9249 if (Cand1IsSpecialization && Cand2IsSpecialization) { 9250 if (FunctionTemplateDecl *BetterTemplate 9251 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 9252 Cand2.Function->getPrimaryTemplate(), 9253 Loc, 9254 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 9255 : TPOC_Call, 9256 Cand1.ExplicitCallArguments, 9257 Cand2.ExplicitCallArguments)) 9258 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 9259 } 9260 9261 // FIXME: Work around a defect in the C++17 inheriting constructor wording. 9262 // A derived-class constructor beats an (inherited) base class constructor. 9263 bool Cand1IsInherited = 9264 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 9265 bool Cand2IsInherited = 9266 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 9267 if (Cand1IsInherited != Cand2IsInherited) 9268 return Cand2IsInherited; 9269 else if (Cand1IsInherited) { 9270 assert(Cand2IsInherited); 9271 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 9272 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 9273 if (Cand1Class->isDerivedFrom(Cand2Class)) 9274 return true; 9275 if (Cand2Class->isDerivedFrom(Cand1Class)) 9276 return false; 9277 // Inherited from sibling base classes: still ambiguous. 9278 } 9279 9280 // Check C++17 tie-breakers for deduction guides. 9281 { 9282 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function); 9283 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function); 9284 if (Guide1 && Guide2) { 9285 // -- F1 is generated from a deduction-guide and F2 is not 9286 if (Guide1->isImplicit() != Guide2->isImplicit()) 9287 return Guide2->isImplicit(); 9288 9289 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not 9290 if (Guide1->isCopyDeductionCandidate()) 9291 return true; 9292 } 9293 } 9294 9295 // Check for enable_if value-based overload resolution. 9296 if (Cand1.Function && Cand2.Function) { 9297 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 9298 if (Cmp != Comparison::Equal) 9299 return Cmp == Comparison::Better; 9300 } 9301 9302 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 9303 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9304 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 9305 S.IdentifyCUDAPreference(Caller, Cand2.Function); 9306 } 9307 9308 bool HasPS1 = Cand1.Function != nullptr && 9309 functionHasPassObjectSizeParams(Cand1.Function); 9310 bool HasPS2 = Cand2.Function != nullptr && 9311 functionHasPassObjectSizeParams(Cand2.Function); 9312 if (HasPS1 != HasPS2 && HasPS1) 9313 return true; 9314 9315 return isBetterMultiversionCandidate(Cand1, Cand2); 9316 } 9317 9318 /// Determine whether two declarations are "equivalent" for the purposes of 9319 /// name lookup and overload resolution. This applies when the same internal/no 9320 /// linkage entity is defined by two modules (probably by textually including 9321 /// the same header). In such a case, we don't consider the declarations to 9322 /// declare the same entity, but we also don't want lookups with both 9323 /// declarations visible to be ambiguous in some cases (this happens when using 9324 /// a modularized libstdc++). 9325 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 9326 const NamedDecl *B) { 9327 auto *VA = dyn_cast_or_null<ValueDecl>(A); 9328 auto *VB = dyn_cast_or_null<ValueDecl>(B); 9329 if (!VA || !VB) 9330 return false; 9331 9332 // The declarations must be declaring the same name as an internal linkage 9333 // entity in different modules. 9334 if (!VA->getDeclContext()->getRedeclContext()->Equals( 9335 VB->getDeclContext()->getRedeclContext()) || 9336 getOwningModule(const_cast<ValueDecl *>(VA)) == 9337 getOwningModule(const_cast<ValueDecl *>(VB)) || 9338 VA->isExternallyVisible() || VB->isExternallyVisible()) 9339 return false; 9340 9341 // Check that the declarations appear to be equivalent. 9342 // 9343 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 9344 // For constants and functions, we should check the initializer or body is 9345 // the same. For non-constant variables, we shouldn't allow it at all. 9346 if (Context.hasSameType(VA->getType(), VB->getType())) 9347 return true; 9348 9349 // Enum constants within unnamed enumerations will have different types, but 9350 // may still be similar enough to be interchangeable for our purposes. 9351 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 9352 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 9353 // Only handle anonymous enums. If the enumerations were named and 9354 // equivalent, they would have been merged to the same type. 9355 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 9356 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 9357 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 9358 !Context.hasSameType(EnumA->getIntegerType(), 9359 EnumB->getIntegerType())) 9360 return false; 9361 // Allow this only if the value is the same for both enumerators. 9362 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 9363 } 9364 } 9365 9366 // Nothing else is sufficiently similar. 9367 return false; 9368 } 9369 9370 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 9371 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 9372 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 9373 9374 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 9375 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 9376 << !M << (M ? M->getFullModuleName() : ""); 9377 9378 for (auto *E : Equiv) { 9379 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 9380 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 9381 << !M << (M ? M->getFullModuleName() : ""); 9382 } 9383 } 9384 9385 /// Computes the best viable function (C++ 13.3.3) 9386 /// within an overload candidate set. 9387 /// 9388 /// \param Loc The location of the function name (or operator symbol) for 9389 /// which overload resolution occurs. 9390 /// 9391 /// \param Best If overload resolution was successful or found a deleted 9392 /// function, \p Best points to the candidate function found. 9393 /// 9394 /// \returns The result of overload resolution. 9395 OverloadingResult 9396 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 9397 iterator &Best) { 9398 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 9399 std::transform(begin(), end(), std::back_inserter(Candidates), 9400 [](OverloadCandidate &Cand) { return &Cand; }); 9401 9402 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 9403 // are accepted by both clang and NVCC. However, during a particular 9404 // compilation mode only one call variant is viable. We need to 9405 // exclude non-viable overload candidates from consideration based 9406 // only on their host/device attributes. Specifically, if one 9407 // candidate call is WrongSide and the other is SameSide, we ignore 9408 // the WrongSide candidate. 9409 if (S.getLangOpts().CUDA) { 9410 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 9411 bool ContainsSameSideCandidate = 9412 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 9413 return Cand->Function && 9414 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9415 Sema::CFP_SameSide; 9416 }); 9417 if (ContainsSameSideCandidate) { 9418 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 9419 return Cand->Function && 9420 S.IdentifyCUDAPreference(Caller, Cand->Function) == 9421 Sema::CFP_WrongSide; 9422 }; 9423 llvm::erase_if(Candidates, IsWrongSideCandidate); 9424 } 9425 } 9426 9427 // Find the best viable function. 9428 Best = end(); 9429 for (auto *Cand : Candidates) 9430 if (Cand->Viable) 9431 if (Best == end() || 9432 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind)) 9433 Best = Cand; 9434 9435 // If we didn't find any viable functions, abort. 9436 if (Best == end()) 9437 return OR_No_Viable_Function; 9438 9439 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 9440 9441 // Make sure that this function is better than every other viable 9442 // function. If not, we have an ambiguity. 9443 for (auto *Cand : Candidates) { 9444 if (Cand->Viable && Cand != Best && 9445 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) { 9446 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 9447 Cand->Function)) { 9448 EquivalentCands.push_back(Cand->Function); 9449 continue; 9450 } 9451 9452 Best = end(); 9453 return OR_Ambiguous; 9454 } 9455 } 9456 9457 // Best is the best viable function. 9458 if (Best->Function && 9459 (Best->Function->isDeleted() || 9460 S.isFunctionConsideredUnavailable(Best->Function))) 9461 return OR_Deleted; 9462 9463 if (!EquivalentCands.empty()) 9464 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 9465 EquivalentCands); 9466 9467 return OR_Success; 9468 } 9469 9470 namespace { 9471 9472 enum OverloadCandidateKind { 9473 oc_function, 9474 oc_method, 9475 oc_constructor, 9476 oc_implicit_default_constructor, 9477 oc_implicit_copy_constructor, 9478 oc_implicit_move_constructor, 9479 oc_implicit_copy_assignment, 9480 oc_implicit_move_assignment, 9481 oc_inherited_constructor 9482 }; 9483 9484 enum OverloadCandidateSelect { 9485 ocs_non_template, 9486 ocs_template, 9487 ocs_described_template, 9488 }; 9489 9490 static std::pair<OverloadCandidateKind, OverloadCandidateSelect> 9491 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9492 std::string &Description) { 9493 9494 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl(); 9495 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9496 isTemplate = true; 9497 Description = S.getTemplateArgumentBindingsText( 9498 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9499 } 9500 9501 OverloadCandidateSelect Select = [&]() { 9502 if (!Description.empty()) 9503 return ocs_described_template; 9504 return isTemplate ? ocs_template : ocs_non_template; 9505 }(); 9506 9507 OverloadCandidateKind Kind = [&]() { 9508 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9509 if (!Ctor->isImplicit()) { 9510 if (isa<ConstructorUsingShadowDecl>(Found)) 9511 return oc_inherited_constructor; 9512 else 9513 return oc_constructor; 9514 } 9515 9516 if (Ctor->isDefaultConstructor()) 9517 return oc_implicit_default_constructor; 9518 9519 if (Ctor->isMoveConstructor()) 9520 return oc_implicit_move_constructor; 9521 9522 assert(Ctor->isCopyConstructor() && 9523 "unexpected sort of implicit constructor"); 9524 return oc_implicit_copy_constructor; 9525 } 9526 9527 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9528 // This actually gets spelled 'candidate function' for now, but 9529 // it doesn't hurt to split it out. 9530 if (!Meth->isImplicit()) 9531 return oc_method; 9532 9533 if (Meth->isMoveAssignmentOperator()) 9534 return oc_implicit_move_assignment; 9535 9536 if (Meth->isCopyAssignmentOperator()) 9537 return oc_implicit_copy_assignment; 9538 9539 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9540 return oc_method; 9541 } 9542 9543 return oc_function; 9544 }(); 9545 9546 return std::make_pair(Kind, Select); 9547 } 9548 9549 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9550 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9551 // set. 9552 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9553 S.Diag(FoundDecl->getLocation(), 9554 diag::note_ovl_candidate_inherited_constructor) 9555 << Shadow->getNominatedBaseClass(); 9556 } 9557 9558 } // end anonymous namespace 9559 9560 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9561 const FunctionDecl *FD) { 9562 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9563 bool AlwaysTrue; 9564 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9565 return false; 9566 if (!AlwaysTrue) 9567 return false; 9568 } 9569 return true; 9570 } 9571 9572 /// Returns true if we can take the address of the function. 9573 /// 9574 /// \param Complain - If true, we'll emit a diagnostic 9575 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9576 /// we in overload resolution? 9577 /// \param Loc - The location of the statement we're complaining about. Ignored 9578 /// if we're not complaining, or if we're in overload resolution. 9579 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9580 bool Complain, 9581 bool InOverloadResolution, 9582 SourceLocation Loc) { 9583 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9584 if (Complain) { 9585 if (InOverloadResolution) 9586 S.Diag(FD->getBeginLoc(), 9587 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9588 else 9589 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9590 } 9591 return false; 9592 } 9593 9594 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9595 return P->hasAttr<PassObjectSizeAttr>(); 9596 }); 9597 if (I == FD->param_end()) 9598 return true; 9599 9600 if (Complain) { 9601 // Add one to ParamNo because it's user-facing 9602 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9603 if (InOverloadResolution) 9604 S.Diag(FD->getLocation(), 9605 diag::note_ovl_candidate_has_pass_object_size_params) 9606 << ParamNo; 9607 else 9608 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9609 << FD << ParamNo; 9610 } 9611 return false; 9612 } 9613 9614 static bool checkAddressOfCandidateIsAvailable(Sema &S, 9615 const FunctionDecl *FD) { 9616 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9617 /*InOverloadResolution=*/true, 9618 /*Loc=*/SourceLocation()); 9619 } 9620 9621 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 9622 bool Complain, 9623 SourceLocation Loc) { 9624 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 9625 /*InOverloadResolution=*/false, 9626 Loc); 9627 } 9628 9629 // Notes the location of an overload candidate. 9630 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 9631 QualType DestType, bool TakingAddress) { 9632 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9633 return; 9634 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() && 9635 !Fn->getAttr<TargetAttr>()->isDefaultVersion()) 9636 return; 9637 9638 std::string FnDesc; 9639 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair = 9640 ClassifyOverloadCandidate(*this, Found, Fn, FnDesc); 9641 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9642 << (unsigned)KSPair.first << (unsigned)KSPair.second 9643 << Fn << FnDesc; 9644 9645 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9646 Diag(Fn->getLocation(), PD); 9647 MaybeEmitInheritedConstructorNote(*this, Found); 9648 } 9649 9650 // Notes the location of all overload candidates designated through 9651 // OverloadedExpr 9652 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9653 bool TakingAddress) { 9654 assert(OverloadedExpr->getType() == Context.OverloadTy); 9655 9656 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9657 OverloadExpr *OvlExpr = Ovl.Expression; 9658 9659 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9660 IEnd = OvlExpr->decls_end(); 9661 I != IEnd; ++I) { 9662 if (FunctionTemplateDecl *FunTmpl = 9663 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9664 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType, 9665 TakingAddress); 9666 } else if (FunctionDecl *Fun 9667 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9668 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress); 9669 } 9670 } 9671 } 9672 9673 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9674 /// "lead" diagnostic; it will be given two arguments, the source and 9675 /// target types of the conversion. 9676 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9677 Sema &S, 9678 SourceLocation CaretLoc, 9679 const PartialDiagnostic &PDiag) const { 9680 S.Diag(CaretLoc, PDiag) 9681 << Ambiguous.getFromType() << Ambiguous.getToType(); 9682 // FIXME: The note limiting machinery is borrowed from 9683 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9684 // refactoring here. 9685 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9686 unsigned CandsShown = 0; 9687 AmbiguousConversionSequence::const_iterator I, E; 9688 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9689 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9690 break; 9691 ++CandsShown; 9692 S.NoteOverloadCandidate(I->first, I->second); 9693 } 9694 if (I != E) 9695 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9696 } 9697 9698 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9699 unsigned I, bool TakingCandidateAddress) { 9700 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9701 assert(Conv.isBad()); 9702 assert(Cand->Function && "for now, candidate must be a function"); 9703 FunctionDecl *Fn = Cand->Function; 9704 9705 // There's a conversion slot for the object argument if this is a 9706 // non-constructor method. Note that 'I' corresponds the 9707 // conversion-slot index. 9708 bool isObjectArgument = false; 9709 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9710 if (I == 0) 9711 isObjectArgument = true; 9712 else 9713 I--; 9714 } 9715 9716 std::string FnDesc; 9717 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 9718 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9719 9720 Expr *FromExpr = Conv.Bad.FromExpr; 9721 QualType FromTy = Conv.Bad.getFromType(); 9722 QualType ToTy = Conv.Bad.getToType(); 9723 9724 if (FromTy == S.Context.OverloadTy) { 9725 assert(FromExpr && "overload set argument came from implicit argument?"); 9726 Expr *E = FromExpr->IgnoreParens(); 9727 if (isa<UnaryOperator>(E)) 9728 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9729 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9730 9731 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9732 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9733 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy 9734 << Name << I + 1; 9735 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9736 return; 9737 } 9738 9739 // Do some hand-waving analysis to see if the non-viability is due 9740 // to a qualifier mismatch. 9741 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9742 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9743 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9744 CToTy = RT->getPointeeType(); 9745 else { 9746 // TODO: detect and diagnose the full richness of const mismatches. 9747 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9748 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9749 CFromTy = FromPT->getPointeeType(); 9750 CToTy = ToPT->getPointeeType(); 9751 } 9752 } 9753 9754 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9755 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9756 Qualifiers FromQs = CFromTy.getQualifiers(); 9757 Qualifiers ToQs = CToTy.getQualifiers(); 9758 9759 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9760 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9761 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9762 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9763 << ToTy << (unsigned)isObjectArgument << I + 1; 9764 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9765 return; 9766 } 9767 9768 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9769 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9770 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9771 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9772 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9773 << (unsigned)isObjectArgument << I + 1; 9774 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9775 return; 9776 } 9777 9778 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9779 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9780 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9781 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9782 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9783 << (unsigned)isObjectArgument << I + 1; 9784 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9785 return; 9786 } 9787 9788 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 9789 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 9790 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9791 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9792 << FromQs.hasUnaligned() << I + 1; 9793 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9794 return; 9795 } 9796 9797 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9798 assert(CVR && "unexpected qualifiers mismatch"); 9799 9800 if (isObjectArgument) { 9801 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9802 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9803 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9804 << (CVR - 1); 9805 } else { 9806 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9807 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9808 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9809 << (CVR - 1) << I + 1; 9810 } 9811 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9812 return; 9813 } 9814 9815 // Special diagnostic for failure to convert an initializer list, since 9816 // telling the user that it has type void is not useful. 9817 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9818 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9819 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9820 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9821 << ToTy << (unsigned)isObjectArgument << I + 1; 9822 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9823 return; 9824 } 9825 9826 // Diagnose references or pointers to incomplete types differently, 9827 // since it's far from impossible that the incompleteness triggered 9828 // the failure. 9829 QualType TempFromTy = FromTy.getNonReferenceType(); 9830 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9831 TempFromTy = PTy->getPointeeType(); 9832 if (TempFromTy->isIncompleteType()) { 9833 // Emit the generic diagnostic and, optionally, add the hints to it. 9834 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9835 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9836 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9837 << ToTy << (unsigned)isObjectArgument << I + 1 9838 << (unsigned)(Cand->Fix.Kind); 9839 9840 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9841 return; 9842 } 9843 9844 // Diagnose base -> derived pointer conversions. 9845 unsigned BaseToDerivedConversion = 0; 9846 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9847 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9848 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9849 FromPtrTy->getPointeeType()) && 9850 !FromPtrTy->getPointeeType()->isIncompleteType() && 9851 !ToPtrTy->getPointeeType()->isIncompleteType() && 9852 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9853 FromPtrTy->getPointeeType())) 9854 BaseToDerivedConversion = 1; 9855 } 9856 } else if (const ObjCObjectPointerType *FromPtrTy 9857 = FromTy->getAs<ObjCObjectPointerType>()) { 9858 if (const ObjCObjectPointerType *ToPtrTy 9859 = ToTy->getAs<ObjCObjectPointerType>()) 9860 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9861 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9862 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9863 FromPtrTy->getPointeeType()) && 9864 FromIface->isSuperClassOf(ToIface)) 9865 BaseToDerivedConversion = 2; 9866 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9867 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9868 !FromTy->isIncompleteType() && 9869 !ToRefTy->getPointeeType()->isIncompleteType() && 9870 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9871 BaseToDerivedConversion = 3; 9872 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9873 ToTy.getNonReferenceType().getCanonicalType() == 9874 FromTy.getNonReferenceType().getCanonicalType()) { 9875 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9876 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9877 << (unsigned)isObjectArgument << I + 1 9878 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()); 9879 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9880 return; 9881 } 9882 } 9883 9884 if (BaseToDerivedConversion) { 9885 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv) 9886 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9887 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9888 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1; 9889 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9890 return; 9891 } 9892 9893 if (isa<ObjCObjectPointerType>(CFromTy) && 9894 isa<PointerType>(CToTy)) { 9895 Qualifiers FromQs = CFromTy.getQualifiers(); 9896 Qualifiers ToQs = CToTy.getQualifiers(); 9897 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9898 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9899 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9900 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9901 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1; 9902 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9903 return; 9904 } 9905 } 9906 9907 if (TakingCandidateAddress && 9908 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9909 return; 9910 9911 // Emit the generic diagnostic and, optionally, add the hints to it. 9912 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9913 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 9914 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy 9915 << ToTy << (unsigned)isObjectArgument << I + 1 9916 << (unsigned)(Cand->Fix.Kind); 9917 9918 // If we can fix the conversion, suggest the FixIts. 9919 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9920 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9921 FDiag << *HI; 9922 S.Diag(Fn->getLocation(), FDiag); 9923 9924 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9925 } 9926 9927 /// Additional arity mismatch diagnosis specific to a function overload 9928 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9929 /// over a candidate in any candidate set. 9930 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9931 unsigned NumArgs) { 9932 FunctionDecl *Fn = Cand->Function; 9933 unsigned MinParams = Fn->getMinRequiredArguments(); 9934 9935 // With invalid overloaded operators, it's possible that we think we 9936 // have an arity mismatch when in fact it looks like we have the 9937 // right number of arguments, because only overloaded operators have 9938 // the weird behavior of overloading member and non-member functions. 9939 // Just don't report anything. 9940 if (Fn->isInvalidDecl() && 9941 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9942 return true; 9943 9944 if (NumArgs < MinParams) { 9945 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9946 (Cand->FailureKind == ovl_fail_bad_deduction && 9947 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9948 } else { 9949 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9950 (Cand->FailureKind == ovl_fail_bad_deduction && 9951 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9952 } 9953 9954 return false; 9955 } 9956 9957 /// General arity mismatch diagnosis over a candidate in a candidate set. 9958 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 9959 unsigned NumFormalArgs) { 9960 assert(isa<FunctionDecl>(D) && 9961 "The templated declaration should at least be a function" 9962 " when diagnosing bad template argument deduction due to too many" 9963 " or too few arguments"); 9964 9965 FunctionDecl *Fn = cast<FunctionDecl>(D); 9966 9967 // TODO: treat calls to a missing default constructor as a special case 9968 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9969 unsigned MinParams = Fn->getMinRequiredArguments(); 9970 9971 // at least / at most / exactly 9972 unsigned mode, modeCount; 9973 if (NumFormalArgs < MinParams) { 9974 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9975 FnTy->isTemplateVariadic()) 9976 mode = 0; // "at least" 9977 else 9978 mode = 2; // "exactly" 9979 modeCount = MinParams; 9980 } else { 9981 if (MinParams != FnTy->getNumParams()) 9982 mode = 1; // "at most" 9983 else 9984 mode = 2; // "exactly" 9985 modeCount = FnTy->getNumParams(); 9986 } 9987 9988 std::string Description; 9989 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 9990 ClassifyOverloadCandidate(S, Found, Fn, Description); 9991 9992 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9993 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9994 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9995 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs; 9996 else 9997 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9998 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second 9999 << Description << mode << modeCount << NumFormalArgs; 10000 10001 MaybeEmitInheritedConstructorNote(S, Found); 10002 } 10003 10004 /// Arity mismatch diagnosis specific to a function overload candidate. 10005 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 10006 unsigned NumFormalArgs) { 10007 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 10008 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 10009 } 10010 10011 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 10012 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 10013 return TD; 10014 llvm_unreachable("Unsupported: Getting the described template declaration" 10015 " for bad deduction diagnosis"); 10016 } 10017 10018 /// Diagnose a failed template-argument deduction. 10019 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 10020 DeductionFailureInfo &DeductionFailure, 10021 unsigned NumArgs, 10022 bool TakingCandidateAddress) { 10023 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 10024 NamedDecl *ParamD; 10025 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 10026 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 10027 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 10028 switch (DeductionFailure.Result) { 10029 case Sema::TDK_Success: 10030 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10031 10032 case Sema::TDK_Incomplete: { 10033 assert(ParamD && "no parameter found for incomplete deduction result"); 10034 S.Diag(Templated->getLocation(), 10035 diag::note_ovl_candidate_incomplete_deduction) 10036 << ParamD->getDeclName(); 10037 MaybeEmitInheritedConstructorNote(S, Found); 10038 return; 10039 } 10040 10041 case Sema::TDK_IncompletePack: { 10042 assert(ParamD && "no parameter found for incomplete deduction result"); 10043 S.Diag(Templated->getLocation(), 10044 diag::note_ovl_candidate_incomplete_deduction_pack) 10045 << ParamD->getDeclName() 10046 << (DeductionFailure.getFirstArg()->pack_size() + 1) 10047 << *DeductionFailure.getFirstArg(); 10048 MaybeEmitInheritedConstructorNote(S, Found); 10049 return; 10050 } 10051 10052 case Sema::TDK_Underqualified: { 10053 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 10054 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 10055 10056 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 10057 10058 // Param will have been canonicalized, but it should just be a 10059 // qualified version of ParamD, so move the qualifiers to that. 10060 QualifierCollector Qs; 10061 Qs.strip(Param); 10062 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 10063 assert(S.Context.hasSameType(Param, NonCanonParam)); 10064 10065 // Arg has also been canonicalized, but there's nothing we can do 10066 // about that. It also doesn't matter as much, because it won't 10067 // have any template parameters in it (because deduction isn't 10068 // done on dependent types). 10069 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 10070 10071 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 10072 << ParamD->getDeclName() << Arg << NonCanonParam; 10073 MaybeEmitInheritedConstructorNote(S, Found); 10074 return; 10075 } 10076 10077 case Sema::TDK_Inconsistent: { 10078 assert(ParamD && "no parameter found for inconsistent deduction result"); 10079 int which = 0; 10080 if (isa<TemplateTypeParmDecl>(ParamD)) 10081 which = 0; 10082 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 10083 // Deduction might have failed because we deduced arguments of two 10084 // different types for a non-type template parameter. 10085 // FIXME: Use a different TDK value for this. 10086 QualType T1 = 10087 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 10088 QualType T2 = 10089 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 10090 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) { 10091 S.Diag(Templated->getLocation(), 10092 diag::note_ovl_candidate_inconsistent_deduction_types) 10093 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 10094 << *DeductionFailure.getSecondArg() << T2; 10095 MaybeEmitInheritedConstructorNote(S, Found); 10096 return; 10097 } 10098 10099 which = 1; 10100 } else { 10101 which = 2; 10102 } 10103 10104 S.Diag(Templated->getLocation(), 10105 diag::note_ovl_candidate_inconsistent_deduction) 10106 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 10107 << *DeductionFailure.getSecondArg(); 10108 MaybeEmitInheritedConstructorNote(S, Found); 10109 return; 10110 } 10111 10112 case Sema::TDK_InvalidExplicitArguments: 10113 assert(ParamD && "no parameter found for invalid explicit arguments"); 10114 if (ParamD->getDeclName()) 10115 S.Diag(Templated->getLocation(), 10116 diag::note_ovl_candidate_explicit_arg_mismatch_named) 10117 << ParamD->getDeclName(); 10118 else { 10119 int index = 0; 10120 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 10121 index = TTP->getIndex(); 10122 else if (NonTypeTemplateParmDecl *NTTP 10123 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 10124 index = NTTP->getIndex(); 10125 else 10126 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 10127 S.Diag(Templated->getLocation(), 10128 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 10129 << (index + 1); 10130 } 10131 MaybeEmitInheritedConstructorNote(S, Found); 10132 return; 10133 10134 case Sema::TDK_TooManyArguments: 10135 case Sema::TDK_TooFewArguments: 10136 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 10137 return; 10138 10139 case Sema::TDK_InstantiationDepth: 10140 S.Diag(Templated->getLocation(), 10141 diag::note_ovl_candidate_instantiation_depth); 10142 MaybeEmitInheritedConstructorNote(S, Found); 10143 return; 10144 10145 case Sema::TDK_SubstitutionFailure: { 10146 // Format the template argument list into the argument string. 10147 SmallString<128> TemplateArgString; 10148 if (TemplateArgumentList *Args = 10149 DeductionFailure.getTemplateArgumentList()) { 10150 TemplateArgString = " "; 10151 TemplateArgString += S.getTemplateArgumentBindingsText( 10152 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10153 } 10154 10155 // If this candidate was disabled by enable_if, say so. 10156 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 10157 if (PDiag && PDiag->second.getDiagID() == 10158 diag::err_typename_nested_not_found_enable_if) { 10159 // FIXME: Use the source range of the condition, and the fully-qualified 10160 // name of the enable_if template. These are both present in PDiag. 10161 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 10162 << "'enable_if'" << TemplateArgString; 10163 return; 10164 } 10165 10166 // We found a specific requirement that disabled the enable_if. 10167 if (PDiag && PDiag->second.getDiagID() == 10168 diag::err_typename_nested_not_found_requirement) { 10169 S.Diag(Templated->getLocation(), 10170 diag::note_ovl_candidate_disabled_by_requirement) 10171 << PDiag->second.getStringArg(0) << TemplateArgString; 10172 return; 10173 } 10174 10175 // Format the SFINAE diagnostic into the argument string. 10176 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 10177 // formatted message in another diagnostic. 10178 SmallString<128> SFINAEArgString; 10179 SourceRange R; 10180 if (PDiag) { 10181 SFINAEArgString = ": "; 10182 R = SourceRange(PDiag->first, PDiag->first); 10183 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 10184 } 10185 10186 S.Diag(Templated->getLocation(), 10187 diag::note_ovl_candidate_substitution_failure) 10188 << TemplateArgString << SFINAEArgString << R; 10189 MaybeEmitInheritedConstructorNote(S, Found); 10190 return; 10191 } 10192 10193 case Sema::TDK_DeducedMismatch: 10194 case Sema::TDK_DeducedMismatchNested: { 10195 // Format the template argument list into the argument string. 10196 SmallString<128> TemplateArgString; 10197 if (TemplateArgumentList *Args = 10198 DeductionFailure.getTemplateArgumentList()) { 10199 TemplateArgString = " "; 10200 TemplateArgString += S.getTemplateArgumentBindingsText( 10201 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 10202 } 10203 10204 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 10205 << (*DeductionFailure.getCallArgIndex() + 1) 10206 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 10207 << TemplateArgString 10208 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested); 10209 break; 10210 } 10211 10212 case Sema::TDK_NonDeducedMismatch: { 10213 // FIXME: Provide a source location to indicate what we couldn't match. 10214 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 10215 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 10216 if (FirstTA.getKind() == TemplateArgument::Template && 10217 SecondTA.getKind() == TemplateArgument::Template) { 10218 TemplateName FirstTN = FirstTA.getAsTemplate(); 10219 TemplateName SecondTN = SecondTA.getAsTemplate(); 10220 if (FirstTN.getKind() == TemplateName::Template && 10221 SecondTN.getKind() == TemplateName::Template) { 10222 if (FirstTN.getAsTemplateDecl()->getName() == 10223 SecondTN.getAsTemplateDecl()->getName()) { 10224 // FIXME: This fixes a bad diagnostic where both templates are named 10225 // the same. This particular case is a bit difficult since: 10226 // 1) It is passed as a string to the diagnostic printer. 10227 // 2) The diagnostic printer only attempts to find a better 10228 // name for types, not decls. 10229 // Ideally, this should folded into the diagnostic printer. 10230 S.Diag(Templated->getLocation(), 10231 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 10232 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 10233 return; 10234 } 10235 } 10236 } 10237 10238 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 10239 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 10240 return; 10241 10242 // FIXME: For generic lambda parameters, check if the function is a lambda 10243 // call operator, and if so, emit a prettier and more informative 10244 // diagnostic that mentions 'auto' and lambda in addition to 10245 // (or instead of?) the canonical template type parameters. 10246 S.Diag(Templated->getLocation(), 10247 diag::note_ovl_candidate_non_deduced_mismatch) 10248 << FirstTA << SecondTA; 10249 return; 10250 } 10251 // TODO: diagnose these individually, then kill off 10252 // note_ovl_candidate_bad_deduction, which is uselessly vague. 10253 case Sema::TDK_MiscellaneousDeductionFailure: 10254 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 10255 MaybeEmitInheritedConstructorNote(S, Found); 10256 return; 10257 case Sema::TDK_CUDATargetMismatch: 10258 S.Diag(Templated->getLocation(), 10259 diag::note_cuda_ovl_candidate_target_mismatch); 10260 return; 10261 } 10262 } 10263 10264 /// Diagnose a failed template-argument deduction, for function calls. 10265 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 10266 unsigned NumArgs, 10267 bool TakingCandidateAddress) { 10268 unsigned TDK = Cand->DeductionFailure.Result; 10269 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 10270 if (CheckArityMismatch(S, Cand, NumArgs)) 10271 return; 10272 } 10273 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 10274 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 10275 } 10276 10277 /// CUDA: diagnose an invalid call across targets. 10278 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 10279 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 10280 FunctionDecl *Callee = Cand->Function; 10281 10282 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 10283 CalleeTarget = S.IdentifyCUDATarget(Callee); 10284 10285 std::string FnDesc; 10286 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10287 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc); 10288 10289 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 10290 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template 10291 << FnDesc /* Ignored */ 10292 << CalleeTarget << CallerTarget; 10293 10294 // This could be an implicit constructor for which we could not infer the 10295 // target due to a collsion. Diagnose that case. 10296 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 10297 if (Meth != nullptr && Meth->isImplicit()) { 10298 CXXRecordDecl *ParentClass = Meth->getParent(); 10299 Sema::CXXSpecialMember CSM; 10300 10301 switch (FnKindPair.first) { 10302 default: 10303 return; 10304 case oc_implicit_default_constructor: 10305 CSM = Sema::CXXDefaultConstructor; 10306 break; 10307 case oc_implicit_copy_constructor: 10308 CSM = Sema::CXXCopyConstructor; 10309 break; 10310 case oc_implicit_move_constructor: 10311 CSM = Sema::CXXMoveConstructor; 10312 break; 10313 case oc_implicit_copy_assignment: 10314 CSM = Sema::CXXCopyAssignment; 10315 break; 10316 case oc_implicit_move_assignment: 10317 CSM = Sema::CXXMoveAssignment; 10318 break; 10319 }; 10320 10321 bool ConstRHS = false; 10322 if (Meth->getNumParams()) { 10323 if (const ReferenceType *RT = 10324 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 10325 ConstRHS = RT->getPointeeType().isConstQualified(); 10326 } 10327 } 10328 10329 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 10330 /* ConstRHS */ ConstRHS, 10331 /* Diagnose */ true); 10332 } 10333 } 10334 10335 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 10336 FunctionDecl *Callee = Cand->Function; 10337 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 10338 10339 S.Diag(Callee->getLocation(), 10340 diag::note_ovl_candidate_disabled_by_function_cond_attr) 10341 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 10342 } 10343 10344 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 10345 FunctionDecl *Callee = Cand->Function; 10346 10347 S.Diag(Callee->getLocation(), 10348 diag::note_ovl_candidate_disabled_by_extension) 10349 << S.getOpenCLExtensionsFromDeclExtMap(Callee); 10350 } 10351 10352 /// Generates a 'note' diagnostic for an overload candidate. We've 10353 /// already generated a primary error at the call site. 10354 /// 10355 /// It really does need to be a single diagnostic with its caret 10356 /// pointed at the candidate declaration. Yes, this creates some 10357 /// major challenges of technical writing. Yes, this makes pointing 10358 /// out problems with specific arguments quite awkward. It's still 10359 /// better than generating twenty screens of text for every failed 10360 /// overload. 10361 /// 10362 /// It would be great to be able to express per-candidate problems 10363 /// more richly for those diagnostic clients that cared, but we'd 10364 /// still have to be just as careful with the default diagnostics. 10365 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 10366 unsigned NumArgs, 10367 bool TakingCandidateAddress) { 10368 FunctionDecl *Fn = Cand->Function; 10369 10370 // Note deleted candidates, but only if they're viable. 10371 if (Cand->Viable) { 10372 if (Fn->isDeleted() || S.isFunctionConsideredUnavailable(Fn)) { 10373 std::string FnDesc; 10374 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair = 10375 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 10376 10377 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 10378 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc 10379 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 10380 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10381 return; 10382 } 10383 10384 // We don't really have anything else to say about viable candidates. 10385 S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10386 return; 10387 } 10388 10389 switch (Cand->FailureKind) { 10390 case ovl_fail_too_many_arguments: 10391 case ovl_fail_too_few_arguments: 10392 return DiagnoseArityMismatch(S, Cand, NumArgs); 10393 10394 case ovl_fail_bad_deduction: 10395 return DiagnoseBadDeduction(S, Cand, NumArgs, 10396 TakingCandidateAddress); 10397 10398 case ovl_fail_illegal_constructor: { 10399 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 10400 << (Fn->getPrimaryTemplate() ? 1 : 0); 10401 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10402 return; 10403 } 10404 10405 case ovl_fail_trivial_conversion: 10406 case ovl_fail_bad_final_conversion: 10407 case ovl_fail_final_conversion_not_exact: 10408 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10409 10410 case ovl_fail_bad_conversion: { 10411 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 10412 for (unsigned N = Cand->Conversions.size(); I != N; ++I) 10413 if (Cand->Conversions[I].isBad()) 10414 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 10415 10416 // FIXME: this currently happens when we're called from SemaInit 10417 // when user-conversion overload fails. Figure out how to handle 10418 // those conditions and diagnose them well. 10419 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 10420 } 10421 10422 case ovl_fail_bad_target: 10423 return DiagnoseBadTarget(S, Cand); 10424 10425 case ovl_fail_enable_if: 10426 return DiagnoseFailedEnableIfAttr(S, Cand); 10427 10428 case ovl_fail_ext_disabled: 10429 return DiagnoseOpenCLExtensionDisabled(S, Cand); 10430 10431 case ovl_fail_inhctor_slice: 10432 // It's generally not interesting to note copy/move constructors here. 10433 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor()) 10434 return; 10435 S.Diag(Fn->getLocation(), 10436 diag::note_ovl_candidate_inherited_constructor_slice) 10437 << (Fn->getPrimaryTemplate() ? 1 : 0) 10438 << Fn->getParamDecl(0)->getType()->isRValueReferenceType(); 10439 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 10440 return; 10441 10442 case ovl_fail_addr_not_available: { 10443 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 10444 (void)Available; 10445 assert(!Available); 10446 break; 10447 } 10448 case ovl_non_default_multiversion_function: 10449 // Do nothing, these should simply be ignored. 10450 break; 10451 } 10452 } 10453 10454 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 10455 // Desugar the type of the surrogate down to a function type, 10456 // retaining as many typedefs as possible while still showing 10457 // the function type (and, therefore, its parameter types). 10458 QualType FnType = Cand->Surrogate->getConversionType(); 10459 bool isLValueReference = false; 10460 bool isRValueReference = false; 10461 bool isPointer = false; 10462 if (const LValueReferenceType *FnTypeRef = 10463 FnType->getAs<LValueReferenceType>()) { 10464 FnType = FnTypeRef->getPointeeType(); 10465 isLValueReference = true; 10466 } else if (const RValueReferenceType *FnTypeRef = 10467 FnType->getAs<RValueReferenceType>()) { 10468 FnType = FnTypeRef->getPointeeType(); 10469 isRValueReference = true; 10470 } 10471 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 10472 FnType = FnTypePtr->getPointeeType(); 10473 isPointer = true; 10474 } 10475 // Desugar down to a function type. 10476 FnType = QualType(FnType->getAs<FunctionType>(), 0); 10477 // Reconstruct the pointer/reference as appropriate. 10478 if (isPointer) FnType = S.Context.getPointerType(FnType); 10479 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 10480 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 10481 10482 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 10483 << FnType; 10484 } 10485 10486 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 10487 SourceLocation OpLoc, 10488 OverloadCandidate *Cand) { 10489 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary"); 10490 std::string TypeStr("operator"); 10491 TypeStr += Opc; 10492 TypeStr += "("; 10493 TypeStr += Cand->BuiltinParamTypes[0].getAsString(); 10494 if (Cand->Conversions.size() == 1) { 10495 TypeStr += ")"; 10496 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 10497 } else { 10498 TypeStr += ", "; 10499 TypeStr += Cand->BuiltinParamTypes[1].getAsString(); 10500 TypeStr += ")"; 10501 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 10502 } 10503 } 10504 10505 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 10506 OverloadCandidate *Cand) { 10507 for (const ImplicitConversionSequence &ICS : Cand->Conversions) { 10508 if (ICS.isBad()) break; // all meaningless after first invalid 10509 if (!ICS.isAmbiguous()) continue; 10510 10511 ICS.DiagnoseAmbiguousConversion( 10512 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 10513 } 10514 } 10515 10516 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 10517 if (Cand->Function) 10518 return Cand->Function->getLocation(); 10519 if (Cand->IsSurrogate) 10520 return Cand->Surrogate->getLocation(); 10521 return SourceLocation(); 10522 } 10523 10524 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 10525 switch ((Sema::TemplateDeductionResult)DFI.Result) { 10526 case Sema::TDK_Success: 10527 case Sema::TDK_NonDependentConversionFailure: 10528 llvm_unreachable("non-deduction failure while diagnosing bad deduction"); 10529 10530 case Sema::TDK_Invalid: 10531 case Sema::TDK_Incomplete: 10532 case Sema::TDK_IncompletePack: 10533 return 1; 10534 10535 case Sema::TDK_Underqualified: 10536 case Sema::TDK_Inconsistent: 10537 return 2; 10538 10539 case Sema::TDK_SubstitutionFailure: 10540 case Sema::TDK_DeducedMismatch: 10541 case Sema::TDK_DeducedMismatchNested: 10542 case Sema::TDK_NonDeducedMismatch: 10543 case Sema::TDK_MiscellaneousDeductionFailure: 10544 case Sema::TDK_CUDATargetMismatch: 10545 return 3; 10546 10547 case Sema::TDK_InstantiationDepth: 10548 return 4; 10549 10550 case Sema::TDK_InvalidExplicitArguments: 10551 return 5; 10552 10553 case Sema::TDK_TooManyArguments: 10554 case Sema::TDK_TooFewArguments: 10555 return 6; 10556 } 10557 llvm_unreachable("Unhandled deduction result"); 10558 } 10559 10560 namespace { 10561 struct CompareOverloadCandidatesForDisplay { 10562 Sema &S; 10563 SourceLocation Loc; 10564 size_t NumArgs; 10565 OverloadCandidateSet::CandidateSetKind CSK; 10566 10567 CompareOverloadCandidatesForDisplay( 10568 Sema &S, SourceLocation Loc, size_t NArgs, 10569 OverloadCandidateSet::CandidateSetKind CSK) 10570 : S(S), NumArgs(NArgs), CSK(CSK) {} 10571 10572 bool operator()(const OverloadCandidate *L, 10573 const OverloadCandidate *R) { 10574 // Fast-path this check. 10575 if (L == R) return false; 10576 10577 // Order first by viability. 10578 if (L->Viable) { 10579 if (!R->Viable) return true; 10580 10581 // TODO: introduce a tri-valued comparison for overload 10582 // candidates. Would be more worthwhile if we had a sort 10583 // that could exploit it. 10584 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK)) 10585 return true; 10586 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK)) 10587 return false; 10588 } else if (R->Viable) 10589 return false; 10590 10591 assert(L->Viable == R->Viable); 10592 10593 // Criteria by which we can sort non-viable candidates: 10594 if (!L->Viable) { 10595 // 1. Arity mismatches come after other candidates. 10596 if (L->FailureKind == ovl_fail_too_many_arguments || 10597 L->FailureKind == ovl_fail_too_few_arguments) { 10598 if (R->FailureKind == ovl_fail_too_many_arguments || 10599 R->FailureKind == ovl_fail_too_few_arguments) { 10600 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 10601 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 10602 if (LDist == RDist) { 10603 if (L->FailureKind == R->FailureKind) 10604 // Sort non-surrogates before surrogates. 10605 return !L->IsSurrogate && R->IsSurrogate; 10606 // Sort candidates requiring fewer parameters than there were 10607 // arguments given after candidates requiring more parameters 10608 // than there were arguments given. 10609 return L->FailureKind == ovl_fail_too_many_arguments; 10610 } 10611 return LDist < RDist; 10612 } 10613 return false; 10614 } 10615 if (R->FailureKind == ovl_fail_too_many_arguments || 10616 R->FailureKind == ovl_fail_too_few_arguments) 10617 return true; 10618 10619 // 2. Bad conversions come first and are ordered by the number 10620 // of bad conversions and quality of good conversions. 10621 if (L->FailureKind == ovl_fail_bad_conversion) { 10622 if (R->FailureKind != ovl_fail_bad_conversion) 10623 return true; 10624 10625 // The conversion that can be fixed with a smaller number of changes, 10626 // comes first. 10627 unsigned numLFixes = L->Fix.NumConversionsFixed; 10628 unsigned numRFixes = R->Fix.NumConversionsFixed; 10629 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 10630 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 10631 if (numLFixes != numRFixes) { 10632 return numLFixes < numRFixes; 10633 } 10634 10635 // If there's any ordering between the defined conversions... 10636 // FIXME: this might not be transitive. 10637 assert(L->Conversions.size() == R->Conversions.size()); 10638 10639 int leftBetter = 0; 10640 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 10641 for (unsigned E = L->Conversions.size(); I != E; ++I) { 10642 switch (CompareImplicitConversionSequences(S, Loc, 10643 L->Conversions[I], 10644 R->Conversions[I])) { 10645 case ImplicitConversionSequence::Better: 10646 leftBetter++; 10647 break; 10648 10649 case ImplicitConversionSequence::Worse: 10650 leftBetter--; 10651 break; 10652 10653 case ImplicitConversionSequence::Indistinguishable: 10654 break; 10655 } 10656 } 10657 if (leftBetter > 0) return true; 10658 if (leftBetter < 0) return false; 10659 10660 } else if (R->FailureKind == ovl_fail_bad_conversion) 10661 return false; 10662 10663 if (L->FailureKind == ovl_fail_bad_deduction) { 10664 if (R->FailureKind != ovl_fail_bad_deduction) 10665 return true; 10666 10667 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10668 return RankDeductionFailure(L->DeductionFailure) 10669 < RankDeductionFailure(R->DeductionFailure); 10670 } else if (R->FailureKind == ovl_fail_bad_deduction) 10671 return false; 10672 10673 // TODO: others? 10674 } 10675 10676 // Sort everything else by location. 10677 SourceLocation LLoc = GetLocationForCandidate(L); 10678 SourceLocation RLoc = GetLocationForCandidate(R); 10679 10680 // Put candidates without locations (e.g. builtins) at the end. 10681 if (LLoc.isInvalid()) return false; 10682 if (RLoc.isInvalid()) return true; 10683 10684 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10685 } 10686 }; 10687 } 10688 10689 /// CompleteNonViableCandidate - Normally, overload resolution only 10690 /// computes up to the first bad conversion. Produces the FixIt set if 10691 /// possible. 10692 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 10693 ArrayRef<Expr *> Args) { 10694 assert(!Cand->Viable); 10695 10696 // Don't do anything on failures other than bad conversion. 10697 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 10698 10699 // We only want the FixIts if all the arguments can be corrected. 10700 bool Unfixable = false; 10701 // Use a implicit copy initialization to check conversion fixes. 10702 Cand->Fix.setConversionChecker(TryCopyInitialization); 10703 10704 // Attempt to fix the bad conversion. 10705 unsigned ConvCount = Cand->Conversions.size(); 10706 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/; 10707 ++ConvIdx) { 10708 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 10709 if (Cand->Conversions[ConvIdx].isInitialized() && 10710 Cand->Conversions[ConvIdx].isBad()) { 10711 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10712 break; 10713 } 10714 } 10715 10716 // FIXME: this should probably be preserved from the overload 10717 // operation somehow. 10718 bool SuppressUserConversions = false; 10719 10720 unsigned ConvIdx = 0; 10721 ArrayRef<QualType> ParamTypes; 10722 10723 if (Cand->IsSurrogate) { 10724 QualType ConvType 10725 = Cand->Surrogate->getConversionType().getNonReferenceType(); 10726 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10727 ConvType = ConvPtrType->getPointeeType(); 10728 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes(); 10729 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10730 ConvIdx = 1; 10731 } else if (Cand->Function) { 10732 ParamTypes = 10733 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes(); 10734 if (isa<CXXMethodDecl>(Cand->Function) && 10735 !isa<CXXConstructorDecl>(Cand->Function)) { 10736 // Conversion 0 is 'this', which doesn't have a corresponding argument. 10737 ConvIdx = 1; 10738 } 10739 } else { 10740 // Builtin operator. 10741 assert(ConvCount <= 3); 10742 ParamTypes = Cand->BuiltinParamTypes; 10743 } 10744 10745 // Fill in the rest of the conversions. 10746 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 10747 if (Cand->Conversions[ConvIdx].isInitialized()) { 10748 // We've already checked this conversion. 10749 } else if (ArgIdx < ParamTypes.size()) { 10750 if (ParamTypes[ArgIdx]->isDependentType()) 10751 Cand->Conversions[ConvIdx].setAsIdentityConversion( 10752 Args[ArgIdx]->getType()); 10753 else { 10754 Cand->Conversions[ConvIdx] = 10755 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx], 10756 SuppressUserConversions, 10757 /*InOverloadResolution=*/true, 10758 /*AllowObjCWritebackConversion=*/ 10759 S.getLangOpts().ObjCAutoRefCount); 10760 // Store the FixIt in the candidate if it exists. 10761 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 10762 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10763 } 10764 } else 10765 Cand->Conversions[ConvIdx].setEllipsis(); 10766 } 10767 } 10768 10769 /// When overload resolution fails, prints diagnostic messages containing the 10770 /// candidates in the candidate set. 10771 void OverloadCandidateSet::NoteCandidates( 10772 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 10773 StringRef Opc, SourceLocation OpLoc, 10774 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 10775 // Sort the candidates by viability and position. Sorting directly would 10776 // be prohibitive, so we make a set of pointers and sort those. 10777 SmallVector<OverloadCandidate*, 32> Cands; 10778 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10779 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10780 if (!Filter(*Cand)) 10781 continue; 10782 if (Cand->Viable) 10783 Cands.push_back(Cand); 10784 else if (OCD == OCD_AllCandidates) { 10785 CompleteNonViableCandidate(S, Cand, Args); 10786 if (Cand->Function || Cand->IsSurrogate) 10787 Cands.push_back(Cand); 10788 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10789 // want to list every possible builtin candidate. 10790 } 10791 } 10792 10793 std::stable_sort(Cands.begin(), Cands.end(), 10794 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind)); 10795 10796 bool ReportedAmbiguousConversions = false; 10797 10798 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 10799 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10800 unsigned CandsShown = 0; 10801 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10802 OverloadCandidate *Cand = *I; 10803 10804 // Set an arbitrary limit on the number of candidate functions we'll spam 10805 // the user with. FIXME: This limit should depend on details of the 10806 // candidate list. 10807 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10808 break; 10809 } 10810 ++CandsShown; 10811 10812 if (Cand->Function) 10813 NoteFunctionCandidate(S, Cand, Args.size(), 10814 /*TakingCandidateAddress=*/false); 10815 else if (Cand->IsSurrogate) 10816 NoteSurrogateCandidate(S, Cand); 10817 else { 10818 assert(Cand->Viable && 10819 "Non-viable built-in candidates are not added to Cands."); 10820 // Generally we only see ambiguities including viable builtin 10821 // operators if overload resolution got screwed up by an 10822 // ambiguous user-defined conversion. 10823 // 10824 // FIXME: It's quite possible for different conversions to see 10825 // different ambiguities, though. 10826 if (!ReportedAmbiguousConversions) { 10827 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10828 ReportedAmbiguousConversions = true; 10829 } 10830 10831 // If this is a viable builtin, print it. 10832 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10833 } 10834 } 10835 10836 if (I != E) 10837 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10838 } 10839 10840 static SourceLocation 10841 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10842 return Cand->Specialization ? Cand->Specialization->getLocation() 10843 : SourceLocation(); 10844 } 10845 10846 namespace { 10847 struct CompareTemplateSpecCandidatesForDisplay { 10848 Sema &S; 10849 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10850 10851 bool operator()(const TemplateSpecCandidate *L, 10852 const TemplateSpecCandidate *R) { 10853 // Fast-path this check. 10854 if (L == R) 10855 return false; 10856 10857 // Assuming that both candidates are not matches... 10858 10859 // Sort by the ranking of deduction failures. 10860 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10861 return RankDeductionFailure(L->DeductionFailure) < 10862 RankDeductionFailure(R->DeductionFailure); 10863 10864 // Sort everything else by location. 10865 SourceLocation LLoc = GetLocationForCandidate(L); 10866 SourceLocation RLoc = GetLocationForCandidate(R); 10867 10868 // Put candidates without locations (e.g. builtins) at the end. 10869 if (LLoc.isInvalid()) 10870 return false; 10871 if (RLoc.isInvalid()) 10872 return true; 10873 10874 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10875 } 10876 }; 10877 } 10878 10879 /// Diagnose a template argument deduction failure. 10880 /// We are treating these failures as overload failures due to bad 10881 /// deductions. 10882 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10883 bool ForTakingAddress) { 10884 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 10885 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10886 } 10887 10888 void TemplateSpecCandidateSet::destroyCandidates() { 10889 for (iterator i = begin(), e = end(); i != e; ++i) { 10890 i->DeductionFailure.Destroy(); 10891 } 10892 } 10893 10894 void TemplateSpecCandidateSet::clear() { 10895 destroyCandidates(); 10896 Candidates.clear(); 10897 } 10898 10899 /// NoteCandidates - When no template specialization match is found, prints 10900 /// diagnostic messages containing the non-matching specializations that form 10901 /// the candidate set. 10902 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10903 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10904 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10905 // Sort the candidates by position (assuming no candidate is a match). 10906 // Sorting directly would be prohibitive, so we make a set of pointers 10907 // and sort those. 10908 SmallVector<TemplateSpecCandidate *, 32> Cands; 10909 Cands.reserve(size()); 10910 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10911 if (Cand->Specialization) 10912 Cands.push_back(Cand); 10913 // Otherwise, this is a non-matching builtin candidate. We do not, 10914 // in general, want to list every possible builtin candidate. 10915 } 10916 10917 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S)); 10918 10919 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10920 // for generalization purposes (?). 10921 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10922 10923 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10924 unsigned CandsShown = 0; 10925 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10926 TemplateSpecCandidate *Cand = *I; 10927 10928 // Set an arbitrary limit on the number of candidates we'll spam 10929 // the user with. FIXME: This limit should depend on details of the 10930 // candidate list. 10931 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10932 break; 10933 ++CandsShown; 10934 10935 assert(Cand->Specialization && 10936 "Non-matching built-in candidates are not added to Cands."); 10937 Cand->NoteDeductionFailure(S, ForTakingAddress); 10938 } 10939 10940 if (I != E) 10941 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10942 } 10943 10944 // [PossiblyAFunctionType] --> [Return] 10945 // NonFunctionType --> NonFunctionType 10946 // R (A) --> R(A) 10947 // R (*)(A) --> R (A) 10948 // R (&)(A) --> R (A) 10949 // R (S::*)(A) --> R (A) 10950 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10951 QualType Ret = PossiblyAFunctionType; 10952 if (const PointerType *ToTypePtr = 10953 PossiblyAFunctionType->getAs<PointerType>()) 10954 Ret = ToTypePtr->getPointeeType(); 10955 else if (const ReferenceType *ToTypeRef = 10956 PossiblyAFunctionType->getAs<ReferenceType>()) 10957 Ret = ToTypeRef->getPointeeType(); 10958 else if (const MemberPointerType *MemTypePtr = 10959 PossiblyAFunctionType->getAs<MemberPointerType>()) 10960 Ret = MemTypePtr->getPointeeType(); 10961 Ret = 10962 Context.getCanonicalType(Ret).getUnqualifiedType(); 10963 return Ret; 10964 } 10965 10966 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 10967 bool Complain = true) { 10968 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 10969 S.DeduceReturnType(FD, Loc, Complain)) 10970 return true; 10971 10972 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 10973 if (S.getLangOpts().CPlusPlus17 && 10974 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 10975 !S.ResolveExceptionSpec(Loc, FPT)) 10976 return true; 10977 10978 return false; 10979 } 10980 10981 namespace { 10982 // A helper class to help with address of function resolution 10983 // - allows us to avoid passing around all those ugly parameters 10984 class AddressOfFunctionResolver { 10985 Sema& S; 10986 Expr* SourceExpr; 10987 const QualType& TargetType; 10988 QualType TargetFunctionType; // Extracted function type from target type 10989 10990 bool Complain; 10991 //DeclAccessPair& ResultFunctionAccessPair; 10992 ASTContext& Context; 10993 10994 bool TargetTypeIsNonStaticMemberFunction; 10995 bool FoundNonTemplateFunction; 10996 bool StaticMemberFunctionFromBoundPointer; 10997 bool HasComplained; 10998 10999 OverloadExpr::FindResult OvlExprInfo; 11000 OverloadExpr *OvlExpr; 11001 TemplateArgumentListInfo OvlExplicitTemplateArgs; 11002 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 11003 TemplateSpecCandidateSet FailedCandidates; 11004 11005 public: 11006 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 11007 const QualType &TargetType, bool Complain) 11008 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 11009 Complain(Complain), Context(S.getASTContext()), 11010 TargetTypeIsNonStaticMemberFunction( 11011 !!TargetType->getAs<MemberPointerType>()), 11012 FoundNonTemplateFunction(false), 11013 StaticMemberFunctionFromBoundPointer(false), 11014 HasComplained(false), 11015 OvlExprInfo(OverloadExpr::find(SourceExpr)), 11016 OvlExpr(OvlExprInfo.Expression), 11017 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 11018 ExtractUnqualifiedFunctionTypeFromTargetType(); 11019 11020 if (TargetFunctionType->isFunctionType()) { 11021 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 11022 if (!UME->isImplicitAccess() && 11023 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 11024 StaticMemberFunctionFromBoundPointer = true; 11025 } else if (OvlExpr->hasExplicitTemplateArgs()) { 11026 DeclAccessPair dap; 11027 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 11028 OvlExpr, false, &dap)) { 11029 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 11030 if (!Method->isStatic()) { 11031 // If the target type is a non-function type and the function found 11032 // is a non-static member function, pretend as if that was the 11033 // target, it's the only possible type to end up with. 11034 TargetTypeIsNonStaticMemberFunction = true; 11035 11036 // And skip adding the function if its not in the proper form. 11037 // We'll diagnose this due to an empty set of functions. 11038 if (!OvlExprInfo.HasFormOfMemberPointer) 11039 return; 11040 } 11041 11042 Matches.push_back(std::make_pair(dap, Fn)); 11043 } 11044 return; 11045 } 11046 11047 if (OvlExpr->hasExplicitTemplateArgs()) 11048 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 11049 11050 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 11051 // C++ [over.over]p4: 11052 // If more than one function is selected, [...] 11053 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 11054 if (FoundNonTemplateFunction) 11055 EliminateAllTemplateMatches(); 11056 else 11057 EliminateAllExceptMostSpecializedTemplate(); 11058 } 11059 } 11060 11061 if (S.getLangOpts().CUDA && Matches.size() > 1) 11062 EliminateSuboptimalCudaMatches(); 11063 } 11064 11065 bool hasComplained() const { return HasComplained; } 11066 11067 private: 11068 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 11069 QualType Discard; 11070 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 11071 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 11072 } 11073 11074 /// \return true if A is considered a better overload candidate for the 11075 /// desired type than B. 11076 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 11077 // If A doesn't have exactly the correct type, we don't want to classify it 11078 // as "better" than anything else. This way, the user is required to 11079 // disambiguate for us if there are multiple candidates and no exact match. 11080 return candidateHasExactlyCorrectType(A) && 11081 (!candidateHasExactlyCorrectType(B) || 11082 compareEnableIfAttrs(S, A, B) == Comparison::Better); 11083 } 11084 11085 /// \return true if we were able to eliminate all but one overload candidate, 11086 /// false otherwise. 11087 bool eliminiateSuboptimalOverloadCandidates() { 11088 // Same algorithm as overload resolution -- one pass to pick the "best", 11089 // another pass to be sure that nothing is better than the best. 11090 auto Best = Matches.begin(); 11091 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 11092 if (isBetterCandidate(I->second, Best->second)) 11093 Best = I; 11094 11095 const FunctionDecl *BestFn = Best->second; 11096 auto IsBestOrInferiorToBest = [this, BestFn]( 11097 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 11098 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 11099 }; 11100 11101 // Note: We explicitly leave Matches unmodified if there isn't a clear best 11102 // option, so we can potentially give the user a better error 11103 if (!llvm::all_of(Matches, IsBestOrInferiorToBest)) 11104 return false; 11105 Matches[0] = *Best; 11106 Matches.resize(1); 11107 return true; 11108 } 11109 11110 bool isTargetTypeAFunction() const { 11111 return TargetFunctionType->isFunctionType(); 11112 } 11113 11114 // [ToType] [Return] 11115 11116 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 11117 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 11118 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 11119 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 11120 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 11121 } 11122 11123 // return true if any matching specializations were found 11124 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 11125 const DeclAccessPair& CurAccessFunPair) { 11126 if (CXXMethodDecl *Method 11127 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 11128 // Skip non-static function templates when converting to pointer, and 11129 // static when converting to member pointer. 11130 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11131 return false; 11132 } 11133 else if (TargetTypeIsNonStaticMemberFunction) 11134 return false; 11135 11136 // C++ [over.over]p2: 11137 // If the name is a function template, template argument deduction is 11138 // done (14.8.2.2), and if the argument deduction succeeds, the 11139 // resulting template argument list is used to generate a single 11140 // function template specialization, which is added to the set of 11141 // overloaded functions considered. 11142 FunctionDecl *Specialization = nullptr; 11143 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11144 if (Sema::TemplateDeductionResult Result 11145 = S.DeduceTemplateArguments(FunctionTemplate, 11146 &OvlExplicitTemplateArgs, 11147 TargetFunctionType, Specialization, 11148 Info, /*IsAddressOfFunction*/true)) { 11149 // Make a note of the failed deduction for diagnostics. 11150 FailedCandidates.addCandidate() 11151 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 11152 MakeDeductionFailureInfo(Context, Result, Info)); 11153 return false; 11154 } 11155 11156 // Template argument deduction ensures that we have an exact match or 11157 // compatible pointer-to-function arguments that would be adjusted by ICS. 11158 // This function template specicalization works. 11159 assert(S.isSameOrCompatibleFunctionType( 11160 Context.getCanonicalType(Specialization->getType()), 11161 Context.getCanonicalType(TargetFunctionType))); 11162 11163 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 11164 return false; 11165 11166 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 11167 return true; 11168 } 11169 11170 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 11171 const DeclAccessPair& CurAccessFunPair) { 11172 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 11173 // Skip non-static functions when converting to pointer, and static 11174 // when converting to member pointer. 11175 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 11176 return false; 11177 } 11178 else if (TargetTypeIsNonStaticMemberFunction) 11179 return false; 11180 11181 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 11182 if (S.getLangOpts().CUDA) 11183 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 11184 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 11185 return false; 11186 if (FunDecl->isMultiVersion()) { 11187 const auto *TA = FunDecl->getAttr<TargetAttr>(); 11188 if (TA && !TA->isDefaultVersion()) 11189 return false; 11190 } 11191 11192 // If any candidate has a placeholder return type, trigger its deduction 11193 // now. 11194 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(), 11195 Complain)) { 11196 HasComplained |= Complain; 11197 return false; 11198 } 11199 11200 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 11201 return false; 11202 11203 // If we're in C, we need to support types that aren't exactly identical. 11204 if (!S.getLangOpts().CPlusPlus || 11205 candidateHasExactlyCorrectType(FunDecl)) { 11206 Matches.push_back(std::make_pair( 11207 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 11208 FoundNonTemplateFunction = true; 11209 return true; 11210 } 11211 } 11212 11213 return false; 11214 } 11215 11216 bool FindAllFunctionsThatMatchTargetTypeExactly() { 11217 bool Ret = false; 11218 11219 // If the overload expression doesn't have the form of a pointer to 11220 // member, don't try to convert it to a pointer-to-member type. 11221 if (IsInvalidFormOfPointerToMemberFunction()) 11222 return false; 11223 11224 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11225 E = OvlExpr->decls_end(); 11226 I != E; ++I) { 11227 // Look through any using declarations to find the underlying function. 11228 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 11229 11230 // C++ [over.over]p3: 11231 // Non-member functions and static member functions match 11232 // targets of type "pointer-to-function" or "reference-to-function." 11233 // Nonstatic member functions match targets of 11234 // type "pointer-to-member-function." 11235 // Note that according to DR 247, the containing class does not matter. 11236 if (FunctionTemplateDecl *FunctionTemplate 11237 = dyn_cast<FunctionTemplateDecl>(Fn)) { 11238 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 11239 Ret = true; 11240 } 11241 // If we have explicit template arguments supplied, skip non-templates. 11242 else if (!OvlExpr->hasExplicitTemplateArgs() && 11243 AddMatchingNonTemplateFunction(Fn, I.getPair())) 11244 Ret = true; 11245 } 11246 assert(Ret || Matches.empty()); 11247 return Ret; 11248 } 11249 11250 void EliminateAllExceptMostSpecializedTemplate() { 11251 // [...] and any given function template specialization F1 is 11252 // eliminated if the set contains a second function template 11253 // specialization whose function template is more specialized 11254 // than the function template of F1 according to the partial 11255 // ordering rules of 14.5.5.2. 11256 11257 // The algorithm specified above is quadratic. We instead use a 11258 // two-pass algorithm (similar to the one used to identify the 11259 // best viable function in an overload set) that identifies the 11260 // best function template (if it exists). 11261 11262 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 11263 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 11264 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 11265 11266 // TODO: It looks like FailedCandidates does not serve much purpose 11267 // here, since the no_viable diagnostic has index 0. 11268 UnresolvedSetIterator Result = S.getMostSpecialized( 11269 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 11270 SourceExpr->getBeginLoc(), S.PDiag(), 11271 S.PDiag(diag::err_addr_ovl_ambiguous) 11272 << Matches[0].second->getDeclName(), 11273 S.PDiag(diag::note_ovl_candidate) 11274 << (unsigned)oc_function << (unsigned)ocs_described_template, 11275 Complain, TargetFunctionType); 11276 11277 if (Result != MatchesCopy.end()) { 11278 // Make it the first and only element 11279 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 11280 Matches[0].second = cast<FunctionDecl>(*Result); 11281 Matches.resize(1); 11282 } else 11283 HasComplained |= Complain; 11284 } 11285 11286 void EliminateAllTemplateMatches() { 11287 // [...] any function template specializations in the set are 11288 // eliminated if the set also contains a non-template function, [...] 11289 for (unsigned I = 0, N = Matches.size(); I != N; ) { 11290 if (Matches[I].second->getPrimaryTemplate() == nullptr) 11291 ++I; 11292 else { 11293 Matches[I] = Matches[--N]; 11294 Matches.resize(N); 11295 } 11296 } 11297 } 11298 11299 void EliminateSuboptimalCudaMatches() { 11300 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 11301 } 11302 11303 public: 11304 void ComplainNoMatchesFound() const { 11305 assert(Matches.empty()); 11306 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable) 11307 << OvlExpr->getName() << TargetFunctionType 11308 << OvlExpr->getSourceRange(); 11309 if (FailedCandidates.empty()) 11310 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11311 /*TakingAddress=*/true); 11312 else { 11313 // We have some deduction failure messages. Use them to diagnose 11314 // the function templates, and diagnose the non-template candidates 11315 // normally. 11316 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 11317 IEnd = OvlExpr->decls_end(); 11318 I != IEnd; ++I) 11319 if (FunctionDecl *Fun = 11320 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 11321 if (!functionHasPassObjectSizeParams(Fun)) 11322 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType, 11323 /*TakingAddress=*/true); 11324 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc()); 11325 } 11326 } 11327 11328 bool IsInvalidFormOfPointerToMemberFunction() const { 11329 return TargetTypeIsNonStaticMemberFunction && 11330 !OvlExprInfo.HasFormOfMemberPointer; 11331 } 11332 11333 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 11334 // TODO: Should we condition this on whether any functions might 11335 // have matched, or is it more appropriate to do that in callers? 11336 // TODO: a fixit wouldn't hurt. 11337 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 11338 << TargetType << OvlExpr->getSourceRange(); 11339 } 11340 11341 bool IsStaticMemberFunctionFromBoundPointer() const { 11342 return StaticMemberFunctionFromBoundPointer; 11343 } 11344 11345 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 11346 S.Diag(OvlExpr->getBeginLoc(), 11347 diag::err_invalid_form_pointer_member_function) 11348 << OvlExpr->getSourceRange(); 11349 } 11350 11351 void ComplainOfInvalidConversion() const { 11352 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref) 11353 << OvlExpr->getName() << TargetType; 11354 } 11355 11356 void ComplainMultipleMatchesFound() const { 11357 assert(Matches.size() > 1); 11358 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous) 11359 << OvlExpr->getName() << OvlExpr->getSourceRange(); 11360 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 11361 /*TakingAddress=*/true); 11362 } 11363 11364 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 11365 11366 int getNumMatches() const { return Matches.size(); } 11367 11368 FunctionDecl* getMatchingFunctionDecl() const { 11369 if (Matches.size() != 1) return nullptr; 11370 return Matches[0].second; 11371 } 11372 11373 const DeclAccessPair* getMatchingFunctionAccessPair() const { 11374 if (Matches.size() != 1) return nullptr; 11375 return &Matches[0].first; 11376 } 11377 }; 11378 } 11379 11380 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 11381 /// an overloaded function (C++ [over.over]), where @p From is an 11382 /// expression with overloaded function type and @p ToType is the type 11383 /// we're trying to resolve to. For example: 11384 /// 11385 /// @code 11386 /// int f(double); 11387 /// int f(int); 11388 /// 11389 /// int (*pfd)(double) = f; // selects f(double) 11390 /// @endcode 11391 /// 11392 /// This routine returns the resulting FunctionDecl if it could be 11393 /// resolved, and NULL otherwise. When @p Complain is true, this 11394 /// routine will emit diagnostics if there is an error. 11395 FunctionDecl * 11396 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 11397 QualType TargetType, 11398 bool Complain, 11399 DeclAccessPair &FoundResult, 11400 bool *pHadMultipleCandidates) { 11401 assert(AddressOfExpr->getType() == Context.OverloadTy); 11402 11403 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 11404 Complain); 11405 int NumMatches = Resolver.getNumMatches(); 11406 FunctionDecl *Fn = nullptr; 11407 bool ShouldComplain = Complain && !Resolver.hasComplained(); 11408 if (NumMatches == 0 && ShouldComplain) { 11409 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 11410 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 11411 else 11412 Resolver.ComplainNoMatchesFound(); 11413 } 11414 else if (NumMatches > 1 && ShouldComplain) 11415 Resolver.ComplainMultipleMatchesFound(); 11416 else if (NumMatches == 1) { 11417 Fn = Resolver.getMatchingFunctionDecl(); 11418 assert(Fn); 11419 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 11420 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 11421 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 11422 if (Complain) { 11423 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 11424 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 11425 else 11426 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 11427 } 11428 } 11429 11430 if (pHadMultipleCandidates) 11431 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 11432 return Fn; 11433 } 11434 11435 /// Given an expression that refers to an overloaded function, try to 11436 /// resolve that function to a single function that can have its address taken. 11437 /// This will modify `Pair` iff it returns non-null. 11438 /// 11439 /// This routine can only realistically succeed if all but one candidates in the 11440 /// overload set for SrcExpr cannot have their addresses taken. 11441 FunctionDecl * 11442 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 11443 DeclAccessPair &Pair) { 11444 OverloadExpr::FindResult R = OverloadExpr::find(E); 11445 OverloadExpr *Ovl = R.Expression; 11446 FunctionDecl *Result = nullptr; 11447 DeclAccessPair DAP; 11448 // Don't use the AddressOfResolver because we're specifically looking for 11449 // cases where we have one overload candidate that lacks 11450 // enable_if/pass_object_size/... 11451 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 11452 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 11453 if (!FD) 11454 return nullptr; 11455 11456 if (!checkAddressOfFunctionIsAvailable(FD)) 11457 continue; 11458 11459 // We have more than one result; quit. 11460 if (Result) 11461 return nullptr; 11462 DAP = I.getPair(); 11463 Result = FD; 11464 } 11465 11466 if (Result) 11467 Pair = DAP; 11468 return Result; 11469 } 11470 11471 /// Given an overloaded function, tries to turn it into a non-overloaded 11472 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 11473 /// will perform access checks, diagnose the use of the resultant decl, and, if 11474 /// requested, potentially perform a function-to-pointer decay. 11475 /// 11476 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 11477 /// Otherwise, returns true. This may emit diagnostics and return true. 11478 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 11479 ExprResult &SrcExpr, bool DoFunctionPointerConverion) { 11480 Expr *E = SrcExpr.get(); 11481 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 11482 11483 DeclAccessPair DAP; 11484 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 11485 if (!Found || Found->isCPUDispatchMultiVersion() || 11486 Found->isCPUSpecificMultiVersion()) 11487 return false; 11488 11489 // Emitting multiple diagnostics for a function that is both inaccessible and 11490 // unavailable is consistent with our behavior elsewhere. So, always check 11491 // for both. 11492 DiagnoseUseOfDecl(Found, E->getExprLoc()); 11493 CheckAddressOfMemberAccess(E, DAP); 11494 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 11495 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType()) 11496 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 11497 else 11498 SrcExpr = Fixed; 11499 return true; 11500 } 11501 11502 /// Given an expression that refers to an overloaded function, try to 11503 /// resolve that overloaded function expression down to a single function. 11504 /// 11505 /// This routine can only resolve template-ids that refer to a single function 11506 /// template, where that template-id refers to a single template whose template 11507 /// arguments are either provided by the template-id or have defaults, 11508 /// as described in C++0x [temp.arg.explicit]p3. 11509 /// 11510 /// If no template-ids are found, no diagnostics are emitted and NULL is 11511 /// returned. 11512 FunctionDecl * 11513 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 11514 bool Complain, 11515 DeclAccessPair *FoundResult) { 11516 // C++ [over.over]p1: 11517 // [...] [Note: any redundant set of parentheses surrounding the 11518 // overloaded function name is ignored (5.1). ] 11519 // C++ [over.over]p1: 11520 // [...] The overloaded function name can be preceded by the & 11521 // operator. 11522 11523 // If we didn't actually find any template-ids, we're done. 11524 if (!ovl->hasExplicitTemplateArgs()) 11525 return nullptr; 11526 11527 TemplateArgumentListInfo ExplicitTemplateArgs; 11528 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 11529 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 11530 11531 // Look through all of the overloaded functions, searching for one 11532 // whose type matches exactly. 11533 FunctionDecl *Matched = nullptr; 11534 for (UnresolvedSetIterator I = ovl->decls_begin(), 11535 E = ovl->decls_end(); I != E; ++I) { 11536 // C++0x [temp.arg.explicit]p3: 11537 // [...] In contexts where deduction is done and fails, or in contexts 11538 // where deduction is not done, if a template argument list is 11539 // specified and it, along with any default template arguments, 11540 // identifies a single function template specialization, then the 11541 // template-id is an lvalue for the function template specialization. 11542 FunctionTemplateDecl *FunctionTemplate 11543 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 11544 11545 // C++ [over.over]p2: 11546 // If the name is a function template, template argument deduction is 11547 // done (14.8.2.2), and if the argument deduction succeeds, the 11548 // resulting template argument list is used to generate a single 11549 // function template specialization, which is added to the set of 11550 // overloaded functions considered. 11551 FunctionDecl *Specialization = nullptr; 11552 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11553 if (TemplateDeductionResult Result 11554 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 11555 Specialization, Info, 11556 /*IsAddressOfFunction*/true)) { 11557 // Make a note of the failed deduction for diagnostics. 11558 // TODO: Actually use the failed-deduction info? 11559 FailedCandidates.addCandidate() 11560 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 11561 MakeDeductionFailureInfo(Context, Result, Info)); 11562 continue; 11563 } 11564 11565 assert(Specialization && "no specialization and no error?"); 11566 11567 // Multiple matches; we can't resolve to a single declaration. 11568 if (Matched) { 11569 if (Complain) { 11570 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 11571 << ovl->getName(); 11572 NoteAllOverloadCandidates(ovl); 11573 } 11574 return nullptr; 11575 } 11576 11577 Matched = Specialization; 11578 if (FoundResult) *FoundResult = I.getPair(); 11579 } 11580 11581 if (Matched && 11582 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 11583 return nullptr; 11584 11585 return Matched; 11586 } 11587 11588 // Resolve and fix an overloaded expression that can be resolved 11589 // because it identifies a single function template specialization. 11590 // 11591 // Last three arguments should only be supplied if Complain = true 11592 // 11593 // Return true if it was logically possible to so resolve the 11594 // expression, regardless of whether or not it succeeded. Always 11595 // returns true if 'complain' is set. 11596 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 11597 ExprResult &SrcExpr, bool doFunctionPointerConverion, 11598 bool complain, SourceRange OpRangeForComplaining, 11599 QualType DestTypeForComplaining, 11600 unsigned DiagIDForComplaining) { 11601 assert(SrcExpr.get()->getType() == Context.OverloadTy); 11602 11603 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 11604 11605 DeclAccessPair found; 11606 ExprResult SingleFunctionExpression; 11607 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 11608 ovl.Expression, /*complain*/ false, &found)) { 11609 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) { 11610 SrcExpr = ExprError(); 11611 return true; 11612 } 11613 11614 // It is only correct to resolve to an instance method if we're 11615 // resolving a form that's permitted to be a pointer to member. 11616 // Otherwise we'll end up making a bound member expression, which 11617 // is illegal in all the contexts we resolve like this. 11618 if (!ovl.HasFormOfMemberPointer && 11619 isa<CXXMethodDecl>(fn) && 11620 cast<CXXMethodDecl>(fn)->isInstance()) { 11621 if (!complain) return false; 11622 11623 Diag(ovl.Expression->getExprLoc(), 11624 diag::err_bound_member_function) 11625 << 0 << ovl.Expression->getSourceRange(); 11626 11627 // TODO: I believe we only end up here if there's a mix of 11628 // static and non-static candidates (otherwise the expression 11629 // would have 'bound member' type, not 'overload' type). 11630 // Ideally we would note which candidate was chosen and why 11631 // the static candidates were rejected. 11632 SrcExpr = ExprError(); 11633 return true; 11634 } 11635 11636 // Fix the expression to refer to 'fn'. 11637 SingleFunctionExpression = 11638 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 11639 11640 // If desired, do function-to-pointer decay. 11641 if (doFunctionPointerConverion) { 11642 SingleFunctionExpression = 11643 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 11644 if (SingleFunctionExpression.isInvalid()) { 11645 SrcExpr = ExprError(); 11646 return true; 11647 } 11648 } 11649 } 11650 11651 if (!SingleFunctionExpression.isUsable()) { 11652 if (complain) { 11653 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 11654 << ovl.Expression->getName() 11655 << DestTypeForComplaining 11656 << OpRangeForComplaining 11657 << ovl.Expression->getQualifierLoc().getSourceRange(); 11658 NoteAllOverloadCandidates(SrcExpr.get()); 11659 11660 SrcExpr = ExprError(); 11661 return true; 11662 } 11663 11664 return false; 11665 } 11666 11667 SrcExpr = SingleFunctionExpression; 11668 return true; 11669 } 11670 11671 /// Add a single candidate to the overload set. 11672 static void AddOverloadedCallCandidate(Sema &S, 11673 DeclAccessPair FoundDecl, 11674 TemplateArgumentListInfo *ExplicitTemplateArgs, 11675 ArrayRef<Expr *> Args, 11676 OverloadCandidateSet &CandidateSet, 11677 bool PartialOverloading, 11678 bool KnownValid) { 11679 NamedDecl *Callee = FoundDecl.getDecl(); 11680 if (isa<UsingShadowDecl>(Callee)) 11681 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 11682 11683 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 11684 if (ExplicitTemplateArgs) { 11685 assert(!KnownValid && "Explicit template arguments?"); 11686 return; 11687 } 11688 // Prevent ill-formed function decls to be added as overload candidates. 11689 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>())) 11690 return; 11691 11692 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 11693 /*SuppressUsedConversions=*/false, 11694 PartialOverloading); 11695 return; 11696 } 11697 11698 if (FunctionTemplateDecl *FuncTemplate 11699 = dyn_cast<FunctionTemplateDecl>(Callee)) { 11700 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 11701 ExplicitTemplateArgs, Args, CandidateSet, 11702 /*SuppressUsedConversions=*/false, 11703 PartialOverloading); 11704 return; 11705 } 11706 11707 assert(!KnownValid && "unhandled case in overloaded call candidate"); 11708 } 11709 11710 /// Add the overload candidates named by callee and/or found by argument 11711 /// dependent lookup to the given overload set. 11712 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 11713 ArrayRef<Expr *> Args, 11714 OverloadCandidateSet &CandidateSet, 11715 bool PartialOverloading) { 11716 11717 #ifndef NDEBUG 11718 // Verify that ArgumentDependentLookup is consistent with the rules 11719 // in C++0x [basic.lookup.argdep]p3: 11720 // 11721 // Let X be the lookup set produced by unqualified lookup (3.4.1) 11722 // and let Y be the lookup set produced by argument dependent 11723 // lookup (defined as follows). If X contains 11724 // 11725 // -- a declaration of a class member, or 11726 // 11727 // -- a block-scope function declaration that is not a 11728 // using-declaration, or 11729 // 11730 // -- a declaration that is neither a function or a function 11731 // template 11732 // 11733 // then Y is empty. 11734 11735 if (ULE->requiresADL()) { 11736 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11737 E = ULE->decls_end(); I != E; ++I) { 11738 assert(!(*I)->getDeclContext()->isRecord()); 11739 assert(isa<UsingShadowDecl>(*I) || 11740 !(*I)->getDeclContext()->isFunctionOrMethod()); 11741 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 11742 } 11743 } 11744 #endif 11745 11746 // It would be nice to avoid this copy. 11747 TemplateArgumentListInfo TABuffer; 11748 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11749 if (ULE->hasExplicitTemplateArgs()) { 11750 ULE->copyTemplateArgumentsInto(TABuffer); 11751 ExplicitTemplateArgs = &TABuffer; 11752 } 11753 11754 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11755 E = ULE->decls_end(); I != E; ++I) 11756 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 11757 CandidateSet, PartialOverloading, 11758 /*KnownValid*/ true); 11759 11760 if (ULE->requiresADL()) 11761 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 11762 Args, ExplicitTemplateArgs, 11763 CandidateSet, PartialOverloading); 11764 } 11765 11766 /// Determine whether a declaration with the specified name could be moved into 11767 /// a different namespace. 11768 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 11769 switch (Name.getCXXOverloadedOperator()) { 11770 case OO_New: case OO_Array_New: 11771 case OO_Delete: case OO_Array_Delete: 11772 return false; 11773 11774 default: 11775 return true; 11776 } 11777 } 11778 11779 /// Attempt to recover from an ill-formed use of a non-dependent name in a 11780 /// template, where the non-dependent name was declared after the template 11781 /// was defined. This is common in code written for a compilers which do not 11782 /// correctly implement two-stage name lookup. 11783 /// 11784 /// Returns true if a viable candidate was found and a diagnostic was issued. 11785 static bool 11786 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 11787 const CXXScopeSpec &SS, LookupResult &R, 11788 OverloadCandidateSet::CandidateSetKind CSK, 11789 TemplateArgumentListInfo *ExplicitTemplateArgs, 11790 ArrayRef<Expr *> Args, 11791 bool *DoDiagnoseEmptyLookup = nullptr) { 11792 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty()) 11793 return false; 11794 11795 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 11796 if (DC->isTransparentContext()) 11797 continue; 11798 11799 SemaRef.LookupQualifiedName(R, DC); 11800 11801 if (!R.empty()) { 11802 R.suppressDiagnostics(); 11803 11804 if (isa<CXXRecordDecl>(DC)) { 11805 // Don't diagnose names we find in classes; we get much better 11806 // diagnostics for these from DiagnoseEmptyLookup. 11807 R.clear(); 11808 if (DoDiagnoseEmptyLookup) 11809 *DoDiagnoseEmptyLookup = true; 11810 return false; 11811 } 11812 11813 OverloadCandidateSet Candidates(FnLoc, CSK); 11814 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11815 AddOverloadedCallCandidate(SemaRef, I.getPair(), 11816 ExplicitTemplateArgs, Args, 11817 Candidates, false, /*KnownValid*/ false); 11818 11819 OverloadCandidateSet::iterator Best; 11820 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 11821 // No viable functions. Don't bother the user with notes for functions 11822 // which don't work and shouldn't be found anyway. 11823 R.clear(); 11824 return false; 11825 } 11826 11827 // Find the namespaces where ADL would have looked, and suggest 11828 // declaring the function there instead. 11829 Sema::AssociatedNamespaceSet AssociatedNamespaces; 11830 Sema::AssociatedClassSet AssociatedClasses; 11831 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 11832 AssociatedNamespaces, 11833 AssociatedClasses); 11834 Sema::AssociatedNamespaceSet SuggestedNamespaces; 11835 if (canBeDeclaredInNamespace(R.getLookupName())) { 11836 DeclContext *Std = SemaRef.getStdNamespace(); 11837 for (Sema::AssociatedNamespaceSet::iterator 11838 it = AssociatedNamespaces.begin(), 11839 end = AssociatedNamespaces.end(); it != end; ++it) { 11840 // Never suggest declaring a function within namespace 'std'. 11841 if (Std && Std->Encloses(*it)) 11842 continue; 11843 11844 // Never suggest declaring a function within a namespace with a 11845 // reserved name, like __gnu_cxx. 11846 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 11847 if (NS && 11848 NS->getQualifiedNameAsString().find("__") != std::string::npos) 11849 continue; 11850 11851 SuggestedNamespaces.insert(*it); 11852 } 11853 } 11854 11855 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 11856 << R.getLookupName(); 11857 if (SuggestedNamespaces.empty()) { 11858 SemaRef.Diag(Best->Function->getLocation(), 11859 diag::note_not_found_by_two_phase_lookup) 11860 << R.getLookupName() << 0; 11861 } else if (SuggestedNamespaces.size() == 1) { 11862 SemaRef.Diag(Best->Function->getLocation(), 11863 diag::note_not_found_by_two_phase_lookup) 11864 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11865 } else { 11866 // FIXME: It would be useful to list the associated namespaces here, 11867 // but the diagnostics infrastructure doesn't provide a way to produce 11868 // a localized representation of a list of items. 11869 SemaRef.Diag(Best->Function->getLocation(), 11870 diag::note_not_found_by_two_phase_lookup) 11871 << R.getLookupName() << 2; 11872 } 11873 11874 // Try to recover by calling this function. 11875 return true; 11876 } 11877 11878 R.clear(); 11879 } 11880 11881 return false; 11882 } 11883 11884 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11885 /// template, where the non-dependent operator was declared after the template 11886 /// was defined. 11887 /// 11888 /// Returns true if a viable candidate was found and a diagnostic was issued. 11889 static bool 11890 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11891 SourceLocation OpLoc, 11892 ArrayRef<Expr *> Args) { 11893 DeclarationName OpName = 11894 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11895 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11896 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11897 OverloadCandidateSet::CSK_Operator, 11898 /*ExplicitTemplateArgs=*/nullptr, Args); 11899 } 11900 11901 namespace { 11902 class BuildRecoveryCallExprRAII { 11903 Sema &SemaRef; 11904 public: 11905 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11906 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11907 SemaRef.IsBuildingRecoveryCallExpr = true; 11908 } 11909 11910 ~BuildRecoveryCallExprRAII() { 11911 SemaRef.IsBuildingRecoveryCallExpr = false; 11912 } 11913 }; 11914 11915 } 11916 11917 static std::unique_ptr<CorrectionCandidateCallback> 11918 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 11919 bool HasTemplateArgs, bool AllowTypoCorrection) { 11920 if (!AllowTypoCorrection) 11921 return llvm::make_unique<NoTypoCorrectionCCC>(); 11922 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 11923 HasTemplateArgs, ME); 11924 } 11925 11926 /// Attempts to recover from a call where no functions were found. 11927 /// 11928 /// Returns true if new candidates were found. 11929 static ExprResult 11930 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11931 UnresolvedLookupExpr *ULE, 11932 SourceLocation LParenLoc, 11933 MutableArrayRef<Expr *> Args, 11934 SourceLocation RParenLoc, 11935 bool EmptyLookup, bool AllowTypoCorrection) { 11936 // Do not try to recover if it is already building a recovery call. 11937 // This stops infinite loops for template instantiations like 11938 // 11939 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 11940 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 11941 // 11942 if (SemaRef.IsBuildingRecoveryCallExpr) 11943 return ExprError(); 11944 BuildRecoveryCallExprRAII RCE(SemaRef); 11945 11946 CXXScopeSpec SS; 11947 SS.Adopt(ULE->getQualifierLoc()); 11948 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11949 11950 TemplateArgumentListInfo TABuffer; 11951 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11952 if (ULE->hasExplicitTemplateArgs()) { 11953 ULE->copyTemplateArgumentsInto(TABuffer); 11954 ExplicitTemplateArgs = &TABuffer; 11955 } 11956 11957 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 11958 Sema::LookupOrdinaryName); 11959 bool DoDiagnoseEmptyLookup = EmptyLookup; 11960 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 11961 OverloadCandidateSet::CSK_Normal, 11962 ExplicitTemplateArgs, Args, 11963 &DoDiagnoseEmptyLookup) && 11964 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 11965 S, SS, R, 11966 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 11967 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 11968 ExplicitTemplateArgs, Args))) 11969 return ExprError(); 11970 11971 assert(!R.empty() && "lookup results empty despite recovery"); 11972 11973 // If recovery created an ambiguity, just bail out. 11974 if (R.isAmbiguous()) { 11975 R.suppressDiagnostics(); 11976 return ExprError(); 11977 } 11978 11979 // Build an implicit member call if appropriate. Just drop the 11980 // casts and such from the call, we don't really care. 11981 ExprResult NewFn = ExprError(); 11982 if ((*R.begin())->isCXXClassMember()) 11983 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 11984 ExplicitTemplateArgs, S); 11985 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 11986 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 11987 ExplicitTemplateArgs); 11988 else 11989 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 11990 11991 if (NewFn.isInvalid()) 11992 return ExprError(); 11993 11994 // This shouldn't cause an infinite loop because we're giving it 11995 // an expression with viable lookup results, which should never 11996 // end up here. 11997 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 11998 MultiExprArg(Args.data(), Args.size()), 11999 RParenLoc); 12000 } 12001 12002 /// Constructs and populates an OverloadedCandidateSet from 12003 /// the given function. 12004 /// \returns true when an the ExprResult output parameter has been set. 12005 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 12006 UnresolvedLookupExpr *ULE, 12007 MultiExprArg Args, 12008 SourceLocation RParenLoc, 12009 OverloadCandidateSet *CandidateSet, 12010 ExprResult *Result) { 12011 #ifndef NDEBUG 12012 if (ULE->requiresADL()) { 12013 // To do ADL, we must have found an unqualified name. 12014 assert(!ULE->getQualifier() && "qualified name with ADL"); 12015 12016 // We don't perform ADL for implicit declarations of builtins. 12017 // Verify that this was correctly set up. 12018 FunctionDecl *F; 12019 if (ULE->decls_begin() + 1 == ULE->decls_end() && 12020 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 12021 F->getBuiltinID() && F->isImplicit()) 12022 llvm_unreachable("performing ADL for builtin"); 12023 12024 // We don't perform ADL in C. 12025 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 12026 } 12027 #endif 12028 12029 UnbridgedCastsSet UnbridgedCasts; 12030 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 12031 *Result = ExprError(); 12032 return true; 12033 } 12034 12035 // Add the functions denoted by the callee to the set of candidate 12036 // functions, including those from argument-dependent lookup. 12037 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 12038 12039 if (getLangOpts().MSVCCompat && 12040 CurContext->isDependentContext() && !isSFINAEContext() && 12041 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 12042 12043 OverloadCandidateSet::iterator Best; 12044 if (CandidateSet->empty() || 12045 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) == 12046 OR_No_Viable_Function) { 12047 // In Microsoft mode, if we are inside a template class member function 12048 // then create a type dependent CallExpr. The goal is to postpone name 12049 // lookup to instantiation time to be able to search into type dependent 12050 // base classes. 12051 CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy, 12052 VK_RValue, RParenLoc); 12053 CE->setTypeDependent(true); 12054 CE->setValueDependent(true); 12055 CE->setInstantiationDependent(true); 12056 *Result = CE; 12057 return true; 12058 } 12059 } 12060 12061 if (CandidateSet->empty()) 12062 return false; 12063 12064 UnbridgedCasts.restore(); 12065 return false; 12066 } 12067 12068 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 12069 /// the completed call expression. If overload resolution fails, emits 12070 /// diagnostics and returns ExprError() 12071 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 12072 UnresolvedLookupExpr *ULE, 12073 SourceLocation LParenLoc, 12074 MultiExprArg Args, 12075 SourceLocation RParenLoc, 12076 Expr *ExecConfig, 12077 OverloadCandidateSet *CandidateSet, 12078 OverloadCandidateSet::iterator *Best, 12079 OverloadingResult OverloadResult, 12080 bool AllowTypoCorrection) { 12081 if (CandidateSet->empty()) 12082 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 12083 RParenLoc, /*EmptyLookup=*/true, 12084 AllowTypoCorrection); 12085 12086 switch (OverloadResult) { 12087 case OR_Success: { 12088 FunctionDecl *FDecl = (*Best)->Function; 12089 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 12090 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 12091 return ExprError(); 12092 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12093 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12094 ExecConfig, /*IsExecConfig=*/false, 12095 (*Best)->IsADLCandidate); 12096 } 12097 12098 case OR_No_Viable_Function: { 12099 // Try to recover by looking for viable functions which the user might 12100 // have meant to call. 12101 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 12102 Args, RParenLoc, 12103 /*EmptyLookup=*/false, 12104 AllowTypoCorrection); 12105 if (!Recovery.isInvalid()) 12106 return Recovery; 12107 12108 // If the user passes in a function that we can't take the address of, we 12109 // generally end up emitting really bad error messages. Here, we attempt to 12110 // emit better ones. 12111 for (const Expr *Arg : Args) { 12112 if (!Arg->getType()->isFunctionType()) 12113 continue; 12114 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 12115 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 12116 if (FD && 12117 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 12118 Arg->getExprLoc())) 12119 return ExprError(); 12120 } 12121 } 12122 12123 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_no_viable_function_in_call) 12124 << ULE->getName() << Fn->getSourceRange(); 12125 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 12126 break; 12127 } 12128 12129 case OR_Ambiguous: 12130 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_ambiguous_call) 12131 << ULE->getName() << Fn->getSourceRange(); 12132 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 12133 break; 12134 12135 case OR_Deleted: { 12136 SemaRef.Diag(Fn->getBeginLoc(), diag::err_ovl_deleted_call) 12137 << (*Best)->Function->isDeleted() << ULE->getName() 12138 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 12139 << Fn->getSourceRange(); 12140 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 12141 12142 // We emitted an error for the unavailable/deleted function call but keep 12143 // the call in the AST. 12144 FunctionDecl *FDecl = (*Best)->Function; 12145 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 12146 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 12147 ExecConfig, /*IsExecConfig=*/false, 12148 (*Best)->IsADLCandidate); 12149 } 12150 } 12151 12152 // Overload resolution failed. 12153 return ExprError(); 12154 } 12155 12156 static void markUnaddressableCandidatesUnviable(Sema &S, 12157 OverloadCandidateSet &CS) { 12158 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 12159 if (I->Viable && 12160 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 12161 I->Viable = false; 12162 I->FailureKind = ovl_fail_addr_not_available; 12163 } 12164 } 12165 } 12166 12167 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 12168 /// (which eventually refers to the declaration Func) and the call 12169 /// arguments Args/NumArgs, attempt to resolve the function call down 12170 /// to a specific function. If overload resolution succeeds, returns 12171 /// the call expression produced by overload resolution. 12172 /// Otherwise, emits diagnostics and returns ExprError. 12173 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 12174 UnresolvedLookupExpr *ULE, 12175 SourceLocation LParenLoc, 12176 MultiExprArg Args, 12177 SourceLocation RParenLoc, 12178 Expr *ExecConfig, 12179 bool AllowTypoCorrection, 12180 bool CalleesAddressIsTaken) { 12181 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 12182 OverloadCandidateSet::CSK_Normal); 12183 ExprResult result; 12184 12185 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 12186 &result)) 12187 return result; 12188 12189 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 12190 // functions that aren't addressible are considered unviable. 12191 if (CalleesAddressIsTaken) 12192 markUnaddressableCandidatesUnviable(*this, CandidateSet); 12193 12194 OverloadCandidateSet::iterator Best; 12195 OverloadingResult OverloadResult = 12196 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best); 12197 12198 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 12199 RParenLoc, ExecConfig, &CandidateSet, 12200 &Best, OverloadResult, 12201 AllowTypoCorrection); 12202 } 12203 12204 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 12205 return Functions.size() > 1 || 12206 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 12207 } 12208 12209 /// Create a unary operation that may resolve to an overloaded 12210 /// operator. 12211 /// 12212 /// \param OpLoc The location of the operator itself (e.g., '*'). 12213 /// 12214 /// \param Opc The UnaryOperatorKind that describes this operator. 12215 /// 12216 /// \param Fns The set of non-member functions that will be 12217 /// considered by overload resolution. The caller needs to build this 12218 /// set based on the context using, e.g., 12219 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12220 /// set should not contain any member functions; those will be added 12221 /// by CreateOverloadedUnaryOp(). 12222 /// 12223 /// \param Input The input argument. 12224 ExprResult 12225 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 12226 const UnresolvedSetImpl &Fns, 12227 Expr *Input, bool PerformADL) { 12228 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 12229 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 12230 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12231 // TODO: provide better source location info. 12232 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12233 12234 if (checkPlaceholderForOverload(*this, Input)) 12235 return ExprError(); 12236 12237 Expr *Args[2] = { Input, nullptr }; 12238 unsigned NumArgs = 1; 12239 12240 // For post-increment and post-decrement, add the implicit '0' as 12241 // the second argument, so that we know this is a post-increment or 12242 // post-decrement. 12243 if (Opc == UO_PostInc || Opc == UO_PostDec) { 12244 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 12245 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 12246 SourceLocation()); 12247 NumArgs = 2; 12248 } 12249 12250 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 12251 12252 if (Input->isTypeDependent()) { 12253 if (Fns.empty()) 12254 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 12255 VK_RValue, OK_Ordinary, OpLoc, false); 12256 12257 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12258 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 12259 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 12260 /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end()); 12261 return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray, 12262 Context.DependentTy, VK_RValue, OpLoc, 12263 FPOptions()); 12264 } 12265 12266 // Build an empty overload set. 12267 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12268 12269 // Add the candidates from the given function set. 12270 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 12271 12272 // Add operator candidates that are member functions. 12273 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12274 12275 // Add candidates from ADL. 12276 if (PerformADL) { 12277 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 12278 /*ExplicitTemplateArgs*/nullptr, 12279 CandidateSet); 12280 } 12281 12282 // Add builtin operator candidates. 12283 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 12284 12285 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12286 12287 // Perform overload resolution. 12288 OverloadCandidateSet::iterator Best; 12289 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12290 case OR_Success: { 12291 // We found a built-in operator or an overloaded operator. 12292 FunctionDecl *FnDecl = Best->Function; 12293 12294 if (FnDecl) { 12295 Expr *Base = nullptr; 12296 // We matched an overloaded operator. Build a call to that 12297 // operator. 12298 12299 // Convert the arguments. 12300 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12301 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 12302 12303 ExprResult InputRes = 12304 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 12305 Best->FoundDecl, Method); 12306 if (InputRes.isInvalid()) 12307 return ExprError(); 12308 Base = Input = InputRes.get(); 12309 } else { 12310 // Convert the arguments. 12311 ExprResult InputInit 12312 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12313 Context, 12314 FnDecl->getParamDecl(0)), 12315 SourceLocation(), 12316 Input); 12317 if (InputInit.isInvalid()) 12318 return ExprError(); 12319 Input = InputInit.get(); 12320 } 12321 12322 // Build the actual expression node. 12323 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 12324 Base, HadMultipleCandidates, 12325 OpLoc); 12326 if (FnExpr.isInvalid()) 12327 return ExprError(); 12328 12329 // Determine the result type. 12330 QualType ResultTy = FnDecl->getReturnType(); 12331 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12332 ResultTy = ResultTy.getNonLValueExprType(Context); 12333 12334 Args[0] = Input; 12335 CallExpr *TheCall = CXXOperatorCallExpr::Create( 12336 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc, 12337 FPOptions(), Best->IsADLCandidate); 12338 12339 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 12340 return ExprError(); 12341 12342 if (CheckFunctionCall(FnDecl, TheCall, 12343 FnDecl->getType()->castAs<FunctionProtoType>())) 12344 return ExprError(); 12345 12346 return MaybeBindToTemporary(TheCall); 12347 } else { 12348 // We matched a built-in operator. Convert the arguments, then 12349 // break out so that we will build the appropriate built-in 12350 // operator node. 12351 ExprResult InputRes = PerformImplicitConversion( 12352 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing, 12353 CCK_ForBuiltinOverloadedOp); 12354 if (InputRes.isInvalid()) 12355 return ExprError(); 12356 Input = InputRes.get(); 12357 break; 12358 } 12359 } 12360 12361 case OR_No_Viable_Function: 12362 // This is an erroneous use of an operator which can be overloaded by 12363 // a non-member function. Check for non-member operators which were 12364 // defined too late to be candidates. 12365 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 12366 // FIXME: Recover by calling the found function. 12367 return ExprError(); 12368 12369 // No viable function; fall through to handling this as a 12370 // built-in operator, which will produce an error message for us. 12371 break; 12372 12373 case OR_Ambiguous: 12374 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12375 << UnaryOperator::getOpcodeStr(Opc) 12376 << Input->getType() 12377 << Input->getSourceRange(); 12378 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 12379 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12380 return ExprError(); 12381 12382 case OR_Deleted: 12383 Diag(OpLoc, diag::err_ovl_deleted_oper) 12384 << Best->Function->isDeleted() 12385 << UnaryOperator::getOpcodeStr(Opc) 12386 << getDeletedOrUnavailableSuffix(Best->Function) 12387 << Input->getSourceRange(); 12388 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 12389 UnaryOperator::getOpcodeStr(Opc), OpLoc); 12390 return ExprError(); 12391 } 12392 12393 // Either we found no viable overloaded operator or we matched a 12394 // built-in operator. In either case, fall through to trying to 12395 // build a built-in operation. 12396 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 12397 } 12398 12399 /// Create a binary operation that may resolve to an overloaded 12400 /// operator. 12401 /// 12402 /// \param OpLoc The location of the operator itself (e.g., '+'). 12403 /// 12404 /// \param Opc The BinaryOperatorKind that describes this operator. 12405 /// 12406 /// \param Fns The set of non-member functions that will be 12407 /// considered by overload resolution. The caller needs to build this 12408 /// set based on the context using, e.g., 12409 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 12410 /// set should not contain any member functions; those will be added 12411 /// by CreateOverloadedBinOp(). 12412 /// 12413 /// \param LHS Left-hand argument. 12414 /// \param RHS Right-hand argument. 12415 ExprResult 12416 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 12417 BinaryOperatorKind Opc, 12418 const UnresolvedSetImpl &Fns, 12419 Expr *LHS, Expr *RHS, bool PerformADL) { 12420 Expr *Args[2] = { LHS, RHS }; 12421 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 12422 12423 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 12424 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 12425 12426 // If either side is type-dependent, create an appropriate dependent 12427 // expression. 12428 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12429 if (Fns.empty()) { 12430 // If there are no functions to store, just build a dependent 12431 // BinaryOperator or CompoundAssignment. 12432 if (Opc <= BO_Assign || Opc > BO_OrAssign) 12433 return new (Context) BinaryOperator( 12434 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 12435 OpLoc, FPFeatures); 12436 12437 return new (Context) CompoundAssignOperator( 12438 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 12439 Context.DependentTy, Context.DependentTy, OpLoc, 12440 FPFeatures); 12441 } 12442 12443 // FIXME: save results of ADL from here? 12444 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12445 // TODO: provide better source location info in DNLoc component. 12446 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 12447 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create( 12448 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo, 12449 /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end()); 12450 return CXXOperatorCallExpr::Create(Context, Op, Fn, Args, 12451 Context.DependentTy, VK_RValue, OpLoc, 12452 FPFeatures); 12453 } 12454 12455 // Always do placeholder-like conversions on the RHS. 12456 if (checkPlaceholderForOverload(*this, Args[1])) 12457 return ExprError(); 12458 12459 // Do placeholder-like conversion on the LHS; note that we should 12460 // not get here with a PseudoObject LHS. 12461 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 12462 if (checkPlaceholderForOverload(*this, Args[0])) 12463 return ExprError(); 12464 12465 // If this is the assignment operator, we only perform overload resolution 12466 // if the left-hand side is a class or enumeration type. This is actually 12467 // a hack. The standard requires that we do overload resolution between the 12468 // various built-in candidates, but as DR507 points out, this can lead to 12469 // problems. So we do it this way, which pretty much follows what GCC does. 12470 // Note that we go the traditional code path for compound assignment forms. 12471 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 12472 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12473 12474 // If this is the .* operator, which is not overloadable, just 12475 // create a built-in binary operator. 12476 if (Opc == BO_PtrMemD) 12477 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12478 12479 // Build an empty overload set. 12480 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 12481 12482 // Add the candidates from the given function set. 12483 AddFunctionCandidates(Fns, Args, CandidateSet); 12484 12485 // Add operator candidates that are member functions. 12486 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12487 12488 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 12489 // performed for an assignment operator (nor for operator[] nor operator->, 12490 // which don't get here). 12491 if (Opc != BO_Assign && PerformADL) 12492 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 12493 /*ExplicitTemplateArgs*/ nullptr, 12494 CandidateSet); 12495 12496 // Add builtin operator candidates. 12497 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 12498 12499 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12500 12501 // Perform overload resolution. 12502 OverloadCandidateSet::iterator Best; 12503 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12504 case OR_Success: { 12505 // We found a built-in operator or an overloaded operator. 12506 FunctionDecl *FnDecl = Best->Function; 12507 12508 if (FnDecl) { 12509 Expr *Base = nullptr; 12510 // We matched an overloaded operator. Build a call to that 12511 // operator. 12512 12513 // Convert the arguments. 12514 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 12515 // Best->Access is only meaningful for class members. 12516 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 12517 12518 ExprResult Arg1 = 12519 PerformCopyInitialization( 12520 InitializedEntity::InitializeParameter(Context, 12521 FnDecl->getParamDecl(0)), 12522 SourceLocation(), Args[1]); 12523 if (Arg1.isInvalid()) 12524 return ExprError(); 12525 12526 ExprResult Arg0 = 12527 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12528 Best->FoundDecl, Method); 12529 if (Arg0.isInvalid()) 12530 return ExprError(); 12531 Base = Args[0] = Arg0.getAs<Expr>(); 12532 Args[1] = RHS = Arg1.getAs<Expr>(); 12533 } else { 12534 // Convert the arguments. 12535 ExprResult Arg0 = PerformCopyInitialization( 12536 InitializedEntity::InitializeParameter(Context, 12537 FnDecl->getParamDecl(0)), 12538 SourceLocation(), Args[0]); 12539 if (Arg0.isInvalid()) 12540 return ExprError(); 12541 12542 ExprResult Arg1 = 12543 PerformCopyInitialization( 12544 InitializedEntity::InitializeParameter(Context, 12545 FnDecl->getParamDecl(1)), 12546 SourceLocation(), Args[1]); 12547 if (Arg1.isInvalid()) 12548 return ExprError(); 12549 Args[0] = LHS = Arg0.getAs<Expr>(); 12550 Args[1] = RHS = Arg1.getAs<Expr>(); 12551 } 12552 12553 // Build the actual expression node. 12554 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12555 Best->FoundDecl, Base, 12556 HadMultipleCandidates, OpLoc); 12557 if (FnExpr.isInvalid()) 12558 return ExprError(); 12559 12560 // Determine the result type. 12561 QualType ResultTy = FnDecl->getReturnType(); 12562 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12563 ResultTy = ResultTy.getNonLValueExprType(Context); 12564 12565 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 12566 Context, Op, FnExpr.get(), Args, ResultTy, VK, OpLoc, FPFeatures, 12567 Best->IsADLCandidate); 12568 12569 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 12570 FnDecl)) 12571 return ExprError(); 12572 12573 ArrayRef<const Expr *> ArgsArray(Args, 2); 12574 const Expr *ImplicitThis = nullptr; 12575 // Cut off the implicit 'this'. 12576 if (isa<CXXMethodDecl>(FnDecl)) { 12577 ImplicitThis = ArgsArray[0]; 12578 ArgsArray = ArgsArray.slice(1); 12579 } 12580 12581 // Check for a self move. 12582 if (Op == OO_Equal) 12583 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 12584 12585 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray, 12586 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(), 12587 VariadicDoesNotApply); 12588 12589 return MaybeBindToTemporary(TheCall); 12590 } else { 12591 // We matched a built-in operator. Convert the arguments, then 12592 // break out so that we will build the appropriate built-in 12593 // operator node. 12594 ExprResult ArgsRes0 = PerformImplicitConversion( 12595 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 12596 AA_Passing, CCK_ForBuiltinOverloadedOp); 12597 if (ArgsRes0.isInvalid()) 12598 return ExprError(); 12599 Args[0] = ArgsRes0.get(); 12600 12601 ExprResult ArgsRes1 = PerformImplicitConversion( 12602 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 12603 AA_Passing, CCK_ForBuiltinOverloadedOp); 12604 if (ArgsRes1.isInvalid()) 12605 return ExprError(); 12606 Args[1] = ArgsRes1.get(); 12607 break; 12608 } 12609 } 12610 12611 case OR_No_Viable_Function: { 12612 // C++ [over.match.oper]p9: 12613 // If the operator is the operator , [...] and there are no 12614 // viable functions, then the operator is assumed to be the 12615 // built-in operator and interpreted according to clause 5. 12616 if (Opc == BO_Comma) 12617 break; 12618 12619 // For class as left operand for assignment or compound assignment 12620 // operator do not fall through to handling in built-in, but report that 12621 // no overloaded assignment operator found 12622 ExprResult Result = ExprError(); 12623 if (Args[0]->getType()->isRecordType() && 12624 Opc >= BO_Assign && Opc <= BO_OrAssign) { 12625 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12626 << BinaryOperator::getOpcodeStr(Opc) 12627 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12628 if (Args[0]->getType()->isIncompleteType()) { 12629 Diag(OpLoc, diag::note_assign_lhs_incomplete) 12630 << Args[0]->getType() 12631 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12632 } 12633 } else { 12634 // This is an erroneous use of an operator which can be overloaded by 12635 // a non-member function. Check for non-member operators which were 12636 // defined too late to be candidates. 12637 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 12638 // FIXME: Recover by calling the found function. 12639 return ExprError(); 12640 12641 // No viable function; try to create a built-in operation, which will 12642 // produce an error. Then, show the non-viable candidates. 12643 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12644 } 12645 assert(Result.isInvalid() && 12646 "C++ binary operator overloading is missing candidates!"); 12647 if (Result.isInvalid()) 12648 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12649 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12650 return Result; 12651 } 12652 12653 case OR_Ambiguous: 12654 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 12655 << BinaryOperator::getOpcodeStr(Opc) 12656 << Args[0]->getType() << Args[1]->getType() 12657 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12658 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12659 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12660 return ExprError(); 12661 12662 case OR_Deleted: 12663 if (isImplicitlyDeleted(Best->Function)) { 12664 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12665 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 12666 << Context.getRecordType(Method->getParent()) 12667 << getSpecialMember(Method); 12668 12669 // The user probably meant to call this special member. Just 12670 // explain why it's deleted. 12671 NoteDeletedFunction(Method); 12672 return ExprError(); 12673 } else { 12674 Diag(OpLoc, diag::err_ovl_deleted_oper) 12675 << Best->Function->isDeleted() 12676 << BinaryOperator::getOpcodeStr(Opc) 12677 << getDeletedOrUnavailableSuffix(Best->Function) 12678 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12679 } 12680 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12681 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12682 return ExprError(); 12683 } 12684 12685 // We matched a built-in operator; build it. 12686 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12687 } 12688 12689 ExprResult 12690 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 12691 SourceLocation RLoc, 12692 Expr *Base, Expr *Idx) { 12693 Expr *Args[2] = { Base, Idx }; 12694 DeclarationName OpName = 12695 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 12696 12697 // If either side is type-dependent, create an appropriate dependent 12698 // expression. 12699 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12700 12701 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12702 // CHECKME: no 'operator' keyword? 12703 DeclarationNameInfo OpNameInfo(OpName, LLoc); 12704 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12705 UnresolvedLookupExpr *Fn 12706 = UnresolvedLookupExpr::Create(Context, NamingClass, 12707 NestedNameSpecifierLoc(), OpNameInfo, 12708 /*ADL*/ true, /*Overloaded*/ false, 12709 UnresolvedSetIterator(), 12710 UnresolvedSetIterator()); 12711 // Can't add any actual overloads yet 12712 12713 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args, 12714 Context.DependentTy, VK_RValue, RLoc, 12715 FPOptions()); 12716 } 12717 12718 // Handle placeholders on both operands. 12719 if (checkPlaceholderForOverload(*this, Args[0])) 12720 return ExprError(); 12721 if (checkPlaceholderForOverload(*this, Args[1])) 12722 return ExprError(); 12723 12724 // Build an empty overload set. 12725 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 12726 12727 // Subscript can only be overloaded as a member function. 12728 12729 // Add operator candidates that are member functions. 12730 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12731 12732 // Add builtin operator candidates. 12733 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12734 12735 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12736 12737 // Perform overload resolution. 12738 OverloadCandidateSet::iterator Best; 12739 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 12740 case OR_Success: { 12741 // We found a built-in operator or an overloaded operator. 12742 FunctionDecl *FnDecl = Best->Function; 12743 12744 if (FnDecl) { 12745 // We matched an overloaded operator. Build a call to that 12746 // operator. 12747 12748 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 12749 12750 // Convert the arguments. 12751 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 12752 ExprResult Arg0 = 12753 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12754 Best->FoundDecl, Method); 12755 if (Arg0.isInvalid()) 12756 return ExprError(); 12757 Args[0] = Arg0.get(); 12758 12759 // Convert the arguments. 12760 ExprResult InputInit 12761 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12762 Context, 12763 FnDecl->getParamDecl(0)), 12764 SourceLocation(), 12765 Args[1]); 12766 if (InputInit.isInvalid()) 12767 return ExprError(); 12768 12769 Args[1] = InputInit.getAs<Expr>(); 12770 12771 // Build the actual expression node. 12772 DeclarationNameInfo OpLocInfo(OpName, LLoc); 12773 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12774 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12775 Best->FoundDecl, 12776 Base, 12777 HadMultipleCandidates, 12778 OpLocInfo.getLoc(), 12779 OpLocInfo.getInfo()); 12780 if (FnExpr.isInvalid()) 12781 return ExprError(); 12782 12783 // Determine the result type 12784 QualType ResultTy = FnDecl->getReturnType(); 12785 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12786 ResultTy = ResultTy.getNonLValueExprType(Context); 12787 12788 CXXOperatorCallExpr *TheCall = 12789 CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(), 12790 Args, ResultTy, VK, RLoc, FPOptions()); 12791 12792 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 12793 return ExprError(); 12794 12795 if (CheckFunctionCall(Method, TheCall, 12796 Method->getType()->castAs<FunctionProtoType>())) 12797 return ExprError(); 12798 12799 return MaybeBindToTemporary(TheCall); 12800 } else { 12801 // We matched a built-in operator. Convert the arguments, then 12802 // break out so that we will build the appropriate built-in 12803 // operator node. 12804 ExprResult ArgsRes0 = PerformImplicitConversion( 12805 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0], 12806 AA_Passing, CCK_ForBuiltinOverloadedOp); 12807 if (ArgsRes0.isInvalid()) 12808 return ExprError(); 12809 Args[0] = ArgsRes0.get(); 12810 12811 ExprResult ArgsRes1 = PerformImplicitConversion( 12812 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1], 12813 AA_Passing, CCK_ForBuiltinOverloadedOp); 12814 if (ArgsRes1.isInvalid()) 12815 return ExprError(); 12816 Args[1] = ArgsRes1.get(); 12817 12818 break; 12819 } 12820 } 12821 12822 case OR_No_Viable_Function: { 12823 if (CandidateSet.empty()) 12824 Diag(LLoc, diag::err_ovl_no_oper) 12825 << Args[0]->getType() << /*subscript*/ 0 12826 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12827 else 12828 Diag(LLoc, diag::err_ovl_no_viable_subscript) 12829 << Args[0]->getType() 12830 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12831 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12832 "[]", LLoc); 12833 return ExprError(); 12834 } 12835 12836 case OR_Ambiguous: 12837 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 12838 << "[]" 12839 << Args[0]->getType() << Args[1]->getType() 12840 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12841 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12842 "[]", LLoc); 12843 return ExprError(); 12844 12845 case OR_Deleted: 12846 Diag(LLoc, diag::err_ovl_deleted_oper) 12847 << Best->Function->isDeleted() << "[]" 12848 << getDeletedOrUnavailableSuffix(Best->Function) 12849 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12850 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12851 "[]", LLoc); 12852 return ExprError(); 12853 } 12854 12855 // We matched a built-in operator; build it. 12856 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 12857 } 12858 12859 /// BuildCallToMemberFunction - Build a call to a member 12860 /// function. MemExpr is the expression that refers to the member 12861 /// function (and includes the object parameter), Args/NumArgs are the 12862 /// arguments to the function call (not including the object 12863 /// parameter). The caller needs to validate that the member 12864 /// expression refers to a non-static member function or an overloaded 12865 /// member function. 12866 ExprResult 12867 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 12868 SourceLocation LParenLoc, 12869 MultiExprArg Args, 12870 SourceLocation RParenLoc) { 12871 assert(MemExprE->getType() == Context.BoundMemberTy || 12872 MemExprE->getType() == Context.OverloadTy); 12873 12874 // Dig out the member expression. This holds both the object 12875 // argument and the member function we're referring to. 12876 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12877 12878 // Determine whether this is a call to a pointer-to-member function. 12879 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12880 assert(op->getType() == Context.BoundMemberTy); 12881 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12882 12883 QualType fnType = 12884 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12885 12886 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12887 QualType resultType = proto->getCallResultType(Context); 12888 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12889 12890 // Check that the object type isn't more qualified than the 12891 // member function we're calling. 12892 Qualifiers funcQuals = proto->getMethodQuals(); 12893 12894 QualType objectType = op->getLHS()->getType(); 12895 if (op->getOpcode() == BO_PtrMemI) 12896 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12897 Qualifiers objectQuals = objectType.getQualifiers(); 12898 12899 Qualifiers difference = objectQuals - funcQuals; 12900 difference.removeObjCGCAttr(); 12901 difference.removeAddressSpace(); 12902 if (difference) { 12903 std::string qualsString = difference.getAsString(); 12904 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12905 << fnType.getUnqualifiedType() 12906 << qualsString 12907 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12908 } 12909 12910 CXXMemberCallExpr *call = 12911 CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType, 12912 valueKind, RParenLoc, proto->getNumParams()); 12913 12914 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(), 12915 call, nullptr)) 12916 return ExprError(); 12917 12918 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12919 return ExprError(); 12920 12921 if (CheckOtherCall(call, proto)) 12922 return ExprError(); 12923 12924 return MaybeBindToTemporary(call); 12925 } 12926 12927 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 12928 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue, 12929 RParenLoc); 12930 12931 UnbridgedCastsSet UnbridgedCasts; 12932 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12933 return ExprError(); 12934 12935 MemberExpr *MemExpr; 12936 CXXMethodDecl *Method = nullptr; 12937 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 12938 NestedNameSpecifier *Qualifier = nullptr; 12939 if (isa<MemberExpr>(NakedMemExpr)) { 12940 MemExpr = cast<MemberExpr>(NakedMemExpr); 12941 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 12942 FoundDecl = MemExpr->getFoundDecl(); 12943 Qualifier = MemExpr->getQualifier(); 12944 UnbridgedCasts.restore(); 12945 } else { 12946 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 12947 Qualifier = UnresExpr->getQualifier(); 12948 12949 QualType ObjectType = UnresExpr->getBaseType(); 12950 Expr::Classification ObjectClassification 12951 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 12952 : UnresExpr->getBase()->Classify(Context); 12953 12954 // Add overload candidates 12955 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 12956 OverloadCandidateSet::CSK_Normal); 12957 12958 // FIXME: avoid copy. 12959 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12960 if (UnresExpr->hasExplicitTemplateArgs()) { 12961 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12962 TemplateArgs = &TemplateArgsBuffer; 12963 } 12964 12965 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 12966 E = UnresExpr->decls_end(); I != E; ++I) { 12967 12968 NamedDecl *Func = *I; 12969 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 12970 if (isa<UsingShadowDecl>(Func)) 12971 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 12972 12973 12974 // Microsoft supports direct constructor calls. 12975 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 12976 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 12977 Args, CandidateSet); 12978 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 12979 // If explicit template arguments were provided, we can't call a 12980 // non-template member function. 12981 if (TemplateArgs) 12982 continue; 12983 12984 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 12985 ObjectClassification, Args, CandidateSet, 12986 /*SuppressUserConversions=*/false); 12987 } else { 12988 AddMethodTemplateCandidate( 12989 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC, 12990 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet, 12991 /*SuppressUsedConversions=*/false); 12992 } 12993 } 12994 12995 DeclarationName DeclName = UnresExpr->getMemberName(); 12996 12997 UnbridgedCasts.restore(); 12998 12999 OverloadCandidateSet::iterator Best; 13000 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(), 13001 Best)) { 13002 case OR_Success: 13003 Method = cast<CXXMethodDecl>(Best->Function); 13004 FoundDecl = Best->FoundDecl; 13005 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 13006 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 13007 return ExprError(); 13008 // If FoundDecl is different from Method (such as if one is a template 13009 // and the other a specialization), make sure DiagnoseUseOfDecl is 13010 // called on both. 13011 // FIXME: This would be more comprehensively addressed by modifying 13012 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 13013 // being used. 13014 if (Method != FoundDecl.getDecl() && 13015 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 13016 return ExprError(); 13017 break; 13018 13019 case OR_No_Viable_Function: 13020 Diag(UnresExpr->getMemberLoc(), 13021 diag::err_ovl_no_viable_member_function_in_call) 13022 << DeclName << MemExprE->getSourceRange(); 13023 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13024 // FIXME: Leaking incoming expressions! 13025 return ExprError(); 13026 13027 case OR_Ambiguous: 13028 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 13029 << DeclName << MemExprE->getSourceRange(); 13030 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13031 // FIXME: Leaking incoming expressions! 13032 return ExprError(); 13033 13034 case OR_Deleted: 13035 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 13036 << Best->Function->isDeleted() 13037 << DeclName 13038 << getDeletedOrUnavailableSuffix(Best->Function) 13039 << MemExprE->getSourceRange(); 13040 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13041 // FIXME: Leaking incoming expressions! 13042 return ExprError(); 13043 } 13044 13045 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 13046 13047 // If overload resolution picked a static member, build a 13048 // non-member call based on that function. 13049 if (Method->isStatic()) { 13050 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 13051 RParenLoc); 13052 } 13053 13054 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 13055 } 13056 13057 QualType ResultType = Method->getReturnType(); 13058 ExprValueKind VK = Expr::getValueKindForType(ResultType); 13059 ResultType = ResultType.getNonLValueExprType(Context); 13060 13061 assert(Method && "Member call to something that isn't a method?"); 13062 const auto *Proto = Method->getType()->getAs<FunctionProtoType>(); 13063 CXXMemberCallExpr *TheCall = 13064 CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK, 13065 RParenLoc, Proto->getNumParams()); 13066 13067 // Check for a valid return type. 13068 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 13069 TheCall, Method)) 13070 return ExprError(); 13071 13072 // Convert the object argument (for a non-static member function call). 13073 // We only need to do this if there was actually an overload; otherwise 13074 // it was done at lookup. 13075 if (!Method->isStatic()) { 13076 ExprResult ObjectArg = 13077 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 13078 FoundDecl, Method); 13079 if (ObjectArg.isInvalid()) 13080 return ExprError(); 13081 MemExpr->setBase(ObjectArg.get()); 13082 } 13083 13084 // Convert the rest of the arguments 13085 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 13086 RParenLoc)) 13087 return ExprError(); 13088 13089 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13090 13091 if (CheckFunctionCall(Method, TheCall, Proto)) 13092 return ExprError(); 13093 13094 // In the case the method to call was not selected by the overloading 13095 // resolution process, we still need to handle the enable_if attribute. Do 13096 // that here, so it will not hide previous -- and more relevant -- errors. 13097 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 13098 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 13099 Diag(MemE->getMemberLoc(), 13100 diag::err_ovl_no_viable_member_function_in_call) 13101 << Method << Method->getSourceRange(); 13102 Diag(Method->getLocation(), 13103 diag::note_ovl_candidate_disabled_by_function_cond_attr) 13104 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 13105 return ExprError(); 13106 } 13107 } 13108 13109 if ((isa<CXXConstructorDecl>(CurContext) || 13110 isa<CXXDestructorDecl>(CurContext)) && 13111 TheCall->getMethodDecl()->isPure()) { 13112 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 13113 13114 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 13115 MemExpr->performsVirtualDispatch(getLangOpts())) { 13116 Diag(MemExpr->getBeginLoc(), 13117 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 13118 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 13119 << MD->getParent()->getDeclName(); 13120 13121 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName(); 13122 if (getLangOpts().AppleKext) 13123 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext) 13124 << MD->getParent()->getDeclName() << MD->getDeclName(); 13125 } 13126 } 13127 13128 if (CXXDestructorDecl *DD = 13129 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 13130 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 13131 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 13132 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false, 13133 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 13134 MemExpr->getMemberLoc()); 13135 } 13136 13137 return MaybeBindToTemporary(TheCall); 13138 } 13139 13140 /// BuildCallToObjectOfClassType - Build a call to an object of class 13141 /// type (C++ [over.call.object]), which can end up invoking an 13142 /// overloaded function call operator (@c operator()) or performing a 13143 /// user-defined conversion on the object argument. 13144 ExprResult 13145 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 13146 SourceLocation LParenLoc, 13147 MultiExprArg Args, 13148 SourceLocation RParenLoc) { 13149 if (checkPlaceholderForOverload(*this, Obj)) 13150 return ExprError(); 13151 ExprResult Object = Obj; 13152 13153 UnbridgedCastsSet UnbridgedCasts; 13154 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 13155 return ExprError(); 13156 13157 assert(Object.get()->getType()->isRecordType() && 13158 "Requires object type argument"); 13159 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 13160 13161 // C++ [over.call.object]p1: 13162 // If the primary-expression E in the function call syntax 13163 // evaluates to a class object of type "cv T", then the set of 13164 // candidate functions includes at least the function call 13165 // operators of T. The function call operators of T are obtained by 13166 // ordinary lookup of the name operator() in the context of 13167 // (E).operator(). 13168 OverloadCandidateSet CandidateSet(LParenLoc, 13169 OverloadCandidateSet::CSK_Operator); 13170 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 13171 13172 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 13173 diag::err_incomplete_object_call, Object.get())) 13174 return true; 13175 13176 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 13177 LookupQualifiedName(R, Record->getDecl()); 13178 R.suppressDiagnostics(); 13179 13180 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13181 Oper != OperEnd; ++Oper) { 13182 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 13183 Object.get()->Classify(Context), Args, CandidateSet, 13184 /*SuppressUserConversions=*/false); 13185 } 13186 13187 // C++ [over.call.object]p2: 13188 // In addition, for each (non-explicit in C++0x) conversion function 13189 // declared in T of the form 13190 // 13191 // operator conversion-type-id () cv-qualifier; 13192 // 13193 // where cv-qualifier is the same cv-qualification as, or a 13194 // greater cv-qualification than, cv, and where conversion-type-id 13195 // denotes the type "pointer to function of (P1,...,Pn) returning 13196 // R", or the type "reference to pointer to function of 13197 // (P1,...,Pn) returning R", or the type "reference to function 13198 // of (P1,...,Pn) returning R", a surrogate call function [...] 13199 // is also considered as a candidate function. Similarly, 13200 // surrogate call functions are added to the set of candidate 13201 // functions for each conversion function declared in an 13202 // accessible base class provided the function is not hidden 13203 // within T by another intervening declaration. 13204 const auto &Conversions = 13205 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 13206 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 13207 NamedDecl *D = *I; 13208 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 13209 if (isa<UsingShadowDecl>(D)) 13210 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 13211 13212 // Skip over templated conversion functions; they aren't 13213 // surrogates. 13214 if (isa<FunctionTemplateDecl>(D)) 13215 continue; 13216 13217 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 13218 if (!Conv->isExplicit()) { 13219 // Strip the reference type (if any) and then the pointer type (if 13220 // any) to get down to what might be a function type. 13221 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 13222 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 13223 ConvType = ConvPtrType->getPointeeType(); 13224 13225 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 13226 { 13227 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 13228 Object.get(), Args, CandidateSet); 13229 } 13230 } 13231 } 13232 13233 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13234 13235 // Perform overload resolution. 13236 OverloadCandidateSet::iterator Best; 13237 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(), 13238 Best)) { 13239 case OR_Success: 13240 // Overload resolution succeeded; we'll build the appropriate call 13241 // below. 13242 break; 13243 13244 case OR_No_Viable_Function: 13245 if (CandidateSet.empty()) 13246 Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_oper) 13247 << Object.get()->getType() << /*call*/ 1 13248 << Object.get()->getSourceRange(); 13249 else 13250 Diag(Object.get()->getBeginLoc(), diag::err_ovl_no_viable_object_call) 13251 << Object.get()->getType() << Object.get()->getSourceRange(); 13252 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13253 break; 13254 13255 case OR_Ambiguous: 13256 Diag(Object.get()->getBeginLoc(), diag::err_ovl_ambiguous_object_call) 13257 << Object.get()->getType() << Object.get()->getSourceRange(); 13258 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 13259 break; 13260 13261 case OR_Deleted: 13262 Diag(Object.get()->getBeginLoc(), diag::err_ovl_deleted_object_call) 13263 << Best->Function->isDeleted() << Object.get()->getType() 13264 << getDeletedOrUnavailableSuffix(Best->Function) 13265 << Object.get()->getSourceRange(); 13266 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13267 break; 13268 } 13269 13270 if (Best == CandidateSet.end()) 13271 return true; 13272 13273 UnbridgedCasts.restore(); 13274 13275 if (Best->Function == nullptr) { 13276 // Since there is no function declaration, this is one of the 13277 // surrogate candidates. Dig out the conversion function. 13278 CXXConversionDecl *Conv 13279 = cast<CXXConversionDecl>( 13280 Best->Conversions[0].UserDefined.ConversionFunction); 13281 13282 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 13283 Best->FoundDecl); 13284 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 13285 return ExprError(); 13286 assert(Conv == Best->FoundDecl.getDecl() && 13287 "Found Decl & conversion-to-functionptr should be same, right?!"); 13288 // We selected one of the surrogate functions that converts the 13289 // object parameter to a function pointer. Perform the conversion 13290 // on the object argument, then let ActOnCallExpr finish the job. 13291 13292 // Create an implicit member expr to refer to the conversion operator. 13293 // and then call it. 13294 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 13295 Conv, HadMultipleCandidates); 13296 if (Call.isInvalid()) 13297 return ExprError(); 13298 // Record usage of conversion in an implicit cast. 13299 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 13300 CK_UserDefinedConversion, Call.get(), 13301 nullptr, VK_RValue); 13302 13303 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 13304 } 13305 13306 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 13307 13308 // We found an overloaded operator(). Build a CXXOperatorCallExpr 13309 // that calls this method, using Object for the implicit object 13310 // parameter and passing along the remaining arguments. 13311 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13312 13313 // An error diagnostic has already been printed when parsing the declaration. 13314 if (Method->isInvalidDecl()) 13315 return ExprError(); 13316 13317 const FunctionProtoType *Proto = 13318 Method->getType()->getAs<FunctionProtoType>(); 13319 13320 unsigned NumParams = Proto->getNumParams(); 13321 13322 DeclarationNameInfo OpLocInfo( 13323 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 13324 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 13325 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13326 Obj, HadMultipleCandidates, 13327 OpLocInfo.getLoc(), 13328 OpLocInfo.getInfo()); 13329 if (NewFn.isInvalid()) 13330 return true; 13331 13332 // The number of argument slots to allocate in the call. If we have default 13333 // arguments we need to allocate space for them as well. We additionally 13334 // need one more slot for the object parameter. 13335 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams); 13336 13337 // Build the full argument list for the method call (the implicit object 13338 // parameter is placed at the beginning of the list). 13339 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots); 13340 13341 bool IsError = false; 13342 13343 // Initialize the implicit object parameter. 13344 ExprResult ObjRes = 13345 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 13346 Best->FoundDecl, Method); 13347 if (ObjRes.isInvalid()) 13348 IsError = true; 13349 else 13350 Object = ObjRes; 13351 MethodArgs[0] = Object.get(); 13352 13353 // Check the argument types. 13354 for (unsigned i = 0; i != NumParams; i++) { 13355 Expr *Arg; 13356 if (i < Args.size()) { 13357 Arg = Args[i]; 13358 13359 // Pass the argument. 13360 13361 ExprResult InputInit 13362 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 13363 Context, 13364 Method->getParamDecl(i)), 13365 SourceLocation(), Arg); 13366 13367 IsError |= InputInit.isInvalid(); 13368 Arg = InputInit.getAs<Expr>(); 13369 } else { 13370 ExprResult DefArg 13371 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 13372 if (DefArg.isInvalid()) { 13373 IsError = true; 13374 break; 13375 } 13376 13377 Arg = DefArg.getAs<Expr>(); 13378 } 13379 13380 MethodArgs[i + 1] = Arg; 13381 } 13382 13383 // If this is a variadic call, handle args passed through "...". 13384 if (Proto->isVariadic()) { 13385 // Promote the arguments (C99 6.5.2.2p7). 13386 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 13387 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 13388 nullptr); 13389 IsError |= Arg.isInvalid(); 13390 MethodArgs[i + 1] = Arg.get(); 13391 } 13392 } 13393 13394 if (IsError) 13395 return true; 13396 13397 DiagnoseSentinelCalls(Method, LParenLoc, Args); 13398 13399 // Once we've built TheCall, all of the expressions are properly owned. 13400 QualType ResultTy = Method->getReturnType(); 13401 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13402 ResultTy = ResultTy.getNonLValueExprType(Context); 13403 13404 CXXOperatorCallExpr *TheCall = 13405 CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs, 13406 ResultTy, VK, RParenLoc, FPOptions()); 13407 13408 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 13409 return true; 13410 13411 if (CheckFunctionCall(Method, TheCall, Proto)) 13412 return true; 13413 13414 return MaybeBindToTemporary(TheCall); 13415 } 13416 13417 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 13418 /// (if one exists), where @c Base is an expression of class type and 13419 /// @c Member is the name of the member we're trying to find. 13420 ExprResult 13421 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 13422 bool *NoArrowOperatorFound) { 13423 assert(Base->getType()->isRecordType() && 13424 "left-hand side must have class type"); 13425 13426 if (checkPlaceholderForOverload(*this, Base)) 13427 return ExprError(); 13428 13429 SourceLocation Loc = Base->getExprLoc(); 13430 13431 // C++ [over.ref]p1: 13432 // 13433 // [...] An expression x->m is interpreted as (x.operator->())->m 13434 // for a class object x of type T if T::operator->() exists and if 13435 // the operator is selected as the best match function by the 13436 // overload resolution mechanism (13.3). 13437 DeclarationName OpName = 13438 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 13439 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 13440 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 13441 13442 if (RequireCompleteType(Loc, Base->getType(), 13443 diag::err_typecheck_incomplete_tag, Base)) 13444 return ExprError(); 13445 13446 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 13447 LookupQualifiedName(R, BaseRecord->getDecl()); 13448 R.suppressDiagnostics(); 13449 13450 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 13451 Oper != OperEnd; ++Oper) { 13452 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 13453 None, CandidateSet, /*SuppressUserConversions=*/false); 13454 } 13455 13456 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13457 13458 // Perform overload resolution. 13459 OverloadCandidateSet::iterator Best; 13460 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 13461 case OR_Success: 13462 // Overload resolution succeeded; we'll build the call below. 13463 break; 13464 13465 case OR_No_Viable_Function: 13466 if (CandidateSet.empty()) { 13467 QualType BaseType = Base->getType(); 13468 if (NoArrowOperatorFound) { 13469 // Report this specific error to the caller instead of emitting a 13470 // diagnostic, as requested. 13471 *NoArrowOperatorFound = true; 13472 return ExprError(); 13473 } 13474 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 13475 << BaseType << Base->getSourceRange(); 13476 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 13477 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 13478 << FixItHint::CreateReplacement(OpLoc, "."); 13479 } 13480 } else 13481 Diag(OpLoc, diag::err_ovl_no_viable_oper) 13482 << "operator->" << Base->getSourceRange(); 13483 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 13484 return ExprError(); 13485 13486 case OR_Ambiguous: 13487 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 13488 << "->" << Base->getType() << Base->getSourceRange(); 13489 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 13490 return ExprError(); 13491 13492 case OR_Deleted: 13493 Diag(OpLoc, diag::err_ovl_deleted_oper) 13494 << Best->Function->isDeleted() 13495 << "->" 13496 << getDeletedOrUnavailableSuffix(Best->Function) 13497 << Base->getSourceRange(); 13498 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 13499 return ExprError(); 13500 } 13501 13502 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 13503 13504 // Convert the object parameter. 13505 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 13506 ExprResult BaseResult = 13507 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 13508 Best->FoundDecl, Method); 13509 if (BaseResult.isInvalid()) 13510 return ExprError(); 13511 Base = BaseResult.get(); 13512 13513 // Build the operator call. 13514 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 13515 Base, HadMultipleCandidates, OpLoc); 13516 if (FnExpr.isInvalid()) 13517 return ExprError(); 13518 13519 QualType ResultTy = Method->getReturnType(); 13520 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13521 ResultTy = ResultTy.getNonLValueExprType(Context); 13522 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create( 13523 Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions()); 13524 13525 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 13526 return ExprError(); 13527 13528 if (CheckFunctionCall(Method, TheCall, 13529 Method->getType()->castAs<FunctionProtoType>())) 13530 return ExprError(); 13531 13532 return MaybeBindToTemporary(TheCall); 13533 } 13534 13535 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 13536 /// a literal operator described by the provided lookup results. 13537 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 13538 DeclarationNameInfo &SuffixInfo, 13539 ArrayRef<Expr*> Args, 13540 SourceLocation LitEndLoc, 13541 TemplateArgumentListInfo *TemplateArgs) { 13542 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 13543 13544 OverloadCandidateSet CandidateSet(UDSuffixLoc, 13545 OverloadCandidateSet::CSK_Normal); 13546 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 13547 /*SuppressUserConversions=*/true); 13548 13549 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13550 13551 // Perform overload resolution. This will usually be trivial, but might need 13552 // to perform substitutions for a literal operator template. 13553 OverloadCandidateSet::iterator Best; 13554 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 13555 case OR_Success: 13556 case OR_Deleted: 13557 break; 13558 13559 case OR_No_Viable_Function: 13560 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 13561 << R.getLookupName(); 13562 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13563 return ExprError(); 13564 13565 case OR_Ambiguous: 13566 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 13567 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 13568 return ExprError(); 13569 } 13570 13571 FunctionDecl *FD = Best->Function; 13572 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 13573 nullptr, HadMultipleCandidates, 13574 SuffixInfo.getLoc(), 13575 SuffixInfo.getInfo()); 13576 if (Fn.isInvalid()) 13577 return true; 13578 13579 // Check the argument types. This should almost always be a no-op, except 13580 // that array-to-pointer decay is applied to string literals. 13581 Expr *ConvArgs[2]; 13582 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 13583 ExprResult InputInit = PerformCopyInitialization( 13584 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 13585 SourceLocation(), Args[ArgIdx]); 13586 if (InputInit.isInvalid()) 13587 return true; 13588 ConvArgs[ArgIdx] = InputInit.get(); 13589 } 13590 13591 QualType ResultTy = FD->getReturnType(); 13592 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13593 ResultTy = ResultTy.getNonLValueExprType(Context); 13594 13595 UserDefinedLiteral *UDL = UserDefinedLiteral::Create( 13596 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy, 13597 VK, LitEndLoc, UDSuffixLoc); 13598 13599 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 13600 return ExprError(); 13601 13602 if (CheckFunctionCall(FD, UDL, nullptr)) 13603 return ExprError(); 13604 13605 return MaybeBindToTemporary(UDL); 13606 } 13607 13608 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 13609 /// given LookupResult is non-empty, it is assumed to describe a member which 13610 /// will be invoked. Otherwise, the function will be found via argument 13611 /// dependent lookup. 13612 /// CallExpr is set to a valid expression and FRS_Success returned on success, 13613 /// otherwise CallExpr is set to ExprError() and some non-success value 13614 /// is returned. 13615 Sema::ForRangeStatus 13616 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 13617 SourceLocation RangeLoc, 13618 const DeclarationNameInfo &NameInfo, 13619 LookupResult &MemberLookup, 13620 OverloadCandidateSet *CandidateSet, 13621 Expr *Range, ExprResult *CallExpr) { 13622 Scope *S = nullptr; 13623 13624 CandidateSet->clear(OverloadCandidateSet::CSK_Normal); 13625 if (!MemberLookup.empty()) { 13626 ExprResult MemberRef = 13627 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 13628 /*IsPtr=*/false, CXXScopeSpec(), 13629 /*TemplateKWLoc=*/SourceLocation(), 13630 /*FirstQualifierInScope=*/nullptr, 13631 MemberLookup, 13632 /*TemplateArgs=*/nullptr, S); 13633 if (MemberRef.isInvalid()) { 13634 *CallExpr = ExprError(); 13635 return FRS_DiagnosticIssued; 13636 } 13637 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 13638 if (CallExpr->isInvalid()) { 13639 *CallExpr = ExprError(); 13640 return FRS_DiagnosticIssued; 13641 } 13642 } else { 13643 UnresolvedSet<0> FoundNames; 13644 UnresolvedLookupExpr *Fn = 13645 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 13646 NestedNameSpecifierLoc(), NameInfo, 13647 /*NeedsADL=*/true, /*Overloaded=*/false, 13648 FoundNames.begin(), FoundNames.end()); 13649 13650 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 13651 CandidateSet, CallExpr); 13652 if (CandidateSet->empty() || CandidateSetError) { 13653 *CallExpr = ExprError(); 13654 return FRS_NoViableFunction; 13655 } 13656 OverloadCandidateSet::iterator Best; 13657 OverloadingResult OverloadResult = 13658 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best); 13659 13660 if (OverloadResult == OR_No_Viable_Function) { 13661 *CallExpr = ExprError(); 13662 return FRS_NoViableFunction; 13663 } 13664 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 13665 Loc, nullptr, CandidateSet, &Best, 13666 OverloadResult, 13667 /*AllowTypoCorrection=*/false); 13668 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 13669 *CallExpr = ExprError(); 13670 return FRS_DiagnosticIssued; 13671 } 13672 } 13673 return FRS_Success; 13674 } 13675 13676 13677 /// FixOverloadedFunctionReference - E is an expression that refers to 13678 /// a C++ overloaded function (possibly with some parentheses and 13679 /// perhaps a '&' around it). We have resolved the overloaded function 13680 /// to the function declaration Fn, so patch up the expression E to 13681 /// refer (possibly indirectly) to Fn. Returns the new expr. 13682 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 13683 FunctionDecl *Fn) { 13684 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 13685 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 13686 Found, Fn); 13687 if (SubExpr == PE->getSubExpr()) 13688 return PE; 13689 13690 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 13691 } 13692 13693 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 13694 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 13695 Found, Fn); 13696 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 13697 SubExpr->getType()) && 13698 "Implicit cast type cannot be determined from overload"); 13699 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 13700 if (SubExpr == ICE->getSubExpr()) 13701 return ICE; 13702 13703 return ImplicitCastExpr::Create(Context, ICE->getType(), 13704 ICE->getCastKind(), 13705 SubExpr, nullptr, 13706 ICE->getValueKind()); 13707 } 13708 13709 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 13710 if (!GSE->isResultDependent()) { 13711 Expr *SubExpr = 13712 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 13713 if (SubExpr == GSE->getResultExpr()) 13714 return GSE; 13715 13716 // Replace the resulting type information before rebuilding the generic 13717 // selection expression. 13718 ArrayRef<Expr *> A = GSE->getAssocExprs(); 13719 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 13720 unsigned ResultIdx = GSE->getResultIndex(); 13721 AssocExprs[ResultIdx] = SubExpr; 13722 13723 return GenericSelectionExpr::Create( 13724 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 13725 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 13726 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 13727 ResultIdx); 13728 } 13729 // Rather than fall through to the unreachable, return the original generic 13730 // selection expression. 13731 return GSE; 13732 } 13733 13734 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 13735 assert(UnOp->getOpcode() == UO_AddrOf && 13736 "Can only take the address of an overloaded function"); 13737 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 13738 if (Method->isStatic()) { 13739 // Do nothing: static member functions aren't any different 13740 // from non-member functions. 13741 } else { 13742 // Fix the subexpression, which really has to be an 13743 // UnresolvedLookupExpr holding an overloaded member function 13744 // or template. 13745 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13746 Found, Fn); 13747 if (SubExpr == UnOp->getSubExpr()) 13748 return UnOp; 13749 13750 assert(isa<DeclRefExpr>(SubExpr) 13751 && "fixed to something other than a decl ref"); 13752 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 13753 && "fixed to a member ref with no nested name qualifier"); 13754 13755 // We have taken the address of a pointer to member 13756 // function. Perform the computation here so that we get the 13757 // appropriate pointer to member type. 13758 QualType ClassType 13759 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 13760 QualType MemPtrType 13761 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 13762 // Under the MS ABI, lock down the inheritance model now. 13763 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13764 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 13765 13766 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 13767 VK_RValue, OK_Ordinary, 13768 UnOp->getOperatorLoc(), false); 13769 } 13770 } 13771 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13772 Found, Fn); 13773 if (SubExpr == UnOp->getSubExpr()) 13774 return UnOp; 13775 13776 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 13777 Context.getPointerType(SubExpr->getType()), 13778 VK_RValue, OK_Ordinary, 13779 UnOp->getOperatorLoc(), false); 13780 } 13781 13782 // C++ [except.spec]p17: 13783 // An exception-specification is considered to be needed when: 13784 // - in an expression the function is the unique lookup result or the 13785 // selected member of a set of overloaded functions 13786 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 13787 ResolveExceptionSpec(E->getExprLoc(), FPT); 13788 13789 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13790 // FIXME: avoid copy. 13791 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13792 if (ULE->hasExplicitTemplateArgs()) { 13793 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 13794 TemplateArgs = &TemplateArgsBuffer; 13795 } 13796 13797 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13798 ULE->getQualifierLoc(), 13799 ULE->getTemplateKeywordLoc(), 13800 Fn, 13801 /*enclosing*/ false, // FIXME? 13802 ULE->getNameLoc(), 13803 Fn->getType(), 13804 VK_LValue, 13805 Found.getDecl(), 13806 TemplateArgs); 13807 MarkDeclRefReferenced(DRE); 13808 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 13809 return DRE; 13810 } 13811 13812 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 13813 // FIXME: avoid copy. 13814 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13815 if (MemExpr->hasExplicitTemplateArgs()) { 13816 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13817 TemplateArgs = &TemplateArgsBuffer; 13818 } 13819 13820 Expr *Base; 13821 13822 // If we're filling in a static method where we used to have an 13823 // implicit member access, rewrite to a simple decl ref. 13824 if (MemExpr->isImplicitAccess()) { 13825 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13826 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13827 MemExpr->getQualifierLoc(), 13828 MemExpr->getTemplateKeywordLoc(), 13829 Fn, 13830 /*enclosing*/ false, 13831 MemExpr->getMemberLoc(), 13832 Fn->getType(), 13833 VK_LValue, 13834 Found.getDecl(), 13835 TemplateArgs); 13836 MarkDeclRefReferenced(DRE); 13837 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 13838 return DRE; 13839 } else { 13840 SourceLocation Loc = MemExpr->getMemberLoc(); 13841 if (MemExpr->getQualifier()) 13842 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 13843 CheckCXXThisCapture(Loc); 13844 Base = new (Context) CXXThisExpr(Loc, 13845 MemExpr->getBaseType(), 13846 /*isImplicit=*/true); 13847 } 13848 } else 13849 Base = MemExpr->getBase(); 13850 13851 ExprValueKind valueKind; 13852 QualType type; 13853 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13854 valueKind = VK_LValue; 13855 type = Fn->getType(); 13856 } else { 13857 valueKind = VK_RValue; 13858 type = Context.BoundMemberTy; 13859 } 13860 13861 MemberExpr *ME = MemberExpr::Create( 13862 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 13863 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 13864 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 13865 OK_Ordinary); 13866 ME->setHadMultipleCandidates(true); 13867 MarkMemberReferenced(ME); 13868 return ME; 13869 } 13870 13871 llvm_unreachable("Invalid reference to overloaded function"); 13872 } 13873 13874 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 13875 DeclAccessPair Found, 13876 FunctionDecl *Fn) { 13877 return FixOverloadedFunctionReference(E.get(), Found, Fn); 13878 } 13879