SemaOverload.cpp revision 18fe56863be253a27b940022d27a3101778adaf6
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 if (!To) { 578 return false; 579 } 580 581 // An rvalue of type char, signed char, unsigned char, short int, or 582 // unsigned short int can be converted to an rvalue of type int if 583 // int can represent all the values of the source type; otherwise, 584 // the source rvalue can be converted to an rvalue of type unsigned 585 // int (C++ 4.5p1). 586 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) { 587 if (// We can promote any signed, promotable integer type to an int 588 (FromType->isSignedIntegerType() || 589 // We can promote any unsigned integer type whose size is 590 // less than int to an int. 591 (!FromType->isSignedIntegerType() && 592 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 593 return To->getKind() == BuiltinType::Int; 594 } 595 596 return To->getKind() == BuiltinType::UInt; 597 } 598 599 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2) 600 // can be converted to an rvalue of the first of the following types 601 // that can represent all the values of its underlying type: int, 602 // unsigned int, long, or unsigned long (C++ 4.5p2). 603 if ((FromType->isEnumeralType() || FromType->isWideCharType()) 604 && ToType->isIntegerType()) { 605 // Determine whether the type we're converting from is signed or 606 // unsigned. 607 bool FromIsSigned; 608 uint64_t FromSize = Context.getTypeSize(FromType); 609 if (const EnumType *FromEnumType = FromType->getAsEnumType()) { 610 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType(); 611 FromIsSigned = UnderlyingType->isSignedIntegerType(); 612 } else { 613 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now. 614 FromIsSigned = true; 615 } 616 617 // The types we'll try to promote to, in the appropriate 618 // order. Try each of these types. 619 QualType PromoteTypes[4] = { 620 Context.IntTy, Context.UnsignedIntTy, 621 Context.LongTy, Context.UnsignedLongTy 622 }; 623 for (int Idx = 0; Idx < 0; ++Idx) { 624 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 625 if (FromSize < ToSize || 626 (FromSize == ToSize && 627 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 628 // We found the type that we can promote to. If this is the 629 // type we wanted, we have a promotion. Otherwise, no 630 // promotion. 631 return Context.getCanonicalType(ToType).getUnqualifiedType() 632 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType(); 633 } 634 } 635 } 636 637 // An rvalue for an integral bit-field (9.6) can be converted to an 638 // rvalue of type int if int can represent all the values of the 639 // bit-field; otherwise, it can be converted to unsigned int if 640 // unsigned int can represent all the values of the bit-field. If 641 // the bit-field is larger yet, no integral promotion applies to 642 // it. If the bit-field has an enumerated type, it is treated as any 643 // other value of that type for promotion purposes (C++ 4.5p3). 644 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) { 645 using llvm::APSInt; 646 FieldDecl *MemberDecl = MemRef->getMemberDecl(); 647 APSInt BitWidth; 648 if (MemberDecl->isBitField() && 649 FromType->isIntegralType() && !FromType->isEnumeralType() && 650 From->isIntegerConstantExpr(BitWidth, Context)) { 651 APSInt ToSize(Context.getTypeSize(ToType)); 652 653 // Are we promoting to an int from a bitfield that fits in an int? 654 if (BitWidth < ToSize || 655 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 656 return To->getKind() == BuiltinType::Int; 657 } 658 659 // Are we promoting to an unsigned int from an unsigned bitfield 660 // that fits into an unsigned int? 661 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 662 return To->getKind() == BuiltinType::UInt; 663 } 664 665 return false; 666 } 667 } 668 669 // An rvalue of type bool can be converted to an rvalue of type int, 670 // with false becoming zero and true becoming one (C++ 4.5p4). 671 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 672 return true; 673 } 674 675 return false; 676} 677 678/// IsFloatingPointPromotion - Determines whether the conversion from 679/// FromType to ToType is a floating point promotion (C++ 4.6). If so, 680/// returns true and sets PromotedType to the promoted type. 681bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) 682{ 683 /// An rvalue of type float can be converted to an rvalue of type 684 /// double. (C++ 4.6p1). 685 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType()) 686 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) 687 if (FromBuiltin->getKind() == BuiltinType::Float && 688 ToBuiltin->getKind() == BuiltinType::Double) 689 return true; 690 691 return false; 692} 693 694/// IsPointerConversion - Determines whether the conversion of the 695/// expression From, which has the (possibly adjusted) type FromType, 696/// can be converted to the type ToType via a pointer conversion (C++ 697/// 4.10). If so, returns true and places the converted type (that 698/// might differ from ToType in its cv-qualifiers at some level) into 699/// ConvertedType. 700bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 701 QualType& ConvertedType) 702{ 703 const PointerType* ToTypePtr = ToType->getAsPointerType(); 704 if (!ToTypePtr) 705 return false; 706 707 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 708 if (From->isNullPointerConstant(Context)) { 709 ConvertedType = ToType; 710 return true; 711 } 712 713 // An rvalue of type "pointer to cv T," where T is an object type, 714 // can be converted to an rvalue of type "pointer to cv void" (C++ 715 // 4.10p2). 716 if (FromType->isPointerType() && 717 FromType->getAsPointerType()->getPointeeType()->isObjectType() && 718 ToTypePtr->getPointeeType()->isVoidType()) { 719 // We need to produce a pointer to cv void, where cv is the same 720 // set of cv-qualifiers as we had on the incoming pointee type. 721 QualType toPointee = ToTypePtr->getPointeeType(); 722 unsigned Quals = Context.getCanonicalType(FromType)->getAsPointerType() 723 ->getPointeeType().getCVRQualifiers(); 724 725 if (Context.getCanonicalType(ToTypePtr->getPointeeType()).getCVRQualifiers() 726 == Quals) { 727 // ToType is exactly the type we want. Use it. 728 ConvertedType = ToType; 729 } else { 730 // Build a new type with the right qualifiers. 731 ConvertedType 732 = Context.getPointerType(Context.VoidTy.getQualifiedType(Quals)); 733 } 734 return true; 735 } 736 737 // C++ [conv.ptr]p3: 738 // 739 // An rvalue of type "pointer to cv D," where D is a class type, 740 // can be converted to an rvalue of type "pointer to cv B," where 741 // B is a base class (clause 10) of D. If B is an inaccessible 742 // (clause 11) or ambiguous (10.2) base class of D, a program that 743 // necessitates this conversion is ill-formed. The result of the 744 // conversion is a pointer to the base class sub-object of the 745 // derived class object. The null pointer value is converted to 746 // the null pointer value of the destination type. 747 // 748 // Note that we do not check for ambiguity or inaccessibility 749 // here. That is handled by CheckPointerConversion. 750 if (const PointerType *FromPtrType = FromType->getAsPointerType()) 751 if (const PointerType *ToPtrType = ToType->getAsPointerType()) { 752 if (FromPtrType->getPointeeType()->isRecordType() && 753 ToPtrType->getPointeeType()->isRecordType() && 754 IsDerivedFrom(FromPtrType->getPointeeType(), 755 ToPtrType->getPointeeType())) { 756 // The conversion is okay. Now, we need to produce the type 757 // that results from this conversion, which will have the same 758 // qualifiers as the incoming type. 759 QualType CanonFromPointee 760 = Context.getCanonicalType(FromPtrType->getPointeeType()); 761 QualType ToPointee = ToPtrType->getPointeeType(); 762 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 763 unsigned Quals = CanonFromPointee.getCVRQualifiers(); 764 765 if (CanonToPointee.getCVRQualifiers() == Quals) { 766 // ToType is exactly the type we want. Use it. 767 ConvertedType = ToType; 768 } else { 769 // Build a new type with the right qualifiers. 770 ConvertedType 771 = Context.getPointerType(CanonToPointee.getQualifiedType(Quals)); 772 } 773 return true; 774 } 775 } 776 777 return false; 778} 779 780/// CheckPointerConversion - Check the pointer conversion from the 781/// expression From to the type ToType. This routine checks for 782/// ambiguous (FIXME: or inaccessible) derived-to-base pointer 783/// conversions for which IsPointerConversion has already returned 784/// true. It returns true and produces a diagnostic if there was an 785/// error, or returns false otherwise. 786bool Sema::CheckPointerConversion(Expr *From, QualType ToType) { 787 QualType FromType = From->getType(); 788 789 if (const PointerType *FromPtrType = FromType->getAsPointerType()) 790 if (const PointerType *ToPtrType = ToType->getAsPointerType()) { 791 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 792 /*DetectVirtual=*/false); 793 QualType FromPointeeType = FromPtrType->getPointeeType(), 794 ToPointeeType = ToPtrType->getPointeeType(); 795 if (FromPointeeType->isRecordType() && 796 ToPointeeType->isRecordType()) { 797 // We must have a derived-to-base conversion. Check an 798 // ambiguous or inaccessible conversion. 799 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 800 From->getExprLoc(), 801 From->getSourceRange()); 802 } 803 } 804 805 return false; 806} 807 808/// IsQualificationConversion - Determines whether the conversion from 809/// an rvalue of type FromType to ToType is a qualification conversion 810/// (C++ 4.4). 811bool 812Sema::IsQualificationConversion(QualType FromType, QualType ToType) 813{ 814 FromType = Context.getCanonicalType(FromType); 815 ToType = Context.getCanonicalType(ToType); 816 817 // If FromType and ToType are the same type, this is not a 818 // qualification conversion. 819 if (FromType == ToType) 820 return false; 821 822 // (C++ 4.4p4): 823 // A conversion can add cv-qualifiers at levels other than the first 824 // in multi-level pointers, subject to the following rules: [...] 825 bool PreviousToQualsIncludeConst = true; 826 bool UnwrappedAnyPointer = false; 827 while (UnwrapSimilarPointerTypes(FromType, ToType)) { 828 // Within each iteration of the loop, we check the qualifiers to 829 // determine if this still looks like a qualification 830 // conversion. Then, if all is well, we unwrap one more level of 831 // pointers or pointers-to-members and do it all again 832 // until there are no more pointers or pointers-to-members left to 833 // unwrap. 834 UnwrappedAnyPointer = true; 835 836 // -- for every j > 0, if const is in cv 1,j then const is in cv 837 // 2,j, and similarly for volatile. 838 if (!ToType.isAtLeastAsQualifiedAs(FromType)) 839 return false; 840 841 // -- if the cv 1,j and cv 2,j are different, then const is in 842 // every cv for 0 < k < j. 843 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers() 844 && !PreviousToQualsIncludeConst) 845 return false; 846 847 // Keep track of whether all prior cv-qualifiers in the "to" type 848 // include const. 849 PreviousToQualsIncludeConst 850 = PreviousToQualsIncludeConst && ToType.isConstQualified(); 851 } 852 853 // We are left with FromType and ToType being the pointee types 854 // after unwrapping the original FromType and ToType the same number 855 // of types. If we unwrapped any pointers, and if FromType and 856 // ToType have the same unqualified type (since we checked 857 // qualifiers above), then this is a qualification conversion. 858 return UnwrappedAnyPointer && 859 FromType.getUnqualifiedType() == ToType.getUnqualifiedType(); 860} 861 862/// IsUserDefinedConversion - Determines whether there is a 863/// user-defined conversion sequence (C++ [over.ics.user]) that 864/// converts expression From to the type ToType. If such a conversion 865/// exists, User will contain the user-defined conversion sequence 866/// that performs such a conversion and this routine will return 867/// true. Otherwise, this routine returns false and User is 868/// unspecified. 869bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType, 870 UserDefinedConversionSequence& User) 871{ 872 OverloadCandidateSet CandidateSet; 873 if (const CXXRecordType *ToRecordType 874 = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) { 875 // C++ [over.match.ctor]p1: 876 // When objects of class type are direct-initialized (8.5), or 877 // copy-initialized from an expression of the same or a 878 // derived class type (8.5), overload resolution selects the 879 // constructor. [...] For copy-initialization, the candidate 880 // functions are all the converting constructors (12.3.1) of 881 // that class. The argument list is the expression-list within 882 // the parentheses of the initializer. 883 CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl(); 884 const OverloadedFunctionDecl *Constructors = ToRecordDecl->getConstructors(); 885 for (OverloadedFunctionDecl::function_const_iterator func 886 = Constructors->function_begin(); 887 func != Constructors->function_end(); ++func) { 888 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*func); 889 if (Constructor->isConvertingConstructor()) 890 AddOverloadCandidate(Constructor, &From, 1, CandidateSet, 891 /*SuppressUserConversions=*/true); 892 } 893 } 894 895 // FIXME: Implement support for user-defined conversion operators. 896 897 OverloadCandidateSet::iterator Best; 898 switch (BestViableFunction(CandidateSet, Best)) { 899 case OR_Success: 900 // Record the standard conversion we used and the conversion function. 901 // FIXME: Handle user-defined conversion operators. 902 if (CXXConstructorDecl *Constructor 903 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 904 // C++ [over.ics.user]p1: 905 // If the user-defined conversion is specified by a 906 // constructor (12.3.1), the initial standard conversion 907 // sequence converts the source type to the type required by 908 // the argument of the constructor. 909 // 910 // FIXME: What about ellipsis conversions? 911 QualType ThisType = Constructor->getThisType(Context); 912 User.Before = Best->Conversions[0].Standard; 913 User.ConversionFunction = Constructor; 914 User.After.setAsIdentityConversion(); 915 User.After.FromTypePtr 916 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr(); 917 User.After.ToTypePtr = ToType.getAsOpaquePtr(); 918 return true; 919 } else { 920 assert(false && 921 "Cannot perform user-defined conversion via a conversion operator"); 922 return false; 923 } 924 925 case OR_No_Viable_Function: 926 // No conversion here! We're done. 927 return false; 928 929 case OR_Ambiguous: 930 // FIXME: See C++ [over.best.ics]p10 for the handling of 931 // ambiguous conversion sequences. 932 return false; 933 } 934 935 return false; 936} 937 938/// CompareImplicitConversionSequences - Compare two implicit 939/// conversion sequences to determine whether one is better than the 940/// other or if they are indistinguishable (C++ 13.3.3.2). 941ImplicitConversionSequence::CompareKind 942Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1, 943 const ImplicitConversionSequence& ICS2) 944{ 945 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 946 // conversion sequences (as defined in 13.3.3.1) 947 // -- a standard conversion sequence (13.3.3.1.1) is a better 948 // conversion sequence than a user-defined conversion sequence or 949 // an ellipsis conversion sequence, and 950 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 951 // conversion sequence than an ellipsis conversion sequence 952 // (13.3.3.1.3). 953 // 954 if (ICS1.ConversionKind < ICS2.ConversionKind) 955 return ImplicitConversionSequence::Better; 956 else if (ICS2.ConversionKind < ICS1.ConversionKind) 957 return ImplicitConversionSequence::Worse; 958 959 // Two implicit conversion sequences of the same form are 960 // indistinguishable conversion sequences unless one of the 961 // following rules apply: (C++ 13.3.3.2p3): 962 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion) 963 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard); 964 else if (ICS1.ConversionKind == 965 ImplicitConversionSequence::UserDefinedConversion) { 966 // User-defined conversion sequence U1 is a better conversion 967 // sequence than another user-defined conversion sequence U2 if 968 // they contain the same user-defined conversion function or 969 // constructor and if the second standard conversion sequence of 970 // U1 is better than the second standard conversion sequence of 971 // U2 (C++ 13.3.3.2p3). 972 if (ICS1.UserDefined.ConversionFunction == 973 ICS2.UserDefined.ConversionFunction) 974 return CompareStandardConversionSequences(ICS1.UserDefined.After, 975 ICS2.UserDefined.After); 976 } 977 978 return ImplicitConversionSequence::Indistinguishable; 979} 980 981/// CompareStandardConversionSequences - Compare two standard 982/// conversion sequences to determine whether one is better than the 983/// other or if they are indistinguishable (C++ 13.3.3.2p3). 984ImplicitConversionSequence::CompareKind 985Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1, 986 const StandardConversionSequence& SCS2) 987{ 988 // Standard conversion sequence S1 is a better conversion sequence 989 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 990 991 // -- S1 is a proper subsequence of S2 (comparing the conversion 992 // sequences in the canonical form defined by 13.3.3.1.1, 993 // excluding any Lvalue Transformation; the identity conversion 994 // sequence is considered to be a subsequence of any 995 // non-identity conversion sequence) or, if not that, 996 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third) 997 // Neither is a proper subsequence of the other. Do nothing. 998 ; 999 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) || 1000 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) || 1001 (SCS1.Second == ICK_Identity && 1002 SCS1.Third == ICK_Identity)) 1003 // SCS1 is a proper subsequence of SCS2. 1004 return ImplicitConversionSequence::Better; 1005 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) || 1006 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) || 1007 (SCS2.Second == ICK_Identity && 1008 SCS2.Third == ICK_Identity)) 1009 // SCS2 is a proper subsequence of SCS1. 1010 return ImplicitConversionSequence::Worse; 1011 1012 // -- the rank of S1 is better than the rank of S2 (by the rules 1013 // defined below), or, if not that, 1014 ImplicitConversionRank Rank1 = SCS1.getRank(); 1015 ImplicitConversionRank Rank2 = SCS2.getRank(); 1016 if (Rank1 < Rank2) 1017 return ImplicitConversionSequence::Better; 1018 else if (Rank2 < Rank1) 1019 return ImplicitConversionSequence::Worse; 1020 1021 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 1022 // are indistinguishable unless one of the following rules 1023 // applies: 1024 1025 // A conversion that is not a conversion of a pointer, or 1026 // pointer to member, to bool is better than another conversion 1027 // that is such a conversion. 1028 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 1029 return SCS2.isPointerConversionToBool() 1030 ? ImplicitConversionSequence::Better 1031 : ImplicitConversionSequence::Worse; 1032 1033 // C++ [over.ics.rank]p4b2: 1034 // 1035 // If class B is derived directly or indirectly from class A, 1036 // conversion of B* to A* is better than conversion of B* to 1037 // void*, and conversion of A* to void* is better than conversion 1038 // of B* to void*. 1039 bool SCS1ConvertsToVoid 1040 = SCS1.isPointerConversionToVoidPointer(Context); 1041 bool SCS2ConvertsToVoid 1042 = SCS2.isPointerConversionToVoidPointer(Context); 1043 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 1044 // Exactly one of the conversion sequences is a conversion to 1045 // a void pointer; it's the worse conversion. 1046 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 1047 : ImplicitConversionSequence::Worse; 1048 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 1049 // Neither conversion sequence converts to a void pointer; compare 1050 // their derived-to-base conversions. 1051 if (ImplicitConversionSequence::CompareKind DerivedCK 1052 = CompareDerivedToBaseConversions(SCS1, SCS2)) 1053 return DerivedCK; 1054 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) { 1055 // Both conversion sequences are conversions to void 1056 // pointers. Compare the source types to determine if there's an 1057 // inheritance relationship in their sources. 1058 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr); 1059 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr); 1060 1061 // Adjust the types we're converting from via the array-to-pointer 1062 // conversion, if we need to. 1063 if (SCS1.First == ICK_Array_To_Pointer) 1064 FromType1 = Context.getArrayDecayedType(FromType1); 1065 if (SCS2.First == ICK_Array_To_Pointer) 1066 FromType2 = Context.getArrayDecayedType(FromType2); 1067 1068 QualType FromPointee1 1069 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1070 QualType FromPointee2 1071 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1072 1073 if (IsDerivedFrom(FromPointee2, FromPointee1)) 1074 return ImplicitConversionSequence::Better; 1075 else if (IsDerivedFrom(FromPointee1, FromPointee2)) 1076 return ImplicitConversionSequence::Worse; 1077 } 1078 1079 // Compare based on qualification conversions (C++ 13.3.3.2p3, 1080 // bullet 3). 1081 if (ImplicitConversionSequence::CompareKind QualCK 1082 = CompareQualificationConversions(SCS1, SCS2)) 1083 return QualCK; 1084 1085 // C++ [over.ics.rank]p3b4: 1086 // -- S1 and S2 are reference bindings (8.5.3), and the types to 1087 // which the references refer are the same type except for 1088 // top-level cv-qualifiers, and the type to which the reference 1089 // initialized by S2 refers is more cv-qualified than the type 1090 // to which the reference initialized by S1 refers. 1091 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 1092 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr); 1093 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr); 1094 T1 = Context.getCanonicalType(T1); 1095 T2 = Context.getCanonicalType(T2); 1096 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) { 1097 if (T2.isMoreQualifiedThan(T1)) 1098 return ImplicitConversionSequence::Better; 1099 else if (T1.isMoreQualifiedThan(T2)) 1100 return ImplicitConversionSequence::Worse; 1101 } 1102 } 1103 1104 return ImplicitConversionSequence::Indistinguishable; 1105} 1106 1107/// CompareQualificationConversions - Compares two standard conversion 1108/// sequences to determine whether they can be ranked based on their 1109/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 1110ImplicitConversionSequence::CompareKind 1111Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1, 1112 const StandardConversionSequence& SCS2) 1113{ 1114 // C++ 13.3.3.2p3: 1115 // -- S1 and S2 differ only in their qualification conversion and 1116 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 1117 // cv-qualification signature of type T1 is a proper subset of 1118 // the cv-qualification signature of type T2, and S1 is not the 1119 // deprecated string literal array-to-pointer conversion (4.2). 1120 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 1121 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 1122 return ImplicitConversionSequence::Indistinguishable; 1123 1124 // FIXME: the example in the standard doesn't use a qualification 1125 // conversion (!) 1126 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr); 1127 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr); 1128 T1 = Context.getCanonicalType(T1); 1129 T2 = Context.getCanonicalType(T2); 1130 1131 // If the types are the same, we won't learn anything by unwrapped 1132 // them. 1133 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) 1134 return ImplicitConversionSequence::Indistinguishable; 1135 1136 ImplicitConversionSequence::CompareKind Result 1137 = ImplicitConversionSequence::Indistinguishable; 1138 while (UnwrapSimilarPointerTypes(T1, T2)) { 1139 // Within each iteration of the loop, we check the qualifiers to 1140 // determine if this still looks like a qualification 1141 // conversion. Then, if all is well, we unwrap one more level of 1142 // pointers or pointers-to-members and do it all again 1143 // until there are no more pointers or pointers-to-members left 1144 // to unwrap. This essentially mimics what 1145 // IsQualificationConversion does, but here we're checking for a 1146 // strict subset of qualifiers. 1147 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 1148 // The qualifiers are the same, so this doesn't tell us anything 1149 // about how the sequences rank. 1150 ; 1151 else if (T2.isMoreQualifiedThan(T1)) { 1152 // T1 has fewer qualifiers, so it could be the better sequence. 1153 if (Result == ImplicitConversionSequence::Worse) 1154 // Neither has qualifiers that are a subset of the other's 1155 // qualifiers. 1156 return ImplicitConversionSequence::Indistinguishable; 1157 1158 Result = ImplicitConversionSequence::Better; 1159 } else if (T1.isMoreQualifiedThan(T2)) { 1160 // T2 has fewer qualifiers, so it could be the better sequence. 1161 if (Result == ImplicitConversionSequence::Better) 1162 // Neither has qualifiers that are a subset of the other's 1163 // qualifiers. 1164 return ImplicitConversionSequence::Indistinguishable; 1165 1166 Result = ImplicitConversionSequence::Worse; 1167 } else { 1168 // Qualifiers are disjoint. 1169 return ImplicitConversionSequence::Indistinguishable; 1170 } 1171 1172 // If the types after this point are equivalent, we're done. 1173 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) 1174 break; 1175 } 1176 1177 // Check that the winning standard conversion sequence isn't using 1178 // the deprecated string literal array to pointer conversion. 1179 switch (Result) { 1180 case ImplicitConversionSequence::Better: 1181 if (SCS1.Deprecated) 1182 Result = ImplicitConversionSequence::Indistinguishable; 1183 break; 1184 1185 case ImplicitConversionSequence::Indistinguishable: 1186 break; 1187 1188 case ImplicitConversionSequence::Worse: 1189 if (SCS2.Deprecated) 1190 Result = ImplicitConversionSequence::Indistinguishable; 1191 break; 1192 } 1193 1194 return Result; 1195} 1196 1197/// CompareDerivedToBaseConversions - Compares two standard conversion 1198/// sequences to determine whether they can be ranked based on their 1199/// various kinds of derived-to-base conversions (C++ [over.ics.rank]p4b3). 1200ImplicitConversionSequence::CompareKind 1201Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1, 1202 const StandardConversionSequence& SCS2) { 1203 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr); 1204 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr); 1205 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr); 1206 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr); 1207 1208 // Adjust the types we're converting from via the array-to-pointer 1209 // conversion, if we need to. 1210 if (SCS1.First == ICK_Array_To_Pointer) 1211 FromType1 = Context.getArrayDecayedType(FromType1); 1212 if (SCS2.First == ICK_Array_To_Pointer) 1213 FromType2 = Context.getArrayDecayedType(FromType2); 1214 1215 // Canonicalize all of the types. 1216 FromType1 = Context.getCanonicalType(FromType1); 1217 ToType1 = Context.getCanonicalType(ToType1); 1218 FromType2 = Context.getCanonicalType(FromType2); 1219 ToType2 = Context.getCanonicalType(ToType2); 1220 1221 // C++ [over.ics.rank]p4b3: 1222 // 1223 // If class B is derived directly or indirectly from class A and 1224 // class C is derived directly or indirectly from B, 1225 1226 // Compare based on pointer conversions. 1227 if (SCS1.Second == ICK_Pointer_Conversion && 1228 SCS2.Second == ICK_Pointer_Conversion) { 1229 QualType FromPointee1 1230 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1231 QualType ToPointee1 1232 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1233 QualType FromPointee2 1234 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1235 QualType ToPointee2 1236 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1237 // -- conversion of C* to B* is better than conversion of C* to A*, 1238 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 1239 if (IsDerivedFrom(ToPointee1, ToPointee2)) 1240 return ImplicitConversionSequence::Better; 1241 else if (IsDerivedFrom(ToPointee2, ToPointee1)) 1242 return ImplicitConversionSequence::Worse; 1243 } 1244 1245 // -- conversion of B* to A* is better than conversion of C* to A*, 1246 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 1247 if (IsDerivedFrom(FromPointee2, FromPointee1)) 1248 return ImplicitConversionSequence::Better; 1249 else if (IsDerivedFrom(FromPointee1, FromPointee2)) 1250 return ImplicitConversionSequence::Worse; 1251 } 1252 } 1253 1254 // Compare based on reference bindings. 1255 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding && 1256 SCS1.Second == ICK_Derived_To_Base) { 1257 // -- binding of an expression of type C to a reference of type 1258 // B& is better than binding an expression of type C to a 1259 // reference of type A&, 1260 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() && 1261 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) { 1262 if (IsDerivedFrom(ToType1, ToType2)) 1263 return ImplicitConversionSequence::Better; 1264 else if (IsDerivedFrom(ToType2, ToType1)) 1265 return ImplicitConversionSequence::Worse; 1266 } 1267 1268 // -- binding of an expression of type B to a reference of type 1269 // A& is better than binding an expression of type C to a 1270 // reference of type A&, 1271 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() && 1272 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) { 1273 if (IsDerivedFrom(FromType2, FromType1)) 1274 return ImplicitConversionSequence::Better; 1275 else if (IsDerivedFrom(FromType1, FromType2)) 1276 return ImplicitConversionSequence::Worse; 1277 } 1278 } 1279 1280 1281 // FIXME: conversion of A::* to B::* is better than conversion of 1282 // A::* to C::*, 1283 1284 // FIXME: conversion of B::* to C::* is better than conversion of 1285 // A::* to C::*, and 1286 1287 if (SCS1.CopyConstructor && SCS2.CopyConstructor && 1288 SCS1.Second == ICK_Derived_To_Base) { 1289 // -- conversion of C to B is better than conversion of C to A, 1290 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() && 1291 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) { 1292 if (IsDerivedFrom(ToType1, ToType2)) 1293 return ImplicitConversionSequence::Better; 1294 else if (IsDerivedFrom(ToType2, ToType1)) 1295 return ImplicitConversionSequence::Worse; 1296 } 1297 1298 // -- conversion of B to A is better than conversion of C to A. 1299 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() && 1300 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) { 1301 if (IsDerivedFrom(FromType2, FromType1)) 1302 return ImplicitConversionSequence::Better; 1303 else if (IsDerivedFrom(FromType1, FromType2)) 1304 return ImplicitConversionSequence::Worse; 1305 } 1306 } 1307 1308 return ImplicitConversionSequence::Indistinguishable; 1309} 1310 1311/// TryCopyInitialization - Try to copy-initialize a value of type 1312/// ToType from the expression From. Return the implicit conversion 1313/// sequence required to pass this argument, which may be a bad 1314/// conversion sequence (meaning that the argument cannot be passed to 1315/// a parameter of this type). If @p SuppressUserConversions, then we 1316/// do not permit any user-defined conversion sequences. 1317ImplicitConversionSequence 1318Sema::TryCopyInitialization(Expr *From, QualType ToType, 1319 bool SuppressUserConversions) { 1320 if (!getLangOptions().CPlusPlus) { 1321 // In C, copy initialization is the same as performing an assignment. 1322 AssignConvertType ConvTy = 1323 CheckSingleAssignmentConstraints(ToType, From); 1324 ImplicitConversionSequence ICS; 1325 if (getLangOptions().NoExtensions? ConvTy != Compatible 1326 : ConvTy == Incompatible) 1327 ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 1328 else 1329 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion; 1330 return ICS; 1331 } else if (ToType->isReferenceType()) { 1332 ImplicitConversionSequence ICS; 1333 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions); 1334 return ICS; 1335 } else { 1336 return TryImplicitConversion(From, ToType, SuppressUserConversions); 1337 } 1338} 1339 1340/// PerformArgumentPassing - Pass the argument Arg into a parameter of 1341/// type ToType. Returns true (and emits a diagnostic) if there was 1342/// an error, returns false if the initialization succeeded. 1343bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType, 1344 const char* Flavor) { 1345 if (!getLangOptions().CPlusPlus) { 1346 // In C, argument passing is the same as performing an assignment. 1347 QualType FromType = From->getType(); 1348 AssignConvertType ConvTy = 1349 CheckSingleAssignmentConstraints(ToType, From); 1350 1351 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType, 1352 FromType, From, Flavor); 1353 } else if (ToType->isReferenceType()) { 1354 return CheckReferenceInit(From, ToType); 1355 } else { 1356 if (PerformImplicitConversion(From, ToType)) 1357 return Diag(From->getSourceRange().getBegin(), 1358 diag::err_typecheck_convert_incompatible, 1359 ToType.getAsString(), From->getType().getAsString(), 1360 Flavor, 1361 From->getSourceRange()); 1362 else 1363 return false; 1364 } 1365} 1366 1367/// AddOverloadCandidate - Adds the given function to the set of 1368/// candidate functions, using the given function call arguments. If 1369/// @p SuppressUserConversions, then don't allow user-defined 1370/// conversions via constructors or conversion operators. 1371void 1372Sema::AddOverloadCandidate(FunctionDecl *Function, 1373 Expr **Args, unsigned NumArgs, 1374 OverloadCandidateSet& CandidateSet, 1375 bool SuppressUserConversions) 1376{ 1377 const FunctionTypeProto* Proto 1378 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType()); 1379 assert(Proto && "Functions without a prototype cannot be overloaded"); 1380 1381 // Add this candidate 1382 CandidateSet.push_back(OverloadCandidate()); 1383 OverloadCandidate& Candidate = CandidateSet.back(); 1384 Candidate.Function = Function; 1385 1386 unsigned NumArgsInProto = Proto->getNumArgs(); 1387 1388 // (C++ 13.3.2p2): A candidate function having fewer than m 1389 // parameters is viable only if it has an ellipsis in its parameter 1390 // list (8.3.5). 1391 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 1392 Candidate.Viable = false; 1393 return; 1394 } 1395 1396 // (C++ 13.3.2p2): A candidate function having more than m parameters 1397 // is viable only if the (m+1)st parameter has a default argument 1398 // (8.3.6). For the purposes of overload resolution, the 1399 // parameter list is truncated on the right, so that there are 1400 // exactly m parameters. 1401 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 1402 if (NumArgs < MinRequiredArgs) { 1403 // Not enough arguments. 1404 Candidate.Viable = false; 1405 return; 1406 } 1407 1408 // Determine the implicit conversion sequences for each of the 1409 // arguments. 1410 Candidate.Viable = true; 1411 Candidate.Conversions.resize(NumArgs); 1412 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 1413 if (ArgIdx < NumArgsInProto) { 1414 // (C++ 13.3.2p3): for F to be a viable function, there shall 1415 // exist for each argument an implicit conversion sequence 1416 // (13.3.3.1) that converts that argument to the corresponding 1417 // parameter of F. 1418 QualType ParamType = Proto->getArgType(ArgIdx); 1419 Candidate.Conversions[ArgIdx] 1420 = TryCopyInitialization(Args[ArgIdx], ParamType, 1421 SuppressUserConversions); 1422 if (Candidate.Conversions[ArgIdx].ConversionKind 1423 == ImplicitConversionSequence::BadConversion) 1424 Candidate.Viable = false; 1425 } else { 1426 // (C++ 13.3.2p2): For the purposes of overload resolution, any 1427 // argument for which there is no corresponding parameter is 1428 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 1429 Candidate.Conversions[ArgIdx].ConversionKind 1430 = ImplicitConversionSequence::EllipsisConversion; 1431 } 1432 } 1433} 1434 1435/// AddOverloadCandidates - Add all of the function overloads in Ovl 1436/// to the candidate set. 1437void 1438Sema::AddOverloadCandidates(const OverloadedFunctionDecl *Ovl, 1439 Expr **Args, unsigned NumArgs, 1440 OverloadCandidateSet& CandidateSet, 1441 bool SuppressUserConversions) 1442{ 1443 for (OverloadedFunctionDecl::function_const_iterator Func 1444 = Ovl->function_begin(); 1445 Func != Ovl->function_end(); ++Func) 1446 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet, 1447 SuppressUserConversions); 1448} 1449 1450/// isBetterOverloadCandidate - Determines whether the first overload 1451/// candidate is a better candidate than the second (C++ 13.3.3p1). 1452bool 1453Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1, 1454 const OverloadCandidate& Cand2) 1455{ 1456 // Define viable functions to be better candidates than non-viable 1457 // functions. 1458 if (!Cand2.Viable) 1459 return Cand1.Viable; 1460 else if (!Cand1.Viable) 1461 return false; 1462 1463 // FIXME: Deal with the implicit object parameter for static member 1464 // functions. (C++ 13.3.3p1). 1465 1466 // (C++ 13.3.3p1): a viable function F1 is defined to be a better 1467 // function than another viable function F2 if for all arguments i, 1468 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and 1469 // then... 1470 unsigned NumArgs = Cand1.Conversions.size(); 1471 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 1472 bool HasBetterConversion = false; 1473 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 1474 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx], 1475 Cand2.Conversions[ArgIdx])) { 1476 case ImplicitConversionSequence::Better: 1477 // Cand1 has a better conversion sequence. 1478 HasBetterConversion = true; 1479 break; 1480 1481 case ImplicitConversionSequence::Worse: 1482 // Cand1 can't be better than Cand2. 1483 return false; 1484 1485 case ImplicitConversionSequence::Indistinguishable: 1486 // Do nothing. 1487 break; 1488 } 1489 } 1490 1491 if (HasBetterConversion) 1492 return true; 1493 1494 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be implemented. 1495 1496 return false; 1497} 1498 1499/// BestViableFunction - Computes the best viable function (C++ 13.3.3) 1500/// within an overload candidate set. If overloading is successful, 1501/// the result will be OR_Success and Best will be set to point to the 1502/// best viable function within the candidate set. Otherwise, one of 1503/// several kinds of errors will be returned; see 1504/// Sema::OverloadingResult. 1505Sema::OverloadingResult 1506Sema::BestViableFunction(OverloadCandidateSet& CandidateSet, 1507 OverloadCandidateSet::iterator& Best) 1508{ 1509 // Find the best viable function. 1510 Best = CandidateSet.end(); 1511 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 1512 Cand != CandidateSet.end(); ++Cand) { 1513 if (Cand->Viable) { 1514 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best)) 1515 Best = Cand; 1516 } 1517 } 1518 1519 // If we didn't find any viable functions, abort. 1520 if (Best == CandidateSet.end()) 1521 return OR_No_Viable_Function; 1522 1523 // Make sure that this function is better than every other viable 1524 // function. If not, we have an ambiguity. 1525 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 1526 Cand != CandidateSet.end(); ++Cand) { 1527 if (Cand->Viable && 1528 Cand != Best && 1529 !isBetterOverloadCandidate(*Best, *Cand)) 1530 return OR_Ambiguous; 1531 } 1532 1533 // Best is the best viable function. 1534 return OR_Success; 1535} 1536 1537/// PrintOverloadCandidates - When overload resolution fails, prints 1538/// diagnostic messages containing the candidates in the candidate 1539/// set. If OnlyViable is true, only viable candidates will be printed. 1540void 1541Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet, 1542 bool OnlyViable) 1543{ 1544 OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 1545 LastCand = CandidateSet.end(); 1546 for (; Cand != LastCand; ++Cand) { 1547 if (Cand->Viable ||!OnlyViable) 1548 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate); 1549 } 1550} 1551 1552} // end namespace clang 1553