SemaOverload.cpp revision f9eb905197e44ed5634205512074993f6f40470d
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/Lex/Preprocessor.h" 18#include "clang/AST/ASTContext.h" 19#include "clang/AST/Expr.h" 20#include "clang/AST/ExprCXX.h" 21#include "clang/AST/TypeOrdering.h" 22#include "llvm/ADT/SmallPtrSet.h" 23#include "llvm/Support/Compiler.h" 24#include <algorithm> 25 26namespace clang { 27 28/// GetConversionCategory - Retrieve the implicit conversion 29/// category corresponding to the given implicit conversion kind. 30ImplicitConversionCategory 31GetConversionCategory(ImplicitConversionKind Kind) { 32 static const ImplicitConversionCategory 33 Category[(int)ICK_Num_Conversion_Kinds] = { 34 ICC_Identity, 35 ICC_Lvalue_Transformation, 36 ICC_Lvalue_Transformation, 37 ICC_Lvalue_Transformation, 38 ICC_Qualification_Adjustment, 39 ICC_Promotion, 40 ICC_Promotion, 41 ICC_Conversion, 42 ICC_Conversion, 43 ICC_Conversion, 44 ICC_Conversion, 45 ICC_Conversion, 46 ICC_Conversion, 47 ICC_Conversion 48 }; 49 return Category[(int)Kind]; 50} 51 52/// GetConversionRank - Retrieve the implicit conversion rank 53/// corresponding to the given implicit conversion kind. 54ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) { 55 static const ImplicitConversionRank 56 Rank[(int)ICK_Num_Conversion_Kinds] = { 57 ICR_Exact_Match, 58 ICR_Exact_Match, 59 ICR_Exact_Match, 60 ICR_Exact_Match, 61 ICR_Exact_Match, 62 ICR_Promotion, 63 ICR_Promotion, 64 ICR_Conversion, 65 ICR_Conversion, 66 ICR_Conversion, 67 ICR_Conversion, 68 ICR_Conversion, 69 ICR_Conversion, 70 ICR_Conversion 71 }; 72 return Rank[(int)Kind]; 73} 74 75/// GetImplicitConversionName - Return the name of this kind of 76/// implicit conversion. 77const char* GetImplicitConversionName(ImplicitConversionKind Kind) { 78 static const char* Name[(int)ICK_Num_Conversion_Kinds] = { 79 "No conversion", 80 "Lvalue-to-rvalue", 81 "Array-to-pointer", 82 "Function-to-pointer", 83 "Qualification", 84 "Integral promotion", 85 "Floating point promotion", 86 "Integral conversion", 87 "Floating conversion", 88 "Floating-integral conversion", 89 "Pointer conversion", 90 "Pointer-to-member conversion", 91 "Boolean conversion", 92 "Derived-to-base conversion" 93 }; 94 return Name[Kind]; 95} 96 97/// StandardConversionSequence - Set the standard conversion 98/// sequence to the identity conversion. 99void StandardConversionSequence::setAsIdentityConversion() { 100 First = ICK_Identity; 101 Second = ICK_Identity; 102 Third = ICK_Identity; 103 Deprecated = false; 104 ReferenceBinding = false; 105 DirectBinding = false; 106 CopyConstructor = 0; 107} 108 109/// getRank - Retrieve the rank of this standard conversion sequence 110/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the 111/// implicit conversions. 112ImplicitConversionRank StandardConversionSequence::getRank() const { 113 ImplicitConversionRank Rank = ICR_Exact_Match; 114 if (GetConversionRank(First) > Rank) 115 Rank = GetConversionRank(First); 116 if (GetConversionRank(Second) > Rank) 117 Rank = GetConversionRank(Second); 118 if (GetConversionRank(Third) > Rank) 119 Rank = GetConversionRank(Third); 120 return Rank; 121} 122 123/// isPointerConversionToBool - Determines whether this conversion is 124/// a conversion of a pointer or pointer-to-member to bool. This is 125/// used as part of the ranking of standard conversion sequences 126/// (C++ 13.3.3.2p4). 127bool StandardConversionSequence::isPointerConversionToBool() const 128{ 129 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr); 130 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr); 131 132 // Note that FromType has not necessarily been transformed by the 133 // array-to-pointer or function-to-pointer implicit conversions, so 134 // check for their presence as well as checking whether FromType is 135 // a pointer. 136 if (ToType->isBooleanType() && 137 (FromType->isPointerType() || 138 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer)) 139 return true; 140 141 return false; 142} 143 144/// isPointerConversionToVoidPointer - Determines whether this 145/// conversion is a conversion of a pointer to a void pointer. This is 146/// used as part of the ranking of standard conversion sequences (C++ 147/// 13.3.3.2p4). 148bool 149StandardConversionSequence:: 150isPointerConversionToVoidPointer(ASTContext& Context) const 151{ 152 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr); 153 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr); 154 155 // Note that FromType has not necessarily been transformed by the 156 // array-to-pointer implicit conversion, so check for its presence 157 // and redo the conversion to get a pointer. 158 if (First == ICK_Array_To_Pointer) 159 FromType = Context.getArrayDecayedType(FromType); 160 161 if (Second == ICK_Pointer_Conversion) 162 if (const PointerType* ToPtrType = ToType->getAsPointerType()) 163 return ToPtrType->getPointeeType()->isVoidType(); 164 165 return false; 166} 167 168/// DebugPrint - Print this standard conversion sequence to standard 169/// error. Useful for debugging overloading issues. 170void StandardConversionSequence::DebugPrint() const { 171 bool PrintedSomething = false; 172 if (First != ICK_Identity) { 173 fprintf(stderr, "%s", GetImplicitConversionName(First)); 174 PrintedSomething = true; 175 } 176 177 if (Second != ICK_Identity) { 178 if (PrintedSomething) { 179 fprintf(stderr, " -> "); 180 } 181 fprintf(stderr, "%s", GetImplicitConversionName(Second)); 182 183 if (CopyConstructor) { 184 fprintf(stderr, " (by copy constructor)"); 185 } else if (DirectBinding) { 186 fprintf(stderr, " (direct reference binding)"); 187 } else if (ReferenceBinding) { 188 fprintf(stderr, " (reference binding)"); 189 } 190 PrintedSomething = true; 191 } 192 193 if (Third != ICK_Identity) { 194 if (PrintedSomething) { 195 fprintf(stderr, " -> "); 196 } 197 fprintf(stderr, "%s", GetImplicitConversionName(Third)); 198 PrintedSomething = true; 199 } 200 201 if (!PrintedSomething) { 202 fprintf(stderr, "No conversions required"); 203 } 204} 205 206/// DebugPrint - Print this user-defined conversion sequence to standard 207/// error. Useful for debugging overloading issues. 208void UserDefinedConversionSequence::DebugPrint() const { 209 if (Before.First || Before.Second || Before.Third) { 210 Before.DebugPrint(); 211 fprintf(stderr, " -> "); 212 } 213 fprintf(stderr, "'%s'", ConversionFunction->getName().c_str()); 214 if (After.First || After.Second || After.Third) { 215 fprintf(stderr, " -> "); 216 After.DebugPrint(); 217 } 218} 219 220/// DebugPrint - Print this implicit conversion sequence to standard 221/// error. Useful for debugging overloading issues. 222void ImplicitConversionSequence::DebugPrint() const { 223 switch (ConversionKind) { 224 case StandardConversion: 225 fprintf(stderr, "Standard conversion: "); 226 Standard.DebugPrint(); 227 break; 228 case UserDefinedConversion: 229 fprintf(stderr, "User-defined conversion: "); 230 UserDefined.DebugPrint(); 231 break; 232 case EllipsisConversion: 233 fprintf(stderr, "Ellipsis conversion"); 234 break; 235 case BadConversion: 236 fprintf(stderr, "Bad conversion"); 237 break; 238 } 239 240 fprintf(stderr, "\n"); 241} 242 243// IsOverload - Determine whether the given New declaration is an 244// overload of the Old declaration. This routine returns false if New 245// and Old cannot be overloaded, e.g., if they are functions with the 246// same signature (C++ 1.3.10) or if the Old declaration isn't a 247// function (or overload set). When it does return false and Old is an 248// OverloadedFunctionDecl, MatchedDecl will be set to point to the 249// FunctionDecl that New cannot be overloaded with. 250// 251// Example: Given the following input: 252// 253// void f(int, float); // #1 254// void f(int, int); // #2 255// int f(int, int); // #3 256// 257// When we process #1, there is no previous declaration of "f", 258// so IsOverload will not be used. 259// 260// When we process #2, Old is a FunctionDecl for #1. By comparing the 261// parameter types, we see that #1 and #2 are overloaded (since they 262// have different signatures), so this routine returns false; 263// MatchedDecl is unchanged. 264// 265// When we process #3, Old is an OverloadedFunctionDecl containing #1 266// and #2. We compare the signatures of #3 to #1 (they're overloaded, 267// so we do nothing) and then #3 to #2. Since the signatures of #3 and 268// #2 are identical (return types of functions are not part of the 269// signature), IsOverload returns false and MatchedDecl will be set to 270// point to the FunctionDecl for #2. 271bool 272Sema::IsOverload(FunctionDecl *New, Decl* OldD, 273 OverloadedFunctionDecl::function_iterator& MatchedDecl) 274{ 275 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) { 276 // Is this new function an overload of every function in the 277 // overload set? 278 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(), 279 FuncEnd = Ovl->function_end(); 280 for (; Func != FuncEnd; ++Func) { 281 if (!IsOverload(New, *Func, MatchedDecl)) { 282 MatchedDecl = Func; 283 return false; 284 } 285 } 286 287 // This function overloads every function in the overload set. 288 return true; 289 } else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) { 290 // Is the function New an overload of the function Old? 291 QualType OldQType = Context.getCanonicalType(Old->getType()); 292 QualType NewQType = Context.getCanonicalType(New->getType()); 293 294 // Compare the signatures (C++ 1.3.10) of the two functions to 295 // determine whether they are overloads. If we find any mismatch 296 // in the signature, they are overloads. 297 298 // If either of these functions is a K&R-style function (no 299 // prototype), then we consider them to have matching signatures. 300 if (isa<FunctionTypeNoProto>(OldQType.getTypePtr()) || 301 isa<FunctionTypeNoProto>(NewQType.getTypePtr())) 302 return false; 303 304 FunctionTypeProto* OldType = cast<FunctionTypeProto>(OldQType.getTypePtr()); 305 FunctionTypeProto* NewType = cast<FunctionTypeProto>(NewQType.getTypePtr()); 306 307 // The signature of a function includes the types of its 308 // parameters (C++ 1.3.10), which includes the presence or absence 309 // of the ellipsis; see C++ DR 357). 310 if (OldQType != NewQType && 311 (OldType->getNumArgs() != NewType->getNumArgs() || 312 OldType->isVariadic() != NewType->isVariadic() || 313 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(), 314 NewType->arg_type_begin()))) 315 return true; 316 317 // If the function is a class member, its signature includes the 318 // cv-qualifiers (if any) on the function itself. 319 // 320 // As part of this, also check whether one of the member functions 321 // is static, in which case they are not overloads (C++ 322 // 13.1p2). While not part of the definition of the signature, 323 // this check is important to determine whether these functions 324 // can be overloaded. 325 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old); 326 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New); 327 if (OldMethod && NewMethod && 328 !OldMethod->isStatic() && !NewMethod->isStatic() && 329 OldQType.getCVRQualifiers() != NewQType.getCVRQualifiers()) 330 return true; 331 332 // The signatures match; this is not an overload. 333 return false; 334 } else { 335 // (C++ 13p1): 336 // Only function declarations can be overloaded; object and type 337 // declarations cannot be overloaded. 338 return false; 339 } 340} 341 342/// TryImplicitConversion - Attempt to perform an implicit conversion 343/// from the given expression (Expr) to the given type (ToType). This 344/// function returns an implicit conversion sequence that can be used 345/// to perform the initialization. Given 346/// 347/// void f(float f); 348/// void g(int i) { f(i); } 349/// 350/// this routine would produce an implicit conversion sequence to 351/// describe the initialization of f from i, which will be a standard 352/// conversion sequence containing an lvalue-to-rvalue conversion (C++ 353/// 4.1) followed by a floating-integral conversion (C++ 4.9). 354// 355/// Note that this routine only determines how the conversion can be 356/// performed; it does not actually perform the conversion. As such, 357/// it will not produce any diagnostics if no conversion is available, 358/// but will instead return an implicit conversion sequence of kind 359/// "BadConversion". 360/// 361/// If @p SuppressUserConversions, then user-defined conversions are 362/// not permitted. 363ImplicitConversionSequence 364Sema::TryImplicitConversion(Expr* From, QualType ToType, 365 bool SuppressUserConversions) 366{ 367 ImplicitConversionSequence ICS; 368 if (IsStandardConversion(From, ToType, ICS.Standard)) 369 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion; 370 else if (!SuppressUserConversions && 371 IsUserDefinedConversion(From, ToType, ICS.UserDefined)) { 372 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion; 373 // C++ [over.ics.user]p4: 374 // A conversion of an expression of class type to the same class 375 // type is given Exact Match rank, and a conversion of an 376 // expression of class type to a base class of that type is 377 // given Conversion rank, in spite of the fact that a copy 378 // constructor (i.e., a user-defined conversion function) is 379 // called for those cases. 380 if (CXXConstructorDecl *Constructor 381 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) { 382 if (Constructor->isCopyConstructor(Context)) { 383 // Turn this into a "standard" conversion sequence, so that it 384 // gets ranked with standard conversion sequences. 385 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion; 386 ICS.Standard.setAsIdentityConversion(); 387 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr(); 388 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr(); 389 ICS.Standard.CopyConstructor = Constructor; 390 if (IsDerivedFrom(From->getType().getUnqualifiedType(), 391 ToType.getUnqualifiedType())) 392 ICS.Standard.Second = ICK_Derived_To_Base; 393 } 394 } 395 } else 396 ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 397 398 return ICS; 399} 400 401/// IsStandardConversion - Determines whether there is a standard 402/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the 403/// expression From to the type ToType. Standard conversion sequences 404/// only consider non-class types; for conversions that involve class 405/// types, use TryImplicitConversion. If a conversion exists, SCS will 406/// contain the standard conversion sequence required to perform this 407/// conversion and this routine will return true. Otherwise, this 408/// routine will return false and the value of SCS is unspecified. 409bool 410Sema::IsStandardConversion(Expr* From, QualType ToType, 411 StandardConversionSequence &SCS) 412{ 413 QualType FromType = From->getType(); 414 415 // There are no standard conversions for class types, so abort early. 416 if (FromType->isRecordType() || ToType->isRecordType()) 417 return false; 418 419 // Standard conversions (C++ [conv]) 420 SCS.setAsIdentityConversion(); 421 SCS.Deprecated = false; 422 SCS.FromTypePtr = FromType.getAsOpaquePtr(); 423 SCS.CopyConstructor = 0; 424 425 // The first conversion can be an lvalue-to-rvalue conversion, 426 // array-to-pointer conversion, or function-to-pointer conversion 427 // (C++ 4p1). 428 429 // Lvalue-to-rvalue conversion (C++ 4.1): 430 // An lvalue (3.10) of a non-function, non-array type T can be 431 // converted to an rvalue. 432 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context); 433 if (argIsLvalue == Expr::LV_Valid && 434 !FromType->isFunctionType() && !FromType->isArrayType() && 435 !FromType->isOverloadType()) { 436 SCS.First = ICK_Lvalue_To_Rvalue; 437 438 // If T is a non-class type, the type of the rvalue is the 439 // cv-unqualified version of T. Otherwise, the type of the rvalue 440 // is T (C++ 4.1p1). 441 FromType = FromType.getUnqualifiedType(); 442 } 443 // Array-to-pointer conversion (C++ 4.2) 444 else if (FromType->isArrayType()) { 445 SCS.First = ICK_Array_To_Pointer; 446 447 // An lvalue or rvalue of type "array of N T" or "array of unknown 448 // bound of T" can be converted to an rvalue of type "pointer to 449 // T" (C++ 4.2p1). 450 FromType = Context.getArrayDecayedType(FromType); 451 452 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) { 453 // This conversion is deprecated. (C++ D.4). 454 SCS.Deprecated = true; 455 456 // For the purpose of ranking in overload resolution 457 // (13.3.3.1.1), this conversion is considered an 458 // array-to-pointer conversion followed by a qualification 459 // conversion (4.4). (C++ 4.2p2) 460 SCS.Second = ICK_Identity; 461 SCS.Third = ICK_Qualification; 462 SCS.ToTypePtr = ToType.getAsOpaquePtr(); 463 return true; 464 } 465 } 466 // Function-to-pointer conversion (C++ 4.3). 467 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) { 468 SCS.First = ICK_Function_To_Pointer; 469 470 // An lvalue of function type T can be converted to an rvalue of 471 // type "pointer to T." The result is a pointer to the 472 // function. (C++ 4.3p1). 473 FromType = Context.getPointerType(FromType); 474 } 475 // Address of overloaded function (C++ [over.over]). 476 else if (FunctionDecl *Fn 477 = ResolveAddressOfOverloadedFunction(From, ToType, false)) { 478 SCS.First = ICK_Function_To_Pointer; 479 480 // We were able to resolve the address of the overloaded function, 481 // so we can convert to the type of that function. 482 FromType = Fn->getType(); 483 if (ToType->isReferenceType()) 484 FromType = Context.getReferenceType(FromType); 485 else 486 FromType = Context.getPointerType(FromType); 487 } 488 // We don't require any conversions for the first step. 489 else { 490 SCS.First = ICK_Identity; 491 } 492 493 // The second conversion can be an integral promotion, floating 494 // point promotion, integral conversion, floating point conversion, 495 // floating-integral conversion, pointer conversion, 496 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 497 if (Context.getCanonicalType(FromType).getUnqualifiedType() == 498 Context.getCanonicalType(ToType).getUnqualifiedType()) { 499 // The unqualified versions of the types are the same: there's no 500 // conversion to do. 501 SCS.Second = ICK_Identity; 502 } 503 // Integral promotion (C++ 4.5). 504 else if (IsIntegralPromotion(From, FromType, ToType)) { 505 SCS.Second = ICK_Integral_Promotion; 506 FromType = ToType.getUnqualifiedType(); 507 } 508 // Floating point promotion (C++ 4.6). 509 else if (IsFloatingPointPromotion(FromType, ToType)) { 510 SCS.Second = ICK_Floating_Promotion; 511 FromType = ToType.getUnqualifiedType(); 512 } 513 // Integral conversions (C++ 4.7). 514 // FIXME: isIntegralType shouldn't be true for enums in C++. 515 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) && 516 (ToType->isIntegralType() && !ToType->isEnumeralType())) { 517 SCS.Second = ICK_Integral_Conversion; 518 FromType = ToType.getUnqualifiedType(); 519 } 520 // Floating point conversions (C++ 4.8). 521 else if (FromType->isFloatingType() && ToType->isFloatingType()) { 522 SCS.Second = ICK_Floating_Conversion; 523 FromType = ToType.getUnqualifiedType(); 524 } 525 // Floating-integral conversions (C++ 4.9). 526 // FIXME: isIntegralType shouldn't be true for enums in C++. 527 else if ((FromType->isFloatingType() && 528 ToType->isIntegralType() && !ToType->isBooleanType() && 529 !ToType->isEnumeralType()) || 530 ((FromType->isIntegralType() || FromType->isEnumeralType()) && 531 ToType->isFloatingType())) { 532 SCS.Second = ICK_Floating_Integral; 533 FromType = ToType.getUnqualifiedType(); 534 } 535 // Pointer conversions (C++ 4.10). 536 else if (IsPointerConversion(From, FromType, ToType, FromType)) { 537 SCS.Second = ICK_Pointer_Conversion; 538 } 539 // FIXME: Pointer to member conversions (4.11). 540 // Boolean conversions (C++ 4.12). 541 // FIXME: pointer-to-member type 542 else if (ToType->isBooleanType() && 543 (FromType->isArithmeticType() || 544 FromType->isEnumeralType() || 545 FromType->isPointerType())) { 546 SCS.Second = ICK_Boolean_Conversion; 547 FromType = Context.BoolTy; 548 } else { 549 // No second conversion required. 550 SCS.Second = ICK_Identity; 551 } 552 553 QualType CanonFrom; 554 QualType CanonTo; 555 // The third conversion can be a qualification conversion (C++ 4p1). 556 if (IsQualificationConversion(FromType, ToType)) { 557 SCS.Third = ICK_Qualification; 558 FromType = ToType; 559 CanonFrom = Context.getCanonicalType(FromType); 560 CanonTo = Context.getCanonicalType(ToType); 561 } else { 562 // No conversion required 563 SCS.Third = ICK_Identity; 564 565 // C++ [over.best.ics]p6: 566 // [...] Any difference in top-level cv-qualification is 567 // subsumed by the initialization itself and does not constitute 568 // a conversion. [...] 569 CanonFrom = Context.getCanonicalType(FromType); 570 CanonTo = Context.getCanonicalType(ToType); 571 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() && 572 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) { 573 FromType = ToType; 574 CanonFrom = CanonTo; 575 } 576 } 577 578 // If we have not converted the argument type to the parameter type, 579 // this is a bad conversion sequence. 580 if (CanonFrom != CanonTo) 581 return false; 582 583 SCS.ToTypePtr = FromType.getAsOpaquePtr(); 584 return true; 585} 586 587/// IsIntegralPromotion - Determines whether the conversion from the 588/// expression From (whose potentially-adjusted type is FromType) to 589/// ToType is an integral promotion (C++ 4.5). If so, returns true and 590/// sets PromotedType to the promoted type. 591bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) 592{ 593 const BuiltinType *To = ToType->getAsBuiltinType(); 594 // All integers are built-in. 595 if (!To) { 596 return false; 597 } 598 599 // An rvalue of type char, signed char, unsigned char, short int, or 600 // unsigned short int can be converted to an rvalue of type int if 601 // int can represent all the values of the source type; otherwise, 602 // the source rvalue can be converted to an rvalue of type unsigned 603 // int (C++ 4.5p1). 604 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) { 605 if (// We can promote any signed, promotable integer type to an int 606 (FromType->isSignedIntegerType() || 607 // We can promote any unsigned integer type whose size is 608 // less than int to an int. 609 (!FromType->isSignedIntegerType() && 610 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 611 return To->getKind() == BuiltinType::Int; 612 } 613 614 return To->getKind() == BuiltinType::UInt; 615 } 616 617 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2) 618 // can be converted to an rvalue of the first of the following types 619 // that can represent all the values of its underlying type: int, 620 // unsigned int, long, or unsigned long (C++ 4.5p2). 621 if ((FromType->isEnumeralType() || FromType->isWideCharType()) 622 && ToType->isIntegerType()) { 623 // Determine whether the type we're converting from is signed or 624 // unsigned. 625 bool FromIsSigned; 626 uint64_t FromSize = Context.getTypeSize(FromType); 627 if (const EnumType *FromEnumType = FromType->getAsEnumType()) { 628 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType(); 629 FromIsSigned = UnderlyingType->isSignedIntegerType(); 630 } else { 631 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now. 632 FromIsSigned = true; 633 } 634 635 // The types we'll try to promote to, in the appropriate 636 // order. Try each of these types. 637 QualType PromoteTypes[4] = { 638 Context.IntTy, Context.UnsignedIntTy, 639 Context.LongTy, Context.UnsignedLongTy 640 }; 641 for (int Idx = 0; Idx < 4; ++Idx) { 642 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 643 if (FromSize < ToSize || 644 (FromSize == ToSize && 645 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 646 // We found the type that we can promote to. If this is the 647 // type we wanted, we have a promotion. Otherwise, no 648 // promotion. 649 return Context.getCanonicalType(ToType).getUnqualifiedType() 650 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType(); 651 } 652 } 653 } 654 655 // An rvalue for an integral bit-field (9.6) can be converted to an 656 // rvalue of type int if int can represent all the values of the 657 // bit-field; otherwise, it can be converted to unsigned int if 658 // unsigned int can represent all the values of the bit-field. If 659 // the bit-field is larger yet, no integral promotion applies to 660 // it. If the bit-field has an enumerated type, it is treated as any 661 // other value of that type for promotion purposes (C++ 4.5p3). 662 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) { 663 using llvm::APSInt; 664 FieldDecl *MemberDecl = MemRef->getMemberDecl(); 665 APSInt BitWidth; 666 if (MemberDecl->isBitField() && 667 FromType->isIntegralType() && !FromType->isEnumeralType() && 668 From->isIntegerConstantExpr(BitWidth, Context)) { 669 APSInt ToSize(Context.getTypeSize(ToType)); 670 671 // Are we promoting to an int from a bitfield that fits in an int? 672 if (BitWidth < ToSize || 673 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 674 return To->getKind() == BuiltinType::Int; 675 } 676 677 // Are we promoting to an unsigned int from an unsigned bitfield 678 // that fits into an unsigned int? 679 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 680 return To->getKind() == BuiltinType::UInt; 681 } 682 683 return false; 684 } 685 } 686 687 // An rvalue of type bool can be converted to an rvalue of type int, 688 // with false becoming zero and true becoming one (C++ 4.5p4). 689 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 690 return true; 691 } 692 693 return false; 694} 695 696/// IsFloatingPointPromotion - Determines whether the conversion from 697/// FromType to ToType is a floating point promotion (C++ 4.6). If so, 698/// returns true and sets PromotedType to the promoted type. 699bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) 700{ 701 /// An rvalue of type float can be converted to an rvalue of type 702 /// double. (C++ 4.6p1). 703 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType()) 704 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) 705 if (FromBuiltin->getKind() == BuiltinType::Float && 706 ToBuiltin->getKind() == BuiltinType::Double) 707 return true; 708 709 return false; 710} 711 712/// IsPointerConversion - Determines whether the conversion of the 713/// expression From, which has the (possibly adjusted) type FromType, 714/// can be converted to the type ToType via a pointer conversion (C++ 715/// 4.10). If so, returns true and places the converted type (that 716/// might differ from ToType in its cv-qualifiers at some level) into 717/// ConvertedType. 718bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 719 QualType& ConvertedType) 720{ 721 const PointerType* ToTypePtr = ToType->getAsPointerType(); 722 if (!ToTypePtr) 723 return false; 724 725 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 726 if (From->isNullPointerConstant(Context)) { 727 ConvertedType = ToType; 728 return true; 729 } 730 731 // An rvalue of type "pointer to cv T," where T is an object type, 732 // can be converted to an rvalue of type "pointer to cv void" (C++ 733 // 4.10p2). 734 if (FromType->isPointerType() && 735 FromType->getAsPointerType()->getPointeeType()->isObjectType() && 736 ToTypePtr->getPointeeType()->isVoidType()) { 737 // We need to produce a pointer to cv void, where cv is the same 738 // set of cv-qualifiers as we had on the incoming pointee type. 739 QualType toPointee = ToTypePtr->getPointeeType(); 740 unsigned Quals = Context.getCanonicalType(FromType)->getAsPointerType() 741 ->getPointeeType().getCVRQualifiers(); 742 743 if (Context.getCanonicalType(ToTypePtr->getPointeeType()).getCVRQualifiers() 744 == Quals) { 745 // ToType is exactly the type we want. Use it. 746 ConvertedType = ToType; 747 } else { 748 // Build a new type with the right qualifiers. 749 ConvertedType 750 = Context.getPointerType(Context.VoidTy.getQualifiedType(Quals)); 751 } 752 return true; 753 } 754 755 // C++ [conv.ptr]p3: 756 // 757 // An rvalue of type "pointer to cv D," where D is a class type, 758 // can be converted to an rvalue of type "pointer to cv B," where 759 // B is a base class (clause 10) of D. If B is an inaccessible 760 // (clause 11) or ambiguous (10.2) base class of D, a program that 761 // necessitates this conversion is ill-formed. The result of the 762 // conversion is a pointer to the base class sub-object of the 763 // derived class object. The null pointer value is converted to 764 // the null pointer value of the destination type. 765 // 766 // Note that we do not check for ambiguity or inaccessibility 767 // here. That is handled by CheckPointerConversion. 768 if (const PointerType *FromPtrType = FromType->getAsPointerType()) 769 if (const PointerType *ToPtrType = ToType->getAsPointerType()) { 770 if (FromPtrType->getPointeeType()->isRecordType() && 771 ToPtrType->getPointeeType()->isRecordType() && 772 IsDerivedFrom(FromPtrType->getPointeeType(), 773 ToPtrType->getPointeeType())) { 774 // The conversion is okay. Now, we need to produce the type 775 // that results from this conversion, which will have the same 776 // qualifiers as the incoming type. 777 QualType CanonFromPointee 778 = Context.getCanonicalType(FromPtrType->getPointeeType()); 779 QualType ToPointee = ToPtrType->getPointeeType(); 780 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 781 unsigned Quals = CanonFromPointee.getCVRQualifiers(); 782 783 if (CanonToPointee.getCVRQualifiers() == Quals) { 784 // ToType is exactly the type we want. Use it. 785 ConvertedType = ToType; 786 } else { 787 // Build a new type with the right qualifiers. 788 ConvertedType 789 = Context.getPointerType(CanonToPointee.getQualifiedType(Quals)); 790 } 791 return true; 792 } 793 } 794 795 return false; 796} 797 798/// CheckPointerConversion - Check the pointer conversion from the 799/// expression From to the type ToType. This routine checks for 800/// ambiguous (FIXME: or inaccessible) derived-to-base pointer 801/// conversions for which IsPointerConversion has already returned 802/// true. It returns true and produces a diagnostic if there was an 803/// error, or returns false otherwise. 804bool Sema::CheckPointerConversion(Expr *From, QualType ToType) { 805 QualType FromType = From->getType(); 806 807 if (const PointerType *FromPtrType = FromType->getAsPointerType()) 808 if (const PointerType *ToPtrType = ToType->getAsPointerType()) { 809 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 810 /*DetectVirtual=*/false); 811 QualType FromPointeeType = FromPtrType->getPointeeType(), 812 ToPointeeType = ToPtrType->getPointeeType(); 813 if (FromPointeeType->isRecordType() && 814 ToPointeeType->isRecordType()) { 815 // We must have a derived-to-base conversion. Check an 816 // ambiguous or inaccessible conversion. 817 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 818 From->getExprLoc(), 819 From->getSourceRange()); 820 } 821 } 822 823 return false; 824} 825 826/// IsQualificationConversion - Determines whether the conversion from 827/// an rvalue of type FromType to ToType is a qualification conversion 828/// (C++ 4.4). 829bool 830Sema::IsQualificationConversion(QualType FromType, QualType ToType) 831{ 832 FromType = Context.getCanonicalType(FromType); 833 ToType = Context.getCanonicalType(ToType); 834 835 // If FromType and ToType are the same type, this is not a 836 // qualification conversion. 837 if (FromType == ToType) 838 return false; 839 840 // (C++ 4.4p4): 841 // A conversion can add cv-qualifiers at levels other than the first 842 // in multi-level pointers, subject to the following rules: [...] 843 bool PreviousToQualsIncludeConst = true; 844 bool UnwrappedAnyPointer = false; 845 while (UnwrapSimilarPointerTypes(FromType, ToType)) { 846 // Within each iteration of the loop, we check the qualifiers to 847 // determine if this still looks like a qualification 848 // conversion. Then, if all is well, we unwrap one more level of 849 // pointers or pointers-to-members and do it all again 850 // until there are no more pointers or pointers-to-members left to 851 // unwrap. 852 UnwrappedAnyPointer = true; 853 854 // -- for every j > 0, if const is in cv 1,j then const is in cv 855 // 2,j, and similarly for volatile. 856 if (!ToType.isAtLeastAsQualifiedAs(FromType)) 857 return false; 858 859 // -- if the cv 1,j and cv 2,j are different, then const is in 860 // every cv for 0 < k < j. 861 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers() 862 && !PreviousToQualsIncludeConst) 863 return false; 864 865 // Keep track of whether all prior cv-qualifiers in the "to" type 866 // include const. 867 PreviousToQualsIncludeConst 868 = PreviousToQualsIncludeConst && ToType.isConstQualified(); 869 } 870 871 // We are left with FromType and ToType being the pointee types 872 // after unwrapping the original FromType and ToType the same number 873 // of types. If we unwrapped any pointers, and if FromType and 874 // ToType have the same unqualified type (since we checked 875 // qualifiers above), then this is a qualification conversion. 876 return UnwrappedAnyPointer && 877 FromType.getUnqualifiedType() == ToType.getUnqualifiedType(); 878} 879 880/// IsUserDefinedConversion - Determines whether there is a 881/// user-defined conversion sequence (C++ [over.ics.user]) that 882/// converts expression From to the type ToType. If such a conversion 883/// exists, User will contain the user-defined conversion sequence 884/// that performs such a conversion and this routine will return 885/// true. Otherwise, this routine returns false and User is 886/// unspecified. 887bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType, 888 UserDefinedConversionSequence& User) 889{ 890 OverloadCandidateSet CandidateSet; 891 if (const CXXRecordType *ToRecordType 892 = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) { 893 // C++ [over.match.ctor]p1: 894 // When objects of class type are direct-initialized (8.5), or 895 // copy-initialized from an expression of the same or a 896 // derived class type (8.5), overload resolution selects the 897 // constructor. [...] For copy-initialization, the candidate 898 // functions are all the converting constructors (12.3.1) of 899 // that class. The argument list is the expression-list within 900 // the parentheses of the initializer. 901 CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl(); 902 const OverloadedFunctionDecl *Constructors = ToRecordDecl->getConstructors(); 903 for (OverloadedFunctionDecl::function_const_iterator func 904 = Constructors->function_begin(); 905 func != Constructors->function_end(); ++func) { 906 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*func); 907 if (Constructor->isConvertingConstructor()) 908 AddOverloadCandidate(Constructor, &From, 1, CandidateSet, 909 /*SuppressUserConversions=*/true); 910 } 911 } 912 913 if (const CXXRecordType *FromRecordType 914 = dyn_cast_or_null<CXXRecordType>(From->getType()->getAsRecordType())) { 915 // Add all of the conversion functions as candidates. 916 // FIXME: Look for conversions in base classes! 917 CXXRecordDecl *FromRecordDecl = FromRecordType->getDecl(); 918 OverloadedFunctionDecl *Conversions 919 = FromRecordDecl->getConversionFunctions(); 920 for (OverloadedFunctionDecl::function_iterator Func 921 = Conversions->function_begin(); 922 Func != Conversions->function_end(); ++Func) { 923 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func); 924 AddConversionCandidate(Conv, From, ToType, CandidateSet); 925 } 926 } 927 928 OverloadCandidateSet::iterator Best; 929 switch (BestViableFunction(CandidateSet, Best)) { 930 case OR_Success: 931 // Record the standard conversion we used and the conversion function. 932 if (CXXConstructorDecl *Constructor 933 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 934 // C++ [over.ics.user]p1: 935 // If the user-defined conversion is specified by a 936 // constructor (12.3.1), the initial standard conversion 937 // sequence converts the source type to the type required by 938 // the argument of the constructor. 939 // 940 // FIXME: What about ellipsis conversions? 941 QualType ThisType = Constructor->getThisType(Context); 942 User.Before = Best->Conversions[0].Standard; 943 User.ConversionFunction = Constructor; 944 User.After.setAsIdentityConversion(); 945 User.After.FromTypePtr 946 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr(); 947 User.After.ToTypePtr = ToType.getAsOpaquePtr(); 948 return true; 949 } else if (CXXConversionDecl *Conversion 950 = dyn_cast<CXXConversionDecl>(Best->Function)) { 951 // C++ [over.ics.user]p1: 952 // 953 // [...] If the user-defined conversion is specified by a 954 // conversion function (12.3.2), the initial standard 955 // conversion sequence converts the source type to the 956 // implicit object parameter of the conversion function. 957 User.Before = Best->Conversions[0].Standard; 958 User.ConversionFunction = Conversion; 959 960 // C++ [over.ics.user]p2: 961 // The second standard conversion sequence converts the 962 // result of the user-defined conversion to the target type 963 // for the sequence. Since an implicit conversion sequence 964 // is an initialization, the special rules for 965 // initialization by user-defined conversion apply when 966 // selecting the best user-defined conversion for a 967 // user-defined conversion sequence (see 13.3.3 and 968 // 13.3.3.1). 969 User.After = Best->FinalConversion; 970 return true; 971 } else { 972 assert(false && "Not a constructor or conversion function?"); 973 return false; 974 } 975 976 case OR_No_Viable_Function: 977 // No conversion here! We're done. 978 return false; 979 980 case OR_Ambiguous: 981 // FIXME: See C++ [over.best.ics]p10 for the handling of 982 // ambiguous conversion sequences. 983 return false; 984 } 985 986 return false; 987} 988 989/// CompareImplicitConversionSequences - Compare two implicit 990/// conversion sequences to determine whether one is better than the 991/// other or if they are indistinguishable (C++ 13.3.3.2). 992ImplicitConversionSequence::CompareKind 993Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1, 994 const ImplicitConversionSequence& ICS2) 995{ 996 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 997 // conversion sequences (as defined in 13.3.3.1) 998 // -- a standard conversion sequence (13.3.3.1.1) is a better 999 // conversion sequence than a user-defined conversion sequence or 1000 // an ellipsis conversion sequence, and 1001 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 1002 // conversion sequence than an ellipsis conversion sequence 1003 // (13.3.3.1.3). 1004 // 1005 if (ICS1.ConversionKind < ICS2.ConversionKind) 1006 return ImplicitConversionSequence::Better; 1007 else if (ICS2.ConversionKind < ICS1.ConversionKind) 1008 return ImplicitConversionSequence::Worse; 1009 1010 // Two implicit conversion sequences of the same form are 1011 // indistinguishable conversion sequences unless one of the 1012 // following rules apply: (C++ 13.3.3.2p3): 1013 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion) 1014 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard); 1015 else if (ICS1.ConversionKind == 1016 ImplicitConversionSequence::UserDefinedConversion) { 1017 // User-defined conversion sequence U1 is a better conversion 1018 // sequence than another user-defined conversion sequence U2 if 1019 // they contain the same user-defined conversion function or 1020 // constructor and if the second standard conversion sequence of 1021 // U1 is better than the second standard conversion sequence of 1022 // U2 (C++ 13.3.3.2p3). 1023 if (ICS1.UserDefined.ConversionFunction == 1024 ICS2.UserDefined.ConversionFunction) 1025 return CompareStandardConversionSequences(ICS1.UserDefined.After, 1026 ICS2.UserDefined.After); 1027 } 1028 1029 return ImplicitConversionSequence::Indistinguishable; 1030} 1031 1032/// CompareStandardConversionSequences - Compare two standard 1033/// conversion sequences to determine whether one is better than the 1034/// other or if they are indistinguishable (C++ 13.3.3.2p3). 1035ImplicitConversionSequence::CompareKind 1036Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1, 1037 const StandardConversionSequence& SCS2) 1038{ 1039 // Standard conversion sequence S1 is a better conversion sequence 1040 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 1041 1042 // -- S1 is a proper subsequence of S2 (comparing the conversion 1043 // sequences in the canonical form defined by 13.3.3.1.1, 1044 // excluding any Lvalue Transformation; the identity conversion 1045 // sequence is considered to be a subsequence of any 1046 // non-identity conversion sequence) or, if not that, 1047 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third) 1048 // Neither is a proper subsequence of the other. Do nothing. 1049 ; 1050 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) || 1051 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) || 1052 (SCS1.Second == ICK_Identity && 1053 SCS1.Third == ICK_Identity)) 1054 // SCS1 is a proper subsequence of SCS2. 1055 return ImplicitConversionSequence::Better; 1056 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) || 1057 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) || 1058 (SCS2.Second == ICK_Identity && 1059 SCS2.Third == ICK_Identity)) 1060 // SCS2 is a proper subsequence of SCS1. 1061 return ImplicitConversionSequence::Worse; 1062 1063 // -- the rank of S1 is better than the rank of S2 (by the rules 1064 // defined below), or, if not that, 1065 ImplicitConversionRank Rank1 = SCS1.getRank(); 1066 ImplicitConversionRank Rank2 = SCS2.getRank(); 1067 if (Rank1 < Rank2) 1068 return ImplicitConversionSequence::Better; 1069 else if (Rank2 < Rank1) 1070 return ImplicitConversionSequence::Worse; 1071 1072 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 1073 // are indistinguishable unless one of the following rules 1074 // applies: 1075 1076 // A conversion that is not a conversion of a pointer, or 1077 // pointer to member, to bool is better than another conversion 1078 // that is such a conversion. 1079 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 1080 return SCS2.isPointerConversionToBool() 1081 ? ImplicitConversionSequence::Better 1082 : ImplicitConversionSequence::Worse; 1083 1084 // C++ [over.ics.rank]p4b2: 1085 // 1086 // If class B is derived directly or indirectly from class A, 1087 // conversion of B* to A* is better than conversion of B* to 1088 // void*, and conversion of A* to void* is better than conversion 1089 // of B* to void*. 1090 bool SCS1ConvertsToVoid 1091 = SCS1.isPointerConversionToVoidPointer(Context); 1092 bool SCS2ConvertsToVoid 1093 = SCS2.isPointerConversionToVoidPointer(Context); 1094 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 1095 // Exactly one of the conversion sequences is a conversion to 1096 // a void pointer; it's the worse conversion. 1097 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 1098 : ImplicitConversionSequence::Worse; 1099 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 1100 // Neither conversion sequence converts to a void pointer; compare 1101 // their derived-to-base conversions. 1102 if (ImplicitConversionSequence::CompareKind DerivedCK 1103 = CompareDerivedToBaseConversions(SCS1, SCS2)) 1104 return DerivedCK; 1105 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) { 1106 // Both conversion sequences are conversions to void 1107 // pointers. Compare the source types to determine if there's an 1108 // inheritance relationship in their sources. 1109 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr); 1110 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr); 1111 1112 // Adjust the types we're converting from via the array-to-pointer 1113 // conversion, if we need to. 1114 if (SCS1.First == ICK_Array_To_Pointer) 1115 FromType1 = Context.getArrayDecayedType(FromType1); 1116 if (SCS2.First == ICK_Array_To_Pointer) 1117 FromType2 = Context.getArrayDecayedType(FromType2); 1118 1119 QualType FromPointee1 1120 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1121 QualType FromPointee2 1122 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1123 1124 if (IsDerivedFrom(FromPointee2, FromPointee1)) 1125 return ImplicitConversionSequence::Better; 1126 else if (IsDerivedFrom(FromPointee1, FromPointee2)) 1127 return ImplicitConversionSequence::Worse; 1128 } 1129 1130 // Compare based on qualification conversions (C++ 13.3.3.2p3, 1131 // bullet 3). 1132 if (ImplicitConversionSequence::CompareKind QualCK 1133 = CompareQualificationConversions(SCS1, SCS2)) 1134 return QualCK; 1135 1136 // C++ [over.ics.rank]p3b4: 1137 // -- S1 and S2 are reference bindings (8.5.3), and the types to 1138 // which the references refer are the same type except for 1139 // top-level cv-qualifiers, and the type to which the reference 1140 // initialized by S2 refers is more cv-qualified than the type 1141 // to which the reference initialized by S1 refers. 1142 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 1143 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr); 1144 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr); 1145 T1 = Context.getCanonicalType(T1); 1146 T2 = Context.getCanonicalType(T2); 1147 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) { 1148 if (T2.isMoreQualifiedThan(T1)) 1149 return ImplicitConversionSequence::Better; 1150 else if (T1.isMoreQualifiedThan(T2)) 1151 return ImplicitConversionSequence::Worse; 1152 } 1153 } 1154 1155 return ImplicitConversionSequence::Indistinguishable; 1156} 1157 1158/// CompareQualificationConversions - Compares two standard conversion 1159/// sequences to determine whether they can be ranked based on their 1160/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 1161ImplicitConversionSequence::CompareKind 1162Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1, 1163 const StandardConversionSequence& SCS2) 1164{ 1165 // C++ 13.3.3.2p3: 1166 // -- S1 and S2 differ only in their qualification conversion and 1167 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 1168 // cv-qualification signature of type T1 is a proper subset of 1169 // the cv-qualification signature of type T2, and S1 is not the 1170 // deprecated string literal array-to-pointer conversion (4.2). 1171 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 1172 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 1173 return ImplicitConversionSequence::Indistinguishable; 1174 1175 // FIXME: the example in the standard doesn't use a qualification 1176 // conversion (!) 1177 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr); 1178 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr); 1179 T1 = Context.getCanonicalType(T1); 1180 T2 = Context.getCanonicalType(T2); 1181 1182 // If the types are the same, we won't learn anything by unwrapped 1183 // them. 1184 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) 1185 return ImplicitConversionSequence::Indistinguishable; 1186 1187 ImplicitConversionSequence::CompareKind Result 1188 = ImplicitConversionSequence::Indistinguishable; 1189 while (UnwrapSimilarPointerTypes(T1, T2)) { 1190 // Within each iteration of the loop, we check the qualifiers to 1191 // determine if this still looks like a qualification 1192 // conversion. Then, if all is well, we unwrap one more level of 1193 // pointers or pointers-to-members and do it all again 1194 // until there are no more pointers or pointers-to-members left 1195 // to unwrap. This essentially mimics what 1196 // IsQualificationConversion does, but here we're checking for a 1197 // strict subset of qualifiers. 1198 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 1199 // The qualifiers are the same, so this doesn't tell us anything 1200 // about how the sequences rank. 1201 ; 1202 else if (T2.isMoreQualifiedThan(T1)) { 1203 // T1 has fewer qualifiers, so it could be the better sequence. 1204 if (Result == ImplicitConversionSequence::Worse) 1205 // Neither has qualifiers that are a subset of the other's 1206 // qualifiers. 1207 return ImplicitConversionSequence::Indistinguishable; 1208 1209 Result = ImplicitConversionSequence::Better; 1210 } else if (T1.isMoreQualifiedThan(T2)) { 1211 // T2 has fewer qualifiers, so it could be the better sequence. 1212 if (Result == ImplicitConversionSequence::Better) 1213 // Neither has qualifiers that are a subset of the other's 1214 // qualifiers. 1215 return ImplicitConversionSequence::Indistinguishable; 1216 1217 Result = ImplicitConversionSequence::Worse; 1218 } else { 1219 // Qualifiers are disjoint. 1220 return ImplicitConversionSequence::Indistinguishable; 1221 } 1222 1223 // If the types after this point are equivalent, we're done. 1224 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) 1225 break; 1226 } 1227 1228 // Check that the winning standard conversion sequence isn't using 1229 // the deprecated string literal array to pointer conversion. 1230 switch (Result) { 1231 case ImplicitConversionSequence::Better: 1232 if (SCS1.Deprecated) 1233 Result = ImplicitConversionSequence::Indistinguishable; 1234 break; 1235 1236 case ImplicitConversionSequence::Indistinguishable: 1237 break; 1238 1239 case ImplicitConversionSequence::Worse: 1240 if (SCS2.Deprecated) 1241 Result = ImplicitConversionSequence::Indistinguishable; 1242 break; 1243 } 1244 1245 return Result; 1246} 1247 1248/// CompareDerivedToBaseConversions - Compares two standard conversion 1249/// sequences to determine whether they can be ranked based on their 1250/// various kinds of derived-to-base conversions (C++ [over.ics.rank]p4b3). 1251ImplicitConversionSequence::CompareKind 1252Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1, 1253 const StandardConversionSequence& SCS2) { 1254 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr); 1255 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr); 1256 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr); 1257 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr); 1258 1259 // Adjust the types we're converting from via the array-to-pointer 1260 // conversion, if we need to. 1261 if (SCS1.First == ICK_Array_To_Pointer) 1262 FromType1 = Context.getArrayDecayedType(FromType1); 1263 if (SCS2.First == ICK_Array_To_Pointer) 1264 FromType2 = Context.getArrayDecayedType(FromType2); 1265 1266 // Canonicalize all of the types. 1267 FromType1 = Context.getCanonicalType(FromType1); 1268 ToType1 = Context.getCanonicalType(ToType1); 1269 FromType2 = Context.getCanonicalType(FromType2); 1270 ToType2 = Context.getCanonicalType(ToType2); 1271 1272 // C++ [over.ics.rank]p4b3: 1273 // 1274 // If class B is derived directly or indirectly from class A and 1275 // class C is derived directly or indirectly from B, 1276 1277 // Compare based on pointer conversions. 1278 if (SCS1.Second == ICK_Pointer_Conversion && 1279 SCS2.Second == ICK_Pointer_Conversion) { 1280 QualType FromPointee1 1281 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1282 QualType ToPointee1 1283 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1284 QualType FromPointee2 1285 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1286 QualType ToPointee2 1287 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1288 // -- conversion of C* to B* is better than conversion of C* to A*, 1289 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 1290 if (IsDerivedFrom(ToPointee1, ToPointee2)) 1291 return ImplicitConversionSequence::Better; 1292 else if (IsDerivedFrom(ToPointee2, ToPointee1)) 1293 return ImplicitConversionSequence::Worse; 1294 } 1295 1296 // -- conversion of B* to A* is better than conversion of C* to A*, 1297 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 1298 if (IsDerivedFrom(FromPointee2, FromPointee1)) 1299 return ImplicitConversionSequence::Better; 1300 else if (IsDerivedFrom(FromPointee1, FromPointee2)) 1301 return ImplicitConversionSequence::Worse; 1302 } 1303 } 1304 1305 // Compare based on reference bindings. 1306 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding && 1307 SCS1.Second == ICK_Derived_To_Base) { 1308 // -- binding of an expression of type C to a reference of type 1309 // B& is better than binding an expression of type C to a 1310 // reference of type A&, 1311 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() && 1312 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) { 1313 if (IsDerivedFrom(ToType1, ToType2)) 1314 return ImplicitConversionSequence::Better; 1315 else if (IsDerivedFrom(ToType2, ToType1)) 1316 return ImplicitConversionSequence::Worse; 1317 } 1318 1319 // -- binding of an expression of type B to a reference of type 1320 // A& is better than binding an expression of type C to a 1321 // reference of type A&, 1322 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() && 1323 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) { 1324 if (IsDerivedFrom(FromType2, FromType1)) 1325 return ImplicitConversionSequence::Better; 1326 else if (IsDerivedFrom(FromType1, FromType2)) 1327 return ImplicitConversionSequence::Worse; 1328 } 1329 } 1330 1331 1332 // FIXME: conversion of A::* to B::* is better than conversion of 1333 // A::* to C::*, 1334 1335 // FIXME: conversion of B::* to C::* is better than conversion of 1336 // A::* to C::*, and 1337 1338 if (SCS1.CopyConstructor && SCS2.CopyConstructor && 1339 SCS1.Second == ICK_Derived_To_Base) { 1340 // -- conversion of C to B is better than conversion of C to A, 1341 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() && 1342 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) { 1343 if (IsDerivedFrom(ToType1, ToType2)) 1344 return ImplicitConversionSequence::Better; 1345 else if (IsDerivedFrom(ToType2, ToType1)) 1346 return ImplicitConversionSequence::Worse; 1347 } 1348 1349 // -- conversion of B to A is better than conversion of C to A. 1350 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() && 1351 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) { 1352 if (IsDerivedFrom(FromType2, FromType1)) 1353 return ImplicitConversionSequence::Better; 1354 else if (IsDerivedFrom(FromType1, FromType2)) 1355 return ImplicitConversionSequence::Worse; 1356 } 1357 } 1358 1359 return ImplicitConversionSequence::Indistinguishable; 1360} 1361 1362/// TryCopyInitialization - Try to copy-initialize a value of type 1363/// ToType from the expression From. Return the implicit conversion 1364/// sequence required to pass this argument, which may be a bad 1365/// conversion sequence (meaning that the argument cannot be passed to 1366/// a parameter of this type). If @p SuppressUserConversions, then we 1367/// do not permit any user-defined conversion sequences. 1368ImplicitConversionSequence 1369Sema::TryCopyInitialization(Expr *From, QualType ToType, 1370 bool SuppressUserConversions) { 1371 if (!getLangOptions().CPlusPlus) { 1372 // In C, copy initialization is the same as performing an assignment. 1373 AssignConvertType ConvTy = 1374 CheckSingleAssignmentConstraints(ToType, From); 1375 ImplicitConversionSequence ICS; 1376 if (getLangOptions().NoExtensions? ConvTy != Compatible 1377 : ConvTy == Incompatible) 1378 ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 1379 else 1380 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion; 1381 return ICS; 1382 } else if (ToType->isReferenceType()) { 1383 ImplicitConversionSequence ICS; 1384 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions); 1385 return ICS; 1386 } else { 1387 return TryImplicitConversion(From, ToType, SuppressUserConversions); 1388 } 1389} 1390 1391/// PerformArgumentPassing - Pass the argument Arg into a parameter of 1392/// type ToType. Returns true (and emits a diagnostic) if there was 1393/// an error, returns false if the initialization succeeded. 1394bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType, 1395 const char* Flavor) { 1396 if (!getLangOptions().CPlusPlus) { 1397 // In C, argument passing is the same as performing an assignment. 1398 QualType FromType = From->getType(); 1399 AssignConvertType ConvTy = 1400 CheckSingleAssignmentConstraints(ToType, From); 1401 1402 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType, 1403 FromType, From, Flavor); 1404 } else if (ToType->isReferenceType()) { 1405 return CheckReferenceInit(From, ToType); 1406 } else { 1407 if (PerformImplicitConversion(From, ToType)) 1408 return Diag(From->getSourceRange().getBegin(), 1409 diag::err_typecheck_convert_incompatible) 1410 << ToType.getAsString() << From->getType().getAsString() 1411 << Flavor << From->getSourceRange(); 1412 else 1413 return false; 1414 } 1415} 1416 1417/// TryObjectArgumentInitialization - Try to initialize the object 1418/// parameter of the given member function (@c Method) from the 1419/// expression @p From. 1420ImplicitConversionSequence 1421Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) { 1422 QualType ClassType = Context.getTypeDeclType(Method->getParent()); 1423 unsigned MethodQuals = Method->getTypeQualifiers(); 1424 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals); 1425 1426 // Set up the conversion sequence as a "bad" conversion, to allow us 1427 // to exit early. 1428 ImplicitConversionSequence ICS; 1429 ICS.Standard.setAsIdentityConversion(); 1430 ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 1431 1432 // We need to have an object of class type. 1433 QualType FromType = From->getType(); 1434 if (!FromType->isRecordType()) 1435 return ICS; 1436 1437 // The implicit object parmeter is has the type "reference to cv X", 1438 // where X is the class of which the function is a member 1439 // (C++ [over.match.funcs]p4). However, when finding an implicit 1440 // conversion sequence for the argument, we are not allowed to 1441 // create temporaries or perform user-defined conversions 1442 // (C++ [over.match.funcs]p5). We perform a simplified version of 1443 // reference binding here, that allows class rvalues to bind to 1444 // non-constant references. 1445 1446 // First check the qualifiers. We don't care about lvalue-vs-rvalue 1447 // with the implicit object parameter (C++ [over.match.funcs]p5). 1448 QualType FromTypeCanon = Context.getCanonicalType(FromType); 1449 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() && 1450 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType)) 1451 return ICS; 1452 1453 // Check that we have either the same type or a derived type. It 1454 // affects the conversion rank. 1455 QualType ClassTypeCanon = Context.getCanonicalType(ClassType); 1456 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType()) 1457 ICS.Standard.Second = ICK_Identity; 1458 else if (IsDerivedFrom(FromType, ClassType)) 1459 ICS.Standard.Second = ICK_Derived_To_Base; 1460 else 1461 return ICS; 1462 1463 // Success. Mark this as a reference binding. 1464 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion; 1465 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr(); 1466 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr(); 1467 ICS.Standard.ReferenceBinding = true; 1468 ICS.Standard.DirectBinding = true; 1469 return ICS; 1470} 1471 1472/// PerformObjectArgumentInitialization - Perform initialization of 1473/// the implicit object parameter for the given Method with the given 1474/// expression. 1475bool 1476Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) { 1477 QualType ImplicitParamType 1478 = Method->getThisType(Context)->getAsPointerType()->getPointeeType(); 1479 ImplicitConversionSequence ICS 1480 = TryObjectArgumentInitialization(From, Method); 1481 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) 1482 return Diag(From->getSourceRange().getBegin(), 1483 diag::err_implicit_object_parameter_init) 1484 << ImplicitParamType.getAsString() << From->getType().getAsString() 1485 << From->getSourceRange(); 1486 1487 if (ICS.Standard.Second == ICK_Derived_To_Base && 1488 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType, 1489 From->getSourceRange().getBegin(), 1490 From->getSourceRange())) 1491 return true; 1492 1493 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true); 1494 return false; 1495} 1496 1497/// AddOverloadCandidate - Adds the given function to the set of 1498/// candidate functions, using the given function call arguments. If 1499/// @p SuppressUserConversions, then don't allow user-defined 1500/// conversions via constructors or conversion operators. 1501void 1502Sema::AddOverloadCandidate(FunctionDecl *Function, 1503 Expr **Args, unsigned NumArgs, 1504 OverloadCandidateSet& CandidateSet, 1505 bool SuppressUserConversions) 1506{ 1507 const FunctionTypeProto* Proto 1508 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType()); 1509 assert(Proto && "Functions without a prototype cannot be overloaded"); 1510 assert(!isa<CXXConversionDecl>(Function) && 1511 "Use AddConversionCandidate for conversion functions"); 1512 1513 // Add this candidate 1514 CandidateSet.push_back(OverloadCandidate()); 1515 OverloadCandidate& Candidate = CandidateSet.back(); 1516 Candidate.Function = Function; 1517 1518 unsigned NumArgsInProto = Proto->getNumArgs(); 1519 1520 // (C++ 13.3.2p2): A candidate function having fewer than m 1521 // parameters is viable only if it has an ellipsis in its parameter 1522 // list (8.3.5). 1523 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 1524 Candidate.Viable = false; 1525 return; 1526 } 1527 1528 // (C++ 13.3.2p2): A candidate function having more than m parameters 1529 // is viable only if the (m+1)st parameter has a default argument 1530 // (8.3.6). For the purposes of overload resolution, the 1531 // parameter list is truncated on the right, so that there are 1532 // exactly m parameters. 1533 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 1534 if (NumArgs < MinRequiredArgs) { 1535 // Not enough arguments. 1536 Candidate.Viable = false; 1537 return; 1538 } 1539 1540 // Determine the implicit conversion sequences for each of the 1541 // arguments. 1542 Candidate.Viable = true; 1543 Candidate.Conversions.resize(NumArgs); 1544 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 1545 if (ArgIdx < NumArgsInProto) { 1546 // (C++ 13.3.2p3): for F to be a viable function, there shall 1547 // exist for each argument an implicit conversion sequence 1548 // (13.3.3.1) that converts that argument to the corresponding 1549 // parameter of F. 1550 QualType ParamType = Proto->getArgType(ArgIdx); 1551 Candidate.Conversions[ArgIdx] 1552 = TryCopyInitialization(Args[ArgIdx], ParamType, 1553 SuppressUserConversions); 1554 if (Candidate.Conversions[ArgIdx].ConversionKind 1555 == ImplicitConversionSequence::BadConversion) { 1556 Candidate.Viable = false; 1557 break; 1558 } 1559 } else { 1560 // (C++ 13.3.2p2): For the purposes of overload resolution, any 1561 // argument for which there is no corresponding parameter is 1562 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 1563 Candidate.Conversions[ArgIdx].ConversionKind 1564 = ImplicitConversionSequence::EllipsisConversion; 1565 } 1566 } 1567} 1568 1569/// AddMethodCandidate - Adds the given C++ member function to the set 1570/// of candidate functions, using the given function call arguments 1571/// and the object argument (@c Object). For example, in a call 1572/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 1573/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 1574/// allow user-defined conversions via constructors or conversion 1575/// operators. 1576void 1577Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object, 1578 Expr **Args, unsigned NumArgs, 1579 OverloadCandidateSet& CandidateSet, 1580 bool SuppressUserConversions) 1581{ 1582 const FunctionTypeProto* Proto 1583 = dyn_cast<FunctionTypeProto>(Method->getType()->getAsFunctionType()); 1584 assert(Proto && "Methods without a prototype cannot be overloaded"); 1585 assert(!isa<CXXConversionDecl>(Method) && 1586 "Use AddConversionCandidate for conversion functions"); 1587 1588 // Add this candidate 1589 CandidateSet.push_back(OverloadCandidate()); 1590 OverloadCandidate& Candidate = CandidateSet.back(); 1591 Candidate.Function = Method; 1592 1593 unsigned NumArgsInProto = Proto->getNumArgs(); 1594 1595 // (C++ 13.3.2p2): A candidate function having fewer than m 1596 // parameters is viable only if it has an ellipsis in its parameter 1597 // list (8.3.5). 1598 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 1599 Candidate.Viable = false; 1600 return; 1601 } 1602 1603 // (C++ 13.3.2p2): A candidate function having more than m parameters 1604 // is viable only if the (m+1)st parameter has a default argument 1605 // (8.3.6). For the purposes of overload resolution, the 1606 // parameter list is truncated on the right, so that there are 1607 // exactly m parameters. 1608 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 1609 if (NumArgs < MinRequiredArgs) { 1610 // Not enough arguments. 1611 Candidate.Viable = false; 1612 return; 1613 } 1614 1615 Candidate.Viable = true; 1616 Candidate.Conversions.resize(NumArgs + 1); 1617 1618 // Determine the implicit conversion sequence for the object 1619 // parameter. 1620 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method); 1621 if (Candidate.Conversions[0].ConversionKind 1622 == ImplicitConversionSequence::BadConversion) { 1623 Candidate.Viable = false; 1624 return; 1625 } 1626 1627 // Determine the implicit conversion sequences for each of the 1628 // arguments. 1629 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 1630 if (ArgIdx < NumArgsInProto) { 1631 // (C++ 13.3.2p3): for F to be a viable function, there shall 1632 // exist for each argument an implicit conversion sequence 1633 // (13.3.3.1) that converts that argument to the corresponding 1634 // parameter of F. 1635 QualType ParamType = Proto->getArgType(ArgIdx); 1636 Candidate.Conversions[ArgIdx + 1] 1637 = TryCopyInitialization(Args[ArgIdx], ParamType, 1638 SuppressUserConversions); 1639 if (Candidate.Conversions[ArgIdx + 1].ConversionKind 1640 == ImplicitConversionSequence::BadConversion) { 1641 Candidate.Viable = false; 1642 break; 1643 } 1644 } else { 1645 // (C++ 13.3.2p2): For the purposes of overload resolution, any 1646 // argument for which there is no corresponding parameter is 1647 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 1648 Candidate.Conversions[ArgIdx + 1].ConversionKind 1649 = ImplicitConversionSequence::EllipsisConversion; 1650 } 1651 } 1652} 1653 1654/// AddConversionCandidate - Add a C++ conversion function as a 1655/// candidate in the candidate set (C++ [over.match.conv], 1656/// C++ [over.match.copy]). From is the expression we're converting from, 1657/// and ToType is the type that we're eventually trying to convert to 1658/// (which may or may not be the same type as the type that the 1659/// conversion function produces). 1660void 1661Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 1662 Expr *From, QualType ToType, 1663 OverloadCandidateSet& CandidateSet) { 1664 // Add this candidate 1665 CandidateSet.push_back(OverloadCandidate()); 1666 OverloadCandidate& Candidate = CandidateSet.back(); 1667 Candidate.Function = Conversion; 1668 Candidate.FinalConversion.setAsIdentityConversion(); 1669 Candidate.FinalConversion.FromTypePtr 1670 = Conversion->getConversionType().getAsOpaquePtr(); 1671 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr(); 1672 1673 // Determine the implicit conversion sequence for the implicit 1674 // object parameter. 1675 Candidate.Viable = true; 1676 Candidate.Conversions.resize(1); 1677 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion); 1678 1679 if (Candidate.Conversions[0].ConversionKind 1680 == ImplicitConversionSequence::BadConversion) { 1681 Candidate.Viable = false; 1682 return; 1683 } 1684 1685 // To determine what the conversion from the result of calling the 1686 // conversion function to the type we're eventually trying to 1687 // convert to (ToType), we need to synthesize a call to the 1688 // conversion function and attempt copy initialization from it. This 1689 // makes sure that we get the right semantics with respect to 1690 // lvalues/rvalues and the type. Fortunately, we can allocate this 1691 // call on the stack and we don't need its arguments to be 1692 // well-formed. 1693 DeclRefExpr ConversionRef(Conversion, Conversion->getType(), 1694 SourceLocation()); 1695 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()), 1696 &ConversionRef, false); 1697 CallExpr Call(&ConversionFn, 0, 0, 1698 Conversion->getConversionType().getNonReferenceType(), 1699 SourceLocation()); 1700 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true); 1701 switch (ICS.ConversionKind) { 1702 case ImplicitConversionSequence::StandardConversion: 1703 Candidate.FinalConversion = ICS.Standard; 1704 break; 1705 1706 case ImplicitConversionSequence::BadConversion: 1707 Candidate.Viable = false; 1708 break; 1709 1710 default: 1711 assert(false && 1712 "Can only end up with a standard conversion sequence or failure"); 1713 } 1714} 1715 1716/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 1717/// an acceptable non-member overloaded operator for a call whose 1718/// arguments have types T1 (and, if non-empty, T2). This routine 1719/// implements the check in C++ [over.match.oper]p3b2 concerning 1720/// enumeration types. 1721static bool 1722IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn, 1723 QualType T1, QualType T2, 1724 ASTContext &Context) { 1725 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 1726 return true; 1727 1728 const FunctionTypeProto *Proto = Fn->getType()->getAsFunctionTypeProto(); 1729 if (Proto->getNumArgs() < 1) 1730 return false; 1731 1732 if (T1->isEnumeralType()) { 1733 QualType ArgType = Proto->getArgType(0).getNonReferenceType(); 1734 if (Context.getCanonicalType(T1).getUnqualifiedType() 1735 == Context.getCanonicalType(ArgType).getUnqualifiedType()) 1736 return true; 1737 } 1738 1739 if (Proto->getNumArgs() < 2) 1740 return false; 1741 1742 if (!T2.isNull() && T2->isEnumeralType()) { 1743 QualType ArgType = Proto->getArgType(1).getNonReferenceType(); 1744 if (Context.getCanonicalType(T2).getUnqualifiedType() 1745 == Context.getCanonicalType(ArgType).getUnqualifiedType()) 1746 return true; 1747 } 1748 1749 return false; 1750} 1751 1752/// AddOperatorCandidates - Add the overloaded operator candidates for 1753/// the operator Op that was used in an operator expression such as "x 1754/// Op y". S is the scope in which the expression occurred (used for 1755/// name lookup of the operator), Args/NumArgs provides the operator 1756/// arguments, and CandidateSet will store the added overload 1757/// candidates. (C++ [over.match.oper]). 1758void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S, 1759 Expr **Args, unsigned NumArgs, 1760 OverloadCandidateSet& CandidateSet) { 1761 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 1762 1763 // C++ [over.match.oper]p3: 1764 // For a unary operator @ with an operand of a type whose 1765 // cv-unqualified version is T1, and for a binary operator @ with 1766 // a left operand of a type whose cv-unqualified version is T1 and 1767 // a right operand of a type whose cv-unqualified version is T2, 1768 // three sets of candidate functions, designated member 1769 // candidates, non-member candidates and built-in candidates, are 1770 // constructed as follows: 1771 QualType T1 = Args[0]->getType(); 1772 QualType T2; 1773 if (NumArgs > 1) 1774 T2 = Args[1]->getType(); 1775 1776 // -- If T1 is a class type, the set of member candidates is the 1777 // result of the qualified lookup of T1::operator@ 1778 // (13.3.1.1.1); otherwise, the set of member candidates is 1779 // empty. 1780 if (const RecordType *T1Rec = T1->getAsRecordType()) { 1781 IdentifierResolver::iterator I 1782 = IdResolver.begin(OpName, cast<CXXRecordType>(T1Rec)->getDecl(), 1783 /*LookInParentCtx=*/false); 1784 NamedDecl *MemberOps = (I == IdResolver.end())? 0 : *I; 1785 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps)) 1786 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet, 1787 /*SuppressUserConversions=*/false); 1788 else if (OverloadedFunctionDecl *Ovl 1789 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) { 1790 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(), 1791 FEnd = Ovl->function_end(); 1792 F != FEnd; ++F) { 1793 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F)) 1794 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet, 1795 /*SuppressUserConversions=*/false); 1796 } 1797 } 1798 } 1799 1800 // -- The set of non-member candidates is the result of the 1801 // unqualified lookup of operator@ in the context of the 1802 // expression according to the usual rules for name lookup in 1803 // unqualified function calls (3.4.2) except that all member 1804 // functions are ignored. However, if no operand has a class 1805 // type, only those non-member functions in the lookup set 1806 // that have a first parameter of type T1 or “reference to 1807 // (possibly cv-qualified) T1”, when T1 is an enumeration 1808 // type, or (if there is a right operand) a second parameter 1809 // of type T2 or “reference to (possibly cv-qualified) T2”, 1810 // when T2 is an enumeration type, are candidate functions. 1811 { 1812 NamedDecl *NonMemberOps = 0; 1813 for (IdentifierResolver::iterator I 1814 = IdResolver.begin(OpName, CurContext, true/*LookInParentCtx*/); 1815 I != IdResolver.end(); ++I) { 1816 // We don't need to check the identifier namespace, because 1817 // operator names can only be ordinary identifiers. 1818 1819 // Ignore member functions. 1820 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(*I)) { 1821 if (SD->getDeclContext()->isCXXRecord()) 1822 continue; 1823 } 1824 1825 // We found something with this name. We're done. 1826 NonMemberOps = *I; 1827 break; 1828 } 1829 1830 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NonMemberOps)) { 1831 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context)) 1832 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet, 1833 /*SuppressUserConversions=*/false); 1834 } else if (OverloadedFunctionDecl *Ovl 1835 = dyn_cast_or_null<OverloadedFunctionDecl>(NonMemberOps)) { 1836 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(), 1837 FEnd = Ovl->function_end(); 1838 F != FEnd; ++F) { 1839 if (IsAcceptableNonMemberOperatorCandidate(*F, T1, T2, Context)) 1840 AddOverloadCandidate(*F, Args, NumArgs, CandidateSet, 1841 /*SuppressUserConversions=*/false); 1842 } 1843 } 1844 } 1845 1846 // Add builtin overload candidates (C++ [over.built]). 1847 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet); 1848} 1849 1850/// AddBuiltinCandidate - Add a candidate for a built-in 1851/// operator. ResultTy and ParamTys are the result and parameter types 1852/// of the built-in candidate, respectively. Args and NumArgs are the 1853/// arguments being passed to the candidate. 1854void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 1855 Expr **Args, unsigned NumArgs, 1856 OverloadCandidateSet& CandidateSet) { 1857 // Add this candidate 1858 CandidateSet.push_back(OverloadCandidate()); 1859 OverloadCandidate& Candidate = CandidateSet.back(); 1860 Candidate.Function = 0; 1861 Candidate.BuiltinTypes.ResultTy = ResultTy; 1862 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 1863 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 1864 1865 // Determine the implicit conversion sequences for each of the 1866 // arguments. 1867 Candidate.Viable = true; 1868 Candidate.Conversions.resize(NumArgs); 1869 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 1870 Candidate.Conversions[ArgIdx] 1871 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx], false); 1872 if (Candidate.Conversions[ArgIdx].ConversionKind 1873 == ImplicitConversionSequence::BadConversion) { 1874 Candidate.Viable = false; 1875 break; 1876 } 1877 } 1878} 1879 1880/// BuiltinCandidateTypeSet - A set of types that will be used for the 1881/// candidate operator functions for built-in operators (C++ 1882/// [over.built]). The types are separated into pointer types and 1883/// enumeration types. 1884class BuiltinCandidateTypeSet { 1885 /// TypeSet - A set of types. 1886 typedef llvm::SmallPtrSet<void*, 8> TypeSet; 1887 1888 /// PointerTypes - The set of pointer types that will be used in the 1889 /// built-in candidates. 1890 TypeSet PointerTypes; 1891 1892 /// EnumerationTypes - The set of enumeration types that will be 1893 /// used in the built-in candidates. 1894 TypeSet EnumerationTypes; 1895 1896 /// Context - The AST context in which we will build the type sets. 1897 ASTContext &Context; 1898 1899 bool AddWithMoreQualifiedTypeVariants(QualType Ty); 1900 1901public: 1902 /// iterator - Iterates through the types that are part of the set. 1903 class iterator { 1904 TypeSet::iterator Base; 1905 1906 public: 1907 typedef QualType value_type; 1908 typedef QualType reference; 1909 typedef QualType pointer; 1910 typedef std::ptrdiff_t difference_type; 1911 typedef std::input_iterator_tag iterator_category; 1912 1913 iterator(TypeSet::iterator B) : Base(B) { } 1914 1915 iterator& operator++() { 1916 ++Base; 1917 return *this; 1918 } 1919 1920 iterator operator++(int) { 1921 iterator tmp(*this); 1922 ++(*this); 1923 return tmp; 1924 } 1925 1926 reference operator*() const { 1927 return QualType::getFromOpaquePtr(*Base); 1928 } 1929 1930 pointer operator->() const { 1931 return **this; 1932 } 1933 1934 friend bool operator==(iterator LHS, iterator RHS) { 1935 return LHS.Base == RHS.Base; 1936 } 1937 1938 friend bool operator!=(iterator LHS, iterator RHS) { 1939 return LHS.Base != RHS.Base; 1940 } 1941 }; 1942 1943 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { } 1944 1945 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions = true); 1946 1947 /// pointer_begin - First pointer type found; 1948 iterator pointer_begin() { return PointerTypes.begin(); } 1949 1950 /// pointer_end - Last pointer type found; 1951 iterator pointer_end() { return PointerTypes.end(); } 1952 1953 /// enumeration_begin - First enumeration type found; 1954 iterator enumeration_begin() { return EnumerationTypes.begin(); } 1955 1956 /// enumeration_end - Last enumeration type found; 1957 iterator enumeration_end() { return EnumerationTypes.end(); } 1958}; 1959 1960/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 1961/// the set of pointer types along with any more-qualified variants of 1962/// that type. For example, if @p Ty is "int const *", this routine 1963/// will add "int const *", "int const volatile *", "int const 1964/// restrict *", and "int const volatile restrict *" to the set of 1965/// pointer types. Returns true if the add of @p Ty itself succeeded, 1966/// false otherwise. 1967bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) { 1968 // Insert this type. 1969 if (!PointerTypes.insert(Ty.getAsOpaquePtr())) 1970 return false; 1971 1972 if (const PointerType *PointerTy = Ty->getAsPointerType()) { 1973 QualType PointeeTy = PointerTy->getPointeeType(); 1974 // FIXME: Optimize this so that we don't keep trying to add the same types. 1975 1976 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal 1977 // with all pointer conversions that don't cast away constness? 1978 if (!PointeeTy.isConstQualified()) 1979 AddWithMoreQualifiedTypeVariants 1980 (Context.getPointerType(PointeeTy.withConst())); 1981 if (!PointeeTy.isVolatileQualified()) 1982 AddWithMoreQualifiedTypeVariants 1983 (Context.getPointerType(PointeeTy.withVolatile())); 1984 if (!PointeeTy.isRestrictQualified()) 1985 AddWithMoreQualifiedTypeVariants 1986 (Context.getPointerType(PointeeTy.withRestrict())); 1987 } 1988 1989 return true; 1990} 1991 1992/// AddTypesConvertedFrom - Add each of the types to which the type @p 1993/// Ty can be implicit converted to the given set of @p Types. We're 1994/// primarily interested in pointer types, enumeration types, 1995void BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 1996 bool AllowUserConversions) { 1997 // Only deal with canonical types. 1998 Ty = Context.getCanonicalType(Ty); 1999 2000 // Look through reference types; they aren't part of the type of an 2001 // expression for the purposes of conversions. 2002 if (const ReferenceType *RefTy = Ty->getAsReferenceType()) 2003 Ty = RefTy->getPointeeType(); 2004 2005 // We don't care about qualifiers on the type. 2006 Ty = Ty.getUnqualifiedType(); 2007 2008 if (const PointerType *PointerTy = Ty->getAsPointerType()) { 2009 QualType PointeeTy = PointerTy->getPointeeType(); 2010 2011 // Insert our type, and its more-qualified variants, into the set 2012 // of types. 2013 if (!AddWithMoreQualifiedTypeVariants(Ty)) 2014 return; 2015 2016 // Add 'cv void*' to our set of types. 2017 if (!Ty->isVoidType()) { 2018 QualType QualVoid 2019 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers()); 2020 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid)); 2021 } 2022 2023 // If this is a pointer to a class type, add pointers to its bases 2024 // (with the same level of cv-qualification as the original 2025 // derived class, of course). 2026 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) { 2027 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl()); 2028 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 2029 Base != ClassDecl->bases_end(); ++Base) { 2030 QualType BaseTy = Context.getCanonicalType(Base->getType()); 2031 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers()); 2032 2033 // Add the pointer type, recursively, so that we get all of 2034 // the indirect base classes, too. 2035 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false); 2036 } 2037 } 2038 } else if (Ty->isEnumeralType()) { 2039 EnumerationTypes.insert(Ty.getAsOpaquePtr()); 2040 } else if (AllowUserConversions) { 2041 if (const RecordType *TyRec = Ty->getAsRecordType()) { 2042 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 2043 // FIXME: Visit conversion functions in the base classes, too. 2044 OverloadedFunctionDecl *Conversions 2045 = ClassDecl->getConversionFunctions(); 2046 for (OverloadedFunctionDecl::function_iterator Func 2047 = Conversions->function_begin(); 2048 Func != Conversions->function_end(); ++Func) { 2049 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func); 2050 AddTypesConvertedFrom(Conv->getConversionType(), false); 2051 } 2052 } 2053 } 2054} 2055 2056/// AddBuiltinOperatorCandidates - Add the appropriate built-in 2057/// operator overloads to the candidate set (C++ [over.built]), based 2058/// on the operator @p Op and the arguments given. For example, if the 2059/// operator is a binary '+', this routine might add "int 2060/// operator+(int, int)" to cover integer addition. 2061void 2062Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 2063 Expr **Args, unsigned NumArgs, 2064 OverloadCandidateSet& CandidateSet) { 2065 // The set of "promoted arithmetic types", which are the arithmetic 2066 // types are that preserved by promotion (C++ [over.built]p2). Note 2067 // that the first few of these types are the promoted integral 2068 // types; these types need to be first. 2069 // FIXME: What about complex? 2070 const unsigned FirstIntegralType = 0; 2071 const unsigned LastIntegralType = 13; 2072 const unsigned FirstPromotedIntegralType = 7, 2073 LastPromotedIntegralType = 13; 2074 const unsigned FirstPromotedArithmeticType = 7, 2075 LastPromotedArithmeticType = 16; 2076 const unsigned NumArithmeticTypes = 16; 2077 QualType ArithmeticTypes[NumArithmeticTypes] = { 2078 Context.BoolTy, Context.CharTy, Context.WCharTy, 2079 Context.SignedCharTy, Context.ShortTy, 2080 Context.UnsignedCharTy, Context.UnsignedShortTy, 2081 Context.IntTy, Context.LongTy, Context.LongLongTy, 2082 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy, 2083 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy 2084 }; 2085 2086 // Find all of the types that the arguments can convert to, but only 2087 // if the operator we're looking at has built-in operator candidates 2088 // that make use of these types. 2089 BuiltinCandidateTypeSet CandidateTypes(Context); 2090 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual || 2091 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual || 2092 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal || 2093 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript || 2094 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus || 2095 (Op == OO_Star && NumArgs == 1)) { 2096 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 2097 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType()); 2098 } 2099 2100 bool isComparison = false; 2101 switch (Op) { 2102 case OO_None: 2103 case NUM_OVERLOADED_OPERATORS: 2104 assert(false && "Expected an overloaded operator"); 2105 break; 2106 2107 case OO_Star: // '*' is either unary or binary 2108 if (NumArgs == 1) 2109 goto UnaryStar; 2110 else 2111 goto BinaryStar; 2112 break; 2113 2114 case OO_Plus: // '+' is either unary or binary 2115 if (NumArgs == 1) 2116 goto UnaryPlus; 2117 else 2118 goto BinaryPlus; 2119 break; 2120 2121 case OO_Minus: // '-' is either unary or binary 2122 if (NumArgs == 1) 2123 goto UnaryMinus; 2124 else 2125 goto BinaryMinus; 2126 break; 2127 2128 case OO_Amp: // '&' is either unary or binary 2129 if (NumArgs == 1) 2130 goto UnaryAmp; 2131 else 2132 goto BinaryAmp; 2133 2134 case OO_PlusPlus: 2135 case OO_MinusMinus: 2136 // C++ [over.built]p3: 2137 // 2138 // For every pair (T, VQ), where T is an arithmetic type, and VQ 2139 // is either volatile or empty, there exist candidate operator 2140 // functions of the form 2141 // 2142 // VQ T& operator++(VQ T&); 2143 // T operator++(VQ T&, int); 2144 // 2145 // C++ [over.built]p4: 2146 // 2147 // For every pair (T, VQ), where T is an arithmetic type other 2148 // than bool, and VQ is either volatile or empty, there exist 2149 // candidate operator functions of the form 2150 // 2151 // VQ T& operator--(VQ T&); 2152 // T operator--(VQ T&, int); 2153 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 2154 Arith < NumArithmeticTypes; ++Arith) { 2155 QualType ArithTy = ArithmeticTypes[Arith]; 2156 QualType ParamTypes[2] 2157 = { Context.getReferenceType(ArithTy), Context.IntTy }; 2158 2159 // Non-volatile version. 2160 if (NumArgs == 1) 2161 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 2162 else 2163 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet); 2164 2165 // Volatile version 2166 ParamTypes[0] = Context.getReferenceType(ArithTy.withVolatile()); 2167 if (NumArgs == 1) 2168 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 2169 else 2170 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet); 2171 } 2172 2173 // C++ [over.built]p5: 2174 // 2175 // For every pair (T, VQ), where T is a cv-qualified or 2176 // cv-unqualified object type, and VQ is either volatile or 2177 // empty, there exist candidate operator functions of the form 2178 // 2179 // T*VQ& operator++(T*VQ&); 2180 // T*VQ& operator--(T*VQ&); 2181 // T* operator++(T*VQ&, int); 2182 // T* operator--(T*VQ&, int); 2183 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2184 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2185 // Skip pointer types that aren't pointers to object types. 2186 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isObjectType()) 2187 continue; 2188 2189 QualType ParamTypes[2] = { 2190 Context.getReferenceType(*Ptr), Context.IntTy 2191 }; 2192 2193 // Without volatile 2194 if (NumArgs == 1) 2195 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 2196 else 2197 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 2198 2199 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) { 2200 // With volatile 2201 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile()); 2202 if (NumArgs == 1) 2203 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 2204 else 2205 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 2206 } 2207 } 2208 break; 2209 2210 UnaryStar: 2211 // C++ [over.built]p6: 2212 // For every cv-qualified or cv-unqualified object type T, there 2213 // exist candidate operator functions of the form 2214 // 2215 // T& operator*(T*); 2216 // 2217 // C++ [over.built]p7: 2218 // For every function type T, there exist candidate operator 2219 // functions of the form 2220 // T& operator*(T*); 2221 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2222 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2223 QualType ParamTy = *Ptr; 2224 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType(); 2225 AddBuiltinCandidate(Context.getReferenceType(PointeeTy), 2226 &ParamTy, Args, 1, CandidateSet); 2227 } 2228 break; 2229 2230 UnaryPlus: 2231 // C++ [over.built]p8: 2232 // For every type T, there exist candidate operator functions of 2233 // the form 2234 // 2235 // T* operator+(T*); 2236 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2237 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2238 QualType ParamTy = *Ptr; 2239 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 2240 } 2241 2242 // Fall through 2243 2244 UnaryMinus: 2245 // C++ [over.built]p9: 2246 // For every promoted arithmetic type T, there exist candidate 2247 // operator functions of the form 2248 // 2249 // T operator+(T); 2250 // T operator-(T); 2251 for (unsigned Arith = FirstPromotedArithmeticType; 2252 Arith < LastPromotedArithmeticType; ++Arith) { 2253 QualType ArithTy = ArithmeticTypes[Arith]; 2254 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet); 2255 } 2256 break; 2257 2258 case OO_Tilde: 2259 // C++ [over.built]p10: 2260 // For every promoted integral type T, there exist candidate 2261 // operator functions of the form 2262 // 2263 // T operator~(T); 2264 for (unsigned Int = FirstPromotedIntegralType; 2265 Int < LastPromotedIntegralType; ++Int) { 2266 QualType IntTy = ArithmeticTypes[Int]; 2267 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet); 2268 } 2269 break; 2270 2271 case OO_New: 2272 case OO_Delete: 2273 case OO_Array_New: 2274 case OO_Array_Delete: 2275 case OO_Call: 2276 assert(false && "Special operators don't use AddBuiltinOperatorCandidates"); 2277 break; 2278 2279 case OO_Comma: 2280 UnaryAmp: 2281 case OO_Arrow: 2282 // C++ [over.match.oper]p3: 2283 // -- For the operator ',', the unary operator '&', or the 2284 // operator '->', the built-in candidates set is empty. 2285 break; 2286 2287 case OO_Less: 2288 case OO_Greater: 2289 case OO_LessEqual: 2290 case OO_GreaterEqual: 2291 case OO_EqualEqual: 2292 case OO_ExclaimEqual: 2293 // C++ [over.built]p15: 2294 // 2295 // For every pointer or enumeration type T, there exist 2296 // candidate operator functions of the form 2297 // 2298 // bool operator<(T, T); 2299 // bool operator>(T, T); 2300 // bool operator<=(T, T); 2301 // bool operator>=(T, T); 2302 // bool operator==(T, T); 2303 // bool operator!=(T, T); 2304 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2305 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2306 QualType ParamTypes[2] = { *Ptr, *Ptr }; 2307 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet); 2308 } 2309 for (BuiltinCandidateTypeSet::iterator Enum 2310 = CandidateTypes.enumeration_begin(); 2311 Enum != CandidateTypes.enumeration_end(); ++Enum) { 2312 QualType ParamTypes[2] = { *Enum, *Enum }; 2313 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet); 2314 } 2315 2316 // Fall through. 2317 isComparison = true; 2318 2319 BinaryPlus: 2320 BinaryMinus: 2321 if (!isComparison) { 2322 // We didn't fall through, so we must have OO_Plus or OO_Minus. 2323 2324 // C++ [over.built]p13: 2325 // 2326 // For every cv-qualified or cv-unqualified object type T 2327 // there exist candidate operator functions of the form 2328 // 2329 // T* operator+(T*, ptrdiff_t); 2330 // T& operator[](T*, ptrdiff_t); [BELOW] 2331 // T* operator-(T*, ptrdiff_t); 2332 // T* operator+(ptrdiff_t, T*); 2333 // T& operator[](ptrdiff_t, T*); [BELOW] 2334 // 2335 // C++ [over.built]p14: 2336 // 2337 // For every T, where T is a pointer to object type, there 2338 // exist candidate operator functions of the form 2339 // 2340 // ptrdiff_t operator-(T, T); 2341 for (BuiltinCandidateTypeSet::iterator Ptr 2342 = CandidateTypes.pointer_begin(); 2343 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2344 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() }; 2345 2346 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 2347 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 2348 2349 if (Op == OO_Plus) { 2350 // T* operator+(ptrdiff_t, T*); 2351 ParamTypes[0] = ParamTypes[1]; 2352 ParamTypes[1] = *Ptr; 2353 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 2354 } else { 2355 // ptrdiff_t operator-(T, T); 2356 ParamTypes[1] = *Ptr; 2357 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes, 2358 Args, 2, CandidateSet); 2359 } 2360 } 2361 } 2362 // Fall through 2363 2364 case OO_Slash: 2365 BinaryStar: 2366 // C++ [over.built]p12: 2367 // 2368 // For every pair of promoted arithmetic types L and R, there 2369 // exist candidate operator functions of the form 2370 // 2371 // LR operator*(L, R); 2372 // LR operator/(L, R); 2373 // LR operator+(L, R); 2374 // LR operator-(L, R); 2375 // bool operator<(L, R); 2376 // bool operator>(L, R); 2377 // bool operator<=(L, R); 2378 // bool operator>=(L, R); 2379 // bool operator==(L, R); 2380 // bool operator!=(L, R); 2381 // 2382 // where LR is the result of the usual arithmetic conversions 2383 // between types L and R. 2384 for (unsigned Left = FirstPromotedArithmeticType; 2385 Left < LastPromotedArithmeticType; ++Left) { 2386 for (unsigned Right = FirstPromotedArithmeticType; 2387 Right < LastPromotedArithmeticType; ++Right) { 2388 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] }; 2389 QualType Result 2390 = isComparison? Context.BoolTy 2391 : UsualArithmeticConversionsType(LandR[0], LandR[1]); 2392 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 2393 } 2394 } 2395 break; 2396 2397 case OO_Percent: 2398 BinaryAmp: 2399 case OO_Caret: 2400 case OO_Pipe: 2401 case OO_LessLess: 2402 case OO_GreaterGreater: 2403 // C++ [over.built]p17: 2404 // 2405 // For every pair of promoted integral types L and R, there 2406 // exist candidate operator functions of the form 2407 // 2408 // LR operator%(L, R); 2409 // LR operator&(L, R); 2410 // LR operator^(L, R); 2411 // LR operator|(L, R); 2412 // L operator<<(L, R); 2413 // L operator>>(L, R); 2414 // 2415 // where LR is the result of the usual arithmetic conversions 2416 // between types L and R. 2417 for (unsigned Left = FirstPromotedIntegralType; 2418 Left < LastPromotedIntegralType; ++Left) { 2419 for (unsigned Right = FirstPromotedIntegralType; 2420 Right < LastPromotedIntegralType; ++Right) { 2421 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] }; 2422 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 2423 ? LandR[0] 2424 : UsualArithmeticConversionsType(LandR[0], LandR[1]); 2425 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 2426 } 2427 } 2428 break; 2429 2430 case OO_Equal: 2431 // C++ [over.built]p20: 2432 // 2433 // For every pair (T, VQ), where T is an enumeration or 2434 // (FIXME:) pointer to member type and VQ is either volatile or 2435 // empty, there exist candidate operator functions of the form 2436 // 2437 // VQ T& operator=(VQ T&, T); 2438 for (BuiltinCandidateTypeSet::iterator Enum 2439 = CandidateTypes.enumeration_begin(); 2440 Enum != CandidateTypes.enumeration_end(); ++Enum) { 2441 QualType ParamTypes[2]; 2442 2443 // T& operator=(T&, T) 2444 ParamTypes[0] = Context.getReferenceType(*Enum); 2445 ParamTypes[1] = *Enum; 2446 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2447 2448 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) { 2449 // volatile T& operator=(volatile T&, T) 2450 ParamTypes[0] = Context.getReferenceType((*Enum).withVolatile()); 2451 ParamTypes[1] = *Enum; 2452 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2453 } 2454 } 2455 // Fall through. 2456 2457 case OO_PlusEqual: 2458 case OO_MinusEqual: 2459 // C++ [over.built]p19: 2460 // 2461 // For every pair (T, VQ), where T is any type and VQ is either 2462 // volatile or empty, there exist candidate operator functions 2463 // of the form 2464 // 2465 // T*VQ& operator=(T*VQ&, T*); 2466 // 2467 // C++ [over.built]p21: 2468 // 2469 // For every pair (T, VQ), where T is a cv-qualified or 2470 // cv-unqualified object type and VQ is either volatile or 2471 // empty, there exist candidate operator functions of the form 2472 // 2473 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 2474 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 2475 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2476 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2477 QualType ParamTypes[2]; 2478 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType(); 2479 2480 // non-volatile version 2481 ParamTypes[0] = Context.getReferenceType(*Ptr); 2482 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2483 2484 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) { 2485 // volatile version 2486 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile()); 2487 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2488 } 2489 } 2490 // Fall through. 2491 2492 case OO_StarEqual: 2493 case OO_SlashEqual: 2494 // C++ [over.built]p18: 2495 // 2496 // For every triple (L, VQ, R), where L is an arithmetic type, 2497 // VQ is either volatile or empty, and R is a promoted 2498 // arithmetic type, there exist candidate operator functions of 2499 // the form 2500 // 2501 // VQ L& operator=(VQ L&, R); 2502 // VQ L& operator*=(VQ L&, R); 2503 // VQ L& operator/=(VQ L&, R); 2504 // VQ L& operator+=(VQ L&, R); 2505 // VQ L& operator-=(VQ L&, R); 2506 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 2507 for (unsigned Right = FirstPromotedArithmeticType; 2508 Right < LastPromotedArithmeticType; ++Right) { 2509 QualType ParamTypes[2]; 2510 ParamTypes[1] = ArithmeticTypes[Right]; 2511 2512 // Add this built-in operator as a candidate (VQ is empty). 2513 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]); 2514 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2515 2516 // Add this built-in operator as a candidate (VQ is 'volatile'). 2517 ParamTypes[0] = ArithmeticTypes[Left].withVolatile(); 2518 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]); 2519 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2520 } 2521 } 2522 break; 2523 2524 case OO_PercentEqual: 2525 case OO_LessLessEqual: 2526 case OO_GreaterGreaterEqual: 2527 case OO_AmpEqual: 2528 case OO_CaretEqual: 2529 case OO_PipeEqual: 2530 // C++ [over.built]p22: 2531 // 2532 // For every triple (L, VQ, R), where L is an integral type, VQ 2533 // is either volatile or empty, and R is a promoted integral 2534 // type, there exist candidate operator functions of the form 2535 // 2536 // VQ L& operator%=(VQ L&, R); 2537 // VQ L& operator<<=(VQ L&, R); 2538 // VQ L& operator>>=(VQ L&, R); 2539 // VQ L& operator&=(VQ L&, R); 2540 // VQ L& operator^=(VQ L&, R); 2541 // VQ L& operator|=(VQ L&, R); 2542 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 2543 for (unsigned Right = FirstPromotedIntegralType; 2544 Right < LastPromotedIntegralType; ++Right) { 2545 QualType ParamTypes[2]; 2546 ParamTypes[1] = ArithmeticTypes[Right]; 2547 2548 // Add this built-in operator as a candidate (VQ is empty). 2549 // FIXME: We should be caching these declarations somewhere, 2550 // rather than re-building them every time. 2551 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]); 2552 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2553 2554 // Add this built-in operator as a candidate (VQ is 'volatile'). 2555 ParamTypes[0] = ArithmeticTypes[Left]; 2556 ParamTypes[0].addVolatile(); 2557 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]); 2558 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2559 } 2560 } 2561 break; 2562 2563 case OO_Exclaim: { 2564 // C++ [over.operator]p23: 2565 // 2566 // There also exist candidate operator functions of the form 2567 // 2568 // bool operator!(bool); 2569 // bool operator&&(bool, bool); [BELOW] 2570 // bool operator||(bool, bool); [BELOW] 2571 QualType ParamTy = Context.BoolTy; 2572 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 2573 break; 2574 } 2575 2576 case OO_AmpAmp: 2577 case OO_PipePipe: { 2578 // C++ [over.operator]p23: 2579 // 2580 // There also exist candidate operator functions of the form 2581 // 2582 // bool operator!(bool); [ABOVE] 2583 // bool operator&&(bool, bool); 2584 // bool operator||(bool, bool); 2585 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy }; 2586 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet); 2587 break; 2588 } 2589 2590 case OO_Subscript: 2591 // C++ [over.built]p13: 2592 // 2593 // For every cv-qualified or cv-unqualified object type T there 2594 // exist candidate operator functions of the form 2595 // 2596 // T* operator+(T*, ptrdiff_t); [ABOVE] 2597 // T& operator[](T*, ptrdiff_t); 2598 // T* operator-(T*, ptrdiff_t); [ABOVE] 2599 // T* operator+(ptrdiff_t, T*); [ABOVE] 2600 // T& operator[](ptrdiff_t, T*); 2601 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2602 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2603 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() }; 2604 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType(); 2605 QualType ResultTy = Context.getReferenceType(PointeeType); 2606 2607 // T& operator[](T*, ptrdiff_t) 2608 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 2609 2610 // T& operator[](ptrdiff_t, T*); 2611 ParamTypes[0] = ParamTypes[1]; 2612 ParamTypes[1] = *Ptr; 2613 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 2614 } 2615 break; 2616 2617 case OO_ArrowStar: 2618 // FIXME: No support for pointer-to-members yet. 2619 break; 2620 } 2621} 2622 2623/// AddOverloadCandidates - Add all of the function overloads in Ovl 2624/// to the candidate set. 2625void 2626Sema::AddOverloadCandidates(const OverloadedFunctionDecl *Ovl, 2627 Expr **Args, unsigned NumArgs, 2628 OverloadCandidateSet& CandidateSet, 2629 bool SuppressUserConversions) 2630{ 2631 for (OverloadedFunctionDecl::function_const_iterator Func 2632 = Ovl->function_begin(); 2633 Func != Ovl->function_end(); ++Func) 2634 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet, 2635 SuppressUserConversions); 2636} 2637 2638/// isBetterOverloadCandidate - Determines whether the first overload 2639/// candidate is a better candidate than the second (C++ 13.3.3p1). 2640bool 2641Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1, 2642 const OverloadCandidate& Cand2) 2643{ 2644 // Define viable functions to be better candidates than non-viable 2645 // functions. 2646 if (!Cand2.Viable) 2647 return Cand1.Viable; 2648 else if (!Cand1.Viable) 2649 return false; 2650 2651 // FIXME: Deal with the implicit object parameter for static member 2652 // functions. (C++ 13.3.3p1). 2653 2654 // (C++ 13.3.3p1): a viable function F1 is defined to be a better 2655 // function than another viable function F2 if for all arguments i, 2656 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and 2657 // then... 2658 unsigned NumArgs = Cand1.Conversions.size(); 2659 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 2660 bool HasBetterConversion = false; 2661 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 2662 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx], 2663 Cand2.Conversions[ArgIdx])) { 2664 case ImplicitConversionSequence::Better: 2665 // Cand1 has a better conversion sequence. 2666 HasBetterConversion = true; 2667 break; 2668 2669 case ImplicitConversionSequence::Worse: 2670 // Cand1 can't be better than Cand2. 2671 return false; 2672 2673 case ImplicitConversionSequence::Indistinguishable: 2674 // Do nothing. 2675 break; 2676 } 2677 } 2678 2679 if (HasBetterConversion) 2680 return true; 2681 2682 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be 2683 // implemented, but they require template support. 2684 2685 // C++ [over.match.best]p1b4: 2686 // 2687 // -- the context is an initialization by user-defined conversion 2688 // (see 8.5, 13.3.1.5) and the standard conversion sequence 2689 // from the return type of F1 to the destination type (i.e., 2690 // the type of the entity being initialized) is a better 2691 // conversion sequence than the standard conversion sequence 2692 // from the return type of F2 to the destination type. 2693 if (Cand1.Function && Cand2.Function && 2694 isa<CXXConversionDecl>(Cand1.Function) && 2695 isa<CXXConversionDecl>(Cand2.Function)) { 2696 switch (CompareStandardConversionSequences(Cand1.FinalConversion, 2697 Cand2.FinalConversion)) { 2698 case ImplicitConversionSequence::Better: 2699 // Cand1 has a better conversion sequence. 2700 return true; 2701 2702 case ImplicitConversionSequence::Worse: 2703 // Cand1 can't be better than Cand2. 2704 return false; 2705 2706 case ImplicitConversionSequence::Indistinguishable: 2707 // Do nothing 2708 break; 2709 } 2710 } 2711 2712 return false; 2713} 2714 2715/// BestViableFunction - Computes the best viable function (C++ 13.3.3) 2716/// within an overload candidate set. If overloading is successful, 2717/// the result will be OR_Success and Best will be set to point to the 2718/// best viable function within the candidate set. Otherwise, one of 2719/// several kinds of errors will be returned; see 2720/// Sema::OverloadingResult. 2721Sema::OverloadingResult 2722Sema::BestViableFunction(OverloadCandidateSet& CandidateSet, 2723 OverloadCandidateSet::iterator& Best) 2724{ 2725 // Find the best viable function. 2726 Best = CandidateSet.end(); 2727 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 2728 Cand != CandidateSet.end(); ++Cand) { 2729 if (Cand->Viable) { 2730 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best)) 2731 Best = Cand; 2732 } 2733 } 2734 2735 // If we didn't find any viable functions, abort. 2736 if (Best == CandidateSet.end()) 2737 return OR_No_Viable_Function; 2738 2739 // Make sure that this function is better than every other viable 2740 // function. If not, we have an ambiguity. 2741 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 2742 Cand != CandidateSet.end(); ++Cand) { 2743 if (Cand->Viable && 2744 Cand != Best && 2745 !isBetterOverloadCandidate(*Best, *Cand)) 2746 return OR_Ambiguous; 2747 } 2748 2749 // Best is the best viable function. 2750 return OR_Success; 2751} 2752 2753/// PrintOverloadCandidates - When overload resolution fails, prints 2754/// diagnostic messages containing the candidates in the candidate 2755/// set. If OnlyViable is true, only viable candidates will be printed. 2756void 2757Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet, 2758 bool OnlyViable) 2759{ 2760 OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 2761 LastCand = CandidateSet.end(); 2762 for (; Cand != LastCand; ++Cand) { 2763 if (Cand->Viable || !OnlyViable) { 2764 if (Cand->Function) { 2765 // Normal function 2766 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate); 2767 } else { 2768 // FIXME: We need to get the identifier in here 2769 // FIXME: Do we want the error message to point at the 2770 // operator? (built-ins won't have a location) 2771 QualType FnType 2772 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy, 2773 Cand->BuiltinTypes.ParamTypes, 2774 Cand->Conversions.size(), 2775 false, 0); 2776 2777 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) 2778 << FnType.getAsString(); 2779 } 2780 } 2781 } 2782} 2783 2784/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 2785/// an overloaded function (C++ [over.over]), where @p From is an 2786/// expression with overloaded function type and @p ToType is the type 2787/// we're trying to resolve to. For example: 2788/// 2789/// @code 2790/// int f(double); 2791/// int f(int); 2792/// 2793/// int (*pfd)(double) = f; // selects f(double) 2794/// @endcode 2795/// 2796/// This routine returns the resulting FunctionDecl if it could be 2797/// resolved, and NULL otherwise. When @p Complain is true, this 2798/// routine will emit diagnostics if there is an error. 2799FunctionDecl * 2800Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType, 2801 bool Complain) { 2802 QualType FunctionType = ToType; 2803 if (const PointerLikeType *ToTypePtr = ToType->getAsPointerLikeType()) 2804 FunctionType = ToTypePtr->getPointeeType(); 2805 2806 // We only look at pointers or references to functions. 2807 if (!FunctionType->isFunctionType()) 2808 return 0; 2809 2810 // Find the actual overloaded function declaration. 2811 OverloadedFunctionDecl *Ovl = 0; 2812 2813 // C++ [over.over]p1: 2814 // [...] [Note: any redundant set of parentheses surrounding the 2815 // overloaded function name is ignored (5.1). ] 2816 Expr *OvlExpr = From->IgnoreParens(); 2817 2818 // C++ [over.over]p1: 2819 // [...] The overloaded function name can be preceded by the & 2820 // operator. 2821 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) { 2822 if (UnOp->getOpcode() == UnaryOperator::AddrOf) 2823 OvlExpr = UnOp->getSubExpr()->IgnoreParens(); 2824 } 2825 2826 // Try to dig out the overloaded function. 2827 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) 2828 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl()); 2829 2830 // If there's no overloaded function declaration, we're done. 2831 if (!Ovl) 2832 return 0; 2833 2834 // Look through all of the overloaded functions, searching for one 2835 // whose type matches exactly. 2836 // FIXME: When templates or using declarations come along, we'll actually 2837 // have to deal with duplicates, partial ordering, etc. For now, we 2838 // can just do a simple search. 2839 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType()); 2840 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin(); 2841 Fun != Ovl->function_end(); ++Fun) { 2842 // C++ [over.over]p3: 2843 // Non-member functions and static member functions match 2844 // targets of type “pointer-to-function”or 2845 // “reference-to-function.” 2846 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) 2847 if (!Method->isStatic()) 2848 continue; 2849 2850 if (FunctionType == Context.getCanonicalType((*Fun)->getType())) 2851 return *Fun; 2852 } 2853 2854 return 0; 2855} 2856 2857/// BuildCallToObjectOfClassType - Build a call to an object of class 2858/// type (C++ [over.call.object]), which can end up invoking an 2859/// overloaded function call operator (@c operator()) or performing a 2860/// user-defined conversion on the object argument. 2861Action::ExprResult 2862Sema::BuildCallToObjectOfClassType(Expr *Object, SourceLocation LParenLoc, 2863 Expr **Args, unsigned NumArgs, 2864 SourceLocation *CommaLocs, 2865 SourceLocation RParenLoc) { 2866 assert(Object->getType()->isRecordType() && "Requires object type argument"); 2867 const RecordType *Record = Object->getType()->getAsRecordType(); 2868 2869 // C++ [over.call.object]p1: 2870 // If the primary-expression E in the function call syntax 2871 // evaluates to a class object of type “cv T”, then the set of 2872 // candidate functions includes at least the function call 2873 // operators of T. The function call operators of T are obtained by 2874 // ordinary lookup of the name operator() in the context of 2875 // (E).operator(). 2876 OverloadCandidateSet CandidateSet; 2877 IdentifierResolver::iterator I 2878 = IdResolver.begin(Context.DeclarationNames.getCXXOperatorName(OO_Call), 2879 cast<CXXRecordType>(Record)->getDecl(), 2880 /*LookInParentCtx=*/false); 2881 NamedDecl *MemberOps = (I == IdResolver.end())? 0 : *I; 2882 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps)) 2883 AddMethodCandidate(Method, Object, Args, NumArgs, CandidateSet, 2884 /*SuppressUserConversions=*/false); 2885 else if (OverloadedFunctionDecl *Ovl 2886 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) { 2887 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(), 2888 FEnd = Ovl->function_end(); 2889 F != FEnd; ++F) { 2890 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F)) 2891 AddMethodCandidate(Method, Object, Args, NumArgs, CandidateSet, 2892 /*SuppressUserConversions=*/false); 2893 } 2894 } 2895 2896 CXXMethodDecl *Method = 0; 2897 2898 // Perform overload resolution. 2899 OverloadCandidateSet::iterator Best; 2900 switch (BestViableFunction(CandidateSet, Best)) { 2901 case OR_Success: 2902 // We found a method. We'll build a call to it below. 2903 Method = cast<CXXMethodDecl>(Best->Function); 2904 break; 2905 2906 case OR_No_Viable_Function: 2907 if (CandidateSet.empty()) 2908 Diag(Object->getSourceRange().getBegin(), 2909 diag::err_ovl_no_viable_object_call) 2910 << Object->getType().getAsString() << Object->getSourceRange(); 2911 else { 2912 Diag(Object->getSourceRange().getBegin(), 2913 diag::err_ovl_no_viable_object_call_with_cands) 2914 << Object->getType().getAsString() << Object->getSourceRange(); 2915 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 2916 } 2917 break; 2918 2919 case OR_Ambiguous: 2920 Diag(Object->getSourceRange().getBegin(), 2921 diag::err_ovl_ambiguous_object_call) 2922 << Object->getType().getAsString() << Object->getSourceRange(); 2923 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 2924 break; 2925 } 2926 2927 if (!Method) { 2928 // We had an error; delete all of the subexpressions and return 2929 // the error. 2930 delete Object; 2931 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 2932 delete Args[ArgIdx]; 2933 return true; 2934 } 2935 2936 // Build a CXXOperatorCallExpr that calls this method, using Object for 2937 // the implicit object parameter and passing along the remaining 2938 // arguments. 2939 const FunctionTypeProto *Proto = Method->getType()->getAsFunctionTypeProto(); 2940 2941 unsigned NumArgsInProto = Proto->getNumArgs(); 2942 unsigned NumArgsToCheck = NumArgs; 2943 2944 // Build the full argument list for the method call (the 2945 // implicit object parameter is placed at the beginning of the 2946 // list). 2947 Expr **MethodArgs; 2948 if (NumArgs < NumArgsInProto) { 2949 NumArgsToCheck = NumArgsInProto; 2950 MethodArgs = new Expr*[NumArgsInProto + 1]; 2951 } else { 2952 MethodArgs = new Expr*[NumArgs + 1]; 2953 } 2954 MethodArgs[0] = Object; 2955 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 2956 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 2957 2958 Expr *NewFn = new DeclRefExpr(Method, Method->getType(), 2959 SourceLocation()); 2960 UsualUnaryConversions(NewFn); 2961 2962 // Once we've built TheCall, all of the expressions are properly 2963 // owned. 2964 QualType ResultTy = Method->getResultType().getNonReferenceType(); 2965 llvm::OwningPtr<CXXOperatorCallExpr> 2966 TheCall(new CXXOperatorCallExpr(NewFn, MethodArgs, NumArgs + 1, 2967 ResultTy, RParenLoc)); 2968 delete [] MethodArgs; 2969 2970 // Initialize the implicit object parameter. 2971 if (!PerformObjectArgumentInitialization(Object, Method)) 2972 return true; 2973 TheCall->setArg(0, Object); 2974 2975 // Check the argument types. 2976 for (unsigned i = 0; i != NumArgsToCheck; i++) { 2977 QualType ProtoArgType = Proto->getArgType(i); 2978 2979 Expr *Arg; 2980 if (i < NumArgs) 2981 Arg = Args[i]; 2982 else 2983 Arg = new CXXDefaultArgExpr(Method->getParamDecl(i)); 2984 QualType ArgType = Arg->getType(); 2985 2986 // Pass the argument. 2987 if (PerformCopyInitialization(Arg, ProtoArgType, "passing")) 2988 return true; 2989 2990 TheCall->setArg(i + 1, Arg); 2991 } 2992 2993 // If this is a variadic call, handle args passed through "...". 2994 if (Proto->isVariadic()) { 2995 // Promote the arguments (C99 6.5.2.2p7). 2996 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 2997 Expr *Arg = Args[i]; 2998 DefaultArgumentPromotion(Arg); 2999 TheCall->setArg(i + 1, Arg); 3000 } 3001 } 3002 3003 return CheckFunctionCall(Method, TheCall.take()); 3004} 3005 3006/// FixOverloadedFunctionReference - E is an expression that refers to 3007/// a C++ overloaded function (possibly with some parentheses and 3008/// perhaps a '&' around it). We have resolved the overloaded function 3009/// to the function declaration Fn, so patch up the expression E to 3010/// refer (possibly indirectly) to Fn. 3011void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) { 3012 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 3013 FixOverloadedFunctionReference(PE->getSubExpr(), Fn); 3014 E->setType(PE->getSubExpr()->getType()); 3015 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 3016 assert(UnOp->getOpcode() == UnaryOperator::AddrOf && 3017 "Can only take the address of an overloaded function"); 3018 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn); 3019 E->setType(Context.getPointerType(E->getType())); 3020 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 3021 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) && 3022 "Expected overloaded function"); 3023 DR->setDecl(Fn); 3024 E->setType(Fn->getType()); 3025 } else { 3026 assert(false && "Invalid reference to overloaded function"); 3027 } 3028} 3029 3030} // end namespace clang 3031