SemaOverload.cpp revision f7be9448af88e0ebb204bdcebfc13f4cb2b9d8e1
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 "Sema.h" 15#include "SemaInherit.h" 16#include "clang/Basic/Diagnostic.h" 17#include "clang/AST/ASTContext.h" 18#include "clang/AST/Expr.h" 19#include "llvm/Support/Compiler.h" 20#include <algorithm> 21 22namespace clang { 23 24/// GetConversionCategory - Retrieve the implicit conversion 25/// category corresponding to the given implicit conversion kind. 26ImplicitConversionCategory 27GetConversionCategory(ImplicitConversionKind Kind) { 28 static const ImplicitConversionCategory 29 Category[(int)ICK_Num_Conversion_Kinds] = { 30 ICC_Identity, 31 ICC_Lvalue_Transformation, 32 ICC_Lvalue_Transformation, 33 ICC_Lvalue_Transformation, 34 ICC_Qualification_Adjustment, 35 ICC_Promotion, 36 ICC_Promotion, 37 ICC_Conversion, 38 ICC_Conversion, 39 ICC_Conversion, 40 ICC_Conversion, 41 ICC_Conversion, 42 ICC_Conversion, 43 ICC_Conversion 44 }; 45 return Category[(int)Kind]; 46} 47 48/// GetConversionRank - Retrieve the implicit conversion rank 49/// corresponding to the given implicit conversion kind. 50ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 51 static const ImplicitConversionRank 52 Rank[(int)ICK_Num_Conversion_Kinds] = { 53 ICR_Exact_Match, 54 ICR_Exact_Match, 55 ICR_Exact_Match, 56 ICR_Exact_Match, 57 ICR_Exact_Match, 58 ICR_Promotion, 59 ICR_Promotion, 60 ICR_Conversion, 61 ICR_Conversion, 62 ICR_Conversion, 63 ICR_Conversion, 64 ICR_Conversion, 65 ICR_Conversion, 66 ICR_Conversion 67 }; 68 return Rank[(int)Kind]; 69} 70 71/// GetImplicitConversionName - Return the name of this kind of 72/// implicit conversion. 73const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 74 static const char* Name[(int)ICK_Num_Conversion_Kinds] = { 75 "No conversion", 76 "Lvalue-to-rvalue", 77 "Array-to-pointer", 78 "Function-to-pointer", 79 "Qualification", 80 "Integral promotion", 81 "Floating point promotion", 82 "Integral conversion", 83 "Floating conversion", 84 "Floating-integral conversion", 85 "Pointer conversion", 86 "Pointer-to-member conversion", 87 "Boolean conversion", 88 "Derived-to-base conversion" 89 }; 90 return Name[Kind]; 91} 92 93/// StandardConversionSequence - Set the standard conversion 94/// sequence to the identity conversion. 95void StandardConversionSequence::setAsIdentityConversion() { 96 First = ICK_Identity; 97 Second = ICK_Identity; 98 Third = ICK_Identity; 99 Deprecated = false; 100 ReferenceBinding = false; 101 DirectBinding = false; 102 CopyConstructor = 0; 103} 104 105/// getRank - Retrieve the rank of this standard conversion sequence 106/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 107/// implicit conversions. 108ImplicitConversionRank StandardConversionSequence::getRank() const { 109 ImplicitConversionRank Rank = ICR_Exact_Match; 110 if (GetConversionRank(First) > Rank) 111 Rank = GetConversionRank(First); 112 if (GetConversionRank(Second) > Rank) 113 Rank = GetConversionRank(Second); 114 if (GetConversionRank(Third) > Rank) 115 Rank = GetConversionRank(Third); 116 return Rank; 117} 118 119/// isPointerConversionToBool - Determines whether this conversion is 120/// a conversion of a pointer or pointer-to-member to bool. This is 121/// used as part of the ranking of standard conversion sequences 122/// (C++ 13.3.3.2p4). 123bool StandardConversionSequence::isPointerConversionToBool() const 124{ 125 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr); 126 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr); 127 128 // Note that FromType has not necessarily been transformed by the 129 // array-to-pointer or function-to-pointer implicit conversions, so 130 // check for their presence as well as checking whether FromType is 131 // a pointer. 132 if (ToType->isBooleanType() && 133 (FromType->isPointerType() || 134 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 135 return true; 136 137 return false; 138} 139 140/// isPointerConversionToVoidPointer - Determines whether this 141/// conversion is a conversion of a pointer to a void pointer. This is 142/// used as part of the ranking of standard conversion sequences (C++ 143/// 13.3.3.2p4). 144bool 145StandardConversionSequence:: 146isPointerConversionToVoidPointer(ASTContext& Context) const 147{ 148 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr); 149 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr); 150 151 // Note that FromType has not necessarily been transformed by the 152 // array-to-pointer implicit conversion, so check for its presence 153 // and redo the conversion to get a pointer. 154 if (First == ICK_Array_To_Pointer) 155 FromType = Context.getArrayDecayedType(FromType); 156 157 if (Second == ICK_Pointer_Conversion) 158 if (const PointerType* ToPtrType = ToType->getAsPointerType()) 159 return ToPtrType->getPointeeType()->isVoidType(); 160 161 return false; 162} 163 164/// DebugPrint - Print this standard conversion sequence to standard 165/// error. Useful for debugging overloading issues. 166void StandardConversionSequence::DebugPrint() const { 167 bool PrintedSomething = false; 168 if (First != ICK_Identity) { 169 fprintf(stderr, "%s", GetImplicitConversionName(First)); 170 PrintedSomething = true; 171 } 172 173 if (Second != ICK_Identity) { 174 if (PrintedSomething) { 175 fprintf(stderr, " -> "); 176 } 177 fprintf(stderr, "%s", GetImplicitConversionName(Second)); 178 179 if (CopyConstructor) { 180 fprintf(stderr, " (by copy constructor)"); 181 } else if (DirectBinding) { 182 fprintf(stderr, " (direct reference binding)"); 183 } else if (ReferenceBinding) { 184 fprintf(stderr, " (reference binding)"); 185 } 186 PrintedSomething = true; 187 } 188 189 if (Third != ICK_Identity) { 190 if (PrintedSomething) { 191 fprintf(stderr, " -> "); 192 } 193 fprintf(stderr, "%s", GetImplicitConversionName(Third)); 194 PrintedSomething = true; 195 } 196 197 if (!PrintedSomething) { 198 fprintf(stderr, "No conversions required"); 199 } 200} 201 202/// DebugPrint - Print this user-defined conversion sequence to standard 203/// error. Useful for debugging overloading issues. 204void UserDefinedConversionSequence::DebugPrint() const { 205 if (Before.First || Before.Second || Before.Third) { 206 Before.DebugPrint(); 207 fprintf(stderr, " -> "); 208 } 209 fprintf(stderr, "'%s'", ConversionFunction->getName()); 210 if (After.First || After.Second || After.Third) { 211 fprintf(stderr, " -> "); 212 After.DebugPrint(); 213 } 214} 215 216/// DebugPrint - Print this implicit conversion sequence to standard 217/// error. Useful for debugging overloading issues. 218void ImplicitConversionSequence::DebugPrint() const { 219 switch (ConversionKind) { 220 case StandardConversion: 221 fprintf(stderr, "Standard conversion: "); 222 Standard.DebugPrint(); 223 break; 224 case UserDefinedConversion: 225 fprintf(stderr, "User-defined conversion: "); 226 UserDefined.DebugPrint(); 227 break; 228 case EllipsisConversion: 229 fprintf(stderr, "Ellipsis conversion"); 230 break; 231 case BadConversion: 232 fprintf(stderr, "Bad conversion"); 233 break; 234 } 235 236 fprintf(stderr, "\n"); 237} 238 239// IsOverload - Determine whether the given New declaration is an 240// overload of the Old declaration. This routine returns false if New 241// and Old cannot be overloaded, e.g., if they are functions with the 242// same signature (C++ 1.3.10) or if the Old declaration isn't a 243// function (or overload set). When it does return false and Old is an 244// OverloadedFunctionDecl, MatchedDecl will be set to point to the 245// FunctionDecl that New cannot be overloaded with. 246// 247// Example: Given the following input: 248// 249// void f(int, float); // #1 250// void f(int, int); // #2 251// int f(int, int); // #3 252// 253// When we process #1, there is no previous declaration of "f", 254// so IsOverload will not be used. 255// 256// When we process #2, Old is a FunctionDecl for #1. By comparing the 257// parameter types, we see that #1 and #2 are overloaded (since they 258// have different signatures), so this routine returns false; 259// MatchedDecl is unchanged. 260// 261// When we process #3, Old is an OverloadedFunctionDecl containing #1 262// and #2. We compare the signatures of #3 to #1 (they're overloaded, 263// so we do nothing) and then #3 to #2. Since the signatures of #3 and 264// #2 are identical (return types of functions are not part of the 265// signature), IsOverload returns false and MatchedDecl will be set to 266// point to the FunctionDecl for #2. 267bool 268Sema::IsOverload(FunctionDecl *New, Decl* OldD, 269 OverloadedFunctionDecl::function_iterator& MatchedDecl) 270{ 271 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) { 272 // Is this new function an overload of every function in the 273 // overload set? 274 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(), 275 FuncEnd = Ovl->function_end(); 276 for (; Func != FuncEnd; ++Func) { 277 if (!IsOverload(New, *Func, MatchedDecl)) { 278 MatchedDecl = Func; 279 return false; 280 } 281 } 282 283 // This function overloads every function in the overload set. 284 return true; 285 } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) { 286 // Is the function New an overload of the function Old? 287 QualType OldQType = Context.getCanonicalType(Old->getType()); 288 QualType NewQType = Context.getCanonicalType(New->getType()); 289 290 // Compare the signatures (C++ 1.3.10) of the two functions to 291 // determine whether they are overloads. If we find any mismatch 292 // in the signature, they are overloads. 293 294 // If either of these functions is a K&R-style function (no 295 // prototype), then we consider them to have matching signatures. 296 if (isa<FunctionTypeNoProto>(OldQType.getTypePtr()) || 297 isa<FunctionTypeNoProto>(NewQType.getTypePtr())) 298 return false; 299 300 FunctionTypeProto* OldType = cast<FunctionTypeProto>(OldQType.getTypePtr()); 301 FunctionTypeProto* NewType = cast<FunctionTypeProto>(NewQType.getTypePtr()); 302 303 // The signature of a function includes the types of its 304 // parameters (C++ 1.3.10), which includes the presence or absence 305 // of the ellipsis; see C++ DR 357). 306 if (OldQType != NewQType && 307 (OldType->getNumArgs() != NewType->getNumArgs() || 308 OldType->isVariadic() != NewType->isVariadic() || 309 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(), 310 NewType->arg_type_begin()))) 311 return true; 312 313 // If the function is a class member, its signature includes the 314 // cv-qualifiers (if any) on the function itself. 315 // 316 // As part of this, also check whether one of the member functions 317 // is static, in which case they are not overloads (C++ 318 // 13.1p2). While not part of the definition of the signature, 319 // this check is important to determine whether these functions 320 // can be overloaded. 321 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 322 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 323 if (OldMethod && NewMethod && 324 !OldMethod->isStatic() && !NewMethod->isStatic() && 325 OldQType.getCVRQualifiers() != NewQType.getCVRQualifiers()) 326 return true; 327 328 // The signatures match; this is not an overload. 329 return false; 330 } else { 331 // (C++ 13p1): 332 // Only function declarations can be overloaded; object and type 333 // declarations cannot be overloaded. 334 return false; 335 } 336} 337 338/// TryImplicitConversion - Attempt to perform an implicit conversion 339/// from the given expression (Expr) to the given type (ToType). This 340/// function returns an implicit conversion sequence that can be used 341/// to perform the initialization. Given 342/// 343/// void f(float f); 344/// void g(int i) { f(i); } 345/// 346/// this routine would produce an implicit conversion sequence to 347/// describe the initialization of f from i, which will be a standard 348/// conversion sequence containing an lvalue-to-rvalue conversion (C++ 349/// 4.1) followed by a floating-integral conversion (C++ 4.9). 350// 351/// Note that this routine only determines how the conversion can be 352/// performed; it does not actually perform the conversion. As such, 353/// it will not produce any diagnostics if no conversion is available, 354/// but will instead return an implicit conversion sequence of kind 355/// "BadConversion". 356/// 357/// If @p SuppressUserConversions, then user-defined conversions are 358/// not permitted. 359ImplicitConversionSequence 360Sema::TryImplicitConversion(Expr* From, QualType ToType, 361 bool SuppressUserConversions) 362{ 363 ImplicitConversionSequence ICS; 364 if (IsStandardConversion(From, ToType, ICS.Standard)) 365 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion; 366 else if (!SuppressUserConversions && 367 IsUserDefinedConversion(From, ToType, ICS.UserDefined)) { 368 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion; 369 // C++ [over.ics.user]p4: 370 // A conversion of an expression of class type to the same class 371 // type is given Exact Match rank, and a conversion of an 372 // expression of class type to a base class of that type is 373 // given Conversion rank, in spite of the fact that a copy 374 // constructor (i.e., a user-defined conversion function) is 375 // called for those cases. 376 if (CXXConstructorDecl *Constructor 377 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 378 if (Constructor->isCopyConstructor(Context)) { 379 // Turn this into a "standard" conversion sequence, so that it 380 // gets ranked with standard conversion sequences. 381 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion; 382 ICS.Standard.setAsIdentityConversion(); 383 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr(); 384 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr(); 385 ICS.Standard.CopyConstructor = Constructor; 386 if (IsDerivedFrom(From->getType().getUnqualifiedType(), 387 ToType.getUnqualifiedType())) 388 ICS.Standard.Second = ICK_Derived_To_Base; 389 } 390 } 391 } else 392 ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 393 394 return ICS; 395} 396 397/// IsStandardConversion - Determines whether there is a standard 398/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 399/// expression From to the type ToType. Standard conversion sequences 400/// only consider non-class types; for conversions that involve class 401/// types, use TryImplicitConversion. If a conversion exists, SCS will 402/// contain the standard conversion sequence required to perform this 403/// conversion and this routine will return true. Otherwise, this 404/// routine will return false and the value of SCS is unspecified. 405bool 406Sema::IsStandardConversion(Expr* From, QualType ToType, 407 StandardConversionSequence &SCS) 408{ 409 QualType FromType = From->getType(); 410 411 // There are no standard conversions for class types, so abort early. 412 if (FromType->isRecordType() || ToType->isRecordType()) 413 return false; 414 415 // Standard conversions (C++ [conv]) 416 SCS.Deprecated = false; 417 SCS.FromTypePtr = FromType.getAsOpaquePtr(); 418 SCS.CopyConstructor = 0; 419 420 // The first conversion can be an lvalue-to-rvalue conversion, 421 // array-to-pointer conversion, or function-to-pointer conversion 422 // (C++ 4p1). 423 424 // Lvalue-to-rvalue conversion (C++ 4.1): 425 // An lvalue (3.10) of a non-function, non-array type T can be 426 // converted to an rvalue. 427 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context); 428 if (argIsLvalue == Expr::LV_Valid && 429 !FromType->isFunctionType() && !FromType->isArrayType()) { 430 SCS.First = ICK_Lvalue_To_Rvalue; 431 432 // If T is a non-class type, the type of the rvalue is the 433 // cv-unqualified version of T. Otherwise, the type of the rvalue 434 // is T (C++ 4.1p1). 435 FromType = FromType.getUnqualifiedType(); 436 } 437 // Array-to-pointer conversion (C++ 4.2) 438 else if (FromType->isArrayType()) { 439 SCS.First = ICK_Array_To_Pointer; 440 441 // An lvalue or rvalue of type "array of N T" or "array of unknown 442 // bound of T" can be converted to an rvalue of type "pointer to 443 // T" (C++ 4.2p1). 444 FromType = Context.getArrayDecayedType(FromType); 445 446 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) { 447 // This conversion is deprecated. (C++ D.4). 448 SCS.Deprecated = true; 449 450 // For the purpose of ranking in overload resolution 451 // (13.3.3.1.1), this conversion is considered an 452 // array-to-pointer conversion followed by a qualification 453 // conversion (4.4). (C++ 4.2p2) 454 SCS.Second = ICK_Identity; 455 SCS.Third = ICK_Qualification; 456 SCS.ToTypePtr = ToType.getAsOpaquePtr(); 457 return true; 458 } 459 } 460 // Function-to-pointer conversion (C++ 4.3). 461 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) { 462 SCS.First = ICK_Function_To_Pointer; 463 464 // An lvalue of function type T can be converted to an rvalue of 465 // type "pointer to T." The result is a pointer to the 466 // function. (C++ 4.3p1). 467 FromType = Context.getPointerType(FromType); 468 469 // FIXME: Deal with overloaded functions here (C++ 4.3p2). 470 } 471 // We don't require any conversions for the first step. 472 else { 473 SCS.First = ICK_Identity; 474 } 475 476 // The second conversion can be an integral promotion, floating 477 // point promotion, integral conversion, floating point conversion, 478 // floating-integral conversion, pointer conversion, 479 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 480 if (Context.getCanonicalType(FromType).getUnqualifiedType() == 481 Context.getCanonicalType(ToType).getUnqualifiedType()) { 482 // The unqualified versions of the types are the same: there's no 483 // conversion to do. 484 SCS.Second = ICK_Identity; 485 } 486 // Integral promotion (C++ 4.5). 487 else if (IsIntegralPromotion(From, FromType, ToType)) { 488 SCS.Second = ICK_Integral_Promotion; 489 FromType = ToType.getUnqualifiedType(); 490 } 491 // Floating point promotion (C++ 4.6). 492 else if (IsFloatingPointPromotion(FromType, ToType)) { 493 SCS.Second = ICK_Floating_Promotion; 494 FromType = ToType.getUnqualifiedType(); 495 } 496 // Integral conversions (C++ 4.7). 497 // FIXME: isIntegralType shouldn't be true for enums in C++. 498 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) && 499 (ToType->isIntegralType() && !ToType->isEnumeralType())) { 500 SCS.Second = ICK_Integral_Conversion; 501 FromType = ToType.getUnqualifiedType(); 502 } 503 // Floating point conversions (C++ 4.8). 504 else if (FromType->isFloatingType() && ToType->isFloatingType()) { 505 SCS.Second = ICK_Floating_Conversion; 506 FromType = ToType.getUnqualifiedType(); 507 } 508 // Floating-integral conversions (C++ 4.9). 509 // FIXME: isIntegralType shouldn't be true for enums in C++. 510 else if ((FromType->isFloatingType() && 511 ToType->isIntegralType() && !ToType->isBooleanType() && 512 !ToType->isEnumeralType()) || 513 ((FromType->isIntegralType() || FromType->isEnumeralType()) && 514 ToType->isFloatingType())) { 515 SCS.Second = ICK_Floating_Integral; 516 FromType = ToType.getUnqualifiedType(); 517 } 518 // Pointer conversions (C++ 4.10). 519 else if (IsPointerConversion(From, FromType, ToType, FromType)) { 520 SCS.Second = ICK_Pointer_Conversion; 521 } 522 // FIXME: Pointer to member conversions (4.11). 523 // Boolean conversions (C++ 4.12). 524 // FIXME: pointer-to-member type 525 else if (ToType->isBooleanType() && 526 (FromType->isArithmeticType() || 527 FromType->isEnumeralType() || 528 FromType->isPointerType())) { 529 SCS.Second = ICK_Boolean_Conversion; 530 FromType = Context.BoolTy; 531 } else { 532 // No second conversion required. 533 SCS.Second = ICK_Identity; 534 } 535 536 QualType CanonFrom; 537 QualType CanonTo; 538 // The third conversion can be a qualification conversion (C++ 4p1). 539 if (IsQualificationConversion(FromType, ToType)) { 540 SCS.Third = ICK_Qualification; 541 FromType = ToType; 542 CanonFrom = Context.getCanonicalType(FromType); 543 CanonTo = Context.getCanonicalType(ToType); 544 } else { 545 // No conversion required 546 SCS.Third = ICK_Identity; 547 548 // C++ [over.best.ics]p6: 549 // [...] Any difference in top-level cv-qualification is 550 // subsumed by the initialization itself and does not constitute 551 // a conversion. [...] 552 CanonFrom = Context.getCanonicalType(FromType); 553 CanonTo = Context.getCanonicalType(ToType); 554 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() && 555 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) { 556 FromType = ToType; 557 CanonFrom = CanonTo; 558 } 559 } 560 561 // If we have not converted the argument type to the parameter type, 562 // this is a bad conversion sequence. 563 if (CanonFrom != CanonTo) 564 return false; 565 566 SCS.ToTypePtr = FromType.getAsOpaquePtr(); 567 return true; 568} 569 570/// IsIntegralPromotion - Determines whether the conversion from the 571/// expression From (whose potentially-adjusted type is FromType) to 572/// ToType is an integral promotion (C++ 4.5). If so, returns true and 573/// sets PromotedType to the promoted type. 574bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) 575{ 576 const BuiltinType *To = ToType->getAsBuiltinType(); 577 // All integers are built-in. 578 if (!To) { 579 return false; 580 } 581 582 // An rvalue of type char, signed char, unsigned char, short int, or 583 // unsigned short int can be converted to an rvalue of type int if 584 // int can represent all the values of the source type; otherwise, 585 // the source rvalue can be converted to an rvalue of type unsigned 586 // int (C++ 4.5p1). 587 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) { 588 if (// We can promote any signed, promotable integer type to an int 589 (FromType->isSignedIntegerType() || 590 // We can promote any unsigned integer type whose size is 591 // less than int to an int. 592 (!FromType->isSignedIntegerType() && 593 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 594 return To->getKind() == BuiltinType::Int; 595 } 596 597 return To->getKind() == BuiltinType::UInt; 598 } 599 600 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2) 601 // can be converted to an rvalue of the first of the following types 602 // that can represent all the values of its underlying type: int, 603 // unsigned int, long, or unsigned long (C++ 4.5p2). 604 if ((FromType->isEnumeralType() || FromType->isWideCharType()) 605 && ToType->isIntegerType()) { 606 // Determine whether the type we're converting from is signed or 607 // unsigned. 608 bool FromIsSigned; 609 uint64_t FromSize = Context.getTypeSize(FromType); 610 if (const EnumType *FromEnumType = FromType->getAsEnumType()) { 611 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType(); 612 FromIsSigned = UnderlyingType->isSignedIntegerType(); 613 } else { 614 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now. 615 FromIsSigned = true; 616 } 617 618 // The types we'll try to promote to, in the appropriate 619 // order. Try each of these types. 620 QualType PromoteTypes[4] = { 621 Context.IntTy, Context.UnsignedIntTy, 622 Context.LongTy, Context.UnsignedLongTy 623 }; 624 for (int Idx = 0; Idx < 0; ++Idx) { 625 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 626 if (FromSize < ToSize || 627 (FromSize == ToSize && 628 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 629 // We found the type that we can promote to. If this is the 630 // type we wanted, we have a promotion. Otherwise, no 631 // promotion. 632 return Context.getCanonicalType(ToType).getUnqualifiedType() 633 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType(); 634 } 635 } 636 } 637 638 // An rvalue for an integral bit-field (9.6) can be converted to an 639 // rvalue of type int if int can represent all the values of the 640 // bit-field; otherwise, it can be converted to unsigned int if 641 // unsigned int can represent all the values of the bit-field. If 642 // the bit-field is larger yet, no integral promotion applies to 643 // it. If the bit-field has an enumerated type, it is treated as any 644 // other value of that type for promotion purposes (C++ 4.5p3). 645 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) { 646 using llvm::APSInt; 647 FieldDecl *MemberDecl = MemRef->getMemberDecl(); 648 APSInt BitWidth; 649 if (MemberDecl->isBitField() && 650 FromType->isIntegralType() && !FromType->isEnumeralType() && 651 From->isIntegerConstantExpr(BitWidth, Context)) { 652 APSInt ToSize(Context.getTypeSize(ToType)); 653 654 // Are we promoting to an int from a bitfield that fits in an int? 655 if (BitWidth < ToSize || 656 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 657 return To->getKind() == BuiltinType::Int; 658 } 659 660 // Are we promoting to an unsigned int from an unsigned bitfield 661 // that fits into an unsigned int? 662 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 663 return To->getKind() == BuiltinType::UInt; 664 } 665 666 return false; 667 } 668 } 669 670 // An rvalue of type bool can be converted to an rvalue of type int, 671 // with false becoming zero and true becoming one (C++ 4.5p4). 672 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 673 return true; 674 } 675 676 return false; 677} 678 679/// IsFloatingPointPromotion - Determines whether the conversion from 680/// FromType to ToType is a floating point promotion (C++ 4.6). If so, 681/// returns true and sets PromotedType to the promoted type. 682bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) 683{ 684 /// An rvalue of type float can be converted to an rvalue of type 685 /// double. (C++ 4.6p1). 686 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType()) 687 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) 688 if (FromBuiltin->getKind() == BuiltinType::Float && 689 ToBuiltin->getKind() == BuiltinType::Double) 690 return true; 691 692 return false; 693} 694 695/// IsPointerConversion - Determines whether the conversion of the 696/// expression From, which has the (possibly adjusted) type FromType, 697/// can be converted to the type ToType via a pointer conversion (C++ 698/// 4.10). If so, returns true and places the converted type (that 699/// might differ from ToType in its cv-qualifiers at some level) into 700/// ConvertedType. 701bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 702 QualType& ConvertedType) 703{ 704 const PointerType* ToTypePtr = ToType->getAsPointerType(); 705 if (!ToTypePtr) 706 return false; 707 708 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 709 if (From->isNullPointerConstant(Context)) { 710 ConvertedType = ToType; 711 return true; 712 } 713 714 // An rvalue of type "pointer to cv T," where T is an object type, 715 // can be converted to an rvalue of type "pointer to cv void" (C++ 716 // 4.10p2). 717 if (FromType->isPointerType() && 718 FromType->getAsPointerType()->getPointeeType()->isObjectType() && 719 ToTypePtr->getPointeeType()->isVoidType()) { 720 // We need to produce a pointer to cv void, where cv is the same 721 // set of cv-qualifiers as we had on the incoming pointee type. 722 QualType toPointee = ToTypePtr->getPointeeType(); 723 unsigned Quals = Context.getCanonicalType(FromType)->getAsPointerType() 724 ->getPointeeType().getCVRQualifiers(); 725 726 if (Context.getCanonicalType(ToTypePtr->getPointeeType()).getCVRQualifiers() 727 == Quals) { 728 // ToType is exactly the type we want. Use it. 729 ConvertedType = ToType; 730 } else { 731 // Build a new type with the right qualifiers. 732 ConvertedType 733 = Context.getPointerType(Context.VoidTy.getQualifiedType(Quals)); 734 } 735 return true; 736 } 737 738 // C++ [conv.ptr]p3: 739 // 740 // An rvalue of type "pointer to cv D," where D is a class type, 741 // can be converted to an rvalue of type "pointer to cv B," where 742 // B is a base class (clause 10) of D. If B is an inaccessible 743 // (clause 11) or ambiguous (10.2) base class of D, a program that 744 // necessitates this conversion is ill-formed. The result of the 745 // conversion is a pointer to the base class sub-object of the 746 // derived class object. The null pointer value is converted to 747 // the null pointer value of the destination type. 748 // 749 // Note that we do not check for ambiguity or inaccessibility 750 // here. That is handled by CheckPointerConversion. 751 if (const PointerType *FromPtrType = FromType->getAsPointerType()) 752 if (const PointerType *ToPtrType = ToType->getAsPointerType()) { 753 if (FromPtrType->getPointeeType()->isRecordType() && 754 ToPtrType->getPointeeType()->isRecordType() && 755 IsDerivedFrom(FromPtrType->getPointeeType(), 756 ToPtrType->getPointeeType())) { 757 // The conversion is okay. Now, we need to produce the type 758 // that results from this conversion, which will have the same 759 // qualifiers as the incoming type. 760 QualType CanonFromPointee 761 = Context.getCanonicalType(FromPtrType->getPointeeType()); 762 QualType ToPointee = ToPtrType->getPointeeType(); 763 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 764 unsigned Quals = CanonFromPointee.getCVRQualifiers(); 765 766 if (CanonToPointee.getCVRQualifiers() == Quals) { 767 // ToType is exactly the type we want. Use it. 768 ConvertedType = ToType; 769 } else { 770 // Build a new type with the right qualifiers. 771 ConvertedType 772 = Context.getPointerType(CanonToPointee.getQualifiedType(Quals)); 773 } 774 return true; 775 } 776 } 777 778 return false; 779} 780 781/// CheckPointerConversion - Check the pointer conversion from the 782/// expression From to the type ToType. This routine checks for 783/// ambiguous (FIXME: or inaccessible) derived-to-base pointer 784/// conversions for which IsPointerConversion has already returned 785/// true. It returns true and produces a diagnostic if there was an 786/// error, or returns false otherwise. 787bool Sema::CheckPointerConversion(Expr *From, QualType ToType) { 788 QualType FromType = From->getType(); 789 790 if (const PointerType *FromPtrType = FromType->getAsPointerType()) 791 if (const PointerType *ToPtrType = ToType->getAsPointerType()) { 792 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 793 /*DetectVirtual=*/false); 794 QualType FromPointeeType = FromPtrType->getPointeeType(), 795 ToPointeeType = ToPtrType->getPointeeType(); 796 if (FromPointeeType->isRecordType() && 797 ToPointeeType->isRecordType()) { 798 // We must have a derived-to-base conversion. Check an 799 // ambiguous or inaccessible conversion. 800 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 801 From->getExprLoc(), 802 From->getSourceRange()); 803 } 804 } 805 806 return false; 807} 808 809/// IsQualificationConversion - Determines whether the conversion from 810/// an rvalue of type FromType to ToType is a qualification conversion 811/// (C++ 4.4). 812bool 813Sema::IsQualificationConversion(QualType FromType, QualType ToType) 814{ 815 FromType = Context.getCanonicalType(FromType); 816 ToType = Context.getCanonicalType(ToType); 817 818 // If FromType and ToType are the same type, this is not a 819 // qualification conversion. 820 if (FromType == ToType) 821 return false; 822 823 // (C++ 4.4p4): 824 // A conversion can add cv-qualifiers at levels other than the first 825 // in multi-level pointers, subject to the following rules: [...] 826 bool PreviousToQualsIncludeConst = true; 827 bool UnwrappedAnyPointer = false; 828 while (UnwrapSimilarPointerTypes(FromType, ToType)) { 829 // Within each iteration of the loop, we check the qualifiers to 830 // determine if this still looks like a qualification 831 // conversion. Then, if all is well, we unwrap one more level of 832 // pointers or pointers-to-members and do it all again 833 // until there are no more pointers or pointers-to-members left to 834 // unwrap. 835 UnwrappedAnyPointer = true; 836 837 // -- for every j > 0, if const is in cv 1,j then const is in cv 838 // 2,j, and similarly for volatile. 839 if (!ToType.isAtLeastAsQualifiedAs(FromType)) 840 return false; 841 842 // -- if the cv 1,j and cv 2,j are different, then const is in 843 // every cv for 0 < k < j. 844 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers() 845 && !PreviousToQualsIncludeConst) 846 return false; 847 848 // Keep track of whether all prior cv-qualifiers in the "to" type 849 // include const. 850 PreviousToQualsIncludeConst 851 = PreviousToQualsIncludeConst && ToType.isConstQualified(); 852 } 853 854 // We are left with FromType and ToType being the pointee types 855 // after unwrapping the original FromType and ToType the same number 856 // of types. If we unwrapped any pointers, and if FromType and 857 // ToType have the same unqualified type (since we checked 858 // qualifiers above), then this is a qualification conversion. 859 return UnwrappedAnyPointer && 860 FromType.getUnqualifiedType() == ToType.getUnqualifiedType(); 861} 862 863/// IsUserDefinedConversion - Determines whether there is a 864/// user-defined conversion sequence (C++ [over.ics.user]) that 865/// converts expression From to the type ToType. If such a conversion 866/// exists, User will contain the user-defined conversion sequence 867/// that performs such a conversion and this routine will return 868/// true. Otherwise, this routine returns false and User is 869/// unspecified. 870bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType, 871 UserDefinedConversionSequence& User) 872{ 873 OverloadCandidateSet CandidateSet; 874 if (const CXXRecordType *ToRecordType 875 = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) { 876 // C++ [over.match.ctor]p1: 877 // When objects of class type are direct-initialized (8.5), or 878 // copy-initialized from an expression of the same or a 879 // derived class type (8.5), overload resolution selects the 880 // constructor. [...] For copy-initialization, the candidate 881 // functions are all the converting constructors (12.3.1) of 882 // that class. The argument list is the expression-list within 883 // the parentheses of the initializer. 884 CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl(); 885 const OverloadedFunctionDecl *Constructors = ToRecordDecl->getConstructors(); 886 for (OverloadedFunctionDecl::function_const_iterator func 887 = Constructors->function_begin(); 888 func != Constructors->function_end(); ++func) { 889 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*func); 890 if (Constructor->isConvertingConstructor()) 891 AddOverloadCandidate(Constructor, &From, 1, CandidateSet, 892 /*SuppressUserConversions=*/true); 893 } 894 } 895 896 // FIXME: Implement support for user-defined conversion operators. 897 898 OverloadCandidateSet::iterator Best; 899 switch (BestViableFunction(CandidateSet, Best)) { 900 case OR_Success: 901 // Record the standard conversion we used and the conversion function. 902 // FIXME: Handle user-defined conversion operators. 903 if (CXXConstructorDecl *Constructor 904 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 905 // C++ [over.ics.user]p1: 906 // If the user-defined conversion is specified by a 907 // constructor (12.3.1), the initial standard conversion 908 // sequence converts the source type to the type required by 909 // the argument of the constructor. 910 // 911 // FIXME: What about ellipsis conversions? 912 QualType ThisType = Constructor->getThisType(Context); 913 User.Before = Best->Conversions[0].Standard; 914 User.ConversionFunction = Constructor; 915 User.After.setAsIdentityConversion(); 916 User.After.FromTypePtr 917 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr(); 918 User.After.ToTypePtr = ToType.getAsOpaquePtr(); 919 return true; 920 } else { 921 assert(false && 922 "Cannot perform user-defined conversion via a conversion operator"); 923 return false; 924 } 925 926 case OR_No_Viable_Function: 927 // No conversion here! We're done. 928 return false; 929 930 case OR_Ambiguous: 931 // FIXME: See C++ [over.best.ics]p10 for the handling of 932 // ambiguous conversion sequences. 933 return false; 934 } 935 936 return false; 937} 938 939/// CompareImplicitConversionSequences - Compare two implicit 940/// conversion sequences to determine whether one is better than the 941/// other or if they are indistinguishable (C++ 13.3.3.2). 942ImplicitConversionSequence::CompareKind 943Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1, 944 const ImplicitConversionSequence& ICS2) 945{ 946 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 947 // conversion sequences (as defined in 13.3.3.1) 948 // -- a standard conversion sequence (13.3.3.1.1) is a better 949 // conversion sequence than a user-defined conversion sequence or 950 // an ellipsis conversion sequence, and 951 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 952 // conversion sequence than an ellipsis conversion sequence 953 // (13.3.3.1.3). 954 // 955 if (ICS1.ConversionKind < ICS2.ConversionKind) 956 return ImplicitConversionSequence::Better; 957 else if (ICS2.ConversionKind < ICS1.ConversionKind) 958 return ImplicitConversionSequence::Worse; 959 960 // Two implicit conversion sequences of the same form are 961 // indistinguishable conversion sequences unless one of the 962 // following rules apply: (C++ 13.3.3.2p3): 963 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion) 964 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard); 965 else if (ICS1.ConversionKind == 966 ImplicitConversionSequence::UserDefinedConversion) { 967 // User-defined conversion sequence U1 is a better conversion 968 // sequence than another user-defined conversion sequence U2 if 969 // they contain the same user-defined conversion function or 970 // constructor and if the second standard conversion sequence of 971 // U1 is better than the second standard conversion sequence of 972 // U2 (C++ 13.3.3.2p3). 973 if (ICS1.UserDefined.ConversionFunction == 974 ICS2.UserDefined.ConversionFunction) 975 return CompareStandardConversionSequences(ICS1.UserDefined.After, 976 ICS2.UserDefined.After); 977 } 978 979 return ImplicitConversionSequence::Indistinguishable; 980} 981 982/// CompareStandardConversionSequences - Compare two standard 983/// conversion sequences to determine whether one is better than the 984/// other or if they are indistinguishable (C++ 13.3.3.2p3). 985ImplicitConversionSequence::CompareKind 986Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1, 987 const StandardConversionSequence& SCS2) 988{ 989 // Standard conversion sequence S1 is a better conversion sequence 990 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 991 992 // -- S1 is a proper subsequence of S2 (comparing the conversion 993 // sequences in the canonical form defined by 13.3.3.1.1, 994 // excluding any Lvalue Transformation; the identity conversion 995 // sequence is considered to be a subsequence of any 996 // non-identity conversion sequence) or, if not that, 997 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third) 998 // Neither is a proper subsequence of the other. Do nothing. 999 ; 1000 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) || 1001 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) || 1002 (SCS1.Second == ICK_Identity && 1003 SCS1.Third == ICK_Identity)) 1004 // SCS1 is a proper subsequence of SCS2. 1005 return ImplicitConversionSequence::Better; 1006 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) || 1007 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) || 1008 (SCS2.Second == ICK_Identity && 1009 SCS2.Third == ICK_Identity)) 1010 // SCS2 is a proper subsequence of SCS1. 1011 return ImplicitConversionSequence::Worse; 1012 1013 // -- the rank of S1 is better than the rank of S2 (by the rules 1014 // defined below), or, if not that, 1015 ImplicitConversionRank Rank1 = SCS1.getRank(); 1016 ImplicitConversionRank Rank2 = SCS2.getRank(); 1017 if (Rank1 < Rank2) 1018 return ImplicitConversionSequence::Better; 1019 else if (Rank2 < Rank1) 1020 return ImplicitConversionSequence::Worse; 1021 1022 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 1023 // are indistinguishable unless one of the following rules 1024 // applies: 1025 1026 // A conversion that is not a conversion of a pointer, or 1027 // pointer to member, to bool is better than another conversion 1028 // that is such a conversion. 1029 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 1030 return SCS2.isPointerConversionToBool() 1031 ? ImplicitConversionSequence::Better 1032 : ImplicitConversionSequence::Worse; 1033 1034 // C++ [over.ics.rank]p4b2: 1035 // 1036 // If class B is derived directly or indirectly from class A, 1037 // conversion of B* to A* is better than conversion of B* to 1038 // void*, and conversion of A* to void* is better than conversion 1039 // of B* to void*. 1040 bool SCS1ConvertsToVoid 1041 = SCS1.isPointerConversionToVoidPointer(Context); 1042 bool SCS2ConvertsToVoid 1043 = SCS2.isPointerConversionToVoidPointer(Context); 1044 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 1045 // Exactly one of the conversion sequences is a conversion to 1046 // a void pointer; it's the worse conversion. 1047 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 1048 : ImplicitConversionSequence::Worse; 1049 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 1050 // Neither conversion sequence converts to a void pointer; compare 1051 // their derived-to-base conversions. 1052 if (ImplicitConversionSequence::CompareKind DerivedCK 1053 = CompareDerivedToBaseConversions(SCS1, SCS2)) 1054 return DerivedCK; 1055 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) { 1056 // Both conversion sequences are conversions to void 1057 // pointers. Compare the source types to determine if there's an 1058 // inheritance relationship in their sources. 1059 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr); 1060 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr); 1061 1062 // Adjust the types we're converting from via the array-to-pointer 1063 // conversion, if we need to. 1064 if (SCS1.First == ICK_Array_To_Pointer) 1065 FromType1 = Context.getArrayDecayedType(FromType1); 1066 if (SCS2.First == ICK_Array_To_Pointer) 1067 FromType2 = Context.getArrayDecayedType(FromType2); 1068 1069 QualType FromPointee1 1070 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1071 QualType FromPointee2 1072 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1073 1074 if (IsDerivedFrom(FromPointee2, FromPointee1)) 1075 return ImplicitConversionSequence::Better; 1076 else if (IsDerivedFrom(FromPointee1, FromPointee2)) 1077 return ImplicitConversionSequence::Worse; 1078 } 1079 1080 // Compare based on qualification conversions (C++ 13.3.3.2p3, 1081 // bullet 3). 1082 if (ImplicitConversionSequence::CompareKind QualCK 1083 = CompareQualificationConversions(SCS1, SCS2)) 1084 return QualCK; 1085 1086 // C++ [over.ics.rank]p3b4: 1087 // -- S1 and S2 are reference bindings (8.5.3), and the types to 1088 // which the references refer are the same type except for 1089 // top-level cv-qualifiers, and the type to which the reference 1090 // initialized by S2 refers is more cv-qualified than the type 1091 // to which the reference initialized by S1 refers. 1092 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 1093 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr); 1094 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr); 1095 T1 = Context.getCanonicalType(T1); 1096 T2 = Context.getCanonicalType(T2); 1097 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) { 1098 if (T2.isMoreQualifiedThan(T1)) 1099 return ImplicitConversionSequence::Better; 1100 else if (T1.isMoreQualifiedThan(T2)) 1101 return ImplicitConversionSequence::Worse; 1102 } 1103 } 1104 1105 return ImplicitConversionSequence::Indistinguishable; 1106} 1107 1108/// CompareQualificationConversions - Compares two standard conversion 1109/// sequences to determine whether they can be ranked based on their 1110/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 1111ImplicitConversionSequence::CompareKind 1112Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1, 1113 const StandardConversionSequence& SCS2) 1114{ 1115 // C++ 13.3.3.2p3: 1116 // -- S1 and S2 differ only in their qualification conversion and 1117 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 1118 // cv-qualification signature of type T1 is a proper subset of 1119 // the cv-qualification signature of type T2, and S1 is not the 1120 // deprecated string literal array-to-pointer conversion (4.2). 1121 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 1122 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 1123 return ImplicitConversionSequence::Indistinguishable; 1124 1125 // FIXME: the example in the standard doesn't use a qualification 1126 // conversion (!) 1127 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr); 1128 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr); 1129 T1 = Context.getCanonicalType(T1); 1130 T2 = Context.getCanonicalType(T2); 1131 1132 // If the types are the same, we won't learn anything by unwrapped 1133 // them. 1134 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) 1135 return ImplicitConversionSequence::Indistinguishable; 1136 1137 ImplicitConversionSequence::CompareKind Result 1138 = ImplicitConversionSequence::Indistinguishable; 1139 while (UnwrapSimilarPointerTypes(T1, T2)) { 1140 // Within each iteration of the loop, we check the qualifiers to 1141 // determine if this still looks like a qualification 1142 // conversion. Then, if all is well, we unwrap one more level of 1143 // pointers or pointers-to-members and do it all again 1144 // until there are no more pointers or pointers-to-members left 1145 // to unwrap. This essentially mimics what 1146 // IsQualificationConversion does, but here we're checking for a 1147 // strict subset of qualifiers. 1148 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 1149 // The qualifiers are the same, so this doesn't tell us anything 1150 // about how the sequences rank. 1151 ; 1152 else if (T2.isMoreQualifiedThan(T1)) { 1153 // T1 has fewer qualifiers, so it could be the better sequence. 1154 if (Result == ImplicitConversionSequence::Worse) 1155 // Neither has qualifiers that are a subset of the other's 1156 // qualifiers. 1157 return ImplicitConversionSequence::Indistinguishable; 1158 1159 Result = ImplicitConversionSequence::Better; 1160 } else if (T1.isMoreQualifiedThan(T2)) { 1161 // T2 has fewer qualifiers, so it could be the better sequence. 1162 if (Result == ImplicitConversionSequence::Better) 1163 // Neither has qualifiers that are a subset of the other's 1164 // qualifiers. 1165 return ImplicitConversionSequence::Indistinguishable; 1166 1167 Result = ImplicitConversionSequence::Worse; 1168 } else { 1169 // Qualifiers are disjoint. 1170 return ImplicitConversionSequence::Indistinguishable; 1171 } 1172 1173 // If the types after this point are equivalent, we're done. 1174 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) 1175 break; 1176 } 1177 1178 // Check that the winning standard conversion sequence isn't using 1179 // the deprecated string literal array to pointer conversion. 1180 switch (Result) { 1181 case ImplicitConversionSequence::Better: 1182 if (SCS1.Deprecated) 1183 Result = ImplicitConversionSequence::Indistinguishable; 1184 break; 1185 1186 case ImplicitConversionSequence::Indistinguishable: 1187 break; 1188 1189 case ImplicitConversionSequence::Worse: 1190 if (SCS2.Deprecated) 1191 Result = ImplicitConversionSequence::Indistinguishable; 1192 break; 1193 } 1194 1195 return Result; 1196} 1197 1198/// CompareDerivedToBaseConversions - Compares two standard conversion 1199/// sequences to determine whether they can be ranked based on their 1200/// various kinds of derived-to-base conversions (C++ [over.ics.rank]p4b3). 1201ImplicitConversionSequence::CompareKind 1202Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1, 1203 const StandardConversionSequence& SCS2) { 1204 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr); 1205 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr); 1206 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr); 1207 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr); 1208 1209 // Adjust the types we're converting from via the array-to-pointer 1210 // conversion, if we need to. 1211 if (SCS1.First == ICK_Array_To_Pointer) 1212 FromType1 = Context.getArrayDecayedType(FromType1); 1213 if (SCS2.First == ICK_Array_To_Pointer) 1214 FromType2 = Context.getArrayDecayedType(FromType2); 1215 1216 // Canonicalize all of the types. 1217 FromType1 = Context.getCanonicalType(FromType1); 1218 ToType1 = Context.getCanonicalType(ToType1); 1219 FromType2 = Context.getCanonicalType(FromType2); 1220 ToType2 = Context.getCanonicalType(ToType2); 1221 1222 // C++ [over.ics.rank]p4b3: 1223 // 1224 // If class B is derived directly or indirectly from class A and 1225 // class C is derived directly or indirectly from B, 1226 1227 // Compare based on pointer conversions. 1228 if (SCS1.Second == ICK_Pointer_Conversion && 1229 SCS2.Second == ICK_Pointer_Conversion) { 1230 QualType FromPointee1 1231 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1232 QualType ToPointee1 1233 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1234 QualType FromPointee2 1235 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1236 QualType ToPointee2 1237 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1238 // -- conversion of C* to B* is better than conversion of C* to A*, 1239 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 1240 if (IsDerivedFrom(ToPointee1, ToPointee2)) 1241 return ImplicitConversionSequence::Better; 1242 else if (IsDerivedFrom(ToPointee2, ToPointee1)) 1243 return ImplicitConversionSequence::Worse; 1244 } 1245 1246 // -- conversion of B* to A* is better than conversion of C* to A*, 1247 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 1248 if (IsDerivedFrom(FromPointee2, FromPointee1)) 1249 return ImplicitConversionSequence::Better; 1250 else if (IsDerivedFrom(FromPointee1, FromPointee2)) 1251 return ImplicitConversionSequence::Worse; 1252 } 1253 } 1254 1255 // Compare based on reference bindings. 1256 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding && 1257 SCS1.Second == ICK_Derived_To_Base) { 1258 // -- binding of an expression of type C to a reference of type 1259 // B& is better than binding an expression of type C to a 1260 // reference of type A&, 1261 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() && 1262 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) { 1263 if (IsDerivedFrom(ToType1, ToType2)) 1264 return ImplicitConversionSequence::Better; 1265 else if (IsDerivedFrom(ToType2, ToType1)) 1266 return ImplicitConversionSequence::Worse; 1267 } 1268 1269 // -- binding of an expression of type B to a reference of type 1270 // A& is better than binding an expression of type C to a 1271 // reference of type A&, 1272 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() && 1273 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) { 1274 if (IsDerivedFrom(FromType2, FromType1)) 1275 return ImplicitConversionSequence::Better; 1276 else if (IsDerivedFrom(FromType1, FromType2)) 1277 return ImplicitConversionSequence::Worse; 1278 } 1279 } 1280 1281 1282 // FIXME: conversion of A::* to B::* is better than conversion of 1283 // A::* to C::*, 1284 1285 // FIXME: conversion of B::* to C::* is better than conversion of 1286 // A::* to C::*, and 1287 1288 if (SCS1.CopyConstructor && SCS2.CopyConstructor && 1289 SCS1.Second == ICK_Derived_To_Base) { 1290 // -- conversion of C to B is better than conversion of C to A, 1291 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() && 1292 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) { 1293 if (IsDerivedFrom(ToType1, ToType2)) 1294 return ImplicitConversionSequence::Better; 1295 else if (IsDerivedFrom(ToType2, ToType1)) 1296 return ImplicitConversionSequence::Worse; 1297 } 1298 1299 // -- conversion of B to A is better than conversion of C to A. 1300 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() && 1301 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) { 1302 if (IsDerivedFrom(FromType2, FromType1)) 1303 return ImplicitConversionSequence::Better; 1304 else if (IsDerivedFrom(FromType1, FromType2)) 1305 return ImplicitConversionSequence::Worse; 1306 } 1307 } 1308 1309 return ImplicitConversionSequence::Indistinguishable; 1310} 1311 1312/// TryCopyInitialization - Try to copy-initialize a value of type 1313/// ToType from the expression From. Return the implicit conversion 1314/// sequence required to pass this argument, which may be a bad 1315/// conversion sequence (meaning that the argument cannot be passed to 1316/// a parameter of this type). If @p SuppressUserConversions, then we 1317/// do not permit any user-defined conversion sequences. 1318ImplicitConversionSequence 1319Sema::TryCopyInitialization(Expr *From, QualType ToType, 1320 bool SuppressUserConversions) { 1321 if (!getLangOptions().CPlusPlus) { 1322 // In C, copy initialization is the same as performing an assignment. 1323 AssignConvertType ConvTy = 1324 CheckSingleAssignmentConstraints(ToType, From); 1325 ImplicitConversionSequence ICS; 1326 if (getLangOptions().NoExtensions? ConvTy != Compatible 1327 : ConvTy == Incompatible) 1328 ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 1329 else 1330 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion; 1331 return ICS; 1332 } else if (ToType->isReferenceType()) { 1333 ImplicitConversionSequence ICS; 1334 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions); 1335 return ICS; 1336 } else { 1337 return TryImplicitConversion(From, ToType, SuppressUserConversions); 1338 } 1339} 1340 1341/// PerformArgumentPassing - Pass the argument Arg into a parameter of 1342/// type ToType. Returns true (and emits a diagnostic) if there was 1343/// an error, returns false if the initialization succeeded. 1344bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType, 1345 const char* Flavor) { 1346 if (!getLangOptions().CPlusPlus) { 1347 // In C, argument passing is the same as performing an assignment. 1348 QualType FromType = From->getType(); 1349 AssignConvertType ConvTy = 1350 CheckSingleAssignmentConstraints(ToType, From); 1351 1352 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType, 1353 FromType, From, Flavor); 1354 } else if (ToType->isReferenceType()) { 1355 return CheckReferenceInit(From, ToType); 1356 } else { 1357 if (PerformImplicitConversion(From, ToType)) 1358 return Diag(From->getSourceRange().getBegin(), 1359 diag::err_typecheck_convert_incompatible, 1360 ToType.getAsString(), From->getType().getAsString(), 1361 Flavor, 1362 From->getSourceRange()); 1363 else 1364 return false; 1365 } 1366} 1367 1368/// AddOverloadCandidate - Adds the given function to the set of 1369/// candidate functions, using the given function call arguments. If 1370/// @p SuppressUserConversions, then don't allow user-defined 1371/// conversions via constructors or conversion operators. 1372void 1373Sema::AddOverloadCandidate(FunctionDecl *Function, 1374 Expr **Args, unsigned NumArgs, 1375 OverloadCandidateSet& CandidateSet, 1376 bool SuppressUserConversions) 1377{ 1378 const FunctionTypeProto* Proto 1379 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType()); 1380 assert(Proto && "Functions without a prototype cannot be overloaded"); 1381 1382 // Add this candidate 1383 CandidateSet.push_back(OverloadCandidate()); 1384 OverloadCandidate& Candidate = CandidateSet.back(); 1385 Candidate.Function = Function; 1386 1387 unsigned NumArgsInProto = Proto->getNumArgs(); 1388 1389 // (C++ 13.3.2p2): A candidate function having fewer than m 1390 // parameters is viable only if it has an ellipsis in its parameter 1391 // list (8.3.5). 1392 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 1393 Candidate.Viable = false; 1394 return; 1395 } 1396 1397 // (C++ 13.3.2p2): A candidate function having more than m parameters 1398 // is viable only if the (m+1)st parameter has a default argument 1399 // (8.3.6). For the purposes of overload resolution, the 1400 // parameter list is truncated on the right, so that there are 1401 // exactly m parameters. 1402 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 1403 if (NumArgs < MinRequiredArgs) { 1404 // Not enough arguments. 1405 Candidate.Viable = false; 1406 return; 1407 } 1408 1409 // Determine the implicit conversion sequences for each of the 1410 // arguments. 1411 Candidate.Viable = true; 1412 Candidate.Conversions.resize(NumArgs); 1413 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 1414 if (ArgIdx < NumArgsInProto) { 1415 // (C++ 13.3.2p3): for F to be a viable function, there shall 1416 // exist for each argument an implicit conversion sequence 1417 // (13.3.3.1) that converts that argument to the corresponding 1418 // parameter of F. 1419 QualType ParamType = Proto->getArgType(ArgIdx); 1420 Candidate.Conversions[ArgIdx] 1421 = TryCopyInitialization(Args[ArgIdx], ParamType, 1422 SuppressUserConversions); 1423 if (Candidate.Conversions[ArgIdx].ConversionKind 1424 == ImplicitConversionSequence::BadConversion) 1425 Candidate.Viable = false; 1426 } else { 1427 // (C++ 13.3.2p2): For the purposes of overload resolution, any 1428 // argument for which there is no corresponding parameter is 1429 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 1430 Candidate.Conversions[ArgIdx].ConversionKind 1431 = ImplicitConversionSequence::EllipsisConversion; 1432 } 1433 } 1434} 1435 1436/// AddOverloadCandidates - Add all of the function overloads in Ovl 1437/// to the candidate set. 1438void 1439Sema::AddOverloadCandidates(const OverloadedFunctionDecl *Ovl, 1440 Expr **Args, unsigned NumArgs, 1441 OverloadCandidateSet& CandidateSet, 1442 bool SuppressUserConversions) 1443{ 1444 for (OverloadedFunctionDecl::function_const_iterator Func 1445 = Ovl->function_begin(); 1446 Func != Ovl->function_end(); ++Func) 1447 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet, 1448 SuppressUserConversions); 1449} 1450 1451/// isBetterOverloadCandidate - Determines whether the first overload 1452/// candidate is a better candidate than the second (C++ 13.3.3p1). 1453bool 1454Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1, 1455 const OverloadCandidate& Cand2) 1456{ 1457 // Define viable functions to be better candidates than non-viable 1458 // functions. 1459 if (!Cand2.Viable) 1460 return Cand1.Viable; 1461 else if (!Cand1.Viable) 1462 return false; 1463 1464 // FIXME: Deal with the implicit object parameter for static member 1465 // functions. (C++ 13.3.3p1). 1466 1467 // (C++ 13.3.3p1): a viable function F1 is defined to be a better 1468 // function than another viable function F2 if for all arguments i, 1469 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and 1470 // then... 1471 unsigned NumArgs = Cand1.Conversions.size(); 1472 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 1473 bool HasBetterConversion = false; 1474 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 1475 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx], 1476 Cand2.Conversions[ArgIdx])) { 1477 case ImplicitConversionSequence::Better: 1478 // Cand1 has a better conversion sequence. 1479 HasBetterConversion = true; 1480 break; 1481 1482 case ImplicitConversionSequence::Worse: 1483 // Cand1 can't be better than Cand2. 1484 return false; 1485 1486 case ImplicitConversionSequence::Indistinguishable: 1487 // Do nothing. 1488 break; 1489 } 1490 } 1491 1492 if (HasBetterConversion) 1493 return true; 1494 1495 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be implemented. 1496 1497 return false; 1498} 1499 1500/// BestViableFunction - Computes the best viable function (C++ 13.3.3) 1501/// within an overload candidate set. If overloading is successful, 1502/// the result will be OR_Success and Best will be set to point to the 1503/// best viable function within the candidate set. Otherwise, one of 1504/// several kinds of errors will be returned; see 1505/// Sema::OverloadingResult. 1506Sema::OverloadingResult 1507Sema::BestViableFunction(OverloadCandidateSet& CandidateSet, 1508 OverloadCandidateSet::iterator& Best) 1509{ 1510 // Find the best viable function. 1511 Best = CandidateSet.end(); 1512 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 1513 Cand != CandidateSet.end(); ++Cand) { 1514 if (Cand->Viable) { 1515 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best)) 1516 Best = Cand; 1517 } 1518 } 1519 1520 // If we didn't find any viable functions, abort. 1521 if (Best == CandidateSet.end()) 1522 return OR_No_Viable_Function; 1523 1524 // Make sure that this function is better than every other viable 1525 // function. If not, we have an ambiguity. 1526 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 1527 Cand != CandidateSet.end(); ++Cand) { 1528 if (Cand->Viable && 1529 Cand != Best && 1530 !isBetterOverloadCandidate(*Best, *Cand)) 1531 return OR_Ambiguous; 1532 } 1533 1534 // Best is the best viable function. 1535 return OR_Success; 1536} 1537 1538/// PrintOverloadCandidates - When overload resolution fails, prints 1539/// diagnostic messages containing the candidates in the candidate 1540/// set. If OnlyViable is true, only viable candidates will be printed. 1541void 1542Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet, 1543 bool OnlyViable) 1544{ 1545 OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 1546 LastCand = CandidateSet.end(); 1547 for (; Cand != LastCand; ++Cand) { 1548 if (Cand->Viable ||!OnlyViable) 1549 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate); 1550 } 1551} 1552 1553} // end namespace clang 1554