1 //===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===// 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/SemaInternal.h" 15 #include "clang/Sema/Lookup.h" 16 #include "clang/Sema/Initialization.h" 17 #include "clang/Sema/Template.h" 18 #include "clang/Sema/TemplateDeduction.h" 19 #include "clang/Basic/Diagnostic.h" 20 #include "clang/Lex/Preprocessor.h" 21 #include "clang/AST/ASTContext.h" 22 #include "clang/AST/CXXInheritance.h" 23 #include "clang/AST/DeclObjC.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/ExprObjC.h" 27 #include "clang/AST/TypeOrdering.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "llvm/ADT/DenseSet.h" 30 #include "llvm/ADT/SmallPtrSet.h" 31 #include "llvm/ADT/STLExtras.h" 32 #include <algorithm> 33 34 namespace clang { 35 using namespace sema; 36 37 /// A convenience routine for creating a decayed reference to a 38 /// function. 39 static ExprResult 40 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates, 41 SourceLocation Loc = SourceLocation(), 42 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){ 43 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(), 44 VK_LValue, Loc, LocInfo); 45 if (HadMultipleCandidates) 46 DRE->setHadMultipleCandidates(true); 47 ExprResult E = S.Owned(DRE); 48 E = S.DefaultFunctionArrayConversion(E.take()); 49 if (E.isInvalid()) 50 return ExprError(); 51 return move(E); 52 } 53 54 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 55 bool InOverloadResolution, 56 StandardConversionSequence &SCS, 57 bool CStyle, 58 bool AllowObjCWritebackConversion); 59 60 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From, 61 QualType &ToType, 62 bool InOverloadResolution, 63 StandardConversionSequence &SCS, 64 bool CStyle); 65 static OverloadingResult 66 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 67 UserDefinedConversionSequence& User, 68 OverloadCandidateSet& Conversions, 69 bool AllowExplicit); 70 71 72 static ImplicitConversionSequence::CompareKind 73 CompareStandardConversionSequences(Sema &S, 74 const StandardConversionSequence& SCS1, 75 const StandardConversionSequence& SCS2); 76 77 static ImplicitConversionSequence::CompareKind 78 CompareQualificationConversions(Sema &S, 79 const StandardConversionSequence& SCS1, 80 const StandardConversionSequence& SCS2); 81 82 static ImplicitConversionSequence::CompareKind 83 CompareDerivedToBaseConversions(Sema &S, 84 const StandardConversionSequence& SCS1, 85 const StandardConversionSequence& SCS2); 86 87 88 89 /// GetConversionCategory - Retrieve the implicit conversion 90 /// category corresponding to the given implicit conversion kind. 91 ImplicitConversionCategory 92 GetConversionCategory(ImplicitConversionKind Kind) { 93 static const ImplicitConversionCategory 94 Category[(int)ICK_Num_Conversion_Kinds] = { 95 ICC_Identity, 96 ICC_Lvalue_Transformation, 97 ICC_Lvalue_Transformation, 98 ICC_Lvalue_Transformation, 99 ICC_Identity, 100 ICC_Qualification_Adjustment, 101 ICC_Promotion, 102 ICC_Promotion, 103 ICC_Promotion, 104 ICC_Conversion, 105 ICC_Conversion, 106 ICC_Conversion, 107 ICC_Conversion, 108 ICC_Conversion, 109 ICC_Conversion, 110 ICC_Conversion, 111 ICC_Conversion, 112 ICC_Conversion, 113 ICC_Conversion, 114 ICC_Conversion, 115 ICC_Conversion, 116 ICC_Conversion 117 }; 118 return Category[(int)Kind]; 119 } 120 121 /// GetConversionRank - Retrieve the implicit conversion rank 122 /// corresponding to the given implicit conversion kind. 123 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 124 static const ImplicitConversionRank 125 Rank[(int)ICK_Num_Conversion_Kinds] = { 126 ICR_Exact_Match, 127 ICR_Exact_Match, 128 ICR_Exact_Match, 129 ICR_Exact_Match, 130 ICR_Exact_Match, 131 ICR_Exact_Match, 132 ICR_Promotion, 133 ICR_Promotion, 134 ICR_Promotion, 135 ICR_Conversion, 136 ICR_Conversion, 137 ICR_Conversion, 138 ICR_Conversion, 139 ICR_Conversion, 140 ICR_Conversion, 141 ICR_Conversion, 142 ICR_Conversion, 143 ICR_Conversion, 144 ICR_Conversion, 145 ICR_Conversion, 146 ICR_Complex_Real_Conversion, 147 ICR_Conversion, 148 ICR_Conversion, 149 ICR_Writeback_Conversion 150 }; 151 return Rank[(int)Kind]; 152 } 153 154 /// GetImplicitConversionName - Return the name of this kind of 155 /// implicit conversion. 156 const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 157 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = { 158 "No conversion", 159 "Lvalue-to-rvalue", 160 "Array-to-pointer", 161 "Function-to-pointer", 162 "Noreturn adjustment", 163 "Qualification", 164 "Integral promotion", 165 "Floating point promotion", 166 "Complex promotion", 167 "Integral conversion", 168 "Floating conversion", 169 "Complex conversion", 170 "Floating-integral conversion", 171 "Pointer conversion", 172 "Pointer-to-member conversion", 173 "Boolean conversion", 174 "Compatible-types conversion", 175 "Derived-to-base conversion", 176 "Vector conversion", 177 "Vector splat", 178 "Complex-real conversion", 179 "Block Pointer conversion", 180 "Transparent Union Conversion" 181 "Writeback conversion" 182 }; 183 return Name[Kind]; 184 } 185 186 /// StandardConversionSequence - Set the standard conversion 187 /// sequence to the identity conversion. 188 void StandardConversionSequence::setAsIdentityConversion() { 189 First = ICK_Identity; 190 Second = ICK_Identity; 191 Third = ICK_Identity; 192 DeprecatedStringLiteralToCharPtr = false; 193 QualificationIncludesObjCLifetime = false; 194 ReferenceBinding = false; 195 DirectBinding = false; 196 IsLvalueReference = true; 197 BindsToFunctionLvalue = false; 198 BindsToRvalue = false; 199 BindsImplicitObjectArgumentWithoutRefQualifier = false; 200 ObjCLifetimeConversionBinding = false; 201 CopyConstructor = 0; 202 } 203 204 /// getRank - Retrieve the rank of this standard conversion sequence 205 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 206 /// implicit conversions. 207 ImplicitConversionRank StandardConversionSequence::getRank() const { 208 ImplicitConversionRank Rank = ICR_Exact_Match; 209 if (GetConversionRank(First) > Rank) 210 Rank = GetConversionRank(First); 211 if (GetConversionRank(Second) > Rank) 212 Rank = GetConversionRank(Second); 213 if (GetConversionRank(Third) > Rank) 214 Rank = GetConversionRank(Third); 215 return Rank; 216 } 217 218 /// isPointerConversionToBool - Determines whether this conversion is 219 /// a conversion of a pointer or pointer-to-member to bool. This is 220 /// used as part of the ranking of standard conversion sequences 221 /// (C++ 13.3.3.2p4). 222 bool StandardConversionSequence::isPointerConversionToBool() const { 223 // Note that FromType has not necessarily been transformed by the 224 // array-to-pointer or function-to-pointer implicit conversions, so 225 // check for their presence as well as checking whether FromType is 226 // a pointer. 227 if (getToType(1)->isBooleanType() && 228 (getFromType()->isPointerType() || 229 getFromType()->isObjCObjectPointerType() || 230 getFromType()->isBlockPointerType() || 231 getFromType()->isNullPtrType() || 232 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 233 return true; 234 235 return false; 236 } 237 238 /// isPointerConversionToVoidPointer - Determines whether this 239 /// conversion is a conversion of a pointer to a void pointer. This is 240 /// used as part of the ranking of standard conversion sequences (C++ 241 /// 13.3.3.2p4). 242 bool 243 StandardConversionSequence:: 244 isPointerConversionToVoidPointer(ASTContext& Context) const { 245 QualType FromType = getFromType(); 246 QualType ToType = getToType(1); 247 248 // Note that FromType has not necessarily been transformed by the 249 // array-to-pointer implicit conversion, so check for its presence 250 // and redo the conversion to get a pointer. 251 if (First == ICK_Array_To_Pointer) 252 FromType = Context.getArrayDecayedType(FromType); 253 254 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType()) 255 if (const PointerType* ToPtrType = ToType->getAs<PointerType>()) 256 return ToPtrType->getPointeeType()->isVoidType(); 257 258 return false; 259 } 260 261 /// Skip any implicit casts which could be either part of a narrowing conversion 262 /// or after one in an implicit conversion. 263 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) { 264 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) { 265 switch (ICE->getCastKind()) { 266 case CK_NoOp: 267 case CK_IntegralCast: 268 case CK_IntegralToBoolean: 269 case CK_IntegralToFloating: 270 case CK_FloatingToIntegral: 271 case CK_FloatingToBoolean: 272 case CK_FloatingCast: 273 Converted = ICE->getSubExpr(); 274 continue; 275 276 default: 277 return Converted; 278 } 279 } 280 281 return Converted; 282 } 283 284 /// Check if this standard conversion sequence represents a narrowing 285 /// conversion, according to C++11 [dcl.init.list]p7. 286 /// 287 /// \param Ctx The AST context. 288 /// \param Converted The result of applying this standard conversion sequence. 289 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the 290 /// value of the expression prior to the narrowing conversion. 291 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the 292 /// type of the expression prior to the narrowing conversion. 293 NarrowingKind 294 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx, 295 const Expr *Converted, 296 APValue &ConstantValue, 297 QualType &ConstantType) const { 298 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++"); 299 300 // C++11 [dcl.init.list]p7: 301 // A narrowing conversion is an implicit conversion ... 302 QualType FromType = getToType(0); 303 QualType ToType = getToType(1); 304 switch (Second) { 305 // -- from a floating-point type to an integer type, or 306 // 307 // -- from an integer type or unscoped enumeration type to a floating-point 308 // type, except where the source is a constant expression and the actual 309 // value after conversion will fit into the target type and will produce 310 // the original value when converted back to the original type, or 311 case ICK_Floating_Integral: 312 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) { 313 return NK_Type_Narrowing; 314 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) { 315 llvm::APSInt IntConstantValue; 316 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 317 if (Initializer && 318 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) { 319 // Convert the integer to the floating type. 320 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType)); 321 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(), 322 llvm::APFloat::rmNearestTiesToEven); 323 // And back. 324 llvm::APSInt ConvertedValue = IntConstantValue; 325 bool ignored; 326 Result.convertToInteger(ConvertedValue, 327 llvm::APFloat::rmTowardZero, &ignored); 328 // If the resulting value is different, this was a narrowing conversion. 329 if (IntConstantValue != ConvertedValue) { 330 ConstantValue = APValue(IntConstantValue); 331 ConstantType = Initializer->getType(); 332 return NK_Constant_Narrowing; 333 } 334 } else { 335 // Variables are always narrowings. 336 return NK_Variable_Narrowing; 337 } 338 } 339 return NK_Not_Narrowing; 340 341 // -- from long double to double or float, or from double to float, except 342 // where the source is a constant expression and the actual value after 343 // conversion is within the range of values that can be represented (even 344 // if it cannot be represented exactly), or 345 case ICK_Floating_Conversion: 346 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() && 347 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) { 348 // FromType is larger than ToType. 349 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 350 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) { 351 // Constant! 352 assert(ConstantValue.isFloat()); 353 llvm::APFloat FloatVal = ConstantValue.getFloat(); 354 // Convert the source value into the target type. 355 bool ignored; 356 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert( 357 Ctx.getFloatTypeSemantics(ToType), 358 llvm::APFloat::rmNearestTiesToEven, &ignored); 359 // If there was no overflow, the source value is within the range of 360 // values that can be represented. 361 if (ConvertStatus & llvm::APFloat::opOverflow) { 362 ConstantType = Initializer->getType(); 363 return NK_Constant_Narrowing; 364 } 365 } else { 366 return NK_Variable_Narrowing; 367 } 368 } 369 return NK_Not_Narrowing; 370 371 // -- from an integer type or unscoped enumeration type to an integer type 372 // that cannot represent all the values of the original type, except where 373 // the source is a constant expression and the actual value after 374 // conversion will fit into the target type and will produce the original 375 // value when converted back to the original type. 376 case ICK_Boolean_Conversion: // Bools are integers too. 377 if (!FromType->isIntegralOrUnscopedEnumerationType()) { 378 // Boolean conversions can be from pointers and pointers to members 379 // [conv.bool], and those aren't considered narrowing conversions. 380 return NK_Not_Narrowing; 381 } // Otherwise, fall through to the integral case. 382 case ICK_Integral_Conversion: { 383 assert(FromType->isIntegralOrUnscopedEnumerationType()); 384 assert(ToType->isIntegralOrUnscopedEnumerationType()); 385 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType(); 386 const unsigned FromWidth = Ctx.getIntWidth(FromType); 387 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType(); 388 const unsigned ToWidth = Ctx.getIntWidth(ToType); 389 390 if (FromWidth > ToWidth || 391 (FromWidth == ToWidth && FromSigned != ToSigned)) { 392 // Not all values of FromType can be represented in ToType. 393 llvm::APSInt InitializerValue; 394 const Expr *Initializer = IgnoreNarrowingConversion(Converted); 395 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) { 396 ConstantValue = APValue(InitializerValue); 397 398 // Add a bit to the InitializerValue so we don't have to worry about 399 // signed vs. unsigned comparisons. 400 InitializerValue = InitializerValue.extend( 401 InitializerValue.getBitWidth() + 1); 402 // Convert the initializer to and from the target width and signed-ness. 403 llvm::APSInt ConvertedValue = InitializerValue; 404 ConvertedValue = ConvertedValue.trunc(ToWidth); 405 ConvertedValue.setIsSigned(ToSigned); 406 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth()); 407 ConvertedValue.setIsSigned(InitializerValue.isSigned()); 408 // If the result is different, this was a narrowing conversion. 409 if (ConvertedValue != InitializerValue) { 410 ConstantType = Initializer->getType(); 411 return NK_Constant_Narrowing; 412 } 413 } else { 414 // Variables are always narrowings. 415 return NK_Variable_Narrowing; 416 } 417 } 418 return NK_Not_Narrowing; 419 } 420 421 default: 422 // Other kinds of conversions are not narrowings. 423 return NK_Not_Narrowing; 424 } 425 } 426 427 /// DebugPrint - Print this standard conversion sequence to standard 428 /// error. Useful for debugging overloading issues. 429 void StandardConversionSequence::DebugPrint() const { 430 raw_ostream &OS = llvm::errs(); 431 bool PrintedSomething = false; 432 if (First != ICK_Identity) { 433 OS << GetImplicitConversionName(First); 434 PrintedSomething = true; 435 } 436 437 if (Second != ICK_Identity) { 438 if (PrintedSomething) { 439 OS << " -> "; 440 } 441 OS << GetImplicitConversionName(Second); 442 443 if (CopyConstructor) { 444 OS << " (by copy constructor)"; 445 } else if (DirectBinding) { 446 OS << " (direct reference binding)"; 447 } else if (ReferenceBinding) { 448 OS << " (reference binding)"; 449 } 450 PrintedSomething = true; 451 } 452 453 if (Third != ICK_Identity) { 454 if (PrintedSomething) { 455 OS << " -> "; 456 } 457 OS << GetImplicitConversionName(Third); 458 PrintedSomething = true; 459 } 460 461 if (!PrintedSomething) { 462 OS << "No conversions required"; 463 } 464 } 465 466 /// DebugPrint - Print this user-defined conversion sequence to standard 467 /// error. Useful for debugging overloading issues. 468 void UserDefinedConversionSequence::DebugPrint() const { 469 raw_ostream &OS = llvm::errs(); 470 if (Before.First || Before.Second || Before.Third) { 471 Before.DebugPrint(); 472 OS << " -> "; 473 } 474 if (ConversionFunction) 475 OS << '\'' << *ConversionFunction << '\''; 476 else 477 OS << "aggregate initialization"; 478 if (After.First || After.Second || After.Third) { 479 OS << " -> "; 480 After.DebugPrint(); 481 } 482 } 483 484 /// DebugPrint - Print this implicit conversion sequence to standard 485 /// error. Useful for debugging overloading issues. 486 void ImplicitConversionSequence::DebugPrint() const { 487 raw_ostream &OS = llvm::errs(); 488 switch (ConversionKind) { 489 case StandardConversion: 490 OS << "Standard conversion: "; 491 Standard.DebugPrint(); 492 break; 493 case UserDefinedConversion: 494 OS << "User-defined conversion: "; 495 UserDefined.DebugPrint(); 496 break; 497 case EllipsisConversion: 498 OS << "Ellipsis conversion"; 499 break; 500 case AmbiguousConversion: 501 OS << "Ambiguous conversion"; 502 break; 503 case BadConversion: 504 OS << "Bad conversion"; 505 break; 506 } 507 508 OS << "\n"; 509 } 510 511 void AmbiguousConversionSequence::construct() { 512 new (&conversions()) ConversionSet(); 513 } 514 515 void AmbiguousConversionSequence::destruct() { 516 conversions().~ConversionSet(); 517 } 518 519 void 520 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) { 521 FromTypePtr = O.FromTypePtr; 522 ToTypePtr = O.ToTypePtr; 523 new (&conversions()) ConversionSet(O.conversions()); 524 } 525 526 namespace { 527 // Structure used by OverloadCandidate::DeductionFailureInfo to store 528 // template parameter and template argument information. 529 struct DFIParamWithArguments { 530 TemplateParameter Param; 531 TemplateArgument FirstArg; 532 TemplateArgument SecondArg; 533 }; 534 } 535 536 /// \brief Convert from Sema's representation of template deduction information 537 /// to the form used in overload-candidate information. 538 OverloadCandidate::DeductionFailureInfo 539 static MakeDeductionFailureInfo(ASTContext &Context, 540 Sema::TemplateDeductionResult TDK, 541 TemplateDeductionInfo &Info) { 542 OverloadCandidate::DeductionFailureInfo Result; 543 Result.Result = static_cast<unsigned>(TDK); 544 Result.Data = 0; 545 switch (TDK) { 546 case Sema::TDK_Success: 547 case Sema::TDK_InstantiationDepth: 548 case Sema::TDK_TooManyArguments: 549 case Sema::TDK_TooFewArguments: 550 break; 551 552 case Sema::TDK_Incomplete: 553 case Sema::TDK_InvalidExplicitArguments: 554 Result.Data = Info.Param.getOpaqueValue(); 555 break; 556 557 case Sema::TDK_Inconsistent: 558 case Sema::TDK_Underqualified: { 559 // FIXME: Should allocate from normal heap so that we can free this later. 560 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments; 561 Saved->Param = Info.Param; 562 Saved->FirstArg = Info.FirstArg; 563 Saved->SecondArg = Info.SecondArg; 564 Result.Data = Saved; 565 break; 566 } 567 568 case Sema::TDK_SubstitutionFailure: 569 Result.Data = Info.take(); 570 break; 571 572 case Sema::TDK_NonDeducedMismatch: 573 case Sema::TDK_FailedOverloadResolution: 574 break; 575 } 576 577 return Result; 578 } 579 580 void OverloadCandidate::DeductionFailureInfo::Destroy() { 581 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 582 case Sema::TDK_Success: 583 case Sema::TDK_InstantiationDepth: 584 case Sema::TDK_Incomplete: 585 case Sema::TDK_TooManyArguments: 586 case Sema::TDK_TooFewArguments: 587 case Sema::TDK_InvalidExplicitArguments: 588 break; 589 590 case Sema::TDK_Inconsistent: 591 case Sema::TDK_Underqualified: 592 // FIXME: Destroy the data? 593 Data = 0; 594 break; 595 596 case Sema::TDK_SubstitutionFailure: 597 // FIXME: Destroy the template arugment list? 598 Data = 0; 599 break; 600 601 // Unhandled 602 case Sema::TDK_NonDeducedMismatch: 603 case Sema::TDK_FailedOverloadResolution: 604 break; 605 } 606 } 607 608 TemplateParameter 609 OverloadCandidate::DeductionFailureInfo::getTemplateParameter() { 610 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 611 case Sema::TDK_Success: 612 case Sema::TDK_InstantiationDepth: 613 case Sema::TDK_TooManyArguments: 614 case Sema::TDK_TooFewArguments: 615 case Sema::TDK_SubstitutionFailure: 616 return TemplateParameter(); 617 618 case Sema::TDK_Incomplete: 619 case Sema::TDK_InvalidExplicitArguments: 620 return TemplateParameter::getFromOpaqueValue(Data); 621 622 case Sema::TDK_Inconsistent: 623 case Sema::TDK_Underqualified: 624 return static_cast<DFIParamWithArguments*>(Data)->Param; 625 626 // Unhandled 627 case Sema::TDK_NonDeducedMismatch: 628 case Sema::TDK_FailedOverloadResolution: 629 break; 630 } 631 632 return TemplateParameter(); 633 } 634 635 TemplateArgumentList * 636 OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() { 637 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 638 case Sema::TDK_Success: 639 case Sema::TDK_InstantiationDepth: 640 case Sema::TDK_TooManyArguments: 641 case Sema::TDK_TooFewArguments: 642 case Sema::TDK_Incomplete: 643 case Sema::TDK_InvalidExplicitArguments: 644 case Sema::TDK_Inconsistent: 645 case Sema::TDK_Underqualified: 646 return 0; 647 648 case Sema::TDK_SubstitutionFailure: 649 return static_cast<TemplateArgumentList*>(Data); 650 651 // Unhandled 652 case Sema::TDK_NonDeducedMismatch: 653 case Sema::TDK_FailedOverloadResolution: 654 break; 655 } 656 657 return 0; 658 } 659 660 const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() { 661 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 662 case Sema::TDK_Success: 663 case Sema::TDK_InstantiationDepth: 664 case Sema::TDK_Incomplete: 665 case Sema::TDK_TooManyArguments: 666 case Sema::TDK_TooFewArguments: 667 case Sema::TDK_InvalidExplicitArguments: 668 case Sema::TDK_SubstitutionFailure: 669 return 0; 670 671 case Sema::TDK_Inconsistent: 672 case Sema::TDK_Underqualified: 673 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg; 674 675 // Unhandled 676 case Sema::TDK_NonDeducedMismatch: 677 case Sema::TDK_FailedOverloadResolution: 678 break; 679 } 680 681 return 0; 682 } 683 684 const TemplateArgument * 685 OverloadCandidate::DeductionFailureInfo::getSecondArg() { 686 switch (static_cast<Sema::TemplateDeductionResult>(Result)) { 687 case Sema::TDK_Success: 688 case Sema::TDK_InstantiationDepth: 689 case Sema::TDK_Incomplete: 690 case Sema::TDK_TooManyArguments: 691 case Sema::TDK_TooFewArguments: 692 case Sema::TDK_InvalidExplicitArguments: 693 case Sema::TDK_SubstitutionFailure: 694 return 0; 695 696 case Sema::TDK_Inconsistent: 697 case Sema::TDK_Underqualified: 698 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg; 699 700 // Unhandled 701 case Sema::TDK_NonDeducedMismatch: 702 case Sema::TDK_FailedOverloadResolution: 703 break; 704 } 705 706 return 0; 707 } 708 709 void OverloadCandidateSet::clear() { 710 for (iterator i = begin(), e = end(); i != e; ++i) 711 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii) 712 i->Conversions[ii].~ImplicitConversionSequence(); 713 NumInlineSequences = 0; 714 Candidates.clear(); 715 Functions.clear(); 716 } 717 718 namespace { 719 class UnbridgedCastsSet { 720 struct Entry { 721 Expr **Addr; 722 Expr *Saved; 723 }; 724 SmallVector<Entry, 2> Entries; 725 726 public: 727 void save(Sema &S, Expr *&E) { 728 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); 729 Entry entry = { &E, E }; 730 Entries.push_back(entry); 731 E = S.stripARCUnbridgedCast(E); 732 } 733 734 void restore() { 735 for (SmallVectorImpl<Entry>::iterator 736 i = Entries.begin(), e = Entries.end(); i != e; ++i) 737 *i->Addr = i->Saved; 738 } 739 }; 740 } 741 742 /// checkPlaceholderForOverload - Do any interesting placeholder-like 743 /// preprocessing on the given expression. 744 /// 745 /// \param unbridgedCasts a collection to which to add unbridged casts; 746 /// without this, they will be immediately diagnosed as errors 747 /// 748 /// Return true on unrecoverable error. 749 static bool checkPlaceholderForOverload(Sema &S, Expr *&E, 750 UnbridgedCastsSet *unbridgedCasts = 0) { 751 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) { 752 // We can't handle overloaded expressions here because overload 753 // resolution might reasonably tweak them. 754 if (placeholder->getKind() == BuiltinType::Overload) return false; 755 756 // If the context potentially accepts unbridged ARC casts, strip 757 // the unbridged cast and add it to the collection for later restoration. 758 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast && 759 unbridgedCasts) { 760 unbridgedCasts->save(S, E); 761 return false; 762 } 763 764 // Go ahead and check everything else. 765 ExprResult result = S.CheckPlaceholderExpr(E); 766 if (result.isInvalid()) 767 return true; 768 769 E = result.take(); 770 return false; 771 } 772 773 // Nothing to do. 774 return false; 775 } 776 777 /// checkArgPlaceholdersForOverload - Check a set of call operands for 778 /// placeholders. 779 static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args, 780 unsigned numArgs, 781 UnbridgedCastsSet &unbridged) { 782 for (unsigned i = 0; i != numArgs; ++i) 783 if (checkPlaceholderForOverload(S, args[i], &unbridged)) 784 return true; 785 786 return false; 787 } 788 789 // IsOverload - Determine whether the given New declaration is an 790 // overload of the declarations in Old. This routine returns false if 791 // New and Old cannot be overloaded, e.g., if New has the same 792 // signature as some function in Old (C++ 1.3.10) or if the Old 793 // declarations aren't functions (or function templates) at all. When 794 // it does return false, MatchedDecl will point to the decl that New 795 // cannot be overloaded with. This decl may be a UsingShadowDecl on 796 // top of the underlying declaration. 797 // 798 // Example: Given the following input: 799 // 800 // void f(int, float); // #1 801 // void f(int, int); // #2 802 // int f(int, int); // #3 803 // 804 // When we process #1, there is no previous declaration of "f", 805 // so IsOverload will not be used. 806 // 807 // When we process #2, Old contains only the FunctionDecl for #1. By 808 // comparing the parameter types, we see that #1 and #2 are overloaded 809 // (since they have different signatures), so this routine returns 810 // false; MatchedDecl is unchanged. 811 // 812 // When we process #3, Old is an overload set containing #1 and #2. We 813 // compare the signatures of #3 to #1 (they're overloaded, so we do 814 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are 815 // identical (return types of functions are not part of the 816 // signature), IsOverload returns false and MatchedDecl will be set to 817 // point to the FunctionDecl for #2. 818 // 819 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced 820 // into a class by a using declaration. The rules for whether to hide 821 // shadow declarations ignore some properties which otherwise figure 822 // into a function template's signature. 823 Sema::OverloadKind 824 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old, 825 NamedDecl *&Match, bool NewIsUsingDecl) { 826 for (LookupResult::iterator I = Old.begin(), E = Old.end(); 827 I != E; ++I) { 828 NamedDecl *OldD = *I; 829 830 bool OldIsUsingDecl = false; 831 if (isa<UsingShadowDecl>(OldD)) { 832 OldIsUsingDecl = true; 833 834 // We can always introduce two using declarations into the same 835 // context, even if they have identical signatures. 836 if (NewIsUsingDecl) continue; 837 838 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl(); 839 } 840 841 // If either declaration was introduced by a using declaration, 842 // we'll need to use slightly different rules for matching. 843 // Essentially, these rules are the normal rules, except that 844 // function templates hide function templates with different 845 // return types or template parameter lists. 846 bool UseMemberUsingDeclRules = 847 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord(); 848 849 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) { 850 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) { 851 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 852 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 853 continue; 854 } 855 856 Match = *I; 857 return Ovl_Match; 858 } 859 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) { 860 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) { 861 if (UseMemberUsingDeclRules && OldIsUsingDecl) { 862 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I)); 863 continue; 864 } 865 866 Match = *I; 867 return Ovl_Match; 868 } 869 } else if (isa<UsingDecl>(OldD)) { 870 // We can overload with these, which can show up when doing 871 // redeclaration checks for UsingDecls. 872 assert(Old.getLookupKind() == LookupUsingDeclName); 873 } else if (isa<TagDecl>(OldD)) { 874 // We can always overload with tags by hiding them. 875 } else if (isa<UnresolvedUsingValueDecl>(OldD)) { 876 // Optimistically assume that an unresolved using decl will 877 // overload; if it doesn't, we'll have to diagnose during 878 // template instantiation. 879 } else { 880 // (C++ 13p1): 881 // Only function declarations can be overloaded; object and type 882 // declarations cannot be overloaded. 883 Match = *I; 884 return Ovl_NonFunction; 885 } 886 } 887 888 return Ovl_Overload; 889 } 890 891 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old, 892 bool UseUsingDeclRules) { 893 // If both of the functions are extern "C", then they are not 894 // overloads. 895 if (Old->isExternC() && New->isExternC()) 896 return false; 897 898 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate(); 899 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate(); 900 901 // C++ [temp.fct]p2: 902 // A function template can be overloaded with other function templates 903 // and with normal (non-template) functions. 904 if ((OldTemplate == 0) != (NewTemplate == 0)) 905 return true; 906 907 // Is the function New an overload of the function Old? 908 QualType OldQType = Context.getCanonicalType(Old->getType()); 909 QualType NewQType = Context.getCanonicalType(New->getType()); 910 911 // Compare the signatures (C++ 1.3.10) of the two functions to 912 // determine whether they are overloads. If we find any mismatch 913 // in the signature, they are overloads. 914 915 // If either of these functions is a K&R-style function (no 916 // prototype), then we consider them to have matching signatures. 917 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) || 918 isa<FunctionNoProtoType>(NewQType.getTypePtr())) 919 return false; 920 921 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType); 922 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType); 923 924 // The signature of a function includes the types of its 925 // parameters (C++ 1.3.10), which includes the presence or absence 926 // of the ellipsis; see C++ DR 357). 927 if (OldQType != NewQType && 928 (OldType->getNumArgs() != NewType->getNumArgs() || 929 OldType->isVariadic() != NewType->isVariadic() || 930 !FunctionArgTypesAreEqual(OldType, NewType))) 931 return true; 932 933 // C++ [temp.over.link]p4: 934 // The signature of a function template consists of its function 935 // signature, its return type and its template parameter list. The names 936 // of the template parameters are significant only for establishing the 937 // relationship between the template parameters and the rest of the 938 // signature. 939 // 940 // We check the return type and template parameter lists for function 941 // templates first; the remaining checks follow. 942 // 943 // However, we don't consider either of these when deciding whether 944 // a member introduced by a shadow declaration is hidden. 945 if (!UseUsingDeclRules && NewTemplate && 946 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(), 947 OldTemplate->getTemplateParameters(), 948 false, TPL_TemplateMatch) || 949 OldType->getResultType() != NewType->getResultType())) 950 return true; 951 952 // If the function is a class member, its signature includes the 953 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself. 954 // 955 // As part of this, also check whether one of the member functions 956 // is static, in which case they are not overloads (C++ 957 // 13.1p2). While not part of the definition of the signature, 958 // this check is important to determine whether these functions 959 // can be overloaded. 960 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 961 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 962 if (OldMethod && NewMethod && 963 !OldMethod->isStatic() && !NewMethod->isStatic() && 964 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() || 965 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) { 966 if (!UseUsingDeclRules && 967 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() && 968 (OldMethod->getRefQualifier() == RQ_None || 969 NewMethod->getRefQualifier() == RQ_None)) { 970 // C++0x [over.load]p2: 971 // - Member function declarations with the same name and the same 972 // parameter-type-list as well as member function template 973 // declarations with the same name, the same parameter-type-list, and 974 // the same template parameter lists cannot be overloaded if any of 975 // them, but not all, have a ref-qualifier (8.3.5). 976 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload) 977 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier(); 978 Diag(OldMethod->getLocation(), diag::note_previous_declaration); 979 } 980 981 return true; 982 } 983 984 // The signatures match; this is not an overload. 985 return false; 986 } 987 988 /// \brief Checks availability of the function depending on the current 989 /// function context. Inside an unavailable function, unavailability is ignored. 990 /// 991 /// \returns true if \arg FD is unavailable and current context is inside 992 /// an available function, false otherwise. 993 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) { 994 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable(); 995 } 996 997 /// \brief Tries a user-defined conversion from From to ToType. 998 /// 999 /// Produces an implicit conversion sequence for when a standard conversion 1000 /// is not an option. See TryImplicitConversion for more information. 1001 static ImplicitConversionSequence 1002 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 1003 bool SuppressUserConversions, 1004 bool AllowExplicit, 1005 bool InOverloadResolution, 1006 bool CStyle, 1007 bool AllowObjCWritebackConversion) { 1008 ImplicitConversionSequence ICS; 1009 1010 if (SuppressUserConversions) { 1011 // We're not in the case above, so there is no conversion that 1012 // we can perform. 1013 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1014 return ICS; 1015 } 1016 1017 // Attempt user-defined conversion. 1018 OverloadCandidateSet Conversions(From->getExprLoc()); 1019 OverloadingResult UserDefResult 1020 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions, 1021 AllowExplicit); 1022 1023 if (UserDefResult == OR_Success) { 1024 ICS.setUserDefined(); 1025 // C++ [over.ics.user]p4: 1026 // A conversion of an expression of class type to the same class 1027 // type is given Exact Match rank, and a conversion of an 1028 // expression of class type to a base class of that type is 1029 // given Conversion rank, in spite of the fact that a copy 1030 // constructor (i.e., a user-defined conversion function) is 1031 // called for those cases. 1032 if (CXXConstructorDecl *Constructor 1033 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 1034 QualType FromCanon 1035 = S.Context.getCanonicalType(From->getType().getUnqualifiedType()); 1036 QualType ToCanon 1037 = S.Context.getCanonicalType(ToType).getUnqualifiedType(); 1038 if (Constructor->isCopyConstructor() && 1039 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) { 1040 // Turn this into a "standard" conversion sequence, so that it 1041 // gets ranked with standard conversion sequences. 1042 ICS.setStandard(); 1043 ICS.Standard.setAsIdentityConversion(); 1044 ICS.Standard.setFromType(From->getType()); 1045 ICS.Standard.setAllToTypes(ToType); 1046 ICS.Standard.CopyConstructor = Constructor; 1047 if (ToCanon != FromCanon) 1048 ICS.Standard.Second = ICK_Derived_To_Base; 1049 } 1050 } 1051 1052 // C++ [over.best.ics]p4: 1053 // However, when considering the argument of a user-defined 1054 // conversion function that is a candidate by 13.3.1.3 when 1055 // invoked for the copying of the temporary in the second step 1056 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or 1057 // 13.3.1.6 in all cases, only standard conversion sequences and 1058 // ellipsis conversion sequences are allowed. 1059 if (SuppressUserConversions && ICS.isUserDefined()) { 1060 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType); 1061 } 1062 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) { 1063 ICS.setAmbiguous(); 1064 ICS.Ambiguous.setFromType(From->getType()); 1065 ICS.Ambiguous.setToType(ToType); 1066 for (OverloadCandidateSet::iterator Cand = Conversions.begin(); 1067 Cand != Conversions.end(); ++Cand) 1068 if (Cand->Viable) 1069 ICS.Ambiguous.addConversion(Cand->Function); 1070 } else { 1071 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1072 } 1073 1074 return ICS; 1075 } 1076 1077 /// TryImplicitConversion - Attempt to perform an implicit conversion 1078 /// from the given expression (Expr) to the given type (ToType). This 1079 /// function returns an implicit conversion sequence that can be used 1080 /// to perform the initialization. Given 1081 /// 1082 /// void f(float f); 1083 /// void g(int i) { f(i); } 1084 /// 1085 /// this routine would produce an implicit conversion sequence to 1086 /// describe the initialization of f from i, which will be a standard 1087 /// conversion sequence containing an lvalue-to-rvalue conversion (C++ 1088 /// 4.1) followed by a floating-integral conversion (C++ 4.9). 1089 // 1090 /// Note that this routine only determines how the conversion can be 1091 /// performed; it does not actually perform the conversion. As such, 1092 /// it will not produce any diagnostics if no conversion is available, 1093 /// but will instead return an implicit conversion sequence of kind 1094 /// "BadConversion". 1095 /// 1096 /// If @p SuppressUserConversions, then user-defined conversions are 1097 /// not permitted. 1098 /// If @p AllowExplicit, then explicit user-defined conversions are 1099 /// permitted. 1100 /// 1101 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C 1102 /// writeback conversion, which allows __autoreleasing id* parameters to 1103 /// be initialized with __strong id* or __weak id* arguments. 1104 static ImplicitConversionSequence 1105 TryImplicitConversion(Sema &S, Expr *From, QualType ToType, 1106 bool SuppressUserConversions, 1107 bool AllowExplicit, 1108 bool InOverloadResolution, 1109 bool CStyle, 1110 bool AllowObjCWritebackConversion) { 1111 ImplicitConversionSequence ICS; 1112 if (IsStandardConversion(S, From, ToType, InOverloadResolution, 1113 ICS.Standard, CStyle, AllowObjCWritebackConversion)){ 1114 ICS.setStandard(); 1115 return ICS; 1116 } 1117 1118 if (!S.getLangOpts().CPlusPlus) { 1119 ICS.setBad(BadConversionSequence::no_conversion, From, ToType); 1120 return ICS; 1121 } 1122 1123 // C++ [over.ics.user]p4: 1124 // A conversion of an expression of class type to the same class 1125 // type is given Exact Match rank, and a conversion of an 1126 // expression of class type to a base class of that type is 1127 // given Conversion rank, in spite of the fact that a copy/move 1128 // constructor (i.e., a user-defined conversion function) is 1129 // called for those cases. 1130 QualType FromType = From->getType(); 1131 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() && 1132 (S.Context.hasSameUnqualifiedType(FromType, ToType) || 1133 S.IsDerivedFrom(FromType, ToType))) { 1134 ICS.setStandard(); 1135 ICS.Standard.setAsIdentityConversion(); 1136 ICS.Standard.setFromType(FromType); 1137 ICS.Standard.setAllToTypes(ToType); 1138 1139 // We don't actually check at this point whether there is a valid 1140 // copy/move constructor, since overloading just assumes that it 1141 // exists. When we actually perform initialization, we'll find the 1142 // appropriate constructor to copy the returned object, if needed. 1143 ICS.Standard.CopyConstructor = 0; 1144 1145 // Determine whether this is considered a derived-to-base conversion. 1146 if (!S.Context.hasSameUnqualifiedType(FromType, ToType)) 1147 ICS.Standard.Second = ICK_Derived_To_Base; 1148 1149 return ICS; 1150 } 1151 1152 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions, 1153 AllowExplicit, InOverloadResolution, CStyle, 1154 AllowObjCWritebackConversion); 1155 } 1156 1157 ImplicitConversionSequence 1158 Sema::TryImplicitConversion(Expr *From, QualType ToType, 1159 bool SuppressUserConversions, 1160 bool AllowExplicit, 1161 bool InOverloadResolution, 1162 bool CStyle, 1163 bool AllowObjCWritebackConversion) { 1164 return clang::TryImplicitConversion(*this, From, ToType, 1165 SuppressUserConversions, AllowExplicit, 1166 InOverloadResolution, CStyle, 1167 AllowObjCWritebackConversion); 1168 } 1169 1170 /// PerformImplicitConversion - Perform an implicit conversion of the 1171 /// expression From to the type ToType. Returns the 1172 /// converted expression. Flavor is the kind of conversion we're 1173 /// performing, used in the error message. If @p AllowExplicit, 1174 /// explicit user-defined conversions are permitted. 1175 ExprResult 1176 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1177 AssignmentAction Action, bool AllowExplicit) { 1178 ImplicitConversionSequence ICS; 1179 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS); 1180 } 1181 1182 ExprResult 1183 Sema::PerformImplicitConversion(Expr *From, QualType ToType, 1184 AssignmentAction Action, bool AllowExplicit, 1185 ImplicitConversionSequence& ICS) { 1186 if (checkPlaceholderForOverload(*this, From)) 1187 return ExprError(); 1188 1189 // Objective-C ARC: Determine whether we will allow the writeback conversion. 1190 bool AllowObjCWritebackConversion 1191 = getLangOpts().ObjCAutoRefCount && 1192 (Action == AA_Passing || Action == AA_Sending); 1193 1194 ICS = clang::TryImplicitConversion(*this, From, ToType, 1195 /*SuppressUserConversions=*/false, 1196 AllowExplicit, 1197 /*InOverloadResolution=*/false, 1198 /*CStyle=*/false, 1199 AllowObjCWritebackConversion); 1200 return PerformImplicitConversion(From, ToType, ICS, Action); 1201 } 1202 1203 /// \brief Determine whether the conversion from FromType to ToType is a valid 1204 /// conversion that strips "noreturn" off the nested function type. 1205 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType, 1206 QualType &ResultTy) { 1207 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1208 return false; 1209 1210 // Permit the conversion F(t __attribute__((noreturn))) -> F(t) 1211 // where F adds one of the following at most once: 1212 // - a pointer 1213 // - a member pointer 1214 // - a block pointer 1215 CanQualType CanTo = Context.getCanonicalType(ToType); 1216 CanQualType CanFrom = Context.getCanonicalType(FromType); 1217 Type::TypeClass TyClass = CanTo->getTypeClass(); 1218 if (TyClass != CanFrom->getTypeClass()) return false; 1219 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) { 1220 if (TyClass == Type::Pointer) { 1221 CanTo = CanTo.getAs<PointerType>()->getPointeeType(); 1222 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType(); 1223 } else if (TyClass == Type::BlockPointer) { 1224 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType(); 1225 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType(); 1226 } else if (TyClass == Type::MemberPointer) { 1227 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType(); 1228 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType(); 1229 } else { 1230 return false; 1231 } 1232 1233 TyClass = CanTo->getTypeClass(); 1234 if (TyClass != CanFrom->getTypeClass()) return false; 1235 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) 1236 return false; 1237 } 1238 1239 const FunctionType *FromFn = cast<FunctionType>(CanFrom); 1240 FunctionType::ExtInfo EInfo = FromFn->getExtInfo(); 1241 if (!EInfo.getNoReturn()) return false; 1242 1243 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false)); 1244 assert(QualType(FromFn, 0).isCanonical()); 1245 if (QualType(FromFn, 0) != CanTo) return false; 1246 1247 ResultTy = ToType; 1248 return true; 1249 } 1250 1251 /// \brief Determine whether the conversion from FromType to ToType is a valid 1252 /// vector conversion. 1253 /// 1254 /// \param ICK Will be set to the vector conversion kind, if this is a vector 1255 /// conversion. 1256 static bool IsVectorConversion(ASTContext &Context, QualType FromType, 1257 QualType ToType, ImplicitConversionKind &ICK) { 1258 // We need at least one of these types to be a vector type to have a vector 1259 // conversion. 1260 if (!ToType->isVectorType() && !FromType->isVectorType()) 1261 return false; 1262 1263 // Identical types require no conversions. 1264 if (Context.hasSameUnqualifiedType(FromType, ToType)) 1265 return false; 1266 1267 // There are no conversions between extended vector types, only identity. 1268 if (ToType->isExtVectorType()) { 1269 // There are no conversions between extended vector types other than the 1270 // identity conversion. 1271 if (FromType->isExtVectorType()) 1272 return false; 1273 1274 // Vector splat from any arithmetic type to a vector. 1275 if (FromType->isArithmeticType()) { 1276 ICK = ICK_Vector_Splat; 1277 return true; 1278 } 1279 } 1280 1281 // We can perform the conversion between vector types in the following cases: 1282 // 1)vector types are equivalent AltiVec and GCC vector types 1283 // 2)lax vector conversions are permitted and the vector types are of the 1284 // same size 1285 if (ToType->isVectorType() && FromType->isVectorType()) { 1286 if (Context.areCompatibleVectorTypes(FromType, ToType) || 1287 (Context.getLangOpts().LaxVectorConversions && 1288 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) { 1289 ICK = ICK_Vector_Conversion; 1290 return true; 1291 } 1292 } 1293 1294 return false; 1295 } 1296 1297 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 1298 bool InOverloadResolution, 1299 StandardConversionSequence &SCS, 1300 bool CStyle); 1301 1302 /// IsStandardConversion - Determines whether there is a standard 1303 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 1304 /// expression From to the type ToType. Standard conversion sequences 1305 /// only consider non-class types; for conversions that involve class 1306 /// types, use TryImplicitConversion. If a conversion exists, SCS will 1307 /// contain the standard conversion sequence required to perform this 1308 /// conversion and this routine will return true. Otherwise, this 1309 /// routine will return false and the value of SCS is unspecified. 1310 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType, 1311 bool InOverloadResolution, 1312 StandardConversionSequence &SCS, 1313 bool CStyle, 1314 bool AllowObjCWritebackConversion) { 1315 QualType FromType = From->getType(); 1316 1317 // Standard conversions (C++ [conv]) 1318 SCS.setAsIdentityConversion(); 1319 SCS.DeprecatedStringLiteralToCharPtr = false; 1320 SCS.IncompatibleObjC = false; 1321 SCS.setFromType(FromType); 1322 SCS.CopyConstructor = 0; 1323 1324 // There are no standard conversions for class types in C++, so 1325 // abort early. When overloading in C, however, we do permit 1326 if (FromType->isRecordType() || ToType->isRecordType()) { 1327 if (S.getLangOpts().CPlusPlus) 1328 return false; 1329 1330 // When we're overloading in C, we allow, as standard conversions, 1331 } 1332 1333 // The first conversion can be an lvalue-to-rvalue conversion, 1334 // array-to-pointer conversion, or function-to-pointer conversion 1335 // (C++ 4p1). 1336 1337 if (FromType == S.Context.OverloadTy) { 1338 DeclAccessPair AccessPair; 1339 if (FunctionDecl *Fn 1340 = S.ResolveAddressOfOverloadedFunction(From, ToType, false, 1341 AccessPair)) { 1342 // We were able to resolve the address of the overloaded function, 1343 // so we can convert to the type of that function. 1344 FromType = Fn->getType(); 1345 1346 // we can sometimes resolve &foo<int> regardless of ToType, so check 1347 // if the type matches (identity) or we are converting to bool 1348 if (!S.Context.hasSameUnqualifiedType( 1349 S.ExtractUnqualifiedFunctionType(ToType), FromType)) { 1350 QualType resultTy; 1351 // if the function type matches except for [[noreturn]], it's ok 1352 if (!S.IsNoReturnConversion(FromType, 1353 S.ExtractUnqualifiedFunctionType(ToType), resultTy)) 1354 // otherwise, only a boolean conversion is standard 1355 if (!ToType->isBooleanType()) 1356 return false; 1357 } 1358 1359 // Check if the "from" expression is taking the address of an overloaded 1360 // function and recompute the FromType accordingly. Take advantage of the 1361 // fact that non-static member functions *must* have such an address-of 1362 // expression. 1363 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn); 1364 if (Method && !Method->isStatic()) { 1365 assert(isa<UnaryOperator>(From->IgnoreParens()) && 1366 "Non-unary operator on non-static member address"); 1367 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() 1368 == UO_AddrOf && 1369 "Non-address-of operator on non-static member address"); 1370 const Type *ClassType 1371 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr(); 1372 FromType = S.Context.getMemberPointerType(FromType, ClassType); 1373 } else if (isa<UnaryOperator>(From->IgnoreParens())) { 1374 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() == 1375 UO_AddrOf && 1376 "Non-address-of operator for overloaded function expression"); 1377 FromType = S.Context.getPointerType(FromType); 1378 } 1379 1380 // Check that we've computed the proper type after overload resolution. 1381 assert(S.Context.hasSameType( 1382 FromType, 1383 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType())); 1384 } else { 1385 return false; 1386 } 1387 } 1388 // Lvalue-to-rvalue conversion (C++11 4.1): 1389 // A glvalue (3.10) of a non-function, non-array type T can 1390 // be converted to a prvalue. 1391 bool argIsLValue = From->isGLValue(); 1392 if (argIsLValue && 1393 !FromType->isFunctionType() && !FromType->isArrayType() && 1394 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) { 1395 SCS.First = ICK_Lvalue_To_Rvalue; 1396 1397 // C11 6.3.2.1p2: 1398 // ... if the lvalue has atomic type, the value has the non-atomic version 1399 // of the type of the lvalue ... 1400 if (const AtomicType *Atomic = FromType->getAs<AtomicType>()) 1401 FromType = Atomic->getValueType(); 1402 1403 // If T is a non-class type, the type of the rvalue is the 1404 // cv-unqualified version of T. Otherwise, the type of the rvalue 1405 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we 1406 // just strip the qualifiers because they don't matter. 1407 FromType = FromType.getUnqualifiedType(); 1408 } else if (FromType->isArrayType()) { 1409 // Array-to-pointer conversion (C++ 4.2) 1410 SCS.First = ICK_Array_To_Pointer; 1411 1412 // An lvalue or rvalue of type "array of N T" or "array of unknown 1413 // bound of T" can be converted to an rvalue of type "pointer to 1414 // T" (C++ 4.2p1). 1415 FromType = S.Context.getArrayDecayedType(FromType); 1416 1417 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) { 1418 // This conversion is deprecated. (C++ D.4). 1419 SCS.DeprecatedStringLiteralToCharPtr = true; 1420 1421 // For the purpose of ranking in overload resolution 1422 // (13.3.3.1.1), this conversion is considered an 1423 // array-to-pointer conversion followed by a qualification 1424 // conversion (4.4). (C++ 4.2p2) 1425 SCS.Second = ICK_Identity; 1426 SCS.Third = ICK_Qualification; 1427 SCS.QualificationIncludesObjCLifetime = false; 1428 SCS.setAllToTypes(FromType); 1429 return true; 1430 } 1431 } else if (FromType->isFunctionType() && argIsLValue) { 1432 // Function-to-pointer conversion (C++ 4.3). 1433 SCS.First = ICK_Function_To_Pointer; 1434 1435 // An lvalue of function type T can be converted to an rvalue of 1436 // type "pointer to T." The result is a pointer to the 1437 // function. (C++ 4.3p1). 1438 FromType = S.Context.getPointerType(FromType); 1439 } else { 1440 // We don't require any conversions for the first step. 1441 SCS.First = ICK_Identity; 1442 } 1443 SCS.setToType(0, FromType); 1444 1445 // The second conversion can be an integral promotion, floating 1446 // point promotion, integral conversion, floating point conversion, 1447 // floating-integral conversion, pointer conversion, 1448 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 1449 // For overloading in C, this can also be a "compatible-type" 1450 // conversion. 1451 bool IncompatibleObjC = false; 1452 ImplicitConversionKind SecondICK = ICK_Identity; 1453 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) { 1454 // The unqualified versions of the types are the same: there's no 1455 // conversion to do. 1456 SCS.Second = ICK_Identity; 1457 } else if (S.IsIntegralPromotion(From, FromType, ToType)) { 1458 // Integral promotion (C++ 4.5). 1459 SCS.Second = ICK_Integral_Promotion; 1460 FromType = ToType.getUnqualifiedType(); 1461 } else if (S.IsFloatingPointPromotion(FromType, ToType)) { 1462 // Floating point promotion (C++ 4.6). 1463 SCS.Second = ICK_Floating_Promotion; 1464 FromType = ToType.getUnqualifiedType(); 1465 } else if (S.IsComplexPromotion(FromType, ToType)) { 1466 // Complex promotion (Clang extension) 1467 SCS.Second = ICK_Complex_Promotion; 1468 FromType = ToType.getUnqualifiedType(); 1469 } else if (ToType->isBooleanType() && 1470 (FromType->isArithmeticType() || 1471 FromType->isAnyPointerType() || 1472 FromType->isBlockPointerType() || 1473 FromType->isMemberPointerType() || 1474 FromType->isNullPtrType())) { 1475 // Boolean conversions (C++ 4.12). 1476 SCS.Second = ICK_Boolean_Conversion; 1477 FromType = S.Context.BoolTy; 1478 } else if (FromType->isIntegralOrUnscopedEnumerationType() && 1479 ToType->isIntegralType(S.Context)) { 1480 // Integral conversions (C++ 4.7). 1481 SCS.Second = ICK_Integral_Conversion; 1482 FromType = ToType.getUnqualifiedType(); 1483 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) { 1484 // Complex conversions (C99 6.3.1.6) 1485 SCS.Second = ICK_Complex_Conversion; 1486 FromType = ToType.getUnqualifiedType(); 1487 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) || 1488 (ToType->isAnyComplexType() && FromType->isArithmeticType())) { 1489 // Complex-real conversions (C99 6.3.1.7) 1490 SCS.Second = ICK_Complex_Real; 1491 FromType = ToType.getUnqualifiedType(); 1492 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) { 1493 // Floating point conversions (C++ 4.8). 1494 SCS.Second = ICK_Floating_Conversion; 1495 FromType = ToType.getUnqualifiedType(); 1496 } else if ((FromType->isRealFloatingType() && 1497 ToType->isIntegralType(S.Context)) || 1498 (FromType->isIntegralOrUnscopedEnumerationType() && 1499 ToType->isRealFloatingType())) { 1500 // Floating-integral conversions (C++ 4.9). 1501 SCS.Second = ICK_Floating_Integral; 1502 FromType = ToType.getUnqualifiedType(); 1503 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) { 1504 SCS.Second = ICK_Block_Pointer_Conversion; 1505 } else if (AllowObjCWritebackConversion && 1506 S.isObjCWritebackConversion(FromType, ToType, FromType)) { 1507 SCS.Second = ICK_Writeback_Conversion; 1508 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution, 1509 FromType, IncompatibleObjC)) { 1510 // Pointer conversions (C++ 4.10). 1511 SCS.Second = ICK_Pointer_Conversion; 1512 SCS.IncompatibleObjC = IncompatibleObjC; 1513 FromType = FromType.getUnqualifiedType(); 1514 } else if (S.IsMemberPointerConversion(From, FromType, ToType, 1515 InOverloadResolution, FromType)) { 1516 // Pointer to member conversions (4.11). 1517 SCS.Second = ICK_Pointer_Member; 1518 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) { 1519 SCS.Second = SecondICK; 1520 FromType = ToType.getUnqualifiedType(); 1521 } else if (!S.getLangOpts().CPlusPlus && 1522 S.Context.typesAreCompatible(ToType, FromType)) { 1523 // Compatible conversions (Clang extension for C function overloading) 1524 SCS.Second = ICK_Compatible_Conversion; 1525 FromType = ToType.getUnqualifiedType(); 1526 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) { 1527 // Treat a conversion that strips "noreturn" as an identity conversion. 1528 SCS.Second = ICK_NoReturn_Adjustment; 1529 } else if (IsTransparentUnionStandardConversion(S, From, ToType, 1530 InOverloadResolution, 1531 SCS, CStyle)) { 1532 SCS.Second = ICK_TransparentUnionConversion; 1533 FromType = ToType; 1534 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS, 1535 CStyle)) { 1536 // tryAtomicConversion has updated the standard conversion sequence 1537 // appropriately. 1538 return true; 1539 } else { 1540 // No second conversion required. 1541 SCS.Second = ICK_Identity; 1542 } 1543 SCS.setToType(1, FromType); 1544 1545 QualType CanonFrom; 1546 QualType CanonTo; 1547 // The third conversion can be a qualification conversion (C++ 4p1). 1548 bool ObjCLifetimeConversion; 1549 if (S.IsQualificationConversion(FromType, ToType, CStyle, 1550 ObjCLifetimeConversion)) { 1551 SCS.Third = ICK_Qualification; 1552 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion; 1553 FromType = ToType; 1554 CanonFrom = S.Context.getCanonicalType(FromType); 1555 CanonTo = S.Context.getCanonicalType(ToType); 1556 } else { 1557 // No conversion required 1558 SCS.Third = ICK_Identity; 1559 1560 // C++ [over.best.ics]p6: 1561 // [...] Any difference in top-level cv-qualification is 1562 // subsumed by the initialization itself and does not constitute 1563 // a conversion. [...] 1564 CanonFrom = S.Context.getCanonicalType(FromType); 1565 CanonTo = S.Context.getCanonicalType(ToType); 1566 if (CanonFrom.getLocalUnqualifiedType() 1567 == CanonTo.getLocalUnqualifiedType() && 1568 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers() 1569 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr() 1570 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) { 1571 FromType = ToType; 1572 CanonFrom = CanonTo; 1573 } 1574 } 1575 SCS.setToType(2, FromType); 1576 1577 // If we have not converted the argument type to the parameter type, 1578 // this is a bad conversion sequence. 1579 if (CanonFrom != CanonTo) 1580 return false; 1581 1582 return true; 1583 } 1584 1585 static bool 1586 IsTransparentUnionStandardConversion(Sema &S, Expr* From, 1587 QualType &ToType, 1588 bool InOverloadResolution, 1589 StandardConversionSequence &SCS, 1590 bool CStyle) { 1591 1592 const RecordType *UT = ToType->getAsUnionType(); 1593 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>()) 1594 return false; 1595 // The field to initialize within the transparent union. 1596 RecordDecl *UD = UT->getDecl(); 1597 // It's compatible if the expression matches any of the fields. 1598 for (RecordDecl::field_iterator it = UD->field_begin(), 1599 itend = UD->field_end(); 1600 it != itend; ++it) { 1601 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, 1602 CStyle, /*ObjCWritebackConversion=*/false)) { 1603 ToType = it->getType(); 1604 return true; 1605 } 1606 } 1607 return false; 1608 } 1609 1610 /// IsIntegralPromotion - Determines whether the conversion from the 1611 /// expression From (whose potentially-adjusted type is FromType) to 1612 /// ToType is an integral promotion (C++ 4.5). If so, returns true and 1613 /// sets PromotedType to the promoted type. 1614 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) { 1615 const BuiltinType *To = ToType->getAs<BuiltinType>(); 1616 // All integers are built-in. 1617 if (!To) { 1618 return false; 1619 } 1620 1621 // An rvalue of type char, signed char, unsigned char, short int, or 1622 // unsigned short int can be converted to an rvalue of type int if 1623 // int can represent all the values of the source type; otherwise, 1624 // the source rvalue can be converted to an rvalue of type unsigned 1625 // int (C++ 4.5p1). 1626 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() && 1627 !FromType->isEnumeralType()) { 1628 if (// We can promote any signed, promotable integer type to an int 1629 (FromType->isSignedIntegerType() || 1630 // We can promote any unsigned integer type whose size is 1631 // less than int to an int. 1632 (!FromType->isSignedIntegerType() && 1633 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 1634 return To->getKind() == BuiltinType::Int; 1635 } 1636 1637 return To->getKind() == BuiltinType::UInt; 1638 } 1639 1640 // C++0x [conv.prom]p3: 1641 // A prvalue of an unscoped enumeration type whose underlying type is not 1642 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the 1643 // following types that can represent all the values of the enumeration 1644 // (i.e., the values in the range bmin to bmax as described in 7.2): int, 1645 // unsigned int, long int, unsigned long int, long long int, or unsigned 1646 // long long int. If none of the types in that list can represent all the 1647 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration 1648 // type can be converted to an rvalue a prvalue of the extended integer type 1649 // with lowest integer conversion rank (4.13) greater than the rank of long 1650 // long in which all the values of the enumeration can be represented. If 1651 // there are two such extended types, the signed one is chosen. 1652 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) { 1653 // C++0x 7.2p9: Note that this implicit enum to int conversion is not 1654 // provided for a scoped enumeration. 1655 if (FromEnumType->getDecl()->isScoped()) 1656 return false; 1657 1658 // We have already pre-calculated the promotion type, so this is trivial. 1659 if (ToType->isIntegerType() && 1660 !RequireCompleteType(From->getLocStart(), FromType, PDiag())) 1661 return Context.hasSameUnqualifiedType(ToType, 1662 FromEnumType->getDecl()->getPromotionType()); 1663 } 1664 1665 // C++0x [conv.prom]p2: 1666 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted 1667 // to an rvalue a prvalue of the first of the following types that can 1668 // represent all the values of its underlying type: int, unsigned int, 1669 // long int, unsigned long int, long long int, or unsigned long long int. 1670 // If none of the types in that list can represent all the values of its 1671 // underlying type, an rvalue a prvalue of type char16_t, char32_t, 1672 // or wchar_t can be converted to an rvalue a prvalue of its underlying 1673 // type. 1674 if (FromType->isAnyCharacterType() && !FromType->isCharType() && 1675 ToType->isIntegerType()) { 1676 // Determine whether the type we're converting from is signed or 1677 // unsigned. 1678 bool FromIsSigned = FromType->isSignedIntegerType(); 1679 uint64_t FromSize = Context.getTypeSize(FromType); 1680 1681 // The types we'll try to promote to, in the appropriate 1682 // order. Try each of these types. 1683 QualType PromoteTypes[6] = { 1684 Context.IntTy, Context.UnsignedIntTy, 1685 Context.LongTy, Context.UnsignedLongTy , 1686 Context.LongLongTy, Context.UnsignedLongLongTy 1687 }; 1688 for (int Idx = 0; Idx < 6; ++Idx) { 1689 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 1690 if (FromSize < ToSize || 1691 (FromSize == ToSize && 1692 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 1693 // We found the type that we can promote to. If this is the 1694 // type we wanted, we have a promotion. Otherwise, no 1695 // promotion. 1696 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]); 1697 } 1698 } 1699 } 1700 1701 // An rvalue for an integral bit-field (9.6) can be converted to an 1702 // rvalue of type int if int can represent all the values of the 1703 // bit-field; otherwise, it can be converted to unsigned int if 1704 // unsigned int can represent all the values of the bit-field. If 1705 // the bit-field is larger yet, no integral promotion applies to 1706 // it. If the bit-field has an enumerated type, it is treated as any 1707 // other value of that type for promotion purposes (C++ 4.5p3). 1708 // FIXME: We should delay checking of bit-fields until we actually perform the 1709 // conversion. 1710 using llvm::APSInt; 1711 if (From) 1712 if (FieldDecl *MemberDecl = From->getBitField()) { 1713 APSInt BitWidth; 1714 if (FromType->isIntegralType(Context) && 1715 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) { 1716 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned()); 1717 ToSize = Context.getTypeSize(ToType); 1718 1719 // Are we promoting to an int from a bitfield that fits in an int? 1720 if (BitWidth < ToSize || 1721 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 1722 return To->getKind() == BuiltinType::Int; 1723 } 1724 1725 // Are we promoting to an unsigned int from an unsigned bitfield 1726 // that fits into an unsigned int? 1727 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 1728 return To->getKind() == BuiltinType::UInt; 1729 } 1730 1731 return false; 1732 } 1733 } 1734 1735 // An rvalue of type bool can be converted to an rvalue of type int, 1736 // with false becoming zero and true becoming one (C++ 4.5p4). 1737 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 1738 return true; 1739 } 1740 1741 return false; 1742 } 1743 1744 /// IsFloatingPointPromotion - Determines whether the conversion from 1745 /// FromType to ToType is a floating point promotion (C++ 4.6). If so, 1746 /// returns true and sets PromotedType to the promoted type. 1747 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) { 1748 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>()) 1749 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) { 1750 /// An rvalue of type float can be converted to an rvalue of type 1751 /// double. (C++ 4.6p1). 1752 if (FromBuiltin->getKind() == BuiltinType::Float && 1753 ToBuiltin->getKind() == BuiltinType::Double) 1754 return true; 1755 1756 // C99 6.3.1.5p1: 1757 // When a float is promoted to double or long double, or a 1758 // double is promoted to long double [...]. 1759 if (!getLangOpts().CPlusPlus && 1760 (FromBuiltin->getKind() == BuiltinType::Float || 1761 FromBuiltin->getKind() == BuiltinType::Double) && 1762 (ToBuiltin->getKind() == BuiltinType::LongDouble)) 1763 return true; 1764 1765 // Half can be promoted to float. 1766 if (FromBuiltin->getKind() == BuiltinType::Half && 1767 ToBuiltin->getKind() == BuiltinType::Float) 1768 return true; 1769 } 1770 1771 return false; 1772 } 1773 1774 /// \brief Determine if a conversion is a complex promotion. 1775 /// 1776 /// A complex promotion is defined as a complex -> complex conversion 1777 /// where the conversion between the underlying real types is a 1778 /// floating-point or integral promotion. 1779 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) { 1780 const ComplexType *FromComplex = FromType->getAs<ComplexType>(); 1781 if (!FromComplex) 1782 return false; 1783 1784 const ComplexType *ToComplex = ToType->getAs<ComplexType>(); 1785 if (!ToComplex) 1786 return false; 1787 1788 return IsFloatingPointPromotion(FromComplex->getElementType(), 1789 ToComplex->getElementType()) || 1790 IsIntegralPromotion(0, FromComplex->getElementType(), 1791 ToComplex->getElementType()); 1792 } 1793 1794 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 1795 /// the pointer type FromPtr to a pointer to type ToPointee, with the 1796 /// same type qualifiers as FromPtr has on its pointee type. ToType, 1797 /// if non-empty, will be a pointer to ToType that may or may not have 1798 /// the right set of qualifiers on its pointee. 1799 /// 1800 static QualType 1801 BuildSimilarlyQualifiedPointerType(const Type *FromPtr, 1802 QualType ToPointee, QualType ToType, 1803 ASTContext &Context, 1804 bool StripObjCLifetime = false) { 1805 assert((FromPtr->getTypeClass() == Type::Pointer || 1806 FromPtr->getTypeClass() == Type::ObjCObjectPointer) && 1807 "Invalid similarly-qualified pointer type"); 1808 1809 /// Conversions to 'id' subsume cv-qualifier conversions. 1810 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType()) 1811 return ToType.getUnqualifiedType(); 1812 1813 QualType CanonFromPointee 1814 = Context.getCanonicalType(FromPtr->getPointeeType()); 1815 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 1816 Qualifiers Quals = CanonFromPointee.getQualifiers(); 1817 1818 if (StripObjCLifetime) 1819 Quals.removeObjCLifetime(); 1820 1821 // Exact qualifier match -> return the pointer type we're converting to. 1822 if (CanonToPointee.getLocalQualifiers() == Quals) { 1823 // ToType is exactly what we need. Return it. 1824 if (!ToType.isNull()) 1825 return ToType.getUnqualifiedType(); 1826 1827 // Build a pointer to ToPointee. It has the right qualifiers 1828 // already. 1829 if (isa<ObjCObjectPointerType>(ToType)) 1830 return Context.getObjCObjectPointerType(ToPointee); 1831 return Context.getPointerType(ToPointee); 1832 } 1833 1834 // Just build a canonical type that has the right qualifiers. 1835 QualType QualifiedCanonToPointee 1836 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals); 1837 1838 if (isa<ObjCObjectPointerType>(ToType)) 1839 return Context.getObjCObjectPointerType(QualifiedCanonToPointee); 1840 return Context.getPointerType(QualifiedCanonToPointee); 1841 } 1842 1843 static bool isNullPointerConstantForConversion(Expr *Expr, 1844 bool InOverloadResolution, 1845 ASTContext &Context) { 1846 // Handle value-dependent integral null pointer constants correctly. 1847 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903 1848 if (Expr->isValueDependent() && !Expr->isTypeDependent() && 1849 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType()) 1850 return !InOverloadResolution; 1851 1852 return Expr->isNullPointerConstant(Context, 1853 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 1854 : Expr::NPC_ValueDependentIsNull); 1855 } 1856 1857 /// IsPointerConversion - Determines whether the conversion of the 1858 /// expression From, which has the (possibly adjusted) type FromType, 1859 /// can be converted to the type ToType via a pointer conversion (C++ 1860 /// 4.10). If so, returns true and places the converted type (that 1861 /// might differ from ToType in its cv-qualifiers at some level) into 1862 /// ConvertedType. 1863 /// 1864 /// This routine also supports conversions to and from block pointers 1865 /// and conversions with Objective-C's 'id', 'id<protocols...>', and 1866 /// pointers to interfaces. FIXME: Once we've determined the 1867 /// appropriate overloading rules for Objective-C, we may want to 1868 /// split the Objective-C checks into a different routine; however, 1869 /// GCC seems to consider all of these conversions to be pointer 1870 /// conversions, so for now they live here. IncompatibleObjC will be 1871 /// set if the conversion is an allowed Objective-C conversion that 1872 /// should result in a warning. 1873 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 1874 bool InOverloadResolution, 1875 QualType& ConvertedType, 1876 bool &IncompatibleObjC) { 1877 IncompatibleObjC = false; 1878 if (isObjCPointerConversion(FromType, ToType, ConvertedType, 1879 IncompatibleObjC)) 1880 return true; 1881 1882 // Conversion from a null pointer constant to any Objective-C pointer type. 1883 if (ToType->isObjCObjectPointerType() && 1884 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1885 ConvertedType = ToType; 1886 return true; 1887 } 1888 1889 // Blocks: Block pointers can be converted to void*. 1890 if (FromType->isBlockPointerType() && ToType->isPointerType() && 1891 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) { 1892 ConvertedType = ToType; 1893 return true; 1894 } 1895 // Blocks: A null pointer constant can be converted to a block 1896 // pointer type. 1897 if (ToType->isBlockPointerType() && 1898 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1899 ConvertedType = ToType; 1900 return true; 1901 } 1902 1903 // If the left-hand-side is nullptr_t, the right side can be a null 1904 // pointer constant. 1905 if (ToType->isNullPtrType() && 1906 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1907 ConvertedType = ToType; 1908 return true; 1909 } 1910 1911 const PointerType* ToTypePtr = ToType->getAs<PointerType>(); 1912 if (!ToTypePtr) 1913 return false; 1914 1915 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 1916 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) { 1917 ConvertedType = ToType; 1918 return true; 1919 } 1920 1921 // Beyond this point, both types need to be pointers 1922 // , including objective-c pointers. 1923 QualType ToPointeeType = ToTypePtr->getPointeeType(); 1924 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() && 1925 !getLangOpts().ObjCAutoRefCount) { 1926 ConvertedType = BuildSimilarlyQualifiedPointerType( 1927 FromType->getAs<ObjCObjectPointerType>(), 1928 ToPointeeType, 1929 ToType, Context); 1930 return true; 1931 } 1932 const PointerType *FromTypePtr = FromType->getAs<PointerType>(); 1933 if (!FromTypePtr) 1934 return false; 1935 1936 QualType FromPointeeType = FromTypePtr->getPointeeType(); 1937 1938 // If the unqualified pointee types are the same, this can't be a 1939 // pointer conversion, so don't do all of the work below. 1940 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) 1941 return false; 1942 1943 // An rvalue of type "pointer to cv T," where T is an object type, 1944 // can be converted to an rvalue of type "pointer to cv void" (C++ 1945 // 4.10p2). 1946 if (FromPointeeType->isIncompleteOrObjectType() && 1947 ToPointeeType->isVoidType()) { 1948 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1949 ToPointeeType, 1950 ToType, Context, 1951 /*StripObjCLifetime=*/true); 1952 return true; 1953 } 1954 1955 // MSVC allows implicit function to void* type conversion. 1956 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() && 1957 ToPointeeType->isVoidType()) { 1958 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1959 ToPointeeType, 1960 ToType, Context); 1961 return true; 1962 } 1963 1964 // When we're overloading in C, we allow a special kind of pointer 1965 // conversion for compatible-but-not-identical pointee types. 1966 if (!getLangOpts().CPlusPlus && 1967 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) { 1968 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1969 ToPointeeType, 1970 ToType, Context); 1971 return true; 1972 } 1973 1974 // C++ [conv.ptr]p3: 1975 // 1976 // An rvalue of type "pointer to cv D," where D is a class type, 1977 // can be converted to an rvalue of type "pointer to cv B," where 1978 // B is a base class (clause 10) of D. If B is an inaccessible 1979 // (clause 11) or ambiguous (10.2) base class of D, a program that 1980 // necessitates this conversion is ill-formed. The result of the 1981 // conversion is a pointer to the base class sub-object of the 1982 // derived class object. The null pointer value is converted to 1983 // the null pointer value of the destination type. 1984 // 1985 // Note that we do not check for ambiguity or inaccessibility 1986 // here. That is handled by CheckPointerConversion. 1987 if (getLangOpts().CPlusPlus && 1988 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 1989 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) && 1990 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) && 1991 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 1992 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 1993 ToPointeeType, 1994 ToType, Context); 1995 return true; 1996 } 1997 1998 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() && 1999 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) { 2000 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 2001 ToPointeeType, 2002 ToType, Context); 2003 return true; 2004 } 2005 2006 return false; 2007 } 2008 2009 /// \brief Adopt the given qualifiers for the given type. 2010 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){ 2011 Qualifiers TQs = T.getQualifiers(); 2012 2013 // Check whether qualifiers already match. 2014 if (TQs == Qs) 2015 return T; 2016 2017 if (Qs.compatiblyIncludes(TQs)) 2018 return Context.getQualifiedType(T, Qs); 2019 2020 return Context.getQualifiedType(T.getUnqualifiedType(), Qs); 2021 } 2022 2023 /// isObjCPointerConversion - Determines whether this is an 2024 /// Objective-C pointer conversion. Subroutine of IsPointerConversion, 2025 /// with the same arguments and return values. 2026 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 2027 QualType& ConvertedType, 2028 bool &IncompatibleObjC) { 2029 if (!getLangOpts().ObjC1) 2030 return false; 2031 2032 // The set of qualifiers on the type we're converting from. 2033 Qualifiers FromQualifiers = FromType.getQualifiers(); 2034 2035 // First, we handle all conversions on ObjC object pointer types. 2036 const ObjCObjectPointerType* ToObjCPtr = 2037 ToType->getAs<ObjCObjectPointerType>(); 2038 const ObjCObjectPointerType *FromObjCPtr = 2039 FromType->getAs<ObjCObjectPointerType>(); 2040 2041 if (ToObjCPtr && FromObjCPtr) { 2042 // If the pointee types are the same (ignoring qualifications), 2043 // then this is not a pointer conversion. 2044 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(), 2045 FromObjCPtr->getPointeeType())) 2046 return false; 2047 2048 // Check for compatible 2049 // Objective C++: We're able to convert between "id" or "Class" and a 2050 // pointer to any interface (in both directions). 2051 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) { 2052 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2053 return true; 2054 } 2055 // Conversions with Objective-C's id<...>. 2056 if ((FromObjCPtr->isObjCQualifiedIdType() || 2057 ToObjCPtr->isObjCQualifiedIdType()) && 2058 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType, 2059 /*compare=*/false)) { 2060 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2061 return true; 2062 } 2063 // Objective C++: We're able to convert from a pointer to an 2064 // interface to a pointer to a different interface. 2065 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) { 2066 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType(); 2067 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType(); 2068 if (getLangOpts().CPlusPlus && LHS && RHS && 2069 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs( 2070 FromObjCPtr->getPointeeType())) 2071 return false; 2072 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2073 ToObjCPtr->getPointeeType(), 2074 ToType, Context); 2075 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2076 return true; 2077 } 2078 2079 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) { 2080 // Okay: this is some kind of implicit downcast of Objective-C 2081 // interfaces, which is permitted. However, we're going to 2082 // complain about it. 2083 IncompatibleObjC = true; 2084 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr, 2085 ToObjCPtr->getPointeeType(), 2086 ToType, Context); 2087 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2088 return true; 2089 } 2090 } 2091 // Beyond this point, both types need to be C pointers or block pointers. 2092 QualType ToPointeeType; 2093 if (const PointerType *ToCPtr = ToType->getAs<PointerType>()) 2094 ToPointeeType = ToCPtr->getPointeeType(); 2095 else if (const BlockPointerType *ToBlockPtr = 2096 ToType->getAs<BlockPointerType>()) { 2097 // Objective C++: We're able to convert from a pointer to any object 2098 // to a block pointer type. 2099 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) { 2100 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2101 return true; 2102 } 2103 ToPointeeType = ToBlockPtr->getPointeeType(); 2104 } 2105 else if (FromType->getAs<BlockPointerType>() && 2106 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) { 2107 // Objective C++: We're able to convert from a block pointer type to a 2108 // pointer to any object. 2109 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2110 return true; 2111 } 2112 else 2113 return false; 2114 2115 QualType FromPointeeType; 2116 if (const PointerType *FromCPtr = FromType->getAs<PointerType>()) 2117 FromPointeeType = FromCPtr->getPointeeType(); 2118 else if (const BlockPointerType *FromBlockPtr = 2119 FromType->getAs<BlockPointerType>()) 2120 FromPointeeType = FromBlockPtr->getPointeeType(); 2121 else 2122 return false; 2123 2124 // If we have pointers to pointers, recursively check whether this 2125 // is an Objective-C conversion. 2126 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 2127 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2128 IncompatibleObjC)) { 2129 // We always complain about this conversion. 2130 IncompatibleObjC = true; 2131 ConvertedType = Context.getPointerType(ConvertedType); 2132 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2133 return true; 2134 } 2135 // Allow conversion of pointee being objective-c pointer to another one; 2136 // as in I* to id. 2137 if (FromPointeeType->getAs<ObjCObjectPointerType>() && 2138 ToPointeeType->getAs<ObjCObjectPointerType>() && 2139 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 2140 IncompatibleObjC)) { 2141 2142 ConvertedType = Context.getPointerType(ConvertedType); 2143 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers); 2144 return true; 2145 } 2146 2147 // If we have pointers to functions or blocks, check whether the only 2148 // differences in the argument and result types are in Objective-C 2149 // pointer conversions. If so, we permit the conversion (but 2150 // complain about it). 2151 const FunctionProtoType *FromFunctionType 2152 = FromPointeeType->getAs<FunctionProtoType>(); 2153 const FunctionProtoType *ToFunctionType 2154 = ToPointeeType->getAs<FunctionProtoType>(); 2155 if (FromFunctionType && ToFunctionType) { 2156 // If the function types are exactly the same, this isn't an 2157 // Objective-C pointer conversion. 2158 if (Context.getCanonicalType(FromPointeeType) 2159 == Context.getCanonicalType(ToPointeeType)) 2160 return false; 2161 2162 // Perform the quick checks that will tell us whether these 2163 // function types are obviously different. 2164 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2165 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 2166 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 2167 return false; 2168 2169 bool HasObjCConversion = false; 2170 if (Context.getCanonicalType(FromFunctionType->getResultType()) 2171 == Context.getCanonicalType(ToFunctionType->getResultType())) { 2172 // Okay, the types match exactly. Nothing to do. 2173 } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 2174 ToFunctionType->getResultType(), 2175 ConvertedType, IncompatibleObjC)) { 2176 // Okay, we have an Objective-C pointer conversion. 2177 HasObjCConversion = true; 2178 } else { 2179 // Function types are too different. Abort. 2180 return false; 2181 } 2182 2183 // Check argument types. 2184 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2185 ArgIdx != NumArgs; ++ArgIdx) { 2186 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2187 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2188 if (Context.getCanonicalType(FromArgType) 2189 == Context.getCanonicalType(ToArgType)) { 2190 // Okay, the types match exactly. Nothing to do. 2191 } else if (isObjCPointerConversion(FromArgType, ToArgType, 2192 ConvertedType, IncompatibleObjC)) { 2193 // Okay, we have an Objective-C pointer conversion. 2194 HasObjCConversion = true; 2195 } else { 2196 // Argument types are too different. Abort. 2197 return false; 2198 } 2199 } 2200 2201 if (HasObjCConversion) { 2202 // We had an Objective-C conversion. Allow this pointer 2203 // conversion, but complain about it. 2204 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers); 2205 IncompatibleObjC = true; 2206 return true; 2207 } 2208 } 2209 2210 return false; 2211 } 2212 2213 /// \brief Determine whether this is an Objective-C writeback conversion, 2214 /// used for parameter passing when performing automatic reference counting. 2215 /// 2216 /// \param FromType The type we're converting form. 2217 /// 2218 /// \param ToType The type we're converting to. 2219 /// 2220 /// \param ConvertedType The type that will be produced after applying 2221 /// this conversion. 2222 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType, 2223 QualType &ConvertedType) { 2224 if (!getLangOpts().ObjCAutoRefCount || 2225 Context.hasSameUnqualifiedType(FromType, ToType)) 2226 return false; 2227 2228 // Parameter must be a pointer to __autoreleasing (with no other qualifiers). 2229 QualType ToPointee; 2230 if (const PointerType *ToPointer = ToType->getAs<PointerType>()) 2231 ToPointee = ToPointer->getPointeeType(); 2232 else 2233 return false; 2234 2235 Qualifiers ToQuals = ToPointee.getQualifiers(); 2236 if (!ToPointee->isObjCLifetimeType() || 2237 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing || 2238 !ToQuals.withoutObjCLifetime().empty()) 2239 return false; 2240 2241 // Argument must be a pointer to __strong to __weak. 2242 QualType FromPointee; 2243 if (const PointerType *FromPointer = FromType->getAs<PointerType>()) 2244 FromPointee = FromPointer->getPointeeType(); 2245 else 2246 return false; 2247 2248 Qualifiers FromQuals = FromPointee.getQualifiers(); 2249 if (!FromPointee->isObjCLifetimeType() || 2250 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong && 2251 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak)) 2252 return false; 2253 2254 // Make sure that we have compatible qualifiers. 2255 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing); 2256 if (!ToQuals.compatiblyIncludes(FromQuals)) 2257 return false; 2258 2259 // Remove qualifiers from the pointee type we're converting from; they 2260 // aren't used in the compatibility check belong, and we'll be adding back 2261 // qualifiers (with __autoreleasing) if the compatibility check succeeds. 2262 FromPointee = FromPointee.getUnqualifiedType(); 2263 2264 // The unqualified form of the pointee types must be compatible. 2265 ToPointee = ToPointee.getUnqualifiedType(); 2266 bool IncompatibleObjC; 2267 if (Context.typesAreCompatible(FromPointee, ToPointee)) 2268 FromPointee = ToPointee; 2269 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee, 2270 IncompatibleObjC)) 2271 return false; 2272 2273 /// \brief Construct the type we're converting to, which is a pointer to 2274 /// __autoreleasing pointee. 2275 FromPointee = Context.getQualifiedType(FromPointee, FromQuals); 2276 ConvertedType = Context.getPointerType(FromPointee); 2277 return true; 2278 } 2279 2280 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType, 2281 QualType& ConvertedType) { 2282 QualType ToPointeeType; 2283 if (const BlockPointerType *ToBlockPtr = 2284 ToType->getAs<BlockPointerType>()) 2285 ToPointeeType = ToBlockPtr->getPointeeType(); 2286 else 2287 return false; 2288 2289 QualType FromPointeeType; 2290 if (const BlockPointerType *FromBlockPtr = 2291 FromType->getAs<BlockPointerType>()) 2292 FromPointeeType = FromBlockPtr->getPointeeType(); 2293 else 2294 return false; 2295 // We have pointer to blocks, check whether the only 2296 // differences in the argument and result types are in Objective-C 2297 // pointer conversions. If so, we permit the conversion. 2298 2299 const FunctionProtoType *FromFunctionType 2300 = FromPointeeType->getAs<FunctionProtoType>(); 2301 const FunctionProtoType *ToFunctionType 2302 = ToPointeeType->getAs<FunctionProtoType>(); 2303 2304 if (!FromFunctionType || !ToFunctionType) 2305 return false; 2306 2307 if (Context.hasSameType(FromPointeeType, ToPointeeType)) 2308 return true; 2309 2310 // Perform the quick checks that will tell us whether these 2311 // function types are obviously different. 2312 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 2313 FromFunctionType->isVariadic() != ToFunctionType->isVariadic()) 2314 return false; 2315 2316 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo(); 2317 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo(); 2318 if (FromEInfo != ToEInfo) 2319 return false; 2320 2321 bool IncompatibleObjC = false; 2322 if (Context.hasSameType(FromFunctionType->getResultType(), 2323 ToFunctionType->getResultType())) { 2324 // Okay, the types match exactly. Nothing to do. 2325 } else { 2326 QualType RHS = FromFunctionType->getResultType(); 2327 QualType LHS = ToFunctionType->getResultType(); 2328 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) && 2329 !RHS.hasQualifiers() && LHS.hasQualifiers()) 2330 LHS = LHS.getUnqualifiedType(); 2331 2332 if (Context.hasSameType(RHS,LHS)) { 2333 // OK exact match. 2334 } else if (isObjCPointerConversion(RHS, LHS, 2335 ConvertedType, IncompatibleObjC)) { 2336 if (IncompatibleObjC) 2337 return false; 2338 // Okay, we have an Objective-C pointer conversion. 2339 } 2340 else 2341 return false; 2342 } 2343 2344 // Check argument types. 2345 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 2346 ArgIdx != NumArgs; ++ArgIdx) { 2347 IncompatibleObjC = false; 2348 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 2349 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 2350 if (Context.hasSameType(FromArgType, ToArgType)) { 2351 // Okay, the types match exactly. Nothing to do. 2352 } else if (isObjCPointerConversion(ToArgType, FromArgType, 2353 ConvertedType, IncompatibleObjC)) { 2354 if (IncompatibleObjC) 2355 return false; 2356 // Okay, we have an Objective-C pointer conversion. 2357 } else 2358 // Argument types are too different. Abort. 2359 return false; 2360 } 2361 if (LangOpts.ObjCAutoRefCount && 2362 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType, 2363 ToFunctionType)) 2364 return false; 2365 2366 ConvertedType = ToType; 2367 return true; 2368 } 2369 2370 enum { 2371 ft_default, 2372 ft_different_class, 2373 ft_parameter_arity, 2374 ft_parameter_mismatch, 2375 ft_return_type, 2376 ft_qualifer_mismatch 2377 }; 2378 2379 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing 2380 /// function types. Catches different number of parameter, mismatch in 2381 /// parameter types, and different return types. 2382 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, 2383 QualType FromType, QualType ToType) { 2384 // If either type is not valid, include no extra info. 2385 if (FromType.isNull() || ToType.isNull()) { 2386 PDiag << ft_default; 2387 return; 2388 } 2389 2390 // Get the function type from the pointers. 2391 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) { 2392 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(), 2393 *ToMember = ToType->getAs<MemberPointerType>(); 2394 if (FromMember->getClass() != ToMember->getClass()) { 2395 PDiag << ft_different_class << QualType(ToMember->getClass(), 0) 2396 << QualType(FromMember->getClass(), 0); 2397 return; 2398 } 2399 FromType = FromMember->getPointeeType(); 2400 ToType = ToMember->getPointeeType(); 2401 } 2402 2403 if (FromType->isPointerType()) 2404 FromType = FromType->getPointeeType(); 2405 if (ToType->isPointerType()) 2406 ToType = ToType->getPointeeType(); 2407 2408 // Remove references. 2409 FromType = FromType.getNonReferenceType(); 2410 ToType = ToType.getNonReferenceType(); 2411 2412 // Don't print extra info for non-specialized template functions. 2413 if (FromType->isInstantiationDependentType() && 2414 !FromType->getAs<TemplateSpecializationType>()) { 2415 PDiag << ft_default; 2416 return; 2417 } 2418 2419 // No extra info for same types. 2420 if (Context.hasSameType(FromType, ToType)) { 2421 PDiag << ft_default; 2422 return; 2423 } 2424 2425 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(), 2426 *ToFunction = ToType->getAs<FunctionProtoType>(); 2427 2428 // Both types need to be function types. 2429 if (!FromFunction || !ToFunction) { 2430 PDiag << ft_default; 2431 return; 2432 } 2433 2434 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) { 2435 PDiag << ft_parameter_arity << ToFunction->getNumArgs() 2436 << FromFunction->getNumArgs(); 2437 return; 2438 } 2439 2440 // Handle different parameter types. 2441 unsigned ArgPos; 2442 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) { 2443 PDiag << ft_parameter_mismatch << ArgPos + 1 2444 << ToFunction->getArgType(ArgPos) 2445 << FromFunction->getArgType(ArgPos); 2446 return; 2447 } 2448 2449 // Handle different return type. 2450 if (!Context.hasSameType(FromFunction->getResultType(), 2451 ToFunction->getResultType())) { 2452 PDiag << ft_return_type << ToFunction->getResultType() 2453 << FromFunction->getResultType(); 2454 return; 2455 } 2456 2457 unsigned FromQuals = FromFunction->getTypeQuals(), 2458 ToQuals = ToFunction->getTypeQuals(); 2459 if (FromQuals != ToQuals) { 2460 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals; 2461 return; 2462 } 2463 2464 // Unable to find a difference, so add no extra info. 2465 PDiag << ft_default; 2466 } 2467 2468 /// FunctionArgTypesAreEqual - This routine checks two function proto types 2469 /// for equality of their argument types. Caller has already checked that 2470 /// they have same number of arguments. This routine assumes that Objective-C 2471 /// pointer types which only differ in their protocol qualifiers are equal. 2472 /// If the parameters are different, ArgPos will have the the parameter index 2473 /// of the first different parameter. 2474 bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType, 2475 const FunctionProtoType *NewType, 2476 unsigned *ArgPos) { 2477 if (!getLangOpts().ObjC1) { 2478 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2479 N = NewType->arg_type_begin(), 2480 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2481 if (!Context.hasSameType(*O, *N)) { 2482 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2483 return false; 2484 } 2485 } 2486 return true; 2487 } 2488 2489 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(), 2490 N = NewType->arg_type_begin(), 2491 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) { 2492 QualType ToType = (*O); 2493 QualType FromType = (*N); 2494 if (!Context.hasSameType(ToType, FromType)) { 2495 if (const PointerType *PTTo = ToType->getAs<PointerType>()) { 2496 if (const PointerType *PTFr = FromType->getAs<PointerType>()) 2497 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() && 2498 PTFr->getPointeeType()->isObjCQualifiedIdType()) || 2499 (PTTo->getPointeeType()->isObjCQualifiedClassType() && 2500 PTFr->getPointeeType()->isObjCQualifiedClassType())) 2501 continue; 2502 } 2503 else if (const ObjCObjectPointerType *PTTo = 2504 ToType->getAs<ObjCObjectPointerType>()) { 2505 if (const ObjCObjectPointerType *PTFr = 2506 FromType->getAs<ObjCObjectPointerType>()) 2507 if (Context.hasSameUnqualifiedType( 2508 PTTo->getObjectType()->getBaseType(), 2509 PTFr->getObjectType()->getBaseType())) 2510 continue; 2511 } 2512 if (ArgPos) *ArgPos = O - OldType->arg_type_begin(); 2513 return false; 2514 } 2515 } 2516 return true; 2517 } 2518 2519 /// CheckPointerConversion - Check the pointer conversion from the 2520 /// expression From to the type ToType. This routine checks for 2521 /// ambiguous or inaccessible derived-to-base pointer 2522 /// conversions for which IsPointerConversion has already returned 2523 /// true. It returns true and produces a diagnostic if there was an 2524 /// error, or returns false otherwise. 2525 bool Sema::CheckPointerConversion(Expr *From, QualType ToType, 2526 CastKind &Kind, 2527 CXXCastPath& BasePath, 2528 bool IgnoreBaseAccess) { 2529 QualType FromType = From->getType(); 2530 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess; 2531 2532 Kind = CK_BitCast; 2533 2534 if (!IsCStyleOrFunctionalCast && 2535 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) && 2536 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull)) 2537 DiagRuntimeBehavior(From->getExprLoc(), From, 2538 PDiag(diag::warn_impcast_bool_to_null_pointer) 2539 << ToType << From->getSourceRange()); 2540 2541 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) { 2542 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) { 2543 QualType FromPointeeType = FromPtrType->getPointeeType(), 2544 ToPointeeType = ToPtrType->getPointeeType(); 2545 2546 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 2547 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) { 2548 // We must have a derived-to-base conversion. Check an 2549 // ambiguous or inaccessible conversion. 2550 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 2551 From->getExprLoc(), 2552 From->getSourceRange(), &BasePath, 2553 IgnoreBaseAccess)) 2554 return true; 2555 2556 // The conversion was successful. 2557 Kind = CK_DerivedToBase; 2558 } 2559 } 2560 } else if (const ObjCObjectPointerType *ToPtrType = 2561 ToType->getAs<ObjCObjectPointerType>()) { 2562 if (const ObjCObjectPointerType *FromPtrType = 2563 FromType->getAs<ObjCObjectPointerType>()) { 2564 // Objective-C++ conversions are always okay. 2565 // FIXME: We should have a different class of conversions for the 2566 // Objective-C++ implicit conversions. 2567 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType()) 2568 return false; 2569 } else if (FromType->isBlockPointerType()) { 2570 Kind = CK_BlockPointerToObjCPointerCast; 2571 } else { 2572 Kind = CK_CPointerToObjCPointerCast; 2573 } 2574 } else if (ToType->isBlockPointerType()) { 2575 if (!FromType->isBlockPointerType()) 2576 Kind = CK_AnyPointerToBlockPointerCast; 2577 } 2578 2579 // We shouldn't fall into this case unless it's valid for other 2580 // reasons. 2581 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull)) 2582 Kind = CK_NullToPointer; 2583 2584 return false; 2585 } 2586 2587 /// IsMemberPointerConversion - Determines whether the conversion of the 2588 /// expression From, which has the (possibly adjusted) type FromType, can be 2589 /// converted to the type ToType via a member pointer conversion (C++ 4.11). 2590 /// If so, returns true and places the converted type (that might differ from 2591 /// ToType in its cv-qualifiers at some level) into ConvertedType. 2592 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType, 2593 QualType ToType, 2594 bool InOverloadResolution, 2595 QualType &ConvertedType) { 2596 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>(); 2597 if (!ToTypePtr) 2598 return false; 2599 2600 // A null pointer constant can be converted to a member pointer (C++ 4.11p1) 2601 if (From->isNullPointerConstant(Context, 2602 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull 2603 : Expr::NPC_ValueDependentIsNull)) { 2604 ConvertedType = ToType; 2605 return true; 2606 } 2607 2608 // Otherwise, both types have to be member pointers. 2609 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>(); 2610 if (!FromTypePtr) 2611 return false; 2612 2613 // A pointer to member of B can be converted to a pointer to member of D, 2614 // where D is derived from B (C++ 4.11p2). 2615 QualType FromClass(FromTypePtr->getClass(), 0); 2616 QualType ToClass(ToTypePtr->getClass(), 0); 2617 2618 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) && 2619 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) && 2620 IsDerivedFrom(ToClass, FromClass)) { 2621 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(), 2622 ToClass.getTypePtr()); 2623 return true; 2624 } 2625 2626 return false; 2627 } 2628 2629 /// CheckMemberPointerConversion - Check the member pointer conversion from the 2630 /// expression From to the type ToType. This routine checks for ambiguous or 2631 /// virtual or inaccessible base-to-derived member pointer conversions 2632 /// for which IsMemberPointerConversion has already returned true. It returns 2633 /// true and produces a diagnostic if there was an error, or returns false 2634 /// otherwise. 2635 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType, 2636 CastKind &Kind, 2637 CXXCastPath &BasePath, 2638 bool IgnoreBaseAccess) { 2639 QualType FromType = From->getType(); 2640 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>(); 2641 if (!FromPtrType) { 2642 // This must be a null pointer to member pointer conversion 2643 assert(From->isNullPointerConstant(Context, 2644 Expr::NPC_ValueDependentIsNull) && 2645 "Expr must be null pointer constant!"); 2646 Kind = CK_NullToMemberPointer; 2647 return false; 2648 } 2649 2650 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>(); 2651 assert(ToPtrType && "No member pointer cast has a target type " 2652 "that is not a member pointer."); 2653 2654 QualType FromClass = QualType(FromPtrType->getClass(), 0); 2655 QualType ToClass = QualType(ToPtrType->getClass(), 0); 2656 2657 // FIXME: What about dependent types? 2658 assert(FromClass->isRecordType() && "Pointer into non-class."); 2659 assert(ToClass->isRecordType() && "Pointer into non-class."); 2660 2661 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 2662 /*DetectVirtual=*/true); 2663 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths); 2664 assert(DerivationOkay && 2665 "Should not have been called if derivation isn't OK."); 2666 (void)DerivationOkay; 2667 2668 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass). 2669 getUnqualifiedType())) { 2670 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths); 2671 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv) 2672 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange(); 2673 return true; 2674 } 2675 2676 if (const RecordType *VBase = Paths.getDetectedVirtual()) { 2677 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual) 2678 << FromClass << ToClass << QualType(VBase, 0) 2679 << From->getSourceRange(); 2680 return true; 2681 } 2682 2683 if (!IgnoreBaseAccess) 2684 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass, 2685 Paths.front(), 2686 diag::err_downcast_from_inaccessible_base); 2687 2688 // Must be a base to derived member conversion. 2689 BuildBasePathArray(Paths, BasePath); 2690 Kind = CK_BaseToDerivedMemberPointer; 2691 return false; 2692 } 2693 2694 /// IsQualificationConversion - Determines whether the conversion from 2695 /// an rvalue of type FromType to ToType is a qualification conversion 2696 /// (C++ 4.4). 2697 /// 2698 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate 2699 /// when the qualification conversion involves a change in the Objective-C 2700 /// object lifetime. 2701 bool 2702 Sema::IsQualificationConversion(QualType FromType, QualType ToType, 2703 bool CStyle, bool &ObjCLifetimeConversion) { 2704 FromType = Context.getCanonicalType(FromType); 2705 ToType = Context.getCanonicalType(ToType); 2706 ObjCLifetimeConversion = false; 2707 2708 // If FromType and ToType are the same type, this is not a 2709 // qualification conversion. 2710 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType()) 2711 return false; 2712 2713 // (C++ 4.4p4): 2714 // A conversion can add cv-qualifiers at levels other than the first 2715 // in multi-level pointers, subject to the following rules: [...] 2716 bool PreviousToQualsIncludeConst = true; 2717 bool UnwrappedAnyPointer = false; 2718 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) { 2719 // Within each iteration of the loop, we check the qualifiers to 2720 // determine if this still looks like a qualification 2721 // conversion. Then, if all is well, we unwrap one more level of 2722 // pointers or pointers-to-members and do it all again 2723 // until there are no more pointers or pointers-to-members left to 2724 // unwrap. 2725 UnwrappedAnyPointer = true; 2726 2727 Qualifiers FromQuals = FromType.getQualifiers(); 2728 Qualifiers ToQuals = ToType.getQualifiers(); 2729 2730 // Objective-C ARC: 2731 // Check Objective-C lifetime conversions. 2732 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() && 2733 UnwrappedAnyPointer) { 2734 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) { 2735 ObjCLifetimeConversion = true; 2736 FromQuals.removeObjCLifetime(); 2737 ToQuals.removeObjCLifetime(); 2738 } else { 2739 // Qualification conversions cannot cast between different 2740 // Objective-C lifetime qualifiers. 2741 return false; 2742 } 2743 } 2744 2745 // Allow addition/removal of GC attributes but not changing GC attributes. 2746 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() && 2747 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) { 2748 FromQuals.removeObjCGCAttr(); 2749 ToQuals.removeObjCGCAttr(); 2750 } 2751 2752 // -- for every j > 0, if const is in cv 1,j then const is in cv 2753 // 2,j, and similarly for volatile. 2754 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals)) 2755 return false; 2756 2757 // -- if the cv 1,j and cv 2,j are different, then const is in 2758 // every cv for 0 < k < j. 2759 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() 2760 && !PreviousToQualsIncludeConst) 2761 return false; 2762 2763 // Keep track of whether all prior cv-qualifiers in the "to" type 2764 // include const. 2765 PreviousToQualsIncludeConst 2766 = PreviousToQualsIncludeConst && ToQuals.hasConst(); 2767 } 2768 2769 // We are left with FromType and ToType being the pointee types 2770 // after unwrapping the original FromType and ToType the same number 2771 // of types. If we unwrapped any pointers, and if FromType and 2772 // ToType have the same unqualified type (since we checked 2773 // qualifiers above), then this is a qualification conversion. 2774 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType); 2775 } 2776 2777 /// \brief - Determine whether this is a conversion from a scalar type to an 2778 /// atomic type. 2779 /// 2780 /// If successful, updates \c SCS's second and third steps in the conversion 2781 /// sequence to finish the conversion. 2782 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, 2783 bool InOverloadResolution, 2784 StandardConversionSequence &SCS, 2785 bool CStyle) { 2786 const AtomicType *ToAtomic = ToType->getAs<AtomicType>(); 2787 if (!ToAtomic) 2788 return false; 2789 2790 StandardConversionSequence InnerSCS; 2791 if (!IsStandardConversion(S, From, ToAtomic->getValueType(), 2792 InOverloadResolution, InnerSCS, 2793 CStyle, /*AllowObjCWritebackConversion=*/false)) 2794 return false; 2795 2796 SCS.Second = InnerSCS.Second; 2797 SCS.setToType(1, InnerSCS.getToType(1)); 2798 SCS.Third = InnerSCS.Third; 2799 SCS.QualificationIncludesObjCLifetime 2800 = InnerSCS.QualificationIncludesObjCLifetime; 2801 SCS.setToType(2, InnerSCS.getToType(2)); 2802 return true; 2803 } 2804 2805 static bool isFirstArgumentCompatibleWithType(ASTContext &Context, 2806 CXXConstructorDecl *Constructor, 2807 QualType Type) { 2808 const FunctionProtoType *CtorType = 2809 Constructor->getType()->getAs<FunctionProtoType>(); 2810 if (CtorType->getNumArgs() > 0) { 2811 QualType FirstArg = CtorType->getArgType(0); 2812 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType())) 2813 return true; 2814 } 2815 return false; 2816 } 2817 2818 static OverloadingResult 2819 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, 2820 CXXRecordDecl *To, 2821 UserDefinedConversionSequence &User, 2822 OverloadCandidateSet &CandidateSet, 2823 bool AllowExplicit) { 2824 DeclContext::lookup_iterator Con, ConEnd; 2825 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To); 2826 Con != ConEnd; ++Con) { 2827 NamedDecl *D = *Con; 2828 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2829 2830 // Find the constructor (which may be a template). 2831 CXXConstructorDecl *Constructor = 0; 2832 FunctionTemplateDecl *ConstructorTmpl 2833 = dyn_cast<FunctionTemplateDecl>(D); 2834 if (ConstructorTmpl) 2835 Constructor 2836 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2837 else 2838 Constructor = cast<CXXConstructorDecl>(D); 2839 2840 bool Usable = !Constructor->isInvalidDecl() && 2841 S.isInitListConstructor(Constructor) && 2842 (AllowExplicit || !Constructor->isExplicit()); 2843 if (Usable) { 2844 // If the first argument is (a reference to) the target type, 2845 // suppress conversions. 2846 bool SuppressUserConversions = 2847 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType); 2848 if (ConstructorTmpl) 2849 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2850 /*ExplicitArgs*/ 0, 2851 From, CandidateSet, 2852 SuppressUserConversions); 2853 else 2854 S.AddOverloadCandidate(Constructor, FoundDecl, 2855 From, CandidateSet, 2856 SuppressUserConversions); 2857 } 2858 } 2859 2860 bool HadMultipleCandidates = (CandidateSet.size() > 1); 2861 2862 OverloadCandidateSet::iterator Best; 2863 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 2864 case OR_Success: { 2865 // Record the standard conversion we used and the conversion function. 2866 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function); 2867 S.MarkFunctionReferenced(From->getLocStart(), Constructor); 2868 2869 QualType ThisType = Constructor->getThisType(S.Context); 2870 // Initializer lists don't have conversions as such. 2871 User.Before.setAsIdentityConversion(); 2872 User.HadMultipleCandidates = HadMultipleCandidates; 2873 User.ConversionFunction = Constructor; 2874 User.FoundConversionFunction = Best->FoundDecl; 2875 User.After.setAsIdentityConversion(); 2876 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 2877 User.After.setAllToTypes(ToType); 2878 return OR_Success; 2879 } 2880 2881 case OR_No_Viable_Function: 2882 return OR_No_Viable_Function; 2883 case OR_Deleted: 2884 return OR_Deleted; 2885 case OR_Ambiguous: 2886 return OR_Ambiguous; 2887 } 2888 2889 llvm_unreachable("Invalid OverloadResult!"); 2890 } 2891 2892 /// Determines whether there is a user-defined conversion sequence 2893 /// (C++ [over.ics.user]) that converts expression From to the type 2894 /// ToType. If such a conversion exists, User will contain the 2895 /// user-defined conversion sequence that performs such a conversion 2896 /// and this routine will return true. Otherwise, this routine returns 2897 /// false and User is unspecified. 2898 /// 2899 /// \param AllowExplicit true if the conversion should consider C++0x 2900 /// "explicit" conversion functions as well as non-explicit conversion 2901 /// functions (C++0x [class.conv.fct]p2). 2902 static OverloadingResult 2903 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, 2904 UserDefinedConversionSequence &User, 2905 OverloadCandidateSet &CandidateSet, 2906 bool AllowExplicit) { 2907 // Whether we will only visit constructors. 2908 bool ConstructorsOnly = false; 2909 2910 // If the type we are conversion to is a class type, enumerate its 2911 // constructors. 2912 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) { 2913 // C++ [over.match.ctor]p1: 2914 // When objects of class type are direct-initialized (8.5), or 2915 // copy-initialized from an expression of the same or a 2916 // derived class type (8.5), overload resolution selects the 2917 // constructor. [...] For copy-initialization, the candidate 2918 // functions are all the converting constructors (12.3.1) of 2919 // that class. The argument list is the expression-list within 2920 // the parentheses of the initializer. 2921 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) || 2922 (From->getType()->getAs<RecordType>() && 2923 S.IsDerivedFrom(From->getType(), ToType))) 2924 ConstructorsOnly = true; 2925 2926 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag()); 2927 // RequireCompleteType may have returned true due to some invalid decl 2928 // during template instantiation, but ToType may be complete enough now 2929 // to try to recover. 2930 if (ToType->isIncompleteType()) { 2931 // We're not going to find any constructors. 2932 } else if (CXXRecordDecl *ToRecordDecl 2933 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) { 2934 2935 Expr **Args = &From; 2936 unsigned NumArgs = 1; 2937 bool ListInitializing = false; 2938 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) { 2939 // But first, see if there is an init-list-contructor that will work. 2940 OverloadingResult Result = IsInitializerListConstructorConversion( 2941 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit); 2942 if (Result != OR_No_Viable_Function) 2943 return Result; 2944 // Never mind. 2945 CandidateSet.clear(); 2946 2947 // If we're list-initializing, we pass the individual elements as 2948 // arguments, not the entire list. 2949 Args = InitList->getInits(); 2950 NumArgs = InitList->getNumInits(); 2951 ListInitializing = true; 2952 } 2953 2954 DeclContext::lookup_iterator Con, ConEnd; 2955 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl); 2956 Con != ConEnd; ++Con) { 2957 NamedDecl *D = *Con; 2958 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess()); 2959 2960 // Find the constructor (which may be a template). 2961 CXXConstructorDecl *Constructor = 0; 2962 FunctionTemplateDecl *ConstructorTmpl 2963 = dyn_cast<FunctionTemplateDecl>(D); 2964 if (ConstructorTmpl) 2965 Constructor 2966 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl()); 2967 else 2968 Constructor = cast<CXXConstructorDecl>(D); 2969 2970 bool Usable = !Constructor->isInvalidDecl(); 2971 if (ListInitializing) 2972 Usable = Usable && (AllowExplicit || !Constructor->isExplicit()); 2973 else 2974 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit); 2975 if (Usable) { 2976 bool SuppressUserConversions = !ConstructorsOnly; 2977 if (SuppressUserConversions && ListInitializing) { 2978 SuppressUserConversions = false; 2979 if (NumArgs == 1) { 2980 // If the first argument is (a reference to) the target type, 2981 // suppress conversions. 2982 SuppressUserConversions = isFirstArgumentCompatibleWithType( 2983 S.Context, Constructor, ToType); 2984 } 2985 } 2986 if (ConstructorTmpl) 2987 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl, 2988 /*ExplicitArgs*/ 0, 2989 llvm::makeArrayRef(Args, NumArgs), 2990 CandidateSet, SuppressUserConversions); 2991 else 2992 // Allow one user-defined conversion when user specifies a 2993 // From->ToType conversion via an static cast (c-style, etc). 2994 S.AddOverloadCandidate(Constructor, FoundDecl, 2995 llvm::makeArrayRef(Args, NumArgs), 2996 CandidateSet, SuppressUserConversions); 2997 } 2998 } 2999 } 3000 } 3001 3002 // Enumerate conversion functions, if we're allowed to. 3003 if (ConstructorsOnly || isa<InitListExpr>(From)) { 3004 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 3005 S.PDiag(0) << From->getSourceRange())) { 3006 // No conversion functions from incomplete types. 3007 } else if (const RecordType *FromRecordType 3008 = From->getType()->getAs<RecordType>()) { 3009 if (CXXRecordDecl *FromRecordDecl 3010 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) { 3011 // Add all of the conversion functions as candidates. 3012 const UnresolvedSetImpl *Conversions 3013 = FromRecordDecl->getVisibleConversionFunctions(); 3014 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 3015 E = Conversions->end(); I != E; ++I) { 3016 DeclAccessPair FoundDecl = I.getPair(); 3017 NamedDecl *D = FoundDecl.getDecl(); 3018 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext()); 3019 if (isa<UsingShadowDecl>(D)) 3020 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3021 3022 CXXConversionDecl *Conv; 3023 FunctionTemplateDecl *ConvTemplate; 3024 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D))) 3025 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3026 else 3027 Conv = cast<CXXConversionDecl>(D); 3028 3029 if (AllowExplicit || !Conv->isExplicit()) { 3030 if (ConvTemplate) 3031 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl, 3032 ActingContext, From, ToType, 3033 CandidateSet); 3034 else 3035 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, 3036 From, ToType, CandidateSet); 3037 } 3038 } 3039 } 3040 } 3041 3042 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3043 3044 OverloadCandidateSet::iterator Best; 3045 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) { 3046 case OR_Success: 3047 // Record the standard conversion we used and the conversion function. 3048 if (CXXConstructorDecl *Constructor 3049 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 3050 S.MarkFunctionReferenced(From->getLocStart(), Constructor); 3051 3052 // C++ [over.ics.user]p1: 3053 // If the user-defined conversion is specified by a 3054 // constructor (12.3.1), the initial standard conversion 3055 // sequence converts the source type to the type required by 3056 // the argument of the constructor. 3057 // 3058 QualType ThisType = Constructor->getThisType(S.Context); 3059 if (isa<InitListExpr>(From)) { 3060 // Initializer lists don't have conversions as such. 3061 User.Before.setAsIdentityConversion(); 3062 } else { 3063 if (Best->Conversions[0].isEllipsis()) 3064 User.EllipsisConversion = true; 3065 else { 3066 User.Before = Best->Conversions[0].Standard; 3067 User.EllipsisConversion = false; 3068 } 3069 } 3070 User.HadMultipleCandidates = HadMultipleCandidates; 3071 User.ConversionFunction = Constructor; 3072 User.FoundConversionFunction = Best->FoundDecl; 3073 User.After.setAsIdentityConversion(); 3074 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType()); 3075 User.After.setAllToTypes(ToType); 3076 return OR_Success; 3077 } 3078 if (CXXConversionDecl *Conversion 3079 = dyn_cast<CXXConversionDecl>(Best->Function)) { 3080 S.MarkFunctionReferenced(From->getLocStart(), Conversion); 3081 3082 // C++ [over.ics.user]p1: 3083 // 3084 // [...] If the user-defined conversion is specified by a 3085 // conversion function (12.3.2), the initial standard 3086 // conversion sequence converts the source type to the 3087 // implicit object parameter of the conversion function. 3088 User.Before = Best->Conversions[0].Standard; 3089 User.HadMultipleCandidates = HadMultipleCandidates; 3090 User.ConversionFunction = Conversion; 3091 User.FoundConversionFunction = Best->FoundDecl; 3092 User.EllipsisConversion = false; 3093 3094 // C++ [over.ics.user]p2: 3095 // The second standard conversion sequence converts the 3096 // result of the user-defined conversion to the target type 3097 // for the sequence. Since an implicit conversion sequence 3098 // is an initialization, the special rules for 3099 // initialization by user-defined conversion apply when 3100 // selecting the best user-defined conversion for a 3101 // user-defined conversion sequence (see 13.3.3 and 3102 // 13.3.3.1). 3103 User.After = Best->FinalConversion; 3104 return OR_Success; 3105 } 3106 llvm_unreachable("Not a constructor or conversion function?"); 3107 3108 case OR_No_Viable_Function: 3109 return OR_No_Viable_Function; 3110 case OR_Deleted: 3111 // No conversion here! We're done. 3112 return OR_Deleted; 3113 3114 case OR_Ambiguous: 3115 return OR_Ambiguous; 3116 } 3117 3118 llvm_unreachable("Invalid OverloadResult!"); 3119 } 3120 3121 bool 3122 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) { 3123 ImplicitConversionSequence ICS; 3124 OverloadCandidateSet CandidateSet(From->getExprLoc()); 3125 OverloadingResult OvResult = 3126 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined, 3127 CandidateSet, false); 3128 if (OvResult == OR_Ambiguous) 3129 Diag(From->getLocStart(), 3130 diag::err_typecheck_ambiguous_condition) 3131 << From->getType() << ToType << From->getSourceRange(); 3132 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) 3133 Diag(From->getLocStart(), 3134 diag::err_typecheck_nonviable_condition) 3135 << From->getType() << ToType << From->getSourceRange(); 3136 else 3137 return false; 3138 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From); 3139 return true; 3140 } 3141 3142 /// \brief Compare the user-defined conversion functions or constructors 3143 /// of two user-defined conversion sequences to determine whether any ordering 3144 /// is possible. 3145 static ImplicitConversionSequence::CompareKind 3146 compareConversionFunctions(Sema &S, 3147 FunctionDecl *Function1, 3148 FunctionDecl *Function2) { 3149 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x) 3150 return ImplicitConversionSequence::Indistinguishable; 3151 3152 // Objective-C++: 3153 // If both conversion functions are implicitly-declared conversions from 3154 // a lambda closure type to a function pointer and a block pointer, 3155 // respectively, always prefer the conversion to a function pointer, 3156 // because the function pointer is more lightweight and is more likely 3157 // to keep code working. 3158 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1); 3159 if (!Conv1) 3160 return ImplicitConversionSequence::Indistinguishable; 3161 3162 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2); 3163 if (!Conv2) 3164 return ImplicitConversionSequence::Indistinguishable; 3165 3166 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) { 3167 bool Block1 = Conv1->getConversionType()->isBlockPointerType(); 3168 bool Block2 = Conv2->getConversionType()->isBlockPointerType(); 3169 if (Block1 != Block2) 3170 return Block1? ImplicitConversionSequence::Worse 3171 : ImplicitConversionSequence::Better; 3172 } 3173 3174 return ImplicitConversionSequence::Indistinguishable; 3175 } 3176 3177 /// CompareImplicitConversionSequences - Compare two implicit 3178 /// conversion sequences to determine whether one is better than the 3179 /// other or if they are indistinguishable (C++ 13.3.3.2). 3180 static ImplicitConversionSequence::CompareKind 3181 CompareImplicitConversionSequences(Sema &S, 3182 const ImplicitConversionSequence& ICS1, 3183 const ImplicitConversionSequence& ICS2) 3184 { 3185 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 3186 // conversion sequences (as defined in 13.3.3.1) 3187 // -- a standard conversion sequence (13.3.3.1.1) is a better 3188 // conversion sequence than a user-defined conversion sequence or 3189 // an ellipsis conversion sequence, and 3190 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 3191 // conversion sequence than an ellipsis conversion sequence 3192 // (13.3.3.1.3). 3193 // 3194 // C++0x [over.best.ics]p10: 3195 // For the purpose of ranking implicit conversion sequences as 3196 // described in 13.3.3.2, the ambiguous conversion sequence is 3197 // treated as a user-defined sequence that is indistinguishable 3198 // from any other user-defined conversion sequence. 3199 if (ICS1.getKindRank() < ICS2.getKindRank()) 3200 return ImplicitConversionSequence::Better; 3201 if (ICS2.getKindRank() < ICS1.getKindRank()) 3202 return ImplicitConversionSequence::Worse; 3203 3204 // The following checks require both conversion sequences to be of 3205 // the same kind. 3206 if (ICS1.getKind() != ICS2.getKind()) 3207 return ImplicitConversionSequence::Indistinguishable; 3208 3209 ImplicitConversionSequence::CompareKind Result = 3210 ImplicitConversionSequence::Indistinguishable; 3211 3212 // Two implicit conversion sequences of the same form are 3213 // indistinguishable conversion sequences unless one of the 3214 // following rules apply: (C++ 13.3.3.2p3): 3215 if (ICS1.isStandard()) 3216 Result = CompareStandardConversionSequences(S, 3217 ICS1.Standard, ICS2.Standard); 3218 else if (ICS1.isUserDefined()) { 3219 // User-defined conversion sequence U1 is a better conversion 3220 // sequence than another user-defined conversion sequence U2 if 3221 // they contain the same user-defined conversion function or 3222 // constructor and if the second standard conversion sequence of 3223 // U1 is better than the second standard conversion sequence of 3224 // U2 (C++ 13.3.3.2p3). 3225 if (ICS1.UserDefined.ConversionFunction == 3226 ICS2.UserDefined.ConversionFunction) 3227 Result = CompareStandardConversionSequences(S, 3228 ICS1.UserDefined.After, 3229 ICS2.UserDefined.After); 3230 else 3231 Result = compareConversionFunctions(S, 3232 ICS1.UserDefined.ConversionFunction, 3233 ICS2.UserDefined.ConversionFunction); 3234 } 3235 3236 // List-initialization sequence L1 is a better conversion sequence than 3237 // list-initialization sequence L2 if L1 converts to std::initializer_list<X> 3238 // for some X and L2 does not. 3239 if (Result == ImplicitConversionSequence::Indistinguishable && 3240 !ICS1.isBad() && 3241 ICS1.isListInitializationSequence() && 3242 ICS2.isListInitializationSequence()) { 3243 if (ICS1.isStdInitializerListElement() && 3244 !ICS2.isStdInitializerListElement()) 3245 return ImplicitConversionSequence::Better; 3246 if (!ICS1.isStdInitializerListElement() && 3247 ICS2.isStdInitializerListElement()) 3248 return ImplicitConversionSequence::Worse; 3249 } 3250 3251 return Result; 3252 } 3253 3254 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) { 3255 while (Context.UnwrapSimilarPointerTypes(T1, T2)) { 3256 Qualifiers Quals; 3257 T1 = Context.getUnqualifiedArrayType(T1, Quals); 3258 T2 = Context.getUnqualifiedArrayType(T2, Quals); 3259 } 3260 3261 return Context.hasSameUnqualifiedType(T1, T2); 3262 } 3263 3264 // Per 13.3.3.2p3, compare the given standard conversion sequences to 3265 // determine if one is a proper subset of the other. 3266 static ImplicitConversionSequence::CompareKind 3267 compareStandardConversionSubsets(ASTContext &Context, 3268 const StandardConversionSequence& SCS1, 3269 const StandardConversionSequence& SCS2) { 3270 ImplicitConversionSequence::CompareKind Result 3271 = ImplicitConversionSequence::Indistinguishable; 3272 3273 // the identity conversion sequence is considered to be a subsequence of 3274 // any non-identity conversion sequence 3275 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion()) 3276 return ImplicitConversionSequence::Better; 3277 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion()) 3278 return ImplicitConversionSequence::Worse; 3279 3280 if (SCS1.Second != SCS2.Second) { 3281 if (SCS1.Second == ICK_Identity) 3282 Result = ImplicitConversionSequence::Better; 3283 else if (SCS2.Second == ICK_Identity) 3284 Result = ImplicitConversionSequence::Worse; 3285 else 3286 return ImplicitConversionSequence::Indistinguishable; 3287 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1))) 3288 return ImplicitConversionSequence::Indistinguishable; 3289 3290 if (SCS1.Third == SCS2.Third) { 3291 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result 3292 : ImplicitConversionSequence::Indistinguishable; 3293 } 3294 3295 if (SCS1.Third == ICK_Identity) 3296 return Result == ImplicitConversionSequence::Worse 3297 ? ImplicitConversionSequence::Indistinguishable 3298 : ImplicitConversionSequence::Better; 3299 3300 if (SCS2.Third == ICK_Identity) 3301 return Result == ImplicitConversionSequence::Better 3302 ? ImplicitConversionSequence::Indistinguishable 3303 : ImplicitConversionSequence::Worse; 3304 3305 return ImplicitConversionSequence::Indistinguishable; 3306 } 3307 3308 /// \brief Determine whether one of the given reference bindings is better 3309 /// than the other based on what kind of bindings they are. 3310 static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, 3311 const StandardConversionSequence &SCS2) { 3312 // C++0x [over.ics.rank]p3b4: 3313 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an 3314 // implicit object parameter of a non-static member function declared 3315 // without a ref-qualifier, and *either* S1 binds an rvalue reference 3316 // to an rvalue and S2 binds an lvalue reference *or S1 binds an 3317 // lvalue reference to a function lvalue and S2 binds an rvalue 3318 // reference*. 3319 // 3320 // FIXME: Rvalue references. We're going rogue with the above edits, 3321 // because the semantics in the current C++0x working paper (N3225 at the 3322 // time of this writing) break the standard definition of std::forward 3323 // and std::reference_wrapper when dealing with references to functions. 3324 // Proposed wording changes submitted to CWG for consideration. 3325 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier || 3326 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier) 3327 return false; 3328 3329 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue && 3330 SCS2.IsLvalueReference) || 3331 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue && 3332 !SCS2.IsLvalueReference); 3333 } 3334 3335 /// CompareStandardConversionSequences - Compare two standard 3336 /// conversion sequences to determine whether one is better than the 3337 /// other or if they are indistinguishable (C++ 13.3.3.2p3). 3338 static ImplicitConversionSequence::CompareKind 3339 CompareStandardConversionSequences(Sema &S, 3340 const StandardConversionSequence& SCS1, 3341 const StandardConversionSequence& SCS2) 3342 { 3343 // Standard conversion sequence S1 is a better conversion sequence 3344 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 3345 3346 // -- S1 is a proper subsequence of S2 (comparing the conversion 3347 // sequences in the canonical form defined by 13.3.3.1.1, 3348 // excluding any Lvalue Transformation; the identity conversion 3349 // sequence is considered to be a subsequence of any 3350 // non-identity conversion sequence) or, if not that, 3351 if (ImplicitConversionSequence::CompareKind CK 3352 = compareStandardConversionSubsets(S.Context, SCS1, SCS2)) 3353 return CK; 3354 3355 // -- the rank of S1 is better than the rank of S2 (by the rules 3356 // defined below), or, if not that, 3357 ImplicitConversionRank Rank1 = SCS1.getRank(); 3358 ImplicitConversionRank Rank2 = SCS2.getRank(); 3359 if (Rank1 < Rank2) 3360 return ImplicitConversionSequence::Better; 3361 else if (Rank2 < Rank1) 3362 return ImplicitConversionSequence::Worse; 3363 3364 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 3365 // are indistinguishable unless one of the following rules 3366 // applies: 3367 3368 // A conversion that is not a conversion of a pointer, or 3369 // pointer to member, to bool is better than another conversion 3370 // that is such a conversion. 3371 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 3372 return SCS2.isPointerConversionToBool() 3373 ? ImplicitConversionSequence::Better 3374 : ImplicitConversionSequence::Worse; 3375 3376 // C++ [over.ics.rank]p4b2: 3377 // 3378 // If class B is derived directly or indirectly from class A, 3379 // conversion of B* to A* is better than conversion of B* to 3380 // void*, and conversion of A* to void* is better than conversion 3381 // of B* to void*. 3382 bool SCS1ConvertsToVoid 3383 = SCS1.isPointerConversionToVoidPointer(S.Context); 3384 bool SCS2ConvertsToVoid 3385 = SCS2.isPointerConversionToVoidPointer(S.Context); 3386 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 3387 // Exactly one of the conversion sequences is a conversion to 3388 // a void pointer; it's the worse conversion. 3389 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 3390 : ImplicitConversionSequence::Worse; 3391 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 3392 // Neither conversion sequence converts to a void pointer; compare 3393 // their derived-to-base conversions. 3394 if (ImplicitConversionSequence::CompareKind DerivedCK 3395 = CompareDerivedToBaseConversions(S, SCS1, SCS2)) 3396 return DerivedCK; 3397 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid && 3398 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) { 3399 // Both conversion sequences are conversions to void 3400 // pointers. Compare the source types to determine if there's an 3401 // inheritance relationship in their sources. 3402 QualType FromType1 = SCS1.getFromType(); 3403 QualType FromType2 = SCS2.getFromType(); 3404 3405 // Adjust the types we're converting from via the array-to-pointer 3406 // conversion, if we need to. 3407 if (SCS1.First == ICK_Array_To_Pointer) 3408 FromType1 = S.Context.getArrayDecayedType(FromType1); 3409 if (SCS2.First == ICK_Array_To_Pointer) 3410 FromType2 = S.Context.getArrayDecayedType(FromType2); 3411 3412 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType(); 3413 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType(); 3414 3415 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3416 return ImplicitConversionSequence::Better; 3417 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3418 return ImplicitConversionSequence::Worse; 3419 3420 // Objective-C++: If one interface is more specific than the 3421 // other, it is the better one. 3422 const ObjCObjectPointerType* FromObjCPtr1 3423 = FromType1->getAs<ObjCObjectPointerType>(); 3424 const ObjCObjectPointerType* FromObjCPtr2 3425 = FromType2->getAs<ObjCObjectPointerType>(); 3426 if (FromObjCPtr1 && FromObjCPtr2) { 3427 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1, 3428 FromObjCPtr2); 3429 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2, 3430 FromObjCPtr1); 3431 if (AssignLeft != AssignRight) { 3432 return AssignLeft? ImplicitConversionSequence::Better 3433 : ImplicitConversionSequence::Worse; 3434 } 3435 } 3436 } 3437 3438 // Compare based on qualification conversions (C++ 13.3.3.2p3, 3439 // bullet 3). 3440 if (ImplicitConversionSequence::CompareKind QualCK 3441 = CompareQualificationConversions(S, SCS1, SCS2)) 3442 return QualCK; 3443 3444 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 3445 // Check for a better reference binding based on the kind of bindings. 3446 if (isBetterReferenceBindingKind(SCS1, SCS2)) 3447 return ImplicitConversionSequence::Better; 3448 else if (isBetterReferenceBindingKind(SCS2, SCS1)) 3449 return ImplicitConversionSequence::Worse; 3450 3451 // C++ [over.ics.rank]p3b4: 3452 // -- S1 and S2 are reference bindings (8.5.3), and the types to 3453 // which the references refer are the same type except for 3454 // top-level cv-qualifiers, and the type to which the reference 3455 // initialized by S2 refers is more cv-qualified than the type 3456 // to which the reference initialized by S1 refers. 3457 QualType T1 = SCS1.getToType(2); 3458 QualType T2 = SCS2.getToType(2); 3459 T1 = S.Context.getCanonicalType(T1); 3460 T2 = S.Context.getCanonicalType(T2); 3461 Qualifiers T1Quals, T2Quals; 3462 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3463 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3464 if (UnqualT1 == UnqualT2) { 3465 // Objective-C++ ARC: If the references refer to objects with different 3466 // lifetimes, prefer bindings that don't change lifetime. 3467 if (SCS1.ObjCLifetimeConversionBinding != 3468 SCS2.ObjCLifetimeConversionBinding) { 3469 return SCS1.ObjCLifetimeConversionBinding 3470 ? ImplicitConversionSequence::Worse 3471 : ImplicitConversionSequence::Better; 3472 } 3473 3474 // If the type is an array type, promote the element qualifiers to the 3475 // type for comparison. 3476 if (isa<ArrayType>(T1) && T1Quals) 3477 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3478 if (isa<ArrayType>(T2) && T2Quals) 3479 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3480 if (T2.isMoreQualifiedThan(T1)) 3481 return ImplicitConversionSequence::Better; 3482 else if (T1.isMoreQualifiedThan(T2)) 3483 return ImplicitConversionSequence::Worse; 3484 } 3485 } 3486 3487 // In Microsoft mode, prefer an integral conversion to a 3488 // floating-to-integral conversion if the integral conversion 3489 // is between types of the same size. 3490 // For example: 3491 // void f(float); 3492 // void f(int); 3493 // int main { 3494 // long a; 3495 // f(a); 3496 // } 3497 // Here, MSVC will call f(int) instead of generating a compile error 3498 // as clang will do in standard mode. 3499 if (S.getLangOpts().MicrosoftMode && 3500 SCS1.Second == ICK_Integral_Conversion && 3501 SCS2.Second == ICK_Floating_Integral && 3502 S.Context.getTypeSize(SCS1.getFromType()) == 3503 S.Context.getTypeSize(SCS1.getToType(2))) 3504 return ImplicitConversionSequence::Better; 3505 3506 return ImplicitConversionSequence::Indistinguishable; 3507 } 3508 3509 /// CompareQualificationConversions - Compares two standard conversion 3510 /// sequences to determine whether they can be ranked based on their 3511 /// qualification conversions (C++ 13.3.3.2p3 bullet 3). 3512 ImplicitConversionSequence::CompareKind 3513 CompareQualificationConversions(Sema &S, 3514 const StandardConversionSequence& SCS1, 3515 const StandardConversionSequence& SCS2) { 3516 // C++ 13.3.3.2p3: 3517 // -- S1 and S2 differ only in their qualification conversion and 3518 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 3519 // cv-qualification signature of type T1 is a proper subset of 3520 // the cv-qualification signature of type T2, and S1 is not the 3521 // deprecated string literal array-to-pointer conversion (4.2). 3522 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 3523 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 3524 return ImplicitConversionSequence::Indistinguishable; 3525 3526 // FIXME: the example in the standard doesn't use a qualification 3527 // conversion (!) 3528 QualType T1 = SCS1.getToType(2); 3529 QualType T2 = SCS2.getToType(2); 3530 T1 = S.Context.getCanonicalType(T1); 3531 T2 = S.Context.getCanonicalType(T2); 3532 Qualifiers T1Quals, T2Quals; 3533 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals); 3534 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals); 3535 3536 // If the types are the same, we won't learn anything by unwrapped 3537 // them. 3538 if (UnqualT1 == UnqualT2) 3539 return ImplicitConversionSequence::Indistinguishable; 3540 3541 // If the type is an array type, promote the element qualifiers to the type 3542 // for comparison. 3543 if (isa<ArrayType>(T1) && T1Quals) 3544 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals); 3545 if (isa<ArrayType>(T2) && T2Quals) 3546 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals); 3547 3548 ImplicitConversionSequence::CompareKind Result 3549 = ImplicitConversionSequence::Indistinguishable; 3550 3551 // Objective-C++ ARC: 3552 // Prefer qualification conversions not involving a change in lifetime 3553 // to qualification conversions that do not change lifetime. 3554 if (SCS1.QualificationIncludesObjCLifetime != 3555 SCS2.QualificationIncludesObjCLifetime) { 3556 Result = SCS1.QualificationIncludesObjCLifetime 3557 ? ImplicitConversionSequence::Worse 3558 : ImplicitConversionSequence::Better; 3559 } 3560 3561 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) { 3562 // Within each iteration of the loop, we check the qualifiers to 3563 // determine if this still looks like a qualification 3564 // conversion. Then, if all is well, we unwrap one more level of 3565 // pointers or pointers-to-members and do it all again 3566 // until there are no more pointers or pointers-to-members left 3567 // to unwrap. This essentially mimics what 3568 // IsQualificationConversion does, but here we're checking for a 3569 // strict subset of qualifiers. 3570 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 3571 // The qualifiers are the same, so this doesn't tell us anything 3572 // about how the sequences rank. 3573 ; 3574 else if (T2.isMoreQualifiedThan(T1)) { 3575 // T1 has fewer qualifiers, so it could be the better sequence. 3576 if (Result == ImplicitConversionSequence::Worse) 3577 // Neither has qualifiers that are a subset of the other's 3578 // qualifiers. 3579 return ImplicitConversionSequence::Indistinguishable; 3580 3581 Result = ImplicitConversionSequence::Better; 3582 } else if (T1.isMoreQualifiedThan(T2)) { 3583 // T2 has fewer qualifiers, so it could be the better sequence. 3584 if (Result == ImplicitConversionSequence::Better) 3585 // Neither has qualifiers that are a subset of the other's 3586 // qualifiers. 3587 return ImplicitConversionSequence::Indistinguishable; 3588 3589 Result = ImplicitConversionSequence::Worse; 3590 } else { 3591 // Qualifiers are disjoint. 3592 return ImplicitConversionSequence::Indistinguishable; 3593 } 3594 3595 // If the types after this point are equivalent, we're done. 3596 if (S.Context.hasSameUnqualifiedType(T1, T2)) 3597 break; 3598 } 3599 3600 // Check that the winning standard conversion sequence isn't using 3601 // the deprecated string literal array to pointer conversion. 3602 switch (Result) { 3603 case ImplicitConversionSequence::Better: 3604 if (SCS1.DeprecatedStringLiteralToCharPtr) 3605 Result = ImplicitConversionSequence::Indistinguishable; 3606 break; 3607 3608 case ImplicitConversionSequence::Indistinguishable: 3609 break; 3610 3611 case ImplicitConversionSequence::Worse: 3612 if (SCS2.DeprecatedStringLiteralToCharPtr) 3613 Result = ImplicitConversionSequence::Indistinguishable; 3614 break; 3615 } 3616 3617 return Result; 3618 } 3619 3620 /// CompareDerivedToBaseConversions - Compares two standard conversion 3621 /// sequences to determine whether they can be ranked based on their 3622 /// various kinds of derived-to-base conversions (C++ 3623 /// [over.ics.rank]p4b3). As part of these checks, we also look at 3624 /// conversions between Objective-C interface types. 3625 ImplicitConversionSequence::CompareKind 3626 CompareDerivedToBaseConversions(Sema &S, 3627 const StandardConversionSequence& SCS1, 3628 const StandardConversionSequence& SCS2) { 3629 QualType FromType1 = SCS1.getFromType(); 3630 QualType ToType1 = SCS1.getToType(1); 3631 QualType FromType2 = SCS2.getFromType(); 3632 QualType ToType2 = SCS2.getToType(1); 3633 3634 // Adjust the types we're converting from via the array-to-pointer 3635 // conversion, if we need to. 3636 if (SCS1.First == ICK_Array_To_Pointer) 3637 FromType1 = S.Context.getArrayDecayedType(FromType1); 3638 if (SCS2.First == ICK_Array_To_Pointer) 3639 FromType2 = S.Context.getArrayDecayedType(FromType2); 3640 3641 // Canonicalize all of the types. 3642 FromType1 = S.Context.getCanonicalType(FromType1); 3643 ToType1 = S.Context.getCanonicalType(ToType1); 3644 FromType2 = S.Context.getCanonicalType(FromType2); 3645 ToType2 = S.Context.getCanonicalType(ToType2); 3646 3647 // C++ [over.ics.rank]p4b3: 3648 // 3649 // If class B is derived directly or indirectly from class A and 3650 // class C is derived directly or indirectly from B, 3651 // 3652 // Compare based on pointer conversions. 3653 if (SCS1.Second == ICK_Pointer_Conversion && 3654 SCS2.Second == ICK_Pointer_Conversion && 3655 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 3656 FromType1->isPointerType() && FromType2->isPointerType() && 3657 ToType1->isPointerType() && ToType2->isPointerType()) { 3658 QualType FromPointee1 3659 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3660 QualType ToPointee1 3661 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3662 QualType FromPointee2 3663 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3664 QualType ToPointee2 3665 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType(); 3666 3667 // -- conversion of C* to B* is better than conversion of C* to A*, 3668 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3669 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3670 return ImplicitConversionSequence::Better; 3671 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3672 return ImplicitConversionSequence::Worse; 3673 } 3674 3675 // -- conversion of B* to A* is better than conversion of C* to A*, 3676 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 3677 if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3678 return ImplicitConversionSequence::Better; 3679 else if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3680 return ImplicitConversionSequence::Worse; 3681 } 3682 } else if (SCS1.Second == ICK_Pointer_Conversion && 3683 SCS2.Second == ICK_Pointer_Conversion) { 3684 const ObjCObjectPointerType *FromPtr1 3685 = FromType1->getAs<ObjCObjectPointerType>(); 3686 const ObjCObjectPointerType *FromPtr2 3687 = FromType2->getAs<ObjCObjectPointerType>(); 3688 const ObjCObjectPointerType *ToPtr1 3689 = ToType1->getAs<ObjCObjectPointerType>(); 3690 const ObjCObjectPointerType *ToPtr2 3691 = ToType2->getAs<ObjCObjectPointerType>(); 3692 3693 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) { 3694 // Apply the same conversion ranking rules for Objective-C pointer types 3695 // that we do for C++ pointers to class types. However, we employ the 3696 // Objective-C pseudo-subtyping relationship used for assignment of 3697 // Objective-C pointer types. 3698 bool FromAssignLeft 3699 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2); 3700 bool FromAssignRight 3701 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1); 3702 bool ToAssignLeft 3703 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2); 3704 bool ToAssignRight 3705 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1); 3706 3707 // A conversion to an a non-id object pointer type or qualified 'id' 3708 // type is better than a conversion to 'id'. 3709 if (ToPtr1->isObjCIdType() && 3710 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl())) 3711 return ImplicitConversionSequence::Worse; 3712 if (ToPtr2->isObjCIdType() && 3713 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl())) 3714 return ImplicitConversionSequence::Better; 3715 3716 // A conversion to a non-id object pointer type is better than a 3717 // conversion to a qualified 'id' type 3718 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl()) 3719 return ImplicitConversionSequence::Worse; 3720 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl()) 3721 return ImplicitConversionSequence::Better; 3722 3723 // A conversion to an a non-Class object pointer type or qualified 'Class' 3724 // type is better than a conversion to 'Class'. 3725 if (ToPtr1->isObjCClassType() && 3726 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl())) 3727 return ImplicitConversionSequence::Worse; 3728 if (ToPtr2->isObjCClassType() && 3729 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl())) 3730 return ImplicitConversionSequence::Better; 3731 3732 // A conversion to a non-Class object pointer type is better than a 3733 // conversion to a qualified 'Class' type. 3734 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl()) 3735 return ImplicitConversionSequence::Worse; 3736 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl()) 3737 return ImplicitConversionSequence::Better; 3738 3739 // -- "conversion of C* to B* is better than conversion of C* to A*," 3740 if (S.Context.hasSameType(FromType1, FromType2) && 3741 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() && 3742 (ToAssignLeft != ToAssignRight)) 3743 return ToAssignLeft? ImplicitConversionSequence::Worse 3744 : ImplicitConversionSequence::Better; 3745 3746 // -- "conversion of B* to A* is better than conversion of C* to A*," 3747 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) && 3748 (FromAssignLeft != FromAssignRight)) 3749 return FromAssignLeft? ImplicitConversionSequence::Better 3750 : ImplicitConversionSequence::Worse; 3751 } 3752 } 3753 3754 // Ranking of member-pointer types. 3755 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member && 3756 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() && 3757 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) { 3758 const MemberPointerType * FromMemPointer1 = 3759 FromType1->getAs<MemberPointerType>(); 3760 const MemberPointerType * ToMemPointer1 = 3761 ToType1->getAs<MemberPointerType>(); 3762 const MemberPointerType * FromMemPointer2 = 3763 FromType2->getAs<MemberPointerType>(); 3764 const MemberPointerType * ToMemPointer2 = 3765 ToType2->getAs<MemberPointerType>(); 3766 const Type *FromPointeeType1 = FromMemPointer1->getClass(); 3767 const Type *ToPointeeType1 = ToMemPointer1->getClass(); 3768 const Type *FromPointeeType2 = FromMemPointer2->getClass(); 3769 const Type *ToPointeeType2 = ToMemPointer2->getClass(); 3770 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType(); 3771 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType(); 3772 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType(); 3773 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType(); 3774 // conversion of A::* to B::* is better than conversion of A::* to C::*, 3775 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 3776 if (S.IsDerivedFrom(ToPointee1, ToPointee2)) 3777 return ImplicitConversionSequence::Worse; 3778 else if (S.IsDerivedFrom(ToPointee2, ToPointee1)) 3779 return ImplicitConversionSequence::Better; 3780 } 3781 // conversion of B::* to C::* is better than conversion of A::* to C::* 3782 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) { 3783 if (S.IsDerivedFrom(FromPointee1, FromPointee2)) 3784 return ImplicitConversionSequence::Better; 3785 else if (S.IsDerivedFrom(FromPointee2, FromPointee1)) 3786 return ImplicitConversionSequence::Worse; 3787 } 3788 } 3789 3790 if (SCS1.Second == ICK_Derived_To_Base) { 3791 // -- conversion of C to B is better than conversion of C to A, 3792 // -- binding of an expression of type C to a reference of type 3793 // B& is better than binding an expression of type C to a 3794 // reference of type A&, 3795 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3796 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3797 if (S.IsDerivedFrom(ToType1, ToType2)) 3798 return ImplicitConversionSequence::Better; 3799 else if (S.IsDerivedFrom(ToType2, ToType1)) 3800 return ImplicitConversionSequence::Worse; 3801 } 3802 3803 // -- conversion of B to A is better than conversion of C to A. 3804 // -- binding of an expression of type B to a reference of type 3805 // A& is better than binding an expression of type C to a 3806 // reference of type A&, 3807 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) && 3808 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) { 3809 if (S.IsDerivedFrom(FromType2, FromType1)) 3810 return ImplicitConversionSequence::Better; 3811 else if (S.IsDerivedFrom(FromType1, FromType2)) 3812 return ImplicitConversionSequence::Worse; 3813 } 3814 } 3815 3816 return ImplicitConversionSequence::Indistinguishable; 3817 } 3818 3819 /// CompareReferenceRelationship - Compare the two types T1 and T2 to 3820 /// determine whether they are reference-related, 3821 /// reference-compatible, reference-compatible with added 3822 /// qualification, or incompatible, for use in C++ initialization by 3823 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference 3824 /// type, and the first type (T1) is the pointee type of the reference 3825 /// type being initialized. 3826 Sema::ReferenceCompareResult 3827 Sema::CompareReferenceRelationship(SourceLocation Loc, 3828 QualType OrigT1, QualType OrigT2, 3829 bool &DerivedToBase, 3830 bool &ObjCConversion, 3831 bool &ObjCLifetimeConversion) { 3832 assert(!OrigT1->isReferenceType() && 3833 "T1 must be the pointee type of the reference type"); 3834 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type"); 3835 3836 QualType T1 = Context.getCanonicalType(OrigT1); 3837 QualType T2 = Context.getCanonicalType(OrigT2); 3838 Qualifiers T1Quals, T2Quals; 3839 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals); 3840 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals); 3841 3842 // C++ [dcl.init.ref]p4: 3843 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is 3844 // reference-related to "cv2 T2" if T1 is the same type as T2, or 3845 // T1 is a base class of T2. 3846 DerivedToBase = false; 3847 ObjCConversion = false; 3848 ObjCLifetimeConversion = false; 3849 if (UnqualT1 == UnqualT2) { 3850 // Nothing to do. 3851 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) && 3852 IsDerivedFrom(UnqualT2, UnqualT1)) 3853 DerivedToBase = true; 3854 else if (UnqualT1->isObjCObjectOrInterfaceType() && 3855 UnqualT2->isObjCObjectOrInterfaceType() && 3856 Context.canBindObjCObjectType(UnqualT1, UnqualT2)) 3857 ObjCConversion = true; 3858 else 3859 return Ref_Incompatible; 3860 3861 // At this point, we know that T1 and T2 are reference-related (at 3862 // least). 3863 3864 // If the type is an array type, promote the element qualifiers to the type 3865 // for comparison. 3866 if (isa<ArrayType>(T1) && T1Quals) 3867 T1 = Context.getQualifiedType(UnqualT1, T1Quals); 3868 if (isa<ArrayType>(T2) && T2Quals) 3869 T2 = Context.getQualifiedType(UnqualT2, T2Quals); 3870 3871 // C++ [dcl.init.ref]p4: 3872 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is 3873 // reference-related to T2 and cv1 is the same cv-qualification 3874 // as, or greater cv-qualification than, cv2. For purposes of 3875 // overload resolution, cases for which cv1 is greater 3876 // cv-qualification than cv2 are identified as 3877 // reference-compatible with added qualification (see 13.3.3.2). 3878 // 3879 // Note that we also require equivalence of Objective-C GC and address-space 3880 // qualifiers when performing these computations, so that e.g., an int in 3881 // address space 1 is not reference-compatible with an int in address 3882 // space 2. 3883 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() && 3884 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) { 3885 T1Quals.removeObjCLifetime(); 3886 T2Quals.removeObjCLifetime(); 3887 ObjCLifetimeConversion = true; 3888 } 3889 3890 if (T1Quals == T2Quals) 3891 return Ref_Compatible; 3892 else if (T1Quals.compatiblyIncludes(T2Quals)) 3893 return Ref_Compatible_With_Added_Qualification; 3894 else 3895 return Ref_Related; 3896 } 3897 3898 /// \brief Look for a user-defined conversion to an value reference-compatible 3899 /// with DeclType. Return true if something definite is found. 3900 static bool 3901 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, 3902 QualType DeclType, SourceLocation DeclLoc, 3903 Expr *Init, QualType T2, bool AllowRvalues, 3904 bool AllowExplicit) { 3905 assert(T2->isRecordType() && "Can only find conversions of record types."); 3906 CXXRecordDecl *T2RecordDecl 3907 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl()); 3908 3909 OverloadCandidateSet CandidateSet(DeclLoc); 3910 const UnresolvedSetImpl *Conversions 3911 = T2RecordDecl->getVisibleConversionFunctions(); 3912 for (UnresolvedSetImpl::iterator I = Conversions->begin(), 3913 E = Conversions->end(); I != E; ++I) { 3914 NamedDecl *D = *I; 3915 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext()); 3916 if (isa<UsingShadowDecl>(D)) 3917 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 3918 3919 FunctionTemplateDecl *ConvTemplate 3920 = dyn_cast<FunctionTemplateDecl>(D); 3921 CXXConversionDecl *Conv; 3922 if (ConvTemplate) 3923 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl()); 3924 else 3925 Conv = cast<CXXConversionDecl>(D); 3926 3927 // If this is an explicit conversion, and we're not allowed to consider 3928 // explicit conversions, skip it. 3929 if (!AllowExplicit && Conv->isExplicit()) 3930 continue; 3931 3932 if (AllowRvalues) { 3933 bool DerivedToBase = false; 3934 bool ObjCConversion = false; 3935 bool ObjCLifetimeConversion = false; 3936 3937 // If we are initializing an rvalue reference, don't permit conversion 3938 // functions that return lvalues. 3939 if (!ConvTemplate && DeclType->isRValueReferenceType()) { 3940 const ReferenceType *RefType 3941 = Conv->getConversionType()->getAs<LValueReferenceType>(); 3942 if (RefType && !RefType->getPointeeType()->isFunctionType()) 3943 continue; 3944 } 3945 3946 if (!ConvTemplate && 3947 S.CompareReferenceRelationship( 3948 DeclLoc, 3949 Conv->getConversionType().getNonReferenceType() 3950 .getUnqualifiedType(), 3951 DeclType.getNonReferenceType().getUnqualifiedType(), 3952 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) == 3953 Sema::Ref_Incompatible) 3954 continue; 3955 } else { 3956 // If the conversion function doesn't return a reference type, 3957 // it can't be considered for this conversion. An rvalue reference 3958 // is only acceptable if its referencee is a function type. 3959 3960 const ReferenceType *RefType = 3961 Conv->getConversionType()->getAs<ReferenceType>(); 3962 if (!RefType || 3963 (!RefType->isLValueReferenceType() && 3964 !RefType->getPointeeType()->isFunctionType())) 3965 continue; 3966 } 3967 3968 if (ConvTemplate) 3969 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC, 3970 Init, DeclType, CandidateSet); 3971 else 3972 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init, 3973 DeclType, CandidateSet); 3974 } 3975 3976 bool HadMultipleCandidates = (CandidateSet.size() > 1); 3977 3978 OverloadCandidateSet::iterator Best; 3979 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) { 3980 case OR_Success: 3981 // C++ [over.ics.ref]p1: 3982 // 3983 // [...] If the parameter binds directly to the result of 3984 // applying a conversion function to the argument 3985 // expression, the implicit conversion sequence is a 3986 // user-defined conversion sequence (13.3.3.1.2), with the 3987 // second standard conversion sequence either an identity 3988 // conversion or, if the conversion function returns an 3989 // entity of a type that is a derived class of the parameter 3990 // type, a derived-to-base Conversion. 3991 if (!Best->FinalConversion.DirectBinding) 3992 return false; 3993 3994 if (Best->Function) 3995 S.MarkFunctionReferenced(DeclLoc, Best->Function); 3996 ICS.setUserDefined(); 3997 ICS.UserDefined.Before = Best->Conversions[0].Standard; 3998 ICS.UserDefined.After = Best->FinalConversion; 3999 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates; 4000 ICS.UserDefined.ConversionFunction = Best->Function; 4001 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl; 4002 ICS.UserDefined.EllipsisConversion = false; 4003 assert(ICS.UserDefined.After.ReferenceBinding && 4004 ICS.UserDefined.After.DirectBinding && 4005 "Expected a direct reference binding!"); 4006 return true; 4007 4008 case OR_Ambiguous: 4009 ICS.setAmbiguous(); 4010 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 4011 Cand != CandidateSet.end(); ++Cand) 4012 if (Cand->Viable) 4013 ICS.Ambiguous.addConversion(Cand->Function); 4014 return true; 4015 4016 case OR_No_Viable_Function: 4017 case OR_Deleted: 4018 // There was no suitable conversion, or we found a deleted 4019 // conversion; continue with other checks. 4020 return false; 4021 } 4022 4023 llvm_unreachable("Invalid OverloadResult!"); 4024 } 4025 4026 /// \brief Compute an implicit conversion sequence for reference 4027 /// initialization. 4028 static ImplicitConversionSequence 4029 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, 4030 SourceLocation DeclLoc, 4031 bool SuppressUserConversions, 4032 bool AllowExplicit) { 4033 assert(DeclType->isReferenceType() && "Reference init needs a reference"); 4034 4035 // Most paths end in a failed conversion. 4036 ImplicitConversionSequence ICS; 4037 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4038 4039 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType(); 4040 QualType T2 = Init->getType(); 4041 4042 // If the initializer is the address of an overloaded function, try 4043 // to resolve the overloaded function. If all goes well, T2 is the 4044 // type of the resulting function. 4045 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) { 4046 DeclAccessPair Found; 4047 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType, 4048 false, Found)) 4049 T2 = Fn->getType(); 4050 } 4051 4052 // Compute some basic properties of the types and the initializer. 4053 bool isRValRef = DeclType->isRValueReferenceType(); 4054 bool DerivedToBase = false; 4055 bool ObjCConversion = false; 4056 bool ObjCLifetimeConversion = false; 4057 Expr::Classification InitCategory = Init->Classify(S.Context); 4058 Sema::ReferenceCompareResult RefRelationship 4059 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase, 4060 ObjCConversion, ObjCLifetimeConversion); 4061 4062 4063 // C++0x [dcl.init.ref]p5: 4064 // A reference to type "cv1 T1" is initialized by an expression 4065 // of type "cv2 T2" as follows: 4066 4067 // -- If reference is an lvalue reference and the initializer expression 4068 if (!isRValRef) { 4069 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is 4070 // reference-compatible with "cv2 T2," or 4071 // 4072 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here. 4073 if (InitCategory.isLValue() && 4074 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) { 4075 // C++ [over.ics.ref]p1: 4076 // When a parameter of reference type binds directly (8.5.3) 4077 // to an argument expression, the implicit conversion sequence 4078 // is the identity conversion, unless the argument expression 4079 // has a type that is a derived class of the parameter type, 4080 // in which case the implicit conversion sequence is a 4081 // derived-to-base Conversion (13.3.3.1). 4082 ICS.setStandard(); 4083 ICS.Standard.First = ICK_Identity; 4084 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4085 : ObjCConversion? ICK_Compatible_Conversion 4086 : ICK_Identity; 4087 ICS.Standard.Third = ICK_Identity; 4088 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4089 ICS.Standard.setToType(0, T2); 4090 ICS.Standard.setToType(1, T1); 4091 ICS.Standard.setToType(2, T1); 4092 ICS.Standard.ReferenceBinding = true; 4093 ICS.Standard.DirectBinding = true; 4094 ICS.Standard.IsLvalueReference = !isRValRef; 4095 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4096 ICS.Standard.BindsToRvalue = false; 4097 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4098 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4099 ICS.Standard.CopyConstructor = 0; 4100 4101 // Nothing more to do: the inaccessibility/ambiguity check for 4102 // derived-to-base conversions is suppressed when we're 4103 // computing the implicit conversion sequence (C++ 4104 // [over.best.ics]p2). 4105 return ICS; 4106 } 4107 4108 // -- has a class type (i.e., T2 is a class type), where T1 is 4109 // not reference-related to T2, and can be implicitly 4110 // converted to an lvalue of type "cv3 T3," where "cv1 T1" 4111 // is reference-compatible with "cv3 T3" 92) (this 4112 // conversion is selected by enumerating the applicable 4113 // conversion functions (13.3.1.6) and choosing the best 4114 // one through overload resolution (13.3)), 4115 if (!SuppressUserConversions && T2->isRecordType() && 4116 !S.RequireCompleteType(DeclLoc, T2, 0) && 4117 RefRelationship == Sema::Ref_Incompatible) { 4118 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4119 Init, T2, /*AllowRvalues=*/false, 4120 AllowExplicit)) 4121 return ICS; 4122 } 4123 } 4124 4125 // -- Otherwise, the reference shall be an lvalue reference to a 4126 // non-volatile const type (i.e., cv1 shall be const), or the reference 4127 // shall be an rvalue reference. 4128 // 4129 // We actually handle one oddity of C++ [over.ics.ref] at this 4130 // point, which is that, due to p2 (which short-circuits reference 4131 // binding by only attempting a simple conversion for non-direct 4132 // bindings) and p3's strange wording, we allow a const volatile 4133 // reference to bind to an rvalue. Hence the check for the presence 4134 // of "const" rather than checking for "const" being the only 4135 // qualifier. 4136 // This is also the point where rvalue references and lvalue inits no longer 4137 // go together. 4138 if (!isRValRef && !T1.isConstQualified()) 4139 return ICS; 4140 4141 // -- If the initializer expression 4142 // 4143 // -- is an xvalue, class prvalue, array prvalue or function 4144 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or 4145 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification && 4146 (InitCategory.isXValue() || 4147 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) || 4148 (InitCategory.isLValue() && T2->isFunctionType()))) { 4149 ICS.setStandard(); 4150 ICS.Standard.First = ICK_Identity; 4151 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base 4152 : ObjCConversion? ICK_Compatible_Conversion 4153 : ICK_Identity; 4154 ICS.Standard.Third = ICK_Identity; 4155 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr(); 4156 ICS.Standard.setToType(0, T2); 4157 ICS.Standard.setToType(1, T1); 4158 ICS.Standard.setToType(2, T1); 4159 ICS.Standard.ReferenceBinding = true; 4160 // In C++0x, this is always a direct binding. In C++98/03, it's a direct 4161 // binding unless we're binding to a class prvalue. 4162 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we 4163 // allow the use of rvalue references in C++98/03 for the benefit of 4164 // standard library implementors; therefore, we need the xvalue check here. 4165 ICS.Standard.DirectBinding = 4166 S.getLangOpts().CPlusPlus0x || 4167 (InitCategory.isPRValue() && !T2->isRecordType()); 4168 ICS.Standard.IsLvalueReference = !isRValRef; 4169 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType(); 4170 ICS.Standard.BindsToRvalue = InitCategory.isRValue(); 4171 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false; 4172 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion; 4173 ICS.Standard.CopyConstructor = 0; 4174 return ICS; 4175 } 4176 4177 // -- has a class type (i.e., T2 is a class type), where T1 is not 4178 // reference-related to T2, and can be implicitly converted to 4179 // an xvalue, class prvalue, or function lvalue of type 4180 // "cv3 T3", where "cv1 T1" is reference-compatible with 4181 // "cv3 T3", 4182 // 4183 // then the reference is bound to the value of the initializer 4184 // expression in the first case and to the result of the conversion 4185 // in the second case (or, in either case, to an appropriate base 4186 // class subobject). 4187 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4188 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) && 4189 FindConversionForRefInit(S, ICS, DeclType, DeclLoc, 4190 Init, T2, /*AllowRvalues=*/true, 4191 AllowExplicit)) { 4192 // In the second case, if the reference is an rvalue reference 4193 // and the second standard conversion sequence of the 4194 // user-defined conversion sequence includes an lvalue-to-rvalue 4195 // conversion, the program is ill-formed. 4196 if (ICS.isUserDefined() && isRValRef && 4197 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue) 4198 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType); 4199 4200 return ICS; 4201 } 4202 4203 // -- Otherwise, a temporary of type "cv1 T1" is created and 4204 // initialized from the initializer expression using the 4205 // rules for a non-reference copy initialization (8.5). The 4206 // reference is then bound to the temporary. If T1 is 4207 // reference-related to T2, cv1 must be the same 4208 // cv-qualification as, or greater cv-qualification than, 4209 // cv2; otherwise, the program is ill-formed. 4210 if (RefRelationship == Sema::Ref_Related) { 4211 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then 4212 // we would be reference-compatible or reference-compatible with 4213 // added qualification. But that wasn't the case, so the reference 4214 // initialization fails. 4215 // 4216 // Note that we only want to check address spaces and cvr-qualifiers here. 4217 // ObjC GC and lifetime qualifiers aren't important. 4218 Qualifiers T1Quals = T1.getQualifiers(); 4219 Qualifiers T2Quals = T2.getQualifiers(); 4220 T1Quals.removeObjCGCAttr(); 4221 T1Quals.removeObjCLifetime(); 4222 T2Quals.removeObjCGCAttr(); 4223 T2Quals.removeObjCLifetime(); 4224 if (!T1Quals.compatiblyIncludes(T2Quals)) 4225 return ICS; 4226 } 4227 4228 // If at least one of the types is a class type, the types are not 4229 // related, and we aren't allowed any user conversions, the 4230 // reference binding fails. This case is important for breaking 4231 // recursion, since TryImplicitConversion below will attempt to 4232 // create a temporary through the use of a copy constructor. 4233 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible && 4234 (T1->isRecordType() || T2->isRecordType())) 4235 return ICS; 4236 4237 // If T1 is reference-related to T2 and the reference is an rvalue 4238 // reference, the initializer expression shall not be an lvalue. 4239 if (RefRelationship >= Sema::Ref_Related && 4240 isRValRef && Init->Classify(S.Context).isLValue()) 4241 return ICS; 4242