1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file provides Sema routines for C++ overloading. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/Overload.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/CXXInheritance.h" 17 #include "clang/AST/DeclObjC.h" 18 #include "clang/AST/Expr.h" 19 #include "clang/AST/ExprCXX.h" 20 #include "clang/AST/ExprObjC.h" 21 #include "clang/AST/TypeOrdering.h" 22 #include "clang/Basic/Diagnostic.h" 23 #include "clang/Basic/DiagnosticOptions.h" 24 #include "clang/Basic/PartialDiagnostic.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/SemaInternal.h" 29 #include "clang/Sema/Template.h" 30 #include "clang/Sema/TemplateDeduction.h" 31 #include "llvm/ADT/DenseSet.h" 32 #include "llvm/ADT/STLExtras.h" 33 #include "llvm/ADT/SmallPtrSet.h" 34 #include "llvm/ADT/SmallString.h" 35 #include <algorithm> 36 #include <cstdlib> 37 38 using namespace clang; 39 using namespace sema; 40 41 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) { 42 return llvm::any_of(FD->parameters(), [](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 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) DeclRefExpr(Fn, false, Fn->getType(), 66 VK_LValue, Loc, LocInfo); 67 if (HadMultipleCandidates) 68 DRE->setHadMultipleCandidates(true); 69 70 S.MarkDeclRefReferenced(DRE); 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_Conversion, 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()->isObjCObjectPointerType() || 226 getFromType()->isBlockPointerType() || 227 getFromType()->isNullPtrType() || 228 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 229 return true; 230 231 return false; 232 } 233 234 /// isPointerConversionToVoidPointer - Determines whether this 235 /// conversion is a conversion of a pointer to a void pointer. This is 236 /// used as part of the ranking of standard conversion sequences (C++ 237 /// 13.3.3.2p4). 238 bool 239 StandardConversionSequence:: 240 isPointerConversionToVoidPointer(ASTContext& Context) const { 241 QualType FromType = getFromType(); 242 QualType ToType = getToType(1); 243 244 // Note that FromType has not necessarily been transformed by the 245 // array-to-pointer implicit conversion, so check for its presence 246 // and redo the conversion to get a pointer. 247 if (First == ICK_Array_To_Pointer) 248 FromType = Context.getArrayDecayedType(FromType); 249 250 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 251 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 252 return ToPtrType->getPointeeType()->isVoidType(); 253 254 return false; 255 } 256 257 /// Skip any implicit casts which could be either part of a narrowing conversion 258 /// or after one in an implicit conversion. 259 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 260 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 261 switch (ICE->getCastKind()) { 262 case CK_NoOp: 263 case CK_IntegralCast: 264 case CK_IntegralToBoolean: 265 case CK_IntegralToFloating: 266 case CK_BooleanToSignedIntegral: 267 case CK_FloatingToIntegral: 268 case CK_FloatingToBoolean: 269 case CK_FloatingCast: 270 Converted = ICE->getSubExpr(); 271 continue; 272 273 default: 274 return Converted; 275 } 276 } 277 278 return Converted; 279 } 280 281 /// Check if this standard conversion sequence represents a narrowing 282 /// conversion, according to C++11 [dcl.init.list]p7. 283 /// 284 /// \param Ctx The AST context. 285 /// \param Converted The result of applying this standard conversion sequence. 286 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 287 /// value of the expression prior to the narrowing conversion. 288 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 289 /// type of the expression prior to the narrowing conversion. 290 NarrowingKind 291 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 292 const Expr *Converted, 293 APValue &ConstantValue, 294 QualType &ConstantType) const { 295 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 296 297 // C++11 [dcl.init.list]p7: 298 // A narrowing conversion is an implicit conversion ... 299 QualType FromType = getToType(0); 300 QualType ToType = getToType(1); 301 302 // A conversion to an enumeration type is narrowing if the conversion to 303 // the underlying type is narrowing. This only arises for expressions of 304 // the form 'Enum{init}'. 305 if (auto *ET = ToType->getAs<EnumType>()) 306 ToType = ET->getDecl()->getIntegerType(); 307 308 switch (Second) { 309 // 'bool' is an integral type; dispatch to the right place to handle it. 310 case ICK_Boolean_Conversion: 311 if (FromType->isRealFloatingType()) 312 goto FloatingIntegralConversion; 313 if (FromType->isIntegralOrUnscopedEnumerationType()) 314 goto IntegralConversion; 315 // Boolean conversions can be from pointers and pointers to members 316 // [conv.bool], and those aren't considered narrowing conversions. 317 return NK_Not_Narrowing; 318 319 // -- from a floating-point type to an integer type, or 320 // 321 // -- from an integer type or unscoped enumeration type to a floating-point 322 // type, except where the source is a constant expression and the actual 323 // value after conversion will fit into the target type and will produce 324 // the original value when converted back to the original type, or 325 case ICK_Floating_Integral: 326 FloatingIntegralConversion: 327 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 328 return NK_Type_Narrowing; 329 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 330 llvm::APSInt IntConstantValue; 331 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 332 333 // If it's value-dependent, we can't tell whether it's narrowing. 334 if (Initializer->isValueDependent()) 335 return NK_Dependent_Narrowing; 336 337 if (Initializer && 338 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 339 // Convert the integer to the floating type. 340 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 341 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 342 llvm::APFloat::rmNearestTiesToEven); 343 // And back. 344 llvm::APSInt ConvertedValue = IntConstantValue; 345 bool ignored; 346 Result.convertToInteger(ConvertedValue, 347 llvm::APFloat::rmTowardZero, &ignored); 348 // If the resulting value is different, this was a narrowing conversion. 349 if (IntConstantValue != ConvertedValue) { 350 ConstantValue = APValue(IntConstantValue); 351 ConstantType = Initializer->getType(); 352 return NK_Constant_Narrowing; 353 } 354 } else { 355 // Variables are always narrowings. 356 return NK_Variable_Narrowing; 357 } 358 } 359 return NK_Not_Narrowing; 360 361 // -- from long double to double or float, or from double to float, except 362 // where the source is a constant expression and the actual value after 363 // conversion is within the range of values that can be represented (even 364 // if it cannot be represented exactly), or 365 case ICK_Floating_Conversion: 366 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 367 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 368 // FromType is larger than ToType. 369 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 370 371 // If it's value-dependent, we can't tell whether it's narrowing. 372 if (Initializer->isValueDependent()) 373 return NK_Dependent_Narrowing; 374 375 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 376 // Constant! 377 assert(ConstantValue.isFloat()); 378 llvm::APFloat FloatVal = ConstantValue.getFloat(); 379 // Convert the source value into the target type. 380 bool ignored; 381 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 382 Ctx.getFloatTypeSemantics(ToType), 383 llvm::APFloat::rmNearestTiesToEven, &ignored); 384 // If there was no overflow, the source value is within the range of 385 // values that can be represented. 386 if (ConvertStatus & llvm::APFloat::opOverflow) { 387 ConstantType = Initializer->getType(); 388 return NK_Constant_Narrowing; 389 } 390 } else { 391 return NK_Variable_Narrowing; 392 } 393 } 394 return NK_Not_Narrowing; 395 396 // -- from an integer type or unscoped enumeration type to an integer type 397 // that cannot represent all the values of the original type, except where 398 // the source is a constant expression and the actual value after 399 // conversion will fit into the target type and will produce the original 400 // value when converted back to the original type. 401 case ICK_Integral_Conversion: 402 IntegralConversion: { 403 assert(FromType->isIntegralOrUnscopedEnumerationType()); 404 assert(ToType->isIntegralOrUnscopedEnumerationType()); 405 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 406 const unsigned FromWidth = Ctx.getIntWidth(FromType); 407 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 408 const unsigned ToWidth = Ctx.getIntWidth(ToType); 409 410 if (FromWidth > ToWidth || 411 (FromWidth == ToWidth && FromSigned != ToSigned) || 412 (FromSigned && !ToSigned)) { 413 // Not all values of FromType can be represented in ToType. 414 llvm::APSInt InitializerValue; 415 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 416 417 // If it's value-dependent, we can't tell whether it's narrowing. 418 if (Initializer->isValueDependent()) 419 return NK_Dependent_Narrowing; 420 421 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 422 // Such conversions on variables are always narrowing. 423 return NK_Variable_Narrowing; 424 } 425 bool Narrowing = false; 426 if (FromWidth < ToWidth) { 427 // Negative -> unsigned is narrowing. Otherwise, more bits is never 428 // narrowing. 429 if (InitializerValue.isSigned() && InitializerValue.isNegative()) 430 Narrowing = true; 431 } else { 432 // Add a bit to the InitializerValue so we don't have to worry about 433 // signed vs. unsigned comparisons. 434 InitializerValue = InitializerValue.extend( 435 InitializerValue.getBitWidth() + 1); 436 // Convert the initializer to and from the target width and signed-ness. 437 llvm::APSInt ConvertedValue = InitializerValue; 438 ConvertedValue = ConvertedValue.trunc(ToWidth); 439 ConvertedValue.setIsSigned(ToSigned); 440 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 441 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 442 // If the result is different, this was a narrowing conversion. 443 if (ConvertedValue != InitializerValue) 444 Narrowing = true; 445 } 446 if (Narrowing) { 447 ConstantType = Initializer->getType(); 448 ConstantValue = APValue(InitializerValue); 449 return NK_Constant_Narrowing; 450 } 451 } 452 return NK_Not_Narrowing; 453 } 454 455 default: 456 // Other kinds of conversions are not narrowings. 457 return NK_Not_Narrowing; 458 } 459 } 460 461 /// dump - Print this standard conversion sequence to standard 462 /// error. Useful for debugging overloading issues. 463 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const { 464 raw_ostream &OS = llvm::errs(); 465 bool PrintedSomething = false; 466 if (First != ICK_Identity) { 467 OS << GetImplicitConversionName(First); 468 PrintedSomething = true; 469 } 470 471 if (Second != ICK_Identity) { 472 if (PrintedSomething) { 473 OS << " -> "; 474 } 475 OS << GetImplicitConversionName(Second); 476 477 if (CopyConstructor) { 478 OS << " (by copy constructor)"; 479 } else if (DirectBinding) { 480 OS << " (direct reference binding)"; 481 } else if (ReferenceBinding) { 482 OS << " (reference binding)"; 483 } 484 PrintedSomething = true; 485 } 486 487 if (Third != ICK_Identity) { 488 if (PrintedSomething) { 489 OS << " -> "; 490 } 491 OS << GetImplicitConversionName(Third); 492 PrintedSomething = true; 493 } 494 495 if (!PrintedSomething) { 496 OS << "No conversions required"; 497 } 498 } 499 500 /// dump - Print this user-defined conversion sequence to standard 501 /// error. Useful for debugging overloading issues. 502 void UserDefinedConversionSequence::dump() const { 503 raw_ostream &OS = llvm::errs(); 504 if (Before.First || Before.Second || Before.Third) { 505 Before.dump(); 506 OS << " -> "; 507 } 508 if (ConversionFunction) 509 OS << '\'' << *ConversionFunction << '\''; 510 else 511 OS << "aggregate initialization"; 512 if (After.First || After.Second || After.Third) { 513 OS << " -> "; 514 After.dump(); 515 } 516 } 517 518 /// dump - Print this implicit conversion sequence to standard 519 /// error. Useful for debugging overloading issues. 520 void ImplicitConversionSequence::dump() const { 521 raw_ostream &OS = llvm::errs(); 522 if (isStdInitializerListElement()) 523 OS << "Worst std::initializer_list element conversion: "; 524 switch (ConversionKind) { 525 case StandardConversion: 526 OS << "Standard conversion: "; 527 Standard.dump(); 528 break; 529 case UserDefinedConversion: 530 OS << "User-defined conversion: "; 531 UserDefined.dump(); 532 break; 533 case EllipsisConversion: 534 OS << "Ellipsis conversion"; 535 break; 536 case AmbiguousConversion: 537 OS << "Ambiguous conversion"; 538 break; 539 case BadConversion: 540 OS << "Bad conversion"; 541 break; 542 } 543 544 OS << "\n"; 545 } 546 547 void AmbiguousConversionSequence::construct() { 548 new (&conversions()) ConversionSet(); 549 } 550 551 void AmbiguousConversionSequence::destruct() { 552 conversions().~ConversionSet(); 553 } 554 555 void 556 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 557 FromTypePtr = O.FromTypePtr; 558 ToTypePtr = O.ToTypePtr; 559 new (&conversions()) ConversionSet(O.conversions()); 560 } 561 562 namespace { 563 // Structure used by DeductionFailureInfo to store 564 // template argument information. 565 struct DFIArguments { 566 TemplateArgument FirstArg; 567 TemplateArgument SecondArg; 568 }; 569 // Structure used by DeductionFailureInfo to store 570 // template parameter and template argument information. 571 struct DFIParamWithArguments : DFIArguments { 572 TemplateParameter Param; 573 }; 574 // Structure used by DeductionFailureInfo to store template argument 575 // information and the index of the problematic call argument. 576 struct DFIDeducedMismatchArgs : DFIArguments { 577 TemplateArgumentList *TemplateArgs; 578 unsigned CallArgIndex; 579 }; 580 } 581 582 /// \brief Convert from Sema's representation of template deduction information 583 /// to the form used in overload-candidate information. 584 DeductionFailureInfo 585 clang::MakeDeductionFailureInfo(ASTContext &Context, 586 Sema::TemplateDeductionResult TDK, 587 TemplateDeductionInfo &Info) { 588 DeductionFailureInfo Result; 589 Result.Result = static_cast<unsigned>(TDK); 590 Result.HasDiagnostic = false; 591 switch (TDK) { 592 case Sema::TDK_Success: 593 case Sema::TDK_Invalid: 594 case Sema::TDK_InstantiationDepth: 595 case Sema::TDK_TooManyArguments: 596 case Sema::TDK_TooFewArguments: 597 case Sema::TDK_MiscellaneousDeductionFailure: 598 case Sema::TDK_CUDATargetMismatch: 599 Result.Data = nullptr; 600 break; 601 602 case Sema::TDK_Incomplete: 603 case Sema::TDK_InvalidExplicitArguments: 604 Result.Data = Info.Param.getOpaqueValue(); 605 break; 606 607 case Sema::TDK_DeducedMismatch: { 608 // FIXME: Should allocate from normal heap so that we can free this later. 609 auto *Saved = new (Context) DFIDeducedMismatchArgs; 610 Saved->FirstArg = Info.FirstArg; 611 Saved->SecondArg = Info.SecondArg; 612 Saved->TemplateArgs = Info.take(); 613 Saved->CallArgIndex = Info.CallArgIndex; 614 Result.Data = Saved; 615 break; 616 } 617 618 case Sema::TDK_NonDeducedMismatch: { 619 // FIXME: Should allocate from normal heap so that we can free this later. 620 DFIArguments *Saved = new (Context) DFIArguments; 621 Saved->FirstArg = Info.FirstArg; 622 Saved->SecondArg = Info.SecondArg; 623 Result.Data = Saved; 624 break; 625 } 626 627 case Sema::TDK_Inconsistent: 628 case Sema::TDK_Underqualified: { 629 // FIXME: Should allocate from normal heap so that we can free this later. 630 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 631 Saved->Param = Info.Param; 632 Saved->FirstArg = Info.FirstArg; 633 Saved->SecondArg = Info.SecondArg; 634 Result.Data = Saved; 635 break; 636 } 637 638 case Sema::TDK_SubstitutionFailure: 639 Result.Data = Info.take(); 640 if (Info.hasSFINAEDiagnostic()) { 641 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt( 642 SourceLocation(), PartialDiagnostic::NullDiagnostic()); 643 Info.takeSFINAEDiagnostic(*Diag); 644 Result.HasDiagnostic = true; 645 } 646 break; 647 } 648 649 return Result; 650 } 651 652 void DeductionFailureInfo::Destroy() { 653 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 654 case Sema::TDK_Success: 655 case Sema::TDK_Invalid: 656 case Sema::TDK_InstantiationDepth: 657 case Sema::TDK_Incomplete: 658 case Sema::TDK_TooManyArguments: 659 case Sema::TDK_TooFewArguments: 660 case Sema::TDK_InvalidExplicitArguments: 661 case Sema::TDK_CUDATargetMismatch: 662 break; 663 664 case Sema::TDK_Inconsistent: 665 case Sema::TDK_Underqualified: 666 case Sema::TDK_DeducedMismatch: 667 case Sema::TDK_NonDeducedMismatch: 668 // FIXME: Destroy the data? 669 Data = nullptr; 670 break; 671 672 case Sema::TDK_SubstitutionFailure: 673 // FIXME: Destroy the template argument list? 674 Data = nullptr; 675 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) { 676 Diag->~PartialDiagnosticAt(); 677 HasDiagnostic = false; 678 } 679 break; 680 681 // Unhandled 682 case Sema::TDK_MiscellaneousDeductionFailure: 683 break; 684 } 685 } 686 687 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() { 688 if (HasDiagnostic) 689 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic)); 690 return nullptr; 691 } 692 693 TemplateParameter DeductionFailureInfo::getTemplateParameter() { 694 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 695 case Sema::TDK_Success: 696 case Sema::TDK_Invalid: 697 case Sema::TDK_InstantiationDepth: 698 case Sema::TDK_TooManyArguments: 699 case Sema::TDK_TooFewArguments: 700 case Sema::TDK_SubstitutionFailure: 701 case Sema::TDK_DeducedMismatch: 702 case Sema::TDK_NonDeducedMismatch: 703 case Sema::TDK_CUDATargetMismatch: 704 return TemplateParameter(); 705 706 case Sema::TDK_Incomplete: 707 case Sema::TDK_InvalidExplicitArguments: 708 return TemplateParameter::getFromOpaqueValue(Data); 709 710 case Sema::TDK_Inconsistent: 711 case Sema::TDK_Underqualified: 712 return static_cast<DFIParamWithArguments*>(Data)->Param; 713 714 // Unhandled 715 case Sema::TDK_MiscellaneousDeductionFailure: 716 break; 717 } 718 719 return TemplateParameter(); 720 } 721 722 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() { 723 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 724 case Sema::TDK_Success: 725 case Sema::TDK_Invalid: 726 case Sema::TDK_InstantiationDepth: 727 case Sema::TDK_TooManyArguments: 728 case Sema::TDK_TooFewArguments: 729 case Sema::TDK_Incomplete: 730 case Sema::TDK_InvalidExplicitArguments: 731 case Sema::TDK_Inconsistent: 732 case Sema::TDK_Underqualified: 733 case Sema::TDK_NonDeducedMismatch: 734 case Sema::TDK_CUDATargetMismatch: 735 return nullptr; 736 737 case Sema::TDK_DeducedMismatch: 738 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs; 739 740 case Sema::TDK_SubstitutionFailure: 741 return static_cast<TemplateArgumentList*>(Data); 742 743 // Unhandled 744 case Sema::TDK_MiscellaneousDeductionFailure: 745 break; 746 } 747 748 return nullptr; 749 } 750 751 const TemplateArgument *DeductionFailureInfo::getFirstArg() { 752 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 753 case Sema::TDK_Success: 754 case Sema::TDK_Invalid: 755 case Sema::TDK_InstantiationDepth: 756 case Sema::TDK_Incomplete: 757 case Sema::TDK_TooManyArguments: 758 case Sema::TDK_TooFewArguments: 759 case Sema::TDK_InvalidExplicitArguments: 760 case Sema::TDK_SubstitutionFailure: 761 case Sema::TDK_CUDATargetMismatch: 762 return nullptr; 763 764 case Sema::TDK_Inconsistent: 765 case Sema::TDK_Underqualified: 766 case Sema::TDK_DeducedMismatch: 767 case Sema::TDK_NonDeducedMismatch: 768 return &static_cast<DFIArguments*>(Data)->FirstArg; 769 770 // Unhandled 771 case Sema::TDK_MiscellaneousDeductionFailure: 772 break; 773 } 774 775 return nullptr; 776 } 777 778 const TemplateArgument *DeductionFailureInfo::getSecondArg() { 779 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 780 case Sema::TDK_Success: 781 case Sema::TDK_Invalid: 782 case Sema::TDK_InstantiationDepth: 783 case Sema::TDK_Incomplete: 784 case Sema::TDK_TooManyArguments: 785 case Sema::TDK_TooFewArguments: 786 case Sema::TDK_InvalidExplicitArguments: 787 case Sema::TDK_SubstitutionFailure: 788 case Sema::TDK_CUDATargetMismatch: 789 return nullptr; 790 791 case Sema::TDK_Inconsistent: 792 case Sema::TDK_Underqualified: 793 case Sema::TDK_DeducedMismatch: 794 case Sema::TDK_NonDeducedMismatch: 795 return &static_cast<DFIArguments*>(Data)->SecondArg; 796 797 // Unhandled 798 case Sema::TDK_MiscellaneousDeductionFailure: 799 break; 800 } 801 802 return nullptr; 803 } 804 805 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() { 806 if (static_cast<Sema::TemplateDeductionResult>(Result) == 807 Sema::TDK_DeducedMismatch) 808 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex; 809 810 return llvm::None; 811 } 812 813 void OverloadCandidateSet::destroyCandidates() { 814 for (iterator i = begin(), e = end(); i != e; ++i) { 815 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 816 i->Conversions[ii].~ImplicitConversionSequence(); 817 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction) 818 i->DeductionFailure.Destroy(); 819 } 820 } 821 822 void OverloadCandidateSet::clear() { 823 destroyCandidates(); 824 ConversionSequenceAllocator.Reset(); 825 NumInlineSequences = 0; 826 Candidates.clear(); 827 Functions.clear(); 828 } 829 830 namespace { 831 class UnbridgedCastsSet { 832 struct Entry { 833 Expr **Addr; 834 Expr *Saved; 835 }; 836 SmallVector<Entry, 2> Entries; 837 838 public: 839 void save(Sema &S, Expr *&E) { 840 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 841 Entry entry = { &E, E }; 842 Entries.push_back(entry); 843 E = S.stripARCUnbridgedCast(E); 844 } 845 846 void restore() { 847 for (SmallVectorImpl<Entry>::iterator 848 i = Entries.begin(), e = Entries.end(); i != e; ++i) 849 *i->Addr = i->Saved; 850 } 851 }; 852 } 853 854 /// checkPlaceholderForOverload - Do any interesting placeholder-like 855 /// preprocessing on the given expression. 856 /// 857 /// \param unbridgedCasts a collection to which to add unbridged casts; 858 /// without this, they will be immediately diagnosed as errors 859 /// 860 /// Return true on unrecoverable error. 861 static bool 862 checkPlaceholderForOverload(Sema &S, Expr *&E, 863 UnbridgedCastsSet *unbridgedCasts = nullptr) { 864 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 865 // We can't handle overloaded expressions here because overload 866 // resolution might reasonably tweak them. 867 if (placeholder->getKind() == BuiltinType::Overload) return false; 868 869 // If the context potentially accepts unbridged ARC casts, strip 870 // the unbridged cast and add it to the collection for later restoration. 871 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 872 unbridgedCasts) { 873 unbridgedCasts->save(S, E); 874 return false; 875 } 876 877 // Go ahead and check everything else. 878 ExprResult result = S.CheckPlaceholderExpr(E); 879 if (result.isInvalid()) 880 return true; 881 882 E = result.get(); 883 return false; 884 } 885 886 // Nothing to do. 887 return false; 888 } 889 890 /// checkArgPlaceholdersForOverload - Check a set of call operands for 891 /// placeholders. 892 static bool checkArgPlaceholdersForOverload(Sema &S, 893 MultiExprArg Args, 894 UnbridgedCastsSet &unbridged) { 895 for (unsigned i = 0, e = Args.size(); i != e; ++i) 896 if (checkPlaceholderForOverload(S, Args[i], &unbridged)) 897 return true; 898 899 return false; 900 } 901 902 // IsOverload - Determine whether the given New declaration is an 903 // overload of the declarations in Old. This routine returns false if 904 // New and Old cannot be overloaded, e.g., if New has the same 905 // signature as some function in Old (C++ 1.3.10) or if the Old 906 // declarations aren't functions (or function templates) at all. When 907 // it does return false, MatchedDecl will point to the decl that New 908 // cannot be overloaded with. This decl may be a UsingShadowDecl on 909 // top of the underlying declaration. 910 // 911 // Example: Given the following input: 912 // 913 // void f(int, float); // #1 914 // void f(int, int); // #2 915 // int f(int, int); // #3 916 // 917 // When we process #1, there is no previous declaration of "f", 918 // so IsOverload will not be used. 919 // 920 // When we process #2, Old contains only the FunctionDecl for #1. By 921 // comparing the parameter types, we see that #1 and #2 are overloaded 922 // (since they have different signatures), so this routine returns 923 // false; MatchedDecl is unchanged. 924 // 925 // When we process #3, Old is an overload set containing #1 and #2. We 926 // compare the signatures of #3 to #1 (they're overloaded, so we do 927 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 928 // identical (return types of functions are not part of the 929 // signature), IsOverload returns false and MatchedDecl will be set to 930 // point to the FunctionDecl for #2. 931 // 932 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 933 // into a class by a using declaration. The rules for whether to hide 934 // shadow declarations ignore some properties which otherwise figure 935 // into a function template's signature. 936 Sema::OverloadKind 937 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 938 NamedDecl *&Match, bool NewIsUsingDecl) { 939 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 940 I != E; ++I) { 941 NamedDecl *OldD = *I; 942 943 bool OldIsUsingDecl = false; 944 if (isa<UsingShadowDecl>(OldD)) { 945 OldIsUsingDecl = true; 946 947 // We can always introduce two using declarations into the same 948 // context, even if they have identical signatures. 949 if (NewIsUsingDecl) continue; 950 951 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 952 } 953 954 // A using-declaration does not conflict with another declaration 955 // if one of them is hidden. 956 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I)) 957 continue; 958 959 // If either declaration was introduced by a using declaration, 960 // we'll need to use slightly different rules for matching. 961 // Essentially, these rules are the normal rules, except that 962 // function templates hide function templates with different 963 // return types or template parameter lists. 964 bool UseMemberUsingDeclRules = 965 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() && 966 !New->getFriendObjectKind(); 967 968 if (FunctionDecl *OldF = OldD->getAsFunction()) { 969 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 970 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 971 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 972 continue; 973 } 974 975 if (!isa<FunctionTemplateDecl>(OldD) && 976 !shouldLinkPossiblyHiddenDecl(*I, New)) 977 continue; 978 979 Match = *I; 980 return Ovl_Match; 981 } 982 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) { 983 // We can overload with these, which can show up when doing 984 // redeclaration checks for UsingDecls. 985 assert(Old.getLookupKind() == LookupUsingDeclName); 986 } else if (isa<TagDecl>(OldD)) { 987 // We can always overload with tags by hiding them. 988 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) { 989 // Optimistically assume that an unresolved using decl will 990 // overload; if it doesn't, we'll have to diagnose during 991 // template instantiation. 992 // 993 // Exception: if the scope is dependent and this is not a class 994 // member, the using declaration can only introduce an enumerator. 995 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) { 996 Match = *I; 997 return Ovl_NonFunction; 998 } 999 } else { 1000 // (C++ 13p1): 1001 // Only function declarations can be overloaded; object and type 1002 // declarations cannot be overloaded. 1003 Match = *I; 1004 return Ovl_NonFunction; 1005 } 1006 } 1007 1008 return Ovl_Overload; 1009 } 1010 1011 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 1012 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) { 1013 // C++ [basic.start.main]p2: This function shall not be overloaded. 1014 if (New->isMain()) 1015 return false; 1016 1017 // MSVCRT user defined entry points cannot be overloaded. 1018 if (New->isMSVCRTEntryPoint()) 1019 return false; 1020 1021 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 1022 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 1023 1024 // C++ [temp.fct]p2: 1025 // A function template can be overloaded with other function templates 1026 // and with normal (non-template) functions. 1027 if ((OldTemplate == nullptr) != (NewTemplate == nullptr)) 1028 return true; 1029 1030 // Is the function New an overload of the function Old? 1031 QualType OldQType = Context.getCanonicalType(Old->getType()); 1032 QualType NewQType = Context.getCanonicalType(New->getType()); 1033 1034 // Compare the signatures (C++ 1.3.10) of the two functions to 1035 // determine whether they are overloads. If we find any mismatch 1036 // in the signature, they are overloads. 1037 1038 // If either of these functions is a K&R-style function (no 1039 // prototype), then we consider them to have matching signatures. 1040 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 1041 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 1042 return false; 1043 1044 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType); 1045 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType); 1046 1047 // The signature of a function includes the types of its 1048 // parameters (C++ 1.3.10), which includes the presence or absence 1049 // of the ellipsis; see C++ DR 357). 1050 if (OldQType != NewQType && 1051 (OldType->getNumParams() != NewType->getNumParams() || 1052 OldType->isVariadic() != NewType->isVariadic() || 1053 !FunctionParamTypesAreEqual(OldType, NewType))) 1054 return true; 1055 1056 // C++ [temp.over.link]p4: 1057 // The signature of a function template consists of its function 1058 // signature, its return type and its template parameter list. The names 1059 // of the template parameters are significant only for establishing the 1060 // relationship between the template parameters and the rest of the 1061 // signature. 1062 // 1063 // We check the return type and template parameter lists for function 1064 // templates first; the remaining checks follow. 1065 // 1066 // However, we don't consider either of these when deciding whether 1067 // a member introduced by a shadow declaration is hidden. 1068 if (!UseMemberUsingDeclRules && NewTemplate && 1069 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 1070 OldTemplate->getTemplateParameters(), 1071 false, TPL_TemplateMatch) || 1072 OldType->getReturnType() != NewType->getReturnType())) 1073 return true; 1074 1075 // If the function is a class member, its signature includes the 1076 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 1077 // 1078 // As part of this, also check whether one of the member functions 1079 // is static, in which case they are not overloads (C++ 1080 // 13.1p2). While not part of the definition of the signature, 1081 // this check is important to determine whether these functions 1082 // can be overloaded. 1083 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old); 1084 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New); 1085 if (OldMethod && NewMethod && 1086 !OldMethod->isStatic() && !NewMethod->isStatic()) { 1087 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) { 1088 if (!UseMemberUsingDeclRules && 1089 (OldMethod->getRefQualifier() == RQ_None || 1090 NewMethod->getRefQualifier() == RQ_None)) { 1091 // C++0x [over.load]p2: 1092 // - Member function declarations with the same name and the same 1093 // parameter-type-list as well as member function template 1094 // declarations with the same name, the same parameter-type-list, and 1095 // the same template parameter lists cannot be overloaded if any of 1096 // them, but not all, have a ref-qualifier (8.3.5). 1097 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 1098 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 1099 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 1100 } 1101 return true; 1102 } 1103 1104 // We may not have applied the implicit const for a constexpr member 1105 // function yet (because we haven't yet resolved whether this is a static 1106 // or non-static member function). Add it now, on the assumption that this 1107 // is a redeclaration of OldMethod. 1108 unsigned OldQuals = OldMethod->getTypeQualifiers(); 1109 unsigned NewQuals = NewMethod->getTypeQualifiers(); 1110 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() && 1111 !isa<CXXConstructorDecl>(NewMethod)) 1112 NewQuals |= Qualifiers::Const; 1113 1114 // We do not allow overloading based off of '__restrict'. 1115 OldQuals &= ~Qualifiers::Restrict; 1116 NewQuals &= ~Qualifiers::Restrict; 1117 if (OldQuals != NewQuals) 1118 return true; 1119 } 1120 1121 // Though pass_object_size is placed on parameters and takes an argument, we 1122 // consider it to be a function-level modifier for the sake of function 1123 // identity. Either the function has one or more parameters with 1124 // pass_object_size or it doesn't. 1125 if (functionHasPassObjectSizeParams(New) != 1126 functionHasPassObjectSizeParams(Old)) 1127 return true; 1128 1129 // enable_if attributes are an order-sensitive part of the signature. 1130 for (specific_attr_iterator<EnableIfAttr> 1131 NewI = New->specific_attr_begin<EnableIfAttr>(), 1132 NewE = New->specific_attr_end<EnableIfAttr>(), 1133 OldI = Old->specific_attr_begin<EnableIfAttr>(), 1134 OldE = Old->specific_attr_end<EnableIfAttr>(); 1135 NewI != NewE || OldI != OldE; ++NewI, ++OldI) { 1136 if (NewI == NewE || OldI == OldE) 1137 return true; 1138 llvm::FoldingSetNodeID NewID, OldID; 1139 NewI->getCond()->Profile(NewID, Context, true); 1140 OldI->getCond()->Profile(OldID, Context, true); 1141 if (NewID != OldID) 1142 return true; 1143 } 1144 1145 if (getLangOpts().CUDA && ConsiderCudaAttrs) { 1146 // Don't allow overloading of destructors. (In theory we could, but it 1147 // would be a giant change to clang.) 1148 if (isa<CXXDestructorDecl>(New)) 1149 return false; 1150 1151 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New), 1152 OldTarget = IdentifyCUDATarget(Old); 1153 if (NewTarget == CFT_InvalidTarget) 1154 return false; 1155 1156 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target."); 1157 1158 // Allow overloading of functions with same signature and different CUDA 1159 // target attributes. 1160 return NewTarget != OldTarget; 1161 } 1162 1163 // The signatures match; this is not an overload. 1164 return false; 1165 } 1166 1167 /// \brief Checks availability of the function depending on the current 1168 /// function context. Inside an unavailable function, unavailability is ignored. 1169 /// 1170 /// \returns true if \arg FD is unavailable and current context is inside 1171 /// an available function, false otherwise. 1172 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 1173 if (!FD->isUnavailable()) 1174 return false; 1175 1176 // Walk up the context of the caller. 1177 Decl *C = cast<Decl>(CurContext); 1178 do { 1179 if (C->isUnavailable()) 1180 return false; 1181 } while ((C = cast_or_null<Decl>(C->getDeclContext()))); 1182 return true; 1183 } 1184 1185 /// \brief Tries a user-defined conversion from From to ToType. 1186 /// 1187 /// Produces an implicit conversion sequence for when a standard conversion 1188 /// is not an option. See TryImplicitConversion for more information. 1189 static ImplicitConversionSequence 1190 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1191 bool SuppressUserConversions, 1192 bool AllowExplicit, 1193 bool InOverloadResolution, 1194 bool CStyle, 1195 bool AllowObjCWritebackConversion, 1196 bool AllowObjCConversionOnExplicit) { 1197 ImplicitConversionSequence ICS; 1198 1199 if (SuppressUserConversions) { 1200 // We're not in the case above, so there is no conversion that 1201 // we can perform. 1202 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1203 return ICS; 1204 } 1205 1206 // Attempt user-defined conversion. 1207 OverloadCandidateSet Conversions(From->getExprLoc(), 1208 OverloadCandidateSet::CSK_Normal); 1209 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, 1210 Conversions, AllowExplicit, 1211 AllowObjCConversionOnExplicit)) { 1212 case OR_Success: 1213 case OR_Deleted: 1214 ICS.setUserDefined(); 1215 // C++ [over.ics.user]p4: 1216 // A conversion of an expression of class type to the same class 1217 // type is given Exact Match rank, and a conversion of an 1218 // expression of class type to a base class of that type is 1219 // given Conversion rank, in spite of the fact that a copy 1220 // constructor (i.e., a user-defined conversion function) is 1221 // called for those cases. 1222 if (CXXConstructorDecl *Constructor 1223 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1224 QualType FromCanon 1225 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1226 QualType ToCanon 1227 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1228 if (Constructor->isCopyConstructor() && 1229 (FromCanon == ToCanon || 1230 S.IsDerivedFrom(From->getLocStart(), FromCanon, ToCanon))) { 1231 // Turn this into a "standard" conversion sequence, so that it 1232 // gets ranked with standard conversion sequences. 1233 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction; 1234 ICS.setStandard(); 1235 ICS.Standard.setAsIdentityConversion(); 1236 ICS.Standard.setFromType(From->getType()); 1237 ICS.Standard.setAllToTypes(ToType); 1238 ICS.Standard.CopyConstructor = Constructor; 1239 ICS.Standard.FoundCopyConstructor = Found; 1240 if (ToCanon != FromCanon) 1241 ICS.Standard.Second = ICK_Derived_To_Base; 1242 } 1243 } 1244 break; 1245 1246 case OR_Ambiguous: 1247 ICS.setAmbiguous(); 1248 ICS.Ambiguous.setFromType(From->getType()); 1249 ICS.Ambiguous.setToType(ToType); 1250 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1251 Cand != Conversions.end(); ++Cand) 1252 if (Cand->Viable) 1253 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 1254 break; 1255 1256 // Fall through. 1257 case OR_No_Viable_Function: 1258 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1259 break; 1260 } 1261 1262 return ICS; 1263 } 1264 1265 /// TryImplicitConversion - Attempt to perform an implicit conversion 1266 /// from the given expression (Expr) to the given type (ToType). This 1267 /// function returns an implicit conversion sequence that can be used 1268 /// to perform the initialization. Given 1269 /// 1270 /// void f(float f); 1271 /// void g(int i) { f(i); } 1272 /// 1273 /// this routine would produce an implicit conversion sequence to 1274 /// describe the initialization of f from i, which will be a standard 1275 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1276 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1277 // 1278 /// Note that this routine only determines how the conversion can be 1279 /// performed; it does not actually perform the conversion. As such, 1280 /// it will not produce any diagnostics if no conversion is available, 1281 /// but will instead return an implicit conversion sequence of kind 1282 /// "BadConversion". 1283 /// 1284 /// If @p SuppressUserConversions, then user-defined conversions are 1285 /// not permitted. 1286 /// If @p AllowExplicit, then explicit user-defined conversions are 1287 /// permitted. 1288 /// 1289 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1290 /// writeback conversion, which allows __autoreleasing id* parameters to 1291 /// be initialized with __strong id* or __weak id* arguments. 1292 static ImplicitConversionSequence 1293 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1294 bool SuppressUserConversions, 1295 bool AllowExplicit, 1296 bool InOverloadResolution, 1297 bool CStyle, 1298 bool AllowObjCWritebackConversion, 1299 bool AllowObjCConversionOnExplicit) { 1300 ImplicitConversionSequence ICS; 1301 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1302 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1303 ICS.setStandard(); 1304 return ICS; 1305 } 1306 1307 if (!S.getLangOpts().CPlusPlus) { 1308 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1309 return ICS; 1310 } 1311 1312 // C++ [over.ics.user]p4: 1313 // A conversion of an expression of class type to the same class 1314 // type is given Exact Match rank, and a conversion of an 1315 // expression of class type to a base class of that type is 1316 // given Conversion rank, in spite of the fact that a copy/move 1317 // constructor (i.e., a user-defined conversion function) is 1318 // called for those cases. 1319 QualType FromType = From->getType(); 1320 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1321 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1322 S.IsDerivedFrom(From->getLocStart(), FromType, ToType))) { 1323 ICS.setStandard(); 1324 ICS.Standard.setAsIdentityConversion(); 1325 ICS.Standard.setFromType(FromType); 1326 ICS.Standard.setAllToTypes(ToType); 1327 1328 // We don't actually check at this point whether there is a valid 1329 // copy/move constructor, since overloading just assumes that it 1330 // exists. When we actually perform initialization, we'll find the 1331 // appropriate constructor to copy the returned object, if needed. 1332 ICS.Standard.CopyConstructor = nullptr; 1333 1334 // Determine whether this is considered a derived-to-base conversion. 1335 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1336 ICS.Standard.Second = ICK_Derived_To_Base; 1337 1338 return ICS; 1339 } 1340 1341 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1342 AllowExplicit, InOverloadResolution, CStyle, 1343 AllowObjCWritebackConversion, 1344 AllowObjCConversionOnExplicit); 1345 } 1346 1347 ImplicitConversionSequence 1348 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1349 bool SuppressUserConversions, 1350 bool AllowExplicit, 1351 bool InOverloadResolution, 1352 bool CStyle, 1353 bool AllowObjCWritebackConversion) { 1354 return ::TryImplicitConversion(*this, From, ToType, 1355 SuppressUserConversions, AllowExplicit, 1356 InOverloadResolution, CStyle, 1357 AllowObjCWritebackConversion, 1358 /*AllowObjCConversionOnExplicit=*/false); 1359 } 1360 1361 /// PerformImplicitConversion - Perform an implicit conversion of the 1362 /// expression From to the type ToType. Returns the 1363 /// converted expression. Flavor is the kind of conversion we're 1364 /// performing, used in the error message. If @p AllowExplicit, 1365 /// explicit user-defined conversions are permitted. 1366 ExprResult 1367 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1368 AssignmentAction Action, bool AllowExplicit) { 1369 ImplicitConversionSequence ICS; 1370 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1371 } 1372 1373 ExprResult 1374 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1375 AssignmentAction Action, bool AllowExplicit, 1376 ImplicitConversionSequence& ICS) { 1377 if (checkPlaceholderForOverload(*this, From)) 1378 return ExprError(); 1379 1380 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1381 bool AllowObjCWritebackConversion 1382 = getLangOpts().ObjCAutoRefCount && 1383 (Action == AA_Passing || Action == AA_Sending); 1384 if (getLangOpts().ObjC1) 1385 CheckObjCBridgeRelatedConversions(From->getLocStart(), 1386 ToType, From->getType(), From); 1387 ICS = ::TryImplicitConversion(*this, From, ToType, 1388 /*SuppressUserConversions=*/false, 1389 AllowExplicit, 1390 /*InOverloadResolution=*/false, 1391 /*CStyle=*/false, 1392 AllowObjCWritebackConversion, 1393 /*AllowObjCConversionOnExplicit=*/false); 1394 return PerformImplicitConversion(From, ToType, ICS, Action); 1395 } 1396 1397 /// \brief Determine whether the conversion from FromType to ToType is a valid 1398 /// conversion that strips "noexcept" or "noreturn" off the nested function 1399 /// type. 1400 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType, 1401 QualType &ResultTy) { 1402 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1403 return false; 1404 1405 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1406 // or F(t noexcept) -> F(t) 1407 // where F adds one of the following at most once: 1408 // - a pointer 1409 // - a member pointer 1410 // - a block pointer 1411 // Changes here need matching changes in FindCompositePointerType. 1412 CanQualType CanTo = Context.getCanonicalType(ToType); 1413 CanQualType CanFrom = Context.getCanonicalType(FromType); 1414 Type::TypeClass TyClass = CanTo->getTypeClass(); 1415 if (TyClass != CanFrom->getTypeClass()) return false; 1416 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1417 if (TyClass == Type::Pointer) { 1418 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1419 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1420 } else if (TyClass == Type::BlockPointer) { 1421 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1422 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1423 } else if (TyClass == Type::MemberPointer) { 1424 auto ToMPT = CanTo.getAs<MemberPointerType>(); 1425 auto FromMPT = CanFrom.getAs<MemberPointerType>(); 1426 // A function pointer conversion cannot change the class of the function. 1427 if (ToMPT->getClass() != FromMPT->getClass()) 1428 return false; 1429 CanTo = ToMPT->getPointeeType(); 1430 CanFrom = FromMPT->getPointeeType(); 1431 } else { 1432 return false; 1433 } 1434 1435 TyClass = CanTo->getTypeClass(); 1436 if (TyClass != CanFrom->getTypeClass()) return false; 1437 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1438 return false; 1439 } 1440 1441 const auto *FromFn = cast<FunctionType>(CanFrom); 1442 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo(); 1443 1444 const auto *ToFn = cast<FunctionType>(CanTo); 1445 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo(); 1446 1447 bool Changed = false; 1448 1449 // Drop 'noreturn' if not present in target type. 1450 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) { 1451 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false)); 1452 Changed = true; 1453 } 1454 1455 // Drop 'noexcept' if not present in target type. 1456 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) { 1457 const auto *ToFPT = cast<FunctionProtoType>(ToFn); 1458 if (FromFPT->isNothrow(Context) && !ToFPT->isNothrow(Context)) { 1459 FromFn = cast<FunctionType>( 1460 Context.getFunctionType(FromFPT->getReturnType(), 1461 FromFPT->getParamTypes(), 1462 FromFPT->getExtProtoInfo().withExceptionSpec( 1463 FunctionProtoType::ExceptionSpecInfo())) 1464 .getTypePtr()); 1465 Changed = true; 1466 } 1467 } 1468 1469 if (!Changed) 1470 return false; 1471 1472 assert(QualType(FromFn, 0).isCanonical()); 1473 if (QualType(FromFn, 0) != CanTo) return false; 1474 1475 ResultTy = ToType; 1476 return true; 1477 } 1478 1479 /// \brief Determine whether the conversion from FromType to ToType is a valid 1480 /// vector conversion. 1481 /// 1482 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1483 /// conversion. 1484 static bool IsVectorConversion(Sema &S, QualType FromType, 1485 QualType ToType, ImplicitConversionKind &ICK) { 1486 // We need at least one of these types to be a vector type to have a vector 1487 // conversion. 1488 if (!ToType->isVectorType() && !FromType->isVectorType()) 1489 return false; 1490 1491 // Identical types require no conversions. 1492 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) 1493 return false; 1494 1495 // There are no conversions between extended vector types, only identity. 1496 if (ToType->isExtVectorType()) { 1497 // There are no conversions between extended vector types other than the 1498 // identity conversion. 1499 if (FromType->isExtVectorType()) 1500 return false; 1501 1502 // Vector splat from any arithmetic type to a vector. 1503 if (FromType->isArithmeticType()) { 1504 ICK = ICK_Vector_Splat; 1505 return true; 1506 } 1507 } 1508 1509 // We can perform the conversion between vector types in the following cases: 1510 // 1)vector types are equivalent AltiVec and GCC vector types 1511 // 2)lax vector conversions are permitted and the vector types are of the 1512 // same size 1513 if (ToType->isVectorType() && FromType->isVectorType()) { 1514 if (S.Context.areCompatibleVectorTypes(FromType, ToType) || 1515 S.isLaxVectorConversion(FromType, ToType)) { 1516 ICK = ICK_Vector_Conversion; 1517 return true; 1518 } 1519 } 1520 1521 return false; 1522 } 1523 1524 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1525 bool InOverloadResolution, 1526 StandardConversionSequence &SCS, 1527 bool CStyle); 1528 1529 /// IsStandardConversion - Determines whether there is a standard 1530 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1531 /// expression From to the type ToType. Standard conversion sequences 1532 /// only consider non-class types; for conversions that involve class 1533 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1534 /// contain the standard conversion sequence required to perform this 1535 /// conversion and this routine will return true. Otherwise, this 1536 /// routine will return false and the value of SCS is unspecified. 1537 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1538 bool InOverloadResolution, 1539 StandardConversionSequence &SCS, 1540 bool CStyle, 1541 bool AllowObjCWritebackConversion) { 1542 QualType FromType = From->getType(); 1543 1544 // Standard conversions (C++ [conv]) 1545 SCS.setAsIdentityConversion(); 1546 SCS.IncompatibleObjC = false; 1547 SCS.setFromType(FromType); 1548 SCS.CopyConstructor = nullptr; 1549 1550 // There are no standard conversions for class types in C++, so 1551 // abort early. When overloading in C, however, we do permit them. 1552 if (S.getLangOpts().CPlusPlus && 1553 (FromType->isRecordType() || ToType->isRecordType())) 1554 return false; 1555 1556 // The first conversion can be an lvalue-to-rvalue conversion, 1557 // array-to-pointer conversion, or function-to-pointer conversion 1558 // (C++ 4p1). 1559 1560 if (FromType == S.Context.OverloadTy) { 1561 DeclAccessPair AccessPair; 1562 if (FunctionDecl *Fn 1563 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1564 AccessPair)) { 1565 // We were able to resolve the address of the overloaded function, 1566 // so we can convert to the type of that function. 1567 FromType = Fn->getType(); 1568 SCS.setFromType(FromType); 1569 1570 // we can sometimes resolve &foo<int> regardless of ToType, so check 1571 // if the type matches (identity) or we are converting to bool 1572 if (!S.Context.hasSameUnqualifiedType( 1573 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1574 QualType resultTy; 1575 // if the function type matches except for [[noreturn]], it's ok 1576 if (!S.IsFunctionConversion(FromType, 1577 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1578 // otherwise, only a boolean conversion is standard 1579 if (!ToType->isBooleanType()) 1580 return false; 1581 } 1582 1583 // Check if the "from" expression is taking the address of an overloaded 1584 // function and recompute the FromType accordingly. Take advantage of the 1585 // fact that non-static member functions *must* have such an address-of 1586 // expression. 1587 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1588 if (Method && !Method->isStatic()) { 1589 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1590 "Non-unary operator on non-static member address"); 1591 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1592 == UO_AddrOf && 1593 "Non-address-of operator on non-static member address"); 1594 const Type *ClassType 1595 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1596 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1597 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1598 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1599 UO_AddrOf && 1600 "Non-address-of operator for overloaded function expression"); 1601 FromType = S.Context.getPointerType(FromType); 1602 } 1603 1604 // Check that we've computed the proper type after overload resolution. 1605 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't 1606 // be calling it from within an NDEBUG block. 1607 assert(S.Context.hasSameType( 1608 FromType, 1609 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1610 } else { 1611 return false; 1612 } 1613 } 1614 // Lvalue-to-rvalue conversion (C++11 4.1): 1615 // A glvalue (3.10) of a non-function, non-array type T can 1616 // be converted to a prvalue. 1617 bool argIsLValue = From->isGLValue(); 1618 if (argIsLValue && 1619 !FromType->isFunctionType() && !FromType->isArrayType() && 1620 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1621 SCS.First = ICK_Lvalue_To_Rvalue; 1622 1623 // C11 6.3.2.1p2: 1624 // ... if the lvalue has atomic type, the value has the non-atomic version 1625 // of the type of the lvalue ... 1626 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1627 FromType = Atomic->getValueType(); 1628 1629 // If T is a non-class type, the type of the rvalue is the 1630 // cv-unqualified version of T. Otherwise, the type of the rvalue 1631 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1632 // just strip the qualifiers because they don't matter. 1633 FromType = FromType.getUnqualifiedType(); 1634 } else if (FromType->isArrayType()) { 1635 // Array-to-pointer conversion (C++ 4.2) 1636 SCS.First = ICK_Array_To_Pointer; 1637 1638 // An lvalue or rvalue of type "array of N T" or "array of unknown 1639 // bound of T" can be converted to an rvalue of type "pointer to 1640 // T" (C++ 4.2p1). 1641 FromType = S.Context.getArrayDecayedType(FromType); 1642 1643 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1644 // This conversion is deprecated in C++03 (D.4) 1645 SCS.DeprecatedStringLiteralToCharPtr = true; 1646 1647 // For the purpose of ranking in overload resolution 1648 // (13.3.3.1.1), this conversion is considered an 1649 // array-to-pointer conversion followed by a qualification 1650 // conversion (4.4). (C++ 4.2p2) 1651 SCS.Second = ICK_Identity; 1652 SCS.Third = ICK_Qualification; 1653 SCS.QualificationIncludesObjCLifetime = false; 1654 SCS.setAllToTypes(FromType); 1655 return true; 1656 } 1657 } else if (FromType->isFunctionType() && argIsLValue) { 1658 // Function-to-pointer conversion (C++ 4.3). 1659 SCS.First = ICK_Function_To_Pointer; 1660 1661 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts())) 1662 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl())) 1663 if (!S.checkAddressOfFunctionIsAvailable(FD)) 1664 return false; 1665 1666 // An lvalue of function type T can be converted to an rvalue of 1667 // type "pointer to T." The result is a pointer to the 1668 // function. (C++ 4.3p1). 1669 FromType = S.Context.getPointerType(FromType); 1670 } else { 1671 // We don't require any conversions for the first step. 1672 SCS.First = ICK_Identity; 1673 } 1674 SCS.setToType(0, FromType); 1675 1676 // The second conversion can be an integral promotion, floating 1677 // point promotion, integral conversion, floating point conversion, 1678 // floating-integral conversion, pointer conversion, 1679 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1680 // For overloading in C, this can also be a "compatible-type" 1681 // conversion. 1682 bool IncompatibleObjC = false; 1683 ImplicitConversionKind SecondICK = ICK_Identity; 1684 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1685 // The unqualified versions of the types are the same: there's no 1686 // conversion to do. 1687 SCS.Second = ICK_Identity; 1688 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1689 // Integral promotion (C++ 4.5). 1690 SCS.Second = ICK_Integral_Promotion; 1691 FromType = ToType.getUnqualifiedType(); 1692 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1693 // Floating point promotion (C++ 4.6). 1694 SCS.Second = ICK_Floating_Promotion; 1695 FromType = ToType.getUnqualifiedType(); 1696 } else if (S.IsComplexPromotion(FromType, ToType)) { 1697 // Complex promotion (Clang extension) 1698 SCS.Second = ICK_Complex_Promotion; 1699 FromType = ToType.getUnqualifiedType(); 1700 } else if (ToType->isBooleanType() && 1701 (FromType->isArithmeticType() || 1702 FromType->isAnyPointerType() || 1703 FromType->isBlockPointerType() || 1704 FromType->isMemberPointerType() || 1705 FromType->isNullPtrType())) { 1706 // Boolean conversions (C++ 4.12). 1707 SCS.Second = ICK_Boolean_Conversion; 1708 FromType = S.Context.BoolTy; 1709 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1710 ToType->isIntegralType(S.Context)) { 1711 // Integral conversions (C++ 4.7). 1712 SCS.Second = ICK_Integral_Conversion; 1713 FromType = ToType.getUnqualifiedType(); 1714 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) { 1715 // Complex conversions (C99 6.3.1.6) 1716 SCS.Second = ICK_Complex_Conversion; 1717 FromType = ToType.getUnqualifiedType(); 1718 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1719 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1720 // Complex-real conversions (C99 6.3.1.7) 1721 SCS.Second = ICK_Complex_Real; 1722 FromType = ToType.getUnqualifiedType(); 1723 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1724 // FIXME: disable conversions between long double and __float128 if 1725 // their representation is different until there is back end support 1726 // We of course allow this conversion if long double is really double. 1727 if (&S.Context.getFloatTypeSemantics(FromType) != 1728 &S.Context.getFloatTypeSemantics(ToType)) { 1729 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty && 1730 ToType == S.Context.LongDoubleTy) || 1731 (FromType == S.Context.LongDoubleTy && 1732 ToType == S.Context.Float128Ty)); 1733 if (Float128AndLongDouble && 1734 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) != 1735 &llvm::APFloat::IEEEdouble())) 1736 return false; 1737 } 1738 // Floating point conversions (C++ 4.8). 1739 SCS.Second = ICK_Floating_Conversion; 1740 FromType = ToType.getUnqualifiedType(); 1741 } else if ((FromType->isRealFloatingType() && 1742 ToType->isIntegralType(S.Context)) || 1743 (FromType->isIntegralOrUnscopedEnumerationType() && 1744 ToType->isRealFloatingType())) { 1745 // Floating-integral conversions (C++ 4.9). 1746 SCS.Second = ICK_Floating_Integral; 1747 FromType = ToType.getUnqualifiedType(); 1748 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1749 SCS.Second = ICK_Block_Pointer_Conversion; 1750 } else if (AllowObjCWritebackConversion && 1751 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1752 SCS.Second = ICK_Writeback_Conversion; 1753 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1754 FromType, IncompatibleObjC)) { 1755 // Pointer conversions (C++ 4.10). 1756 SCS.Second = ICK_Pointer_Conversion; 1757 SCS.IncompatibleObjC = IncompatibleObjC; 1758 FromType = FromType.getUnqualifiedType(); 1759 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1760 InOverloadResolution, FromType)) { 1761 // Pointer to member conversions (4.11). 1762 SCS.Second = ICK_Pointer_Member; 1763 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) { 1764 SCS.Second = SecondICK; 1765 FromType = ToType.getUnqualifiedType(); 1766 } else if (!S.getLangOpts().CPlusPlus && 1767 S.Context.typesAreCompatible(ToType, FromType)) { 1768 // Compatible conversions (Clang extension for C function overloading) 1769 SCS.Second = ICK_Compatible_Conversion; 1770 FromType = ToType.getUnqualifiedType(); 1771 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1772 InOverloadResolution, 1773 SCS, CStyle)) { 1774 SCS.Second = ICK_TransparentUnionConversion; 1775 FromType = ToType; 1776 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1777 CStyle)) { 1778 // tryAtomicConversion has updated the standard conversion sequence 1779 // appropriately. 1780 return true; 1781 } else if (ToType->isEventT() && 1782 From->isIntegerConstantExpr(S.getASTContext()) && 1783 From->EvaluateKnownConstInt(S.getASTContext()) == 0) { 1784 SCS.Second = ICK_Zero_Event_Conversion; 1785 FromType = ToType; 1786 } else if (ToType->isQueueT() && 1787 From->isIntegerConstantExpr(S.getASTContext()) && 1788 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) { 1789 SCS.Second = ICK_Zero_Queue_Conversion; 1790 FromType = ToType; 1791 } else { 1792 // No second conversion required. 1793 SCS.Second = ICK_Identity; 1794 } 1795 SCS.setToType(1, FromType); 1796 1797 // The third conversion can be a function pointer conversion or a 1798 // qualification conversion (C++ [conv.fctptr], [conv.qual]). 1799 bool ObjCLifetimeConversion; 1800 if (S.IsFunctionConversion(FromType, ToType, FromType)) { 1801 // Function pointer conversions (removing 'noexcept') including removal of 1802 // 'noreturn' (Clang extension). 1803 SCS.Third = ICK_Function_Conversion; 1804 } else if (S.IsQualificationConversion(FromType, ToType, CStyle, 1805 ObjCLifetimeConversion)) { 1806 SCS.Third = ICK_Qualification; 1807 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1808 FromType = ToType; 1809 } else { 1810 // No conversion required 1811 SCS.Third = ICK_Identity; 1812 } 1813 1814 // C++ [over.best.ics]p6: 1815 // [...] Any difference in top-level cv-qualification is 1816 // subsumed by the initialization itself and does not constitute 1817 // a conversion. [...] 1818 QualType CanonFrom = S.Context.getCanonicalType(FromType); 1819 QualType CanonTo = S.Context.getCanonicalType(ToType); 1820 if (CanonFrom.getLocalUnqualifiedType() 1821 == CanonTo.getLocalUnqualifiedType() && 1822 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) { 1823 FromType = ToType; 1824 CanonFrom = CanonTo; 1825 } 1826 1827 SCS.setToType(2, FromType); 1828 1829 if (CanonFrom == CanonTo) 1830 return true; 1831 1832 // If we have not converted the argument type to the parameter type, 1833 // this is a bad conversion sequence, unless we're resolving an overload in C. 1834 if (S.getLangOpts().CPlusPlus || !InOverloadResolution) 1835 return false; 1836 1837 ExprResult ER = ExprResult{From}; 1838 Sema::AssignConvertType Conv = 1839 S.CheckSingleAssignmentConstraints(ToType, ER, 1840 /*Diagnose=*/false, 1841 /*DiagnoseCFAudited=*/false, 1842 /*ConvertRHS=*/false); 1843 ImplicitConversionKind SecondConv; 1844 switch (Conv) { 1845 case Sema::Compatible: 1846 SecondConv = ICK_C_Only_Conversion; 1847 break; 1848 // For our purposes, discarding qualifiers is just as bad as using an 1849 // incompatible pointer. Note that an IncompatiblePointer conversion can drop 1850 // qualifiers, as well. 1851 case Sema::CompatiblePointerDiscardsQualifiers: 1852 case Sema::IncompatiblePointer: 1853 case Sema::IncompatiblePointerSign: 1854 SecondConv = ICK_Incompatible_Pointer_Conversion; 1855 break; 1856 default: 1857 return false; 1858 } 1859 1860 // First can only be an lvalue conversion, so we pretend that this was the 1861 // second conversion. First should already be valid from earlier in the 1862 // function. 1863 SCS.Second = SecondConv; 1864 SCS.setToType(1, ToType); 1865 1866 // Third is Identity, because Second should rank us worse than any other 1867 // conversion. This could also be ICK_Qualification, but it's simpler to just 1868 // lump everything in with the second conversion, and we don't gain anything 1869 // from making this ICK_Qualification. 1870 SCS.Third = ICK_Identity; 1871 SCS.setToType(2, ToType); 1872 return true; 1873 } 1874 1875 static bool 1876 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1877 QualType &ToType, 1878 bool InOverloadResolution, 1879 StandardConversionSequence &SCS, 1880 bool CStyle) { 1881 1882 const RecordType *UT = ToType->getAsUnionType(); 1883 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1884 return false; 1885 // The field to initialize within the transparent union. 1886 RecordDecl *UD = UT->getDecl(); 1887 // It's compatible if the expression matches any of the fields. 1888 for (const auto *it : UD->fields()) { 1889 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1890 CStyle, /*ObjCWritebackConversion=*/false)) { 1891 ToType = it->getType(); 1892 return true; 1893 } 1894 } 1895 return false; 1896 } 1897 1898 /// IsIntegralPromotion - Determines whether the conversion from the 1899 /// expression From (whose potentially-adjusted type is FromType) to 1900 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1901 /// sets PromotedType to the promoted type. 1902 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1903 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1904 // All integers are built-in. 1905 if (!To) { 1906 return false; 1907 } 1908 1909 // An rvalue of type char, signed char, unsigned char, short int, or 1910 // unsigned short int can be converted to an rvalue of type int if 1911 // int can represent all the values of the source type; otherwise, 1912 // the source rvalue can be converted to an rvalue of type unsigned 1913 // int (C++ 4.5p1). 1914 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1915 !FromType->isEnumeralType()) { 1916 if (// We can promote any signed, promotable integer type to an int 1917 (FromType->isSignedIntegerType() || 1918 // We can promote any unsigned integer type whose size is 1919 // less than int to an int. 1920 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) { 1921 return To->getKind() == BuiltinType::Int; 1922 } 1923 1924 return To->getKind() == BuiltinType::UInt; 1925 } 1926 1927 // C++11 [conv.prom]p3: 1928 // A prvalue of an unscoped enumeration type whose underlying type is not 1929 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1930 // following types that can represent all the values of the enumeration 1931 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1932 // unsigned int, long int, unsigned long int, long long int, or unsigned 1933 // long long int. If none of the types in that list can represent all the 1934 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1935 // type can be converted to an rvalue a prvalue of the extended integer type 1936 // with lowest integer conversion rank (4.13) greater than the rank of long 1937 // long in which all the values of the enumeration can be represented. If 1938 // there are two such extended types, the signed one is chosen. 1939 // C++11 [conv.prom]p4: 1940 // A prvalue of an unscoped enumeration type whose underlying type is fixed 1941 // can be converted to a prvalue of its underlying type. Moreover, if 1942 // integral promotion can be applied to its underlying type, a prvalue of an 1943 // unscoped enumeration type whose underlying type is fixed can also be 1944 // converted to a prvalue of the promoted underlying type. 1945 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1946 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1947 // provided for a scoped enumeration. 1948 if (FromEnumType->getDecl()->isScoped()) 1949 return false; 1950 1951 // We can perform an integral promotion to the underlying type of the enum, 1952 // even if that's not the promoted type. Note that the check for promoting 1953 // the underlying type is based on the type alone, and does not consider 1954 // the bitfield-ness of the actual source expression. 1955 if (FromEnumType->getDecl()->isFixed()) { 1956 QualType Underlying = FromEnumType->getDecl()->getIntegerType(); 1957 return Context.hasSameUnqualifiedType(Underlying, ToType) || 1958 IsIntegralPromotion(nullptr, Underlying, ToType); 1959 } 1960 1961 // We have already pre-calculated the promotion type, so this is trivial. 1962 if (ToType->isIntegerType() && 1963 isCompleteType(From->getLocStart(), FromType)) 1964 return Context.hasSameUnqualifiedType( 1965 ToType, FromEnumType->getDecl()->getPromotionType()); 1966 } 1967 1968 // C++0x [conv.prom]p2: 1969 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1970 // to an rvalue a prvalue of the first of the following types that can 1971 // represent all the values of its underlying type: int, unsigned int, 1972 // long int, unsigned long int, long long int, or unsigned long long int. 1973 // If none of the types in that list can represent all the values of its 1974 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1975 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1976 // type. 1977 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1978 ToType->isIntegerType()) { 1979 // Determine whether the type we're converting from is signed or 1980 // unsigned. 1981 bool FromIsSigned = FromType->isSignedIntegerType(); 1982 uint64_t FromSize = Context.getTypeSize(FromType); 1983 1984 // The types we'll try to promote to, in the appropriate 1985 // order. Try each of these types. 1986 QualType PromoteTypes[6] = { 1987 Context.IntTy, Context.UnsignedIntTy, 1988 Context.LongTy, Context.UnsignedLongTy , 1989 Context.LongLongTy, Context.UnsignedLongLongTy 1990 }; 1991 for (int Idx = 0; Idx < 6; ++Idx) { 1992 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1993 if (FromSize < ToSize || 1994 (FromSize == ToSize && 1995 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1996 // We found the type that we can promote to. If this is the 1997 // type we wanted, we have a promotion. Otherwise, no 1998 // promotion. 1999 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 2000 } 2001 } 2002 } 2003 2004 // An rvalue for an integral bit-field (9.6) can be converted to an 2005 // rvalue of type int if int can represent all the values of the 2006 // bit-field; otherwise, it can be converted to unsigned int if 2007 // unsigned int can represent all the values of the bit-field. If 2008 // the bit-field is larger yet, no integral promotion applies to 2009 // it. If the bit-field has an enumerated type, it is treated as any 2010 // other value of that type for promotion purposes (C++ 4.5p3). 2011 // FIXME: We should delay checking of bit-fields until we actually perform the 2012 // conversion. 2013 if (From) { 2014 if (FieldDecl *MemberDecl = From->getSourceBitField()) { 2015 llvm::APSInt BitWidth; 2016 if (FromType->isIntegralType(Context) && 2017 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 2018 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 2019 ToSize = Context.getTypeSize(ToType); 2020 2021 // Are we promoting to an int from a bitfield that fits in an int? 2022 if (BitWidth < ToSize || 2023 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 2024 return To->getKind() == BuiltinType::Int; 2025 } 2026 2027 // Are we promoting to an unsigned int from an unsigned bitfield 2028 // that fits into an unsigned int? 2029 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 2030 return To->getKind() == BuiltinType::UInt; 2031 } 2032 2033 return false; 2034 } 2035 } 2036 } 2037 2038 // An rvalue of type bool can be converted to an rvalue of type int, 2039 // with false becoming zero and true becoming one (C++ 4.5p4). 2040 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 2041 return true; 2042 } 2043 2044 return false; 2045 } 2046 2047 /// IsFloatingPointPromotion - Determines whether the conversion from 2048 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 2049 /// returns true and sets PromotedType to the promoted type. 2050 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 2051 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 2052 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 2053 /// An rvalue of type float can be converted to an rvalue of type 2054 /// double. (C++ 4.6p1). 2055 if (FromBuiltin->getKind() == BuiltinType::Float && 2056 ToBuiltin->getKind() == BuiltinType::Double) 2057 return true; 2058 2059 // C99 6.3.1.5p1: 2060 // When a float is promoted to double or long double, or a 2061 // double is promoted to long double [...]. 2062 if (!getLangOpts().CPlusPlus && 2063 (FromBuiltin->getKind() == BuiltinType::Float || 2064 FromBuiltin->getKind() == BuiltinType::Double) && 2065 (ToBuiltin->getKind() == BuiltinType::LongDouble || 2066 ToBuiltin->getKind() == BuiltinType::Float128)) 2067 return true; 2068 2069 // Half can be promoted to float. 2070 if (!getLangOpts().NativeHalfType && 2071 FromBuiltin->getKind() == BuiltinType::Half && 2072 ToBuiltin->getKind() == BuiltinType::Float) 2073 return true; 2074 } 2075 2076 return false; 2077 } 2078 2079 /// \brief Determine if a conversion is a complex promotion. 2080 /// 2081 /// A complex promotion is defined as a complex -> complex conversion 2082 /// where the conversion between the underlying real types is a 2083 /// floating-point or integral promotion. 2084 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 2085 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 2086 if (!FromComplex) 2087 return false; 2088 2089 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 2090 if (!ToComplex) 2091 return false; 2092 2093 return IsFloatingPointPromotion(FromComplex->getElementType(), 2094 ToComplex->getElementType()) || 2095 IsIntegralPromotion(nullptr, FromComplex->getElementType(), 2096 ToComplex->getElementType()); 2097 } 2098 2099 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 2100 /// the pointer type FromPtr to a pointer to type ToPointee, with the 2101 /// same type qualifiers as FromPtr has on its pointee type. ToType, 2102 /// if non-empty, will be a pointer to ToType that may or may not have 2103 /// the right set of qualifiers on its pointee. 2104 /// 2105 static QualType 2106 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 2107 QualType ToPointee, QualType ToType, 2108 ASTContext &Context, 2109 bool StripObjCLifetime = false) { 2110 assert((FromPtr->getTypeClass() == Type::Pointer || 2111 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 2112 "Invalid similarly-qualified pointer type"); 2113 2114 /// Conversions to 'id' subsume cv-qualifier conversions. 2115 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 2116 return ToType.getUnqualifiedType(); 2117 2118 QualType CanonFromPointee 2119 = Context.getCanonicalType(FromPtr->getPointeeType()); 2120 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 2121 Qualifiers Quals = CanonFromPointee.getQualifiers(); 2122 2123 if (StripObjCLifetime) 2124 Quals.removeObjCLifetime(); 2125 2126 // Exact qualifier match -> return the pointer type we're converting to. 2127 if (CanonToPointee.getLocalQualifiers() == Quals) { 2128 // ToType is exactly what we need. Return it. 2129 if (!ToType.isNull()) 2130 return ToType.getUnqualifiedType(); 2131 2132 // Build a pointer to ToPointee. It has the right qualifiers 2133 // already. 2134 if (isa<ObjCObjectPointerType>(ToType)) 2135 return Context.getObjCObjectPointerType(ToPointee); 2136 return Context.getPointerType(ToPointee); 2137 } 2138 2139 // Just build a canonical type that has the right qualifiers. 2140 QualType QualifiedCanonToPointee 2141 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 2142 2143 if (isa<ObjCObjectPointerType>(ToType)) 2144 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 2145 return Context.getPointerType(QualifiedCanonToPointee); 2146 } 2147 2148 static bool isNullPointerConstantForConversion(Expr *Expr, 2149 bool InOverloadResolution, 2150 ASTContext &Context) { 2151 // Handle value-dependent integral null pointer constants correctly. 2152 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 2153 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 2154 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 2155 return !InOverloadResolution; 2156 2157 return Expr->isNullPointerConstant(Context, 2158 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2159 : Expr::NPC_ValueDependentIsNull); 2160 } 2161 2162 /// IsPointerConversion - Determines whether the conversion of the 2163 /// expression From, which has the (possibly adjusted) type FromType, 2164 /// can be converted to the type ToType via a pointer conversion (C++ 2165 /// 4.10). If so, returns true and places the converted type (that 2166 /// might differ from ToType in its cv-qualifiers at some level) into 2167 /// ConvertedType. 2168 /// 2169 /// This routine also supports conversions to and from block pointers 2170 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 2171 /// pointers to interfaces. FIXME: Once we've determined the 2172 /// appropriate overloading rules for Objective-C, we may want to 2173 /// split the Objective-C checks into a different routine; however, 2174 /// GCC seems to consider all of these conversions to be pointer 2175 /// conversions, so for now they live here. IncompatibleObjC will be 2176 /// set if the conversion is an allowed Objective-C conversion that 2177 /// should result in a warning. 2178 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 2179 bool InOverloadResolution, 2180 QualType& ConvertedType, 2181 bool &IncompatibleObjC) { 2182 IncompatibleObjC = false; 2183 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 2184 IncompatibleObjC)) 2185 return true; 2186 2187 // Conversion from a null pointer constant to any Objective-C pointer type. 2188 if (ToType->isObjCObjectPointerType() && 2189 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2190 ConvertedType = ToType; 2191 return true; 2192 } 2193 2194 // Blocks: Block pointers can be converted to void*. 2195 if (FromType->isBlockPointerType() && ToType->isPointerType() && 2196 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 2197 ConvertedType = ToType; 2198 return true; 2199 } 2200 // Blocks: A null pointer constant can be converted to a block 2201 // pointer type. 2202 if (ToType->isBlockPointerType() && 2203 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2204 ConvertedType = ToType; 2205 return true; 2206 } 2207 2208 // If the left-hand-side is nullptr_t, the right side can be a null 2209 // pointer constant. 2210 if (ToType->isNullPtrType() && 2211 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2212 ConvertedType = ToType; 2213 return true; 2214 } 2215 2216 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 2217 if (!ToTypePtr) 2218 return false; 2219 2220 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 2221 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 2222 ConvertedType = ToType; 2223 return true; 2224 } 2225 2226 // Beyond this point, both types need to be pointers 2227 // , including objective-c pointers. 2228 QualType ToPointeeType = ToTypePtr->getPointeeType(); 2229 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 2230 !getLangOpts().ObjCAutoRefCount) { 2231 ConvertedType = BuildSimilarlyQualifiedPointerType( 2232 FromType->getAs<ObjCObjectPointerType>(), 2233 ToPointeeType, 2234 ToType, Context); 2235 return true; 2236 } 2237 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 2238 if (!FromTypePtr) 2239 return false; 2240 2241 QualType FromPointeeType = FromTypePtr->getPointeeType(); 2242 2243 // If the unqualified pointee types are the same, this can't be a 2244 // pointer conversion, so don't do all of the work below. 2245 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 2246 return false; 2247 2248 // An rvalue of type "pointer to cv T," where T is an object type, 2249 // can be converted to an rvalue of type "pointer to cv void" (C++ 2250 // 4.10p2). 2251 if (FromPointeeType->isIncompleteOrObjectType() && 2252 ToPointeeType->isVoidType()) { 2253 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2254 ToPointeeType, 2255 ToType, Context, 2256 /*StripObjCLifetime=*/true); 2257 return true; 2258 } 2259 2260 // MSVC allows implicit function to void* type conversion. 2261 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() && 2262 ToPointeeType->isVoidType()) { 2263 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2264 ToPointeeType, 2265 ToType, Context); 2266 return true; 2267 } 2268 2269 // When we're overloading in C, we allow a special kind of pointer 2270 // conversion for compatible-but-not-identical pointee types. 2271 if (!getLangOpts().CPlusPlus && 2272 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 2273 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2274 ToPointeeType, 2275 ToType, Context); 2276 return true; 2277 } 2278 2279 // C++ [conv.ptr]p3: 2280 // 2281 // An rvalue of type "pointer to cv D," where D is a class type, 2282 // can be converted to an rvalue of type "pointer to cv B," where 2283 // B is a base class (clause 10) of D. If B is an inaccessible 2284 // (clause 11) or ambiguous (10.2) base class of D, a program that 2285 // necessitates this conversion is ill-formed. The result of the 2286 // conversion is a pointer to the base class sub-object of the 2287 // derived class object. The null pointer value is converted to 2288 // the null pointer value of the destination type. 2289 // 2290 // Note that we do not check for ambiguity or inaccessibility 2291 // here. That is handled by CheckPointerConversion. 2292 if (getLangOpts().CPlusPlus && 2293 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2294 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 2295 IsDerivedFrom(From->getLocStart(), FromPointeeType, ToPointeeType)) { 2296 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2297 ToPointeeType, 2298 ToType, Context); 2299 return true; 2300 } 2301 2302 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 2303 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2304 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2305 ToPointeeType, 2306 ToType, Context); 2307 return true; 2308 } 2309 2310 return false; 2311 } 2312 2313 /// \brief Adopt the given qualifiers for the given type. 2314 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2315 Qualifiers TQs = T.getQualifiers(); 2316 2317 // Check whether qualifiers already match. 2318 if (TQs == Qs) 2319 return T; 2320 2321 if (Qs.compatiblyIncludes(TQs)) 2322 return Context.getQualifiedType(T, Qs); 2323 2324 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2325 } 2326 2327 /// isObjCPointerConversion - Determines whether this is an 2328 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2329 /// with the same arguments and return values. 2330 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2331 QualType& ConvertedType, 2332 bool &IncompatibleObjC) { 2333 if (!getLangOpts().ObjC1) 2334 return false; 2335 2336 // The set of qualifiers on the type we're converting from. 2337 Qualifiers FromQualifiers = FromType.getQualifiers(); 2338 2339 // First, we handle all conversions on ObjC object pointer types. 2340 const ObjCObjectPointerType* ToObjCPtr = 2341 ToType->getAs<ObjCObjectPointerType>(); 2342 const ObjCObjectPointerType *FromObjCPtr = 2343 FromType->getAs<ObjCObjectPointerType>(); 2344 2345 if (ToObjCPtr && FromObjCPtr) { 2346 // If the pointee types are the same (ignoring qualifications), 2347 // then this is not a pointer conversion. 2348 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2349 FromObjCPtr->getPointeeType())) 2350 return false; 2351 2352 // Conversion between Objective-C pointers. 2353 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2354 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2355 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2356 if (getLangOpts().CPlusPlus && LHS && RHS && 2357 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2358 FromObjCPtr->getPointeeType())) 2359 return false; 2360 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2361 ToObjCPtr->getPointeeType(), 2362 ToType, Context); 2363 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2364 return true; 2365 } 2366 2367 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2368 // Okay: this is some kind of implicit downcast of Objective-C 2369 // interfaces, which is permitted. However, we're going to 2370 // complain about it. 2371 IncompatibleObjC = true; 2372 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2373 ToObjCPtr->getPointeeType(), 2374 ToType, Context); 2375 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2376 return true; 2377 } 2378 } 2379 // Beyond this point, both types need to be C pointers or block pointers. 2380 QualType ToPointeeType; 2381 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2382 ToPointeeType = ToCPtr->getPointeeType(); 2383 else if (const BlockPointerType *ToBlockPtr = 2384 ToType->getAs<BlockPointerType>()) { 2385 // Objective C++: We're able to convert from a pointer to any object 2386 // to a block pointer type. 2387 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2388 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2389 return true; 2390 } 2391 ToPointeeType = ToBlockPtr->getPointeeType(); 2392 } 2393 else if (FromType->getAs<BlockPointerType>() && 2394 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2395 // Objective C++: We're able to convert from a block pointer type to a 2396 // pointer to any object. 2397 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2398 return true; 2399 } 2400 else 2401 return false; 2402 2403 QualType FromPointeeType; 2404 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2405 FromPointeeType = FromCPtr->getPointeeType(); 2406 else if (const BlockPointerType *FromBlockPtr = 2407 FromType->getAs<BlockPointerType>()) 2408 FromPointeeType = FromBlockPtr->getPointeeType(); 2409 else 2410 return false; 2411 2412 // If we have pointers to pointers, recursively check whether this 2413 // is an Objective-C conversion. 2414 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2415 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2416 IncompatibleObjC)) { 2417 // We always complain about this conversion. 2418 IncompatibleObjC = true; 2419 ConvertedType = Context.getPointerType(ConvertedType); 2420 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2421 return true; 2422 } 2423 // Allow conversion of pointee being objective-c pointer to another one; 2424 // as in I* to id. 2425 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2426 ToPointeeType->getAs<ObjCObjectPointerType>() && 2427 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2428 IncompatibleObjC)) { 2429 2430 ConvertedType = Context.getPointerType(ConvertedType); 2431 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2432 return true; 2433 } 2434 2435 // If we have pointers to functions or blocks, check whether the only 2436 // differences in the argument and result types are in Objective-C 2437 // pointer conversions. If so, we permit the conversion (but 2438 // complain about it). 2439 const FunctionProtoType *FromFunctionType 2440 = FromPointeeType->getAs<FunctionProtoType>(); 2441 const FunctionProtoType *ToFunctionType 2442 = ToPointeeType->getAs<FunctionProtoType>(); 2443 if (FromFunctionType && ToFunctionType) { 2444 // If the function types are exactly the same, this isn't an 2445 // Objective-C pointer conversion. 2446 if (Context.getCanonicalType(FromPointeeType) 2447 == Context.getCanonicalType(ToPointeeType)) 2448 return false; 2449 2450 // Perform the quick checks that will tell us whether these 2451 // function types are obviously different. 2452 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2453 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2454 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2455 return false; 2456 2457 bool HasObjCConversion = false; 2458 if (Context.getCanonicalType(FromFunctionType->getReturnType()) == 2459 Context.getCanonicalType(ToFunctionType->getReturnType())) { 2460 // Okay, the types match exactly. Nothing to do. 2461 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(), 2462 ToFunctionType->getReturnType(), 2463 ConvertedType, IncompatibleObjC)) { 2464 // Okay, we have an Objective-C pointer conversion. 2465 HasObjCConversion = true; 2466 } else { 2467 // Function types are too different. Abort. 2468 return false; 2469 } 2470 2471 // Check argument types. 2472 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2473 ArgIdx != NumArgs; ++ArgIdx) { 2474 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2475 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2476 if (Context.getCanonicalType(FromArgType) 2477 == Context.getCanonicalType(ToArgType)) { 2478 // Okay, the types match exactly. Nothing to do. 2479 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2480 ConvertedType, IncompatibleObjC)) { 2481 // Okay, we have an Objective-C pointer conversion. 2482 HasObjCConversion = true; 2483 } else { 2484 // Argument types are too different. Abort. 2485 return false; 2486 } 2487 } 2488 2489 if (HasObjCConversion) { 2490 // We had an Objective-C conversion. Allow this pointer 2491 // conversion, but complain about it. 2492 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2493 IncompatibleObjC = true; 2494 return true; 2495 } 2496 } 2497 2498 return false; 2499 } 2500 2501 /// \brief Determine whether this is an Objective-C writeback conversion, 2502 /// used for parameter passing when performing automatic reference counting. 2503 /// 2504 /// \param FromType The type we're converting form. 2505 /// 2506 /// \param ToType The type we're converting to. 2507 /// 2508 /// \param ConvertedType The type that will be produced after applying 2509 /// this conversion. 2510 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2511 QualType &ConvertedType) { 2512 if (!getLangOpts().ObjCAutoRefCount || 2513 Context.hasSameUnqualifiedType(FromType, ToType)) 2514 return false; 2515 2516 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2517 QualType ToPointee; 2518 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2519 ToPointee = ToPointer->getPointeeType(); 2520 else 2521 return false; 2522 2523 Qualifiers ToQuals = ToPointee.getQualifiers(); 2524 if (!ToPointee->isObjCLifetimeType() || 2525 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2526 !ToQuals.withoutObjCLifetime().empty()) 2527 return false; 2528 2529 // Argument must be a pointer to __strong to __weak. 2530 QualType FromPointee; 2531 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2532 FromPointee = FromPointer->getPointeeType(); 2533 else 2534 return false; 2535 2536 Qualifiers FromQuals = FromPointee.getQualifiers(); 2537 if (!FromPointee->isObjCLifetimeType() || 2538 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2539 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2540 return false; 2541 2542 // Make sure that we have compatible qualifiers. 2543 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2544 if (!ToQuals.compatiblyIncludes(FromQuals)) 2545 return false; 2546 2547 // Remove qualifiers from the pointee type we're converting from; they 2548 // aren't used in the compatibility check belong, and we'll be adding back 2549 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2550 FromPointee = FromPointee.getUnqualifiedType(); 2551 2552 // The unqualified form of the pointee types must be compatible. 2553 ToPointee = ToPointee.getUnqualifiedType(); 2554 bool IncompatibleObjC; 2555 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2556 FromPointee = ToPointee; 2557 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2558 IncompatibleObjC)) 2559 return false; 2560 2561 /// \brief Construct the type we're converting to, which is a pointer to 2562 /// __autoreleasing pointee. 2563 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2564 ConvertedType = Context.getPointerType(FromPointee); 2565 return true; 2566 } 2567 2568 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2569 QualType& ConvertedType) { 2570 QualType ToPointeeType; 2571 if (const BlockPointerType *ToBlockPtr = 2572 ToType->getAs<BlockPointerType>()) 2573 ToPointeeType = ToBlockPtr->getPointeeType(); 2574 else 2575 return false; 2576 2577 QualType FromPointeeType; 2578 if (const BlockPointerType *FromBlockPtr = 2579 FromType->getAs<BlockPointerType>()) 2580 FromPointeeType = FromBlockPtr->getPointeeType(); 2581 else 2582 return false; 2583 // We have pointer to blocks, check whether the only 2584 // differences in the argument and result types are in Objective-C 2585 // pointer conversions. If so, we permit the conversion. 2586 2587 const FunctionProtoType *FromFunctionType 2588 = FromPointeeType->getAs<FunctionProtoType>(); 2589 const FunctionProtoType *ToFunctionType 2590 = ToPointeeType->getAs<FunctionProtoType>(); 2591 2592 if (!FromFunctionType || !ToFunctionType) 2593 return false; 2594 2595 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2596 return true; 2597 2598 // Perform the quick checks that will tell us whether these 2599 // function types are obviously different. 2600 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() || 2601 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2602 return false; 2603 2604 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2605 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2606 if (FromEInfo != ToEInfo) 2607 return false; 2608 2609 bool IncompatibleObjC = false; 2610 if (Context.hasSameType(FromFunctionType->getReturnType(), 2611 ToFunctionType->getReturnType())) { 2612 // Okay, the types match exactly. Nothing to do. 2613 } else { 2614 QualType RHS = FromFunctionType->getReturnType(); 2615 QualType LHS = ToFunctionType->getReturnType(); 2616 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2617 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2618 LHS = LHS.getUnqualifiedType(); 2619 2620 if (Context.hasSameType(RHS,LHS)) { 2621 // OK exact match. 2622 } else if (isObjCPointerConversion(RHS, LHS, 2623 ConvertedType, IncompatibleObjC)) { 2624 if (IncompatibleObjC) 2625 return false; 2626 // Okay, we have an Objective-C pointer conversion. 2627 } 2628 else 2629 return false; 2630 } 2631 2632 // Check argument types. 2633 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams(); 2634 ArgIdx != NumArgs; ++ArgIdx) { 2635 IncompatibleObjC = false; 2636 QualType FromArgType = FromFunctionType->getParamType(ArgIdx); 2637 QualType ToArgType = ToFunctionType->getParamType(ArgIdx); 2638 if (Context.hasSameType(FromArgType, ToArgType)) { 2639 // Okay, the types match exactly. Nothing to do. 2640 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2641 ConvertedType, IncompatibleObjC)) { 2642 if (IncompatibleObjC) 2643 return false; 2644 // Okay, we have an Objective-C pointer conversion. 2645 } else 2646 // Argument types are too different. Abort. 2647 return false; 2648 } 2649 if (!Context.doFunctionTypesMatchOnExtParameterInfos(FromFunctionType, 2650 ToFunctionType)) 2651 return false; 2652 2653 ConvertedType = ToType; 2654 return true; 2655 } 2656 2657 enum { 2658 ft_default, 2659 ft_different_class, 2660 ft_parameter_arity, 2661 ft_parameter_mismatch, 2662 ft_return_type, 2663 ft_qualifer_mismatch, 2664 ft_noexcept 2665 }; 2666 2667 /// Attempts to get the FunctionProtoType from a Type. Handles 2668 /// MemberFunctionPointers properly. 2669 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) { 2670 if (auto *FPT = FromType->getAs<FunctionProtoType>()) 2671 return FPT; 2672 2673 if (auto *MPT = FromType->getAs<MemberPointerType>()) 2674 return MPT->getPointeeType()->getAs<FunctionProtoType>(); 2675 2676 return nullptr; 2677 } 2678 2679 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2680 /// function types. Catches different number of parameter, mismatch in 2681 /// parameter types, and different return types. 2682 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2683 QualType FromType, QualType ToType) { 2684 // If either type is not valid, include no extra info. 2685 if (FromType.isNull() || ToType.isNull()) { 2686 PDiag << ft_default; 2687 return; 2688 } 2689 2690 // Get the function type from the pointers. 2691 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2692 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2693 *ToMember = ToType->getAs<MemberPointerType>(); 2694 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) { 2695 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2696 << QualType(FromMember->getClass(), 0); 2697 return; 2698 } 2699 FromType = FromMember->getPointeeType(); 2700 ToType = ToMember->getPointeeType(); 2701 } 2702 2703 if (FromType->isPointerType()) 2704 FromType = FromType->getPointeeType(); 2705 if (ToType->isPointerType()) 2706 ToType = ToType->getPointeeType(); 2707 2708 // Remove references. 2709 FromType = FromType.getNonReferenceType(); 2710 ToType = ToType.getNonReferenceType(); 2711 2712 // Don't print extra info for non-specialized template functions. 2713 if (FromType->isInstantiationDependentType() && 2714 !FromType->getAs<TemplateSpecializationType>()) { 2715 PDiag << ft_default; 2716 return; 2717 } 2718 2719 // No extra info for same types. 2720 if (Context.hasSameType(FromType, ToType)) { 2721 PDiag << ft_default; 2722 return; 2723 } 2724 2725 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType), 2726 *ToFunction = tryGetFunctionProtoType(ToType); 2727 2728 // Both types need to be function types. 2729 if (!FromFunction || !ToFunction) { 2730 PDiag << ft_default; 2731 return; 2732 } 2733 2734 if (FromFunction->getNumParams() != ToFunction->getNumParams()) { 2735 PDiag << ft_parameter_arity << ToFunction->getNumParams() 2736 << FromFunction->getNumParams(); 2737 return; 2738 } 2739 2740 // Handle different parameter types. 2741 unsigned ArgPos; 2742 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2743 PDiag << ft_parameter_mismatch << ArgPos + 1 2744 << ToFunction->getParamType(ArgPos) 2745 << FromFunction->getParamType(ArgPos); 2746 return; 2747 } 2748 2749 // Handle different return type. 2750 if (!Context.hasSameType(FromFunction->getReturnType(), 2751 ToFunction->getReturnType())) { 2752 PDiag << ft_return_type << ToFunction->getReturnType() 2753 << FromFunction->getReturnType(); 2754 return; 2755 } 2756 2757 unsigned FromQuals = FromFunction->getTypeQuals(), 2758 ToQuals = ToFunction->getTypeQuals(); 2759 if (FromQuals != ToQuals) { 2760 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2761 return; 2762 } 2763 2764 // Handle exception specification differences on canonical type (in C++17 2765 // onwards). 2766 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified()) 2767 ->isNothrow(Context) != 2768 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified()) 2769 ->isNothrow(Context)) { 2770 PDiag << ft_noexcept; 2771 return; 2772 } 2773 2774 // Unable to find a difference, so add no extra info. 2775 PDiag << ft_default; 2776 } 2777 2778 /// FunctionParamTypesAreEqual - This routine checks two function proto types 2779 /// for equality of their argument types. Caller has already checked that 2780 /// they have same number of arguments. If the parameters are different, 2781 /// ArgPos will have the parameter index of the first different parameter. 2782 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType, 2783 const FunctionProtoType *NewType, 2784 unsigned *ArgPos) { 2785 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(), 2786 N = NewType->param_type_begin(), 2787 E = OldType->param_type_end(); 2788 O && (O != E); ++O, ++N) { 2789 if (!Context.hasSameType(O->getUnqualifiedType(), 2790 N->getUnqualifiedType())) { 2791 if (ArgPos) 2792 *ArgPos = O - OldType->param_type_begin(); 2793 return false; 2794 } 2795 } 2796 return true; 2797 } 2798 2799 /// CheckPointerConversion - Check the pointer conversion from the 2800 /// expression From to the type ToType. This routine checks for 2801 /// ambiguous or inaccessible derived-to-base pointer 2802 /// conversions for which IsPointerConversion has already returned 2803 /// true. It returns true and produces a diagnostic if there was an 2804 /// error, or returns false otherwise. 2805 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2806 CastKind &Kind, 2807 CXXCastPath& BasePath, 2808 bool IgnoreBaseAccess, 2809 bool Diagnose) { 2810 QualType FromType = From->getType(); 2811 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2812 2813 Kind = CK_BitCast; 2814 2815 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() && 2816 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) == 2817 Expr::NPCK_ZeroExpression) { 2818 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy)) 2819 DiagRuntimeBehavior(From->getExprLoc(), From, 2820 PDiag(diag::warn_impcast_bool_to_null_pointer) 2821 << ToType << From->getSourceRange()); 2822 else if (!isUnevaluatedContext()) 2823 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer) 2824 << ToType << From->getSourceRange(); 2825 } 2826 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2827 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2828 QualType FromPointeeType = FromPtrType->getPointeeType(), 2829 ToPointeeType = ToPtrType->getPointeeType(); 2830 2831 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2832 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2833 // We must have a derived-to-base conversion. Check an 2834 // ambiguous or inaccessible conversion. 2835 unsigned InaccessibleID = 0; 2836 unsigned AmbigiousID = 0; 2837 if (Diagnose) { 2838 InaccessibleID = diag::err_upcast_to_inaccessible_base; 2839 AmbigiousID = diag::err_ambiguous_derived_to_base_conv; 2840 } 2841 if (CheckDerivedToBaseConversion( 2842 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID, 2843 From->getExprLoc(), From->getSourceRange(), DeclarationName(), 2844 &BasePath, IgnoreBaseAccess)) 2845 return true; 2846 2847 // The conversion was successful. 2848 Kind = CK_DerivedToBase; 2849 } 2850 2851 if (Diagnose && !IsCStyleOrFunctionalCast && 2852 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) { 2853 assert(getLangOpts().MSVCCompat && 2854 "this should only be possible with MSVCCompat!"); 2855 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj) 2856 << From->getSourceRange(); 2857 } 2858 } 2859 } else if (const ObjCObjectPointerType *ToPtrType = 2860 ToType->getAs<ObjCObjectPointerType>()) { 2861 if (const ObjCObjectPointerType *FromPtrType = 2862 FromType->getAs<ObjCObjectPointerType>()) { 2863 // Objective-C++ conversions are always okay. 2864 // FIXME: We should have a different class of conversions for the 2865 // Objective-C++ implicit conversions. 2866 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2867 return false; 2868 } else if (FromType->isBlockPointerType()) { 2869 Kind = CK_BlockPointerToObjCPointerCast; 2870 } else { 2871 Kind = CK_CPointerToObjCPointerCast; 2872 } 2873 } else if (ToType->isBlockPointerType()) { 2874 if (!FromType->isBlockPointerType()) 2875 Kind = CK_AnyPointerToBlockPointerCast; 2876 } 2877 2878 // We shouldn't fall into this case unless it's valid for other 2879 // reasons. 2880 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2881 Kind = CK_NullToPointer; 2882 2883 return false; 2884 } 2885 2886 /// IsMemberPointerConversion - Determines whether the conversion of the 2887 /// expression From, which has the (possibly adjusted) type FromType, can be 2888 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2889 /// If so, returns true and places the converted type (that might differ from 2890 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2891 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2892 QualType ToType, 2893 bool InOverloadResolution, 2894 QualType &ConvertedType) { 2895 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2896 if (!ToTypePtr) 2897 return false; 2898 2899 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2900 if (From->isNullPointerConstant(Context, 2901 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2902 : Expr::NPC_ValueDependentIsNull)) { 2903 ConvertedType = ToType; 2904 return true; 2905 } 2906 2907 // Otherwise, both types have to be member pointers. 2908 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2909 if (!FromTypePtr) 2910 return false; 2911 2912 // A pointer to member of B can be converted to a pointer to member of D, 2913 // where D is derived from B (C++ 4.11p2). 2914 QualType FromClass(FromTypePtr->getClass(), 0); 2915 QualType ToClass(ToTypePtr->getClass(), 0); 2916 2917 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2918 IsDerivedFrom(From->getLocStart(), ToClass, FromClass)) { 2919 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2920 ToClass.getTypePtr()); 2921 return true; 2922 } 2923 2924 return false; 2925 } 2926 2927 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2928 /// expression From to the type ToType. This routine checks for ambiguous or 2929 /// virtual or inaccessible base-to-derived member pointer conversions 2930 /// for which IsMemberPointerConversion has already returned true. It returns 2931 /// true and produces a diagnostic if there was an error, or returns false 2932 /// otherwise. 2933 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2934 CastKind &Kind, 2935 CXXCastPath &BasePath, 2936 bool IgnoreBaseAccess) { 2937 QualType FromType = From->getType(); 2938 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2939 if (!FromPtrType) { 2940 // This must be a null pointer to member pointer conversion 2941 assert(From->isNullPointerConstant(Context, 2942 Expr::NPC_ValueDependentIsNull) && 2943 "Expr must be null pointer constant!"); 2944 Kind = CK_NullToMemberPointer; 2945 return false; 2946 } 2947 2948 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2949 assert(ToPtrType && "No member pointer cast has a target type " 2950 "that is not a member pointer."); 2951 2952 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2953 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2954 2955 // FIXME: What about dependent types? 2956 assert(FromClass->isRecordType() && "Pointer into non-class."); 2957 assert(ToClass->isRecordType() && "Pointer into non-class."); 2958 2959 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2960 /*DetectVirtual=*/true); 2961 bool DerivationOkay = 2962 IsDerivedFrom(From->getLocStart(), ToClass, FromClass, Paths); 2963 assert(DerivationOkay && 2964 "Should not have been called if derivation isn't OK."); 2965 (void)DerivationOkay; 2966 2967 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2968 getUnqualifiedType())) { 2969 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2970 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2971 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2972 return true; 2973 } 2974 2975 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2976 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2977 << FromClass << ToClass << QualType(VBase, 0) 2978 << From->getSourceRange(); 2979 return true; 2980 } 2981 2982 if (!IgnoreBaseAccess) 2983 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2984 Paths.front(), 2985 diag::err_downcast_from_inaccessible_base); 2986 2987 // Must be a base to derived member conversion. 2988 BuildBasePathArray(Paths, BasePath); 2989 Kind = CK_BaseToDerivedMemberPointer; 2990 return false; 2991 } 2992 2993 /// Determine whether the lifetime conversion between the two given 2994 /// qualifiers sets is nontrivial. 2995 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, 2996 Qualifiers ToQuals) { 2997 // Converting anything to const __unsafe_unretained is trivial. 2998 if (ToQuals.hasConst() && 2999 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone) 3000 return false; 3001 3002 return true; 3003 } 3004 3005 /// IsQualificationConversion - Determines whether the conversion from 3006 /// an rvalue of type FromType to ToType is a qualification conversion 3007 /// (C++ 4.4). 3008 /// 3009 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 3010 /// when the qualification conversion involves a change in the Objective-C 3011 /// object lifetime. 3012 bool 3013 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 3014 bool CStyle, bool &ObjCLifetimeConversion) { 3015 FromType = Context.getCanonicalType(FromType); 3016 ToType = Context.getCanonicalType(ToType); 3017 ObjCLifetimeConversion = false; 3018 3019 // If FromType and ToType are the same type, this is not a 3020 // qualification conversion. 3021 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 3022 return false; 3023 3024 // (C++ 4.4p4): 3025 // A conversion can add cv-qualifiers at levels other than the first 3026 // in multi-level pointers, subject to the following rules: [...] 3027 bool PreviousToQualsIncludeConst = true; 3028 bool UnwrappedAnyPointer = false; 3029 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 3030 // Within each iteration of the loop, we check the qualifiers to 3031 // determine if this still looks like a qualification 3032 // conversion. Then, if all is well, we unwrap one more level of 3033 // pointers or pointers-to-members and do it all again 3034 // until there are no more pointers or pointers-to-members left to 3035 // unwrap. 3036 UnwrappedAnyPointer = true; 3037 3038 Qualifiers FromQuals = FromType.getQualifiers(); 3039 Qualifiers ToQuals = ToType.getQualifiers(); 3040 3041 // Ignore __unaligned qualifier if this type is void. 3042 if (ToType.getUnqualifiedType()->isVoidType()) 3043 FromQuals.removeUnaligned(); 3044 3045 // Objective-C ARC: 3046 // Check Objective-C lifetime conversions. 3047 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 3048 UnwrappedAnyPointer) { 3049 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 3050 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals)) 3051 ObjCLifetimeConversion = true; 3052 FromQuals.removeObjCLifetime(); 3053 ToQuals.removeObjCLifetime(); 3054 } else { 3055 // Qualification conversions cannot cast between different 3056 // Objective-C lifetime qualifiers. 3057 return false; 3058 } 3059 } 3060 3061 // Allow addition/removal of GC attributes but not changing GC attributes. 3062 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 3063 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 3064 FromQuals.removeObjCGCAttr(); 3065 ToQuals.removeObjCGCAttr(); 3066 } 3067 3068 // -- for every j > 0, if const is in cv 1,j then const is in cv 3069 // 2,j, and similarly for volatile. 3070 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 3071 return false; 3072 3073 // -- if the cv 1,j and cv 2,j are different, then const is in 3074 // every cv for 0 < k < j. 3075 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 3076 && !PreviousToQualsIncludeConst) 3077 return false; 3078 3079 // Keep track of whether all prior cv-qualifiers in the "to" type 3080 // include const. 3081 PreviousToQualsIncludeConst 3082 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 3083 } 3084 3085 // We are left with FromType and ToType being the pointee types 3086 // after unwrapping the original FromType and ToType the same number 3087 // of types. If we unwrapped any pointers, and if FromType and 3088 // ToType have the same unqualified type (since we checked 3089 // qualifiers above), then this is a qualification conversion. 3090 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 3091 } 3092 3093 /// \brief - Determine whether this is a conversion from a scalar type to an 3094 /// atomic type. 3095 /// 3096 /// If successful, updates \c SCS's second and third steps in the conversion 3097 /// sequence to finish the conversion. 3098 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 3099 bool InOverloadResolution, 3100 StandardConversionSequence &SCS, 3101 bool CStyle) { 3102 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 3103 if (!ToAtomic) 3104 return false; 3105 3106 StandardConversionSequence InnerSCS; 3107 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 3108 InOverloadResolution, InnerSCS, 3109 CStyle, /*AllowObjCWritebackConversion=*/false)) 3110 return false; 3111 3112 SCS.Second = InnerSCS.Second; 3113 SCS.setToType(1, InnerSCS.getToType(1)); 3114 SCS.Third = InnerSCS.Third; 3115 SCS.QualificationIncludesObjCLifetime 3116 = InnerSCS.QualificationIncludesObjCLifetime; 3117 SCS.setToType(2, InnerSCS.getToType(2)); 3118 return true; 3119 } 3120 3121 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 3122 CXXConstructorDecl *Constructor, 3123 QualType Type) { 3124 const FunctionProtoType *CtorType = 3125 Constructor->getType()->getAs<FunctionProtoType>(); 3126 if (CtorType->getNumParams() > 0) { 3127 QualType FirstArg = CtorType->getParamType(0); 3128 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 3129 return true; 3130 } 3131 return false; 3132 } 3133 3134 static OverloadingResult 3135 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 3136 CXXRecordDecl *To, 3137 UserDefinedConversionSequence &User, 3138 OverloadCandidateSet &CandidateSet, 3139 bool AllowExplicit) { 3140 for (auto *D : S.LookupConstructors(To)) { 3141 auto Info = getConstructorInfo(D); 3142 if (!Info) 3143 continue; 3144 3145 bool Usable = !Info.Constructor->isInvalidDecl() && 3146 S.isInitListConstructor(Info.Constructor) && 3147 (AllowExplicit || !Info.Constructor->isExplicit()); 3148 if (Usable) { 3149 // If the first argument is (a reference to) the target type, 3150 // suppress conversions. 3151 bool SuppressUserConversions = isFirstArgumentCompatibleWithType( 3152 S.Context, Info.Constructor, ToType); 3153 if (Info.ConstructorTmpl) 3154 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl, 3155 /*ExplicitArgs*/ nullptr, From, 3156 CandidateSet, SuppressUserConversions); 3157 else 3158 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From, 3159 CandidateSet, SuppressUserConversions); 3160 } 3161 } 3162 3163 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3164 3165 OverloadCandidateSet::iterator Best; 3166 switch (auto Result = 3167 CandidateSet.BestViableFunction(S, From->getLocStart(), 3168 Best, true)) { 3169 case OR_Deleted: 3170 case OR_Success: { 3171 // Record the standard conversion we used and the conversion function. 3172 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 3173 QualType ThisType = Constructor->getThisType(S.Context); 3174 // Initializer lists don't have conversions as such. 3175 User.Before.setAsIdentityConversion(); 3176 User.HadMultipleCandidates = HadMultipleCandidates; 3177 User.ConversionFunction = Constructor; 3178 User.FoundConversionFunction = Best->FoundDecl; 3179 User.After.setAsIdentityConversion(); 3180 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3181 User.After.setAllToTypes(ToType); 3182 return Result; 3183 } 3184 3185 case OR_No_Viable_Function: 3186 return OR_No_Viable_Function; 3187 case OR_Ambiguous: 3188 return OR_Ambiguous; 3189 } 3190 3191 llvm_unreachable("Invalid OverloadResult!"); 3192 } 3193 3194 /// Determines whether there is a user-defined conversion sequence 3195 /// (C++ [over.ics.user]) that converts expression From to the type 3196 /// ToType. If such a conversion exists, User will contain the 3197 /// user-defined conversion sequence that performs such a conversion 3198 /// and this routine will return true. Otherwise, this routine returns 3199 /// false and User is unspecified. 3200 /// 3201 /// \param AllowExplicit true if the conversion should consider C++0x 3202 /// "explicit" conversion functions as well as non-explicit conversion 3203 /// functions (C++0x [class.conv.fct]p2). 3204 /// 3205 /// \param AllowObjCConversionOnExplicit true if the conversion should 3206 /// allow an extra Objective-C pointer conversion on uses of explicit 3207 /// constructors. Requires \c AllowExplicit to also be set. 3208 static OverloadingResult 3209 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 3210 UserDefinedConversionSequence &User, 3211 OverloadCandidateSet &CandidateSet, 3212 bool AllowExplicit, 3213 bool AllowObjCConversionOnExplicit) { 3214 assert(AllowExplicit || !AllowObjCConversionOnExplicit); 3215 3216 // Whether we will only visit constructors. 3217 bool ConstructorsOnly = false; 3218 3219 // If the type we are conversion to is a class type, enumerate its 3220 // constructors. 3221 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 3222 // C++ [over.match.ctor]p1: 3223 // When objects of class type are direct-initialized (8.5), or 3224 // copy-initialized from an expression of the same or a 3225 // derived class type (8.5), overload resolution selects the 3226 // constructor. [...] For copy-initialization, the candidate 3227 // functions are all the converting constructors (12.3.1) of 3228 // that class. The argument list is the expression-list within 3229 // the parentheses of the initializer. 3230 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 3231 (From->getType()->getAs<RecordType>() && 3232 S.IsDerivedFrom(From->getLocStart(), From->getType(), ToType))) 3233 ConstructorsOnly = true; 3234 3235 if (!S.isCompleteType(From->getExprLoc(), ToType)) { 3236 // We're not going to find any constructors. 3237 } else if (CXXRecordDecl *ToRecordDecl 3238 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 3239 3240 Expr **Args = &From; 3241 unsigned NumArgs = 1; 3242 bool ListInitializing = false; 3243 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 3244 // But first, see if there is an init-list-constructor that will work. 3245 OverloadingResult Result = IsInitializerListConstructorConversion( 3246 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 3247 if (Result != OR_No_Viable_Function) 3248 return Result; 3249 // Never mind. 3250 CandidateSet.clear(); 3251 3252 // If we're list-initializing, we pass the individual elements as 3253 // arguments, not the entire list. 3254 Args = InitList->getInits(); 3255 NumArgs = InitList->getNumInits(); 3256 ListInitializing = true; 3257 } 3258 3259 for (auto *D : S.LookupConstructors(ToRecordDecl)) { 3260 auto Info = getConstructorInfo(D); 3261 if (!Info) 3262 continue; 3263 3264 bool Usable = !Info.Constructor->isInvalidDecl(); 3265 if (ListInitializing) 3266 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit()); 3267 else 3268 Usable = Usable && 3269 Info.Constructor->isConvertingConstructor(AllowExplicit); 3270 if (Usable) { 3271 bool SuppressUserConversions = !ConstructorsOnly; 3272 if (SuppressUserConversions && ListInitializing) { 3273 SuppressUserConversions = false; 3274 if (NumArgs == 1) { 3275 // If the first argument is (a reference to) the target type, 3276 // suppress conversions. 3277 SuppressUserConversions = isFirstArgumentCompatibleWithType( 3278 S.Context, Info.Constructor, ToType); 3279 } 3280 } 3281 if (Info.ConstructorTmpl) 3282 S.AddTemplateOverloadCandidate( 3283 Info.ConstructorTmpl, Info.FoundDecl, 3284 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs), 3285 CandidateSet, SuppressUserConversions); 3286 else 3287 // Allow one user-defined conversion when user specifies a 3288 // From->ToType conversion via an static cast (c-style, etc). 3289 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, 3290 llvm::makeArrayRef(Args, NumArgs), 3291 CandidateSet, SuppressUserConversions); 3292 } 3293 } 3294 } 3295 } 3296 3297 // Enumerate conversion functions, if we're allowed to. 3298 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3299 } else if (!S.isCompleteType(From->getLocStart(), From->getType())) { 3300 // No conversion functions from incomplete types. 3301 } else if (const RecordType *FromRecordType 3302 = From->getType()->getAs<RecordType>()) { 3303 if (CXXRecordDecl *FromRecordDecl 3304 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3305 // Add all of the conversion functions as candidates. 3306 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions(); 3307 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 3308 DeclAccessPair FoundDecl = I.getPair(); 3309 NamedDecl *D = FoundDecl.getDecl(); 3310 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3311 if (isa<UsingShadowDecl>(D)) 3312 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3313 3314 CXXConversionDecl *Conv; 3315 FunctionTemplateDecl *ConvTemplate; 3316 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3317 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3318 else 3319 Conv = cast<CXXConversionDecl>(D); 3320 3321 if (AllowExplicit || !Conv->isExplicit()) { 3322 if (ConvTemplate) 3323 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3324 ActingContext, From, ToType, 3325 CandidateSet, 3326 AllowObjCConversionOnExplicit); 3327 else 3328 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3329 From, ToType, CandidateSet, 3330 AllowObjCConversionOnExplicit); 3331 } 3332 } 3333 } 3334 } 3335 3336 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3337 3338 OverloadCandidateSet::iterator Best; 3339 switch (auto Result = CandidateSet.BestViableFunction(S, From->getLocStart(), 3340 Best, true)) { 3341 case OR_Success: 3342 case OR_Deleted: 3343 // Record the standard conversion we used and the conversion function. 3344 if (CXXConstructorDecl *Constructor 3345 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3346 // C++ [over.ics.user]p1: 3347 // If the user-defined conversion is specified by a 3348 // constructor (12.3.1), the initial standard conversion 3349 // sequence converts the source type to the type required by 3350 // the argument of the constructor. 3351 // 3352 QualType ThisType = Constructor->getThisType(S.Context); 3353 if (isa<InitListExpr>(From)) { 3354 // Initializer lists don't have conversions as such. 3355 User.Before.setAsIdentityConversion(); 3356 } else { 3357 if (Best->Conversions[0].isEllipsis()) 3358 User.EllipsisConversion = true; 3359 else { 3360 User.Before = Best->Conversions[0].Standard; 3361 User.EllipsisConversion = false; 3362 } 3363 } 3364 User.HadMultipleCandidates = HadMultipleCandidates; 3365 User.ConversionFunction = Constructor; 3366 User.FoundConversionFunction = Best->FoundDecl; 3367 User.After.setAsIdentityConversion(); 3368 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3369 User.After.setAllToTypes(ToType); 3370 return Result; 3371 } 3372 if (CXXConversionDecl *Conversion 3373 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3374 // C++ [over.ics.user]p1: 3375 // 3376 // [...] If the user-defined conversion is specified by a 3377 // conversion function (12.3.2), the initial standard 3378 // conversion sequence converts the source type to the 3379 // implicit object parameter of the conversion function. 3380 User.Before = Best->Conversions[0].Standard; 3381 User.HadMultipleCandidates = HadMultipleCandidates; 3382 User.ConversionFunction = Conversion; 3383 User.FoundConversionFunction = Best->FoundDecl; 3384 User.EllipsisConversion = false; 3385 3386 // C++ [over.ics.user]p2: 3387 // The second standard conversion sequence converts the 3388 // result of the user-defined conversion to the target type 3389 // for the sequence. Since an implicit conversion sequence 3390 // is an initialization, the special rules for 3391 // initialization by user-defined conversion apply when 3392 // selecting the best user-defined conversion for a 3393 // user-defined conversion sequence (see 13.3.3 and 3394 // 13.3.3.1). 3395 User.After = Best->FinalConversion; 3396 return Result; 3397 } 3398 llvm_unreachable("Not a constructor or conversion function?"); 3399 3400 case OR_No_Viable_Function: 3401 return OR_No_Viable_Function; 3402 3403 case OR_Ambiguous: 3404 return OR_Ambiguous; 3405 } 3406 3407 llvm_unreachable("Invalid OverloadResult!"); 3408 } 3409 3410 bool 3411 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3412 ImplicitConversionSequence ICS; 3413 OverloadCandidateSet CandidateSet(From->getExprLoc(), 3414 OverloadCandidateSet::CSK_Normal); 3415 OverloadingResult OvResult = 3416 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3417 CandidateSet, false, false); 3418 if (OvResult == OR_Ambiguous) 3419 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition) 3420 << From->getType() << ToType << From->getSourceRange(); 3421 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) { 3422 if (!RequireCompleteType(From->getLocStart(), ToType, 3423 diag::err_typecheck_nonviable_condition_incomplete, 3424 From->getType(), From->getSourceRange())) 3425 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition) 3426 << false << From->getType() << From->getSourceRange() << ToType; 3427 } else 3428 return false; 3429 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3430 return true; 3431 } 3432 3433 /// \brief Compare the user-defined conversion functions or constructors 3434 /// of two user-defined conversion sequences to determine whether any ordering 3435 /// is possible. 3436 static ImplicitConversionSequence::CompareKind 3437 compareConversionFunctions(Sema &S, FunctionDecl *Function1, 3438 FunctionDecl *Function2) { 3439 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11) 3440 return ImplicitConversionSequence::Indistinguishable; 3441 3442 // Objective-C++: 3443 // If both conversion functions are implicitly-declared conversions from 3444 // a lambda closure type to a function pointer and a block pointer, 3445 // respectively, always prefer the conversion to a function pointer, 3446 // because the function pointer is more lightweight and is more likely 3447 // to keep code working. 3448 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1); 3449 if (!Conv1) 3450 return ImplicitConversionSequence::Indistinguishable; 3451 3452 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3453 if (!Conv2) 3454 return ImplicitConversionSequence::Indistinguishable; 3455 3456 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3457 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3458 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3459 if (Block1 != Block2) 3460 return Block1 ? ImplicitConversionSequence::Worse 3461 : ImplicitConversionSequence::Better; 3462 } 3463 3464 return ImplicitConversionSequence::Indistinguishable; 3465 } 3466 3467 static bool hasDeprecatedStringLiteralToCharPtrConversion( 3468 const ImplicitConversionSequence &ICS) { 3469 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) || 3470 (ICS.isUserDefined() && 3471 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr); 3472 } 3473 3474 /// CompareImplicitConversionSequences - Compare two implicit 3475 /// conversion sequences to determine whether one is better than the 3476 /// other or if they are indistinguishable (C++ 13.3.3.2). 3477 static ImplicitConversionSequence::CompareKind 3478 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, 3479 const ImplicitConversionSequence& ICS1, 3480 const ImplicitConversionSequence& ICS2) 3481 { 3482 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3483 // conversion sequences (as defined in 13.3.3.1) 3484 // -- a standard conversion sequence (13.3.3.1.1) is a better 3485 // conversion sequence than a user-defined conversion sequence or 3486 // an ellipsis conversion sequence, and 3487 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3488 // conversion sequence than an ellipsis conversion sequence 3489 // (13.3.3.1.3). 3490 // 3491 // C++0x [over.best.ics]p10: 3492 // For the purpose of ranking implicit conversion sequences as 3493 // described in 13.3.3.2, the ambiguous conversion sequence is 3494 // treated as a user-defined sequence that is indistinguishable 3495 // from any other user-defined conversion sequence. 3496 3497 // String literal to 'char *' conversion has been deprecated in C++03. It has 3498 // been removed from C++11. We still accept this conversion, if it happens at 3499 // the best viable function. Otherwise, this conversion is considered worse 3500 // than ellipsis conversion. Consider this as an extension; this is not in the 3501 // standard. For example: 3502 // 3503 // int &f(...); // #1 3504 // void f(char*); // #2 3505 // void g() { int &r = f("foo"); } 3506 // 3507 // In C++03, we pick #2 as the best viable function. 3508 // In C++11, we pick #1 as the best viable function, because ellipsis 3509 // conversion is better than string-literal to char* conversion (since there 3510 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't 3511 // convert arguments, #2 would be the best viable function in C++11. 3512 // If the best viable function has this conversion, a warning will be issued 3513 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11. 3514 3515 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 3516 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) != 3517 hasDeprecatedStringLiteralToCharPtrConversion(ICS2)) 3518 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1) 3519 ? ImplicitConversionSequence::Worse 3520 : ImplicitConversionSequence::Better; 3521 3522 if (ICS1.getKindRank() < ICS2.getKindRank()) 3523 return ImplicitConversionSequence::Better; 3524 if (ICS2.getKindRank() < ICS1.getKindRank()) 3525 return ImplicitConversionSequence::Worse; 3526 3527 // The following checks require both conversion sequences to be of 3528 // the same kind. 3529 if (ICS1.getKind() != ICS2.getKind()) 3530 return ImplicitConversionSequence::Indistinguishable; 3531 3532 ImplicitConversionSequence::CompareKind Result = 3533 ImplicitConversionSequence::Indistinguishable; 3534 3535 // Two implicit conversion sequences of the same form are 3536 // indistinguishable conversion sequences unless one of the 3537 // following rules apply: (C++ 13.3.3.2p3): 3538 3539 // List-initialization sequence L1 is a better conversion sequence than 3540 // list-initialization sequence L2 if: 3541 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or, 3542 // if not that, 3543 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T", 3544 // and N1 is smaller than N2., 3545 // even if one of the other rules in this paragraph would otherwise apply. 3546 if (!ICS1.isBad()) { 3547 if (ICS1.isStdInitializerListElement() && 3548 !ICS2.isStdInitializerListElement()) 3549 return ImplicitConversionSequence::Better; 3550 if (!ICS1.isStdInitializerListElement() && 3551 ICS2.isStdInitializerListElement()) 3552 return ImplicitConversionSequence::Worse; 3553 } 3554 3555 if (ICS1.isStandard()) 3556 // Standard conversion sequence S1 is a better conversion sequence than 3557 // standard conversion sequence S2 if [...] 3558 Result = CompareStandardConversionSequences(S, Loc, 3559 ICS1.Standard, ICS2.Standard); 3560 else if (ICS1.isUserDefined()) { 3561 // User-defined conversion sequence U1 is a better conversion 3562 // sequence than another user-defined conversion sequence U2 if 3563 // they contain the same user-defined conversion function or 3564 // constructor and if the second standard conversion sequence of 3565 // U1 is better than the second standard conversion sequence of 3566 // U2 (C++ 13.3.3.2p3). 3567 if (ICS1.UserDefined.ConversionFunction == 3568 ICS2.UserDefined.ConversionFunction) 3569 Result = CompareStandardConversionSequences(S, Loc, 3570 ICS1.UserDefined.After, 3571 ICS2.UserDefined.After); 3572 else 3573 Result = compareConversionFunctions(S, 3574 ICS1.UserDefined.ConversionFunction, 3575 ICS2.UserDefined.ConversionFunction); 3576 } 3577 3578 return Result; 3579 } 3580 3581 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3582 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3583 Qualifiers Quals; 3584 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3585 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3586 } 3587 3588 return Context.hasSameUnqualifiedType(T1, T2); 3589 } 3590 3591 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3592 // determine if one is a proper subset of the other. 3593 static ImplicitConversionSequence::CompareKind 3594 compareStandardConversionSubsets(ASTContext &Context, 3595 const StandardConversionSequence& SCS1, 3596 const StandardConversionSequence& SCS2) { 3597 ImplicitConversionSequence::CompareKind Result 3598 = ImplicitConversionSequence::Indistinguishable; 3599 3600 // the identity conversion sequence is considered to be a subsequence of 3601 // any non-identity conversion sequence 3602 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3603 return ImplicitConversionSequence::Better; 3604 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3605 return ImplicitConversionSequence::Worse; 3606 3607 if (SCS1.Second != SCS2.Second) { 3608 if (SCS1.Second == ICK_Identity) 3609 Result = ImplicitConversionSequence::Better; 3610 else if (SCS2.Second == ICK_Identity) 3611 Result = ImplicitConversionSequence::Worse; 3612 else 3613 return ImplicitConversionSequence::Indistinguishable; 3614 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3615 return ImplicitConversionSequence::Indistinguishable; 3616 3617 if (SCS1.Third == SCS2.Third) { 3618 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3619 : ImplicitConversionSequence::Indistinguishable; 3620 } 3621 3622 if (SCS1.Third == ICK_Identity) 3623 return Result == ImplicitConversionSequence::Worse 3624 ? ImplicitConversionSequence::Indistinguishable 3625 : ImplicitConversionSequence::Better; 3626 3627 if (SCS2.Third == ICK_Identity) 3628 return Result == ImplicitConversionSequence::Better 3629 ? ImplicitConversionSequence::Indistinguishable 3630 : ImplicitConversionSequence::Worse; 3631 3632 return ImplicitConversionSequence::Indistinguishable; 3633 } 3634 3635 /// \brief Determine whether one of the given reference bindings is better 3636 /// than the other based on what kind of bindings they are. 3637 static bool 3638 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3639 const StandardConversionSequence &SCS2) { 3640 // C++0x [over.ics.rank]p3b4: 3641 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3642 // implicit object parameter of a non-static member function declared 3643 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3644 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3645 // lvalue reference to a function lvalue and S2 binds an rvalue 3646 // reference*. 3647 // 3648 // FIXME: Rvalue references. We're going rogue with the above edits, 3649 // because the semantics in the current C++0x working paper (N3225 at the 3650 // time of this writing) break the standard definition of std::forward 3651 // and std::reference_wrapper when dealing with references to functions. 3652 // Proposed wording changes submitted to CWG for consideration. 3653 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3654 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3655 return false; 3656 3657 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3658 SCS2.IsLvalueReference) || 3659 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3660 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue); 3661 } 3662 3663 /// CompareStandardConversionSequences - Compare two standard 3664 /// conversion sequences to determine whether one is better than the 3665 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3666 static ImplicitConversionSequence::CompareKind 3667 CompareStandardConversionSequences(Sema &S, SourceLocation Loc, 3668 const StandardConversionSequence& SCS1, 3669 const StandardConversionSequence& SCS2) 3670 { 3671 // Standard conversion sequence S1 is a better conversion sequence 3672 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3673 3674 // -- S1 is a proper subsequence of S2 (comparing the conversion 3675 // sequences in the canonical form defined by 13.3.3.1.1, 3676 // excluding any Lvalue Transformation; the identity conversion 3677 // sequence is considered to be a subsequence of any 3678 // non-identity conversion sequence) or, if not that, 3679 if (ImplicitConversionSequence::CompareKind CK 3680 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3681 return CK; 3682 3683 // -- the rank of S1 is better than the rank of S2 (by the rules 3684 // defined below), or, if not that, 3685 ImplicitConversionRank Rank1 = SCS1.getRank(); 3686 ImplicitConversionRank Rank2 = SCS2.getRank(); 3687 if (Rank1 < Rank2) 3688 return ImplicitConversionSequence::Better; 3689 else if (Rank2 < Rank1) 3690 return ImplicitConversionSequence::Worse; 3691 3692 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3693 // are indistinguishable unless one of the following rules 3694 // applies: 3695 3696 // A conversion that is not a conversion of a pointer, or 3697 // pointer to member, to bool is better than another conversion 3698 // that is such a conversion. 3699 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3700 return SCS2.isPointerConversionToBool() 3701 ? ImplicitConversionSequence::Better 3702 : ImplicitConversionSequence::Worse; 3703 3704 // C++ [over.ics.rank]p4b2: 3705 // 3706 // If class B is derived directly or indirectly from class A, 3707 // conversion of B* to A* is better than conversion of B* to 3708 // void*, and conversion of A* to void* is better than conversion 3709 // of B* to void*. 3710 bool SCS1ConvertsToVoid 3711 = SCS1.isPointerConversionToVoidPointer(S.Context); 3712 bool SCS2ConvertsToVoid 3713 = SCS2.isPointerConversionToVoidPointer(S.Context); 3714 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3715 // Exactly one of the conversion sequences is a conversion to 3716 // a void pointer; it's the worse conversion. 3717 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3718 : ImplicitConversionSequence::Worse; 3719 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3720 // Neither conversion sequence converts to a void pointer; compare 3721 // their derived-to-base conversions. 3722 if (ImplicitConversionSequence::CompareKind DerivedCK 3723 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2)) 3724 return DerivedCK; 3725 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3726 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3727 // Both conversion sequences are conversions to void 3728 // pointers. Compare the source types to determine if there's an 3729 // inheritance relationship in their sources. 3730 QualType FromType1 = SCS1.getFromType(); 3731 QualType FromType2 = SCS2.getFromType(); 3732 3733 // Adjust the types we're converting from via the array-to-pointer 3734 // conversion, if we need to. 3735 if (SCS1.First == ICK_Array_To_Pointer) 3736 FromType1 = S.Context.getArrayDecayedType(FromType1); 3737 if (SCS2.First == ICK_Array_To_Pointer) 3738 FromType2 = S.Context.getArrayDecayedType(FromType2); 3739 3740 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3741 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3742 3743 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 3744 return ImplicitConversionSequence::Better; 3745 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 3746 return ImplicitConversionSequence::Worse; 3747 3748 // Objective-C++: If one interface is more specific than the 3749 // other, it is the better one. 3750 const ObjCObjectPointerType* FromObjCPtr1 3751 = FromType1->getAs<ObjCObjectPointerType>(); 3752 const ObjCObjectPointerType* FromObjCPtr2 3753 = FromType2->getAs<ObjCObjectPointerType>(); 3754 if (FromObjCPtr1 && FromObjCPtr2) { 3755 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3756 FromObjCPtr2); 3757 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3758 FromObjCPtr1); 3759 if (AssignLeft != AssignRight) { 3760 return AssignLeft? ImplicitConversionSequence::Better 3761 : ImplicitConversionSequence::Worse; 3762 } 3763 } 3764 } 3765 3766 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3767 // bullet 3). 3768 if (ImplicitConversionSequence::CompareKind QualCK 3769 = CompareQualificationConversions(S, SCS1, SCS2)) 3770 return QualCK; 3771 3772 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3773 // Check for a better reference binding based on the kind of bindings. 3774 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3775 return ImplicitConversionSequence::Better; 3776 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3777 return ImplicitConversionSequence::Worse; 3778 3779 // C++ [over.ics.rank]p3b4: 3780 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3781 // which the references refer are the same type except for 3782 // top-level cv-qualifiers, and the type to which the reference 3783 // initialized by S2 refers is more cv-qualified than the type 3784 // to which the reference initialized by S1 refers. 3785 QualType T1 = SCS1.getToType(2); 3786 QualType T2 = SCS2.getToType(2); 3787 T1 = S.Context.getCanonicalType(T1); 3788 T2 = S.Context.getCanonicalType(T2); 3789 Qualifiers T1Quals, T2Quals; 3790 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3791 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3792 if (UnqualT1 == UnqualT2) { 3793 // Objective-C++ ARC: If the references refer to objects with different 3794 // lifetimes, prefer bindings that don't change lifetime. 3795 if (SCS1.ObjCLifetimeConversionBinding != 3796 SCS2.ObjCLifetimeConversionBinding) { 3797 return SCS1.ObjCLifetimeConversionBinding 3798 ? ImplicitConversionSequence::Worse 3799 : ImplicitConversionSequence::Better; 3800 } 3801 3802 // If the type is an array type, promote the element qualifiers to the 3803 // type for comparison. 3804 if (isa<ArrayType>(T1) && T1Quals) 3805 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3806 if (isa<ArrayType>(T2) && T2Quals) 3807 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3808 if (T2.isMoreQualifiedThan(T1)) 3809 return ImplicitConversionSequence::Better; 3810 else if (T1.isMoreQualifiedThan(T2)) 3811 return ImplicitConversionSequence::Worse; 3812 } 3813 } 3814 3815 // In Microsoft mode, prefer an integral conversion to a 3816 // floating-to-integral conversion if the integral conversion 3817 // is between types of the same size. 3818 // For example: 3819 // void f(float); 3820 // void f(int); 3821 // int main { 3822 // long a; 3823 // f(a); 3824 // } 3825 // Here, MSVC will call f(int) instead of generating a compile error 3826 // as clang will do in standard mode. 3827 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion && 3828 SCS2.Second == ICK_Floating_Integral && 3829 S.Context.getTypeSize(SCS1.getFromType()) == 3830 S.Context.getTypeSize(SCS1.getToType(2))) 3831 return ImplicitConversionSequence::Better; 3832 3833 return ImplicitConversionSequence::Indistinguishable; 3834 } 3835 3836 /// CompareQualificationConversions - Compares two standard conversion 3837 /// sequences to determine whether they can be ranked based on their 3838 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3839 static ImplicitConversionSequence::CompareKind 3840 CompareQualificationConversions(Sema &S, 3841 const StandardConversionSequence& SCS1, 3842 const StandardConversionSequence& SCS2) { 3843 // C++ 13.3.3.2p3: 3844 // -- S1 and S2 differ only in their qualification conversion and 3845 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3846 // cv-qualification signature of type T1 is a proper subset of 3847 // the cv-qualification signature of type T2, and S1 is not the 3848 // deprecated string literal array-to-pointer conversion (4.2). 3849 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3850 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3851 return ImplicitConversionSequence::Indistinguishable; 3852 3853 // FIXME: the example in the standard doesn't use a qualification 3854 // conversion (!) 3855 QualType T1 = SCS1.getToType(2); 3856 QualType T2 = SCS2.getToType(2); 3857 T1 = S.Context.getCanonicalType(T1); 3858 T2 = S.Context.getCanonicalType(T2); 3859 Qualifiers T1Quals, T2Quals; 3860 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3861 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3862 3863 // If the types are the same, we won't learn anything by unwrapped 3864 // them. 3865 if (UnqualT1 == UnqualT2) 3866 return ImplicitConversionSequence::Indistinguishable; 3867 3868 // If the type is an array type, promote the element qualifiers to the type 3869 // for comparison. 3870 if (isa<ArrayType>(T1) && T1Quals) 3871 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3872 if (isa<ArrayType>(T2) && T2Quals) 3873 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3874 3875 ImplicitConversionSequence::CompareKind Result 3876 = ImplicitConversionSequence::Indistinguishable; 3877 3878 // Objective-C++ ARC: 3879 // Prefer qualification conversions not involving a change in lifetime 3880 // to qualification conversions that do not change lifetime. 3881 if (SCS1.QualificationIncludesObjCLifetime != 3882 SCS2.QualificationIncludesObjCLifetime) { 3883 Result = SCS1.QualificationIncludesObjCLifetime 3884 ? ImplicitConversionSequence::Worse 3885 : ImplicitConversionSequence::Better; 3886 } 3887 3888 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3889 // Within each iteration of the loop, we check the qualifiers to 3890 // determine if this still looks like a qualification 3891 // conversion. Then, if all is well, we unwrap one more level of 3892 // pointers or pointers-to-members and do it all again 3893 // until there are no more pointers or pointers-to-members left 3894 // to unwrap. This essentially mimics what 3895 // IsQualificationConversion does, but here we're checking for a 3896 // strict subset of qualifiers. 3897 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3898 // The qualifiers are the same, so this doesn't tell us anything 3899 // about how the sequences rank. 3900 ; 3901 else if (T2.isMoreQualifiedThan(T1)) { 3902 // T1 has fewer qualifiers, so it could be the better sequence. 3903 if (Result == ImplicitConversionSequence::Worse) 3904 // Neither has qualifiers that are a subset of the other's 3905 // qualifiers. 3906 return ImplicitConversionSequence::Indistinguishable; 3907 3908 Result = ImplicitConversionSequence::Better; 3909 } else if (T1.isMoreQualifiedThan(T2)) { 3910 // T2 has fewer qualifiers, so it could be the better sequence. 3911 if (Result == ImplicitConversionSequence::Better) 3912 // Neither has qualifiers that are a subset of the other's 3913 // qualifiers. 3914 return ImplicitConversionSequence::Indistinguishable; 3915 3916 Result = ImplicitConversionSequence::Worse; 3917 } else { 3918 // Qualifiers are disjoint. 3919 return ImplicitConversionSequence::Indistinguishable; 3920 } 3921 3922 // If the types after this point are equivalent, we're done. 3923 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3924 break; 3925 } 3926 3927 // Check that the winning standard conversion sequence isn't using 3928 // the deprecated string literal array to pointer conversion. 3929 switch (Result) { 3930 case ImplicitConversionSequence::Better: 3931 if (SCS1.DeprecatedStringLiteralToCharPtr) 3932 Result = ImplicitConversionSequence::Indistinguishable; 3933 break; 3934 3935 case ImplicitConversionSequence::Indistinguishable: 3936 break; 3937 3938 case ImplicitConversionSequence::Worse: 3939 if (SCS2.DeprecatedStringLiteralToCharPtr) 3940 Result = ImplicitConversionSequence::Indistinguishable; 3941 break; 3942 } 3943 3944 return Result; 3945 } 3946 3947 /// CompareDerivedToBaseConversions - Compares two standard conversion 3948 /// sequences to determine whether they can be ranked based on their 3949 /// various kinds of derived-to-base conversions (C++ 3950 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3951 /// conversions between Objective-C interface types. 3952 static ImplicitConversionSequence::CompareKind 3953 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, 3954 const StandardConversionSequence& SCS1, 3955 const StandardConversionSequence& SCS2) { 3956 QualType FromType1 = SCS1.getFromType(); 3957 QualType ToType1 = SCS1.getToType(1); 3958 QualType FromType2 = SCS2.getFromType(); 3959 QualType ToType2 = SCS2.getToType(1); 3960 3961 // Adjust the types we're converting from via the array-to-pointer 3962 // conversion, if we need to. 3963 if (SCS1.First == ICK_Array_To_Pointer) 3964 FromType1 = S.Context.getArrayDecayedType(FromType1); 3965 if (SCS2.First == ICK_Array_To_Pointer) 3966 FromType2 = S.Context.getArrayDecayedType(FromType2); 3967 3968 // Canonicalize all of the types. 3969 FromType1 = S.Context.getCanonicalType(FromType1); 3970 ToType1 = S.Context.getCanonicalType(ToType1); 3971 FromType2 = S.Context.getCanonicalType(FromType2); 3972 ToType2 = S.Context.getCanonicalType(ToType2); 3973 3974 // C++ [over.ics.rank]p4b3: 3975 // 3976 // If class B is derived directly or indirectly from class A and 3977 // class C is derived directly or indirectly from B, 3978 // 3979 // Compare based on pointer conversions. 3980 if (SCS1.Second == ICK_Pointer_Conversion && 3981 SCS2.Second == ICK_Pointer_Conversion && 3982 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3983 FromType1->isPointerType() && FromType2->isPointerType() && 3984 ToType1->isPointerType() && ToType2->isPointerType()) { 3985 QualType FromPointee1 3986 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3987 QualType ToPointee1 3988 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3989 QualType FromPointee2 3990 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3991 QualType ToPointee2 3992 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3993 3994 // -- conversion of C* to B* is better than conversion of C* to A*, 3995 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3996 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 3997 return ImplicitConversionSequence::Better; 3998 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 3999 return ImplicitConversionSequence::Worse; 4000 } 4001 4002 // -- conversion of B* to A* is better than conversion of C* to A*, 4003 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 4004 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4005 return ImplicitConversionSequence::Better; 4006 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4007 return ImplicitConversionSequence::Worse; 4008 } 4009 } else if (SCS1.Second == ICK_Pointer_Conversion && 4010 SCS2.Second == ICK_Pointer_Conversion) { 4011 const ObjCObjectPointerType *FromPtr1 4012 = FromType1->getAs<ObjCObjectPointerType>(); 4013 const ObjCObjectPointerType *FromPtr2 4014 = FromType2->getAs<ObjCObjectPointerType>(); 4015 const ObjCObjectPointerType *ToPtr1 4016 = ToType1->getAs<ObjCObjectPointerType>(); 4017 const ObjCObjectPointerType *ToPtr2 4018 = ToType2->getAs<ObjCObjectPointerType>(); 4019 4020 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 4021 // Apply the same conversion ranking rules for Objective-C pointer types 4022 // that we do for C++ pointers to class types. However, we employ the 4023 // Objective-C pseudo-subtyping relationship used for assignment of 4024 // Objective-C pointer types. 4025 bool FromAssignLeft 4026 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 4027 bool FromAssignRight 4028 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 4029 bool ToAssignLeft 4030 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 4031 bool ToAssignRight 4032 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 4033 4034 // A conversion to an a non-id object pointer type or qualified 'id' 4035 // type is better than a conversion to 'id'. 4036 if (ToPtr1->isObjCIdType() && 4037 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 4038 return ImplicitConversionSequence::Worse; 4039 if (ToPtr2->isObjCIdType() && 4040 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 4041 return ImplicitConversionSequence::Better; 4042 4043 // A conversion to a non-id object pointer type is better than a 4044 // conversion to a qualified 'id' type 4045 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 4046 return ImplicitConversionSequence::Worse; 4047 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 4048 return ImplicitConversionSequence::Better; 4049 4050 // A conversion to an a non-Class object pointer type or qualified 'Class' 4051 // type is better than a conversion to 'Class'. 4052 if (ToPtr1->isObjCClassType() && 4053 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 4054 return ImplicitConversionSequence::Worse; 4055 if (ToPtr2->isObjCClassType() && 4056 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 4057 return ImplicitConversionSequence::Better; 4058 4059 // A conversion to a non-Class object pointer type is better than a 4060 // conversion to a qualified 'Class' type. 4061 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 4062 return ImplicitConversionSequence::Worse; 4063 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 4064 return ImplicitConversionSequence::Better; 4065 4066 // -- "conversion of C* to B* is better than conversion of C* to A*," 4067 if (S.Context.hasSameType(FromType1, FromType2) && 4068 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 4069 (ToAssignLeft != ToAssignRight)) 4070 return ToAssignLeft? ImplicitConversionSequence::Worse 4071 : ImplicitConversionSequence::Better; 4072 4073 // -- "conversion of B* to A* is better than conversion of C* to A*," 4074 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 4075 (FromAssignLeft != FromAssignRight)) 4076 return FromAssignLeft? ImplicitConversionSequence::Better 4077 : ImplicitConversionSequence::Worse; 4078 } 4079 } 4080 4081 // Ranking of member-pointer types. 4082 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 4083 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 4084 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 4085 const MemberPointerType * FromMemPointer1 = 4086 FromType1->getAs<MemberPointerType>(); 4087 const MemberPointerType * ToMemPointer1 = 4088 ToType1->getAs<MemberPointerType>(); 4089 const MemberPointerType * FromMemPointer2 = 4090 FromType2->getAs<MemberPointerType>(); 4091 const MemberPointerType * ToMemPointer2 = 4092 ToType2->getAs<MemberPointerType>(); 4093 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 4094 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 4095 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 4096 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 4097 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 4098 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 4099 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 4100 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 4101 // conversion of A::* to B::* is better than conversion of A::* to C::*, 4102 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 4103 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2)) 4104 return ImplicitConversionSequence::Worse; 4105 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1)) 4106 return ImplicitConversionSequence::Better; 4107 } 4108 // conversion of B::* to C::* is better than conversion of A::* to C::* 4109 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 4110 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2)) 4111 return ImplicitConversionSequence::Better; 4112 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1)) 4113 return ImplicitConversionSequence::Worse; 4114 } 4115 } 4116 4117 if (SCS1.Second == ICK_Derived_To_Base) { 4118 // -- conversion of C to B is better than conversion of C to A, 4119 // -- binding of an expression of type C to a reference of type 4120 // B& is better than binding an expression of type C to a 4121 // reference of type A&, 4122 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4123 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4124 if (S.IsDerivedFrom(Loc, ToType1, ToType2)) 4125 return ImplicitConversionSequence::Better; 4126 else if (S.IsDerivedFrom(Loc, ToType2, ToType1)) 4127 return ImplicitConversionSequence::Worse; 4128 } 4129 4130 // -- conversion of B to A is better than conversion of C to A. 4131 // -- binding of an expression of type B to a reference of type 4132 // A& is better than binding an expression of type C to a 4133 // reference of type A&, 4134 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 4135 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 4136 if (S.IsDerivedFrom(Loc, FromType2, FromType1)) 4137 return ImplicitConversionSequence::Better; 4138 else if (S.IsDerivedFrom(Loc, FromType1, FromType2)) 4139 return ImplicitConversionSequence::Worse; 4140 } 4141 } 4142 4143 return ImplicitConversionSequence::Indistinguishable; 4144 } 4145 4146 /// \brief Determine whether the given type is valid, e.g., it is not an invalid 4147 /// C++ class. 4148 static bool isTypeValid(QualType T) { 4149 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl()) 4150 return !Record->isInvalidDecl(); 4151 4152 return true; 4153 } 4154 4155 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 4156 /// determine whether they are reference-related, 4157 /// reference-compatible, reference-compatible with added 4158 /// qualification, or incompatible, for use in C++ initialization by 4159 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 4160 /// type, and the first type (T1) is the pointee type of the reference 4161 /// type being initialized. 4162 Sema::ReferenceCompareResult 4163 Sema::CompareReferenceRelationship(SourceLocation Loc, 4164 QualType OrigT1, QualType OrigT2, 4165 bool &DerivedToBase, 4166 bool &ObjCConversion, 4167 bool &ObjCLifetimeConversion) { 4168 assert(!OrigT1->isReferenceType() && 4169 "T1 must be the pointee type of the reference type"); 4170 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 4171 4172 QualType T1 = Context.getCanonicalType(OrigT1); 4173 QualType T2 = Context.getCanonicalType(OrigT2); 4174 Qualifiers T1Quals, T2Quals; 4175 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 4176 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 4177 4178 // C++ [dcl.init.ref]p4: 4179 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 4180 // reference-related to "cv2 T2" if T1 is the same type as T2, or 4181 // T1 is a base class of T2. 4182 DerivedToBase = false; 4183 ObjCConversion = false; 4184 ObjCLifetimeConversion = false; 4185 QualType ConvertedT2; 4186 if (UnqualT1 == UnqualT2) { 4187 // Nothing to do. 4188 } else if (isCompleteType(Loc, OrigT2) && 4189 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) && 4190 IsDerivedFrom(Loc, UnqualT2, UnqualT1)) 4191 DerivedToBase = true; 4192 else if (UnqualT1->isObjCObjectOrInterfaceType() && 4193 UnqualT2->isObjCObjectOrInterfaceType() && 4194 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 4195 ObjCConversion = true; 4196 else if (UnqualT2->isFunctionType() && 4197 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) 4198 // C++1z [dcl.init.ref]p4: 4199 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept 4200 // function" and T1 is "function" 4201 // 4202 // We extend this to also apply to 'noreturn', so allow any function 4203 // conversion between function types. 4204 return Ref_Compatible; 4205 else 4206 return Ref_Incompatible; 4207 4208 // At this point, we know that T1 and T2 are reference-related (at 4209 // least). 4210 4211 // If the type is an array type, promote the element qualifiers to the type 4212 // for comparison. 4213 if (isa<ArrayType>(T1) && T1Quals) 4214 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 4215 if (isa<ArrayType>(T2) && T2Quals) 4216 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 4217 4218 // C++ [dcl.init.ref]p4: 4219 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 4220 // reference-related to T2 and cv1 is the same cv-qualification 4221 // as, or greater cv-qualification than, cv2. For purposes of 4222 // overload resolution, cases for which cv1 is greater 4223 // cv-qualification than cv2 are identified as 4224 // reference-compatible with added qualification (see 13.3.3.2). 4225 // 4226 // Note that we also require equivalence of Objective-C GC and address-space 4227 // qualifiers when performing these computations, so that e.g., an int in 4228 // address space 1 is not reference-compatible with an int in address 4229 // space 2. 4230 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 4231 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 4232 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals)) 4233 ObjCLifetimeConversion = true; 4234 4235 T1Quals.removeObjCLifetime(); 4236 T2Quals.removeObjCLifetime(); 4237 } 4238 4239 // MS compiler ignores __unaligned qualifier for references; do the same. 4240 T1Quals.removeUnaligned(); 4241 T2Quals.removeUnaligned(); 4242 4243 if (T1Quals.compatiblyIncludes(T2Quals)) 4244 return Ref_Compatible; 4245 else 4246 return Ref_Related; 4247 } 4248 4249 /// \brief Look for a user-defined conversion to an value reference-compatible 4250 /// with DeclType. Return true if something definite is found. 4251 static bool 4252 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 4253 QualType DeclType, SourceLocation DeclLoc, 4254 Expr *Init, QualType T2, bool AllowRvalues, 4255 bool AllowExplicit) { 4256 assert(T2->isRecordType() && "Can only find conversions of record types."); 4257 CXXRecordDecl *T2RecordDecl 4258 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 4259 4260 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal); 4261 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions(); 4262 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 4263 NamedDecl *D = *I; 4264 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 4265 if (isa<UsingShadowDecl>(D)) 4266 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 4267 4268 FunctionTemplateDecl *ConvTemplate 4269 = dyn_cast<FunctionTemplateDecl>(D); 4270 CXXConversionDecl *Conv; 4271 if (ConvTemplate) 4272 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 4273 else 4274 Conv = cast<CXXConversionDecl>(D); 4275 4276 // If this is an explicit conversion, and we're not allowed to consider 4277 // explicit conversions, skip it. 4278 if (!AllowExplicit && Conv->isExplicit()) 4279 continue; 4280 4281 if (AllowRvalues) { 4282 bool DerivedToBase = false; 4283 bool ObjCConversion = false; 4284 bool ObjCLifetimeConversion = false; 4285 4286 // If we are initializing an rvalue reference, don't permit conversion 4287 // functions that return lvalues. 4288 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 4289 const ReferenceType *RefType 4290 = Conv->getConversionType()->getAs<LValueReferenceType>(); 4291 if (RefType && !RefType->getPointeeType()->isFunctionType()) 4292 continue; 4293 } 4294 4295 if (!ConvTemplate && 4296 S.CompareReferenceRelationship( 4297 DeclLoc, 4298 Conv->getConversionType().getNonReferenceType() 4299 .getUnqualifiedType(), 4300 DeclType.getNonReferenceType().getUnqualifiedType(), 4301 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 4302 Sema::Ref_Incompatible) 4303 continue; 4304 } else { 4305 // If the conversion function doesn't return a reference type, 4306 // it can't be considered for this conversion. An rvalue reference 4307 // is only acceptable if its referencee is a function type. 4308 4309 const ReferenceType *RefType = 4310 Conv->getConversionType()->getAs<ReferenceType>(); 4311 if (!RefType || 4312 (!RefType->isLValueReferenceType() && 4313 !RefType->getPointeeType()->isFunctionType())) 4314 continue; 4315 } 4316 4317 if (ConvTemplate) 4318 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 4319 Init, DeclType, CandidateSet, 4320 /*AllowObjCConversionOnExplicit=*/false); 4321 else 4322 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 4323 DeclType, CandidateSet, 4324 /*AllowObjCConversionOnExplicit=*/false); 4325 } 4326 4327 bool HadMultipleCandidates = (CandidateSet.size() > 1); 4328 4329 OverloadCandidateSet::iterator Best; 4330 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 4331 case OR_Success: 4332 // C++ [over.ics.ref]p1: 4333 // 4334 // [...] If the parameter binds directly to the result of 4335 // applying a conversion function to the argument 4336 // expression, the implicit conversion sequence is a 4337 // user-defined conversion sequence (13.3.3.1.2), with the 4338 // second standard conversion sequence either an identity 4339 // conversion or, if the conversion function returns an 4340 // entity of a type that is a derived class of the parameter 4341 // type, a derived-to-base Conversion. 4342 if (!Best->FinalConversion.DirectBinding) 4343 return false; 4344 4345 ICS.setUserDefined(); 4346 ICS.UserDefined.Before = Best->Conversions[0].Standard; 4347 ICS.UserDefined.After = Best->FinalConversion; 4348 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4349 ICS.UserDefined.ConversionFunction = Best->Function; 4350 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4351 ICS.UserDefined.EllipsisConversion = false; 4352 assert(ICS.UserDefined.After.ReferenceBinding && 4353 ICS.UserDefined.After.DirectBinding && 4354 "Expected a direct reference binding!"); 4355 return true; 4356 4357 case OR_Ambiguous: 4358 ICS.setAmbiguous(); 4359 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4360 Cand != CandidateSet.end(); ++Cand) 4361 if (Cand->Viable) 4362 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function); 4363 return true; 4364 4365 case OR_No_Viable_Function: 4366 case OR_Deleted: 4367 // There was no suitable conversion, or we found a deleted 4368 // conversion; continue with other checks. 4369 return false; 4370 } 4371 4372 llvm_unreachable("Invalid OverloadResult!"); 4373 } 4374 4375 /// \brief Compute an implicit conversion sequence for reference 4376 /// initialization. 4377 static ImplicitConversionSequence 4378 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4379 SourceLocation DeclLoc, 4380 bool SuppressUserConversions, 4381 bool AllowExplicit) { 4382 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4383 4384 // Most paths end in a failed conversion. 4385 ImplicitConversionSequence ICS; 4386 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4387 4388 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4389 QualType T2 = Init->getType(); 4390 4391 // If the initializer is the address of an overloaded function, try 4392 // to resolve the overloaded function. If all goes well, T2 is the 4393 // type of the resulting function. 4394 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4395 DeclAccessPair Found; 4396 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4397 false, Found)) 4398 T2 = Fn->getType(); 4399 } 4400 4401 // Compute some basic properties of the types and the initializer. 4402 bool isRValRef = DeclType->isRValueReferenceType(); 4403 bool DerivedToBase = false; 4404 bool ObjCConversion = false; 4405 bool ObjCLifetimeConversion = false; 4406 Expr::Classification InitCategory = Init->Classify(S.Context); 4407 Sema::ReferenceCompareResult RefRelationship 4408 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4409 ObjCConversion, ObjCLifetimeConversion); 4410 4411 4412 // C++0x [dcl.init.ref]p5: 4413 // A reference to type "cv1 T1" is initialized by an expression 4414 // of type "cv2 T2" as follows: 4415 4416 // -- If reference is an lvalue reference and the initializer expression 4417 if (!isRValRef) { 4418 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4419 // reference-compatible with "cv2 T2," or 4420 // 4421 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4422 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) { 4423 // C++ [over.ics.ref]p1: 4424 // When a parameter of reference type binds directly (8.5.3) 4425 // to an argument expression, the implicit conversion sequence 4426 // is the identity conversion, unless the argument expression 4427 // has a type that is a derived class of the parameter type, 4428 // in which case the implicit conversion sequence is a 4429 // derived-to-base Conversion (13.3.3.1). 4430 ICS.setStandard(); 4431 ICS.Standard.First = ICK_Identity; 4432 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4433 : ObjCConversion? ICK_Compatible_Conversion 4434 : ICK_Identity; 4435 ICS.Standard.Third = ICK_Identity; 4436 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4437 ICS.Standard.setToType(0, T2); 4438 ICS.Standard.setToType(1, T1); 4439 ICS.Standard.setToType(2, T1); 4440 ICS.Standard.ReferenceBinding = true; 4441 ICS.Standard.DirectBinding = true; 4442 ICS.Standard.IsLvalueReference = !isRValRef; 4443 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4444 ICS.Standard.BindsToRvalue = false; 4445 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4446 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4447 ICS.Standard.CopyConstructor = nullptr; 4448 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4449 4450 // Nothing more to do: the inaccessibility/ambiguity check for 4451 // derived-to-base conversions is suppressed when we're 4452 // computing the implicit conversion sequence (C++ 4453 // [over.best.ics]p2). 4454 return ICS; 4455 } 4456 4457 // -- has a class type (i.e., T2 is a class type), where T1 is 4458 // not reference-related to T2, and can be implicitly 4459 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4460 // is reference-compatible with "cv3 T3" 92) (this 4461 // conversion is selected by enumerating the applicable 4462 // conversion functions (13.3.1.6) and choosing the best 4463 // one through overload resolution (13.3)), 4464 if (!SuppressUserConversions && T2->isRecordType() && 4465 S.isCompleteType(DeclLoc, T2) && 4466 RefRelationship == Sema::Ref_Incompatible) { 4467 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4468 Init, T2, /*AllowRvalues=*/false, 4469 AllowExplicit)) 4470 return ICS; 4471 } 4472 } 4473 4474 // -- Otherwise, the reference shall be an lvalue reference to a 4475 // non-volatile const type (i.e., cv1 shall be const), or the reference 4476 // shall be an rvalue reference. 4477 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) 4478 return ICS; 4479 4480 // -- If the initializer expression 4481 // 4482 // -- is an xvalue, class prvalue, array prvalue or function 4483 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4484 if (RefRelationship == Sema::Ref_Compatible && 4485 (InitCategory.isXValue() || 4486 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4487 (InitCategory.isLValue() && T2->isFunctionType()))) { 4488 ICS.setStandard(); 4489 ICS.Standard.First = ICK_Identity; 4490 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4491 : ObjCConversion? ICK_Compatible_Conversion 4492 : ICK_Identity; 4493 ICS.Standard.Third = ICK_Identity; 4494 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4495 ICS.Standard.setToType(0, T2); 4496 ICS.Standard.setToType(1, T1); 4497 ICS.Standard.setToType(2, T1); 4498 ICS.Standard.ReferenceBinding = true; 4499 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4500 // binding unless we're binding to a class prvalue. 4501 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4502 // allow the use of rvalue references in C++98/03 for the benefit of 4503 // standard library implementors; therefore, we need the xvalue check here. 4504 ICS.Standard.DirectBinding = 4505 S.getLangOpts().CPlusPlus11 || 4506 !(InitCategory.isPRValue() || T2->isRecordType()); 4507 ICS.Standard.IsLvalueReference = !isRValRef; 4508 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4509 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4510 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4511 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4512 ICS.Standard.CopyConstructor = nullptr; 4513 ICS.Standard.DeprecatedStringLiteralToCharPtr = false; 4514 return ICS; 4515 } 4516 4517 // -- has a class type (i.e., T2 is a class type), where T1 is not 4518 // reference-related to T2, and can be implicitly converted to 4519 // an xvalue, class prvalue, or function lvalue of type 4520 // "cv3 T3", where "cv1 T1" is reference-compatible with 4521 // "cv3 T3", 4522 // 4523 // then the reference is bound to the value of the initializer 4524 // expression in the first case and to the result of the conversion 4525 // in the second case (or, in either case, to an appropriate base 4526 // class subobject). 4527 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4528 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) && 4529 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4530 Init, T2, /*AllowRvalues=*/true, 4531 AllowExplicit)) { 4532 // In the second case, if the reference is an rvalue reference 4533 // and the second standard conversion sequence of the 4534 // user-defined conversion sequence includes an lvalue-to-rvalue 4535 // conversion, the program is ill-formed. 4536 if (ICS.isUserDefined() && isRValRef && 4537 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4538 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4539 4540 return ICS; 4541 } 4542 4543 // A temporary of function type cannot be created; don't even try. 4544 if (T1->isFunctionType()) 4545 return ICS; 4546 4547 // -- Otherwise, a temporary of type "cv1 T1" is created and 4548 // initialized from the initializer expression using the 4549 // rules for a non-reference copy initialization (8.5). The 4550 // reference is then bound to the temporary. If T1 is 4551 // reference-related to T2, cv1 must be the same 4552 // cv-qualification as, or greater cv-qualification than, 4553 // cv2; otherwise, the program is ill-formed. 4554 if (RefRelationship == Sema::Ref_Related) { 4555 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4556 // we would be reference-compatible or reference-compatible with 4557 // added qualification. But that wasn't the case, so the reference 4558 // initialization fails. 4559 // 4560 // Note that we only want to check address spaces and cvr-qualifiers here. 4561 // ObjC GC, lifetime and unaligned qualifiers aren't important. 4562 Qualifiers T1Quals = T1.getQualifiers(); 4563 Qualifiers T2Quals = T2.getQualifiers(); 4564 T1Quals.removeObjCGCAttr(); 4565 T1Quals.removeObjCLifetime(); 4566 T2Quals.removeObjCGCAttr(); 4567 T2Quals.removeObjCLifetime(); 4568 // MS compiler ignores __unaligned qualifier for references; do the same. 4569 T1Quals.removeUnaligned(); 4570 T2Quals.removeUnaligned(); 4571 if (!T1Quals.compatiblyIncludes(T2Quals)) 4572 return ICS; 4573 } 4574 4575 // If at least one of the types is a class type, the types are not 4576 // related, and we aren't allowed any user conversions, the 4577 // reference binding fails. This case is important for breaking 4578 // recursion, since TryImplicitConversion below will attempt to 4579 // create a temporary through the use of a copy constructor. 4580 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4581 (T1->isRecordType() || T2->isRecordType())) 4582 return ICS; 4583 4584 // If T1 is reference-related to T2 and the reference is an rvalue 4585 // reference, the initializer expression shall not be an lvalue. 4586 if (RefRelationship >= Sema::Ref_Related && 4587 isRValRef && Init->Classify(S.Context).isLValue()) 4588 return ICS; 4589 4590 // C++ [over.ics.ref]p2: 4591 // When a parameter of reference type is not bound directly to 4592 // an argument expression, the conversion sequence is the one 4593 // required to convert the argument expression to the 4594 // underlying type of the reference according to 4595 // 13.3.3.1. Conceptually, this conversion sequence corresponds 4596 // to copy-initializing a temporary of the underlying type with 4597 // the argument expression. Any difference in top-level 4598 // cv-qualification is subsumed by the initialization itself 4599 // and does not constitute a conversion. 4600 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions, 4601 /*AllowExplicit=*/false, 4602 /*InOverloadResolution=*/false, 4603 /*CStyle=*/false, 4604 /*AllowObjCWritebackConversion=*/false, 4605 /*AllowObjCConversionOnExplicit=*/false); 4606 4607 // Of course, that's still a reference binding. 4608 if (ICS.isStandard()) { 4609 ICS.Standard.ReferenceBinding = true; 4610 ICS.Standard.IsLvalueReference = !isRValRef; 4611 ICS.Standard.BindsToFunctionLvalue = false; 4612 ICS.Standard.BindsToRvalue = true; 4613 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4614 ICS.Standard.ObjCLifetimeConversionBinding = false; 4615 } else if (ICS.isUserDefined()) { 4616 const ReferenceType *LValRefType = 4617 ICS.UserDefined.ConversionFunction->getReturnType() 4618 ->getAs<LValueReferenceType>(); 4619 4620 // C++ [over.ics.ref]p3: 4621 // Except for an implicit object parameter, for which see 13.3.1, a 4622 // standard conversion sequence cannot be formed if it requires [...] 4623 // binding an rvalue reference to an lvalue other than a function 4624 // lvalue. 4625 // Note that the function case is not possible here. 4626 if (DeclType->isRValueReferenceType() && LValRefType) { 4627 // FIXME: This is the wrong BadConversionSequence. The problem is binding 4628 // an rvalue reference to a (non-function) lvalue, not binding an lvalue 4629 // reference to an rvalue! 4630 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType); 4631 return ICS; 4632 } 4633 4634 ICS.UserDefined.After.ReferenceBinding = true; 4635 ICS.UserDefined.After.IsLvalueReference = !isRValRef; 4636 ICS.UserDefined.After.BindsToFunctionLvalue = false; 4637 ICS.UserDefined.After.BindsToRvalue = !LValRefType; 4638 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4639 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false; 4640 } 4641 4642 return ICS; 4643 } 4644 4645 static ImplicitConversionSequence 4646 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4647 bool SuppressUserConversions, 4648 bool InOverloadResolution, 4649 bool AllowObjCWritebackConversion, 4650 bool AllowExplicit = false); 4651 4652 /// TryListConversion - Try to copy-initialize a value of type ToType from the 4653 /// initializer list From. 4654 static ImplicitConversionSequence 4655 TryListConversion(Sema &S, InitListExpr *From, QualType ToType, 4656 bool SuppressUserConversions, 4657 bool InOverloadResolution, 4658 bool AllowObjCWritebackConversion) { 4659 // C++11 [over.ics.list]p1: 4660 // When an argument is an initializer list, it is not an expression and 4661 // special rules apply for converting it to a parameter type. 4662 4663 ImplicitConversionSequence Result; 4664 Result.setBad(BadConversionSequence::no_conversion, From, ToType); 4665 4666 // We need a complete type for what follows. Incomplete types can never be 4667 // initialized from init lists. 4668 if (!S.isCompleteType(From->getLocStart(), ToType)) 4669 return Result; 4670 4671 // Per DR1467: 4672 // If the parameter type is a class X and the initializer list has a single 4673 // element of type cv U, where U is X or a class derived from X, the 4674 // implicit conversion sequence is the one required to convert the element 4675 // to the parameter type. 4676 // 4677 // Otherwise, if the parameter type is a character array [... ] 4678 // and the initializer list has a single element that is an 4679 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the 4680 // implicit conversion sequence is the identity conversion. 4681 if (From->getNumInits() == 1) { 4682 if (ToType->isRecordType()) { 4683 QualType InitType = From->getInit(0)->getType(); 4684 if (S.Context.hasSameUnqualifiedType(InitType, ToType) || 4685 S.IsDerivedFrom(From->getLocStart(), InitType, ToType)) 4686 return TryCopyInitialization(S, From->getInit(0), ToType, 4687 SuppressUserConversions, 4688 InOverloadResolution, 4689 AllowObjCWritebackConversion); 4690 } 4691 // FIXME: Check the other conditions here: array of character type, 4692 // initializer is a string literal. 4693 if (ToType->isArrayType()) { 4694 InitializedEntity Entity = 4695 InitializedEntity::InitializeParameter(S.Context, ToType, 4696 /*Consumed=*/false); 4697 if (S.CanPerformCopyInitialization(Entity, From)) { 4698 Result.setStandard(); 4699 Result.Standard.setAsIdentityConversion(); 4700 Result.Standard.setFromType(ToType); 4701 Result.Standard.setAllToTypes(ToType); 4702 return Result; 4703 } 4704 } 4705 } 4706 4707 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below). 4708 // C++11 [over.ics.list]p2: 4709 // If the parameter type is std::initializer_list<X> or "array of X" and 4710 // all the elements can be implicitly converted to X, the implicit 4711 // conversion sequence is the worst conversion necessary to convert an 4712 // element of the list to X. 4713 // 4714 // C++14 [over.ics.list]p3: 4715 // Otherwise, if the parameter type is "array of N X", if the initializer 4716 // list has exactly N elements or if it has fewer than N elements and X is 4717 // default-constructible, and if all the elements of the initializer list 4718 // can be implicitly converted to X, the implicit conversion sequence is 4719 // the worst conversion necessary to convert an element of the list to X. 4720 // 4721 // FIXME: We're missing a lot of these checks. 4722 bool toStdInitializerList = false; 4723 QualType X; 4724 if (ToType->isArrayType()) 4725 X = S.Context.getAsArrayType(ToType)->getElementType(); 4726 else 4727 toStdInitializerList = S.isStdInitializerList(ToType, &X); 4728 if (!X.isNull()) { 4729 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) { 4730 Expr *Init = From->getInit(i); 4731 ImplicitConversionSequence ICS = 4732 TryCopyInitialization(S, Init, X, SuppressUserConversions, 4733 InOverloadResolution, 4734 AllowObjCWritebackConversion); 4735 // If a single element isn't convertible, fail. 4736 if (ICS.isBad()) { 4737 Result = ICS; 4738 break; 4739 } 4740 // Otherwise, look for the worst conversion. 4741 if (Result.isBad() || 4742 CompareImplicitConversionSequences(S, From->getLocStart(), ICS, 4743 Result) == 4744 ImplicitConversionSequence::Worse) 4745 Result = ICS; 4746 } 4747 4748 // For an empty list, we won't have computed any conversion sequence. 4749 // Introduce the identity conversion sequence. 4750 if (From->getNumInits() == 0) { 4751 Result.setStandard(); 4752 Result.Standard.setAsIdentityConversion(); 4753 Result.Standard.setFromType(ToType); 4754 Result.Standard.setAllToTypes(ToType); 4755 } 4756 4757 Result.setStdInitializerListElement(toStdInitializerList); 4758 return Result; 4759 } 4760 4761 // C++14 [over.ics.list]p4: 4762 // C++11 [over.ics.list]p3: 4763 // Otherwise, if the parameter is a non-aggregate class X and overload 4764 // resolution chooses a single best constructor [...] the implicit 4765 // conversion sequence is a user-defined conversion sequence. If multiple 4766 // constructors are viable but none is better than the others, the 4767 // implicit conversion sequence is a user-defined conversion sequence. 4768 if (ToType->isRecordType() && !ToType->isAggregateType()) { 4769 // This function can deal with initializer lists. 4770 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 4771 /*AllowExplicit=*/false, 4772 InOverloadResolution, /*CStyle=*/false, 4773 AllowObjCWritebackConversion, 4774 /*AllowObjCConversionOnExplicit=*/false); 4775 } 4776 4777 // C++14 [over.ics.list]p5: 4778 // C++11 [over.ics.list]p4: 4779 // Otherwise, if the parameter has an aggregate type which can be 4780 // initialized from the initializer list [...] the implicit conversion 4781 // sequence is a user-defined conversion sequence. 4782 if (ToType->isAggregateType()) { 4783 // Type is an aggregate, argument is an init list. At this point it comes 4784 // down to checking whether the initialization works. 4785 // FIXME: Find out whether this parameter is consumed or not. 4786 // FIXME: Expose SemaInit's aggregate initialization code so that we don't 4787 // need to call into the initialization code here; overload resolution 4788 // should not be doing that. 4789 InitializedEntity Entity = 4790 InitializedEntity::InitializeParameter(S.Context, ToType, 4791 /*Consumed=*/false); 4792 if (S.CanPerformCopyInitialization(Entity, From)) { 4793 Result.setUserDefined(); 4794 Result.UserDefined.Before.setAsIdentityConversion(); 4795 // Initializer lists don't have a type. 4796 Result.UserDefined.Before.setFromType(QualType()); 4797 Result.UserDefined.Before.setAllToTypes(QualType()); 4798 4799 Result.UserDefined.After.setAsIdentityConversion(); 4800 Result.UserDefined.After.setFromType(ToType); 4801 Result.UserDefined.After.setAllToTypes(ToType); 4802 Result.UserDefined.ConversionFunction = nullptr; 4803 } 4804 return Result; 4805 } 4806 4807 // C++14 [over.ics.list]p6: 4808 // C++11 [over.ics.list]p5: 4809 // Otherwise, if the parameter is a reference, see 13.3.3.1.4. 4810 if (ToType->isReferenceType()) { 4811 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't 4812 // mention initializer lists in any way. So we go by what list- 4813 // initialization would do and try to extrapolate from that. 4814 4815 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType(); 4816 4817 // If the initializer list has a single element that is reference-related 4818 // to the parameter type, we initialize the reference from that. 4819 if (From->getNumInits() == 1) { 4820 Expr *Init = From->getInit(0); 4821 4822 QualType T2 = Init->getType(); 4823 4824 // If the initializer is the address of an overloaded function, try 4825 // to resolve the overloaded function. If all goes well, T2 is the 4826 // type of the resulting function. 4827 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4828 DeclAccessPair Found; 4829 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction( 4830 Init, ToType, false, Found)) 4831 T2 = Fn->getType(); 4832 } 4833 4834 // Compute some basic properties of the types and the initializer. 4835 bool dummy1 = false; 4836 bool dummy2 = false; 4837 bool dummy3 = false; 4838 Sema::ReferenceCompareResult RefRelationship 4839 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1, 4840 dummy2, dummy3); 4841 4842 if (RefRelationship >= Sema::Ref_Related) { 4843 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(), 4844 SuppressUserConversions, 4845 /*AllowExplicit=*/false); 4846 } 4847 } 4848 4849 // Otherwise, we bind the reference to a temporary created from the 4850 // initializer list. 4851 Result = TryListConversion(S, From, T1, SuppressUserConversions, 4852 InOverloadResolution, 4853 AllowObjCWritebackConversion); 4854 if (Result.isFailure()) 4855 return Result; 4856 assert(!Result.isEllipsis() && 4857 "Sub-initialization cannot result in ellipsis conversion."); 4858 4859 // Can we even bind to a temporary? 4860 if (ToType->isRValueReferenceType() || 4861 (T1.isConstQualified() && !T1.isVolatileQualified())) { 4862 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard : 4863 Result.UserDefined.After; 4864 SCS.ReferenceBinding = true; 4865 SCS.IsLvalueReference = ToType->isLValueReferenceType(); 4866 SCS.BindsToRvalue = true; 4867 SCS.BindsToFunctionLvalue = false; 4868 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4869 SCS.ObjCLifetimeConversionBinding = false; 4870 } else 4871 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue, 4872 From, ToType); 4873 return Result; 4874 } 4875 4876 // C++14 [over.ics.list]p7: 4877 // C++11 [over.ics.list]p6: 4878 // Otherwise, if the parameter type is not a class: 4879 if (!ToType->isRecordType()) { 4880 // - if the initializer list has one element that is not itself an 4881 // initializer list, the implicit conversion sequence is the one 4882 // required to convert the element to the parameter type. 4883 unsigned NumInits = From->getNumInits(); 4884 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0))) 4885 Result = TryCopyInitialization(S, From->getInit(0), ToType, 4886 SuppressUserConversions, 4887 InOverloadResolution, 4888 AllowObjCWritebackConversion); 4889 // - if the initializer list has no elements, the implicit conversion 4890 // sequence is the identity conversion. 4891 else if (NumInits == 0) { 4892 Result.setStandard(); 4893 Result.Standard.setAsIdentityConversion(); 4894 Result.Standard.setFromType(ToType); 4895 Result.Standard.setAllToTypes(ToType); 4896 } 4897 return Result; 4898 } 4899 4900 // C++14 [over.ics.list]p8: 4901 // C++11 [over.ics.list]p7: 4902 // In all cases other than those enumerated above, no conversion is possible 4903 return Result; 4904 } 4905 4906 /// TryCopyInitialization - Try to copy-initialize a value of type 4907 /// ToType from the expression From. Return the implicit conversion 4908 /// sequence required to pass this argument, which may be a bad 4909 /// conversion sequence (meaning that the argument cannot be passed to 4910 /// a parameter of this type). If @p SuppressUserConversions, then we 4911 /// do not permit any user-defined conversion sequences. 4912 static ImplicitConversionSequence 4913 TryCopyInitialization(Sema &S, Expr *From, QualType ToType, 4914 bool SuppressUserConversions, 4915 bool InOverloadResolution, 4916 bool AllowObjCWritebackConversion, 4917 bool AllowExplicit) { 4918 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From)) 4919 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions, 4920 InOverloadResolution,AllowObjCWritebackConversion); 4921 4922 if (ToType->isReferenceType()) 4923 return TryReferenceInit(S, From, ToType, 4924 /*FIXME:*/From->getLocStart(), 4925 SuppressUserConversions, 4926 AllowExplicit); 4927 4928 return TryImplicitConversion(S, From, ToType, 4929 SuppressUserConversions, 4930 /*AllowExplicit=*/false, 4931 InOverloadResolution, 4932 /*CStyle=*/false, 4933 AllowObjCWritebackConversion, 4934 /*AllowObjCConversionOnExplicit=*/false); 4935 } 4936 4937 static bool TryCopyInitialization(const CanQualType FromQTy, 4938 const CanQualType ToQTy, 4939 Sema &S, 4940 SourceLocation Loc, 4941 ExprValueKind FromVK) { 4942 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK); 4943 ImplicitConversionSequence ICS = 4944 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false); 4945 4946 return !ICS.isBad(); 4947 } 4948 4949 /// TryObjectArgumentInitialization - Try to initialize the object 4950 /// parameter of the given member function (@c Method) from the 4951 /// expression @p From. 4952 static ImplicitConversionSequence 4953 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, 4954 Expr::Classification FromClassification, 4955 CXXMethodDecl *Method, 4956 CXXRecordDecl *ActingContext) { 4957 QualType ClassType = S.Context.getTypeDeclType(ActingContext); 4958 // [class.dtor]p2: A destructor can be invoked for a const, volatile or 4959 // const volatile object. 4960 unsigned Quals = isa<CXXDestructorDecl>(Method) ? 4961 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers(); 4962 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals); 4963 4964 // Set up the conversion sequence as a "bad" conversion, to allow us 4965 // to exit early. 4966 ImplicitConversionSequence ICS; 4967 4968 // We need to have an object of class type. 4969 if (const PointerType *PT = FromType->getAs<PointerType>()) { 4970 FromType = PT->getPointeeType(); 4971 4972 // When we had a pointer, it's implicitly dereferenced, so we 4973 // better have an lvalue. 4974 assert(FromClassification.isLValue()); 4975 } 4976 4977 assert(FromType->isRecordType()); 4978 4979 // C++0x [over.match.funcs]p4: 4980 // For non-static member functions, the type of the implicit object 4981 // parameter is 4982 // 4983 // - "lvalue reference to cv X" for functions declared without a 4984 // ref-qualifier or with the & ref-qualifier 4985 // - "rvalue reference to cv X" for functions declared with the && 4986 // ref-qualifier 4987 // 4988 // where X is the class of which the function is a member and cv is the 4989 // cv-qualification on the member function declaration. 4990 // 4991 // However, when finding an implicit conversion sequence for the argument, we 4992 // are not allowed to perform user-defined conversions 4993 // (C++ [over.match.funcs]p5). We perform a simplified version of 4994 // reference binding here, that allows class rvalues to bind to 4995 // non-constant references. 4996 4997 // First check the qualifiers. 4998 QualType FromTypeCanon = S.Context.getCanonicalType(FromType); 4999 if (ImplicitParamType.getCVRQualifiers() 5000 != FromTypeCanon.getLocalCVRQualifiers() && 5001 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) { 5002 ICS.setBad(BadConversionSequence::bad_qualifiers, 5003 FromType, ImplicitParamType); 5004 return ICS; 5005 } 5006 5007 // Check that we have either the same type or a derived type. It 5008 // affects the conversion rank. 5009 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType); 5010 ImplicitConversionKind SecondKind; 5011 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) { 5012 SecondKind = ICK_Identity; 5013 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) 5014 SecondKind = ICK_Derived_To_Base; 5015 else { 5016 ICS.setBad(BadConversionSequence::unrelated_class, 5017 FromType, ImplicitParamType); 5018 return ICS; 5019 } 5020 5021 // Check the ref-qualifier. 5022 switch (Method->getRefQualifier()) { 5023 case RQ_None: 5024 // Do nothing; we don't care about lvalueness or rvalueness. 5025 break; 5026 5027 case RQ_LValue: 5028 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) { 5029 // non-const lvalue reference cannot bind to an rvalue 5030 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType, 5031 ImplicitParamType); 5032 return ICS; 5033 } 5034 break; 5035 5036 case RQ_RValue: 5037 if (!FromClassification.isRValue()) { 5038 // rvalue reference cannot bind to an lvalue 5039 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType, 5040 ImplicitParamType); 5041 return ICS; 5042 } 5043 break; 5044 } 5045 5046 // Success. Mark this as a reference binding. 5047 ICS.setStandard(); 5048 ICS.Standard.setAsIdentityConversion(); 5049 ICS.Standard.Second = SecondKind; 5050 ICS.Standard.setFromType(FromType); 5051 ICS.Standard.setAllToTypes(ImplicitParamType); 5052 ICS.Standard.ReferenceBinding = true; 5053 ICS.Standard.DirectBinding = true; 5054 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue; 5055 ICS.Standard.BindsToFunctionLvalue = false; 5056 ICS.Standard.BindsToRvalue = FromClassification.isRValue(); 5057 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier 5058 = (Method->getRefQualifier() == RQ_None); 5059 return ICS; 5060 } 5061 5062 /// PerformObjectArgumentInitialization - Perform initialization of 5063 /// the implicit object parameter for the given Method with the given 5064 /// expression. 5065 ExprResult 5066 Sema::PerformObjectArgumentInitialization(Expr *From, 5067 NestedNameSpecifier *Qualifier, 5068 NamedDecl *FoundDecl, 5069 CXXMethodDecl *Method) { 5070 QualType FromRecordType, DestType; 5071 QualType ImplicitParamRecordType = 5072 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType(); 5073 5074 Expr::Classification FromClassification; 5075 if (const PointerType *PT = From->getType()->getAs<PointerType>()) { 5076 FromRecordType = PT->getPointeeType(); 5077 DestType = Method->getThisType(Context); 5078 FromClassification = Expr::Classification::makeSimpleLValue(); 5079 } else { 5080 FromRecordType = From->getType(); 5081 DestType = ImplicitParamRecordType; 5082 FromClassification = From->Classify(Context); 5083 } 5084 5085 // Note that we always use the true parent context when performing 5086 // the actual argument initialization. 5087 ImplicitConversionSequence ICS = TryObjectArgumentInitialization( 5088 *this, From->getLocStart(), From->getType(), FromClassification, Method, 5089 Method->getParent()); 5090 if (ICS.isBad()) { 5091 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) { 5092 Qualifiers FromQs = FromRecordType.getQualifiers(); 5093 Qualifiers ToQs = DestType.getQualifiers(); 5094 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 5095 if (CVR) { 5096 Diag(From->getLocStart(), 5097 diag::err_member_function_call_bad_cvr) 5098 << Method->getDeclName() << FromRecordType << (CVR - 1) 5099 << From->getSourceRange(); 5100 Diag(Method->getLocation(), diag::note_previous_decl) 5101 << Method->getDeclName(); 5102 return ExprError(); 5103 } 5104 } 5105 5106 return Diag(From->getLocStart(), 5107 diag::err_implicit_object_parameter_init) 5108 << ImplicitParamRecordType << FromRecordType << From->getSourceRange(); 5109 } 5110 5111 if (ICS.Standard.Second == ICK_Derived_To_Base) { 5112 ExprResult FromRes = 5113 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method); 5114 if (FromRes.isInvalid()) 5115 return ExprError(); 5116 From = FromRes.get(); 5117 } 5118 5119 if (!Context.hasSameType(From->getType(), DestType)) 5120 From = ImpCastExprToType(From, DestType, CK_NoOp, 5121 From->getValueKind()).get(); 5122 return From; 5123 } 5124 5125 /// TryContextuallyConvertToBool - Attempt to contextually convert the 5126 /// expression From to bool (C++0x [conv]p3). 5127 static ImplicitConversionSequence 5128 TryContextuallyConvertToBool(Sema &S, Expr *From) { 5129 return TryImplicitConversion(S, From, S.Context.BoolTy, 5130 /*SuppressUserConversions=*/false, 5131 /*AllowExplicit=*/true, 5132 /*InOverloadResolution=*/false, 5133 /*CStyle=*/false, 5134 /*AllowObjCWritebackConversion=*/false, 5135 /*AllowObjCConversionOnExplicit=*/false); 5136 } 5137 5138 /// PerformContextuallyConvertToBool - Perform a contextual conversion 5139 /// of the expression From to bool (C++0x [conv]p3). 5140 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) { 5141 if (checkPlaceholderForOverload(*this, From)) 5142 return ExprError(); 5143 5144 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From); 5145 if (!ICS.isBad()) 5146 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting); 5147 5148 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy)) 5149 return Diag(From->getLocStart(), 5150 diag::err_typecheck_bool_condition) 5151 << From->getType() << From->getSourceRange(); 5152 return ExprError(); 5153 } 5154 5155 /// Check that the specified conversion is permitted in a converted constant 5156 /// expression, according to C++11 [expr.const]p3. Return true if the conversion 5157 /// is acceptable. 5158 static bool CheckConvertedConstantConversions(Sema &S, 5159 StandardConversionSequence &SCS) { 5160 // Since we know that the target type is an integral or unscoped enumeration 5161 // type, most conversion kinds are impossible. All possible First and Third 5162 // conversions are fine. 5163 switch (SCS.Second) { 5164 case ICK_Identity: 5165 case ICK_Function_Conversion: 5166 case ICK_Integral_Promotion: 5167 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere. 5168 case ICK_Zero_Queue_Conversion: 5169 return true; 5170 5171 case ICK_Boolean_Conversion: 5172 // Conversion from an integral or unscoped enumeration type to bool is 5173 // classified as ICK_Boolean_Conversion, but it's also arguably an integral 5174 // conversion, so we allow it in a converted constant expression. 5175 // 5176 // FIXME: Per core issue 1407, we should not allow this, but that breaks 5177 // a lot of popular code. We should at least add a warning for this 5178 // (non-conforming) extension. 5179 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() && 5180 SCS.getToType(2)->isBooleanType(); 5181 5182 case ICK_Pointer_Conversion: 5183 case ICK_Pointer_Member: 5184 // C++1z: null pointer conversions and null member pointer conversions are 5185 // only permitted if the source type is std::nullptr_t. 5186 return SCS.getFromType()->isNullPtrType(); 5187 5188 case ICK_Floating_Promotion: 5189 case ICK_Complex_Promotion: 5190 case ICK_Floating_Conversion: 5191 case ICK_Complex_Conversion: 5192 case ICK_Floating_Integral: 5193 case ICK_Compatible_Conversion: 5194 case ICK_Derived_To_Base: 5195 case ICK_Vector_Conversion: 5196 case ICK_Vector_Splat: 5197 case ICK_Complex_Real: 5198 case ICK_Block_Pointer_Conversion: 5199 case ICK_TransparentUnionConversion: 5200 case ICK_Writeback_Conversion: 5201 case ICK_Zero_Event_Conversion: 5202 case ICK_C_Only_Conversion: 5203 case ICK_Incompatible_Pointer_Conversion: 5204 return false; 5205 5206 case ICK_Lvalue_To_Rvalue: 5207 case ICK_Array_To_Pointer: 5208 case ICK_Function_To_Pointer: 5209 llvm_unreachable("found a first conversion kind in Second"); 5210 5211 case ICK_Qualification: 5212 llvm_unreachable("found a third conversion kind in Second"); 5213 5214 case ICK_Num_Conversion_Kinds: 5215 break; 5216 } 5217 5218 llvm_unreachable("unknown conversion kind"); 5219 } 5220 5221 /// CheckConvertedConstantExpression - Check that the expression From is a 5222 /// converted constant expression of type T, perform the conversion and produce 5223 /// the converted expression, per C++11 [expr.const]p3. 5224 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, 5225 QualType T, APValue &Value, 5226 Sema::CCEKind CCE, 5227 bool RequireInt) { 5228 assert(S.getLangOpts().CPlusPlus11 && 5229 "converted constant expression outside C++11"); 5230 5231 if (checkPlaceholderForOverload(S, From)) 5232 return ExprError(); 5233 5234 // C++1z [expr.const]p3: 5235 // A converted constant expression of type T is an expression, 5236 // implicitly converted to type T, where the converted 5237 // expression is a constant expression and the implicit conversion 5238 // sequence contains only [... list of conversions ...]. 5239 // C++1z [stmt.if]p2: 5240 // If the if statement is of the form if constexpr, the value of the 5241 // condition shall be a contextually converted constant expression of type 5242 // bool. 5243 ImplicitConversionSequence ICS = 5244 CCE == Sema::CCEK_ConstexprIf 5245 ? TryContextuallyConvertToBool(S, From) 5246 : TryCopyInitialization(S, From, T, 5247 /*SuppressUserConversions=*/false, 5248 /*InOverloadResolution=*/false, 5249 /*AllowObjcWritebackConversion=*/false, 5250 /*AllowExplicit=*/false); 5251 StandardConversionSequence *SCS = nullptr; 5252 switch (ICS.getKind()) { 5253 case ImplicitConversionSequence::StandardConversion: 5254 SCS = &ICS.Standard; 5255 break; 5256 case ImplicitConversionSequence::UserDefinedConversion: 5257 // We are converting to a non-class type, so the Before sequence 5258 // must be trivial. 5259 SCS = &ICS.UserDefined.After; 5260 break; 5261 case ImplicitConversionSequence::AmbiguousConversion: 5262 case ImplicitConversionSequence::BadConversion: 5263 if (!S.DiagnoseMultipleUserDefinedConversion(From, T)) 5264 return S.Diag(From->getLocStart(), 5265 diag::err_typecheck_converted_constant_expression) 5266 << From->getType() << From->getSourceRange() << T; 5267 return ExprError(); 5268 5269 case ImplicitConversionSequence::EllipsisConversion: 5270 llvm_unreachable("ellipsis conversion in converted constant expression"); 5271 } 5272 5273 // Check that we would only use permitted conversions. 5274 if (!CheckConvertedConstantConversions(S, *SCS)) { 5275 return S.Diag(From->getLocStart(), 5276 diag::err_typecheck_converted_constant_expression_disallowed) 5277 << From->getType() << From->getSourceRange() << T; 5278 } 5279 // [...] and where the reference binding (if any) binds directly. 5280 if (SCS->ReferenceBinding && !SCS->DirectBinding) { 5281 return S.Diag(From->getLocStart(), 5282 diag::err_typecheck_converted_constant_expression_indirect) 5283 << From->getType() << From->getSourceRange() << T; 5284 } 5285 5286 ExprResult Result = 5287 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting); 5288 if (Result.isInvalid()) 5289 return Result; 5290 5291 // Check for a narrowing implicit conversion. 5292 APValue PreNarrowingValue; 5293 QualType PreNarrowingType; 5294 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue, 5295 PreNarrowingType)) { 5296 case NK_Dependent_Narrowing: 5297 // Implicit conversion to a narrower type, but the expression is 5298 // value-dependent so we can't tell whether it's actually narrowing. 5299 case NK_Variable_Narrowing: 5300 // Implicit conversion to a narrower type, and the value is not a constant 5301 // expression. We'll diagnose this in a moment. 5302 case NK_Not_Narrowing: 5303 break; 5304 5305 case NK_Constant_Narrowing: 5306 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5307 << CCE << /*Constant*/1 5308 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T; 5309 break; 5310 5311 case NK_Type_Narrowing: 5312 S.Diag(From->getLocStart(), diag::ext_cce_narrowing) 5313 << CCE << /*Constant*/0 << From->getType() << T; 5314 break; 5315 } 5316 5317 if (Result.get()->isValueDependent()) { 5318 Value = APValue(); 5319 return Result; 5320 } 5321 5322 // Check the expression is a constant expression. 5323 SmallVector<PartialDiagnosticAt, 8> Notes; 5324 Expr::EvalResult Eval; 5325 Eval.Diag = &Notes; 5326 5327 if ((T->isReferenceType() 5328 ? !Result.get()->EvaluateAsLValue(Eval, S.Context) 5329 : !Result.get()->EvaluateAsRValue(Eval, S.Context)) || 5330 (RequireInt && !Eval.Val.isInt())) { 5331 // The expression can't be folded, so we can't keep it at this position in 5332 // the AST. 5333 Result = ExprError(); 5334 } else { 5335 Value = Eval.Val; 5336 5337 if (Notes.empty()) { 5338 // It's a constant expression. 5339 return Result; 5340 } 5341 } 5342 5343 // It's not a constant expression. Produce an appropriate diagnostic. 5344 if (Notes.size() == 1 && 5345 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) 5346 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE; 5347 else { 5348 S.Diag(From->getLocStart(), diag::err_expr_not_cce) 5349 << CCE << From->getSourceRange(); 5350 for (unsigned I = 0; I < Notes.size(); ++I) 5351 S.Diag(Notes[I].first, Notes[I].second); 5352 } 5353 return ExprError(); 5354 } 5355 5356 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5357 APValue &Value, CCEKind CCE) { 5358 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false); 5359 } 5360 5361 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T, 5362 llvm::APSInt &Value, 5363 CCEKind CCE) { 5364 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type"); 5365 5366 APValue V; 5367 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true); 5368 if (!R.isInvalid() && !R.get()->isValueDependent()) 5369 Value = V.getInt(); 5370 return R; 5371 } 5372 5373 5374 /// dropPointerConversions - If the given standard conversion sequence 5375 /// involves any pointer conversions, remove them. This may change 5376 /// the result type of the conversion sequence. 5377 static void dropPointerConversion(StandardConversionSequence &SCS) { 5378 if (SCS.Second == ICK_Pointer_Conversion) { 5379 SCS.Second = ICK_Identity; 5380 SCS.Third = ICK_Identity; 5381 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0]; 5382 } 5383 } 5384 5385 /// TryContextuallyConvertToObjCPointer - Attempt to contextually 5386 /// convert the expression From to an Objective-C pointer type. 5387 static ImplicitConversionSequence 5388 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) { 5389 // Do an implicit conversion to 'id'. 5390 QualType Ty = S.Context.getObjCIdType(); 5391 ImplicitConversionSequence ICS 5392 = TryImplicitConversion(S, From, Ty, 5393 // FIXME: Are these flags correct? 5394 /*SuppressUserConversions=*/false, 5395 /*AllowExplicit=*/true, 5396 /*InOverloadResolution=*/false, 5397 /*CStyle=*/false, 5398 /*AllowObjCWritebackConversion=*/false, 5399 /*AllowObjCConversionOnExplicit=*/true); 5400 5401 // Strip off any final conversions to 'id'. 5402 switch (ICS.getKind()) { 5403 case ImplicitConversionSequence::BadConversion: 5404 case ImplicitConversionSequence::AmbiguousConversion: 5405 case ImplicitConversionSequence::EllipsisConversion: 5406 break; 5407 5408 case ImplicitConversionSequence::UserDefinedConversion: 5409 dropPointerConversion(ICS.UserDefined.After); 5410 break; 5411 5412 case ImplicitConversionSequence::StandardConversion: 5413 dropPointerConversion(ICS.Standard); 5414 break; 5415 } 5416 5417 return ICS; 5418 } 5419 5420 /// PerformContextuallyConvertToObjCPointer - Perform a contextual 5421 /// conversion of the expression From to an Objective-C pointer type. 5422 /// Returns a valid but null ExprResult if no conversion sequence exists. 5423 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) { 5424 if (checkPlaceholderForOverload(*this, From)) 5425 return ExprError(); 5426 5427 QualType Ty = Context.getObjCIdType(); 5428 ImplicitConversionSequence ICS = 5429 TryContextuallyConvertToObjCPointer(*this, From); 5430 if (!ICS.isBad()) 5431 return PerformImplicitConversion(From, Ty, ICS, AA_Converting); 5432 return ExprResult(); 5433 } 5434 5435 /// Determine whether the provided type is an integral type, or an enumeration 5436 /// type of a permitted flavor. 5437 bool Sema::ICEConvertDiagnoser::match(QualType T) { 5438 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType() 5439 : T->isIntegralOrUnscopedEnumerationType(); 5440 } 5441 5442 static ExprResult 5443 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, 5444 Sema::ContextualImplicitConverter &Converter, 5445 QualType T, UnresolvedSetImpl &ViableConversions) { 5446 5447 if (Converter.Suppress) 5448 return ExprError(); 5449 5450 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange(); 5451 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5452 CXXConversionDecl *Conv = 5453 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl()); 5454 QualType ConvTy = Conv->getConversionType().getNonReferenceType(); 5455 Converter.noteAmbiguous(SemaRef, Conv, ConvTy); 5456 } 5457 return From; 5458 } 5459 5460 static bool 5461 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5462 Sema::ContextualImplicitConverter &Converter, 5463 QualType T, bool HadMultipleCandidates, 5464 UnresolvedSetImpl &ExplicitConversions) { 5465 if (ExplicitConversions.size() == 1 && !Converter.Suppress) { 5466 DeclAccessPair Found = ExplicitConversions[0]; 5467 CXXConversionDecl *Conversion = 5468 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5469 5470 // The user probably meant to invoke the given explicit 5471 // conversion; use it. 5472 QualType ConvTy = Conversion->getConversionType().getNonReferenceType(); 5473 std::string TypeStr; 5474 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy()); 5475 5476 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy) 5477 << FixItHint::CreateInsertion(From->getLocStart(), 5478 "static_cast<" + TypeStr + ">(") 5479 << FixItHint::CreateInsertion( 5480 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")"); 5481 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy); 5482 5483 // If we aren't in a SFINAE context, build a call to the 5484 // explicit conversion function. 5485 if (SemaRef.isSFINAEContext()) 5486 return true; 5487 5488 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5489 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5490 HadMultipleCandidates); 5491 if (Result.isInvalid()) 5492 return true; 5493 // Record usage of conversion in an implicit cast. 5494 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5495 CK_UserDefinedConversion, Result.get(), 5496 nullptr, Result.get()->getValueKind()); 5497 } 5498 return false; 5499 } 5500 5501 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, 5502 Sema::ContextualImplicitConverter &Converter, 5503 QualType T, bool HadMultipleCandidates, 5504 DeclAccessPair &Found) { 5505 CXXConversionDecl *Conversion = 5506 cast<CXXConversionDecl>(Found->getUnderlyingDecl()); 5507 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found); 5508 5509 QualType ToType = Conversion->getConversionType().getNonReferenceType(); 5510 if (!Converter.SuppressConversion) { 5511 if (SemaRef.isSFINAEContext()) 5512 return true; 5513 5514 Converter.diagnoseConversion(SemaRef, Loc, T, ToType) 5515 << From->getSourceRange(); 5516 } 5517 5518 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion, 5519 HadMultipleCandidates); 5520 if (Result.isInvalid()) 5521 return true; 5522 // Record usage of conversion in an implicit cast. 5523 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(), 5524 CK_UserDefinedConversion, Result.get(), 5525 nullptr, Result.get()->getValueKind()); 5526 return false; 5527 } 5528 5529 static ExprResult finishContextualImplicitConversion( 5530 Sema &SemaRef, SourceLocation Loc, Expr *From, 5531 Sema::ContextualImplicitConverter &Converter) { 5532 if (!Converter.match(From->getType()) && !Converter.Suppress) 5533 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType()) 5534 << From->getSourceRange(); 5535 5536 return SemaRef.DefaultLvalueConversion(From); 5537 } 5538 5539 static void 5540 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, 5541 UnresolvedSetImpl &ViableConversions, 5542 OverloadCandidateSet &CandidateSet) { 5543 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) { 5544 DeclAccessPair FoundDecl = ViableConversions[I]; 5545 NamedDecl *D = FoundDecl.getDecl(); 5546 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 5547 if (isa<UsingShadowDecl>(D)) 5548 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 5549 5550 CXXConversionDecl *Conv; 5551 FunctionTemplateDecl *ConvTemplate; 5552 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 5553 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5554 else 5555 Conv = cast<CXXConversionDecl>(D); 5556 5557 if (ConvTemplate) 5558 SemaRef.AddTemplateConversionCandidate( 5559 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet, 5560 /*AllowObjCConversionOnExplicit=*/false); 5561 else 5562 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, 5563 ToType, CandidateSet, 5564 /*AllowObjCConversionOnExplicit=*/false); 5565 } 5566 } 5567 5568 /// \brief Attempt to convert the given expression to a type which is accepted 5569 /// by the given converter. 5570 /// 5571 /// This routine will attempt to convert an expression of class type to a 5572 /// type accepted by the specified converter. In C++11 and before, the class 5573 /// must have a single non-explicit conversion function converting to a matching 5574 /// type. In C++1y, there can be multiple such conversion functions, but only 5575 /// one target type. 5576 /// 5577 /// \param Loc The source location of the construct that requires the 5578 /// conversion. 5579 /// 5580 /// \param From The expression we're converting from. 5581 /// 5582 /// \param Converter Used to control and diagnose the conversion process. 5583 /// 5584 /// \returns The expression, converted to an integral or enumeration type if 5585 /// successful. 5586 ExprResult Sema::PerformContextualImplicitConversion( 5587 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) { 5588 // We can't perform any more checking for type-dependent expressions. 5589 if (From->isTypeDependent()) 5590 return From; 5591 5592 // Process placeholders immediately. 5593 if (From->hasPlaceholderType()) { 5594 ExprResult result = CheckPlaceholderExpr(From); 5595 if (result.isInvalid()) 5596 return result; 5597 From = result.get(); 5598 } 5599 5600 // If the expression already has a matching type, we're golden. 5601 QualType T = From->getType(); 5602 if (Converter.match(T)) 5603 return DefaultLvalueConversion(From); 5604 5605 // FIXME: Check for missing '()' if T is a function type? 5606 5607 // We can only perform contextual implicit conversions on objects of class 5608 // type. 5609 const RecordType *RecordTy = T->getAs<RecordType>(); 5610 if (!RecordTy || !getLangOpts().CPlusPlus) { 5611 if (!Converter.Suppress) 5612 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange(); 5613 return From; 5614 } 5615 5616 // We must have a complete class type. 5617 struct TypeDiagnoserPartialDiag : TypeDiagnoser { 5618 ContextualImplicitConverter &Converter; 5619 Expr *From; 5620 5621 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From) 5622 : Converter(Converter), From(From) {} 5623 5624 void diagnose(Sema &S, SourceLocation Loc, QualType T) override { 5625 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange(); 5626 } 5627 } IncompleteDiagnoser(Converter, From); 5628 5629 if (Converter.Suppress ? !isCompleteType(Loc, T) 5630 : RequireCompleteType(Loc, T, IncompleteDiagnoser)) 5631 return From; 5632 5633 // Look for a conversion to an integral or enumeration type. 5634 UnresolvedSet<4> 5635 ViableConversions; // These are *potentially* viable in C++1y. 5636 UnresolvedSet<4> ExplicitConversions; 5637 const auto &Conversions = 5638 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions(); 5639 5640 bool HadMultipleCandidates = 5641 (std::distance(Conversions.begin(), Conversions.end()) > 1); 5642 5643 // To check that there is only one target type, in C++1y: 5644 QualType ToType; 5645 bool HasUniqueTargetType = true; 5646 5647 // Collect explicit or viable (potentially in C++1y) conversions. 5648 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 5649 NamedDecl *D = (*I)->getUnderlyingDecl(); 5650 CXXConversionDecl *Conversion; 5651 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D); 5652 if (ConvTemplate) { 5653 if (getLangOpts().CPlusPlus14) 5654 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 5655 else 5656 continue; // C++11 does not consider conversion operator templates(?). 5657 } else 5658 Conversion = cast<CXXConversionDecl>(D); 5659 5660 assert((!ConvTemplate || getLangOpts().CPlusPlus14) && 5661 "Conversion operator templates are considered potentially " 5662 "viable in C++1y"); 5663 5664 QualType CurToType = Conversion->getConversionType().getNonReferenceType(); 5665 if (Converter.match(CurToType) || ConvTemplate) { 5666 5667 if (Conversion->isExplicit()) { 5668 // FIXME: For C++1y, do we need this restriction? 5669 // cf. diagnoseNoViableConversion() 5670 if (!ConvTemplate) 5671 ExplicitConversions.addDecl(I.getDecl(), I.getAccess()); 5672 } else { 5673 if (!ConvTemplate && getLangOpts().CPlusPlus14) { 5674 if (ToType.isNull()) 5675 ToType = CurToType.getUnqualifiedType(); 5676 else if (HasUniqueTargetType && 5677 (CurToType.getUnqualifiedType() != ToType)) 5678 HasUniqueTargetType = false; 5679 } 5680 ViableConversions.addDecl(I.getDecl(), I.getAccess()); 5681 } 5682 } 5683 } 5684 5685 if (getLangOpts().CPlusPlus14) { 5686 // C++1y [conv]p6: 5687 // ... An expression e of class type E appearing in such a context 5688 // is said to be contextually implicitly converted to a specified 5689 // type T and is well-formed if and only if e can be implicitly 5690 // converted to a type T that is determined as follows: E is searched 5691 // for conversion functions whose return type is cv T or reference to 5692 // cv T such that T is allowed by the context. There shall be 5693 // exactly one such T. 5694 5695 // If no unique T is found: 5696 if (ToType.isNull()) { 5697 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5698 HadMultipleCandidates, 5699 ExplicitConversions)) 5700 return ExprError(); 5701 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5702 } 5703 5704 // If more than one unique Ts are found: 5705 if (!HasUniqueTargetType) 5706 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5707 ViableConversions); 5708 5709 // If one unique T is found: 5710 // First, build a candidate set from the previously recorded 5711 // potentially viable conversions. 5712 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal); 5713 collectViableConversionCandidates(*this, From, ToType, ViableConversions, 5714 CandidateSet); 5715 5716 // Then, perform overload resolution over the candidate set. 5717 OverloadCandidateSet::iterator Best; 5718 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) { 5719 case OR_Success: { 5720 // Apply this conversion. 5721 DeclAccessPair Found = 5722 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess()); 5723 if (recordConversion(*this, Loc, From, Converter, T, 5724 HadMultipleCandidates, Found)) 5725 return ExprError(); 5726 break; 5727 } 5728 case OR_Ambiguous: 5729 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5730 ViableConversions); 5731 case OR_No_Viable_Function: 5732 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5733 HadMultipleCandidates, 5734 ExplicitConversions)) 5735 return ExprError(); 5736 // fall through 'OR_Deleted' case. 5737 case OR_Deleted: 5738 // We'll complain below about a non-integral condition type. 5739 break; 5740 } 5741 } else { 5742 switch (ViableConversions.size()) { 5743 case 0: { 5744 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T, 5745 HadMultipleCandidates, 5746 ExplicitConversions)) 5747 return ExprError(); 5748 5749 // We'll complain below about a non-integral condition type. 5750 break; 5751 } 5752 case 1: { 5753 // Apply this conversion. 5754 DeclAccessPair Found = ViableConversions[0]; 5755 if (recordConversion(*this, Loc, From, Converter, T, 5756 HadMultipleCandidates, Found)) 5757 return ExprError(); 5758 break; 5759 } 5760 default: 5761 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T, 5762 ViableConversions); 5763 } 5764 } 5765 5766 return finishContextualImplicitConversion(*this, Loc, From, Converter); 5767 } 5768 5769 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 5770 /// an acceptable non-member overloaded operator for a call whose 5771 /// arguments have types T1 (and, if non-empty, T2). This routine 5772 /// implements the check in C++ [over.match.oper]p3b2 concerning 5773 /// enumeration types. 5774 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, 5775 FunctionDecl *Fn, 5776 ArrayRef<Expr *> Args) { 5777 QualType T1 = Args[0]->getType(); 5778 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType(); 5779 5780 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType())) 5781 return true; 5782 5783 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 5784 return true; 5785 5786 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>(); 5787 if (Proto->getNumParams() < 1) 5788 return false; 5789 5790 if (T1->isEnumeralType()) { 5791 QualType ArgType = Proto->getParamType(0).getNonReferenceType(); 5792 if (Context.hasSameUnqualifiedType(T1, ArgType)) 5793 return true; 5794 } 5795 5796 if (Proto->getNumParams() < 2) 5797 return false; 5798 5799 if (!T2.isNull() && T2->isEnumeralType()) { 5800 QualType ArgType = Proto->getParamType(1).getNonReferenceType(); 5801 if (Context.hasSameUnqualifiedType(T2, ArgType)) 5802 return true; 5803 } 5804 5805 return false; 5806 } 5807 5808 /// AddOverloadCandidate - Adds the given function to the set of 5809 /// candidate functions, using the given function call arguments. If 5810 /// @p SuppressUserConversions, then don't allow user-defined 5811 /// conversions via constructors or conversion operators. 5812 /// 5813 /// \param PartialOverloading true if we are performing "partial" overloading 5814 /// based on an incomplete set of function arguments. This feature is used by 5815 /// code completion. 5816 void 5817 Sema::AddOverloadCandidate(FunctionDecl *Function, 5818 DeclAccessPair FoundDecl, 5819 ArrayRef<Expr *> Args, 5820 OverloadCandidateSet &CandidateSet, 5821 bool SuppressUserConversions, 5822 bool PartialOverloading, 5823 bool AllowExplicit) { 5824 const FunctionProtoType *Proto 5825 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>()); 5826 assert(Proto && "Functions without a prototype cannot be overloaded"); 5827 assert(!Function->getDescribedFunctionTemplate() && 5828 "Use AddTemplateOverloadCandidate for function templates"); 5829 5830 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 5831 if (!isa<CXXConstructorDecl>(Method)) { 5832 // If we get here, it's because we're calling a member function 5833 // that is named without a member access expression (e.g., 5834 // "this->f") that was either written explicitly or created 5835 // implicitly. This can happen with a qualified call to a member 5836 // function, e.g., X::f(). We use an empty type for the implied 5837 // object argument (C++ [over.call.func]p3), and the acting context 5838 // is irrelevant. 5839 AddMethodCandidate(Method, FoundDecl, Method->getParent(), 5840 QualType(), Expr::Classification::makeSimpleLValue(), 5841 Args, CandidateSet, SuppressUserConversions, 5842 PartialOverloading); 5843 return; 5844 } 5845 // We treat a constructor like a non-member function, since its object 5846 // argument doesn't participate in overload resolution. 5847 } 5848 5849 if (!CandidateSet.isNewCandidate(Function)) 5850 return; 5851 5852 // C++ [over.match.oper]p3: 5853 // if no operand has a class type, only those non-member functions in the 5854 // lookup set that have a first parameter of type T1 or "reference to 5855 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there 5856 // is a right operand) a second parameter of type T2 or "reference to 5857 // (possibly cv-qualified) T2", when T2 is an enumeration type, are 5858 // candidate functions. 5859 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator && 5860 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args)) 5861 return; 5862 5863 // C++11 [class.copy]p11: [DR1402] 5864 // A defaulted move constructor that is defined as deleted is ignored by 5865 // overload resolution. 5866 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function); 5867 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() && 5868 Constructor->isMoveConstructor()) 5869 return; 5870 5871 // Overload resolution is always an unevaluated context. 5872 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 5873 5874 // Add this candidate 5875 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 5876 Candidate.FoundDecl = FoundDecl; 5877 Candidate.Function = Function; 5878 Candidate.Viable = true; 5879 Candidate.IsSurrogate = false; 5880 Candidate.IgnoreObjectArgument = false; 5881 Candidate.ExplicitCallArguments = Args.size(); 5882 5883 if (Constructor) { 5884 // C++ [class.copy]p3: 5885 // A member function template is never instantiated to perform the copy 5886 // of a class object to an object of its class type. 5887 QualType ClassType = Context.getTypeDeclType(Constructor->getParent()); 5888 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() && 5889 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) || 5890 IsDerivedFrom(Args[0]->getLocStart(), Args[0]->getType(), 5891 ClassType))) { 5892 Candidate.Viable = false; 5893 Candidate.FailureKind = ovl_fail_illegal_constructor; 5894 return; 5895 } 5896 } 5897 5898 unsigned NumParams = Proto->getNumParams(); 5899 5900 // (C++ 13.3.2p2): A candidate function having fewer than m 5901 // parameters is viable only if it has an ellipsis in its parameter 5902 // list (8.3.5). 5903 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 5904 !Proto->isVariadic()) { 5905 Candidate.Viable = false; 5906 Candidate.FailureKind = ovl_fail_too_many_arguments; 5907 return; 5908 } 5909 5910 // (C++ 13.3.2p2): A candidate function having more than m parameters 5911 // is viable only if the (m+1)st parameter has a default argument 5912 // (8.3.6). For the purposes of overload resolution, the 5913 // parameter list is truncated on the right, so that there are 5914 // exactly m parameters. 5915 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 5916 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 5917 // Not enough arguments. 5918 Candidate.Viable = false; 5919 Candidate.FailureKind = ovl_fail_too_few_arguments; 5920 return; 5921 } 5922 5923 // (CUDA B.1): Check for invalid calls between targets. 5924 if (getLangOpts().CUDA) 5925 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 5926 // Skip the check for callers that are implicit members, because in this 5927 // case we may not yet know what the member's target is; the target is 5928 // inferred for the member automatically, based on the bases and fields of 5929 // the class. 5930 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) { 5931 Candidate.Viable = false; 5932 Candidate.FailureKind = ovl_fail_bad_target; 5933 return; 5934 } 5935 5936 // Determine the implicit conversion sequences for each of the 5937 // arguments. 5938 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 5939 if (ArgIdx < NumParams) { 5940 // (C++ 13.3.2p3): for F to be a viable function, there shall 5941 // exist for each argument an implicit conversion sequence 5942 // (13.3.3.1) that converts that argument to the corresponding 5943 // parameter of F. 5944 QualType ParamType = Proto->getParamType(ArgIdx); 5945 Candidate.Conversions[ArgIdx] 5946 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 5947 SuppressUserConversions, 5948 /*InOverloadResolution=*/true, 5949 /*AllowObjCWritebackConversion=*/ 5950 getLangOpts().ObjCAutoRefCount, 5951 AllowExplicit); 5952 if (Candidate.Conversions[ArgIdx].isBad()) { 5953 Candidate.Viable = false; 5954 Candidate.FailureKind = ovl_fail_bad_conversion; 5955 return; 5956 } 5957 } else { 5958 // (C++ 13.3.2p2): For the purposes of overload resolution, any 5959 // argument for which there is no corresponding parameter is 5960 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 5961 Candidate.Conversions[ArgIdx].setEllipsis(); 5962 } 5963 } 5964 5965 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) { 5966 Candidate.Viable = false; 5967 Candidate.FailureKind = ovl_fail_enable_if; 5968 Candidate.DeductionFailure.Data = FailedAttr; 5969 return; 5970 } 5971 5972 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) { 5973 Candidate.Viable = false; 5974 Candidate.FailureKind = ovl_fail_ext_disabled; 5975 return; 5976 } 5977 } 5978 5979 ObjCMethodDecl * 5980 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, 5981 SmallVectorImpl<ObjCMethodDecl *> &Methods) { 5982 if (Methods.size() <= 1) 5983 return nullptr; 5984 5985 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 5986 bool Match = true; 5987 ObjCMethodDecl *Method = Methods[b]; 5988 unsigned NumNamedArgs = Sel.getNumArgs(); 5989 // Method might have more arguments than selector indicates. This is due 5990 // to addition of c-style arguments in method. 5991 if (Method->param_size() > NumNamedArgs) 5992 NumNamedArgs = Method->param_size(); 5993 if (Args.size() < NumNamedArgs) 5994 continue; 5995 5996 for (unsigned i = 0; i < NumNamedArgs; i++) { 5997 // We can't do any type-checking on a type-dependent argument. 5998 if (Args[i]->isTypeDependent()) { 5999 Match = false; 6000 break; 6001 } 6002 6003 ParmVarDecl *param = Method->parameters()[i]; 6004 Expr *argExpr = Args[i]; 6005 assert(argExpr && "SelectBestMethod(): missing expression"); 6006 6007 // Strip the unbridged-cast placeholder expression off unless it's 6008 // a consumed argument. 6009 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && 6010 !param->hasAttr<CFConsumedAttr>()) 6011 argExpr = stripARCUnbridgedCast(argExpr); 6012 6013 // If the parameter is __unknown_anytype, move on to the next method. 6014 if (param->getType() == Context.UnknownAnyTy) { 6015 Match = false; 6016 break; 6017 } 6018 6019 ImplicitConversionSequence ConversionState 6020 = TryCopyInitialization(*this, argExpr, param->getType(), 6021 /*SuppressUserConversions*/false, 6022 /*InOverloadResolution=*/true, 6023 /*AllowObjCWritebackConversion=*/ 6024 getLangOpts().ObjCAutoRefCount, 6025 /*AllowExplicit*/false); 6026 // This function looks for a reasonably-exact match, so we consider 6027 // incompatible pointer conversions to be a failure here. 6028 if (ConversionState.isBad() || 6029 (ConversionState.isStandard() && 6030 ConversionState.Standard.Second == 6031 ICK_Incompatible_Pointer_Conversion)) { 6032 Match = false; 6033 break; 6034 } 6035 } 6036 // Promote additional arguments to variadic methods. 6037 if (Match && Method->isVariadic()) { 6038 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { 6039 if (Args[i]->isTypeDependent()) { 6040 Match = false; 6041 break; 6042 } 6043 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 6044 nullptr); 6045 if (Arg.isInvalid()) { 6046 Match = false; 6047 break; 6048 } 6049 } 6050 } else { 6051 // Check for extra arguments to non-variadic methods. 6052 if (Args.size() != NumNamedArgs) 6053 Match = false; 6054 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) { 6055 // Special case when selectors have no argument. In this case, select 6056 // one with the most general result type of 'id'. 6057 for (unsigned b = 0, e = Methods.size(); b < e; b++) { 6058 QualType ReturnT = Methods[b]->getReturnType(); 6059 if (ReturnT->isObjCIdType()) 6060 return Methods[b]; 6061 } 6062 } 6063 } 6064 6065 if (Match) 6066 return Method; 6067 } 6068 return nullptr; 6069 } 6070 6071 // specific_attr_iterator iterates over enable_if attributes in reverse, and 6072 // enable_if is order-sensitive. As a result, we need to reverse things 6073 // sometimes. Size of 4 elements is arbitrary. 6074 static SmallVector<EnableIfAttr *, 4> 6075 getOrderedEnableIfAttrs(const FunctionDecl *Function) { 6076 SmallVector<EnableIfAttr *, 4> Result; 6077 if (!Function->hasAttrs()) 6078 return Result; 6079 6080 const auto &FuncAttrs = Function->getAttrs(); 6081 for (Attr *Attr : FuncAttrs) 6082 if (auto *EnableIf = dyn_cast<EnableIfAttr>(Attr)) 6083 Result.push_back(EnableIf); 6084 6085 std::reverse(Result.begin(), Result.end()); 6086 return Result; 6087 } 6088 6089 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, 6090 bool MissingImplicitThis) { 6091 auto EnableIfAttrs = getOrderedEnableIfAttrs(Function); 6092 if (EnableIfAttrs.empty()) 6093 return nullptr; 6094 6095 SFINAETrap Trap(*this); 6096 SmallVector<Expr *, 16> ConvertedArgs; 6097 bool InitializationFailed = false; 6098 6099 // Ignore any variadic arguments. Converting them is pointless, since the 6100 // user can't refer to them in the enable_if condition. 6101 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size()); 6102 6103 // Convert the arguments. 6104 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) { 6105 ExprResult R; 6106 if (I == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) && 6107 !cast<CXXMethodDecl>(Function)->isStatic() && 6108 !isa<CXXConstructorDecl>(Function)) { 6109 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function); 6110 R = PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 6111 Method, Method); 6112 } else { 6113 R = PerformCopyInitialization(InitializedEntity::InitializeParameter( 6114 Context, Function->getParamDecl(I)), 6115 SourceLocation(), Args[I]); 6116 } 6117 6118 if (R.isInvalid()) { 6119 InitializationFailed = true; 6120 break; 6121 } 6122 6123 ConvertedArgs.push_back(R.get()); 6124 } 6125 6126 if (InitializationFailed || Trap.hasErrorOccurred()) 6127 return EnableIfAttrs[0]; 6128 6129 // Push default arguments if needed. 6130 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) { 6131 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) { 6132 ParmVarDecl *P = Function->getParamDecl(i); 6133 ExprResult R = PerformCopyInitialization( 6134 InitializedEntity::InitializeParameter(Context, 6135 Function->getParamDecl(i)), 6136 SourceLocation(), 6137 P->hasUninstantiatedDefaultArg() ? P->getUninstantiatedDefaultArg() 6138 : P->getDefaultArg()); 6139 if (R.isInvalid()) { 6140 InitializationFailed = true; 6141 break; 6142 } 6143 ConvertedArgs.push_back(R.get()); 6144 } 6145 6146 if (InitializationFailed || Trap.hasErrorOccurred()) 6147 return EnableIfAttrs[0]; 6148 } 6149 6150 for (auto *EIA : EnableIfAttrs) { 6151 APValue Result; 6152 // FIXME: This doesn't consider value-dependent cases, because doing so is 6153 // very difficult. Ideally, we should handle them more gracefully. 6154 if (!EIA->getCond()->EvaluateWithSubstitution( 6155 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs))) 6156 return EIA; 6157 6158 if (!Result.isInt() || !Result.getInt().getBoolValue()) 6159 return EIA; 6160 } 6161 return nullptr; 6162 } 6163 6164 /// \brief Add all of the function declarations in the given function set to 6165 /// the overload candidate set. 6166 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns, 6167 ArrayRef<Expr *> Args, 6168 OverloadCandidateSet& CandidateSet, 6169 TemplateArgumentListInfo *ExplicitTemplateArgs, 6170 bool SuppressUserConversions, 6171 bool PartialOverloading) { 6172 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) { 6173 NamedDecl *D = F.getDecl()->getUnderlyingDecl(); 6174 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 6175 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 6176 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(), 6177 cast<CXXMethodDecl>(FD)->getParent(), 6178 Args[0]->getType(), Args[0]->Classify(Context), 6179 Args.slice(1), CandidateSet, 6180 SuppressUserConversions, PartialOverloading); 6181 else 6182 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet, 6183 SuppressUserConversions, PartialOverloading); 6184 } else { 6185 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D); 6186 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) && 6187 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic()) 6188 AddMethodTemplateCandidate(FunTmpl, F.getPair(), 6189 cast<CXXRecordDecl>(FunTmpl->getDeclContext()), 6190 ExplicitTemplateArgs, 6191 Args[0]->getType(), 6192 Args[0]->Classify(Context), Args.slice(1), 6193 CandidateSet, SuppressUserConversions, 6194 PartialOverloading); 6195 else 6196 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), 6197 ExplicitTemplateArgs, Args, 6198 CandidateSet, SuppressUserConversions, 6199 PartialOverloading); 6200 } 6201 } 6202 } 6203 6204 /// AddMethodCandidate - Adds a named decl (which is some kind of 6205 /// method) as a method candidate to the given overload set. 6206 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, 6207 QualType ObjectType, 6208 Expr::Classification ObjectClassification, 6209 ArrayRef<Expr *> Args, 6210 OverloadCandidateSet& CandidateSet, 6211 bool SuppressUserConversions) { 6212 NamedDecl *Decl = FoundDecl.getDecl(); 6213 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext()); 6214 6215 if (isa<UsingShadowDecl>(Decl)) 6216 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl(); 6217 6218 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) { 6219 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) && 6220 "Expected a member function template"); 6221 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext, 6222 /*ExplicitArgs*/ nullptr, 6223 ObjectType, ObjectClassification, 6224 Args, CandidateSet, 6225 SuppressUserConversions); 6226 } else { 6227 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext, 6228 ObjectType, ObjectClassification, 6229 Args, 6230 CandidateSet, SuppressUserConversions); 6231 } 6232 } 6233 6234 /// AddMethodCandidate - Adds the given C++ member function to the set 6235 /// of candidate functions, using the given function call arguments 6236 /// and the object argument (@c Object). For example, in a call 6237 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 6238 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 6239 /// allow user-defined conversions via constructors or conversion 6240 /// operators. 6241 void 6242 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, 6243 CXXRecordDecl *ActingContext, QualType ObjectType, 6244 Expr::Classification ObjectClassification, 6245 ArrayRef<Expr *> Args, 6246 OverloadCandidateSet &CandidateSet, 6247 bool SuppressUserConversions, 6248 bool PartialOverloading) { 6249 const FunctionProtoType *Proto 6250 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>()); 6251 assert(Proto && "Methods without a prototype cannot be overloaded"); 6252 assert(!isa<CXXConstructorDecl>(Method) && 6253 "Use AddOverloadCandidate for constructors"); 6254 6255 if (!CandidateSet.isNewCandidate(Method)) 6256 return; 6257 6258 // C++11 [class.copy]p23: [DR1402] 6259 // A defaulted move assignment operator that is defined as deleted is 6260 // ignored by overload resolution. 6261 if (Method->isDefaulted() && Method->isDeleted() && 6262 Method->isMoveAssignmentOperator()) 6263 return; 6264 6265 // Overload resolution is always an unevaluated context. 6266 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6267 6268 // Add this candidate 6269 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6270 Candidate.FoundDecl = FoundDecl; 6271 Candidate.Function = Method; 6272 Candidate.IsSurrogate = false; 6273 Candidate.IgnoreObjectArgument = false; 6274 Candidate.ExplicitCallArguments = Args.size(); 6275 6276 unsigned NumParams = Proto->getNumParams(); 6277 6278 // (C++ 13.3.2p2): A candidate function having fewer than m 6279 // parameters is viable only if it has an ellipsis in its parameter 6280 // list (8.3.5). 6281 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) && 6282 !Proto->isVariadic()) { 6283 Candidate.Viable = false; 6284 Candidate.FailureKind = ovl_fail_too_many_arguments; 6285 return; 6286 } 6287 6288 // (C++ 13.3.2p2): A candidate function having more than m parameters 6289 // is viable only if the (m+1)st parameter has a default argument 6290 // (8.3.6). For the purposes of overload resolution, the 6291 // parameter list is truncated on the right, so that there are 6292 // exactly m parameters. 6293 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 6294 if (Args.size() < MinRequiredArgs && !PartialOverloading) { 6295 // Not enough arguments. 6296 Candidate.Viable = false; 6297 Candidate.FailureKind = ovl_fail_too_few_arguments; 6298 return; 6299 } 6300 6301 Candidate.Viable = true; 6302 6303 if (Method->isStatic() || ObjectType.isNull()) 6304 // The implicit object argument is ignored. 6305 Candidate.IgnoreObjectArgument = true; 6306 else { 6307 // Determine the implicit conversion sequence for the object 6308 // parameter. 6309 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6310 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification, 6311 Method, ActingContext); 6312 if (Candidate.Conversions[0].isBad()) { 6313 Candidate.Viable = false; 6314 Candidate.FailureKind = ovl_fail_bad_conversion; 6315 return; 6316 } 6317 } 6318 6319 // (CUDA B.1): Check for invalid calls between targets. 6320 if (getLangOpts().CUDA) 6321 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext)) 6322 if (!IsAllowedCUDACall(Caller, Method)) { 6323 Candidate.Viable = false; 6324 Candidate.FailureKind = ovl_fail_bad_target; 6325 return; 6326 } 6327 6328 // Determine the implicit conversion sequences for each of the 6329 // arguments. 6330 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) { 6331 if (ArgIdx < NumParams) { 6332 // (C++ 13.3.2p3): for F to be a viable function, there shall 6333 // exist for each argument an implicit conversion sequence 6334 // (13.3.3.1) that converts that argument to the corresponding 6335 // parameter of F. 6336 QualType ParamType = Proto->getParamType(ArgIdx); 6337 Candidate.Conversions[ArgIdx + 1] 6338 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6339 SuppressUserConversions, 6340 /*InOverloadResolution=*/true, 6341 /*AllowObjCWritebackConversion=*/ 6342 getLangOpts().ObjCAutoRefCount); 6343 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6344 Candidate.Viable = false; 6345 Candidate.FailureKind = ovl_fail_bad_conversion; 6346 return; 6347 } 6348 } else { 6349 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6350 // argument for which there is no corresponding parameter is 6351 // considered to "match the ellipsis" (C+ 13.3.3.1.3). 6352 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6353 } 6354 } 6355 6356 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) { 6357 Candidate.Viable = false; 6358 Candidate.FailureKind = ovl_fail_enable_if; 6359 Candidate.DeductionFailure.Data = FailedAttr; 6360 return; 6361 } 6362 } 6363 6364 /// \brief Add a C++ member function template as a candidate to the candidate 6365 /// set, using template argument deduction to produce an appropriate member 6366 /// function template specialization. 6367 void 6368 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, 6369 DeclAccessPair FoundDecl, 6370 CXXRecordDecl *ActingContext, 6371 TemplateArgumentListInfo *ExplicitTemplateArgs, 6372 QualType ObjectType, 6373 Expr::Classification ObjectClassification, 6374 ArrayRef<Expr *> Args, 6375 OverloadCandidateSet& CandidateSet, 6376 bool SuppressUserConversions, 6377 bool PartialOverloading) { 6378 if (!CandidateSet.isNewCandidate(MethodTmpl)) 6379 return; 6380 6381 // C++ [over.match.funcs]p7: 6382 // In each case where a candidate is a function template, candidate 6383 // function template specializations are generated using template argument 6384 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6385 // candidate functions in the usual way.113) A given name can refer to one 6386 // or more function templates and also to a set of overloaded non-template 6387 // functions. In such a case, the candidate functions generated from each 6388 // function template are combined with the set of non-template candidate 6389 // functions. 6390 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6391 FunctionDecl *Specialization = nullptr; 6392 if (TemplateDeductionResult Result 6393 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args, 6394 Specialization, Info, PartialOverloading)) { 6395 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6396 Candidate.FoundDecl = FoundDecl; 6397 Candidate.Function = MethodTmpl->getTemplatedDecl(); 6398 Candidate.Viable = false; 6399 Candidate.FailureKind = ovl_fail_bad_deduction; 6400 Candidate.IsSurrogate = false; 6401 Candidate.IgnoreObjectArgument = false; 6402 Candidate.ExplicitCallArguments = Args.size(); 6403 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6404 Info); 6405 return; 6406 } 6407 6408 // Add the function template specialization produced by template argument 6409 // deduction as a candidate. 6410 assert(Specialization && "Missing member function template specialization?"); 6411 assert(isa<CXXMethodDecl>(Specialization) && 6412 "Specialization is not a member function?"); 6413 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl, 6414 ActingContext, ObjectType, ObjectClassification, Args, 6415 CandidateSet, SuppressUserConversions, PartialOverloading); 6416 } 6417 6418 /// \brief Add a C++ function template specialization as a candidate 6419 /// in the candidate set, using template argument deduction to produce 6420 /// an appropriate function template specialization. 6421 void 6422 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, 6423 DeclAccessPair FoundDecl, 6424 TemplateArgumentListInfo *ExplicitTemplateArgs, 6425 ArrayRef<Expr *> Args, 6426 OverloadCandidateSet& CandidateSet, 6427 bool SuppressUserConversions, 6428 bool PartialOverloading) { 6429 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6430 return; 6431 6432 // C++ [over.match.funcs]p7: 6433 // In each case where a candidate is a function template, candidate 6434 // function template specializations are generated using template argument 6435 // deduction (14.8.3, 14.8.2). Those candidates are then handled as 6436 // candidate functions in the usual way.113) A given name can refer to one 6437 // or more function templates and also to a set of overloaded non-template 6438 // functions. In such a case, the candidate functions generated from each 6439 // function template are combined with the set of non-template candidate 6440 // functions. 6441 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6442 FunctionDecl *Specialization = nullptr; 6443 if (TemplateDeductionResult Result 6444 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args, 6445 Specialization, Info, PartialOverloading)) { 6446 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6447 Candidate.FoundDecl = FoundDecl; 6448 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6449 Candidate.Viable = false; 6450 Candidate.FailureKind = ovl_fail_bad_deduction; 6451 Candidate.IsSurrogate = false; 6452 Candidate.IgnoreObjectArgument = false; 6453 Candidate.ExplicitCallArguments = Args.size(); 6454 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6455 Info); 6456 return; 6457 } 6458 6459 // Add the function template specialization produced by template argument 6460 // deduction as a candidate. 6461 assert(Specialization && "Missing function template specialization?"); 6462 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet, 6463 SuppressUserConversions, PartialOverloading); 6464 } 6465 6466 /// Determine whether this is an allowable conversion from the result 6467 /// of an explicit conversion operator to the expected type, per C++ 6468 /// [over.match.conv]p1 and [over.match.ref]p1. 6469 /// 6470 /// \param ConvType The return type of the conversion function. 6471 /// 6472 /// \param ToType The type we are converting to. 6473 /// 6474 /// \param AllowObjCPointerConversion Allow a conversion from one 6475 /// Objective-C pointer to another. 6476 /// 6477 /// \returns true if the conversion is allowable, false otherwise. 6478 static bool isAllowableExplicitConversion(Sema &S, 6479 QualType ConvType, QualType ToType, 6480 bool AllowObjCPointerConversion) { 6481 QualType ToNonRefType = ToType.getNonReferenceType(); 6482 6483 // Easy case: the types are the same. 6484 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType)) 6485 return true; 6486 6487 // Allow qualification conversions. 6488 bool ObjCLifetimeConversion; 6489 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false, 6490 ObjCLifetimeConversion)) 6491 return true; 6492 6493 // If we're not allowed to consider Objective-C pointer conversions, 6494 // we're done. 6495 if (!AllowObjCPointerConversion) 6496 return false; 6497 6498 // Is this an Objective-C pointer conversion? 6499 bool IncompatibleObjC = false; 6500 QualType ConvertedType; 6501 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType, 6502 IncompatibleObjC); 6503 } 6504 6505 /// AddConversionCandidate - Add a C++ conversion function as a 6506 /// candidate in the candidate set (C++ [over.match.conv], 6507 /// C++ [over.match.copy]). From is the expression we're converting from, 6508 /// and ToType is the type that we're eventually trying to convert to 6509 /// (which may or may not be the same type as the type that the 6510 /// conversion function produces). 6511 void 6512 Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 6513 DeclAccessPair FoundDecl, 6514 CXXRecordDecl *ActingContext, 6515 Expr *From, QualType ToType, 6516 OverloadCandidateSet& CandidateSet, 6517 bool AllowObjCConversionOnExplicit) { 6518 assert(!Conversion->getDescribedFunctionTemplate() && 6519 "Conversion function templates use AddTemplateConversionCandidate"); 6520 QualType ConvType = Conversion->getConversionType().getNonReferenceType(); 6521 if (!CandidateSet.isNewCandidate(Conversion)) 6522 return; 6523 6524 // If the conversion function has an undeduced return type, trigger its 6525 // deduction now. 6526 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) { 6527 if (DeduceReturnType(Conversion, From->getExprLoc())) 6528 return; 6529 ConvType = Conversion->getConversionType().getNonReferenceType(); 6530 } 6531 6532 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion 6533 // operator is only a candidate if its return type is the target type or 6534 // can be converted to the target type with a qualification conversion. 6535 if (Conversion->isExplicit() && 6536 !isAllowableExplicitConversion(*this, ConvType, ToType, 6537 AllowObjCConversionOnExplicit)) 6538 return; 6539 6540 // Overload resolution is always an unevaluated context. 6541 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6542 6543 // Add this candidate 6544 OverloadCandidate &Candidate = CandidateSet.addCandidate(1); 6545 Candidate.FoundDecl = FoundDecl; 6546 Candidate.Function = Conversion; 6547 Candidate.IsSurrogate = false; 6548 Candidate.IgnoreObjectArgument = false; 6549 Candidate.FinalConversion.setAsIdentityConversion(); 6550 Candidate.FinalConversion.setFromType(ConvType); 6551 Candidate.FinalConversion.setAllToTypes(ToType); 6552 Candidate.Viable = true; 6553 Candidate.ExplicitCallArguments = 1; 6554 6555 // C++ [over.match.funcs]p4: 6556 // For conversion functions, the function is considered to be a member of 6557 // the class of the implicit implied object argument for the purpose of 6558 // defining the type of the implicit object parameter. 6559 // 6560 // Determine the implicit conversion sequence for the implicit 6561 // object parameter. 6562 QualType ImplicitParamType = From->getType(); 6563 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>()) 6564 ImplicitParamType = FromPtrType->getPointeeType(); 6565 CXXRecordDecl *ConversionContext 6566 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl()); 6567 6568 Candidate.Conversions[0] = TryObjectArgumentInitialization( 6569 *this, CandidateSet.getLocation(), From->getType(), 6570 From->Classify(Context), Conversion, ConversionContext); 6571 6572 if (Candidate.Conversions[0].isBad()) { 6573 Candidate.Viable = false; 6574 Candidate.FailureKind = ovl_fail_bad_conversion; 6575 return; 6576 } 6577 6578 // We won't go through a user-defined type conversion function to convert a 6579 // derived to base as such conversions are given Conversion Rank. They only 6580 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user] 6581 QualType FromCanon 6582 = Context.getCanonicalType(From->getType().getUnqualifiedType()); 6583 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType(); 6584 if (FromCanon == ToCanon || 6585 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) { 6586 Candidate.Viable = false; 6587 Candidate.FailureKind = ovl_fail_trivial_conversion; 6588 return; 6589 } 6590 6591 // To determine what the conversion from the result of calling the 6592 // conversion function to the type we're eventually trying to 6593 // convert to (ToType), we need to synthesize a call to the 6594 // conversion function and attempt copy initialization from it. This 6595 // makes sure that we get the right semantics with respect to 6596 // lvalues/rvalues and the type. Fortunately, we can allocate this 6597 // call on the stack and we don't need its arguments to be 6598 // well-formed. 6599 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(), 6600 VK_LValue, From->getLocStart()); 6601 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack, 6602 Context.getPointerType(Conversion->getType()), 6603 CK_FunctionToPointerDecay, 6604 &ConversionRef, VK_RValue); 6605 6606 QualType ConversionType = Conversion->getConversionType(); 6607 if (!isCompleteType(From->getLocStart(), ConversionType)) { 6608 Candidate.Viable = false; 6609 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6610 return; 6611 } 6612 6613 ExprValueKind VK = Expr::getValueKindForType(ConversionType); 6614 6615 // Note that it is safe to allocate CallExpr on the stack here because 6616 // there are 0 arguments (i.e., nothing is allocated using ASTContext's 6617 // allocator). 6618 QualType CallResultType = ConversionType.getNonLValueExprType(Context); 6619 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK, 6620 From->getLocStart()); 6621 ImplicitConversionSequence ICS = 6622 TryCopyInitialization(*this, &Call, ToType, 6623 /*SuppressUserConversions=*/true, 6624 /*InOverloadResolution=*/false, 6625 /*AllowObjCWritebackConversion=*/false); 6626 6627 switch (ICS.getKind()) { 6628 case ImplicitConversionSequence::StandardConversion: 6629 Candidate.FinalConversion = ICS.Standard; 6630 6631 // C++ [over.ics.user]p3: 6632 // If the user-defined conversion is specified by a specialization of a 6633 // conversion function template, the second standard conversion sequence 6634 // shall have exact match rank. 6635 if (Conversion->getPrimaryTemplate() && 6636 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) { 6637 Candidate.Viable = false; 6638 Candidate.FailureKind = ovl_fail_final_conversion_not_exact; 6639 return; 6640 } 6641 6642 // C++0x [dcl.init.ref]p5: 6643 // In the second case, if the reference is an rvalue reference and 6644 // the second standard conversion sequence of the user-defined 6645 // conversion sequence includes an lvalue-to-rvalue conversion, the 6646 // program is ill-formed. 6647 if (ToType->isRValueReferenceType() && 6648 ICS.Standard.First == ICK_Lvalue_To_Rvalue) { 6649 Candidate.Viable = false; 6650 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6651 return; 6652 } 6653 break; 6654 6655 case ImplicitConversionSequence::BadConversion: 6656 Candidate.Viable = false; 6657 Candidate.FailureKind = ovl_fail_bad_final_conversion; 6658 return; 6659 6660 default: 6661 llvm_unreachable( 6662 "Can only end up with a standard conversion sequence or failure"); 6663 } 6664 6665 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6666 Candidate.Viable = false; 6667 Candidate.FailureKind = ovl_fail_enable_if; 6668 Candidate.DeductionFailure.Data = FailedAttr; 6669 return; 6670 } 6671 } 6672 6673 /// \brief Adds a conversion function template specialization 6674 /// candidate to the overload set, using template argument deduction 6675 /// to deduce the template arguments of the conversion function 6676 /// template from the type that we are converting to (C++ 6677 /// [temp.deduct.conv]). 6678 void 6679 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, 6680 DeclAccessPair FoundDecl, 6681 CXXRecordDecl *ActingDC, 6682 Expr *From, QualType ToType, 6683 OverloadCandidateSet &CandidateSet, 6684 bool AllowObjCConversionOnExplicit) { 6685 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) && 6686 "Only conversion function templates permitted here"); 6687 6688 if (!CandidateSet.isNewCandidate(FunctionTemplate)) 6689 return; 6690 6691 TemplateDeductionInfo Info(CandidateSet.getLocation()); 6692 CXXConversionDecl *Specialization = nullptr; 6693 if (TemplateDeductionResult Result 6694 = DeduceTemplateArguments(FunctionTemplate, ToType, 6695 Specialization, Info)) { 6696 OverloadCandidate &Candidate = CandidateSet.addCandidate(); 6697 Candidate.FoundDecl = FoundDecl; 6698 Candidate.Function = FunctionTemplate->getTemplatedDecl(); 6699 Candidate.Viable = false; 6700 Candidate.FailureKind = ovl_fail_bad_deduction; 6701 Candidate.IsSurrogate = false; 6702 Candidate.IgnoreObjectArgument = false; 6703 Candidate.ExplicitCallArguments = 1; 6704 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result, 6705 Info); 6706 return; 6707 } 6708 6709 // Add the conversion function template specialization produced by 6710 // template argument deduction as a candidate. 6711 assert(Specialization && "Missing function template specialization?"); 6712 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType, 6713 CandidateSet, AllowObjCConversionOnExplicit); 6714 } 6715 6716 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that 6717 /// converts the given @c Object to a function pointer via the 6718 /// conversion function @c Conversion, and then attempts to call it 6719 /// with the given arguments (C++ [over.call.object]p2-4). Proto is 6720 /// the type of function that we'll eventually be calling. 6721 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 6722 DeclAccessPair FoundDecl, 6723 CXXRecordDecl *ActingContext, 6724 const FunctionProtoType *Proto, 6725 Expr *Object, 6726 ArrayRef<Expr *> Args, 6727 OverloadCandidateSet& CandidateSet) { 6728 if (!CandidateSet.isNewCandidate(Conversion)) 6729 return; 6730 6731 // Overload resolution is always an unevaluated context. 6732 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6733 6734 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1); 6735 Candidate.FoundDecl = FoundDecl; 6736 Candidate.Function = nullptr; 6737 Candidate.Surrogate = Conversion; 6738 Candidate.Viable = true; 6739 Candidate.IsSurrogate = true; 6740 Candidate.IgnoreObjectArgument = false; 6741 Candidate.ExplicitCallArguments = Args.size(); 6742 6743 // Determine the implicit conversion sequence for the implicit 6744 // object parameter. 6745 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization( 6746 *this, CandidateSet.getLocation(), Object->getType(), 6747 Object->Classify(Context), Conversion, ActingContext); 6748 if (ObjectInit.isBad()) { 6749 Candidate.Viable = false; 6750 Candidate.FailureKind = ovl_fail_bad_conversion; 6751 Candidate.Conversions[0] = ObjectInit; 6752 return; 6753 } 6754 6755 // The first conversion is actually a user-defined conversion whose 6756 // first conversion is ObjectInit's standard conversion (which is 6757 // effectively a reference binding). Record it as such. 6758 Candidate.Conversions[0].setUserDefined(); 6759 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 6760 Candidate.Conversions[0].UserDefined.EllipsisConversion = false; 6761 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false; 6762 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 6763 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl; 6764 Candidate.Conversions[0].UserDefined.After 6765 = Candidate.Conversions[0].UserDefined.Before; 6766 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 6767 6768 // Find the 6769 unsigned NumParams = Proto->getNumParams(); 6770 6771 // (C++ 13.3.2p2): A candidate function having fewer than m 6772 // parameters is viable only if it has an ellipsis in its parameter 6773 // list (8.3.5). 6774 if (Args.size() > NumParams && !Proto->isVariadic()) { 6775 Candidate.Viable = false; 6776 Candidate.FailureKind = ovl_fail_too_many_arguments; 6777 return; 6778 } 6779 6780 // Function types don't have any default arguments, so just check if 6781 // we have enough arguments. 6782 if (Args.size() < NumParams) { 6783 // Not enough arguments. 6784 Candidate.Viable = false; 6785 Candidate.FailureKind = ovl_fail_too_few_arguments; 6786 return; 6787 } 6788 6789 // Determine the implicit conversion sequences for each of the 6790 // arguments. 6791 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6792 if (ArgIdx < NumParams) { 6793 // (C++ 13.3.2p3): for F to be a viable function, there shall 6794 // exist for each argument an implicit conversion sequence 6795 // (13.3.3.1) that converts that argument to the corresponding 6796 // parameter of F. 6797 QualType ParamType = Proto->getParamType(ArgIdx); 6798 Candidate.Conversions[ArgIdx + 1] 6799 = TryCopyInitialization(*this, Args[ArgIdx], ParamType, 6800 /*SuppressUserConversions=*/false, 6801 /*InOverloadResolution=*/false, 6802 /*AllowObjCWritebackConversion=*/ 6803 getLangOpts().ObjCAutoRefCount); 6804 if (Candidate.Conversions[ArgIdx + 1].isBad()) { 6805 Candidate.Viable = false; 6806 Candidate.FailureKind = ovl_fail_bad_conversion; 6807 return; 6808 } 6809 } else { 6810 // (C++ 13.3.2p2): For the purposes of overload resolution, any 6811 // argument for which there is no corresponding parameter is 6812 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 6813 Candidate.Conversions[ArgIdx + 1].setEllipsis(); 6814 } 6815 } 6816 6817 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) { 6818 Candidate.Viable = false; 6819 Candidate.FailureKind = ovl_fail_enable_if; 6820 Candidate.DeductionFailure.Data = FailedAttr; 6821 return; 6822 } 6823 } 6824 6825 /// \brief Add overload candidates for overloaded operators that are 6826 /// member functions. 6827 /// 6828 /// Add the overloaded operator candidates that are member functions 6829 /// for the operator Op that was used in an operator expression such 6830 /// as "x Op y". , Args/NumArgs provides the operator arguments, and 6831 /// CandidateSet will store the added overload candidates. (C++ 6832 /// [over.match.oper]). 6833 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op, 6834 SourceLocation OpLoc, 6835 ArrayRef<Expr *> Args, 6836 OverloadCandidateSet& CandidateSet, 6837 SourceRange OpRange) { 6838 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 6839 6840 // C++ [over.match.oper]p3: 6841 // For a unary operator @ with an operand of a type whose 6842 // cv-unqualified version is T1, and for a binary operator @ with 6843 // a left operand of a type whose cv-unqualified version is T1 and 6844 // a right operand of a type whose cv-unqualified version is T2, 6845 // three sets of candidate functions, designated member 6846 // candidates, non-member candidates and built-in candidates, are 6847 // constructed as follows: 6848 QualType T1 = Args[0]->getType(); 6849 6850 // -- If T1 is a complete class type or a class currently being 6851 // defined, the set of member candidates is the result of the 6852 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 6853 // the set of member candidates is empty. 6854 if (const RecordType *T1Rec = T1->getAs<RecordType>()) { 6855 // Complete the type if it can be completed. 6856 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined()) 6857 return; 6858 // If the type is neither complete nor being defined, bail out now. 6859 if (!T1Rec->getDecl()->getDefinition()) 6860 return; 6861 6862 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName); 6863 LookupQualifiedName(Operators, T1Rec->getDecl()); 6864 Operators.suppressDiagnostics(); 6865 6866 for (LookupResult::iterator Oper = Operators.begin(), 6867 OperEnd = Operators.end(); 6868 Oper != OperEnd; 6869 ++Oper) 6870 AddMethodCandidate(Oper.getPair(), Args[0]->getType(), 6871 Args[0]->Classify(Context), 6872 Args.slice(1), 6873 CandidateSet, 6874 /* SuppressUserConversions = */ false); 6875 } 6876 } 6877 6878 /// AddBuiltinCandidate - Add a candidate for a built-in 6879 /// operator. ResultTy and ParamTys are the result and parameter types 6880 /// of the built-in candidate, respectively. Args and NumArgs are the 6881 /// arguments being passed to the candidate. IsAssignmentOperator 6882 /// should be true when this built-in candidate is an assignment 6883 /// operator. NumContextualBoolArguments is the number of arguments 6884 /// (at the beginning of the argument list) that will be contextually 6885 /// converted to bool. 6886 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 6887 ArrayRef<Expr *> Args, 6888 OverloadCandidateSet& CandidateSet, 6889 bool IsAssignmentOperator, 6890 unsigned NumContextualBoolArguments) { 6891 // Overload resolution is always an unevaluated context. 6892 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated); 6893 6894 // Add this candidate 6895 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size()); 6896 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none); 6897 Candidate.Function = nullptr; 6898 Candidate.IsSurrogate = false; 6899 Candidate.IgnoreObjectArgument = false; 6900 Candidate.BuiltinTypes.ResultTy = ResultTy; 6901 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 6902 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 6903 6904 // Determine the implicit conversion sequences for each of the 6905 // arguments. 6906 Candidate.Viable = true; 6907 Candidate.ExplicitCallArguments = Args.size(); 6908 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 6909 // C++ [over.match.oper]p4: 6910 // For the built-in assignment operators, conversions of the 6911 // left operand are restricted as follows: 6912 // -- no temporaries are introduced to hold the left operand, and 6913 // -- no user-defined conversions are applied to the left 6914 // operand to achieve a type match with the left-most 6915 // parameter of a built-in candidate. 6916 // 6917 // We block these conversions by turning off user-defined 6918 // conversions, since that is the only way that initialization of 6919 // a reference to a non-class type can occur from something that 6920 // is not of the same type. 6921 if (ArgIdx < NumContextualBoolArguments) { 6922 assert(ParamTys[ArgIdx] == Context.BoolTy && 6923 "Contextual conversion to bool requires bool type"); 6924 Candidate.Conversions[ArgIdx] 6925 = TryContextuallyConvertToBool(*this, Args[ArgIdx]); 6926 } else { 6927 Candidate.Conversions[ArgIdx] 6928 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx], 6929 ArgIdx == 0 && IsAssignmentOperator, 6930 /*InOverloadResolution=*/false, 6931 /*AllowObjCWritebackConversion=*/ 6932 getLangOpts().ObjCAutoRefCount); 6933 } 6934 if (Candidate.Conversions[ArgIdx].isBad()) { 6935 Candidate.Viable = false; 6936 Candidate.FailureKind = ovl_fail_bad_conversion; 6937 break; 6938 } 6939 } 6940 } 6941 6942 namespace { 6943 6944 /// BuiltinCandidateTypeSet - A set of types that will be used for the 6945 /// candidate operator functions for built-in operators (C++ 6946 /// [over.built]). The types are separated into pointer types and 6947 /// enumeration types. 6948 class BuiltinCandidateTypeSet { 6949 /// TypeSet - A set of types. 6950 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>, 6951 llvm::SmallPtrSet<QualType, 8>> TypeSet; 6952 6953 /// PointerTypes - The set of pointer types that will be used in the 6954 /// built-in candidates. 6955 TypeSet PointerTypes; 6956 6957 /// MemberPointerTypes - The set of member pointer types that will be 6958 /// used in the built-in candidates. 6959 TypeSet MemberPointerTypes; 6960 6961 /// EnumerationTypes - The set of enumeration types that will be 6962 /// used in the built-in candidates. 6963 TypeSet EnumerationTypes; 6964 6965 /// \brief The set of vector types that will be used in the built-in 6966 /// candidates. 6967 TypeSet VectorTypes; 6968 6969 /// \brief A flag indicating non-record types are viable candidates 6970 bool HasNonRecordTypes; 6971 6972 /// \brief A flag indicating whether either arithmetic or enumeration types 6973 /// were present in the candidate set. 6974 bool HasArithmeticOrEnumeralTypes; 6975 6976 /// \brief A flag indicating whether the nullptr type was present in the 6977 /// candidate set. 6978 bool HasNullPtrType; 6979 6980 /// Sema - The semantic analysis instance where we are building the 6981 /// candidate type set. 6982 Sema &SemaRef; 6983 6984 /// Context - The AST context in which we will build the type sets. 6985 ASTContext &Context; 6986 6987 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 6988 const Qualifiers &VisibleQuals); 6989 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty); 6990 6991 public: 6992 /// iterator - Iterates through the types that are part of the set. 6993 typedef TypeSet::iterator iterator; 6994 6995 BuiltinCandidateTypeSet(Sema &SemaRef) 6996 : HasNonRecordTypes(false), 6997 HasArithmeticOrEnumeralTypes(false), 6998 HasNullPtrType(false), 6999 SemaRef(SemaRef), 7000 Context(SemaRef.Context) { } 7001 7002 void AddTypesConvertedFrom(QualType Ty, 7003 SourceLocation Loc, 7004 bool AllowUserConversions, 7005 bool AllowExplicitConversions, 7006 const Qualifiers &VisibleTypeConversionsQuals); 7007 7008 /// pointer_begin - First pointer type found; 7009 iterator pointer_begin() { return PointerTypes.begin(); } 7010 7011 /// pointer_end - Past the last pointer type found; 7012 iterator pointer_end() { return PointerTypes.end(); } 7013 7014 /// member_pointer_begin - First member pointer type found; 7015 iterator member_pointer_begin() { return MemberPointerTypes.begin(); } 7016 7017 /// member_pointer_end - Past the last member pointer type found; 7018 iterator member_pointer_end() { return MemberPointerTypes.end(); } 7019 7020 /// enumeration_begin - First enumeration type found; 7021 iterator enumeration_begin() { return EnumerationTypes.begin(); } 7022 7023 /// enumeration_end - Past the last enumeration type found; 7024 iterator enumeration_end() { return EnumerationTypes.end(); } 7025 7026 iterator vector_begin() { return VectorTypes.begin(); } 7027 iterator vector_end() { return VectorTypes.end(); } 7028 7029 bool hasNonRecordTypes() { return HasNonRecordTypes; } 7030 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; } 7031 bool hasNullPtrType() const { return HasNullPtrType; } 7032 }; 7033 7034 } // end anonymous namespace 7035 7036 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 7037 /// the set of pointer types along with any more-qualified variants of 7038 /// that type. For example, if @p Ty is "int const *", this routine 7039 /// will add "int const *", "int const volatile *", "int const 7040 /// restrict *", and "int const volatile restrict *" to the set of 7041 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7042 /// false otherwise. 7043 /// 7044 /// FIXME: what to do about extended qualifiers? 7045 bool 7046 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty, 7047 const Qualifiers &VisibleQuals) { 7048 7049 // Insert this type. 7050 if (!PointerTypes.insert(Ty)) 7051 return false; 7052 7053 QualType PointeeTy; 7054 const PointerType *PointerTy = Ty->getAs<PointerType>(); 7055 bool buildObjCPtr = false; 7056 if (!PointerTy) { 7057 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>(); 7058 PointeeTy = PTy->getPointeeType(); 7059 buildObjCPtr = true; 7060 } else { 7061 PointeeTy = PointerTy->getPointeeType(); 7062 } 7063 7064 // Don't add qualified variants of arrays. For one, they're not allowed 7065 // (the qualifier would sink to the element type), and for another, the 7066 // only overload situation where it matters is subscript or pointer +- int, 7067 // and those shouldn't have qualifier variants anyway. 7068 if (PointeeTy->isArrayType()) 7069 return true; 7070 7071 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7072 bool hasVolatile = VisibleQuals.hasVolatile(); 7073 bool hasRestrict = VisibleQuals.hasRestrict(); 7074 7075 // Iterate through all strict supersets of BaseCVR. 7076 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7077 if ((CVR | BaseCVR) != CVR) continue; 7078 // Skip over volatile if no volatile found anywhere in the types. 7079 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue; 7080 7081 // Skip over restrict if no restrict found anywhere in the types, or if 7082 // the type cannot be restrict-qualified. 7083 if ((CVR & Qualifiers::Restrict) && 7084 (!hasRestrict || 7085 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType())))) 7086 continue; 7087 7088 // Build qualified pointee type. 7089 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7090 7091 // Build qualified pointer type. 7092 QualType QPointerTy; 7093 if (!buildObjCPtr) 7094 QPointerTy = Context.getPointerType(QPointeeTy); 7095 else 7096 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy); 7097 7098 // Insert qualified pointer type. 7099 PointerTypes.insert(QPointerTy); 7100 } 7101 7102 return true; 7103 } 7104 7105 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty 7106 /// to the set of pointer types along with any more-qualified variants of 7107 /// that type. For example, if @p Ty is "int const *", this routine 7108 /// will add "int const *", "int const volatile *", "int const 7109 /// restrict *", and "int const volatile restrict *" to the set of 7110 /// pointer types. Returns true if the add of @p Ty itself succeeded, 7111 /// false otherwise. 7112 /// 7113 /// FIXME: what to do about extended qualifiers? 7114 bool 7115 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants( 7116 QualType Ty) { 7117 // Insert this type. 7118 if (!MemberPointerTypes.insert(Ty)) 7119 return false; 7120 7121 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>(); 7122 assert(PointerTy && "type was not a member pointer type!"); 7123 7124 QualType PointeeTy = PointerTy->getPointeeType(); 7125 // Don't add qualified variants of arrays. For one, they're not allowed 7126 // (the qualifier would sink to the element type), and for another, the 7127 // only overload situation where it matters is subscript or pointer +- int, 7128 // and those shouldn't have qualifier variants anyway. 7129 if (PointeeTy->isArrayType()) 7130 return true; 7131 const Type *ClassTy = PointerTy->getClass(); 7132 7133 // Iterate through all strict supersets of the pointee type's CVR 7134 // qualifiers. 7135 unsigned BaseCVR = PointeeTy.getCVRQualifiers(); 7136 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) { 7137 if ((CVR | BaseCVR) != CVR) continue; 7138 7139 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR); 7140 MemberPointerTypes.insert( 7141 Context.getMemberPointerType(QPointeeTy, ClassTy)); 7142 } 7143 7144 return true; 7145 } 7146 7147 /// AddTypesConvertedFrom - Add each of the types to which the type @p 7148 /// Ty can be implicit converted to the given set of @p Types. We're 7149 /// primarily interested in pointer types and enumeration types. We also 7150 /// take member pointer types, for the conditional operator. 7151 /// AllowUserConversions is true if we should look at the conversion 7152 /// functions of a class type, and AllowExplicitConversions if we 7153 /// should also include the explicit conversion functions of a class 7154 /// type. 7155 void 7156 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 7157 SourceLocation Loc, 7158 bool AllowUserConversions, 7159 bool AllowExplicitConversions, 7160 const Qualifiers &VisibleQuals) { 7161 // Only deal with canonical types. 7162 Ty = Context.getCanonicalType(Ty); 7163 7164 // Look through reference types; they aren't part of the type of an 7165 // expression for the purposes of conversions. 7166 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>()) 7167 Ty = RefTy->getPointeeType(); 7168 7169 // If we're dealing with an array type, decay to the pointer. 7170 if (Ty->isArrayType()) 7171 Ty = SemaRef.Context.getArrayDecayedType(Ty); 7172 7173 // Otherwise, we don't care about qualifiers on the type. 7174 Ty = Ty.getLocalUnqualifiedType(); 7175 7176 // Flag if we ever add a non-record type. 7177 const RecordType *TyRec = Ty->getAs<RecordType>(); 7178 HasNonRecordTypes = HasNonRecordTypes || !TyRec; 7179 7180 // Flag if we encounter an arithmetic type. 7181 HasArithmeticOrEnumeralTypes = 7182 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType(); 7183 7184 if (Ty->isObjCIdType() || Ty->isObjCClassType()) 7185 PointerTypes.insert(Ty); 7186 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) { 7187 // Insert our type, and its more-qualified variants, into the set 7188 // of types. 7189 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals)) 7190 return; 7191 } else if (Ty->isMemberPointerType()) { 7192 // Member pointers are far easier, since the pointee can't be converted. 7193 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty)) 7194 return; 7195 } else if (Ty->isEnumeralType()) { 7196 HasArithmeticOrEnumeralTypes = true; 7197 EnumerationTypes.insert(Ty); 7198 } else if (Ty->isVectorType()) { 7199 // We treat vector types as arithmetic types in many contexts as an 7200 // extension. 7201 HasArithmeticOrEnumeralTypes = true; 7202 VectorTypes.insert(Ty); 7203 } else if (Ty->isNullPtrType()) { 7204 HasNullPtrType = true; 7205 } else if (AllowUserConversions && TyRec) { 7206 // No conversion functions in incomplete types. 7207 if (!SemaRef.isCompleteType(Loc, Ty)) 7208 return; 7209 7210 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7211 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7212 if (isa<UsingShadowDecl>(D)) 7213 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7214 7215 // Skip conversion function templates; they don't tell us anything 7216 // about which builtin types we can convert to. 7217 if (isa<FunctionTemplateDecl>(D)) 7218 continue; 7219 7220 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 7221 if (AllowExplicitConversions || !Conv->isExplicit()) { 7222 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false, 7223 VisibleQuals); 7224 } 7225 } 7226 } 7227 } 7228 7229 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds 7230 /// the volatile- and non-volatile-qualified assignment operators for the 7231 /// given type to the candidate set. 7232 static void AddBuiltinAssignmentOperatorCandidates(Sema &S, 7233 QualType T, 7234 ArrayRef<Expr *> Args, 7235 OverloadCandidateSet &CandidateSet) { 7236 QualType ParamTypes[2]; 7237 7238 // T& operator=(T&, T) 7239 ParamTypes[0] = S.Context.getLValueReferenceType(T); 7240 ParamTypes[1] = T; 7241 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7242 /*IsAssignmentOperator=*/true); 7243 7244 if (!S.Context.getCanonicalType(T).isVolatileQualified()) { 7245 // volatile T& operator=(volatile T&, T) 7246 ParamTypes[0] 7247 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T)); 7248 ParamTypes[1] = T; 7249 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 7250 /*IsAssignmentOperator=*/true); 7251 } 7252 } 7253 7254 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, 7255 /// if any, found in visible type conversion functions found in ArgExpr's type. 7256 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) { 7257 Qualifiers VRQuals; 7258 const RecordType *TyRec; 7259 if (const MemberPointerType *RHSMPType = 7260 ArgExpr->getType()->getAs<MemberPointerType>()) 7261 TyRec = RHSMPType->getClass()->getAs<RecordType>(); 7262 else 7263 TyRec = ArgExpr->getType()->getAs<RecordType>(); 7264 if (!TyRec) { 7265 // Just to be safe, assume the worst case. 7266 VRQuals.addVolatile(); 7267 VRQuals.addRestrict(); 7268 return VRQuals; 7269 } 7270 7271 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 7272 if (!ClassDecl->hasDefinition()) 7273 return VRQuals; 7274 7275 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) { 7276 if (isa<UsingShadowDecl>(D)) 7277 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 7278 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) { 7279 QualType CanTy = Context.getCanonicalType(Conv->getConversionType()); 7280 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>()) 7281 CanTy = ResTypeRef->getPointeeType(); 7282 // Need to go down the pointer/mempointer chain and add qualifiers 7283 // as see them. 7284 bool done = false; 7285 while (!done) { 7286 if (CanTy.isRestrictQualified()) 7287 VRQuals.addRestrict(); 7288 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>()) 7289 CanTy = ResTypePtr->getPointeeType(); 7290 else if (const MemberPointerType *ResTypeMPtr = 7291 CanTy->getAs<MemberPointerType>()) 7292 CanTy = ResTypeMPtr->getPointeeType(); 7293 else 7294 done = true; 7295 if (CanTy.isVolatileQualified()) 7296 VRQuals.addVolatile(); 7297 if (VRQuals.hasRestrict() && VRQuals.hasVolatile()) 7298 return VRQuals; 7299 } 7300 } 7301 } 7302 return VRQuals; 7303 } 7304 7305 namespace { 7306 7307 /// \brief Helper class to manage the addition of builtin operator overload 7308 /// candidates. It provides shared state and utility methods used throughout 7309 /// the process, as well as a helper method to add each group of builtin 7310 /// operator overloads from the standard to a candidate set. 7311 class BuiltinOperatorOverloadBuilder { 7312 // Common instance state available to all overload candidate addition methods. 7313 Sema &S; 7314 ArrayRef<Expr *> Args; 7315 Qualifiers VisibleTypeConversionsQuals; 7316 bool HasArithmeticOrEnumeralCandidateType; 7317 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes; 7318 OverloadCandidateSet &CandidateSet; 7319 7320 // Define some constants used to index and iterate over the arithemetic types 7321 // provided via the getArithmeticType() method below. 7322 // The "promoted arithmetic types" are the arithmetic 7323 // types are that preserved by promotion (C++ [over.built]p2). 7324 static const unsigned FirstIntegralType = 4; 7325 static const unsigned LastIntegralType = 21; 7326 static const unsigned FirstPromotedIntegralType = 4, 7327 LastPromotedIntegralType = 12; 7328 static const unsigned FirstPromotedArithmeticType = 0, 7329 LastPromotedArithmeticType = 12; 7330 static const unsigned NumArithmeticTypes = 21; 7331 7332 /// \brief Get the canonical type for a given arithmetic type index. 7333 CanQualType getArithmeticType(unsigned index) { 7334 assert(index < NumArithmeticTypes); 7335 static CanQualType ASTContext::* const 7336 ArithmeticTypes[NumArithmeticTypes] = { 7337 // Start of promoted types. 7338 &ASTContext::FloatTy, 7339 &ASTContext::DoubleTy, 7340 &ASTContext::LongDoubleTy, 7341 &ASTContext::Float128Ty, 7342 7343 // Start of integral types. 7344 &ASTContext::IntTy, 7345 &ASTContext::LongTy, 7346 &ASTContext::LongLongTy, 7347 &ASTContext::Int128Ty, 7348 &ASTContext::UnsignedIntTy, 7349 &ASTContext::UnsignedLongTy, 7350 &ASTContext::UnsignedLongLongTy, 7351 &ASTContext::UnsignedInt128Ty, 7352 // End of promoted types. 7353 7354 &ASTContext::BoolTy, 7355 &ASTContext::CharTy, 7356 &ASTContext::WCharTy, 7357 &ASTContext::Char16Ty, 7358 &ASTContext::Char32Ty, 7359 &ASTContext::SignedCharTy, 7360 &ASTContext::ShortTy, 7361 &ASTContext::UnsignedCharTy, 7362 &ASTContext::UnsignedShortTy, 7363 // End of integral types. 7364 // FIXME: What about complex? What about half? 7365 }; 7366 return S.Context.*ArithmeticTypes[index]; 7367 } 7368 7369 /// \brief Gets the canonical type resulting from the usual arithemetic 7370 /// converions for the given arithmetic types. 7371 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) { 7372 // Accelerator table for performing the usual arithmetic conversions. 7373 // The rules are basically: 7374 // - if either is floating-point, use the wider floating-point 7375 // - if same signedness, use the higher rank 7376 // - if same size, use unsigned of the higher rank 7377 // - use the larger type 7378 // These rules, together with the axiom that higher ranks are 7379 // never smaller, are sufficient to precompute all of these results 7380 // *except* when dealing with signed types of higher rank. 7381 // (we could precompute SLL x UI for all known platforms, but it's 7382 // better not to make any assumptions). 7383 // We assume that int128 has a higher rank than long long on all platforms. 7384 enum PromotedType : int8_t { 7385 Dep=-1, 7386 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 7387 }; 7388 static const PromotedType ConversionsTable[LastPromotedArithmeticType] 7389 [LastPromotedArithmeticType] = { 7390 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt }, 7391 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl }, 7392 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl }, 7393 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 }, 7394 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 }, 7395 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 }, 7396 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 }, 7397 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 }, 7398 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 }, 7399 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 }, 7400 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 }, 7401 }; 7402 7403 assert(L < LastPromotedArithmeticType); 7404 assert(R < LastPromotedArithmeticType); 7405 int Idx = ConversionsTable[L][R]; 7406 7407 // Fast path: the table gives us a concrete answer. 7408 if (Idx != Dep) return getArithmeticType(Idx); 7409 7410 // Slow path: we need to compare widths. 7411 // An invariant is that the signed type has higher rank. 7412 CanQualType LT = getArithmeticType(L), 7413 RT = getArithmeticType(R); 7414 unsigned LW = S.Context.getIntWidth(LT), 7415 RW = S.Context.getIntWidth(RT); 7416 7417 // If they're different widths, use the signed type. 7418 if (LW > RW) return LT; 7419 else if (LW < RW) return RT; 7420 7421 // Otherwise, use the unsigned type of the signed type's rank. 7422 if (L == SL || R == SL) return S.Context.UnsignedLongTy; 7423 assert(L == SLL || R == SLL); 7424 return S.Context.UnsignedLongLongTy; 7425 } 7426 7427 /// \brief Helper method to factor out the common pattern of adding overloads 7428 /// for '++' and '--' builtin operators. 7429 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy, 7430 bool HasVolatile, 7431 bool HasRestrict) { 7432 QualType ParamTypes[2] = { 7433 S.Context.getLValueReferenceType(CandidateTy), 7434 S.Context.IntTy 7435 }; 7436 7437 // Non-volatile version. 7438 if (Args.size() == 1) 7439 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7440 else 7441 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7442 7443 // Use a heuristic to reduce number of builtin candidates in the set: 7444 // add volatile version only if there are conversions to a volatile type. 7445 if (HasVolatile) { 7446 ParamTypes[0] = 7447 S.Context.getLValueReferenceType( 7448 S.Context.getVolatileType(CandidateTy)); 7449 if (Args.size() == 1) 7450 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7451 else 7452 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7453 } 7454 7455 // Add restrict version only if there are conversions to a restrict type 7456 // and our candidate type is a non-restrict-qualified pointer. 7457 if (HasRestrict && CandidateTy->isAnyPointerType() && 7458 !CandidateTy.isRestrictQualified()) { 7459 ParamTypes[0] 7460 = S.Context.getLValueReferenceType( 7461 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict)); 7462 if (Args.size() == 1) 7463 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7464 else 7465 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7466 7467 if (HasVolatile) { 7468 ParamTypes[0] 7469 = S.Context.getLValueReferenceType( 7470 S.Context.getCVRQualifiedType(CandidateTy, 7471 (Qualifiers::Volatile | 7472 Qualifiers::Restrict))); 7473 if (Args.size() == 1) 7474 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 7475 else 7476 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet); 7477 } 7478 } 7479 7480 } 7481 7482 public: 7483 BuiltinOperatorOverloadBuilder( 7484 Sema &S, ArrayRef<Expr *> Args, 7485 Qualifiers VisibleTypeConversionsQuals, 7486 bool HasArithmeticOrEnumeralCandidateType, 7487 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes, 7488 OverloadCandidateSet &CandidateSet) 7489 : S(S), Args(Args), 7490 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals), 7491 HasArithmeticOrEnumeralCandidateType( 7492 HasArithmeticOrEnumeralCandidateType), 7493 CandidateTypes(CandidateTypes), 7494 CandidateSet(CandidateSet) { 7495 // Validate some of our static helper constants in debug builds. 7496 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy && 7497 "Invalid first promoted integral type"); 7498 assert(getArithmeticType(LastPromotedIntegralType - 1) 7499 == S.Context.UnsignedInt128Ty && 7500 "Invalid last promoted integral type"); 7501 assert(getArithmeticType(FirstPromotedArithmeticType) 7502 == S.Context.FloatTy && 7503 "Invalid first promoted arithmetic type"); 7504 assert(getArithmeticType(LastPromotedArithmeticType - 1) 7505 == S.Context.UnsignedInt128Ty && 7506 "Invalid last promoted arithmetic type"); 7507 } 7508 7509 // C++ [over.built]p3: 7510 // 7511 // For every pair (T, VQ), where T is an arithmetic type, and VQ 7512 // is either volatile or empty, there exist candidate operator 7513 // functions of the form 7514 // 7515 // VQ T& operator++(VQ T&); 7516 // T operator++(VQ T&, int); 7517 // 7518 // C++ [over.built]p4: 7519 // 7520 // For every pair (T, VQ), where T is an arithmetic type other 7521 // than bool, and VQ is either volatile or empty, there exist 7522 // candidate operator functions of the form 7523 // 7524 // VQ T& operator--(VQ T&); 7525 // T operator--(VQ T&, int); 7526 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) { 7527 if (!HasArithmeticOrEnumeralCandidateType) 7528 return; 7529 7530 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 7531 Arith < NumArithmeticTypes; ++Arith) { 7532 addPlusPlusMinusMinusStyleOverloads( 7533 getArithmeticType(Arith), 7534 VisibleTypeConversionsQuals.hasVolatile(), 7535 VisibleTypeConversionsQuals.hasRestrict()); 7536 } 7537 } 7538 7539 // C++ [over.built]p5: 7540 // 7541 // For every pair (T, VQ), where T is a cv-qualified or 7542 // cv-unqualified object type, and VQ is either volatile or 7543 // empty, there exist candidate operator functions of the form 7544 // 7545 // T*VQ& operator++(T*VQ&); 7546 // T*VQ& operator--(T*VQ&); 7547 // T* operator++(T*VQ&, int); 7548 // T* operator--(T*VQ&, int); 7549 void addPlusPlusMinusMinusPointerOverloads() { 7550 for (BuiltinCandidateTypeSet::iterator 7551 Ptr = CandidateTypes[0].pointer_begin(), 7552 PtrEnd = CandidateTypes[0].pointer_end(); 7553 Ptr != PtrEnd; ++Ptr) { 7554 // Skip pointer types that aren't pointers to object types. 7555 if (!(*Ptr)->getPointeeType()->isObjectType()) 7556 continue; 7557 7558 addPlusPlusMinusMinusStyleOverloads(*Ptr, 7559 (!(*Ptr).isVolatileQualified() && 7560 VisibleTypeConversionsQuals.hasVolatile()), 7561 (!(*Ptr).isRestrictQualified() && 7562 VisibleTypeConversionsQuals.hasRestrict())); 7563 } 7564 } 7565 7566 // C++ [over.built]p6: 7567 // For every cv-qualified or cv-unqualified object type T, there 7568 // exist candidate operator functions of the form 7569 // 7570 // T& operator*(T*); 7571 // 7572 // C++ [over.built]p7: 7573 // For every function type T that does not have cv-qualifiers or a 7574 // ref-qualifier, there exist candidate operator functions of the form 7575 // T& operator*(T*); 7576 void addUnaryStarPointerOverloads() { 7577 for (BuiltinCandidateTypeSet::iterator 7578 Ptr = CandidateTypes[0].pointer_begin(), 7579 PtrEnd = CandidateTypes[0].pointer_end(); 7580 Ptr != PtrEnd; ++Ptr) { 7581 QualType ParamTy = *Ptr; 7582 QualType PointeeTy = ParamTy->getPointeeType(); 7583 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType()) 7584 continue; 7585 7586 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>()) 7587 if (Proto->getTypeQuals() || Proto->getRefQualifier()) 7588 continue; 7589 7590 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy), 7591 &ParamTy, Args, CandidateSet); 7592 } 7593 } 7594 7595 // C++ [over.built]p9: 7596 // For every promoted arithmetic type T, there exist candidate 7597 // operator functions of the form 7598 // 7599 // T operator+(T); 7600 // T operator-(T); 7601 void addUnaryPlusOrMinusArithmeticOverloads() { 7602 if (!HasArithmeticOrEnumeralCandidateType) 7603 return; 7604 7605 for (unsigned Arith = FirstPromotedArithmeticType; 7606 Arith < LastPromotedArithmeticType; ++Arith) { 7607 QualType ArithTy = getArithmeticType(Arith); 7608 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet); 7609 } 7610 7611 // Extension: We also add these operators for vector types. 7612 for (BuiltinCandidateTypeSet::iterator 7613 Vec = CandidateTypes[0].vector_begin(), 7614 VecEnd = CandidateTypes[0].vector_end(); 7615 Vec != VecEnd; ++Vec) { 7616 QualType VecTy = *Vec; 7617 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7618 } 7619 } 7620 7621 // C++ [over.built]p8: 7622 // For every type T, there exist candidate operator functions of 7623 // the form 7624 // 7625 // T* operator+(T*); 7626 void addUnaryPlusPointerOverloads() { 7627 for (BuiltinCandidateTypeSet::iterator 7628 Ptr = CandidateTypes[0].pointer_begin(), 7629 PtrEnd = CandidateTypes[0].pointer_end(); 7630 Ptr != PtrEnd; ++Ptr) { 7631 QualType ParamTy = *Ptr; 7632 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet); 7633 } 7634 } 7635 7636 // C++ [over.built]p10: 7637 // For every promoted integral type T, there exist candidate 7638 // operator functions of the form 7639 // 7640 // T operator~(T); 7641 void addUnaryTildePromotedIntegralOverloads() { 7642 if (!HasArithmeticOrEnumeralCandidateType) 7643 return; 7644 7645 for (unsigned Int = FirstPromotedIntegralType; 7646 Int < LastPromotedIntegralType; ++Int) { 7647 QualType IntTy = getArithmeticType(Int); 7648 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet); 7649 } 7650 7651 // Extension: We also add this operator for vector types. 7652 for (BuiltinCandidateTypeSet::iterator 7653 Vec = CandidateTypes[0].vector_begin(), 7654 VecEnd = CandidateTypes[0].vector_end(); 7655 Vec != VecEnd; ++Vec) { 7656 QualType VecTy = *Vec; 7657 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet); 7658 } 7659 } 7660 7661 // C++ [over.match.oper]p16: 7662 // For every pointer to member type T or type std::nullptr_t, there 7663 // exist candidate operator functions of the form 7664 // 7665 // bool operator==(T,T); 7666 // bool operator!=(T,T); 7667 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() { 7668 /// Set of (canonical) types that we've already handled. 7669 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7670 7671 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7672 for (BuiltinCandidateTypeSet::iterator 7673 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7674 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7675 MemPtr != MemPtrEnd; 7676 ++MemPtr) { 7677 // Don't add the same builtin candidate twice. 7678 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7679 continue; 7680 7681 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 7682 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7683 } 7684 7685 if (CandidateTypes[ArgIdx].hasNullPtrType()) { 7686 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy); 7687 if (AddedTypes.insert(NullPtrTy).second) { 7688 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy }; 7689 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 7690 CandidateSet); 7691 } 7692 } 7693 } 7694 } 7695 7696 // C++ [over.built]p15: 7697 // 7698 // For every T, where T is an enumeration type or a pointer type, 7699 // there exist candidate operator functions of the form 7700 // 7701 // bool operator<(T, T); 7702 // bool operator>(T, T); 7703 // bool operator<=(T, T); 7704 // bool operator>=(T, T); 7705 // bool operator==(T, T); 7706 // bool operator!=(T, T); 7707 void addRelationalPointerOrEnumeralOverloads() { 7708 // C++ [over.match.oper]p3: 7709 // [...]the built-in candidates include all of the candidate operator 7710 // functions defined in 13.6 that, compared to the given operator, [...] 7711 // do not have the same parameter-type-list as any non-template non-member 7712 // candidate. 7713 // 7714 // Note that in practice, this only affects enumeration types because there 7715 // aren't any built-in candidates of record type, and a user-defined operator 7716 // must have an operand of record or enumeration type. Also, the only other 7717 // overloaded operator with enumeration arguments, operator=, 7718 // cannot be overloaded for enumeration types, so this is the only place 7719 // where we must suppress candidates like this. 7720 llvm::DenseSet<std::pair<CanQualType, CanQualType> > 7721 UserDefinedBinaryOperators; 7722 7723 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7724 if (CandidateTypes[ArgIdx].enumeration_begin() != 7725 CandidateTypes[ArgIdx].enumeration_end()) { 7726 for (OverloadCandidateSet::iterator C = CandidateSet.begin(), 7727 CEnd = CandidateSet.end(); 7728 C != CEnd; ++C) { 7729 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2) 7730 continue; 7731 7732 if (C->Function->isFunctionTemplateSpecialization()) 7733 continue; 7734 7735 QualType FirstParamType = 7736 C->Function->getParamDecl(0)->getType().getUnqualifiedType(); 7737 QualType SecondParamType = 7738 C->Function->getParamDecl(1)->getType().getUnqualifiedType(); 7739 7740 // Skip if either parameter isn't of enumeral type. 7741 if (!FirstParamType->isEnumeralType() || 7742 !SecondParamType->isEnumeralType()) 7743 continue; 7744 7745 // Add this operator to the set of known user-defined operators. 7746 UserDefinedBinaryOperators.insert( 7747 std::make_pair(S.Context.getCanonicalType(FirstParamType), 7748 S.Context.getCanonicalType(SecondParamType))); 7749 } 7750 } 7751 } 7752 7753 /// Set of (canonical) types that we've already handled. 7754 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7755 7756 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 7757 for (BuiltinCandidateTypeSet::iterator 7758 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 7759 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 7760 Ptr != PtrEnd; ++Ptr) { 7761 // Don't add the same builtin candidate twice. 7762 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7763 continue; 7764 7765 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7766 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7767 } 7768 for (BuiltinCandidateTypeSet::iterator 7769 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7770 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7771 Enum != EnumEnd; ++Enum) { 7772 CanQualType CanonType = S.Context.getCanonicalType(*Enum); 7773 7774 // Don't add the same builtin candidate twice, or if a user defined 7775 // candidate exists. 7776 if (!AddedTypes.insert(CanonType).second || 7777 UserDefinedBinaryOperators.count(std::make_pair(CanonType, 7778 CanonType))) 7779 continue; 7780 7781 QualType ParamTypes[2] = { *Enum, *Enum }; 7782 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet); 7783 } 7784 } 7785 } 7786 7787 // C++ [over.built]p13: 7788 // 7789 // For every cv-qualified or cv-unqualified object type T 7790 // there exist candidate operator functions of the form 7791 // 7792 // T* operator+(T*, ptrdiff_t); 7793 // T& operator[](T*, ptrdiff_t); [BELOW] 7794 // T* operator-(T*, ptrdiff_t); 7795 // T* operator+(ptrdiff_t, T*); 7796 // T& operator[](ptrdiff_t, T*); [BELOW] 7797 // 7798 // C++ [over.built]p14: 7799 // 7800 // For every T, where T is a pointer to object type, there 7801 // exist candidate operator functions of the form 7802 // 7803 // ptrdiff_t operator-(T, T); 7804 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) { 7805 /// Set of (canonical) types that we've already handled. 7806 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7807 7808 for (int Arg = 0; Arg < 2; ++Arg) { 7809 QualType AsymmetricParamTypes[2] = { 7810 S.Context.getPointerDiffType(), 7811 S.Context.getPointerDiffType(), 7812 }; 7813 for (BuiltinCandidateTypeSet::iterator 7814 Ptr = CandidateTypes[Arg].pointer_begin(), 7815 PtrEnd = CandidateTypes[Arg].pointer_end(); 7816 Ptr != PtrEnd; ++Ptr) { 7817 QualType PointeeTy = (*Ptr)->getPointeeType(); 7818 if (!PointeeTy->isObjectType()) 7819 continue; 7820 7821 AsymmetricParamTypes[Arg] = *Ptr; 7822 if (Arg == 0 || Op == OO_Plus) { 7823 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 7824 // T* operator+(ptrdiff_t, T*); 7825 S.AddBuiltinCandidate(*Ptr, AsymmetricParamTypes, Args, CandidateSet); 7826 } 7827 if (Op == OO_Minus) { 7828 // ptrdiff_t operator-(T, T); 7829 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 7830 continue; 7831 7832 QualType ParamTypes[2] = { *Ptr, *Ptr }; 7833 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes, 7834 Args, CandidateSet); 7835 } 7836 } 7837 } 7838 } 7839 7840 // C++ [over.built]p12: 7841 // 7842 // For every pair of promoted arithmetic types L and R, there 7843 // exist candidate operator functions of the form 7844 // 7845 // LR operator*(L, R); 7846 // LR operator/(L, R); 7847 // LR operator+(L, R); 7848 // LR operator-(L, R); 7849 // bool operator<(L, R); 7850 // bool operator>(L, R); 7851 // bool operator<=(L, R); 7852 // bool operator>=(L, R); 7853 // bool operator==(L, R); 7854 // bool operator!=(L, R); 7855 // 7856 // where LR is the result of the usual arithmetic conversions 7857 // between types L and R. 7858 // 7859 // C++ [over.built]p24: 7860 // 7861 // For every pair of promoted arithmetic types L and R, there exist 7862 // candidate operator functions of the form 7863 // 7864 // LR operator?(bool, L, R); 7865 // 7866 // where LR is the result of the usual arithmetic conversions 7867 // between types L and R. 7868 // Our candidates ignore the first parameter. 7869 void addGenericBinaryArithmeticOverloads(bool isComparison) { 7870 if (!HasArithmeticOrEnumeralCandidateType) 7871 return; 7872 7873 for (unsigned Left = FirstPromotedArithmeticType; 7874 Left < LastPromotedArithmeticType; ++Left) { 7875 for (unsigned Right = FirstPromotedArithmeticType; 7876 Right < LastPromotedArithmeticType; ++Right) { 7877 QualType LandR[2] = { getArithmeticType(Left), 7878 getArithmeticType(Right) }; 7879 QualType Result = 7880 isComparison ? S.Context.BoolTy 7881 : getUsualArithmeticConversions(Left, Right); 7882 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7883 } 7884 } 7885 7886 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the 7887 // conditional operator for vector types. 7888 for (BuiltinCandidateTypeSet::iterator 7889 Vec1 = CandidateTypes[0].vector_begin(), 7890 Vec1End = CandidateTypes[0].vector_end(); 7891 Vec1 != Vec1End; ++Vec1) { 7892 for (BuiltinCandidateTypeSet::iterator 7893 Vec2 = CandidateTypes[1].vector_begin(), 7894 Vec2End = CandidateTypes[1].vector_end(); 7895 Vec2 != Vec2End; ++Vec2) { 7896 QualType LandR[2] = { *Vec1, *Vec2 }; 7897 QualType Result = S.Context.BoolTy; 7898 if (!isComparison) { 7899 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType()) 7900 Result = *Vec1; 7901 else 7902 Result = *Vec2; 7903 } 7904 7905 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7906 } 7907 } 7908 } 7909 7910 // C++ [over.built]p17: 7911 // 7912 // For every pair of promoted integral types L and R, there 7913 // exist candidate operator functions of the form 7914 // 7915 // LR operator%(L, R); 7916 // LR operator&(L, R); 7917 // LR operator^(L, R); 7918 // LR operator|(L, R); 7919 // L operator<<(L, R); 7920 // L operator>>(L, R); 7921 // 7922 // where LR is the result of the usual arithmetic conversions 7923 // between types L and R. 7924 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) { 7925 if (!HasArithmeticOrEnumeralCandidateType) 7926 return; 7927 7928 for (unsigned Left = FirstPromotedIntegralType; 7929 Left < LastPromotedIntegralType; ++Left) { 7930 for (unsigned Right = FirstPromotedIntegralType; 7931 Right < LastPromotedIntegralType; ++Right) { 7932 QualType LandR[2] = { getArithmeticType(Left), 7933 getArithmeticType(Right) }; 7934 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 7935 ? LandR[0] 7936 : getUsualArithmeticConversions(Left, Right); 7937 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet); 7938 } 7939 } 7940 } 7941 7942 // C++ [over.built]p20: 7943 // 7944 // For every pair (T, VQ), where T is an enumeration or 7945 // pointer to member type and VQ is either volatile or 7946 // empty, there exist candidate operator functions of the form 7947 // 7948 // VQ T& operator=(VQ T&, T); 7949 void addAssignmentMemberPointerOrEnumeralOverloads() { 7950 /// Set of (canonical) types that we've already handled. 7951 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7952 7953 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 7954 for (BuiltinCandidateTypeSet::iterator 7955 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 7956 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 7957 Enum != EnumEnd; ++Enum) { 7958 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 7959 continue; 7960 7961 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet); 7962 } 7963 7964 for (BuiltinCandidateTypeSet::iterator 7965 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 7966 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 7967 MemPtr != MemPtrEnd; ++MemPtr) { 7968 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 7969 continue; 7970 7971 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet); 7972 } 7973 } 7974 } 7975 7976 // C++ [over.built]p19: 7977 // 7978 // For every pair (T, VQ), where T is any type and VQ is either 7979 // volatile or empty, there exist candidate operator functions 7980 // of the form 7981 // 7982 // T*VQ& operator=(T*VQ&, T*); 7983 // 7984 // C++ [over.built]p21: 7985 // 7986 // For every pair (T, VQ), where T is a cv-qualified or 7987 // cv-unqualified object type and VQ is either volatile or 7988 // empty, there exist candidate operator functions of the form 7989 // 7990 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 7991 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 7992 void addAssignmentPointerOverloads(bool isEqualOp) { 7993 /// Set of (canonical) types that we've already handled. 7994 llvm::SmallPtrSet<QualType, 8> AddedTypes; 7995 7996 for (BuiltinCandidateTypeSet::iterator 7997 Ptr = CandidateTypes[0].pointer_begin(), 7998 PtrEnd = CandidateTypes[0].pointer_end(); 7999 Ptr != PtrEnd; ++Ptr) { 8000 // If this is operator=, keep track of the builtin candidates we added. 8001 if (isEqualOp) 8002 AddedTypes.insert(S.Context.getCanonicalType(*Ptr)); 8003 else if (!(*Ptr)->getPointeeType()->isObjectType()) 8004 continue; 8005 8006 // non-volatile version 8007 QualType ParamTypes[2] = { 8008 S.Context.getLValueReferenceType(*Ptr), 8009 isEqualOp ? *Ptr : S.Context.getPointerDiffType(), 8010 }; 8011 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8012 /*IsAssigmentOperator=*/ isEqualOp); 8013 8014 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8015 VisibleTypeConversionsQuals.hasVolatile(); 8016 if (NeedVolatile) { 8017 // volatile version 8018 ParamTypes[0] = 8019 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8020 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8021 /*IsAssigmentOperator=*/isEqualOp); 8022 } 8023 8024 if (!(*Ptr).isRestrictQualified() && 8025 VisibleTypeConversionsQuals.hasRestrict()) { 8026 // restrict version 8027 ParamTypes[0] 8028 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8029 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8030 /*IsAssigmentOperator=*/isEqualOp); 8031 8032 if (NeedVolatile) { 8033 // volatile restrict version 8034 ParamTypes[0] 8035 = S.Context.getLValueReferenceType( 8036 S.Context.getCVRQualifiedType(*Ptr, 8037 (Qualifiers::Volatile | 8038 Qualifiers::Restrict))); 8039 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8040 /*IsAssigmentOperator=*/isEqualOp); 8041 } 8042 } 8043 } 8044 8045 if (isEqualOp) { 8046 for (BuiltinCandidateTypeSet::iterator 8047 Ptr = CandidateTypes[1].pointer_begin(), 8048 PtrEnd = CandidateTypes[1].pointer_end(); 8049 Ptr != PtrEnd; ++Ptr) { 8050 // Make sure we don't add the same candidate twice. 8051 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8052 continue; 8053 8054 QualType ParamTypes[2] = { 8055 S.Context.getLValueReferenceType(*Ptr), 8056 *Ptr, 8057 }; 8058 8059 // non-volatile version 8060 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8061 /*IsAssigmentOperator=*/true); 8062 8063 bool NeedVolatile = !(*Ptr).isVolatileQualified() && 8064 VisibleTypeConversionsQuals.hasVolatile(); 8065 if (NeedVolatile) { 8066 // volatile version 8067 ParamTypes[0] = 8068 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr)); 8069 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8070 /*IsAssigmentOperator=*/true); 8071 } 8072 8073 if (!(*Ptr).isRestrictQualified() && 8074 VisibleTypeConversionsQuals.hasRestrict()) { 8075 // restrict version 8076 ParamTypes[0] 8077 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr)); 8078 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8079 /*IsAssigmentOperator=*/true); 8080 8081 if (NeedVolatile) { 8082 // volatile restrict version 8083 ParamTypes[0] 8084 = S.Context.getLValueReferenceType( 8085 S.Context.getCVRQualifiedType(*Ptr, 8086 (Qualifiers::Volatile | 8087 Qualifiers::Restrict))); 8088 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8089 /*IsAssigmentOperator=*/true); 8090 } 8091 } 8092 } 8093 } 8094 } 8095 8096 // C++ [over.built]p18: 8097 // 8098 // For every triple (L, VQ, R), where L is an arithmetic type, 8099 // VQ is either volatile or empty, and R is a promoted 8100 // arithmetic type, there exist candidate operator functions of 8101 // the form 8102 // 8103 // VQ L& operator=(VQ L&, R); 8104 // VQ L& operator*=(VQ L&, R); 8105 // VQ L& operator/=(VQ L&, R); 8106 // VQ L& operator+=(VQ L&, R); 8107 // VQ L& operator-=(VQ L&, R); 8108 void addAssignmentArithmeticOverloads(bool isEqualOp) { 8109 if (!HasArithmeticOrEnumeralCandidateType) 8110 return; 8111 8112 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 8113 for (unsigned Right = FirstPromotedArithmeticType; 8114 Right < LastPromotedArithmeticType; ++Right) { 8115 QualType ParamTypes[2]; 8116 ParamTypes[1] = getArithmeticType(Right); 8117 8118 // Add this built-in operator as a candidate (VQ is empty). 8119 ParamTypes[0] = 8120 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8121 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8122 /*IsAssigmentOperator=*/isEqualOp); 8123 8124 // Add this built-in operator as a candidate (VQ is 'volatile'). 8125 if (VisibleTypeConversionsQuals.hasVolatile()) { 8126 ParamTypes[0] = 8127 S.Context.getVolatileType(getArithmeticType(Left)); 8128 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8129 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8130 /*IsAssigmentOperator=*/isEqualOp); 8131 } 8132 } 8133 } 8134 8135 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types. 8136 for (BuiltinCandidateTypeSet::iterator 8137 Vec1 = CandidateTypes[0].vector_begin(), 8138 Vec1End = CandidateTypes[0].vector_end(); 8139 Vec1 != Vec1End; ++Vec1) { 8140 for (BuiltinCandidateTypeSet::iterator 8141 Vec2 = CandidateTypes[1].vector_begin(), 8142 Vec2End = CandidateTypes[1].vector_end(); 8143 Vec2 != Vec2End; ++Vec2) { 8144 QualType ParamTypes[2]; 8145 ParamTypes[1] = *Vec2; 8146 // Add this built-in operator as a candidate (VQ is empty). 8147 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1); 8148 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8149 /*IsAssigmentOperator=*/isEqualOp); 8150 8151 // Add this built-in operator as a candidate (VQ is 'volatile'). 8152 if (VisibleTypeConversionsQuals.hasVolatile()) { 8153 ParamTypes[0] = S.Context.getVolatileType(*Vec1); 8154 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8155 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet, 8156 /*IsAssigmentOperator=*/isEqualOp); 8157 } 8158 } 8159 } 8160 } 8161 8162 // C++ [over.built]p22: 8163 // 8164 // For every triple (L, VQ, R), where L is an integral type, VQ 8165 // is either volatile or empty, and R is a promoted integral 8166 // type, there exist candidate operator functions of the form 8167 // 8168 // VQ L& operator%=(VQ L&, R); 8169 // VQ L& operator<<=(VQ L&, R); 8170 // VQ L& operator>>=(VQ L&, R); 8171 // VQ L& operator&=(VQ L&, R); 8172 // VQ L& operator^=(VQ L&, R); 8173 // VQ L& operator|=(VQ L&, R); 8174 void addAssignmentIntegralOverloads() { 8175 if (!HasArithmeticOrEnumeralCandidateType) 8176 return; 8177 8178 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 8179 for (unsigned Right = FirstPromotedIntegralType; 8180 Right < LastPromotedIntegralType; ++Right) { 8181 QualType ParamTypes[2]; 8182 ParamTypes[1] = getArithmeticType(Right); 8183 8184 // Add this built-in operator as a candidate (VQ is empty). 8185 ParamTypes[0] = 8186 S.Context.getLValueReferenceType(getArithmeticType(Left)); 8187 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8188 if (VisibleTypeConversionsQuals.hasVolatile()) { 8189 // Add this built-in operator as a candidate (VQ is 'volatile'). 8190 ParamTypes[0] = getArithmeticType(Left); 8191 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]); 8192 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]); 8193 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet); 8194 } 8195 } 8196 } 8197 } 8198 8199 // C++ [over.operator]p23: 8200 // 8201 // There also exist candidate operator functions of the form 8202 // 8203 // bool operator!(bool); 8204 // bool operator&&(bool, bool); 8205 // bool operator||(bool, bool); 8206 void addExclaimOverload() { 8207 QualType ParamTy = S.Context.BoolTy; 8208 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet, 8209 /*IsAssignmentOperator=*/false, 8210 /*NumContextualBoolArguments=*/1); 8211 } 8212 void addAmpAmpOrPipePipeOverload() { 8213 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy }; 8214 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet, 8215 /*IsAssignmentOperator=*/false, 8216 /*NumContextualBoolArguments=*/2); 8217 } 8218 8219 // C++ [over.built]p13: 8220 // 8221 // For every cv-qualified or cv-unqualified object type T there 8222 // exist candidate operator functions of the form 8223 // 8224 // T* operator+(T*, ptrdiff_t); [ABOVE] 8225 // T& operator[](T*, ptrdiff_t); 8226 // T* operator-(T*, ptrdiff_t); [ABOVE] 8227 // T* operator+(ptrdiff_t, T*); [ABOVE] 8228 // T& operator[](ptrdiff_t, T*); 8229 void addSubscriptOverloads() { 8230 for (BuiltinCandidateTypeSet::iterator 8231 Ptr = CandidateTypes[0].pointer_begin(), 8232 PtrEnd = CandidateTypes[0].pointer_end(); 8233 Ptr != PtrEnd; ++Ptr) { 8234 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() }; 8235 QualType PointeeType = (*Ptr)->getPointeeType(); 8236 if (!PointeeType->isObjectType()) 8237 continue; 8238 8239 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8240 8241 // T& operator[](T*, ptrdiff_t) 8242 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8243 } 8244 8245 for (BuiltinCandidateTypeSet::iterator 8246 Ptr = CandidateTypes[1].pointer_begin(), 8247 PtrEnd = CandidateTypes[1].pointer_end(); 8248 Ptr != PtrEnd; ++Ptr) { 8249 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr }; 8250 QualType PointeeType = (*Ptr)->getPointeeType(); 8251 if (!PointeeType->isObjectType()) 8252 continue; 8253 8254 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType); 8255 8256 // T& operator[](ptrdiff_t, T*) 8257 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8258 } 8259 } 8260 8261 // C++ [over.built]p11: 8262 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type, 8263 // C1 is the same type as C2 or is a derived class of C2, T is an object 8264 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs, 8265 // there exist candidate operator functions of the form 8266 // 8267 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*); 8268 // 8269 // where CV12 is the union of CV1 and CV2. 8270 void addArrowStarOverloads() { 8271 for (BuiltinCandidateTypeSet::iterator 8272 Ptr = CandidateTypes[0].pointer_begin(), 8273 PtrEnd = CandidateTypes[0].pointer_end(); 8274 Ptr != PtrEnd; ++Ptr) { 8275 QualType C1Ty = (*Ptr); 8276 QualType C1; 8277 QualifierCollector Q1; 8278 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0); 8279 if (!isa<RecordType>(C1)) 8280 continue; 8281 // heuristic to reduce number of builtin candidates in the set. 8282 // Add volatile/restrict version only if there are conversions to a 8283 // volatile/restrict type. 8284 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile()) 8285 continue; 8286 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict()) 8287 continue; 8288 for (BuiltinCandidateTypeSet::iterator 8289 MemPtr = CandidateTypes[1].member_pointer_begin(), 8290 MemPtrEnd = CandidateTypes[1].member_pointer_end(); 8291 MemPtr != MemPtrEnd; ++MemPtr) { 8292 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr); 8293 QualType C2 = QualType(mptr->getClass(), 0); 8294 C2 = C2.getUnqualifiedType(); 8295 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2)) 8296 break; 8297 QualType ParamTypes[2] = { *Ptr, *MemPtr }; 8298 // build CV12 T& 8299 QualType T = mptr->getPointeeType(); 8300 if (!VisibleTypeConversionsQuals.hasVolatile() && 8301 T.isVolatileQualified()) 8302 continue; 8303 if (!VisibleTypeConversionsQuals.hasRestrict() && 8304 T.isRestrictQualified()) 8305 continue; 8306 T = Q1.apply(S.Context, T); 8307 QualType ResultTy = S.Context.getLValueReferenceType(T); 8308 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet); 8309 } 8310 } 8311 } 8312 8313 // Note that we don't consider the first argument, since it has been 8314 // contextually converted to bool long ago. The candidates below are 8315 // therefore added as binary. 8316 // 8317 // C++ [over.built]p25: 8318 // For every type T, where T is a pointer, pointer-to-member, or scoped 8319 // enumeration type, there exist candidate operator functions of the form 8320 // 8321 // T operator?(bool, T, T); 8322 // 8323 void addConditionalOperatorOverloads() { 8324 /// Set of (canonical) types that we've already handled. 8325 llvm::SmallPtrSet<QualType, 8> AddedTypes; 8326 8327 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) { 8328 for (BuiltinCandidateTypeSet::iterator 8329 Ptr = CandidateTypes[ArgIdx].pointer_begin(), 8330 PtrEnd = CandidateTypes[ArgIdx].pointer_end(); 8331 Ptr != PtrEnd; ++Ptr) { 8332 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second) 8333 continue; 8334 8335 QualType ParamTypes[2] = { *Ptr, *Ptr }; 8336 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet); 8337 } 8338 8339 for (BuiltinCandidateTypeSet::iterator 8340 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(), 8341 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end(); 8342 MemPtr != MemPtrEnd; ++MemPtr) { 8343 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second) 8344 continue; 8345 8346 QualType ParamTypes[2] = { *MemPtr, *MemPtr }; 8347 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet); 8348 } 8349 8350 if (S.getLangOpts().CPlusPlus11) { 8351 for (BuiltinCandidateTypeSet::iterator 8352 Enum = CandidateTypes[ArgIdx].enumeration_begin(), 8353 EnumEnd = CandidateTypes[ArgIdx].enumeration_end(); 8354 Enum != EnumEnd; ++Enum) { 8355 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped()) 8356 continue; 8357 8358 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second) 8359 continue; 8360 8361 QualType ParamTypes[2] = { *Enum, *Enum }; 8362 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet); 8363 } 8364 } 8365 } 8366 } 8367 }; 8368 8369 } // end anonymous namespace 8370 8371 /// AddBuiltinOperatorCandidates - Add the appropriate built-in 8372 /// operator overloads to the candidate set (C++ [over.built]), based 8373 /// on the operator @p Op and the arguments given. For example, if the 8374 /// operator is a binary '+', this routine might add "int 8375 /// operator+(int, int)" to cover integer addition. 8376 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 8377 SourceLocation OpLoc, 8378 ArrayRef<Expr *> Args, 8379 OverloadCandidateSet &CandidateSet) { 8380 // Find all of the types that the arguments can convert to, but only 8381 // if the operator we're looking at has built-in operator candidates 8382 // that make use of these types. Also record whether we encounter non-record 8383 // candidate types or either arithmetic or enumeral candidate types. 8384 Qualifiers VisibleTypeConversionsQuals; 8385 VisibleTypeConversionsQuals.addConst(); 8386 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) 8387 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]); 8388 8389 bool HasNonRecordCandidateType = false; 8390 bool HasArithmeticOrEnumeralCandidateType = false; 8391 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes; 8392 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 8393 CandidateTypes.emplace_back(*this); 8394 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(), 8395 OpLoc, 8396 true, 8397 (Op == OO_Exclaim || 8398 Op == OO_AmpAmp || 8399 Op == OO_PipePipe), 8400 VisibleTypeConversionsQuals); 8401 HasNonRecordCandidateType = HasNonRecordCandidateType || 8402 CandidateTypes[ArgIdx].hasNonRecordTypes(); 8403 HasArithmeticOrEnumeralCandidateType = 8404 HasArithmeticOrEnumeralCandidateType || 8405 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes(); 8406 } 8407 8408 // Exit early when no non-record types have been added to the candidate set 8409 // for any of the arguments to the operator. 8410 // 8411 // We can't exit early for !, ||, or &&, since there we have always have 8412 // 'bool' overloads. 8413 if (!HasNonRecordCandidateType && 8414 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe)) 8415 return; 8416 8417 // Setup an object to manage the common state for building overloads. 8418 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, 8419 VisibleTypeConversionsQuals, 8420 HasArithmeticOrEnumeralCandidateType, 8421 CandidateTypes, CandidateSet); 8422 8423 // Dispatch over the operation to add in only those overloads which apply. 8424 switch (Op) { 8425 case OO_None: 8426 case NUM_OVERLOADED_OPERATORS: 8427 llvm_unreachable("Expected an overloaded operator"); 8428 8429 case OO_New: 8430 case OO_Delete: 8431 case OO_Array_New: 8432 case OO_Array_Delete: 8433 case OO_Call: 8434 llvm_unreachable( 8435 "Special operators don't use AddBuiltinOperatorCandidates"); 8436 8437 case OO_Comma: 8438 case OO_Arrow: 8439 case OO_Coawait: 8440 // C++ [over.match.oper]p3: 8441 // -- For the operator ',', the unary operator '&', the 8442 // operator '->', or the operator 'co_await', the 8443 // built-in candidates set is empty. 8444 break; 8445 8446 case OO_Plus: // '+' is either unary or binary 8447 if (Args.size() == 1) 8448 OpBuilder.addUnaryPlusPointerOverloads(); 8449 // Fall through. 8450 8451 case OO_Minus: // '-' is either unary or binary 8452 if (Args.size() == 1) { 8453 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads(); 8454 } else { 8455 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op); 8456 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8457 } 8458 break; 8459 8460 case OO_Star: // '*' is either unary or binary 8461 if (Args.size() == 1) 8462 OpBuilder.addUnaryStarPointerOverloads(); 8463 else 8464 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8465 break; 8466 8467 case OO_Slash: 8468 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8469 break; 8470 8471 case OO_PlusPlus: 8472 case OO_MinusMinus: 8473 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op); 8474 OpBuilder.addPlusPlusMinusMinusPointerOverloads(); 8475 break; 8476 8477 case OO_EqualEqual: 8478 case OO_ExclaimEqual: 8479 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads(); 8480 // Fall through. 8481 8482 case OO_Less: 8483 case OO_Greater: 8484 case OO_LessEqual: 8485 case OO_GreaterEqual: 8486 OpBuilder.addRelationalPointerOrEnumeralOverloads(); 8487 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true); 8488 break; 8489 8490 case OO_Percent: 8491 case OO_Caret: 8492 case OO_Pipe: 8493 case OO_LessLess: 8494 case OO_GreaterGreater: 8495 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8496 break; 8497 8498 case OO_Amp: // '&' is either unary or binary 8499 if (Args.size() == 1) 8500 // C++ [over.match.oper]p3: 8501 // -- For the operator ',', the unary operator '&', or the 8502 // operator '->', the built-in candidates set is empty. 8503 break; 8504 8505 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op); 8506 break; 8507 8508 case OO_Tilde: 8509 OpBuilder.addUnaryTildePromotedIntegralOverloads(); 8510 break; 8511 8512 case OO_Equal: 8513 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads(); 8514 // Fall through. 8515 8516 case OO_PlusEqual: 8517 case OO_MinusEqual: 8518 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal); 8519 // Fall through. 8520 8521 case OO_StarEqual: 8522 case OO_SlashEqual: 8523 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal); 8524 break; 8525 8526 case OO_PercentEqual: 8527 case OO_LessLessEqual: 8528 case OO_GreaterGreaterEqual: 8529 case OO_AmpEqual: 8530 case OO_CaretEqual: 8531 case OO_PipeEqual: 8532 OpBuilder.addAssignmentIntegralOverloads(); 8533 break; 8534 8535 case OO_Exclaim: 8536 OpBuilder.addExclaimOverload(); 8537 break; 8538 8539 case OO_AmpAmp: 8540 case OO_PipePipe: 8541 OpBuilder.addAmpAmpOrPipePipeOverload(); 8542 break; 8543 8544 case OO_Subscript: 8545 OpBuilder.addSubscriptOverloads(); 8546 break; 8547 8548 case OO_ArrowStar: 8549 OpBuilder.addArrowStarOverloads(); 8550 break; 8551 8552 case OO_Conditional: 8553 OpBuilder.addConditionalOperatorOverloads(); 8554 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false); 8555 break; 8556 } 8557 } 8558 8559 /// \brief Add function candidates found via argument-dependent lookup 8560 /// to the set of overloading candidates. 8561 /// 8562 /// This routine performs argument-dependent name lookup based on the 8563 /// given function name (which may also be an operator name) and adds 8564 /// all of the overload candidates found by ADL to the overload 8565 /// candidate set (C++ [basic.lookup.argdep]). 8566 void 8567 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name, 8568 SourceLocation Loc, 8569 ArrayRef<Expr *> Args, 8570 TemplateArgumentListInfo *ExplicitTemplateArgs, 8571 OverloadCandidateSet& CandidateSet, 8572 bool PartialOverloading) { 8573 ADLResult Fns; 8574 8575 // FIXME: This approach for uniquing ADL results (and removing 8576 // redundant candidates from the set) relies on pointer-equality, 8577 // which means we need to key off the canonical decl. However, 8578 // always going back to the canonical decl might not get us the 8579 // right set of default arguments. What default arguments are 8580 // we supposed to consider on ADL candidates, anyway? 8581 8582 // FIXME: Pass in the explicit template arguments? 8583 ArgumentDependentLookup(Name, Loc, Args, Fns); 8584 8585 // Erase all of the candidates we already knew about. 8586 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 8587 CandEnd = CandidateSet.end(); 8588 Cand != CandEnd; ++Cand) 8589 if (Cand->Function) { 8590 Fns.erase(Cand->Function); 8591 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate()) 8592 Fns.erase(FunTmpl); 8593 } 8594 8595 // For each of the ADL candidates we found, add it to the overload 8596 // set. 8597 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) { 8598 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none); 8599 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 8600 if (ExplicitTemplateArgs) 8601 continue; 8602 8603 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false, 8604 PartialOverloading); 8605 } else 8606 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I), 8607 FoundDecl, ExplicitTemplateArgs, 8608 Args, CandidateSet, PartialOverloading); 8609 } 8610 } 8611 8612 namespace { 8613 enum class Comparison { Equal, Better, Worse }; 8614 } 8615 8616 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of 8617 /// overload resolution. 8618 /// 8619 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff 8620 /// Cand1's first N enable_if attributes have precisely the same conditions as 8621 /// Cand2's first N enable_if attributes (where N = the number of enable_if 8622 /// attributes on Cand2), and Cand1 has more than N enable_if attributes. 8623 /// 8624 /// Note that you can have a pair of candidates such that Cand1's enable_if 8625 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are 8626 /// worse than Cand1's. 8627 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, 8628 const FunctionDecl *Cand2) { 8629 // Common case: One (or both) decls don't have enable_if attrs. 8630 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>(); 8631 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>(); 8632 if (!Cand1Attr || !Cand2Attr) { 8633 if (Cand1Attr == Cand2Attr) 8634 return Comparison::Equal; 8635 return Cand1Attr ? Comparison::Better : Comparison::Worse; 8636 } 8637 8638 // FIXME: The next several lines are just 8639 // specific_attr_iterator<EnableIfAttr> but going in declaration order, 8640 // instead of reverse order which is how they're stored in the AST. 8641 auto Cand1Attrs = getOrderedEnableIfAttrs(Cand1); 8642 auto Cand2Attrs = getOrderedEnableIfAttrs(Cand2); 8643 8644 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1 8645 // has fewer enable_if attributes than Cand2. 8646 if (Cand1Attrs.size() < Cand2Attrs.size()) 8647 return Comparison::Worse; 8648 8649 auto Cand1I = Cand1Attrs.begin(); 8650 llvm::FoldingSetNodeID Cand1ID, Cand2ID; 8651 for (auto &Cand2A : Cand2Attrs) { 8652 Cand1ID.clear(); 8653 Cand2ID.clear(); 8654 8655 auto &Cand1A = *Cand1I++; 8656 Cand1A->getCond()->Profile(Cand1ID, S.getASTContext(), true); 8657 Cand2A->getCond()->Profile(Cand2ID, S.getASTContext(), true); 8658 if (Cand1ID != Cand2ID) 8659 return Comparison::Worse; 8660 } 8661 8662 return Cand1I == Cand1Attrs.end() ? Comparison::Equal : Comparison::Better; 8663 } 8664 8665 /// isBetterOverloadCandidate - Determines whether the first overload 8666 /// candidate is a better candidate than the second (C++ 13.3.3p1). 8667 bool clang::isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, 8668 const OverloadCandidate &Cand2, 8669 SourceLocation Loc, 8670 bool UserDefinedConversion) { 8671 // Define viable functions to be better candidates than non-viable 8672 // functions. 8673 if (!Cand2.Viable) 8674 return Cand1.Viable; 8675 else if (!Cand1.Viable) 8676 return false; 8677 8678 // C++ [over.match.best]p1: 8679 // 8680 // -- if F is a static member function, ICS1(F) is defined such 8681 // that ICS1(F) is neither better nor worse than ICS1(G) for 8682 // any function G, and, symmetrically, ICS1(G) is neither 8683 // better nor worse than ICS1(F). 8684 unsigned StartArg = 0; 8685 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 8686 StartArg = 1; 8687 8688 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) { 8689 // We don't allow incompatible pointer conversions in C++. 8690 if (!S.getLangOpts().CPlusPlus) 8691 return ICS.isStandard() && 8692 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion; 8693 8694 // The only ill-formed conversion we allow in C++ is the string literal to 8695 // char* conversion, which is only considered ill-formed after C++11. 8696 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings && 8697 hasDeprecatedStringLiteralToCharPtrConversion(ICS); 8698 }; 8699 8700 // Define functions that don't require ill-formed conversions for a given 8701 // argument to be better candidates than functions that do. 8702 unsigned NumArgs = Cand1.NumConversions; 8703 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch"); 8704 bool HasBetterConversion = false; 8705 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8706 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]); 8707 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]); 8708 if (Cand1Bad != Cand2Bad) { 8709 if (Cand1Bad) 8710 return false; 8711 HasBetterConversion = true; 8712 } 8713 } 8714 8715 if (HasBetterConversion) 8716 return true; 8717 8718 // C++ [over.match.best]p1: 8719 // A viable function F1 is defined to be a better function than another 8720 // viable function F2 if for all arguments i, ICSi(F1) is not a worse 8721 // conversion sequence than ICSi(F2), and then... 8722 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 8723 switch (CompareImplicitConversionSequences(S, Loc, 8724 Cand1.Conversions[ArgIdx], 8725 Cand2.Conversions[ArgIdx])) { 8726 case ImplicitConversionSequence::Better: 8727 // Cand1 has a better conversion sequence. 8728 HasBetterConversion = true; 8729 break; 8730 8731 case ImplicitConversionSequence::Worse: 8732 // Cand1 can't be better than Cand2. 8733 return false; 8734 8735 case ImplicitConversionSequence::Indistinguishable: 8736 // Do nothing. 8737 break; 8738 } 8739 } 8740 8741 // -- for some argument j, ICSj(F1) is a better conversion sequence than 8742 // ICSj(F2), or, if not that, 8743 if (HasBetterConversion) 8744 return true; 8745 8746 // -- the context is an initialization by user-defined conversion 8747 // (see 8.5, 13.3.1.5) and the standard conversion sequence 8748 // from the return type of F1 to the destination type (i.e., 8749 // the type of the entity being initialized) is a better 8750 // conversion sequence than the standard conversion sequence 8751 // from the return type of F2 to the destination type. 8752 if (UserDefinedConversion && Cand1.Function && Cand2.Function && 8753 isa<CXXConversionDecl>(Cand1.Function) && 8754 isa<CXXConversionDecl>(Cand2.Function)) { 8755 // First check whether we prefer one of the conversion functions over the 8756 // other. This only distinguishes the results in non-standard, extension 8757 // cases such as the conversion from a lambda closure type to a function 8758 // pointer or block. 8759 ImplicitConversionSequence::CompareKind Result = 8760 compareConversionFunctions(S, Cand1.Function, Cand2.Function); 8761 if (Result == ImplicitConversionSequence::Indistinguishable) 8762 Result = CompareStandardConversionSequences(S, Loc, 8763 Cand1.FinalConversion, 8764 Cand2.FinalConversion); 8765 8766 if (Result != ImplicitConversionSequence::Indistinguishable) 8767 return Result == ImplicitConversionSequence::Better; 8768 8769 // FIXME: Compare kind of reference binding if conversion functions 8770 // convert to a reference type used in direct reference binding, per 8771 // C++14 [over.match.best]p1 section 2 bullet 3. 8772 } 8773 8774 // -- F1 is a non-template function and F2 is a function template 8775 // specialization, or, if not that, 8776 bool Cand1IsSpecialization = Cand1.Function && 8777 Cand1.Function->getPrimaryTemplate(); 8778 bool Cand2IsSpecialization = Cand2.Function && 8779 Cand2.Function->getPrimaryTemplate(); 8780 if (Cand1IsSpecialization != Cand2IsSpecialization) 8781 return Cand2IsSpecialization; 8782 8783 // -- F1 and F2 are function template specializations, and the function 8784 // template for F1 is more specialized than the template for F2 8785 // according to the partial ordering rules described in 14.5.5.2, or, 8786 // if not that, 8787 if (Cand1IsSpecialization && Cand2IsSpecialization) { 8788 if (FunctionTemplateDecl *BetterTemplate 8789 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(), 8790 Cand2.Function->getPrimaryTemplate(), 8791 Loc, 8792 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion 8793 : TPOC_Call, 8794 Cand1.ExplicitCallArguments, 8795 Cand2.ExplicitCallArguments)) 8796 return BetterTemplate == Cand1.Function->getPrimaryTemplate(); 8797 } 8798 8799 // FIXME: Work around a defect in the C++17 inheriting constructor wording. 8800 // A derived-class constructor beats an (inherited) base class constructor. 8801 bool Cand1IsInherited = 8802 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl()); 8803 bool Cand2IsInherited = 8804 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl()); 8805 if (Cand1IsInherited != Cand2IsInherited) 8806 return Cand2IsInherited; 8807 else if (Cand1IsInherited) { 8808 assert(Cand2IsInherited); 8809 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext()); 8810 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext()); 8811 if (Cand1Class->isDerivedFrom(Cand2Class)) 8812 return true; 8813 if (Cand2Class->isDerivedFrom(Cand1Class)) 8814 return false; 8815 // Inherited from sibling base classes: still ambiguous. 8816 } 8817 8818 // Check for enable_if value-based overload resolution. 8819 if (Cand1.Function && Cand2.Function) { 8820 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function); 8821 if (Cmp != Comparison::Equal) 8822 return Cmp == Comparison::Better; 8823 } 8824 8825 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) { 8826 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8827 return S.IdentifyCUDAPreference(Caller, Cand1.Function) > 8828 S.IdentifyCUDAPreference(Caller, Cand2.Function); 8829 } 8830 8831 bool HasPS1 = Cand1.Function != nullptr && 8832 functionHasPassObjectSizeParams(Cand1.Function); 8833 bool HasPS2 = Cand2.Function != nullptr && 8834 functionHasPassObjectSizeParams(Cand2.Function); 8835 return HasPS1 != HasPS2 && HasPS1; 8836 } 8837 8838 /// Determine whether two declarations are "equivalent" for the purposes of 8839 /// name lookup and overload resolution. This applies when the same internal/no 8840 /// linkage entity is defined by two modules (probably by textually including 8841 /// the same header). In such a case, we don't consider the declarations to 8842 /// declare the same entity, but we also don't want lookups with both 8843 /// declarations visible to be ambiguous in some cases (this happens when using 8844 /// a modularized libstdc++). 8845 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A, 8846 const NamedDecl *B) { 8847 auto *VA = dyn_cast_or_null<ValueDecl>(A); 8848 auto *VB = dyn_cast_or_null<ValueDecl>(B); 8849 if (!VA || !VB) 8850 return false; 8851 8852 // The declarations must be declaring the same name as an internal linkage 8853 // entity in different modules. 8854 if (!VA->getDeclContext()->getRedeclContext()->Equals( 8855 VB->getDeclContext()->getRedeclContext()) || 8856 getOwningModule(const_cast<ValueDecl *>(VA)) == 8857 getOwningModule(const_cast<ValueDecl *>(VB)) || 8858 VA->isExternallyVisible() || VB->isExternallyVisible()) 8859 return false; 8860 8861 // Check that the declarations appear to be equivalent. 8862 // 8863 // FIXME: Checking the type isn't really enough to resolve the ambiguity. 8864 // For constants and functions, we should check the initializer or body is 8865 // the same. For non-constant variables, we shouldn't allow it at all. 8866 if (Context.hasSameType(VA->getType(), VB->getType())) 8867 return true; 8868 8869 // Enum constants within unnamed enumerations will have different types, but 8870 // may still be similar enough to be interchangeable for our purposes. 8871 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) { 8872 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) { 8873 // Only handle anonymous enums. If the enumerations were named and 8874 // equivalent, they would have been merged to the same type. 8875 auto *EnumA = cast<EnumDecl>(EA->getDeclContext()); 8876 auto *EnumB = cast<EnumDecl>(EB->getDeclContext()); 8877 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() || 8878 !Context.hasSameType(EnumA->getIntegerType(), 8879 EnumB->getIntegerType())) 8880 return false; 8881 // Allow this only if the value is the same for both enumerators. 8882 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal()); 8883 } 8884 } 8885 8886 // Nothing else is sufficiently similar. 8887 return false; 8888 } 8889 8890 void Sema::diagnoseEquivalentInternalLinkageDeclarations( 8891 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) { 8892 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D; 8893 8894 Module *M = getOwningModule(const_cast<NamedDecl*>(D)); 8895 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl) 8896 << !M << (M ? M->getFullModuleName() : ""); 8897 8898 for (auto *E : Equiv) { 8899 Module *M = getOwningModule(const_cast<NamedDecl*>(E)); 8900 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl) 8901 << !M << (M ? M->getFullModuleName() : ""); 8902 } 8903 } 8904 8905 /// \brief Computes the best viable function (C++ 13.3.3) 8906 /// within an overload candidate set. 8907 /// 8908 /// \param Loc The location of the function name (or operator symbol) for 8909 /// which overload resolution occurs. 8910 /// 8911 /// \param Best If overload resolution was successful or found a deleted 8912 /// function, \p Best points to the candidate function found. 8913 /// 8914 /// \returns The result of overload resolution. 8915 OverloadingResult 8916 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc, 8917 iterator &Best, 8918 bool UserDefinedConversion) { 8919 llvm::SmallVector<OverloadCandidate *, 16> Candidates; 8920 std::transform(begin(), end(), std::back_inserter(Candidates), 8921 [](OverloadCandidate &Cand) { return &Cand; }); 8922 8923 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but 8924 // are accepted by both clang and NVCC. However, during a particular 8925 // compilation mode only one call variant is viable. We need to 8926 // exclude non-viable overload candidates from consideration based 8927 // only on their host/device attributes. Specifically, if one 8928 // candidate call is WrongSide and the other is SameSide, we ignore 8929 // the WrongSide candidate. 8930 if (S.getLangOpts().CUDA) { 8931 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext); 8932 bool ContainsSameSideCandidate = 8933 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) { 8934 return Cand->Function && 8935 S.IdentifyCUDAPreference(Caller, Cand->Function) == 8936 Sema::CFP_SameSide; 8937 }); 8938 if (ContainsSameSideCandidate) { 8939 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) { 8940 return Cand->Function && 8941 S.IdentifyCUDAPreference(Caller, Cand->Function) == 8942 Sema::CFP_WrongSide; 8943 }; 8944 llvm::erase_if(Candidates, IsWrongSideCandidate); 8945 } 8946 } 8947 8948 // Find the best viable function. 8949 Best = end(); 8950 for (auto *Cand : Candidates) 8951 if (Cand->Viable) 8952 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc, 8953 UserDefinedConversion)) 8954 Best = Cand; 8955 8956 // If we didn't find any viable functions, abort. 8957 if (Best == end()) 8958 return OR_No_Viable_Function; 8959 8960 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands; 8961 8962 // Make sure that this function is better than every other viable 8963 // function. If not, we have an ambiguity. 8964 for (auto *Cand : Candidates) { 8965 if (Cand->Viable && 8966 Cand != Best && 8967 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, 8968 UserDefinedConversion)) { 8969 if (S.isEquivalentInternalLinkageDeclaration(Best->Function, 8970 Cand->Function)) { 8971 EquivalentCands.push_back(Cand->Function); 8972 continue; 8973 } 8974 8975 Best = end(); 8976 return OR_Ambiguous; 8977 } 8978 } 8979 8980 // Best is the best viable function. 8981 if (Best->Function && 8982 (Best->Function->isDeleted() || 8983 S.isFunctionConsideredUnavailable(Best->Function))) 8984 return OR_Deleted; 8985 8986 if (!EquivalentCands.empty()) 8987 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function, 8988 EquivalentCands); 8989 8990 return OR_Success; 8991 } 8992 8993 namespace { 8994 8995 enum OverloadCandidateKind { 8996 oc_function, 8997 oc_method, 8998 oc_constructor, 8999 oc_function_template, 9000 oc_method_template, 9001 oc_constructor_template, 9002 oc_implicit_default_constructor, 9003 oc_implicit_copy_constructor, 9004 oc_implicit_move_constructor, 9005 oc_implicit_copy_assignment, 9006 oc_implicit_move_assignment, 9007 oc_inherited_constructor, 9008 oc_inherited_constructor_template 9009 }; 9010 9011 static OverloadCandidateKind 9012 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn, 9013 std::string &Description) { 9014 bool isTemplate = false; 9015 9016 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) { 9017 isTemplate = true; 9018 Description = S.getTemplateArgumentBindingsText( 9019 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs()); 9020 } 9021 9022 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) { 9023 if (!Ctor->isImplicit()) { 9024 if (isa<ConstructorUsingShadowDecl>(Found)) 9025 return isTemplate ? oc_inherited_constructor_template 9026 : oc_inherited_constructor; 9027 else 9028 return isTemplate ? oc_constructor_template : oc_constructor; 9029 } 9030 9031 if (Ctor->isDefaultConstructor()) 9032 return oc_implicit_default_constructor; 9033 9034 if (Ctor->isMoveConstructor()) 9035 return oc_implicit_move_constructor; 9036 9037 assert(Ctor->isCopyConstructor() && 9038 "unexpected sort of implicit constructor"); 9039 return oc_implicit_copy_constructor; 9040 } 9041 9042 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) { 9043 // This actually gets spelled 'candidate function' for now, but 9044 // it doesn't hurt to split it out. 9045 if (!Meth->isImplicit()) 9046 return isTemplate ? oc_method_template : oc_method; 9047 9048 if (Meth->isMoveAssignmentOperator()) 9049 return oc_implicit_move_assignment; 9050 9051 if (Meth->isCopyAssignmentOperator()) 9052 return oc_implicit_copy_assignment; 9053 9054 assert(isa<CXXConversionDecl>(Meth) && "expected conversion"); 9055 return oc_method; 9056 } 9057 9058 return isTemplate ? oc_function_template : oc_function; 9059 } 9060 9061 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) { 9062 // FIXME: It'd be nice to only emit a note once per using-decl per overload 9063 // set. 9064 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) 9065 S.Diag(FoundDecl->getLocation(), 9066 diag::note_ovl_candidate_inherited_constructor) 9067 << Shadow->getNominatedBaseClass(); 9068 } 9069 9070 } // end anonymous namespace 9071 9072 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, 9073 const FunctionDecl *FD) { 9074 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) { 9075 bool AlwaysTrue; 9076 if (!EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx)) 9077 return false; 9078 if (!AlwaysTrue) 9079 return false; 9080 } 9081 return true; 9082 } 9083 9084 /// \brief Returns true if we can take the address of the function. 9085 /// 9086 /// \param Complain - If true, we'll emit a diagnostic 9087 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are 9088 /// we in overload resolution? 9089 /// \param Loc - The location of the statement we're complaining about. Ignored 9090 /// if we're not complaining, or if we're in overload resolution. 9091 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, 9092 bool Complain, 9093 bool InOverloadResolution, 9094 SourceLocation Loc) { 9095 if (!isFunctionAlwaysEnabled(S.Context, FD)) { 9096 if (Complain) { 9097 if (InOverloadResolution) 9098 S.Diag(FD->getLocStart(), 9099 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr); 9100 else 9101 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD; 9102 } 9103 return false; 9104 } 9105 9106 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) { 9107 return P->hasAttr<PassObjectSizeAttr>(); 9108 }); 9109 if (I == FD->param_end()) 9110 return true; 9111 9112 if (Complain) { 9113 // Add one to ParamNo because it's user-facing 9114 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1; 9115 if (InOverloadResolution) 9116 S.Diag(FD->getLocation(), 9117 diag::note_ovl_candidate_has_pass_object_size_params) 9118 << ParamNo; 9119 else 9120 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params) 9121 << FD << ParamNo; 9122 } 9123 return false; 9124 } 9125 9126 static bool checkAddressOfCandidateIsAvailable(Sema &S, 9127 const FunctionDecl *FD) { 9128 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true, 9129 /*InOverloadResolution=*/true, 9130 /*Loc=*/SourceLocation()); 9131 } 9132 9133 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, 9134 bool Complain, 9135 SourceLocation Loc) { 9136 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain, 9137 /*InOverloadResolution=*/false, 9138 Loc); 9139 } 9140 9141 // Notes the location of an overload candidate. 9142 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, 9143 QualType DestType, bool TakingAddress) { 9144 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn)) 9145 return; 9146 9147 std::string FnDesc; 9148 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Found, Fn, FnDesc); 9149 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate) 9150 << (unsigned) K << Fn << FnDesc; 9151 9152 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType); 9153 Diag(Fn->getLocation(), PD); 9154 MaybeEmitInheritedConstructorNote(*this, Found); 9155 } 9156 9157 // Notes the location of all overload candidates designated through 9158 // OverloadedExpr 9159 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType, 9160 bool TakingAddress) { 9161 assert(OverloadedExpr->getType() == Context.OverloadTy); 9162 9163 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr); 9164 OverloadExpr *OvlExpr = Ovl.Expression; 9165 9166 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 9167 IEnd = OvlExpr->decls_end(); 9168 I != IEnd; ++I) { 9169 if (FunctionTemplateDecl *FunTmpl = 9170 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) { 9171 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType, 9172 TakingAddress); 9173 } else if (FunctionDecl *Fun 9174 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) { 9175 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress); 9176 } 9177 } 9178 } 9179 9180 /// Diagnoses an ambiguous conversion. The partial diagnostic is the 9181 /// "lead" diagnostic; it will be given two arguments, the source and 9182 /// target types of the conversion. 9183 void ImplicitConversionSequence::DiagnoseAmbiguousConversion( 9184 Sema &S, 9185 SourceLocation CaretLoc, 9186 const PartialDiagnostic &PDiag) const { 9187 S.Diag(CaretLoc, PDiag) 9188 << Ambiguous.getFromType() << Ambiguous.getToType(); 9189 // FIXME: The note limiting machinery is borrowed from 9190 // OverloadCandidateSet::NoteCandidates; there's an opportunity for 9191 // refactoring here. 9192 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 9193 unsigned CandsShown = 0; 9194 AmbiguousConversionSequence::const_iterator I, E; 9195 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) { 9196 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 9197 break; 9198 ++CandsShown; 9199 S.NoteOverloadCandidate(I->first, I->second); 9200 } 9201 if (I != E) 9202 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I); 9203 } 9204 9205 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, 9206 unsigned I, bool TakingCandidateAddress) { 9207 const ImplicitConversionSequence &Conv = Cand->Conversions[I]; 9208 assert(Conv.isBad()); 9209 assert(Cand->Function && "for now, candidate must be a function"); 9210 FunctionDecl *Fn = Cand->Function; 9211 9212 // There's a conversion slot for the object argument if this is a 9213 // non-constructor method. Note that 'I' corresponds the 9214 // conversion-slot index. 9215 bool isObjectArgument = false; 9216 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) { 9217 if (I == 0) 9218 isObjectArgument = true; 9219 else 9220 I--; 9221 } 9222 9223 std::string FnDesc; 9224 OverloadCandidateKind FnKind = 9225 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9226 9227 Expr *FromExpr = Conv.Bad.FromExpr; 9228 QualType FromTy = Conv.Bad.getFromType(); 9229 QualType ToTy = Conv.Bad.getToType(); 9230 9231 if (FromTy == S.Context.OverloadTy) { 9232 assert(FromExpr && "overload set argument came from implicit argument?"); 9233 Expr *E = FromExpr->IgnoreParens(); 9234 if (isa<UnaryOperator>(E)) 9235 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 9236 DeclarationName Name = cast<OverloadExpr>(E)->getName(); 9237 9238 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload) 9239 << (unsigned) FnKind << FnDesc 9240 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9241 << ToTy << Name << I+1; 9242 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9243 return; 9244 } 9245 9246 // Do some hand-waving analysis to see if the non-viability is due 9247 // to a qualifier mismatch. 9248 CanQualType CFromTy = S.Context.getCanonicalType(FromTy); 9249 CanQualType CToTy = S.Context.getCanonicalType(ToTy); 9250 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>()) 9251 CToTy = RT->getPointeeType(); 9252 else { 9253 // TODO: detect and diagnose the full richness of const mismatches. 9254 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>()) 9255 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) { 9256 CFromTy = FromPT->getPointeeType(); 9257 CToTy = ToPT->getPointeeType(); 9258 } 9259 } 9260 9261 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() && 9262 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) { 9263 Qualifiers FromQs = CFromTy.getQualifiers(); 9264 Qualifiers ToQs = CToTy.getQualifiers(); 9265 9266 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) { 9267 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace) 9268 << (unsigned) FnKind << FnDesc 9269 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9270 << FromTy 9271 << FromQs.getAddressSpace() << ToQs.getAddressSpace() 9272 << (unsigned) isObjectArgument << I+1; 9273 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9274 return; 9275 } 9276 9277 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9278 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership) 9279 << (unsigned) FnKind << FnDesc 9280 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9281 << FromTy 9282 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime() 9283 << (unsigned) isObjectArgument << I+1; 9284 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9285 return; 9286 } 9287 9288 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) { 9289 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc) 9290 << (unsigned) FnKind << FnDesc 9291 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9292 << FromTy 9293 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr() 9294 << (unsigned) isObjectArgument << I+1; 9295 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9296 return; 9297 } 9298 9299 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) { 9300 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned) 9301 << (unsigned) FnKind << FnDesc 9302 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9303 << FromTy << FromQs.hasUnaligned() << I+1; 9304 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9305 return; 9306 } 9307 9308 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers(); 9309 assert(CVR && "unexpected qualifiers mismatch"); 9310 9311 if (isObjectArgument) { 9312 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this) 9313 << (unsigned) FnKind << FnDesc 9314 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9315 << FromTy << (CVR - 1); 9316 } else { 9317 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr) 9318 << (unsigned) FnKind << FnDesc 9319 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9320 << FromTy << (CVR - 1) << I+1; 9321 } 9322 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9323 return; 9324 } 9325 9326 // Special diagnostic for failure to convert an initializer list, since 9327 // telling the user that it has type void is not useful. 9328 if (FromExpr && isa<InitListExpr>(FromExpr)) { 9329 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument) 9330 << (unsigned) FnKind << FnDesc 9331 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9332 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9333 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9334 return; 9335 } 9336 9337 // Diagnose references or pointers to incomplete types differently, 9338 // since it's far from impossible that the incompleteness triggered 9339 // the failure. 9340 QualType TempFromTy = FromTy.getNonReferenceType(); 9341 if (const PointerType *PTy = TempFromTy->getAs<PointerType>()) 9342 TempFromTy = PTy->getPointeeType(); 9343 if (TempFromTy->isIncompleteType()) { 9344 // Emit the generic diagnostic and, optionally, add the hints to it. 9345 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete) 9346 << (unsigned) FnKind << FnDesc 9347 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9348 << FromTy << ToTy << (unsigned) isObjectArgument << I+1 9349 << (unsigned) (Cand->Fix.Kind); 9350 9351 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9352 return; 9353 } 9354 9355 // Diagnose base -> derived pointer conversions. 9356 unsigned BaseToDerivedConversion = 0; 9357 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) { 9358 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) { 9359 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9360 FromPtrTy->getPointeeType()) && 9361 !FromPtrTy->getPointeeType()->isIncompleteType() && 9362 !ToPtrTy->getPointeeType()->isIncompleteType() && 9363 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(), 9364 FromPtrTy->getPointeeType())) 9365 BaseToDerivedConversion = 1; 9366 } 9367 } else if (const ObjCObjectPointerType *FromPtrTy 9368 = FromTy->getAs<ObjCObjectPointerType>()) { 9369 if (const ObjCObjectPointerType *ToPtrTy 9370 = ToTy->getAs<ObjCObjectPointerType>()) 9371 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl()) 9372 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl()) 9373 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs( 9374 FromPtrTy->getPointeeType()) && 9375 FromIface->isSuperClassOf(ToIface)) 9376 BaseToDerivedConversion = 2; 9377 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) { 9378 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) && 9379 !FromTy->isIncompleteType() && 9380 !ToRefTy->getPointeeType()->isIncompleteType() && 9381 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) { 9382 BaseToDerivedConversion = 3; 9383 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() && 9384 ToTy.getNonReferenceType().getCanonicalType() == 9385 FromTy.getNonReferenceType().getCanonicalType()) { 9386 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue) 9387 << (unsigned) FnKind << FnDesc 9388 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9389 << (unsigned) isObjectArgument << I + 1; 9390 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9391 return; 9392 } 9393 } 9394 9395 if (BaseToDerivedConversion) { 9396 S.Diag(Fn->getLocation(), 9397 diag::note_ovl_candidate_bad_base_to_derived_conv) 9398 << (unsigned) FnKind << FnDesc 9399 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9400 << (BaseToDerivedConversion - 1) 9401 << FromTy << ToTy << I+1; 9402 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9403 return; 9404 } 9405 9406 if (isa<ObjCObjectPointerType>(CFromTy) && 9407 isa<PointerType>(CToTy)) { 9408 Qualifiers FromQs = CFromTy.getQualifiers(); 9409 Qualifiers ToQs = CToTy.getQualifiers(); 9410 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) { 9411 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv) 9412 << (unsigned) FnKind << FnDesc 9413 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9414 << FromTy << ToTy << (unsigned) isObjectArgument << I+1; 9415 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9416 return; 9417 } 9418 } 9419 9420 if (TakingCandidateAddress && 9421 !checkAddressOfCandidateIsAvailable(S, Cand->Function)) 9422 return; 9423 9424 // Emit the generic diagnostic and, optionally, add the hints to it. 9425 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv); 9426 FDiag << (unsigned) FnKind << FnDesc 9427 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) 9428 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1 9429 << (unsigned) (Cand->Fix.Kind); 9430 9431 // If we can fix the conversion, suggest the FixIts. 9432 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(), 9433 HE = Cand->Fix.Hints.end(); HI != HE; ++HI) 9434 FDiag << *HI; 9435 S.Diag(Fn->getLocation(), FDiag); 9436 9437 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9438 } 9439 9440 /// Additional arity mismatch diagnosis specific to a function overload 9441 /// candidates. This is not covered by the more general DiagnoseArityMismatch() 9442 /// over a candidate in any candidate set. 9443 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, 9444 unsigned NumArgs) { 9445 FunctionDecl *Fn = Cand->Function; 9446 unsigned MinParams = Fn->getMinRequiredArguments(); 9447 9448 // With invalid overloaded operators, it's possible that we think we 9449 // have an arity mismatch when in fact it looks like we have the 9450 // right number of arguments, because only overloaded operators have 9451 // the weird behavior of overloading member and non-member functions. 9452 // Just don't report anything. 9453 if (Fn->isInvalidDecl() && 9454 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 9455 return true; 9456 9457 if (NumArgs < MinParams) { 9458 assert((Cand->FailureKind == ovl_fail_too_few_arguments) || 9459 (Cand->FailureKind == ovl_fail_bad_deduction && 9460 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments)); 9461 } else { 9462 assert((Cand->FailureKind == ovl_fail_too_many_arguments) || 9463 (Cand->FailureKind == ovl_fail_bad_deduction && 9464 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments)); 9465 } 9466 9467 return false; 9468 } 9469 9470 /// General arity mismatch diagnosis over a candidate in a candidate set. 9471 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, 9472 unsigned NumFormalArgs) { 9473 assert(isa<FunctionDecl>(D) && 9474 "The templated declaration should at least be a function" 9475 " when diagnosing bad template argument deduction due to too many" 9476 " or too few arguments"); 9477 9478 FunctionDecl *Fn = cast<FunctionDecl>(D); 9479 9480 // TODO: treat calls to a missing default constructor as a special case 9481 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>(); 9482 unsigned MinParams = Fn->getMinRequiredArguments(); 9483 9484 // at least / at most / exactly 9485 unsigned mode, modeCount; 9486 if (NumFormalArgs < MinParams) { 9487 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() || 9488 FnTy->isTemplateVariadic()) 9489 mode = 0; // "at least" 9490 else 9491 mode = 2; // "exactly" 9492 modeCount = MinParams; 9493 } else { 9494 if (MinParams != FnTy->getNumParams()) 9495 mode = 1; // "at most" 9496 else 9497 mode = 2; // "exactly" 9498 modeCount = FnTy->getNumParams(); 9499 } 9500 9501 std::string Description; 9502 OverloadCandidateKind FnKind = 9503 ClassifyOverloadCandidate(S, Found, Fn, Description); 9504 9505 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName()) 9506 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one) 9507 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9508 << mode << Fn->getParamDecl(0) << NumFormalArgs; 9509 else 9510 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity) 9511 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr) 9512 << mode << modeCount << NumFormalArgs; 9513 MaybeEmitInheritedConstructorNote(S, Found); 9514 } 9515 9516 /// Arity mismatch diagnosis specific to a function overload candidate. 9517 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand, 9518 unsigned NumFormalArgs) { 9519 if (!CheckArityMismatch(S, Cand, NumFormalArgs)) 9520 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs); 9521 } 9522 9523 static TemplateDecl *getDescribedTemplate(Decl *Templated) { 9524 if (TemplateDecl *TD = Templated->getDescribedTemplate()) 9525 return TD; 9526 llvm_unreachable("Unsupported: Getting the described template declaration" 9527 " for bad deduction diagnosis"); 9528 } 9529 9530 /// Diagnose a failed template-argument deduction. 9531 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, 9532 DeductionFailureInfo &DeductionFailure, 9533 unsigned NumArgs, 9534 bool TakingCandidateAddress) { 9535 TemplateParameter Param = DeductionFailure.getTemplateParameter(); 9536 NamedDecl *ParamD; 9537 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) || 9538 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) || 9539 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>()); 9540 switch (DeductionFailure.Result) { 9541 case Sema::TDK_Success: 9542 llvm_unreachable("TDK_success while diagnosing bad deduction"); 9543 9544 case Sema::TDK_Incomplete: { 9545 assert(ParamD && "no parameter found for incomplete deduction result"); 9546 S.Diag(Templated->getLocation(), 9547 diag::note_ovl_candidate_incomplete_deduction) 9548 << ParamD->getDeclName(); 9549 MaybeEmitInheritedConstructorNote(S, Found); 9550 return; 9551 } 9552 9553 case Sema::TDK_Underqualified: { 9554 assert(ParamD && "no parameter found for bad qualifiers deduction result"); 9555 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD); 9556 9557 QualType Param = DeductionFailure.getFirstArg()->getAsType(); 9558 9559 // Param will have been canonicalized, but it should just be a 9560 // qualified version of ParamD, so move the qualifiers to that. 9561 QualifierCollector Qs; 9562 Qs.strip(Param); 9563 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl()); 9564 assert(S.Context.hasSameType(Param, NonCanonParam)); 9565 9566 // Arg has also been canonicalized, but there's nothing we can do 9567 // about that. It also doesn't matter as much, because it won't 9568 // have any template parameters in it (because deduction isn't 9569 // done on dependent types). 9570 QualType Arg = DeductionFailure.getSecondArg()->getAsType(); 9571 9572 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified) 9573 << ParamD->getDeclName() << Arg << NonCanonParam; 9574 MaybeEmitInheritedConstructorNote(S, Found); 9575 return; 9576 } 9577 9578 case Sema::TDK_Inconsistent: { 9579 assert(ParamD && "no parameter found for inconsistent deduction result"); 9580 int which = 0; 9581 if (isa<TemplateTypeParmDecl>(ParamD)) 9582 which = 0; 9583 else if (isa<NonTypeTemplateParmDecl>(ParamD)) { 9584 // Deduction might have failed because we deduced arguments of two 9585 // different types for a non-type template parameter. 9586 // FIXME: Use a different TDK value for this. 9587 QualType T1 = 9588 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType(); 9589 QualType T2 = 9590 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType(); 9591 if (!S.Context.hasSameType(T1, T2)) { 9592 S.Diag(Templated->getLocation(), 9593 diag::note_ovl_candidate_inconsistent_deduction_types) 9594 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1 9595 << *DeductionFailure.getSecondArg() << T2; 9596 MaybeEmitInheritedConstructorNote(S, Found); 9597 return; 9598 } 9599 9600 which = 1; 9601 } else { 9602 which = 2; 9603 } 9604 9605 S.Diag(Templated->getLocation(), 9606 diag::note_ovl_candidate_inconsistent_deduction) 9607 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg() 9608 << *DeductionFailure.getSecondArg(); 9609 MaybeEmitInheritedConstructorNote(S, Found); 9610 return; 9611 } 9612 9613 case Sema::TDK_InvalidExplicitArguments: 9614 assert(ParamD && "no parameter found for invalid explicit arguments"); 9615 if (ParamD->getDeclName()) 9616 S.Diag(Templated->getLocation(), 9617 diag::note_ovl_candidate_explicit_arg_mismatch_named) 9618 << ParamD->getDeclName(); 9619 else { 9620 int index = 0; 9621 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD)) 9622 index = TTP->getIndex(); 9623 else if (NonTypeTemplateParmDecl *NTTP 9624 = dyn_cast<NonTypeTemplateParmDecl>(ParamD)) 9625 index = NTTP->getIndex(); 9626 else 9627 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex(); 9628 S.Diag(Templated->getLocation(), 9629 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed) 9630 << (index + 1); 9631 } 9632 MaybeEmitInheritedConstructorNote(S, Found); 9633 return; 9634 9635 case Sema::TDK_TooManyArguments: 9636 case Sema::TDK_TooFewArguments: 9637 DiagnoseArityMismatch(S, Found, Templated, NumArgs); 9638 return; 9639 9640 case Sema::TDK_InstantiationDepth: 9641 S.Diag(Templated->getLocation(), 9642 diag::note_ovl_candidate_instantiation_depth); 9643 MaybeEmitInheritedConstructorNote(S, Found); 9644 return; 9645 9646 case Sema::TDK_SubstitutionFailure: { 9647 // Format the template argument list into the argument string. 9648 SmallString<128> TemplateArgString; 9649 if (TemplateArgumentList *Args = 9650 DeductionFailure.getTemplateArgumentList()) { 9651 TemplateArgString = " "; 9652 TemplateArgString += S.getTemplateArgumentBindingsText( 9653 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9654 } 9655 9656 // If this candidate was disabled by enable_if, say so. 9657 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic(); 9658 if (PDiag && PDiag->second.getDiagID() == 9659 diag::err_typename_nested_not_found_enable_if) { 9660 // FIXME: Use the source range of the condition, and the fully-qualified 9661 // name of the enable_if template. These are both present in PDiag. 9662 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if) 9663 << "'enable_if'" << TemplateArgString; 9664 return; 9665 } 9666 9667 // Format the SFINAE diagnostic into the argument string. 9668 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s 9669 // formatted message in another diagnostic. 9670 SmallString<128> SFINAEArgString; 9671 SourceRange R; 9672 if (PDiag) { 9673 SFINAEArgString = ": "; 9674 R = SourceRange(PDiag->first, PDiag->first); 9675 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString); 9676 } 9677 9678 S.Diag(Templated->getLocation(), 9679 diag::note_ovl_candidate_substitution_failure) 9680 << TemplateArgString << SFINAEArgString << R; 9681 MaybeEmitInheritedConstructorNote(S, Found); 9682 return; 9683 } 9684 9685 case Sema::TDK_DeducedMismatch: { 9686 // Format the template argument list into the argument string. 9687 SmallString<128> TemplateArgString; 9688 if (TemplateArgumentList *Args = 9689 DeductionFailure.getTemplateArgumentList()) { 9690 TemplateArgString = " "; 9691 TemplateArgString += S.getTemplateArgumentBindingsText( 9692 getDescribedTemplate(Templated)->getTemplateParameters(), *Args); 9693 } 9694 9695 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch) 9696 << (*DeductionFailure.getCallArgIndex() + 1) 9697 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg() 9698 << TemplateArgString; 9699 break; 9700 } 9701 9702 case Sema::TDK_NonDeducedMismatch: { 9703 // FIXME: Provide a source location to indicate what we couldn't match. 9704 TemplateArgument FirstTA = *DeductionFailure.getFirstArg(); 9705 TemplateArgument SecondTA = *DeductionFailure.getSecondArg(); 9706 if (FirstTA.getKind() == TemplateArgument::Template && 9707 SecondTA.getKind() == TemplateArgument::Template) { 9708 TemplateName FirstTN = FirstTA.getAsTemplate(); 9709 TemplateName SecondTN = SecondTA.getAsTemplate(); 9710 if (FirstTN.getKind() == TemplateName::Template && 9711 SecondTN.getKind() == TemplateName::Template) { 9712 if (FirstTN.getAsTemplateDecl()->getName() == 9713 SecondTN.getAsTemplateDecl()->getName()) { 9714 // FIXME: This fixes a bad diagnostic where both templates are named 9715 // the same. This particular case is a bit difficult since: 9716 // 1) It is passed as a string to the diagnostic printer. 9717 // 2) The diagnostic printer only attempts to find a better 9718 // name for types, not decls. 9719 // Ideally, this should folded into the diagnostic printer. 9720 S.Diag(Templated->getLocation(), 9721 diag::note_ovl_candidate_non_deduced_mismatch_qualified) 9722 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl(); 9723 return; 9724 } 9725 } 9726 } 9727 9728 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) && 9729 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated))) 9730 return; 9731 9732 // FIXME: For generic lambda parameters, check if the function is a lambda 9733 // call operator, and if so, emit a prettier and more informative 9734 // diagnostic that mentions 'auto' and lambda in addition to 9735 // (or instead of?) the canonical template type parameters. 9736 S.Diag(Templated->getLocation(), 9737 diag::note_ovl_candidate_non_deduced_mismatch) 9738 << FirstTA << SecondTA; 9739 return; 9740 } 9741 // TODO: diagnose these individually, then kill off 9742 // note_ovl_candidate_bad_deduction, which is uselessly vague. 9743 case Sema::TDK_MiscellaneousDeductionFailure: 9744 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction); 9745 MaybeEmitInheritedConstructorNote(S, Found); 9746 return; 9747 case Sema::TDK_CUDATargetMismatch: 9748 S.Diag(Templated->getLocation(), 9749 diag::note_cuda_ovl_candidate_target_mismatch); 9750 return; 9751 } 9752 } 9753 9754 /// Diagnose a failed template-argument deduction, for function calls. 9755 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, 9756 unsigned NumArgs, 9757 bool TakingCandidateAddress) { 9758 unsigned TDK = Cand->DeductionFailure.Result; 9759 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) { 9760 if (CheckArityMismatch(S, Cand, NumArgs)) 9761 return; 9762 } 9763 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern 9764 Cand->DeductionFailure, NumArgs, TakingCandidateAddress); 9765 } 9766 9767 /// CUDA: diagnose an invalid call across targets. 9768 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) { 9769 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext); 9770 FunctionDecl *Callee = Cand->Function; 9771 9772 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller), 9773 CalleeTarget = S.IdentifyCUDATarget(Callee); 9774 9775 std::string FnDesc; 9776 OverloadCandidateKind FnKind = 9777 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc); 9778 9779 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target) 9780 << (unsigned)FnKind << CalleeTarget << CallerTarget; 9781 9782 // This could be an implicit constructor for which we could not infer the 9783 // target due to a collsion. Diagnose that case. 9784 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee); 9785 if (Meth != nullptr && Meth->isImplicit()) { 9786 CXXRecordDecl *ParentClass = Meth->getParent(); 9787 Sema::CXXSpecialMember CSM; 9788 9789 switch (FnKind) { 9790 default: 9791 return; 9792 case oc_implicit_default_constructor: 9793 CSM = Sema::CXXDefaultConstructor; 9794 break; 9795 case oc_implicit_copy_constructor: 9796 CSM = Sema::CXXCopyConstructor; 9797 break; 9798 case oc_implicit_move_constructor: 9799 CSM = Sema::CXXMoveConstructor; 9800 break; 9801 case oc_implicit_copy_assignment: 9802 CSM = Sema::CXXCopyAssignment; 9803 break; 9804 case oc_implicit_move_assignment: 9805 CSM = Sema::CXXMoveAssignment; 9806 break; 9807 }; 9808 9809 bool ConstRHS = false; 9810 if (Meth->getNumParams()) { 9811 if (const ReferenceType *RT = 9812 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) { 9813 ConstRHS = RT->getPointeeType().isConstQualified(); 9814 } 9815 } 9816 9817 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth, 9818 /* ConstRHS */ ConstRHS, 9819 /* Diagnose */ true); 9820 } 9821 } 9822 9823 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) { 9824 FunctionDecl *Callee = Cand->Function; 9825 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data); 9826 9827 S.Diag(Callee->getLocation(), 9828 diag::note_ovl_candidate_disabled_by_enable_if_attr) 9829 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 9830 } 9831 9832 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) { 9833 FunctionDecl *Callee = Cand->Function; 9834 9835 S.Diag(Callee->getLocation(), 9836 diag::note_ovl_candidate_disabled_by_extension); 9837 } 9838 9839 /// Generates a 'note' diagnostic for an overload candidate. We've 9840 /// already generated a primary error at the call site. 9841 /// 9842 /// It really does need to be a single diagnostic with its caret 9843 /// pointed at the candidate declaration. Yes, this creates some 9844 /// major challenges of technical writing. Yes, this makes pointing 9845 /// out problems with specific arguments quite awkward. It's still 9846 /// better than generating twenty screens of text for every failed 9847 /// overload. 9848 /// 9849 /// It would be great to be able to express per-candidate problems 9850 /// more richly for those diagnostic clients that cared, but we'd 9851 /// still have to be just as careful with the default diagnostics. 9852 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, 9853 unsigned NumArgs, 9854 bool TakingCandidateAddress) { 9855 FunctionDecl *Fn = Cand->Function; 9856 9857 // Note deleted candidates, but only if they're viable. 9858 if (Cand->Viable && (Fn->isDeleted() || 9859 S.isFunctionConsideredUnavailable(Fn))) { 9860 std::string FnDesc; 9861 OverloadCandidateKind FnKind = 9862 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc); 9863 9864 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted) 9865 << FnKind << FnDesc 9866 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0); 9867 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9868 return; 9869 } 9870 9871 // We don't really have anything else to say about viable candidates. 9872 if (Cand->Viable) { 9873 S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 9874 return; 9875 } 9876 9877 switch (Cand->FailureKind) { 9878 case ovl_fail_too_many_arguments: 9879 case ovl_fail_too_few_arguments: 9880 return DiagnoseArityMismatch(S, Cand, NumArgs); 9881 9882 case ovl_fail_bad_deduction: 9883 return DiagnoseBadDeduction(S, Cand, NumArgs, 9884 TakingCandidateAddress); 9885 9886 case ovl_fail_illegal_constructor: { 9887 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor) 9888 << (Fn->getPrimaryTemplate() ? 1 : 0); 9889 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl); 9890 return; 9891 } 9892 9893 case ovl_fail_trivial_conversion: 9894 case ovl_fail_bad_final_conversion: 9895 case ovl_fail_final_conversion_not_exact: 9896 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 9897 9898 case ovl_fail_bad_conversion: { 9899 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0); 9900 for (unsigned N = Cand->NumConversions; I != N; ++I) 9901 if (Cand->Conversions[I].isBad()) 9902 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress); 9903 9904 // FIXME: this currently happens when we're called from SemaInit 9905 // when user-conversion overload fails. Figure out how to handle 9906 // those conditions and diagnose them well. 9907 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn); 9908 } 9909 9910 case ovl_fail_bad_target: 9911 return DiagnoseBadTarget(S, Cand); 9912 9913 case ovl_fail_enable_if: 9914 return DiagnoseFailedEnableIfAttr(S, Cand); 9915 9916 case ovl_fail_ext_disabled: 9917 return DiagnoseOpenCLExtensionDisabled(S, Cand); 9918 9919 case ovl_fail_addr_not_available: { 9920 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function); 9921 (void)Available; 9922 assert(!Available); 9923 break; 9924 } 9925 } 9926 } 9927 9928 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) { 9929 // Desugar the type of the surrogate down to a function type, 9930 // retaining as many typedefs as possible while still showing 9931 // the function type (and, therefore, its parameter types). 9932 QualType FnType = Cand->Surrogate->getConversionType(); 9933 bool isLValueReference = false; 9934 bool isRValueReference = false; 9935 bool isPointer = false; 9936 if (const LValueReferenceType *FnTypeRef = 9937 FnType->getAs<LValueReferenceType>()) { 9938 FnType = FnTypeRef->getPointeeType(); 9939 isLValueReference = true; 9940 } else if (const RValueReferenceType *FnTypeRef = 9941 FnType->getAs<RValueReferenceType>()) { 9942 FnType = FnTypeRef->getPointeeType(); 9943 isRValueReference = true; 9944 } 9945 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) { 9946 FnType = FnTypePtr->getPointeeType(); 9947 isPointer = true; 9948 } 9949 // Desugar down to a function type. 9950 FnType = QualType(FnType->getAs<FunctionType>(), 0); 9951 // Reconstruct the pointer/reference as appropriate. 9952 if (isPointer) FnType = S.Context.getPointerType(FnType); 9953 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType); 9954 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType); 9955 9956 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand) 9957 << FnType; 9958 } 9959 9960 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, 9961 SourceLocation OpLoc, 9962 OverloadCandidate *Cand) { 9963 assert(Cand->NumConversions <= 2 && "builtin operator is not binary"); 9964 std::string TypeStr("operator"); 9965 TypeStr += Opc; 9966 TypeStr += "("; 9967 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString(); 9968 if (Cand->NumConversions == 1) { 9969 TypeStr += ")"; 9970 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr; 9971 } else { 9972 TypeStr += ", "; 9973 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString(); 9974 TypeStr += ")"; 9975 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr; 9976 } 9977 } 9978 9979 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, 9980 OverloadCandidate *Cand) { 9981 unsigned NoOperands = Cand->NumConversions; 9982 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) { 9983 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx]; 9984 if (ICS.isBad()) break; // all meaningless after first invalid 9985 if (!ICS.isAmbiguous()) continue; 9986 9987 ICS.DiagnoseAmbiguousConversion( 9988 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion)); 9989 } 9990 } 9991 9992 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) { 9993 if (Cand->Function) 9994 return Cand->Function->getLocation(); 9995 if (Cand->IsSurrogate) 9996 return Cand->Surrogate->getLocation(); 9997 return SourceLocation(); 9998 } 9999 10000 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) { 10001 switch ((Sema::TemplateDeductionResult)DFI.Result) { 10002 case Sema::TDK_Success: 10003 llvm_unreachable("TDK_success while diagnosing bad deduction"); 10004 10005 case Sema::TDK_Invalid: 10006 case Sema::TDK_Incomplete: 10007 return 1; 10008 10009 case Sema::TDK_Underqualified: 10010 case Sema::TDK_Inconsistent: 10011 return 2; 10012 10013 case Sema::TDK_SubstitutionFailure: 10014 case Sema::TDK_DeducedMismatch: 10015 case Sema::TDK_NonDeducedMismatch: 10016 case Sema::TDK_MiscellaneousDeductionFailure: 10017 case Sema::TDK_CUDATargetMismatch: 10018 return 3; 10019 10020 case Sema::TDK_InstantiationDepth: 10021 return 4; 10022 10023 case Sema::TDK_InvalidExplicitArguments: 10024 return 5; 10025 10026 case Sema::TDK_TooManyArguments: 10027 case Sema::TDK_TooFewArguments: 10028 return 6; 10029 } 10030 llvm_unreachable("Unhandled deduction result"); 10031 } 10032 10033 namespace { 10034 struct CompareOverloadCandidatesForDisplay { 10035 Sema &S; 10036 SourceLocation Loc; 10037 size_t NumArgs; 10038 10039 CompareOverloadCandidatesForDisplay(Sema &S, SourceLocation Loc, size_t nArgs) 10040 : S(S), NumArgs(nArgs) {} 10041 10042 bool operator()(const OverloadCandidate *L, 10043 const OverloadCandidate *R) { 10044 // Fast-path this check. 10045 if (L == R) return false; 10046 10047 // Order first by viability. 10048 if (L->Viable) { 10049 if (!R->Viable) return true; 10050 10051 // TODO: introduce a tri-valued comparison for overload 10052 // candidates. Would be more worthwhile if we had a sort 10053 // that could exploit it. 10054 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true; 10055 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false; 10056 } else if (R->Viable) 10057 return false; 10058 10059 assert(L->Viable == R->Viable); 10060 10061 // Criteria by which we can sort non-viable candidates: 10062 if (!L->Viable) { 10063 // 1. Arity mismatches come after other candidates. 10064 if (L->FailureKind == ovl_fail_too_many_arguments || 10065 L->FailureKind == ovl_fail_too_few_arguments) { 10066 if (R->FailureKind == ovl_fail_too_many_arguments || 10067 R->FailureKind == ovl_fail_too_few_arguments) { 10068 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs); 10069 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs); 10070 if (LDist == RDist) { 10071 if (L->FailureKind == R->FailureKind) 10072 // Sort non-surrogates before surrogates. 10073 return !L->IsSurrogate && R->IsSurrogate; 10074 // Sort candidates requiring fewer parameters than there were 10075 // arguments given after candidates requiring more parameters 10076 // than there were arguments given. 10077 return L->FailureKind == ovl_fail_too_many_arguments; 10078 } 10079 return LDist < RDist; 10080 } 10081 return false; 10082 } 10083 if (R->FailureKind == ovl_fail_too_many_arguments || 10084 R->FailureKind == ovl_fail_too_few_arguments) 10085 return true; 10086 10087 // 2. Bad conversions come first and are ordered by the number 10088 // of bad conversions and quality of good conversions. 10089 if (L->FailureKind == ovl_fail_bad_conversion) { 10090 if (R->FailureKind != ovl_fail_bad_conversion) 10091 return true; 10092 10093 // The conversion that can be fixed with a smaller number of changes, 10094 // comes first. 10095 unsigned numLFixes = L->Fix.NumConversionsFixed; 10096 unsigned numRFixes = R->Fix.NumConversionsFixed; 10097 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes; 10098 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes; 10099 if (numLFixes != numRFixes) { 10100 return numLFixes < numRFixes; 10101 } 10102 10103 // If there's any ordering between the defined conversions... 10104 // FIXME: this might not be transitive. 10105 assert(L->NumConversions == R->NumConversions); 10106 10107 int leftBetter = 0; 10108 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument); 10109 for (unsigned E = L->NumConversions; I != E; ++I) { 10110 switch (CompareImplicitConversionSequences(S, Loc, 10111 L->Conversions[I], 10112 R->Conversions[I])) { 10113 case ImplicitConversionSequence::Better: 10114 leftBetter++; 10115 break; 10116 10117 case ImplicitConversionSequence::Worse: 10118 leftBetter--; 10119 break; 10120 10121 case ImplicitConversionSequence::Indistinguishable: 10122 break; 10123 } 10124 } 10125 if (leftBetter > 0) return true; 10126 if (leftBetter < 0) return false; 10127 10128 } else if (R->FailureKind == ovl_fail_bad_conversion) 10129 return false; 10130 10131 if (L->FailureKind == ovl_fail_bad_deduction) { 10132 if (R->FailureKind != ovl_fail_bad_deduction) 10133 return true; 10134 10135 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10136 return RankDeductionFailure(L->DeductionFailure) 10137 < RankDeductionFailure(R->DeductionFailure); 10138 } else if (R->FailureKind == ovl_fail_bad_deduction) 10139 return false; 10140 10141 // TODO: others? 10142 } 10143 10144 // Sort everything else by location. 10145 SourceLocation LLoc = GetLocationForCandidate(L); 10146 SourceLocation RLoc = GetLocationForCandidate(R); 10147 10148 // Put candidates without locations (e.g. builtins) at the end. 10149 if (LLoc.isInvalid()) return false; 10150 if (RLoc.isInvalid()) return true; 10151 10152 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10153 } 10154 }; 10155 } 10156 10157 /// CompleteNonViableCandidate - Normally, overload resolution only 10158 /// computes up to the first. Produces the FixIt set if possible. 10159 static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, 10160 ArrayRef<Expr *> Args) { 10161 assert(!Cand->Viable); 10162 10163 // Don't do anything on failures other than bad conversion. 10164 if (Cand->FailureKind != ovl_fail_bad_conversion) return; 10165 10166 // We only want the FixIts if all the arguments can be corrected. 10167 bool Unfixable = false; 10168 // Use a implicit copy initialization to check conversion fixes. 10169 Cand->Fix.setConversionChecker(TryCopyInitialization); 10170 10171 // Skip forward to the first bad conversion. 10172 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); 10173 unsigned ConvCount = Cand->NumConversions; 10174 while (true) { 10175 assert(ConvIdx != ConvCount && "no bad conversion in candidate"); 10176 ConvIdx++; 10177 if (Cand->Conversions[ConvIdx - 1].isBad()) { 10178 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S); 10179 break; 10180 } 10181 } 10182 10183 if (ConvIdx == ConvCount) 10184 return; 10185 10186 assert(!Cand->Conversions[ConvIdx].isInitialized() && 10187 "remaining conversion is initialized?"); 10188 10189 // FIXME: this should probably be preserved from the overload 10190 // operation somehow. 10191 bool SuppressUserConversions = false; 10192 10193 const FunctionProtoType* Proto; 10194 unsigned ArgIdx = ConvIdx; 10195 10196 if (Cand->IsSurrogate) { 10197 QualType ConvType 10198 = Cand->Surrogate->getConversionType().getNonReferenceType(); 10199 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 10200 ConvType = ConvPtrType->getPointeeType(); 10201 Proto = ConvType->getAs<FunctionProtoType>(); 10202 ArgIdx--; 10203 } else if (Cand->Function) { 10204 Proto = Cand->Function->getType()->getAs<FunctionProtoType>(); 10205 if (isa<CXXMethodDecl>(Cand->Function) && 10206 !isa<CXXConstructorDecl>(Cand->Function)) 10207 ArgIdx--; 10208 } else { 10209 // Builtin binary operator with a bad first conversion. 10210 assert(ConvCount <= 3); 10211 for (; ConvIdx != ConvCount; ++ConvIdx) 10212 Cand->Conversions[ConvIdx] 10213 = TryCopyInitialization(S, Args[ConvIdx], 10214 Cand->BuiltinTypes.ParamTypes[ConvIdx], 10215 SuppressUserConversions, 10216 /*InOverloadResolution*/ true, 10217 /*AllowObjCWritebackConversion=*/ 10218 S.getLangOpts().ObjCAutoRefCount); 10219 return; 10220 } 10221 10222 // Fill in the rest of the conversions. 10223 unsigned NumParams = Proto->getNumParams(); 10224 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) { 10225 if (ArgIdx < NumParams) { 10226 Cand->Conversions[ConvIdx] = TryCopyInitialization( 10227 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions, 10228 /*InOverloadResolution=*/true, 10229 /*AllowObjCWritebackConversion=*/ 10230 S.getLangOpts().ObjCAutoRefCount); 10231 // Store the FixIt in the candidate if it exists. 10232 if (!Unfixable && Cand->Conversions[ConvIdx].isBad()) 10233 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S); 10234 } 10235 else 10236 Cand->Conversions[ConvIdx].setEllipsis(); 10237 } 10238 } 10239 10240 /// PrintOverloadCandidates - When overload resolution fails, prints 10241 /// diagnostic messages containing the candidates in the candidate 10242 /// set. 10243 void OverloadCandidateSet::NoteCandidates( 10244 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args, 10245 StringRef Opc, SourceLocation OpLoc, 10246 llvm::function_ref<bool(OverloadCandidate &)> Filter) { 10247 // Sort the candidates by viability and position. Sorting directly would 10248 // be prohibitive, so we make a set of pointers and sort those. 10249 SmallVector<OverloadCandidate*, 32> Cands; 10250 if (OCD == OCD_AllCandidates) Cands.reserve(size()); 10251 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10252 if (!Filter(*Cand)) 10253 continue; 10254 if (Cand->Viable) 10255 Cands.push_back(Cand); 10256 else if (OCD == OCD_AllCandidates) { 10257 CompleteNonViableCandidate(S, Cand, Args); 10258 if (Cand->Function || Cand->IsSurrogate) 10259 Cands.push_back(Cand); 10260 // Otherwise, this a non-viable builtin candidate. We do not, in general, 10261 // want to list every possible builtin candidate. 10262 } 10263 } 10264 10265 std::sort(Cands.begin(), Cands.end(), 10266 CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size())); 10267 10268 bool ReportedAmbiguousConversions = false; 10269 10270 SmallVectorImpl<OverloadCandidate*>::iterator I, E; 10271 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10272 unsigned CandsShown = 0; 10273 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10274 OverloadCandidate *Cand = *I; 10275 10276 // Set an arbitrary limit on the number of candidate functions we'll spam 10277 // the user with. FIXME: This limit should depend on details of the 10278 // candidate list. 10279 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) { 10280 break; 10281 } 10282 ++CandsShown; 10283 10284 if (Cand->Function) 10285 NoteFunctionCandidate(S, Cand, Args.size(), 10286 /*TakingCandidateAddress=*/false); 10287 else if (Cand->IsSurrogate) 10288 NoteSurrogateCandidate(S, Cand); 10289 else { 10290 assert(Cand->Viable && 10291 "Non-viable built-in candidates are not added to Cands."); 10292 // Generally we only see ambiguities including viable builtin 10293 // operators if overload resolution got screwed up by an 10294 // ambiguous user-defined conversion. 10295 // 10296 // FIXME: It's quite possible for different conversions to see 10297 // different ambiguities, though. 10298 if (!ReportedAmbiguousConversions) { 10299 NoteAmbiguousUserConversions(S, OpLoc, Cand); 10300 ReportedAmbiguousConversions = true; 10301 } 10302 10303 // If this is a viable builtin, print it. 10304 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand); 10305 } 10306 } 10307 10308 if (I != E) 10309 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I); 10310 } 10311 10312 static SourceLocation 10313 GetLocationForCandidate(const TemplateSpecCandidate *Cand) { 10314 return Cand->Specialization ? Cand->Specialization->getLocation() 10315 : SourceLocation(); 10316 } 10317 10318 namespace { 10319 struct CompareTemplateSpecCandidatesForDisplay { 10320 Sema &S; 10321 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {} 10322 10323 bool operator()(const TemplateSpecCandidate *L, 10324 const TemplateSpecCandidate *R) { 10325 // Fast-path this check. 10326 if (L == R) 10327 return false; 10328 10329 // Assuming that both candidates are not matches... 10330 10331 // Sort by the ranking of deduction failures. 10332 if (L->DeductionFailure.Result != R->DeductionFailure.Result) 10333 return RankDeductionFailure(L->DeductionFailure) < 10334 RankDeductionFailure(R->DeductionFailure); 10335 10336 // Sort everything else by location. 10337 SourceLocation LLoc = GetLocationForCandidate(L); 10338 SourceLocation RLoc = GetLocationForCandidate(R); 10339 10340 // Put candidates without locations (e.g. builtins) at the end. 10341 if (LLoc.isInvalid()) 10342 return false; 10343 if (RLoc.isInvalid()) 10344 return true; 10345 10346 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc); 10347 } 10348 }; 10349 } 10350 10351 /// Diagnose a template argument deduction failure. 10352 /// We are treating these failures as overload failures due to bad 10353 /// deductions. 10354 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S, 10355 bool ForTakingAddress) { 10356 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern 10357 DeductionFailure, /*NumArgs=*/0, ForTakingAddress); 10358 } 10359 10360 void TemplateSpecCandidateSet::destroyCandidates() { 10361 for (iterator i = begin(), e = end(); i != e; ++i) { 10362 i->DeductionFailure.Destroy(); 10363 } 10364 } 10365 10366 void TemplateSpecCandidateSet::clear() { 10367 destroyCandidates(); 10368 Candidates.clear(); 10369 } 10370 10371 /// NoteCandidates - When no template specialization match is found, prints 10372 /// diagnostic messages containing the non-matching specializations that form 10373 /// the candidate set. 10374 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with 10375 /// OCD == OCD_AllCandidates and Cand->Viable == false. 10376 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) { 10377 // Sort the candidates by position (assuming no candidate is a match). 10378 // Sorting directly would be prohibitive, so we make a set of pointers 10379 // and sort those. 10380 SmallVector<TemplateSpecCandidate *, 32> Cands; 10381 Cands.reserve(size()); 10382 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) { 10383 if (Cand->Specialization) 10384 Cands.push_back(Cand); 10385 // Otherwise, this is a non-matching builtin candidate. We do not, 10386 // in general, want to list every possible builtin candidate. 10387 } 10388 10389 std::sort(Cands.begin(), Cands.end(), 10390 CompareTemplateSpecCandidatesForDisplay(S)); 10391 10392 // FIXME: Perhaps rename OverloadsShown and getShowOverloads() 10393 // for generalization purposes (?). 10394 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads(); 10395 10396 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E; 10397 unsigned CandsShown = 0; 10398 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) { 10399 TemplateSpecCandidate *Cand = *I; 10400 10401 // Set an arbitrary limit on the number of candidates we'll spam 10402 // the user with. FIXME: This limit should depend on details of the 10403 // candidate list. 10404 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) 10405 break; 10406 ++CandsShown; 10407 10408 assert(Cand->Specialization && 10409 "Non-matching built-in candidates are not added to Cands."); 10410 Cand->NoteDeductionFailure(S, ForTakingAddress); 10411 } 10412 10413 if (I != E) 10414 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I); 10415 } 10416 10417 // [PossiblyAFunctionType] --> [Return] 10418 // NonFunctionType --> NonFunctionType 10419 // R (A) --> R(A) 10420 // R (*)(A) --> R (A) 10421 // R (&)(A) --> R (A) 10422 // R (S::*)(A) --> R (A) 10423 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) { 10424 QualType Ret = PossiblyAFunctionType; 10425 if (const PointerType *ToTypePtr = 10426 PossiblyAFunctionType->getAs<PointerType>()) 10427 Ret = ToTypePtr->getPointeeType(); 10428 else if (const ReferenceType *ToTypeRef = 10429 PossiblyAFunctionType->getAs<ReferenceType>()) 10430 Ret = ToTypeRef->getPointeeType(); 10431 else if (const MemberPointerType *MemTypePtr = 10432 PossiblyAFunctionType->getAs<MemberPointerType>()) 10433 Ret = MemTypePtr->getPointeeType(); 10434 Ret = 10435 Context.getCanonicalType(Ret).getUnqualifiedType(); 10436 return Ret; 10437 } 10438 10439 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, 10440 bool Complain = true) { 10441 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() && 10442 S.DeduceReturnType(FD, Loc, Complain)) 10443 return true; 10444 10445 auto *FPT = FD->getType()->castAs<FunctionProtoType>(); 10446 if (S.getLangOpts().CPlusPlus1z && 10447 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 10448 !S.ResolveExceptionSpec(Loc, FPT)) 10449 return true; 10450 10451 return false; 10452 } 10453 10454 namespace { 10455 // A helper class to help with address of function resolution 10456 // - allows us to avoid passing around all those ugly parameters 10457 class AddressOfFunctionResolver { 10458 Sema& S; 10459 Expr* SourceExpr; 10460 const QualType& TargetType; 10461 QualType TargetFunctionType; // Extracted function type from target type 10462 10463 bool Complain; 10464 //DeclAccessPair& ResultFunctionAccessPair; 10465 ASTContext& Context; 10466 10467 bool TargetTypeIsNonStaticMemberFunction; 10468 bool FoundNonTemplateFunction; 10469 bool StaticMemberFunctionFromBoundPointer; 10470 bool HasComplained; 10471 10472 OverloadExpr::FindResult OvlExprInfo; 10473 OverloadExpr *OvlExpr; 10474 TemplateArgumentListInfo OvlExplicitTemplateArgs; 10475 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches; 10476 TemplateSpecCandidateSet FailedCandidates; 10477 10478 public: 10479 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr, 10480 const QualType &TargetType, bool Complain) 10481 : S(S), SourceExpr(SourceExpr), TargetType(TargetType), 10482 Complain(Complain), Context(S.getASTContext()), 10483 TargetTypeIsNonStaticMemberFunction( 10484 !!TargetType->getAs<MemberPointerType>()), 10485 FoundNonTemplateFunction(false), 10486 StaticMemberFunctionFromBoundPointer(false), 10487 HasComplained(false), 10488 OvlExprInfo(OverloadExpr::find(SourceExpr)), 10489 OvlExpr(OvlExprInfo.Expression), 10490 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) { 10491 ExtractUnqualifiedFunctionTypeFromTargetType(); 10492 10493 if (TargetFunctionType->isFunctionType()) { 10494 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr)) 10495 if (!UME->isImplicitAccess() && 10496 !S.ResolveSingleFunctionTemplateSpecialization(UME)) 10497 StaticMemberFunctionFromBoundPointer = true; 10498 } else if (OvlExpr->hasExplicitTemplateArgs()) { 10499 DeclAccessPair dap; 10500 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization( 10501 OvlExpr, false, &dap)) { 10502 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) 10503 if (!Method->isStatic()) { 10504 // If the target type is a non-function type and the function found 10505 // is a non-static member function, pretend as if that was the 10506 // target, it's the only possible type to end up with. 10507 TargetTypeIsNonStaticMemberFunction = true; 10508 10509 // And skip adding the function if its not in the proper form. 10510 // We'll diagnose this due to an empty set of functions. 10511 if (!OvlExprInfo.HasFormOfMemberPointer) 10512 return; 10513 } 10514 10515 Matches.push_back(std::make_pair(dap, Fn)); 10516 } 10517 return; 10518 } 10519 10520 if (OvlExpr->hasExplicitTemplateArgs()) 10521 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs); 10522 10523 if (FindAllFunctionsThatMatchTargetTypeExactly()) { 10524 // C++ [over.over]p4: 10525 // If more than one function is selected, [...] 10526 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) { 10527 if (FoundNonTemplateFunction) 10528 EliminateAllTemplateMatches(); 10529 else 10530 EliminateAllExceptMostSpecializedTemplate(); 10531 } 10532 } 10533 10534 if (S.getLangOpts().CUDA && Matches.size() > 1) 10535 EliminateSuboptimalCudaMatches(); 10536 } 10537 10538 bool hasComplained() const { return HasComplained; } 10539 10540 private: 10541 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) { 10542 QualType Discard; 10543 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) || 10544 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard); 10545 } 10546 10547 /// \return true if A is considered a better overload candidate for the 10548 /// desired type than B. 10549 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) { 10550 // If A doesn't have exactly the correct type, we don't want to classify it 10551 // as "better" than anything else. This way, the user is required to 10552 // disambiguate for us if there are multiple candidates and no exact match. 10553 return candidateHasExactlyCorrectType(A) && 10554 (!candidateHasExactlyCorrectType(B) || 10555 compareEnableIfAttrs(S, A, B) == Comparison::Better); 10556 } 10557 10558 /// \return true if we were able to eliminate all but one overload candidate, 10559 /// false otherwise. 10560 bool eliminiateSuboptimalOverloadCandidates() { 10561 // Same algorithm as overload resolution -- one pass to pick the "best", 10562 // another pass to be sure that nothing is better than the best. 10563 auto Best = Matches.begin(); 10564 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I) 10565 if (isBetterCandidate(I->second, Best->second)) 10566 Best = I; 10567 10568 const FunctionDecl *BestFn = Best->second; 10569 auto IsBestOrInferiorToBest = [this, BestFn]( 10570 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) { 10571 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second); 10572 }; 10573 10574 // Note: We explicitly leave Matches unmodified if there isn't a clear best 10575 // option, so we can potentially give the user a better error 10576 if (!std::all_of(Matches.begin(), Matches.end(), IsBestOrInferiorToBest)) 10577 return false; 10578 Matches[0] = *Best; 10579 Matches.resize(1); 10580 return true; 10581 } 10582 10583 bool isTargetTypeAFunction() const { 10584 return TargetFunctionType->isFunctionType(); 10585 } 10586 10587 // [ToType] [Return] 10588 10589 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false 10590 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false 10591 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true 10592 void inline ExtractUnqualifiedFunctionTypeFromTargetType() { 10593 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType); 10594 } 10595 10596 // return true if any matching specializations were found 10597 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate, 10598 const DeclAccessPair& CurAccessFunPair) { 10599 if (CXXMethodDecl *Method 10600 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) { 10601 // Skip non-static function templates when converting to pointer, and 10602 // static when converting to member pointer. 10603 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10604 return false; 10605 } 10606 else if (TargetTypeIsNonStaticMemberFunction) 10607 return false; 10608 10609 // C++ [over.over]p2: 10610 // If the name is a function template, template argument deduction is 10611 // done (14.8.2.2), and if the argument deduction succeeds, the 10612 // resulting template argument list is used to generate a single 10613 // function template specialization, which is added to the set of 10614 // overloaded functions considered. 10615 FunctionDecl *Specialization = nullptr; 10616 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 10617 if (Sema::TemplateDeductionResult Result 10618 = S.DeduceTemplateArguments(FunctionTemplate, 10619 &OvlExplicitTemplateArgs, 10620 TargetFunctionType, Specialization, 10621 Info, /*IsAddressOfFunction*/true)) { 10622 // Make a note of the failed deduction for diagnostics. 10623 FailedCandidates.addCandidate() 10624 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(), 10625 MakeDeductionFailureInfo(Context, Result, Info)); 10626 return false; 10627 } 10628 10629 // Template argument deduction ensures that we have an exact match or 10630 // compatible pointer-to-function arguments that would be adjusted by ICS. 10631 // This function template specicalization works. 10632 assert(S.isSameOrCompatibleFunctionType( 10633 Context.getCanonicalType(Specialization->getType()), 10634 Context.getCanonicalType(TargetFunctionType))); 10635 10636 if (!S.checkAddressOfFunctionIsAvailable(Specialization)) 10637 return false; 10638 10639 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization)); 10640 return true; 10641 } 10642 10643 bool AddMatchingNonTemplateFunction(NamedDecl* Fn, 10644 const DeclAccessPair& CurAccessFunPair) { 10645 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 10646 // Skip non-static functions when converting to pointer, and static 10647 // when converting to member pointer. 10648 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction) 10649 return false; 10650 } 10651 else if (TargetTypeIsNonStaticMemberFunction) 10652 return false; 10653 10654 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) { 10655 if (S.getLangOpts().CUDA) 10656 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext)) 10657 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl)) 10658 return false; 10659 10660 // If any candidate has a placeholder return type, trigger its deduction 10661 // now. 10662 if (completeFunctionType(S, FunDecl, SourceExpr->getLocStart(), 10663 Complain)) { 10664 HasComplained |= Complain; 10665 return false; 10666 } 10667 10668 if (!S.checkAddressOfFunctionIsAvailable(FunDecl)) 10669 return false; 10670 10671 // If we're in C, we need to support types that aren't exactly identical. 10672 if (!S.getLangOpts().CPlusPlus || 10673 candidateHasExactlyCorrectType(FunDecl)) { 10674 Matches.push_back(std::make_pair( 10675 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl()))); 10676 FoundNonTemplateFunction = true; 10677 return true; 10678 } 10679 } 10680 10681 return false; 10682 } 10683 10684 bool FindAllFunctionsThatMatchTargetTypeExactly() { 10685 bool Ret = false; 10686 10687 // If the overload expression doesn't have the form of a pointer to 10688 // member, don't try to convert it to a pointer-to-member type. 10689 if (IsInvalidFormOfPointerToMemberFunction()) 10690 return false; 10691 10692 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10693 E = OvlExpr->decls_end(); 10694 I != E; ++I) { 10695 // Look through any using declarations to find the underlying function. 10696 NamedDecl *Fn = (*I)->getUnderlyingDecl(); 10697 10698 // C++ [over.over]p3: 10699 // Non-member functions and static member functions match 10700 // targets of type "pointer-to-function" or "reference-to-function." 10701 // Nonstatic member functions match targets of 10702 // type "pointer-to-member-function." 10703 // Note that according to DR 247, the containing class does not matter. 10704 if (FunctionTemplateDecl *FunctionTemplate 10705 = dyn_cast<FunctionTemplateDecl>(Fn)) { 10706 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair())) 10707 Ret = true; 10708 } 10709 // If we have explicit template arguments supplied, skip non-templates. 10710 else if (!OvlExpr->hasExplicitTemplateArgs() && 10711 AddMatchingNonTemplateFunction(Fn, I.getPair())) 10712 Ret = true; 10713 } 10714 assert(Ret || Matches.empty()); 10715 return Ret; 10716 } 10717 10718 void EliminateAllExceptMostSpecializedTemplate() { 10719 // [...] and any given function template specialization F1 is 10720 // eliminated if the set contains a second function template 10721 // specialization whose function template is more specialized 10722 // than the function template of F1 according to the partial 10723 // ordering rules of 14.5.5.2. 10724 10725 // The algorithm specified above is quadratic. We instead use a 10726 // two-pass algorithm (similar to the one used to identify the 10727 // best viable function in an overload set) that identifies the 10728 // best function template (if it exists). 10729 10730 UnresolvedSet<4> MatchesCopy; // TODO: avoid! 10731 for (unsigned I = 0, E = Matches.size(); I != E; ++I) 10732 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess()); 10733 10734 // TODO: It looks like FailedCandidates does not serve much purpose 10735 // here, since the no_viable diagnostic has index 0. 10736 UnresolvedSetIterator Result = S.getMostSpecialized( 10737 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates, 10738 SourceExpr->getLocStart(), S.PDiag(), 10739 S.PDiag(diag::err_addr_ovl_ambiguous) 10740 << Matches[0].second->getDeclName(), 10741 S.PDiag(diag::note_ovl_candidate) 10742 << (unsigned)oc_function_template, 10743 Complain, TargetFunctionType); 10744 10745 if (Result != MatchesCopy.end()) { 10746 // Make it the first and only element 10747 Matches[0].first = Matches[Result - MatchesCopy.begin()].first; 10748 Matches[0].second = cast<FunctionDecl>(*Result); 10749 Matches.resize(1); 10750 } else 10751 HasComplained |= Complain; 10752 } 10753 10754 void EliminateAllTemplateMatches() { 10755 // [...] any function template specializations in the set are 10756 // eliminated if the set also contains a non-template function, [...] 10757 for (unsigned I = 0, N = Matches.size(); I != N; ) { 10758 if (Matches[I].second->getPrimaryTemplate() == nullptr) 10759 ++I; 10760 else { 10761 Matches[I] = Matches[--N]; 10762 Matches.resize(N); 10763 } 10764 } 10765 } 10766 10767 void EliminateSuboptimalCudaMatches() { 10768 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches); 10769 } 10770 10771 public: 10772 void ComplainNoMatchesFound() const { 10773 assert(Matches.empty()); 10774 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable) 10775 << OvlExpr->getName() << TargetFunctionType 10776 << OvlExpr->getSourceRange(); 10777 if (FailedCandidates.empty()) 10778 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10779 /*TakingAddress=*/true); 10780 else { 10781 // We have some deduction failure messages. Use them to diagnose 10782 // the function templates, and diagnose the non-template candidates 10783 // normally. 10784 for (UnresolvedSetIterator I = OvlExpr->decls_begin(), 10785 IEnd = OvlExpr->decls_end(); 10786 I != IEnd; ++I) 10787 if (FunctionDecl *Fun = 10788 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl())) 10789 if (!functionHasPassObjectSizeParams(Fun)) 10790 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType, 10791 /*TakingAddress=*/true); 10792 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart()); 10793 } 10794 } 10795 10796 bool IsInvalidFormOfPointerToMemberFunction() const { 10797 return TargetTypeIsNonStaticMemberFunction && 10798 !OvlExprInfo.HasFormOfMemberPointer; 10799 } 10800 10801 void ComplainIsInvalidFormOfPointerToMemberFunction() const { 10802 // TODO: Should we condition this on whether any functions might 10803 // have matched, or is it more appropriate to do that in callers? 10804 // TODO: a fixit wouldn't hurt. 10805 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier) 10806 << TargetType << OvlExpr->getSourceRange(); 10807 } 10808 10809 bool IsStaticMemberFunctionFromBoundPointer() const { 10810 return StaticMemberFunctionFromBoundPointer; 10811 } 10812 10813 void ComplainIsStaticMemberFunctionFromBoundPointer() const { 10814 S.Diag(OvlExpr->getLocStart(), 10815 diag::err_invalid_form_pointer_member_function) 10816 << OvlExpr->getSourceRange(); 10817 } 10818 10819 void ComplainOfInvalidConversion() const { 10820 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref) 10821 << OvlExpr->getName() << TargetType; 10822 } 10823 10824 void ComplainMultipleMatchesFound() const { 10825 assert(Matches.size() > 1); 10826 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous) 10827 << OvlExpr->getName() 10828 << OvlExpr->getSourceRange(); 10829 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType, 10830 /*TakingAddress=*/true); 10831 } 10832 10833 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); } 10834 10835 int getNumMatches() const { return Matches.size(); } 10836 10837 FunctionDecl* getMatchingFunctionDecl() const { 10838 if (Matches.size() != 1) return nullptr; 10839 return Matches[0].second; 10840 } 10841 10842 const DeclAccessPair* getMatchingFunctionAccessPair() const { 10843 if (Matches.size() != 1) return nullptr; 10844 return &Matches[0].first; 10845 } 10846 }; 10847 } 10848 10849 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of 10850 /// an overloaded function (C++ [over.over]), where @p From is an 10851 /// expression with overloaded function type and @p ToType is the type 10852 /// we're trying to resolve to. For example: 10853 /// 10854 /// @code 10855 /// int f(double); 10856 /// int f(int); 10857 /// 10858 /// int (*pfd)(double) = f; // selects f(double) 10859 /// @endcode 10860 /// 10861 /// This routine returns the resulting FunctionDecl if it could be 10862 /// resolved, and NULL otherwise. When @p Complain is true, this 10863 /// routine will emit diagnostics if there is an error. 10864 FunctionDecl * 10865 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, 10866 QualType TargetType, 10867 bool Complain, 10868 DeclAccessPair &FoundResult, 10869 bool *pHadMultipleCandidates) { 10870 assert(AddressOfExpr->getType() == Context.OverloadTy); 10871 10872 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, 10873 Complain); 10874 int NumMatches = Resolver.getNumMatches(); 10875 FunctionDecl *Fn = nullptr; 10876 bool ShouldComplain = Complain && !Resolver.hasComplained(); 10877 if (NumMatches == 0 && ShouldComplain) { 10878 if (Resolver.IsInvalidFormOfPointerToMemberFunction()) 10879 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction(); 10880 else 10881 Resolver.ComplainNoMatchesFound(); 10882 } 10883 else if (NumMatches > 1 && ShouldComplain) 10884 Resolver.ComplainMultipleMatchesFound(); 10885 else if (NumMatches == 1) { 10886 Fn = Resolver.getMatchingFunctionDecl(); 10887 assert(Fn); 10888 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 10889 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT); 10890 FoundResult = *Resolver.getMatchingFunctionAccessPair(); 10891 if (Complain) { 10892 if (Resolver.IsStaticMemberFunctionFromBoundPointer()) 10893 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer(); 10894 else 10895 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult); 10896 } 10897 } 10898 10899 if (pHadMultipleCandidates) 10900 *pHadMultipleCandidates = Resolver.hadMultipleCandidates(); 10901 return Fn; 10902 } 10903 10904 /// \brief Given an expression that refers to an overloaded function, try to 10905 /// resolve that function to a single function that can have its address taken. 10906 /// This will modify `Pair` iff it returns non-null. 10907 /// 10908 /// This routine can only realistically succeed if all but one candidates in the 10909 /// overload set for SrcExpr cannot have their addresses taken. 10910 FunctionDecl * 10911 Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E, 10912 DeclAccessPair &Pair) { 10913 OverloadExpr::FindResult R = OverloadExpr::find(E); 10914 OverloadExpr *Ovl = R.Expression; 10915 FunctionDecl *Result = nullptr; 10916 DeclAccessPair DAP; 10917 // Don't use the AddressOfResolver because we're specifically looking for 10918 // cases where we have one overload candidate that lacks 10919 // enable_if/pass_object_size/... 10920 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) { 10921 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl()); 10922 if (!FD) 10923 return nullptr; 10924 10925 if (!checkAddressOfFunctionIsAvailable(FD)) 10926 continue; 10927 10928 // We have more than one result; quit. 10929 if (Result) 10930 return nullptr; 10931 DAP = I.getPair(); 10932 Result = FD; 10933 } 10934 10935 if (Result) 10936 Pair = DAP; 10937 return Result; 10938 } 10939 10940 /// \brief Given an overloaded function, tries to turn it into a non-overloaded 10941 /// function reference using resolveAddressOfOnlyViableOverloadCandidate. This 10942 /// will perform access checks, diagnose the use of the resultant decl, and, if 10943 /// necessary, perform a function-to-pointer decay. 10944 /// 10945 /// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails. 10946 /// Otherwise, returns true. This may emit diagnostics and return true. 10947 bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate( 10948 ExprResult &SrcExpr) { 10949 Expr *E = SrcExpr.get(); 10950 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload"); 10951 10952 DeclAccessPair DAP; 10953 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP); 10954 if (!Found) 10955 return false; 10956 10957 // Emitting multiple diagnostics for a function that is both inaccessible and 10958 // unavailable is consistent with our behavior elsewhere. So, always check 10959 // for both. 10960 DiagnoseUseOfDecl(Found, E->getExprLoc()); 10961 CheckAddressOfMemberAccess(E, DAP); 10962 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found); 10963 if (Fixed->getType()->isFunctionType()) 10964 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false); 10965 else 10966 SrcExpr = Fixed; 10967 return true; 10968 } 10969 10970 /// \brief Given an expression that refers to an overloaded function, try to 10971 /// resolve that overloaded function expression down to a single function. 10972 /// 10973 /// This routine can only resolve template-ids that refer to a single function 10974 /// template, where that template-id refers to a single template whose template 10975 /// arguments are either provided by the template-id or have defaults, 10976 /// as described in C++0x [temp.arg.explicit]p3. 10977 /// 10978 /// If no template-ids are found, no diagnostics are emitted and NULL is 10979 /// returned. 10980 FunctionDecl * 10981 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, 10982 bool Complain, 10983 DeclAccessPair *FoundResult) { 10984 // C++ [over.over]p1: 10985 // [...] [Note: any redundant set of parentheses surrounding the 10986 // overloaded function name is ignored (5.1). ] 10987 // C++ [over.over]p1: 10988 // [...] The overloaded function name can be preceded by the & 10989 // operator. 10990 10991 // If we didn't actually find any template-ids, we're done. 10992 if (!ovl->hasExplicitTemplateArgs()) 10993 return nullptr; 10994 10995 TemplateArgumentListInfo ExplicitTemplateArgs; 10996 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs); 10997 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc()); 10998 10999 // Look through all of the overloaded functions, searching for one 11000 // whose type matches exactly. 11001 FunctionDecl *Matched = nullptr; 11002 for (UnresolvedSetIterator I = ovl->decls_begin(), 11003 E = ovl->decls_end(); I != E; ++I) { 11004 // C++0x [temp.arg.explicit]p3: 11005 // [...] In contexts where deduction is done and fails, or in contexts 11006 // where deduction is not done, if a template argument list is 11007 // specified and it, along with any default template arguments, 11008 // identifies a single function template specialization, then the 11009 // template-id is an lvalue for the function template specialization. 11010 FunctionTemplateDecl *FunctionTemplate 11011 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()); 11012 11013 // C++ [over.over]p2: 11014 // If the name is a function template, template argument deduction is 11015 // done (14.8.2.2), and if the argument deduction succeeds, the 11016 // resulting template argument list is used to generate a single 11017 // function template specialization, which is added to the set of 11018 // overloaded functions considered. 11019 FunctionDecl *Specialization = nullptr; 11020 TemplateDeductionInfo Info(FailedCandidates.getLocation()); 11021 if (TemplateDeductionResult Result 11022 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs, 11023 Specialization, Info, 11024 /*IsAddressOfFunction*/true)) { 11025 // Make a note of the failed deduction for diagnostics. 11026 // TODO: Actually use the failed-deduction info? 11027 FailedCandidates.addCandidate() 11028 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(), 11029 MakeDeductionFailureInfo(Context, Result, Info)); 11030 continue; 11031 } 11032 11033 assert(Specialization && "no specialization and no error?"); 11034 11035 // Multiple matches; we can't resolve to a single declaration. 11036 if (Matched) { 11037 if (Complain) { 11038 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous) 11039 << ovl->getName(); 11040 NoteAllOverloadCandidates(ovl); 11041 } 11042 return nullptr; 11043 } 11044 11045 Matched = Specialization; 11046 if (FoundResult) *FoundResult = I.getPair(); 11047 } 11048 11049 if (Matched && 11050 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain)) 11051 return nullptr; 11052 11053 return Matched; 11054 } 11055 11056 11057 11058 11059 // Resolve and fix an overloaded expression that can be resolved 11060 // because it identifies a single function template specialization. 11061 // 11062 // Last three arguments should only be supplied if Complain = true 11063 // 11064 // Return true if it was logically possible to so resolve the 11065 // expression, regardless of whether or not it succeeded. Always 11066 // returns true if 'complain' is set. 11067 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization( 11068 ExprResult &SrcExpr, bool doFunctionPointerConverion, 11069 bool complain, SourceRange OpRangeForComplaining, 11070 QualType DestTypeForComplaining, 11071 unsigned DiagIDForComplaining) { 11072 assert(SrcExpr.get()->getType() == Context.OverloadTy); 11073 11074 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get()); 11075 11076 DeclAccessPair found; 11077 ExprResult SingleFunctionExpression; 11078 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization( 11079 ovl.Expression, /*complain*/ false, &found)) { 11080 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) { 11081 SrcExpr = ExprError(); 11082 return true; 11083 } 11084 11085 // It is only correct to resolve to an instance method if we're 11086 // resolving a form that's permitted to be a pointer to member. 11087 // Otherwise we'll end up making a bound member expression, which 11088 // is illegal in all the contexts we resolve like this. 11089 if (!ovl.HasFormOfMemberPointer && 11090 isa<CXXMethodDecl>(fn) && 11091 cast<CXXMethodDecl>(fn)->isInstance()) { 11092 if (!complain) return false; 11093 11094 Diag(ovl.Expression->getExprLoc(), 11095 diag::err_bound_member_function) 11096 << 0 << ovl.Expression->getSourceRange(); 11097 11098 // TODO: I believe we only end up here if there's a mix of 11099 // static and non-static candidates (otherwise the expression 11100 // would have 'bound member' type, not 'overload' type). 11101 // Ideally we would note which candidate was chosen and why 11102 // the static candidates were rejected. 11103 SrcExpr = ExprError(); 11104 return true; 11105 } 11106 11107 // Fix the expression to refer to 'fn'. 11108 SingleFunctionExpression = 11109 FixOverloadedFunctionReference(SrcExpr.get(), found, fn); 11110 11111 // If desired, do function-to-pointer decay. 11112 if (doFunctionPointerConverion) { 11113 SingleFunctionExpression = 11114 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get()); 11115 if (SingleFunctionExpression.isInvalid()) { 11116 SrcExpr = ExprError(); 11117 return true; 11118 } 11119 } 11120 } 11121 11122 if (!SingleFunctionExpression.isUsable()) { 11123 if (complain) { 11124 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining) 11125 << ovl.Expression->getName() 11126 << DestTypeForComplaining 11127 << OpRangeForComplaining 11128 << ovl.Expression->getQualifierLoc().getSourceRange(); 11129 NoteAllOverloadCandidates(SrcExpr.get()); 11130 11131 SrcExpr = ExprError(); 11132 return true; 11133 } 11134 11135 return false; 11136 } 11137 11138 SrcExpr = SingleFunctionExpression; 11139 return true; 11140 } 11141 11142 /// \brief Add a single candidate to the overload set. 11143 static void AddOverloadedCallCandidate(Sema &S, 11144 DeclAccessPair FoundDecl, 11145 TemplateArgumentListInfo *ExplicitTemplateArgs, 11146 ArrayRef<Expr *> Args, 11147 OverloadCandidateSet &CandidateSet, 11148 bool PartialOverloading, 11149 bool KnownValid) { 11150 NamedDecl *Callee = FoundDecl.getDecl(); 11151 if (isa<UsingShadowDecl>(Callee)) 11152 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl(); 11153 11154 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) { 11155 if (ExplicitTemplateArgs) { 11156 assert(!KnownValid && "Explicit template arguments?"); 11157 return; 11158 } 11159 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, 11160 /*SuppressUsedConversions=*/false, 11161 PartialOverloading); 11162 return; 11163 } 11164 11165 if (FunctionTemplateDecl *FuncTemplate 11166 = dyn_cast<FunctionTemplateDecl>(Callee)) { 11167 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl, 11168 ExplicitTemplateArgs, Args, CandidateSet, 11169 /*SuppressUsedConversions=*/false, 11170 PartialOverloading); 11171 return; 11172 } 11173 11174 assert(!KnownValid && "unhandled case in overloaded call candidate"); 11175 } 11176 11177 /// \brief Add the overload candidates named by callee and/or found by argument 11178 /// dependent lookup to the given overload set. 11179 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, 11180 ArrayRef<Expr *> Args, 11181 OverloadCandidateSet &CandidateSet, 11182 bool PartialOverloading) { 11183 11184 #ifndef NDEBUG 11185 // Verify that ArgumentDependentLookup is consistent with the rules 11186 // in C++0x [basic.lookup.argdep]p3: 11187 // 11188 // Let X be the lookup set produced by unqualified lookup (3.4.1) 11189 // and let Y be the lookup set produced by argument dependent 11190 // lookup (defined as follows). If X contains 11191 // 11192 // -- a declaration of a class member, or 11193 // 11194 // -- a block-scope function declaration that is not a 11195 // using-declaration, or 11196 // 11197 // -- a declaration that is neither a function or a function 11198 // template 11199 // 11200 // then Y is empty. 11201 11202 if (ULE->requiresADL()) { 11203 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11204 E = ULE->decls_end(); I != E; ++I) { 11205 assert(!(*I)->getDeclContext()->isRecord()); 11206 assert(isa<UsingShadowDecl>(*I) || 11207 !(*I)->getDeclContext()->isFunctionOrMethod()); 11208 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate()); 11209 } 11210 } 11211 #endif 11212 11213 // It would be nice to avoid this copy. 11214 TemplateArgumentListInfo TABuffer; 11215 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11216 if (ULE->hasExplicitTemplateArgs()) { 11217 ULE->copyTemplateArgumentsInto(TABuffer); 11218 ExplicitTemplateArgs = &TABuffer; 11219 } 11220 11221 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(), 11222 E = ULE->decls_end(); I != E; ++I) 11223 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args, 11224 CandidateSet, PartialOverloading, 11225 /*KnownValid*/ true); 11226 11227 if (ULE->requiresADL()) 11228 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(), 11229 Args, ExplicitTemplateArgs, 11230 CandidateSet, PartialOverloading); 11231 } 11232 11233 /// Determine whether a declaration with the specified name could be moved into 11234 /// a different namespace. 11235 static bool canBeDeclaredInNamespace(const DeclarationName &Name) { 11236 switch (Name.getCXXOverloadedOperator()) { 11237 case OO_New: case OO_Array_New: 11238 case OO_Delete: case OO_Array_Delete: 11239 return false; 11240 11241 default: 11242 return true; 11243 } 11244 } 11245 11246 /// Attempt to recover from an ill-formed use of a non-dependent name in a 11247 /// template, where the non-dependent name was declared after the template 11248 /// was defined. This is common in code written for a compilers which do not 11249 /// correctly implement two-stage name lookup. 11250 /// 11251 /// Returns true if a viable candidate was found and a diagnostic was issued. 11252 static bool 11253 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, 11254 const CXXScopeSpec &SS, LookupResult &R, 11255 OverloadCandidateSet::CandidateSetKind CSK, 11256 TemplateArgumentListInfo *ExplicitTemplateArgs, 11257 ArrayRef<Expr *> Args, 11258 bool *DoDiagnoseEmptyLookup = nullptr) { 11259 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty()) 11260 return false; 11261 11262 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) { 11263 if (DC->isTransparentContext()) 11264 continue; 11265 11266 SemaRef.LookupQualifiedName(R, DC); 11267 11268 if (!R.empty()) { 11269 R.suppressDiagnostics(); 11270 11271 if (isa<CXXRecordDecl>(DC)) { 11272 // Don't diagnose names we find in classes; we get much better 11273 // diagnostics for these from DiagnoseEmptyLookup. 11274 R.clear(); 11275 if (DoDiagnoseEmptyLookup) 11276 *DoDiagnoseEmptyLookup = true; 11277 return false; 11278 } 11279 11280 OverloadCandidateSet Candidates(FnLoc, CSK); 11281 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) 11282 AddOverloadedCallCandidate(SemaRef, I.getPair(), 11283 ExplicitTemplateArgs, Args, 11284 Candidates, false, /*KnownValid*/ false); 11285 11286 OverloadCandidateSet::iterator Best; 11287 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) { 11288 // No viable functions. Don't bother the user with notes for functions 11289 // which don't work and shouldn't be found anyway. 11290 R.clear(); 11291 return false; 11292 } 11293 11294 // Find the namespaces where ADL would have looked, and suggest 11295 // declaring the function there instead. 11296 Sema::AssociatedNamespaceSet AssociatedNamespaces; 11297 Sema::AssociatedClassSet AssociatedClasses; 11298 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args, 11299 AssociatedNamespaces, 11300 AssociatedClasses); 11301 Sema::AssociatedNamespaceSet SuggestedNamespaces; 11302 if (canBeDeclaredInNamespace(R.getLookupName())) { 11303 DeclContext *Std = SemaRef.getStdNamespace(); 11304 for (Sema::AssociatedNamespaceSet::iterator 11305 it = AssociatedNamespaces.begin(), 11306 end = AssociatedNamespaces.end(); it != end; ++it) { 11307 // Never suggest declaring a function within namespace 'std'. 11308 if (Std && Std->Encloses(*it)) 11309 continue; 11310 11311 // Never suggest declaring a function within a namespace with a 11312 // reserved name, like __gnu_cxx. 11313 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it); 11314 if (NS && 11315 NS->getQualifiedNameAsString().find("__") != std::string::npos) 11316 continue; 11317 11318 SuggestedNamespaces.insert(*it); 11319 } 11320 } 11321 11322 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup) 11323 << R.getLookupName(); 11324 if (SuggestedNamespaces.empty()) { 11325 SemaRef.Diag(Best->Function->getLocation(), 11326 diag::note_not_found_by_two_phase_lookup) 11327 << R.getLookupName() << 0; 11328 } else if (SuggestedNamespaces.size() == 1) { 11329 SemaRef.Diag(Best->Function->getLocation(), 11330 diag::note_not_found_by_two_phase_lookup) 11331 << R.getLookupName() << 1 << *SuggestedNamespaces.begin(); 11332 } else { 11333 // FIXME: It would be useful to list the associated namespaces here, 11334 // but the diagnostics infrastructure doesn't provide a way to produce 11335 // a localized representation of a list of items. 11336 SemaRef.Diag(Best->Function->getLocation(), 11337 diag::note_not_found_by_two_phase_lookup) 11338 << R.getLookupName() << 2; 11339 } 11340 11341 // Try to recover by calling this function. 11342 return true; 11343 } 11344 11345 R.clear(); 11346 } 11347 11348 return false; 11349 } 11350 11351 /// Attempt to recover from ill-formed use of a non-dependent operator in a 11352 /// template, where the non-dependent operator was declared after the template 11353 /// was defined. 11354 /// 11355 /// Returns true if a viable candidate was found and a diagnostic was issued. 11356 static bool 11357 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, 11358 SourceLocation OpLoc, 11359 ArrayRef<Expr *> Args) { 11360 DeclarationName OpName = 11361 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op); 11362 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName); 11363 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R, 11364 OverloadCandidateSet::CSK_Operator, 11365 /*ExplicitTemplateArgs=*/nullptr, Args); 11366 } 11367 11368 namespace { 11369 class BuildRecoveryCallExprRAII { 11370 Sema &SemaRef; 11371 public: 11372 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) { 11373 assert(SemaRef.IsBuildingRecoveryCallExpr == false); 11374 SemaRef.IsBuildingRecoveryCallExpr = true; 11375 } 11376 11377 ~BuildRecoveryCallExprRAII() { 11378 SemaRef.IsBuildingRecoveryCallExpr = false; 11379 } 11380 }; 11381 11382 } 11383 11384 static std::unique_ptr<CorrectionCandidateCallback> 11385 MakeValidator(Sema &SemaRef, MemberExpr *ME, size_t NumArgs, 11386 bool HasTemplateArgs, bool AllowTypoCorrection) { 11387 if (!AllowTypoCorrection) 11388 return llvm::make_unique<NoTypoCorrectionCCC>(); 11389 return llvm::make_unique<FunctionCallFilterCCC>(SemaRef, NumArgs, 11390 HasTemplateArgs, ME); 11391 } 11392 11393 /// Attempts to recover from a call where no functions were found. 11394 /// 11395 /// Returns true if new candidates were found. 11396 static ExprResult 11397 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11398 UnresolvedLookupExpr *ULE, 11399 SourceLocation LParenLoc, 11400 MutableArrayRef<Expr *> Args, 11401 SourceLocation RParenLoc, 11402 bool EmptyLookup, bool AllowTypoCorrection) { 11403 // Do not try to recover if it is already building a recovery call. 11404 // This stops infinite loops for template instantiations like 11405 // 11406 // template <typename T> auto foo(T t) -> decltype(foo(t)) {} 11407 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {} 11408 // 11409 if (SemaRef.IsBuildingRecoveryCallExpr) 11410 return ExprError(); 11411 BuildRecoveryCallExprRAII RCE(SemaRef); 11412 11413 CXXScopeSpec SS; 11414 SS.Adopt(ULE->getQualifierLoc()); 11415 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc(); 11416 11417 TemplateArgumentListInfo TABuffer; 11418 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr; 11419 if (ULE->hasExplicitTemplateArgs()) { 11420 ULE->copyTemplateArgumentsInto(TABuffer); 11421 ExplicitTemplateArgs = &TABuffer; 11422 } 11423 11424 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(), 11425 Sema::LookupOrdinaryName); 11426 bool DoDiagnoseEmptyLookup = EmptyLookup; 11427 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R, 11428 OverloadCandidateSet::CSK_Normal, 11429 ExplicitTemplateArgs, Args, 11430 &DoDiagnoseEmptyLookup) && 11431 (!DoDiagnoseEmptyLookup || SemaRef.DiagnoseEmptyLookup( 11432 S, SS, R, 11433 MakeValidator(SemaRef, dyn_cast<MemberExpr>(Fn), Args.size(), 11434 ExplicitTemplateArgs != nullptr, AllowTypoCorrection), 11435 ExplicitTemplateArgs, Args))) 11436 return ExprError(); 11437 11438 assert(!R.empty() && "lookup results empty despite recovery"); 11439 11440 // If recovery created an ambiguity, just bail out. 11441 if (R.isAmbiguous()) { 11442 R.suppressDiagnostics(); 11443 return ExprError(); 11444 } 11445 11446 // Build an implicit member call if appropriate. Just drop the 11447 // casts and such from the call, we don't really care. 11448 ExprResult NewFn = ExprError(); 11449 if ((*R.begin())->isCXXClassMember()) 11450 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, 11451 ExplicitTemplateArgs, S); 11452 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid()) 11453 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, 11454 ExplicitTemplateArgs); 11455 else 11456 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false); 11457 11458 if (NewFn.isInvalid()) 11459 return ExprError(); 11460 11461 // This shouldn't cause an infinite loop because we're giving it 11462 // an expression with viable lookup results, which should never 11463 // end up here. 11464 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc, 11465 MultiExprArg(Args.data(), Args.size()), 11466 RParenLoc); 11467 } 11468 11469 /// \brief Constructs and populates an OverloadedCandidateSet from 11470 /// the given function. 11471 /// \returns true when an the ExprResult output parameter has been set. 11472 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn, 11473 UnresolvedLookupExpr *ULE, 11474 MultiExprArg Args, 11475 SourceLocation RParenLoc, 11476 OverloadCandidateSet *CandidateSet, 11477 ExprResult *Result) { 11478 #ifndef NDEBUG 11479 if (ULE->requiresADL()) { 11480 // To do ADL, we must have found an unqualified name. 11481 assert(!ULE->getQualifier() && "qualified name with ADL"); 11482 11483 // We don't perform ADL for implicit declarations of builtins. 11484 // Verify that this was correctly set up. 11485 FunctionDecl *F; 11486 if (ULE->decls_begin() + 1 == ULE->decls_end() && 11487 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) && 11488 F->getBuiltinID() && F->isImplicit()) 11489 llvm_unreachable("performing ADL for builtin"); 11490 11491 // We don't perform ADL in C. 11492 assert(getLangOpts().CPlusPlus && "ADL enabled in C"); 11493 } 11494 #endif 11495 11496 UnbridgedCastsSet UnbridgedCasts; 11497 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) { 11498 *Result = ExprError(); 11499 return true; 11500 } 11501 11502 // Add the functions denoted by the callee to the set of candidate 11503 // functions, including those from argument-dependent lookup. 11504 AddOverloadedCallCandidates(ULE, Args, *CandidateSet); 11505 11506 if (getLangOpts().MSVCCompat && 11507 CurContext->isDependentContext() && !isSFINAEContext() && 11508 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) { 11509 11510 OverloadCandidateSet::iterator Best; 11511 if (CandidateSet->empty() || 11512 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best) == 11513 OR_No_Viable_Function) { 11514 // In Microsoft mode, if we are inside a template class member function then 11515 // create a type dependent CallExpr. The goal is to postpone name lookup 11516 // to instantiation time to be able to search into type dependent base 11517 // classes. 11518 CallExpr *CE = new (Context) CallExpr( 11519 Context, Fn, Args, Context.DependentTy, VK_RValue, RParenLoc); 11520 CE->setTypeDependent(true); 11521 CE->setValueDependent(true); 11522 CE->setInstantiationDependent(true); 11523 *Result = CE; 11524 return true; 11525 } 11526 } 11527 11528 if (CandidateSet->empty()) 11529 return false; 11530 11531 UnbridgedCasts.restore(); 11532 return false; 11533 } 11534 11535 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns 11536 /// the completed call expression. If overload resolution fails, emits 11537 /// diagnostics and returns ExprError() 11538 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, 11539 UnresolvedLookupExpr *ULE, 11540 SourceLocation LParenLoc, 11541 MultiExprArg Args, 11542 SourceLocation RParenLoc, 11543 Expr *ExecConfig, 11544 OverloadCandidateSet *CandidateSet, 11545 OverloadCandidateSet::iterator *Best, 11546 OverloadingResult OverloadResult, 11547 bool AllowTypoCorrection) { 11548 if (CandidateSet->empty()) 11549 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args, 11550 RParenLoc, /*EmptyLookup=*/true, 11551 AllowTypoCorrection); 11552 11553 switch (OverloadResult) { 11554 case OR_Success: { 11555 FunctionDecl *FDecl = (*Best)->Function; 11556 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl); 11557 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc())) 11558 return ExprError(); 11559 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11560 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11561 ExecConfig); 11562 } 11563 11564 case OR_No_Viable_Function: { 11565 // Try to recover by looking for viable functions which the user might 11566 // have meant to call. 11567 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, 11568 Args, RParenLoc, 11569 /*EmptyLookup=*/false, 11570 AllowTypoCorrection); 11571 if (!Recovery.isInvalid()) 11572 return Recovery; 11573 11574 // If the user passes in a function that we can't take the address of, we 11575 // generally end up emitting really bad error messages. Here, we attempt to 11576 // emit better ones. 11577 for (const Expr *Arg : Args) { 11578 if (!Arg->getType()->isFunctionType()) 11579 continue; 11580 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) { 11581 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 11582 if (FD && 11583 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 11584 Arg->getExprLoc())) 11585 return ExprError(); 11586 } 11587 } 11588 11589 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_no_viable_function_in_call) 11590 << ULE->getName() << Fn->getSourceRange(); 11591 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11592 break; 11593 } 11594 11595 case OR_Ambiguous: 11596 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call) 11597 << ULE->getName() << Fn->getSourceRange(); 11598 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args); 11599 break; 11600 11601 case OR_Deleted: { 11602 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call) 11603 << (*Best)->Function->isDeleted() 11604 << ULE->getName() 11605 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function) 11606 << Fn->getSourceRange(); 11607 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args); 11608 11609 // We emitted an error for the unvailable/deleted function call but keep 11610 // the call in the AST. 11611 FunctionDecl *FDecl = (*Best)->Function; 11612 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl); 11613 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc, 11614 ExecConfig); 11615 } 11616 } 11617 11618 // Overload resolution failed. 11619 return ExprError(); 11620 } 11621 11622 static void markUnaddressableCandidatesUnviable(Sema &S, 11623 OverloadCandidateSet &CS) { 11624 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) { 11625 if (I->Viable && 11626 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) { 11627 I->Viable = false; 11628 I->FailureKind = ovl_fail_addr_not_available; 11629 } 11630 } 11631 } 11632 11633 /// BuildOverloadedCallExpr - Given the call expression that calls Fn 11634 /// (which eventually refers to the declaration Func) and the call 11635 /// arguments Args/NumArgs, attempt to resolve the function call down 11636 /// to a specific function. If overload resolution succeeds, returns 11637 /// the call expression produced by overload resolution. 11638 /// Otherwise, emits diagnostics and returns ExprError. 11639 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, 11640 UnresolvedLookupExpr *ULE, 11641 SourceLocation LParenLoc, 11642 MultiExprArg Args, 11643 SourceLocation RParenLoc, 11644 Expr *ExecConfig, 11645 bool AllowTypoCorrection, 11646 bool CalleesAddressIsTaken) { 11647 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), 11648 OverloadCandidateSet::CSK_Normal); 11649 ExprResult result; 11650 11651 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet, 11652 &result)) 11653 return result; 11654 11655 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that 11656 // functions that aren't addressible are considered unviable. 11657 if (CalleesAddressIsTaken) 11658 markUnaddressableCandidatesUnviable(*this, CandidateSet); 11659 11660 OverloadCandidateSet::iterator Best; 11661 OverloadingResult OverloadResult = 11662 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best); 11663 11664 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, 11665 RParenLoc, ExecConfig, &CandidateSet, 11666 &Best, OverloadResult, 11667 AllowTypoCorrection); 11668 } 11669 11670 static bool IsOverloaded(const UnresolvedSetImpl &Functions) { 11671 return Functions.size() > 1 || 11672 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin())); 11673 } 11674 11675 /// \brief Create a unary operation that may resolve to an overloaded 11676 /// operator. 11677 /// 11678 /// \param OpLoc The location of the operator itself (e.g., '*'). 11679 /// 11680 /// \param Opc The UnaryOperatorKind that describes this operator. 11681 /// 11682 /// \param Fns The set of non-member functions that will be 11683 /// considered by overload resolution. The caller needs to build this 11684 /// set based on the context using, e.g., 11685 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11686 /// set should not contain any member functions; those will be added 11687 /// by CreateOverloadedUnaryOp(). 11688 /// 11689 /// \param Input The input argument. 11690 ExprResult 11691 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, 11692 const UnresolvedSetImpl &Fns, 11693 Expr *Input) { 11694 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc); 11695 assert(Op != OO_None && "Invalid opcode for overloaded unary operator"); 11696 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11697 // TODO: provide better source location info. 11698 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11699 11700 if (checkPlaceholderForOverload(*this, Input)) 11701 return ExprError(); 11702 11703 Expr *Args[2] = { Input, nullptr }; 11704 unsigned NumArgs = 1; 11705 11706 // For post-increment and post-decrement, add the implicit '0' as 11707 // the second argument, so that we know this is a post-increment or 11708 // post-decrement. 11709 if (Opc == UO_PostInc || Opc == UO_PostDec) { 11710 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false); 11711 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy, 11712 SourceLocation()); 11713 NumArgs = 2; 11714 } 11715 11716 ArrayRef<Expr *> ArgsArray(Args, NumArgs); 11717 11718 if (Input->isTypeDependent()) { 11719 if (Fns.empty()) 11720 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy, 11721 VK_RValue, OK_Ordinary, OpLoc); 11722 11723 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11724 UnresolvedLookupExpr *Fn 11725 = UnresolvedLookupExpr::Create(Context, NamingClass, 11726 NestedNameSpecifierLoc(), OpNameInfo, 11727 /*ADL*/ true, IsOverloaded(Fns), 11728 Fns.begin(), Fns.end()); 11729 return new (Context) 11730 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy, 11731 VK_RValue, OpLoc, false); 11732 } 11733 11734 // Build an empty overload set. 11735 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11736 11737 // Add the candidates from the given function set. 11738 AddFunctionCandidates(Fns, ArgsArray, CandidateSet); 11739 11740 // Add operator candidates that are member functions. 11741 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11742 11743 // Add candidates from ADL. 11744 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray, 11745 /*ExplicitTemplateArgs*/nullptr, 11746 CandidateSet); 11747 11748 // Add builtin operator candidates. 11749 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet); 11750 11751 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11752 11753 // Perform overload resolution. 11754 OverloadCandidateSet::iterator Best; 11755 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11756 case OR_Success: { 11757 // We found a built-in operator or an overloaded operator. 11758 FunctionDecl *FnDecl = Best->Function; 11759 11760 if (FnDecl) { 11761 // We matched an overloaded operator. Build a call to that 11762 // operator. 11763 11764 // Convert the arguments. 11765 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11766 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl); 11767 11768 ExprResult InputRes = 11769 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr, 11770 Best->FoundDecl, Method); 11771 if (InputRes.isInvalid()) 11772 return ExprError(); 11773 Input = InputRes.get(); 11774 } else { 11775 // Convert the arguments. 11776 ExprResult InputInit 11777 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 11778 Context, 11779 FnDecl->getParamDecl(0)), 11780 SourceLocation(), 11781 Input); 11782 if (InputInit.isInvalid()) 11783 return ExprError(); 11784 Input = InputInit.get(); 11785 } 11786 11787 // Build the actual expression node. 11788 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl, 11789 HadMultipleCandidates, OpLoc); 11790 if (FnExpr.isInvalid()) 11791 return ExprError(); 11792 11793 // Determine the result type. 11794 QualType ResultTy = FnDecl->getReturnType(); 11795 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 11796 ResultTy = ResultTy.getNonLValueExprType(Context); 11797 11798 Args[0] = Input; 11799 CallExpr *TheCall = 11800 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray, 11801 ResultTy, VK, OpLoc, false); 11802 11803 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl)) 11804 return ExprError(); 11805 11806 return MaybeBindToTemporary(TheCall); 11807 } else { 11808 // We matched a built-in operator. Convert the arguments, then 11809 // break out so that we will build the appropriate built-in 11810 // operator node. 11811 ExprResult InputRes = 11812 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0], 11813 Best->Conversions[0], AA_Passing); 11814 if (InputRes.isInvalid()) 11815 return ExprError(); 11816 Input = InputRes.get(); 11817 break; 11818 } 11819 } 11820 11821 case OR_No_Viable_Function: 11822 // This is an erroneous use of an operator which can be overloaded by 11823 // a non-member function. Check for non-member operators which were 11824 // defined too late to be candidates. 11825 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray)) 11826 // FIXME: Recover by calling the found function. 11827 return ExprError(); 11828 11829 // No viable function; fall through to handling this as a 11830 // built-in operator, which will produce an error message for us. 11831 break; 11832 11833 case OR_Ambiguous: 11834 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 11835 << UnaryOperator::getOpcodeStr(Opc) 11836 << Input->getType() 11837 << Input->getSourceRange(); 11838 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray, 11839 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11840 return ExprError(); 11841 11842 case OR_Deleted: 11843 Diag(OpLoc, diag::err_ovl_deleted_oper) 11844 << Best->Function->isDeleted() 11845 << UnaryOperator::getOpcodeStr(Opc) 11846 << getDeletedOrUnavailableSuffix(Best->Function) 11847 << Input->getSourceRange(); 11848 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray, 11849 UnaryOperator::getOpcodeStr(Opc), OpLoc); 11850 return ExprError(); 11851 } 11852 11853 // Either we found no viable overloaded operator or we matched a 11854 // built-in operator. In either case, fall through to trying to 11855 // build a built-in operation. 11856 return CreateBuiltinUnaryOp(OpLoc, Opc, Input); 11857 } 11858 11859 /// \brief Create a binary operation that may resolve to an overloaded 11860 /// operator. 11861 /// 11862 /// \param OpLoc The location of the operator itself (e.g., '+'). 11863 /// 11864 /// \param Opc The BinaryOperatorKind that describes this operator. 11865 /// 11866 /// \param Fns The set of non-member functions that will be 11867 /// considered by overload resolution. The caller needs to build this 11868 /// set based on the context using, e.g., 11869 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This 11870 /// set should not contain any member functions; those will be added 11871 /// by CreateOverloadedBinOp(). 11872 /// 11873 /// \param LHS Left-hand argument. 11874 /// \param RHS Right-hand argument. 11875 ExprResult 11876 Sema::CreateOverloadedBinOp(SourceLocation OpLoc, 11877 BinaryOperatorKind Opc, 11878 const UnresolvedSetImpl &Fns, 11879 Expr *LHS, Expr *RHS) { 11880 Expr *Args[2] = { LHS, RHS }; 11881 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple 11882 11883 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc); 11884 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 11885 11886 // If either side is type-dependent, create an appropriate dependent 11887 // expression. 11888 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 11889 if (Fns.empty()) { 11890 // If there are no functions to store, just build a dependent 11891 // BinaryOperator or CompoundAssignment. 11892 if (Opc <= BO_Assign || Opc > BO_OrAssign) 11893 return new (Context) BinaryOperator( 11894 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary, 11895 OpLoc, FPFeatures.fp_contract); 11896 11897 return new (Context) CompoundAssignOperator( 11898 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary, 11899 Context.DependentTy, Context.DependentTy, OpLoc, 11900 FPFeatures.fp_contract); 11901 } 11902 11903 // FIXME: save results of ADL from here? 11904 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 11905 // TODO: provide better source location info in DNLoc component. 11906 DeclarationNameInfo OpNameInfo(OpName, OpLoc); 11907 UnresolvedLookupExpr *Fn 11908 = UnresolvedLookupExpr::Create(Context, NamingClass, 11909 NestedNameSpecifierLoc(), OpNameInfo, 11910 /*ADL*/ true, IsOverloaded(Fns), 11911 Fns.begin(), Fns.end()); 11912 return new (Context) 11913 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy, 11914 VK_RValue, OpLoc, FPFeatures.fp_contract); 11915 } 11916 11917 // Always do placeholder-like conversions on the RHS. 11918 if (checkPlaceholderForOverload(*this, Args[1])) 11919 return ExprError(); 11920 11921 // Do placeholder-like conversion on the LHS; note that we should 11922 // not get here with a PseudoObject LHS. 11923 assert(Args[0]->getObjectKind() != OK_ObjCProperty); 11924 if (checkPlaceholderForOverload(*this, Args[0])) 11925 return ExprError(); 11926 11927 // If this is the assignment operator, we only perform overload resolution 11928 // if the left-hand side is a class or enumeration type. This is actually 11929 // a hack. The standard requires that we do overload resolution between the 11930 // various built-in candidates, but as DR507 points out, this can lead to 11931 // problems. So we do it this way, which pretty much follows what GCC does. 11932 // Note that we go the traditional code path for compound assignment forms. 11933 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType()) 11934 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11935 11936 // If this is the .* operator, which is not overloadable, just 11937 // create a built-in binary operator. 11938 if (Opc == BO_PtrMemD) 11939 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 11940 11941 // Build an empty overload set. 11942 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator); 11943 11944 // Add the candidates from the given function set. 11945 AddFunctionCandidates(Fns, Args, CandidateSet); 11946 11947 // Add operator candidates that are member functions. 11948 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11949 11950 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not 11951 // performed for an assignment operator (nor for operator[] nor operator->, 11952 // which don't get here). 11953 if (Opc != BO_Assign) 11954 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args, 11955 /*ExplicitTemplateArgs*/ nullptr, 11956 CandidateSet); 11957 11958 // Add builtin operator candidates. 11959 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet); 11960 11961 bool HadMultipleCandidates = (CandidateSet.size() > 1); 11962 11963 // Perform overload resolution. 11964 OverloadCandidateSet::iterator Best; 11965 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 11966 case OR_Success: { 11967 // We found a built-in operator or an overloaded operator. 11968 FunctionDecl *FnDecl = Best->Function; 11969 11970 if (FnDecl) { 11971 // We matched an overloaded operator. Build a call to that 11972 // operator. 11973 11974 // Convert the arguments. 11975 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) { 11976 // Best->Access is only meaningful for class members. 11977 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl); 11978 11979 ExprResult Arg1 = 11980 PerformCopyInitialization( 11981 InitializedEntity::InitializeParameter(Context, 11982 FnDecl->getParamDecl(0)), 11983 SourceLocation(), Args[1]); 11984 if (Arg1.isInvalid()) 11985 return ExprError(); 11986 11987 ExprResult Arg0 = 11988 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 11989 Best->FoundDecl, Method); 11990 if (Arg0.isInvalid()) 11991 return ExprError(); 11992 Args[0] = Arg0.getAs<Expr>(); 11993 Args[1] = RHS = Arg1.getAs<Expr>(); 11994 } else { 11995 // Convert the arguments. 11996 ExprResult Arg0 = PerformCopyInitialization( 11997 InitializedEntity::InitializeParameter(Context, 11998 FnDecl->getParamDecl(0)), 11999 SourceLocation(), Args[0]); 12000 if (Arg0.isInvalid()) 12001 return ExprError(); 12002 12003 ExprResult Arg1 = 12004 PerformCopyInitialization( 12005 InitializedEntity::InitializeParameter(Context, 12006 FnDecl->getParamDecl(1)), 12007 SourceLocation(), Args[1]); 12008 if (Arg1.isInvalid()) 12009 return ExprError(); 12010 Args[0] = LHS = Arg0.getAs<Expr>(); 12011 Args[1] = RHS = Arg1.getAs<Expr>(); 12012 } 12013 12014 // Build the actual expression node. 12015 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12016 Best->FoundDecl, 12017 HadMultipleCandidates, OpLoc); 12018 if (FnExpr.isInvalid()) 12019 return ExprError(); 12020 12021 // Determine the result type. 12022 QualType ResultTy = FnDecl->getReturnType(); 12023 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12024 ResultTy = ResultTy.getNonLValueExprType(Context); 12025 12026 CXXOperatorCallExpr *TheCall = 12027 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), 12028 Args, ResultTy, VK, OpLoc, 12029 FPFeatures.fp_contract); 12030 12031 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, 12032 FnDecl)) 12033 return ExprError(); 12034 12035 ArrayRef<const Expr *> ArgsArray(Args, 2); 12036 // Cut off the implicit 'this'. 12037 if (isa<CXXMethodDecl>(FnDecl)) 12038 ArgsArray = ArgsArray.slice(1); 12039 12040 // Check for a self move. 12041 if (Op == OO_Equal) 12042 DiagnoseSelfMove(Args[0], Args[1], OpLoc); 12043 12044 checkCall(FnDecl, nullptr, ArgsArray, isa<CXXMethodDecl>(FnDecl), OpLoc, 12045 TheCall->getSourceRange(), VariadicDoesNotApply); 12046 12047 return MaybeBindToTemporary(TheCall); 12048 } else { 12049 // We matched a built-in operator. Convert the arguments, then 12050 // break out so that we will build the appropriate built-in 12051 // operator node. 12052 ExprResult ArgsRes0 = 12053 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 12054 Best->Conversions[0], AA_Passing); 12055 if (ArgsRes0.isInvalid()) 12056 return ExprError(); 12057 Args[0] = ArgsRes0.get(); 12058 12059 ExprResult ArgsRes1 = 12060 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 12061 Best->Conversions[1], AA_Passing); 12062 if (ArgsRes1.isInvalid()) 12063 return ExprError(); 12064 Args[1] = ArgsRes1.get(); 12065 break; 12066 } 12067 } 12068 12069 case OR_No_Viable_Function: { 12070 // C++ [over.match.oper]p9: 12071 // If the operator is the operator , [...] and there are no 12072 // viable functions, then the operator is assumed to be the 12073 // built-in operator and interpreted according to clause 5. 12074 if (Opc == BO_Comma) 12075 break; 12076 12077 // For class as left operand for assignment or compound assigment 12078 // operator do not fall through to handling in built-in, but report that 12079 // no overloaded assignment operator found 12080 ExprResult Result = ExprError(); 12081 if (Args[0]->getType()->isRecordType() && 12082 Opc >= BO_Assign && Opc <= BO_OrAssign) { 12083 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12084 << BinaryOperator::getOpcodeStr(Opc) 12085 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12086 if (Args[0]->getType()->isIncompleteType()) { 12087 Diag(OpLoc, diag::note_assign_lhs_incomplete) 12088 << Args[0]->getType() 12089 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12090 } 12091 } else { 12092 // This is an erroneous use of an operator which can be overloaded by 12093 // a non-member function. Check for non-member operators which were 12094 // defined too late to be candidates. 12095 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args)) 12096 // FIXME: Recover by calling the found function. 12097 return ExprError(); 12098 12099 // No viable function; try to create a built-in operation, which will 12100 // produce an error. Then, show the non-viable candidates. 12101 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12102 } 12103 assert(Result.isInvalid() && 12104 "C++ binary operator overloading is missing candidates!"); 12105 if (Result.isInvalid()) 12106 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12107 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12108 return Result; 12109 } 12110 12111 case OR_Ambiguous: 12112 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary) 12113 << BinaryOperator::getOpcodeStr(Opc) 12114 << Args[0]->getType() << Args[1]->getType() 12115 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12116 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12117 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12118 return ExprError(); 12119 12120 case OR_Deleted: 12121 if (isImplicitlyDeleted(Best->Function)) { 12122 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12123 Diag(OpLoc, diag::err_ovl_deleted_special_oper) 12124 << Context.getRecordType(Method->getParent()) 12125 << getSpecialMember(Method); 12126 12127 // The user probably meant to call this special member. Just 12128 // explain why it's deleted. 12129 NoteDeletedFunction(Method); 12130 return ExprError(); 12131 } else { 12132 Diag(OpLoc, diag::err_ovl_deleted_oper) 12133 << Best->Function->isDeleted() 12134 << BinaryOperator::getOpcodeStr(Opc) 12135 << getDeletedOrUnavailableSuffix(Best->Function) 12136 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12137 } 12138 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12139 BinaryOperator::getOpcodeStr(Opc), OpLoc); 12140 return ExprError(); 12141 } 12142 12143 // We matched a built-in operator; build it. 12144 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]); 12145 } 12146 12147 ExprResult 12148 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, 12149 SourceLocation RLoc, 12150 Expr *Base, Expr *Idx) { 12151 Expr *Args[2] = { Base, Idx }; 12152 DeclarationName OpName = 12153 Context.DeclarationNames.getCXXOperatorName(OO_Subscript); 12154 12155 // If either side is type-dependent, create an appropriate dependent 12156 // expression. 12157 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) { 12158 12159 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators 12160 // CHECKME: no 'operator' keyword? 12161 DeclarationNameInfo OpNameInfo(OpName, LLoc); 12162 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12163 UnresolvedLookupExpr *Fn 12164 = UnresolvedLookupExpr::Create(Context, NamingClass, 12165 NestedNameSpecifierLoc(), OpNameInfo, 12166 /*ADL*/ true, /*Overloaded*/ false, 12167 UnresolvedSetIterator(), 12168 UnresolvedSetIterator()); 12169 // Can't add any actual overloads yet 12170 12171 return new (Context) 12172 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args, 12173 Context.DependentTy, VK_RValue, RLoc, false); 12174 } 12175 12176 // Handle placeholders on both operands. 12177 if (checkPlaceholderForOverload(*this, Args[0])) 12178 return ExprError(); 12179 if (checkPlaceholderForOverload(*this, Args[1])) 12180 return ExprError(); 12181 12182 // Build an empty overload set. 12183 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator); 12184 12185 // Subscript can only be overloaded as a member function. 12186 12187 // Add operator candidates that are member functions. 12188 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12189 12190 // Add builtin operator candidates. 12191 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet); 12192 12193 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12194 12195 // Perform overload resolution. 12196 OverloadCandidateSet::iterator Best; 12197 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) { 12198 case OR_Success: { 12199 // We found a built-in operator or an overloaded operator. 12200 FunctionDecl *FnDecl = Best->Function; 12201 12202 if (FnDecl) { 12203 // We matched an overloaded operator. Build a call to that 12204 // operator. 12205 12206 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl); 12207 12208 // Convert the arguments. 12209 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl); 12210 ExprResult Arg0 = 12211 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr, 12212 Best->FoundDecl, Method); 12213 if (Arg0.isInvalid()) 12214 return ExprError(); 12215 Args[0] = Arg0.get(); 12216 12217 // Convert the arguments. 12218 ExprResult InputInit 12219 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12220 Context, 12221 FnDecl->getParamDecl(0)), 12222 SourceLocation(), 12223 Args[1]); 12224 if (InputInit.isInvalid()) 12225 return ExprError(); 12226 12227 Args[1] = InputInit.getAs<Expr>(); 12228 12229 // Build the actual expression node. 12230 DeclarationNameInfo OpLocInfo(OpName, LLoc); 12231 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc)); 12232 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, 12233 Best->FoundDecl, 12234 HadMultipleCandidates, 12235 OpLocInfo.getLoc(), 12236 OpLocInfo.getInfo()); 12237 if (FnExpr.isInvalid()) 12238 return ExprError(); 12239 12240 // Determine the result type 12241 QualType ResultTy = FnDecl->getReturnType(); 12242 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12243 ResultTy = ResultTy.getNonLValueExprType(Context); 12244 12245 CXXOperatorCallExpr *TheCall = 12246 new (Context) CXXOperatorCallExpr(Context, OO_Subscript, 12247 FnExpr.get(), Args, 12248 ResultTy, VK, RLoc, 12249 false); 12250 12251 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl)) 12252 return ExprError(); 12253 12254 return MaybeBindToTemporary(TheCall); 12255 } else { 12256 // We matched a built-in operator. Convert the arguments, then 12257 // break out so that we will build the appropriate built-in 12258 // operator node. 12259 ExprResult ArgsRes0 = 12260 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0], 12261 Best->Conversions[0], AA_Passing); 12262 if (ArgsRes0.isInvalid()) 12263 return ExprError(); 12264 Args[0] = ArgsRes0.get(); 12265 12266 ExprResult ArgsRes1 = 12267 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1], 12268 Best->Conversions[1], AA_Passing); 12269 if (ArgsRes1.isInvalid()) 12270 return ExprError(); 12271 Args[1] = ArgsRes1.get(); 12272 12273 break; 12274 } 12275 } 12276 12277 case OR_No_Viable_Function: { 12278 if (CandidateSet.empty()) 12279 Diag(LLoc, diag::err_ovl_no_oper) 12280 << Args[0]->getType() << /*subscript*/ 0 12281 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12282 else 12283 Diag(LLoc, diag::err_ovl_no_viable_subscript) 12284 << Args[0]->getType() 12285 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12286 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12287 "[]", LLoc); 12288 return ExprError(); 12289 } 12290 12291 case OR_Ambiguous: 12292 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary) 12293 << "[]" 12294 << Args[0]->getType() << Args[1]->getType() 12295 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12296 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 12297 "[]", LLoc); 12298 return ExprError(); 12299 12300 case OR_Deleted: 12301 Diag(LLoc, diag::err_ovl_deleted_oper) 12302 << Best->Function->isDeleted() << "[]" 12303 << getDeletedOrUnavailableSuffix(Best->Function) 12304 << Args[0]->getSourceRange() << Args[1]->getSourceRange(); 12305 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 12306 "[]", LLoc); 12307 return ExprError(); 12308 } 12309 12310 // We matched a built-in operator; build it. 12311 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc); 12312 } 12313 12314 /// BuildCallToMemberFunction - Build a call to a member 12315 /// function. MemExpr is the expression that refers to the member 12316 /// function (and includes the object parameter), Args/NumArgs are the 12317 /// arguments to the function call (not including the object 12318 /// parameter). The caller needs to validate that the member 12319 /// expression refers to a non-static member function or an overloaded 12320 /// member function. 12321 ExprResult 12322 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 12323 SourceLocation LParenLoc, 12324 MultiExprArg Args, 12325 SourceLocation RParenLoc) { 12326 assert(MemExprE->getType() == Context.BoundMemberTy || 12327 MemExprE->getType() == Context.OverloadTy); 12328 12329 // Dig out the member expression. This holds both the object 12330 // argument and the member function we're referring to. 12331 Expr *NakedMemExpr = MemExprE->IgnoreParens(); 12332 12333 // Determine whether this is a call to a pointer-to-member function. 12334 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) { 12335 assert(op->getType() == Context.BoundMemberTy); 12336 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI); 12337 12338 QualType fnType = 12339 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType(); 12340 12341 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>(); 12342 QualType resultType = proto->getCallResultType(Context); 12343 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType()); 12344 12345 // Check that the object type isn't more qualified than the 12346 // member function we're calling. 12347 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals()); 12348 12349 QualType objectType = op->getLHS()->getType(); 12350 if (op->getOpcode() == BO_PtrMemI) 12351 objectType = objectType->castAs<PointerType>()->getPointeeType(); 12352 Qualifiers objectQuals = objectType.getQualifiers(); 12353 12354 Qualifiers difference = objectQuals - funcQuals; 12355 difference.removeObjCGCAttr(); 12356 difference.removeAddressSpace(); 12357 if (difference) { 12358 std::string qualsString = difference.getAsString(); 12359 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals) 12360 << fnType.getUnqualifiedType() 12361 << qualsString 12362 << (qualsString.find(' ') == std::string::npos ? 1 : 2); 12363 } 12364 12365 CXXMemberCallExpr *call 12366 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12367 resultType, valueKind, RParenLoc); 12368 12369 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(), 12370 call, nullptr)) 12371 return ExprError(); 12372 12373 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc)) 12374 return ExprError(); 12375 12376 if (CheckOtherCall(call, proto)) 12377 return ExprError(); 12378 12379 return MaybeBindToTemporary(call); 12380 } 12381 12382 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr)) 12383 return new (Context) 12384 CallExpr(Context, MemExprE, Args, Context.VoidTy, VK_RValue, RParenLoc); 12385 12386 UnbridgedCastsSet UnbridgedCasts; 12387 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12388 return ExprError(); 12389 12390 MemberExpr *MemExpr; 12391 CXXMethodDecl *Method = nullptr; 12392 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public); 12393 NestedNameSpecifier *Qualifier = nullptr; 12394 if (isa<MemberExpr>(NakedMemExpr)) { 12395 MemExpr = cast<MemberExpr>(NakedMemExpr); 12396 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 12397 FoundDecl = MemExpr->getFoundDecl(); 12398 Qualifier = MemExpr->getQualifier(); 12399 UnbridgedCasts.restore(); 12400 } else { 12401 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr); 12402 Qualifier = UnresExpr->getQualifier(); 12403 12404 QualType ObjectType = UnresExpr->getBaseType(); 12405 Expr::Classification ObjectClassification 12406 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue() 12407 : UnresExpr->getBase()->Classify(Context); 12408 12409 // Add overload candidates 12410 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(), 12411 OverloadCandidateSet::CSK_Normal); 12412 12413 // FIXME: avoid copy. 12414 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 12415 if (UnresExpr->hasExplicitTemplateArgs()) { 12416 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 12417 TemplateArgs = &TemplateArgsBuffer; 12418 } 12419 12420 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(), 12421 E = UnresExpr->decls_end(); I != E; ++I) { 12422 12423 NamedDecl *Func = *I; 12424 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext()); 12425 if (isa<UsingShadowDecl>(Func)) 12426 Func = cast<UsingShadowDecl>(Func)->getTargetDecl(); 12427 12428 12429 // Microsoft supports direct constructor calls. 12430 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) { 12431 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), 12432 Args, CandidateSet); 12433 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) { 12434 // If explicit template arguments were provided, we can't call a 12435 // non-template member function. 12436 if (TemplateArgs) 12437 continue; 12438 12439 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType, 12440 ObjectClassification, Args, CandidateSet, 12441 /*SuppressUserConversions=*/false); 12442 } else { 12443 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func), 12444 I.getPair(), ActingDC, TemplateArgs, 12445 ObjectType, ObjectClassification, 12446 Args, CandidateSet, 12447 /*SuppressUsedConversions=*/false); 12448 } 12449 } 12450 12451 DeclarationName DeclName = UnresExpr->getMemberName(); 12452 12453 UnbridgedCasts.restore(); 12454 12455 OverloadCandidateSet::iterator Best; 12456 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(), 12457 Best)) { 12458 case OR_Success: 12459 Method = cast<CXXMethodDecl>(Best->Function); 12460 FoundDecl = Best->FoundDecl; 12461 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl); 12462 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc())) 12463 return ExprError(); 12464 // If FoundDecl is different from Method (such as if one is a template 12465 // and the other a specialization), make sure DiagnoseUseOfDecl is 12466 // called on both. 12467 // FIXME: This would be more comprehensively addressed by modifying 12468 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl 12469 // being used. 12470 if (Method != FoundDecl.getDecl() && 12471 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc())) 12472 return ExprError(); 12473 break; 12474 12475 case OR_No_Viable_Function: 12476 Diag(UnresExpr->getMemberLoc(), 12477 diag::err_ovl_no_viable_member_function_in_call) 12478 << DeclName << MemExprE->getSourceRange(); 12479 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12480 // FIXME: Leaking incoming expressions! 12481 return ExprError(); 12482 12483 case OR_Ambiguous: 12484 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call) 12485 << DeclName << MemExprE->getSourceRange(); 12486 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12487 // FIXME: Leaking incoming expressions! 12488 return ExprError(); 12489 12490 case OR_Deleted: 12491 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call) 12492 << Best->Function->isDeleted() 12493 << DeclName 12494 << getDeletedOrUnavailableSuffix(Best->Function) 12495 << MemExprE->getSourceRange(); 12496 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12497 // FIXME: Leaking incoming expressions! 12498 return ExprError(); 12499 } 12500 12501 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method); 12502 12503 // If overload resolution picked a static member, build a 12504 // non-member call based on that function. 12505 if (Method->isStatic()) { 12506 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, 12507 RParenLoc); 12508 } 12509 12510 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens()); 12511 } 12512 12513 QualType ResultType = Method->getReturnType(); 12514 ExprValueKind VK = Expr::getValueKindForType(ResultType); 12515 ResultType = ResultType.getNonLValueExprType(Context); 12516 12517 assert(Method && "Member call to something that isn't a method?"); 12518 CXXMemberCallExpr *TheCall = 12519 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, 12520 ResultType, VK, RParenLoc); 12521 12522 // Check for a valid return type. 12523 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(), 12524 TheCall, Method)) 12525 return ExprError(); 12526 12527 // Convert the object argument (for a non-static member function call). 12528 // We only need to do this if there was actually an overload; otherwise 12529 // it was done at lookup. 12530 if (!Method->isStatic()) { 12531 ExprResult ObjectArg = 12532 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier, 12533 FoundDecl, Method); 12534 if (ObjectArg.isInvalid()) 12535 return ExprError(); 12536 MemExpr->setBase(ObjectArg.get()); 12537 } 12538 12539 // Convert the rest of the arguments 12540 const FunctionProtoType *Proto = 12541 Method->getType()->getAs<FunctionProtoType>(); 12542 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, 12543 RParenLoc)) 12544 return ExprError(); 12545 12546 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12547 12548 if (CheckFunctionCall(Method, TheCall, Proto)) 12549 return ExprError(); 12550 12551 // In the case the method to call was not selected by the overloading 12552 // resolution process, we still need to handle the enable_if attribute. Do 12553 // that here, so it will not hide previous -- and more relevant -- errors. 12554 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) { 12555 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) { 12556 Diag(MemE->getMemberLoc(), 12557 diag::err_ovl_no_viable_member_function_in_call) 12558 << Method << Method->getSourceRange(); 12559 Diag(Method->getLocation(), 12560 diag::note_ovl_candidate_disabled_by_enable_if_attr) 12561 << Attr->getCond()->getSourceRange() << Attr->getMessage(); 12562 return ExprError(); 12563 } 12564 } 12565 12566 if ((isa<CXXConstructorDecl>(CurContext) || 12567 isa<CXXDestructorDecl>(CurContext)) && 12568 TheCall->getMethodDecl()->isPure()) { 12569 const CXXMethodDecl *MD = TheCall->getMethodDecl(); 12570 12571 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) && 12572 MemExpr->performsVirtualDispatch(getLangOpts())) { 12573 Diag(MemExpr->getLocStart(), 12574 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor) 12575 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext) 12576 << MD->getParent()->getDeclName(); 12577 12578 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName(); 12579 if (getLangOpts().AppleKext) 12580 Diag(MemExpr->getLocStart(), 12581 diag::note_pure_qualified_call_kext) 12582 << MD->getParent()->getDeclName() 12583 << MD->getDeclName(); 12584 } 12585 } 12586 12587 if (CXXDestructorDecl *DD = 12588 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) { 12589 // a->A::f() doesn't go through the vtable, except in AppleKext mode. 12590 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext; 12591 CheckVirtualDtorCall(DD, MemExpr->getLocStart(), /*IsDelete=*/false, 12592 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true, 12593 MemExpr->getMemberLoc()); 12594 } 12595 12596 return MaybeBindToTemporary(TheCall); 12597 } 12598 12599 /// BuildCallToObjectOfClassType - Build a call to an object of class 12600 /// type (C++ [over.call.object]), which can end up invoking an 12601 /// overloaded function call operator (@c operator()) or performing a 12602 /// user-defined conversion on the object argument. 12603 ExprResult 12604 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj, 12605 SourceLocation LParenLoc, 12606 MultiExprArg Args, 12607 SourceLocation RParenLoc) { 12608 if (checkPlaceholderForOverload(*this, Obj)) 12609 return ExprError(); 12610 ExprResult Object = Obj; 12611 12612 UnbridgedCastsSet UnbridgedCasts; 12613 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) 12614 return ExprError(); 12615 12616 assert(Object.get()->getType()->isRecordType() && 12617 "Requires object type argument"); 12618 const RecordType *Record = Object.get()->getType()->getAs<RecordType>(); 12619 12620 // C++ [over.call.object]p1: 12621 // If the primary-expression E in the function call syntax 12622 // evaluates to a class object of type "cv T", then the set of 12623 // candidate functions includes at least the function call 12624 // operators of T. The function call operators of T are obtained by 12625 // ordinary lookup of the name operator() in the context of 12626 // (E).operator(). 12627 OverloadCandidateSet CandidateSet(LParenLoc, 12628 OverloadCandidateSet::CSK_Operator); 12629 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 12630 12631 if (RequireCompleteType(LParenLoc, Object.get()->getType(), 12632 diag::err_incomplete_object_call, Object.get())) 12633 return true; 12634 12635 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName); 12636 LookupQualifiedName(R, Record->getDecl()); 12637 R.suppressDiagnostics(); 12638 12639 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12640 Oper != OperEnd; ++Oper) { 12641 AddMethodCandidate(Oper.getPair(), Object.get()->getType(), 12642 Object.get()->Classify(Context), 12643 Args, CandidateSet, 12644 /*SuppressUserConversions=*/ false); 12645 } 12646 12647 // C++ [over.call.object]p2: 12648 // In addition, for each (non-explicit in C++0x) conversion function 12649 // declared in T of the form 12650 // 12651 // operator conversion-type-id () cv-qualifier; 12652 // 12653 // where cv-qualifier is the same cv-qualification as, or a 12654 // greater cv-qualification than, cv, and where conversion-type-id 12655 // denotes the type "pointer to function of (P1,...,Pn) returning 12656 // R", or the type "reference to pointer to function of 12657 // (P1,...,Pn) returning R", or the type "reference to function 12658 // of (P1,...,Pn) returning R", a surrogate call function [...] 12659 // is also considered as a candidate function. Similarly, 12660 // surrogate call functions are added to the set of candidate 12661 // functions for each conversion function declared in an 12662 // accessible base class provided the function is not hidden 12663 // within T by another intervening declaration. 12664 const auto &Conversions = 12665 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions(); 12666 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) { 12667 NamedDecl *D = *I; 12668 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 12669 if (isa<UsingShadowDecl>(D)) 12670 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 12671 12672 // Skip over templated conversion functions; they aren't 12673 // surrogates. 12674 if (isa<FunctionTemplateDecl>(D)) 12675 continue; 12676 12677 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D); 12678 if (!Conv->isExplicit()) { 12679 // Strip the reference type (if any) and then the pointer type (if 12680 // any) to get down to what might be a function type. 12681 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 12682 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>()) 12683 ConvType = ConvPtrType->getPointeeType(); 12684 12685 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>()) 12686 { 12687 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto, 12688 Object.get(), Args, CandidateSet); 12689 } 12690 } 12691 } 12692 12693 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12694 12695 // Perform overload resolution. 12696 OverloadCandidateSet::iterator Best; 12697 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(), 12698 Best)) { 12699 case OR_Success: 12700 // Overload resolution succeeded; we'll build the appropriate call 12701 // below. 12702 break; 12703 12704 case OR_No_Viable_Function: 12705 if (CandidateSet.empty()) 12706 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper) 12707 << Object.get()->getType() << /*call*/ 1 12708 << Object.get()->getSourceRange(); 12709 else 12710 Diag(Object.get()->getLocStart(), 12711 diag::err_ovl_no_viable_object_call) 12712 << Object.get()->getType() << Object.get()->getSourceRange(); 12713 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12714 break; 12715 12716 case OR_Ambiguous: 12717 Diag(Object.get()->getLocStart(), 12718 diag::err_ovl_ambiguous_object_call) 12719 << Object.get()->getType() << Object.get()->getSourceRange(); 12720 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 12721 break; 12722 12723 case OR_Deleted: 12724 Diag(Object.get()->getLocStart(), 12725 diag::err_ovl_deleted_object_call) 12726 << Best->Function->isDeleted() 12727 << Object.get()->getType() 12728 << getDeletedOrUnavailableSuffix(Best->Function) 12729 << Object.get()->getSourceRange(); 12730 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 12731 break; 12732 } 12733 12734 if (Best == CandidateSet.end()) 12735 return true; 12736 12737 UnbridgedCasts.restore(); 12738 12739 if (Best->Function == nullptr) { 12740 // Since there is no function declaration, this is one of the 12741 // surrogate candidates. Dig out the conversion function. 12742 CXXConversionDecl *Conv 12743 = cast<CXXConversionDecl>( 12744 Best->Conversions[0].UserDefined.ConversionFunction); 12745 12746 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, 12747 Best->FoundDecl); 12748 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc)) 12749 return ExprError(); 12750 assert(Conv == Best->FoundDecl.getDecl() && 12751 "Found Decl & conversion-to-functionptr should be same, right?!"); 12752 // We selected one of the surrogate functions that converts the 12753 // object parameter to a function pointer. Perform the conversion 12754 // on the object argument, then let ActOnCallExpr finish the job. 12755 12756 // Create an implicit member expr to refer to the conversion operator. 12757 // and then call it. 12758 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, 12759 Conv, HadMultipleCandidates); 12760 if (Call.isInvalid()) 12761 return ExprError(); 12762 // Record usage of conversion in an implicit cast. 12763 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(), 12764 CK_UserDefinedConversion, Call.get(), 12765 nullptr, VK_RValue); 12766 12767 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc); 12768 } 12769 12770 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl); 12771 12772 // We found an overloaded operator(). Build a CXXOperatorCallExpr 12773 // that calls this method, using Object for the implicit object 12774 // parameter and passing along the remaining arguments. 12775 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12776 12777 // An error diagnostic has already been printed when parsing the declaration. 12778 if (Method->isInvalidDecl()) 12779 return ExprError(); 12780 12781 const FunctionProtoType *Proto = 12782 Method->getType()->getAs<FunctionProtoType>(); 12783 12784 unsigned NumParams = Proto->getNumParams(); 12785 12786 DeclarationNameInfo OpLocInfo( 12787 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc); 12788 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc)); 12789 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12790 HadMultipleCandidates, 12791 OpLocInfo.getLoc(), 12792 OpLocInfo.getInfo()); 12793 if (NewFn.isInvalid()) 12794 return true; 12795 12796 // Build the full argument list for the method call (the implicit object 12797 // parameter is placed at the beginning of the list). 12798 SmallVector<Expr *, 8> MethodArgs(Args.size() + 1); 12799 MethodArgs[0] = Object.get(); 12800 std::copy(Args.begin(), Args.end(), MethodArgs.begin() + 1); 12801 12802 // Once we've built TheCall, all of the expressions are properly 12803 // owned. 12804 QualType ResultTy = Method->getReturnType(); 12805 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12806 ResultTy = ResultTy.getNonLValueExprType(Context); 12807 12808 CXXOperatorCallExpr *TheCall = new (Context) 12809 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, 12810 VK, RParenLoc, false); 12811 12812 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method)) 12813 return true; 12814 12815 // We may have default arguments. If so, we need to allocate more 12816 // slots in the call for them. 12817 if (Args.size() < NumParams) 12818 TheCall->setNumArgs(Context, NumParams + 1); 12819 12820 bool IsError = false; 12821 12822 // Initialize the implicit object parameter. 12823 ExprResult ObjRes = 12824 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr, 12825 Best->FoundDecl, Method); 12826 if (ObjRes.isInvalid()) 12827 IsError = true; 12828 else 12829 Object = ObjRes; 12830 TheCall->setArg(0, Object.get()); 12831 12832 // Check the argument types. 12833 for (unsigned i = 0; i != NumParams; i++) { 12834 Expr *Arg; 12835 if (i < Args.size()) { 12836 Arg = Args[i]; 12837 12838 // Pass the argument. 12839 12840 ExprResult InputInit 12841 = PerformCopyInitialization(InitializedEntity::InitializeParameter( 12842 Context, 12843 Method->getParamDecl(i)), 12844 SourceLocation(), Arg); 12845 12846 IsError |= InputInit.isInvalid(); 12847 Arg = InputInit.getAs<Expr>(); 12848 } else { 12849 ExprResult DefArg 12850 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i)); 12851 if (DefArg.isInvalid()) { 12852 IsError = true; 12853 break; 12854 } 12855 12856 Arg = DefArg.getAs<Expr>(); 12857 } 12858 12859 TheCall->setArg(i + 1, Arg); 12860 } 12861 12862 // If this is a variadic call, handle args passed through "...". 12863 if (Proto->isVariadic()) { 12864 // Promote the arguments (C99 6.5.2.2p7). 12865 for (unsigned i = NumParams, e = Args.size(); i < e; i++) { 12866 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 12867 nullptr); 12868 IsError |= Arg.isInvalid(); 12869 TheCall->setArg(i + 1, Arg.get()); 12870 } 12871 } 12872 12873 if (IsError) return true; 12874 12875 DiagnoseSentinelCalls(Method, LParenLoc, Args); 12876 12877 if (CheckFunctionCall(Method, TheCall, Proto)) 12878 return true; 12879 12880 return MaybeBindToTemporary(TheCall); 12881 } 12882 12883 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 12884 /// (if one exists), where @c Base is an expression of class type and 12885 /// @c Member is the name of the member we're trying to find. 12886 ExprResult 12887 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, 12888 bool *NoArrowOperatorFound) { 12889 assert(Base->getType()->isRecordType() && 12890 "left-hand side must have class type"); 12891 12892 if (checkPlaceholderForOverload(*this, Base)) 12893 return ExprError(); 12894 12895 SourceLocation Loc = Base->getExprLoc(); 12896 12897 // C++ [over.ref]p1: 12898 // 12899 // [...] An expression x->m is interpreted as (x.operator->())->m 12900 // for a class object x of type T if T::operator->() exists and if 12901 // the operator is selected as the best match function by the 12902 // overload resolution mechanism (13.3). 12903 DeclarationName OpName = 12904 Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 12905 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator); 12906 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>(); 12907 12908 if (RequireCompleteType(Loc, Base->getType(), 12909 diag::err_typecheck_incomplete_tag, Base)) 12910 return ExprError(); 12911 12912 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName); 12913 LookupQualifiedName(R, BaseRecord->getDecl()); 12914 R.suppressDiagnostics(); 12915 12916 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end(); 12917 Oper != OperEnd; ++Oper) { 12918 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context), 12919 None, CandidateSet, /*SuppressUserConversions=*/false); 12920 } 12921 12922 bool HadMultipleCandidates = (CandidateSet.size() > 1); 12923 12924 // Perform overload resolution. 12925 OverloadCandidateSet::iterator Best; 12926 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) { 12927 case OR_Success: 12928 // Overload resolution succeeded; we'll build the call below. 12929 break; 12930 12931 case OR_No_Viable_Function: 12932 if (CandidateSet.empty()) { 12933 QualType BaseType = Base->getType(); 12934 if (NoArrowOperatorFound) { 12935 // Report this specific error to the caller instead of emitting a 12936 // diagnostic, as requested. 12937 *NoArrowOperatorFound = true; 12938 return ExprError(); 12939 } 12940 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 12941 << BaseType << Base->getSourceRange(); 12942 if (BaseType->isRecordType() && !BaseType->isPointerType()) { 12943 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion) 12944 << FixItHint::CreateReplacement(OpLoc, "."); 12945 } 12946 } else 12947 Diag(OpLoc, diag::err_ovl_no_viable_oper) 12948 << "operator->" << Base->getSourceRange(); 12949 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12950 return ExprError(); 12951 12952 case OR_Ambiguous: 12953 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary) 12954 << "->" << Base->getType() << Base->getSourceRange(); 12955 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base); 12956 return ExprError(); 12957 12958 case OR_Deleted: 12959 Diag(OpLoc, diag::err_ovl_deleted_oper) 12960 << Best->Function->isDeleted() 12961 << "->" 12962 << getDeletedOrUnavailableSuffix(Best->Function) 12963 << Base->getSourceRange(); 12964 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base); 12965 return ExprError(); 12966 } 12967 12968 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl); 12969 12970 // Convert the object parameter. 12971 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 12972 ExprResult BaseResult = 12973 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr, 12974 Best->FoundDecl, Method); 12975 if (BaseResult.isInvalid()) 12976 return ExprError(); 12977 Base = BaseResult.get(); 12978 12979 // Build the operator call. 12980 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl, 12981 HadMultipleCandidates, OpLoc); 12982 if (FnExpr.isInvalid()) 12983 return ExprError(); 12984 12985 QualType ResultTy = Method->getReturnType(); 12986 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 12987 ResultTy = ResultTy.getNonLValueExprType(Context); 12988 CXXOperatorCallExpr *TheCall = 12989 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(), 12990 Base, ResultTy, VK, OpLoc, false); 12991 12992 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method)) 12993 return ExprError(); 12994 12995 return MaybeBindToTemporary(TheCall); 12996 } 12997 12998 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to 12999 /// a literal operator described by the provided lookup results. 13000 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R, 13001 DeclarationNameInfo &SuffixInfo, 13002 ArrayRef<Expr*> Args, 13003 SourceLocation LitEndLoc, 13004 TemplateArgumentListInfo *TemplateArgs) { 13005 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc(); 13006 13007 OverloadCandidateSet CandidateSet(UDSuffixLoc, 13008 OverloadCandidateSet::CSK_Normal); 13009 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs, 13010 /*SuppressUserConversions=*/true); 13011 13012 bool HadMultipleCandidates = (CandidateSet.size() > 1); 13013 13014 // Perform overload resolution. This will usually be trivial, but might need 13015 // to perform substitutions for a literal operator template. 13016 OverloadCandidateSet::iterator Best; 13017 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) { 13018 case OR_Success: 13019 case OR_Deleted: 13020 break; 13021 13022 case OR_No_Viable_Function: 13023 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call) 13024 << R.getLookupName(); 13025 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args); 13026 return ExprError(); 13027 13028 case OR_Ambiguous: 13029 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); 13030 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args); 13031 return ExprError(); 13032 } 13033 13034 FunctionDecl *FD = Best->Function; 13035 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl, 13036 HadMultipleCandidates, 13037 SuffixInfo.getLoc(), 13038 SuffixInfo.getInfo()); 13039 if (Fn.isInvalid()) 13040 return true; 13041 13042 // Check the argument types. This should almost always be a no-op, except 13043 // that array-to-pointer decay is applied to string literals. 13044 Expr *ConvArgs[2]; 13045 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) { 13046 ExprResult InputInit = PerformCopyInitialization( 13047 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)), 13048 SourceLocation(), Args[ArgIdx]); 13049 if (InputInit.isInvalid()) 13050 return true; 13051 ConvArgs[ArgIdx] = InputInit.get(); 13052 } 13053 13054 QualType ResultTy = FD->getReturnType(); 13055 ExprValueKind VK = Expr::getValueKindForType(ResultTy); 13056 ResultTy = ResultTy.getNonLValueExprType(Context); 13057 13058 UserDefinedLiteral *UDL = 13059 new (Context) UserDefinedLiteral(Context, Fn.get(), 13060 llvm::makeArrayRef(ConvArgs, Args.size()), 13061 ResultTy, VK, LitEndLoc, UDSuffixLoc); 13062 13063 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD)) 13064 return ExprError(); 13065 13066 if (CheckFunctionCall(FD, UDL, nullptr)) 13067 return ExprError(); 13068 13069 return MaybeBindToTemporary(UDL); 13070 } 13071 13072 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the 13073 /// given LookupResult is non-empty, it is assumed to describe a member which 13074 /// will be invoked. Otherwise, the function will be found via argument 13075 /// dependent lookup. 13076 /// CallExpr is set to a valid expression and FRS_Success returned on success, 13077 /// otherwise CallExpr is set to ExprError() and some non-success value 13078 /// is returned. 13079 Sema::ForRangeStatus 13080 Sema::BuildForRangeBeginEndCall(SourceLocation Loc, 13081 SourceLocation RangeLoc, 13082 const DeclarationNameInfo &NameInfo, 13083 LookupResult &MemberLookup, 13084 OverloadCandidateSet *CandidateSet, 13085 Expr *Range, ExprResult *CallExpr) { 13086 Scope *S = nullptr; 13087 13088 CandidateSet->clear(); 13089 if (!MemberLookup.empty()) { 13090 ExprResult MemberRef = 13091 BuildMemberReferenceExpr(Range, Range->getType(), Loc, 13092 /*IsPtr=*/false, CXXScopeSpec(), 13093 /*TemplateKWLoc=*/SourceLocation(), 13094 /*FirstQualifierInScope=*/nullptr, 13095 MemberLookup, 13096 /*TemplateArgs=*/nullptr, S); 13097 if (MemberRef.isInvalid()) { 13098 *CallExpr = ExprError(); 13099 return FRS_DiagnosticIssued; 13100 } 13101 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr); 13102 if (CallExpr->isInvalid()) { 13103 *CallExpr = ExprError(); 13104 return FRS_DiagnosticIssued; 13105 } 13106 } else { 13107 UnresolvedSet<0> FoundNames; 13108 UnresolvedLookupExpr *Fn = 13109 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr, 13110 NestedNameSpecifierLoc(), NameInfo, 13111 /*NeedsADL=*/true, /*Overloaded=*/false, 13112 FoundNames.begin(), FoundNames.end()); 13113 13114 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc, 13115 CandidateSet, CallExpr); 13116 if (CandidateSet->empty() || CandidateSetError) { 13117 *CallExpr = ExprError(); 13118 return FRS_NoViableFunction; 13119 } 13120 OverloadCandidateSet::iterator Best; 13121 OverloadingResult OverloadResult = 13122 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best); 13123 13124 if (OverloadResult == OR_No_Viable_Function) { 13125 *CallExpr = ExprError(); 13126 return FRS_NoViableFunction; 13127 } 13128 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range, 13129 Loc, nullptr, CandidateSet, &Best, 13130 OverloadResult, 13131 /*AllowTypoCorrection=*/false); 13132 if (CallExpr->isInvalid() || OverloadResult != OR_Success) { 13133 *CallExpr = ExprError(); 13134 return FRS_DiagnosticIssued; 13135 } 13136 } 13137 return FRS_Success; 13138 } 13139 13140 13141 /// FixOverloadedFunctionReference - E is an expression that refers to 13142 /// a C++ overloaded function (possibly with some parentheses and 13143 /// perhaps a '&' around it). We have resolved the overloaded function 13144 /// to the function declaration Fn, so patch up the expression E to 13145 /// refer (possibly indirectly) to Fn. Returns the new expr. 13146 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found, 13147 FunctionDecl *Fn) { 13148 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 13149 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(), 13150 Found, Fn); 13151 if (SubExpr == PE->getSubExpr()) 13152 return PE; 13153 13154 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr); 13155 } 13156 13157 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 13158 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), 13159 Found, Fn); 13160 assert(Context.hasSameType(ICE->getSubExpr()->getType(), 13161 SubExpr->getType()) && 13162 "Implicit cast type cannot be determined from overload"); 13163 assert(ICE->path_empty() && "fixing up hierarchy conversion?"); 13164 if (SubExpr == ICE->getSubExpr()) 13165 return ICE; 13166 13167 return ImplicitCastExpr::Create(Context, ICE->getType(), 13168 ICE->getCastKind(), 13169 SubExpr, nullptr, 13170 ICE->getValueKind()); 13171 } 13172 13173 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) { 13174 if (!GSE->isResultDependent()) { 13175 Expr *SubExpr = 13176 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn); 13177 if (SubExpr == GSE->getResultExpr()) 13178 return GSE; 13179 13180 // Replace the resulting type information before rebuilding the generic 13181 // selection expression. 13182 ArrayRef<Expr *> A = GSE->getAssocExprs(); 13183 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end()); 13184 unsigned ResultIdx = GSE->getResultIndex(); 13185 AssocExprs[ResultIdx] = SubExpr; 13186 13187 return new (Context) GenericSelectionExpr( 13188 Context, GSE->getGenericLoc(), GSE->getControllingExpr(), 13189 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(), 13190 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(), 13191 ResultIdx); 13192 } 13193 // Rather than fall through to the unreachable, return the original generic 13194 // selection expression. 13195 return GSE; 13196 } 13197 13198 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 13199 assert(UnOp->getOpcode() == UO_AddrOf && 13200 "Can only take the address of an overloaded function"); 13201 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) { 13202 if (Method->isStatic()) { 13203 // Do nothing: static member functions aren't any different 13204 // from non-member functions. 13205 } else { 13206 // Fix the subexpression, which really has to be an 13207 // UnresolvedLookupExpr holding an overloaded member function 13208 // or template. 13209 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13210 Found, Fn); 13211 if (SubExpr == UnOp->getSubExpr()) 13212 return UnOp; 13213 13214 assert(isa<DeclRefExpr>(SubExpr) 13215 && "fixed to something other than a decl ref"); 13216 assert(cast<DeclRefExpr>(SubExpr)->getQualifier() 13217 && "fixed to a member ref with no nested name qualifier"); 13218 13219 // We have taken the address of a pointer to member 13220 // function. Perform the computation here so that we get the 13221 // appropriate pointer to member type. 13222 QualType ClassType 13223 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext())); 13224 QualType MemPtrType 13225 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr()); 13226 // Under the MS ABI, lock down the inheritance model now. 13227 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) 13228 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType); 13229 13230 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType, 13231 VK_RValue, OK_Ordinary, 13232 UnOp->getOperatorLoc()); 13233 } 13234 } 13235 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), 13236 Found, Fn); 13237 if (SubExpr == UnOp->getSubExpr()) 13238 return UnOp; 13239 13240 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, 13241 Context.getPointerType(SubExpr->getType()), 13242 VK_RValue, OK_Ordinary, 13243 UnOp->getOperatorLoc()); 13244 } 13245 13246 // C++ [except.spec]p17: 13247 // An exception-specification is considered to be needed when: 13248 // - in an expression the function is the unique lookup result or the 13249 // selected member of a set of overloaded functions 13250 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>()) 13251 ResolveExceptionSpec(E->getExprLoc(), FPT); 13252 13253 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 13254 // FIXME: avoid copy. 13255 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13256 if (ULE->hasExplicitTemplateArgs()) { 13257 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer); 13258 TemplateArgs = &TemplateArgsBuffer; 13259 } 13260 13261 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13262 ULE->getQualifierLoc(), 13263 ULE->getTemplateKeywordLoc(), 13264 Fn, 13265 /*enclosing*/ false, // FIXME? 13266 ULE->getNameLoc(), 13267 Fn->getType(), 13268 VK_LValue, 13269 Found.getDecl(), 13270 TemplateArgs); 13271 MarkDeclRefReferenced(DRE); 13272 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1); 13273 return DRE; 13274 } 13275 13276 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) { 13277 // FIXME: avoid copy. 13278 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr; 13279 if (MemExpr->hasExplicitTemplateArgs()) { 13280 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer); 13281 TemplateArgs = &TemplateArgsBuffer; 13282 } 13283 13284 Expr *Base; 13285 13286 // If we're filling in a static method where we used to have an 13287 // implicit member access, rewrite to a simple decl ref. 13288 if (MemExpr->isImplicitAccess()) { 13289 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13290 DeclRefExpr *DRE = DeclRefExpr::Create(Context, 13291 MemExpr->getQualifierLoc(), 13292 MemExpr->getTemplateKeywordLoc(), 13293 Fn, 13294 /*enclosing*/ false, 13295 MemExpr->getMemberLoc(), 13296 Fn->getType(), 13297 VK_LValue, 13298 Found.getDecl(), 13299 TemplateArgs); 13300 MarkDeclRefReferenced(DRE); 13301 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1); 13302 return DRE; 13303 } else { 13304 SourceLocation Loc = MemExpr->getMemberLoc(); 13305 if (MemExpr->getQualifier()) 13306 Loc = MemExpr->getQualifierLoc().getBeginLoc(); 13307 CheckCXXThisCapture(Loc); 13308 Base = new (Context) CXXThisExpr(Loc, 13309 MemExpr->getBaseType(), 13310 /*isImplicit=*/true); 13311 } 13312 } else 13313 Base = MemExpr->getBase(); 13314 13315 ExprValueKind valueKind; 13316 QualType type; 13317 if (cast<CXXMethodDecl>(Fn)->isStatic()) { 13318 valueKind = VK_LValue; 13319 type = Fn->getType(); 13320 } else { 13321 valueKind = VK_RValue; 13322 type = Context.BoundMemberTy; 13323 } 13324 13325 MemberExpr *ME = MemberExpr::Create( 13326 Context, Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(), 13327 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found, 13328 MemExpr->getMemberNameInfo(), TemplateArgs, type, valueKind, 13329 OK_Ordinary); 13330 ME->setHadMultipleCandidates(true); 13331 MarkMemberReferenced(ME); 13332 return ME; 13333 } 13334 13335 llvm_unreachable("Invalid reference to overloaded function"); 13336 } 13337 13338 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E, 13339 DeclAccessPair Found, 13340 FunctionDecl *Fn) { 13341 return FixOverloadedFunctionReference(E.get(), Found, Fn); 13342 } 13343