SemaOverload.cpp revision 88a3514f36de96b19cdf50141c640df1a5f13f6c
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->getNameAsString().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 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers()) 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.IncompatibleObjC = false; 423 SCS.FromTypePtr = FromType.getAsOpaquePtr(); 424 SCS.CopyConstructor = 0; 425 426 // The first conversion can be an lvalue-to-rvalue conversion, 427 // array-to-pointer conversion, or function-to-pointer conversion 428 // (C++ 4p1). 429 430 // Lvalue-to-rvalue conversion (C++ 4.1): 431 // An lvalue (3.10) of a non-function, non-array type T can be 432 // converted to an rvalue. 433 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context); 434 if (argIsLvalue == Expr::LV_Valid && 435 !FromType->isFunctionType() && !FromType->isArrayType() && 436 !FromType->isOverloadType()) { 437 SCS.First = ICK_Lvalue_To_Rvalue; 438 439 // If T is a non-class type, the type of the rvalue is the 440 // cv-unqualified version of T. Otherwise, the type of the rvalue 441 // is T (C++ 4.1p1). 442 FromType = FromType.getUnqualifiedType(); 443 } 444 // Array-to-pointer conversion (C++ 4.2) 445 else if (FromType->isArrayType()) { 446 SCS.First = ICK_Array_To_Pointer; 447 448 // An lvalue or rvalue of type "array of N T" or "array of unknown 449 // bound of T" can be converted to an rvalue of type "pointer to 450 // T" (C++ 4.2p1). 451 FromType = Context.getArrayDecayedType(FromType); 452 453 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) { 454 // This conversion is deprecated. (C++ D.4). 455 SCS.Deprecated = true; 456 457 // For the purpose of ranking in overload resolution 458 // (13.3.3.1.1), this conversion is considered an 459 // array-to-pointer conversion followed by a qualification 460 // conversion (4.4). (C++ 4.2p2) 461 SCS.Second = ICK_Identity; 462 SCS.Third = ICK_Qualification; 463 SCS.ToTypePtr = ToType.getAsOpaquePtr(); 464 return true; 465 } 466 } 467 // Function-to-pointer conversion (C++ 4.3). 468 else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) { 469 SCS.First = ICK_Function_To_Pointer; 470 471 // An lvalue of function type T can be converted to an rvalue of 472 // type "pointer to T." The result is a pointer to the 473 // function. (C++ 4.3p1). 474 FromType = Context.getPointerType(FromType); 475 } 476 // Address of overloaded function (C++ [over.over]). 477 else if (FunctionDecl *Fn 478 = ResolveAddressOfOverloadedFunction(From, ToType, false)) { 479 SCS.First = ICK_Function_To_Pointer; 480 481 // We were able to resolve the address of the overloaded function, 482 // so we can convert to the type of that function. 483 FromType = Fn->getType(); 484 if (ToType->isReferenceType()) 485 FromType = Context.getReferenceType(FromType); 486 else 487 FromType = Context.getPointerType(FromType); 488 } 489 // We don't require any conversions for the first step. 490 else { 491 SCS.First = ICK_Identity; 492 } 493 494 // The second conversion can be an integral promotion, floating 495 // point promotion, integral conversion, floating point conversion, 496 // floating-integral conversion, pointer conversion, 497 // pointer-to-member conversion, or boolean conversion (C++ 4p1). 498 bool IncompatibleObjC = false; 499 if (Context.getCanonicalType(FromType).getUnqualifiedType() == 500 Context.getCanonicalType(ToType).getUnqualifiedType()) { 501 // The unqualified versions of the types are the same: there's no 502 // conversion to do. 503 SCS.Second = ICK_Identity; 504 } 505 // Integral promotion (C++ 4.5). 506 else if (IsIntegralPromotion(From, FromType, ToType)) { 507 SCS.Second = ICK_Integral_Promotion; 508 FromType = ToType.getUnqualifiedType(); 509 } 510 // Floating point promotion (C++ 4.6). 511 else if (IsFloatingPointPromotion(FromType, ToType)) { 512 SCS.Second = ICK_Floating_Promotion; 513 FromType = ToType.getUnqualifiedType(); 514 } 515 // Integral conversions (C++ 4.7). 516 // FIXME: isIntegralType shouldn't be true for enums in C++. 517 else if ((FromType->isIntegralType() || FromType->isEnumeralType()) && 518 (ToType->isIntegralType() && !ToType->isEnumeralType())) { 519 SCS.Second = ICK_Integral_Conversion; 520 FromType = ToType.getUnqualifiedType(); 521 } 522 // Floating point conversions (C++ 4.8). 523 else if (FromType->isFloatingType() && ToType->isFloatingType()) { 524 SCS.Second = ICK_Floating_Conversion; 525 FromType = ToType.getUnqualifiedType(); 526 } 527 // Floating-integral conversions (C++ 4.9). 528 // FIXME: isIntegralType shouldn't be true for enums in C++. 529 else if ((FromType->isFloatingType() && 530 ToType->isIntegralType() && !ToType->isBooleanType() && 531 !ToType->isEnumeralType()) || 532 ((FromType->isIntegralType() || FromType->isEnumeralType()) && 533 ToType->isFloatingType())) { 534 SCS.Second = ICK_Floating_Integral; 535 FromType = ToType.getUnqualifiedType(); 536 } 537 // Pointer conversions (C++ 4.10). 538 else if (IsPointerConversion(From, FromType, ToType, FromType, 539 IncompatibleObjC)) { 540 SCS.Second = ICK_Pointer_Conversion; 541 SCS.IncompatibleObjC = IncompatibleObjC; 542 } 543 // FIXME: Pointer to member conversions (4.11). 544 // Boolean conversions (C++ 4.12). 545 // FIXME: pointer-to-member type 546 else if (ToType->isBooleanType() && 547 (FromType->isArithmeticType() || 548 FromType->isEnumeralType() || 549 FromType->isPointerType())) { 550 SCS.Second = ICK_Boolean_Conversion; 551 FromType = Context.BoolTy; 552 } else { 553 // No second conversion required. 554 SCS.Second = ICK_Identity; 555 } 556 557 QualType CanonFrom; 558 QualType CanonTo; 559 // The third conversion can be a qualification conversion (C++ 4p1). 560 if (IsQualificationConversion(FromType, ToType)) { 561 SCS.Third = ICK_Qualification; 562 FromType = ToType; 563 CanonFrom = Context.getCanonicalType(FromType); 564 CanonTo = Context.getCanonicalType(ToType); 565 } else { 566 // No conversion required 567 SCS.Third = ICK_Identity; 568 569 // C++ [over.best.ics]p6: 570 // [...] Any difference in top-level cv-qualification is 571 // subsumed by the initialization itself and does not constitute 572 // a conversion. [...] 573 CanonFrom = Context.getCanonicalType(FromType); 574 CanonTo = Context.getCanonicalType(ToType); 575 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() && 576 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) { 577 FromType = ToType; 578 CanonFrom = CanonTo; 579 } 580 } 581 582 // If we have not converted the argument type to the parameter type, 583 // this is a bad conversion sequence. 584 if (CanonFrom != CanonTo) 585 return false; 586 587 SCS.ToTypePtr = FromType.getAsOpaquePtr(); 588 return true; 589} 590 591/// IsIntegralPromotion - Determines whether the conversion from the 592/// expression From (whose potentially-adjusted type is FromType) to 593/// ToType is an integral promotion (C++ 4.5). If so, returns true and 594/// sets PromotedType to the promoted type. 595bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) 596{ 597 const BuiltinType *To = ToType->getAsBuiltinType(); 598 // All integers are built-in. 599 if (!To) { 600 return false; 601 } 602 603 // An rvalue of type char, signed char, unsigned char, short int, or 604 // unsigned short int can be converted to an rvalue of type int if 605 // int can represent all the values of the source type; otherwise, 606 // the source rvalue can be converted to an rvalue of type unsigned 607 // int (C++ 4.5p1). 608 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) { 609 if (// We can promote any signed, promotable integer type to an int 610 (FromType->isSignedIntegerType() || 611 // We can promote any unsigned integer type whose size is 612 // less than int to an int. 613 (!FromType->isSignedIntegerType() && 614 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) { 615 return To->getKind() == BuiltinType::Int; 616 } 617 618 return To->getKind() == BuiltinType::UInt; 619 } 620 621 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2) 622 // can be converted to an rvalue of the first of the following types 623 // that can represent all the values of its underlying type: int, 624 // unsigned int, long, or unsigned long (C++ 4.5p2). 625 if ((FromType->isEnumeralType() || FromType->isWideCharType()) 626 && ToType->isIntegerType()) { 627 // Determine whether the type we're converting from is signed or 628 // unsigned. 629 bool FromIsSigned; 630 uint64_t FromSize = Context.getTypeSize(FromType); 631 if (const EnumType *FromEnumType = FromType->getAsEnumType()) { 632 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType(); 633 FromIsSigned = UnderlyingType->isSignedIntegerType(); 634 } else { 635 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now. 636 FromIsSigned = true; 637 } 638 639 // The types we'll try to promote to, in the appropriate 640 // order. Try each of these types. 641 QualType PromoteTypes[6] = { 642 Context.IntTy, Context.UnsignedIntTy, 643 Context.LongTy, Context.UnsignedLongTy , 644 Context.LongLongTy, Context.UnsignedLongLongTy 645 }; 646 for (int Idx = 0; Idx < 6; ++Idx) { 647 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]); 648 if (FromSize < ToSize || 649 (FromSize == ToSize && 650 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) { 651 // We found the type that we can promote to. If this is the 652 // type we wanted, we have a promotion. Otherwise, no 653 // promotion. 654 return Context.getCanonicalType(ToType).getUnqualifiedType() 655 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType(); 656 } 657 } 658 } 659 660 // An rvalue for an integral bit-field (9.6) can be converted to an 661 // rvalue of type int if int can represent all the values of the 662 // bit-field; otherwise, it can be converted to unsigned int if 663 // unsigned int can represent all the values of the bit-field. If 664 // the bit-field is larger yet, no integral promotion applies to 665 // it. If the bit-field has an enumerated type, it is treated as any 666 // other value of that type for promotion purposes (C++ 4.5p3). 667 if (MemberExpr *MemRef = dyn_cast<MemberExpr>(From)) { 668 using llvm::APSInt; 669 if (FieldDecl *MemberDecl = dyn_cast<FieldDecl>(MemRef->getMemberDecl())) { 670 APSInt BitWidth; 671 if (MemberDecl->isBitField() && 672 FromType->isIntegralType() && !FromType->isEnumeralType() && 673 From->isIntegerConstantExpr(BitWidth, Context)) { 674 APSInt ToSize(Context.getTypeSize(ToType)); 675 676 // Are we promoting to an int from a bitfield that fits in an int? 677 if (BitWidth < ToSize || 678 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) { 679 return To->getKind() == BuiltinType::Int; 680 } 681 682 // Are we promoting to an unsigned int from an unsigned bitfield 683 // that fits into an unsigned int? 684 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) { 685 return To->getKind() == BuiltinType::UInt; 686 } 687 688 return false; 689 } 690 } 691 } 692 693 // An rvalue of type bool can be converted to an rvalue of type int, 694 // with false becoming zero and true becoming one (C++ 4.5p4). 695 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) { 696 return true; 697 } 698 699 return false; 700} 701 702/// IsFloatingPointPromotion - Determines whether the conversion from 703/// FromType to ToType is a floating point promotion (C++ 4.6). If so, 704/// returns true and sets PromotedType to the promoted type. 705bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) 706{ 707 /// An rvalue of type float can be converted to an rvalue of type 708 /// double. (C++ 4.6p1). 709 if (const BuiltinType *FromBuiltin = FromType->getAsBuiltinType()) 710 if (const BuiltinType *ToBuiltin = ToType->getAsBuiltinType()) 711 if (FromBuiltin->getKind() == BuiltinType::Float && 712 ToBuiltin->getKind() == BuiltinType::Double) 713 return true; 714 715 return false; 716} 717 718/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from 719/// the pointer type FromPtr to a pointer to type ToPointee, with the 720/// same type qualifiers as FromPtr has on its pointee type. ToType, 721/// if non-empty, will be a pointer to ToType that may or may not have 722/// the right set of qualifiers on its pointee. 723static QualType 724BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr, 725 QualType ToPointee, QualType ToType, 726 ASTContext &Context) { 727 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType()); 728 QualType CanonToPointee = Context.getCanonicalType(ToPointee); 729 unsigned Quals = CanonFromPointee.getCVRQualifiers(); 730 731 // Exact qualifier match -> return the pointer type we're converting to. 732 if (CanonToPointee.getCVRQualifiers() == Quals) { 733 // ToType is exactly what we need. Return it. 734 if (ToType.getTypePtr()) 735 return ToType; 736 737 // Build a pointer to ToPointee. It has the right qualifiers 738 // already. 739 return Context.getPointerType(ToPointee); 740 } 741 742 // Just build a canonical type that has the right qualifiers. 743 return Context.getPointerType(CanonToPointee.getQualifiedType(Quals)); 744} 745 746/// IsPointerConversion - Determines whether the conversion of the 747/// expression From, which has the (possibly adjusted) type FromType, 748/// can be converted to the type ToType via a pointer conversion (C++ 749/// 4.10). If so, returns true and places the converted type (that 750/// might differ from ToType in its cv-qualifiers at some level) into 751/// ConvertedType. 752/// 753/// This routine also supports conversions to and from block pointers 754/// and conversions with Objective-C's 'id', 'id<protocols...>', and 755/// pointers to interfaces. FIXME: Once we've determined the 756/// appropriate overloading rules for Objective-C, we may want to 757/// split the Objective-C checks into a different routine; however, 758/// GCC seems to consider all of these conversions to be pointer 759/// conversions, so for now they live here. IncompatibleObjC will be 760/// set if the conversion is an allowed Objective-C conversion that 761/// should result in a warning. 762bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType, 763 QualType& ConvertedType, 764 bool &IncompatibleObjC) 765{ 766 IncompatibleObjC = false; 767 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC)) 768 return true; 769 770 // Blocks: Block pointers can be converted to void*. 771 if (FromType->isBlockPointerType() && ToType->isPointerType() && 772 ToType->getAsPointerType()->getPointeeType()->isVoidType()) { 773 ConvertedType = ToType; 774 return true; 775 } 776 // Blocks: A null pointer constant can be converted to a block 777 // pointer type. 778 if (ToType->isBlockPointerType() && From->isNullPointerConstant(Context)) { 779 ConvertedType = ToType; 780 return true; 781 } 782 783 const PointerType* ToTypePtr = ToType->getAsPointerType(); 784 if (!ToTypePtr) 785 return false; 786 787 // A null pointer constant can be converted to a pointer type (C++ 4.10p1). 788 if (From->isNullPointerConstant(Context)) { 789 ConvertedType = ToType; 790 return true; 791 } 792 793 // Beyond this point, both types need to be pointers. 794 const PointerType *FromTypePtr = FromType->getAsPointerType(); 795 if (!FromTypePtr) 796 return false; 797 798 QualType FromPointeeType = FromTypePtr->getPointeeType(); 799 QualType ToPointeeType = ToTypePtr->getPointeeType(); 800 801 // An rvalue of type "pointer to cv T," where T is an object type, 802 // can be converted to an rvalue of type "pointer to cv void" (C++ 803 // 4.10p2). 804 if (FromPointeeType->isIncompleteOrObjectType() && 805 ToPointeeType->isVoidType()) { 806 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 807 ToPointeeType, 808 ToType, Context); 809 return true; 810 } 811 812 // C++ [conv.ptr]p3: 813 // 814 // An rvalue of type "pointer to cv D," where D is a class type, 815 // can be converted to an rvalue of type "pointer to cv B," where 816 // B is a base class (clause 10) of D. If B is an inaccessible 817 // (clause 11) or ambiguous (10.2) base class of D, a program that 818 // necessitates this conversion is ill-formed. The result of the 819 // conversion is a pointer to the base class sub-object of the 820 // derived class object. The null pointer value is converted to 821 // the null pointer value of the destination type. 822 // 823 // Note that we do not check for ambiguity or inaccessibility 824 // here. That is handled by CheckPointerConversion. 825 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() && 826 IsDerivedFrom(FromPointeeType, ToPointeeType)) { 827 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 828 ToPointeeType, 829 ToType, Context); 830 return true; 831 } 832 833 return false; 834} 835 836/// isObjCPointerConversion - Determines whether this is an 837/// Objective-C pointer conversion. Subroutine of IsPointerConversion, 838/// with the same arguments and return values. 839bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType, 840 QualType& ConvertedType, 841 bool &IncompatibleObjC) { 842 if (!getLangOptions().ObjC1) 843 return false; 844 845 // Conversions with Objective-C's id<...>. 846 if ((FromType->isObjCQualifiedIdType() || ToType->isObjCQualifiedIdType()) && 847 ObjCQualifiedIdTypesAreCompatible(ToType, FromType, /*compare=*/false)) { 848 ConvertedType = ToType; 849 return true; 850 } 851 852 const PointerType* ToTypePtr = ToType->getAsPointerType(); 853 if (!ToTypePtr) 854 return false; 855 856 // Beyond this point, both types need to be pointers. 857 const PointerType *FromTypePtr = FromType->getAsPointerType(); 858 if (!FromTypePtr) 859 return false; 860 861 QualType FromPointeeType = FromTypePtr->getPointeeType(); 862 QualType ToPointeeType = ToTypePtr->getPointeeType(); 863 864 // Objective C++: We're able to convert from a pointer to an 865 // interface to a pointer to a different interface. 866 const ObjCInterfaceType* FromIface = FromPointeeType->getAsObjCInterfaceType(); 867 const ObjCInterfaceType* ToIface = ToPointeeType->getAsObjCInterfaceType(); 868 if (FromIface && ToIface && 869 Context.canAssignObjCInterfaces(ToIface, FromIface)) { 870 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 871 ToPointeeType, 872 ToType, Context); 873 return true; 874 } 875 876 if (FromIface && ToIface && 877 Context.canAssignObjCInterfaces(FromIface, ToIface)) { 878 // Okay: this is some kind of implicit downcast of Objective-C 879 // interfaces, which is permitted. However, we're going to 880 // complain about it. 881 IncompatibleObjC = true; 882 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 883 ToPointeeType, 884 ToType, Context); 885 return true; 886 } 887 888 // Objective C++: We're able to convert between "id" and a pointer 889 // to any interface (in both directions). 890 if ((FromIface && Context.isObjCIdType(ToPointeeType)) 891 || (ToIface && Context.isObjCIdType(FromPointeeType))) { 892 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr, 893 ToPointeeType, 894 ToType, Context); 895 return true; 896 } 897 898 // Objective C++: Allow conversions between the Objective-C "id" and 899 // "Class", in either direction. 900 if ((Context.isObjCIdType(FromPointeeType) && 901 Context.isObjCClassType(ToPointeeType)) || 902 (Context.isObjCClassType(FromPointeeType) && 903 Context.isObjCIdType(ToPointeeType))) { 904 ConvertedType = ToType; 905 return true; 906 } 907 908 // If we have pointers to pointers, recursively check whether this 909 // is an Objective-C conversion. 910 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() && 911 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType, 912 IncompatibleObjC)) { 913 // We always complain about this conversion. 914 IncompatibleObjC = true; 915 ConvertedType = ToType; 916 return true; 917 } 918 919 // If we have pointers to functions, check whether the only 920 // differences in the argument and result types are in Objective-C 921 // pointer conversions. If so, we permit the conversion (but 922 // complain about it). 923 const FunctionTypeProto *FromFunctionType 924 = FromPointeeType->getAsFunctionTypeProto(); 925 const FunctionTypeProto *ToFunctionType 926 = ToPointeeType->getAsFunctionTypeProto(); 927 if (FromFunctionType && ToFunctionType) { 928 // If the function types are exactly the same, this isn't an 929 // Objective-C pointer conversion. 930 if (Context.getCanonicalType(FromPointeeType) 931 == Context.getCanonicalType(ToPointeeType)) 932 return false; 933 934 // Perform the quick checks that will tell us whether these 935 // function types are obviously different. 936 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() || 937 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() || 938 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals()) 939 return false; 940 941 bool HasObjCConversion = false; 942 if (Context.getCanonicalType(FromFunctionType->getResultType()) 943 == Context.getCanonicalType(ToFunctionType->getResultType())) { 944 // Okay, the types match exactly. Nothing to do. 945 } else if (isObjCPointerConversion(FromFunctionType->getResultType(), 946 ToFunctionType->getResultType(), 947 ConvertedType, IncompatibleObjC)) { 948 // Okay, we have an Objective-C pointer conversion. 949 HasObjCConversion = true; 950 } else { 951 // Function types are too different. Abort. 952 return false; 953 } 954 955 // Check argument types. 956 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 957 ArgIdx != NumArgs; ++ArgIdx) { 958 QualType FromArgType = FromFunctionType->getArgType(ArgIdx); 959 QualType ToArgType = ToFunctionType->getArgType(ArgIdx); 960 if (Context.getCanonicalType(FromArgType) 961 == Context.getCanonicalType(ToArgType)) { 962 // Okay, the types match exactly. Nothing to do. 963 } else if (isObjCPointerConversion(FromArgType, ToArgType, 964 ConvertedType, IncompatibleObjC)) { 965 // Okay, we have an Objective-C pointer conversion. 966 HasObjCConversion = true; 967 } else { 968 // Argument types are too different. Abort. 969 return false; 970 } 971 } 972 973 if (HasObjCConversion) { 974 // We had an Objective-C conversion. Allow this pointer 975 // conversion, but complain about it. 976 ConvertedType = ToType; 977 IncompatibleObjC = true; 978 return true; 979 } 980 } 981 982 return false; 983} 984 985/// CheckPointerConversion - Check the pointer conversion from the 986/// expression From to the type ToType. This routine checks for 987/// ambiguous (FIXME: or inaccessible) derived-to-base pointer 988/// conversions for which IsPointerConversion has already returned 989/// true. It returns true and produces a diagnostic if there was an 990/// error, or returns false otherwise. 991bool Sema::CheckPointerConversion(Expr *From, QualType ToType) { 992 QualType FromType = From->getType(); 993 994 if (const PointerType *FromPtrType = FromType->getAsPointerType()) 995 if (const PointerType *ToPtrType = ToType->getAsPointerType()) { 996 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 997 /*DetectVirtual=*/false); 998 QualType FromPointeeType = FromPtrType->getPointeeType(), 999 ToPointeeType = ToPtrType->getPointeeType(); 1000 1001 // Objective-C++ conversions are always okay. 1002 // FIXME: We should have a different class of conversions for 1003 // the Objective-C++ implicit conversions. 1004 if (Context.isObjCIdType(FromPointeeType) || 1005 Context.isObjCIdType(ToPointeeType) || 1006 Context.isObjCClassType(FromPointeeType) || 1007 Context.isObjCClassType(ToPointeeType)) 1008 return false; 1009 1010 if (FromPointeeType->isRecordType() && 1011 ToPointeeType->isRecordType()) { 1012 // We must have a derived-to-base conversion. Check an 1013 // ambiguous or inaccessible conversion. 1014 return CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType, 1015 From->getExprLoc(), 1016 From->getSourceRange()); 1017 } 1018 } 1019 1020 return false; 1021} 1022 1023/// IsQualificationConversion - Determines whether the conversion from 1024/// an rvalue of type FromType to ToType is a qualification conversion 1025/// (C++ 4.4). 1026bool 1027Sema::IsQualificationConversion(QualType FromType, QualType ToType) 1028{ 1029 FromType = Context.getCanonicalType(FromType); 1030 ToType = Context.getCanonicalType(ToType); 1031 1032 // If FromType and ToType are the same type, this is not a 1033 // qualification conversion. 1034 if (FromType == ToType) 1035 return false; 1036 1037 // (C++ 4.4p4): 1038 // A conversion can add cv-qualifiers at levels other than the first 1039 // in multi-level pointers, subject to the following rules: [...] 1040 bool PreviousToQualsIncludeConst = true; 1041 bool UnwrappedAnyPointer = false; 1042 while (UnwrapSimilarPointerTypes(FromType, ToType)) { 1043 // Within each iteration of the loop, we check the qualifiers to 1044 // determine if this still looks like a qualification 1045 // conversion. Then, if all is well, we unwrap one more level of 1046 // pointers or pointers-to-members and do it all again 1047 // until there are no more pointers or pointers-to-members left to 1048 // unwrap. 1049 UnwrappedAnyPointer = true; 1050 1051 // -- for every j > 0, if const is in cv 1,j then const is in cv 1052 // 2,j, and similarly for volatile. 1053 if (!ToType.isAtLeastAsQualifiedAs(FromType)) 1054 return false; 1055 1056 // -- if the cv 1,j and cv 2,j are different, then const is in 1057 // every cv for 0 < k < j. 1058 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers() 1059 && !PreviousToQualsIncludeConst) 1060 return false; 1061 1062 // Keep track of whether all prior cv-qualifiers in the "to" type 1063 // include const. 1064 PreviousToQualsIncludeConst 1065 = PreviousToQualsIncludeConst && ToType.isConstQualified(); 1066 } 1067 1068 // We are left with FromType and ToType being the pointee types 1069 // after unwrapping the original FromType and ToType the same number 1070 // of types. If we unwrapped any pointers, and if FromType and 1071 // ToType have the same unqualified type (since we checked 1072 // qualifiers above), then this is a qualification conversion. 1073 return UnwrappedAnyPointer && 1074 FromType.getUnqualifiedType() == ToType.getUnqualifiedType(); 1075} 1076 1077/// IsUserDefinedConversion - Determines whether there is a 1078/// user-defined conversion sequence (C++ [over.ics.user]) that 1079/// converts expression From to the type ToType. If such a conversion 1080/// exists, User will contain the user-defined conversion sequence 1081/// that performs such a conversion and this routine will return 1082/// true. Otherwise, this routine returns false and User is 1083/// unspecified. 1084bool Sema::IsUserDefinedConversion(Expr *From, QualType ToType, 1085 UserDefinedConversionSequence& User) 1086{ 1087 OverloadCandidateSet CandidateSet; 1088 if (const CXXRecordType *ToRecordType 1089 = dyn_cast_or_null<CXXRecordType>(ToType->getAsRecordType())) { 1090 // C++ [over.match.ctor]p1: 1091 // When objects of class type are direct-initialized (8.5), or 1092 // copy-initialized from an expression of the same or a 1093 // derived class type (8.5), overload resolution selects the 1094 // constructor. [...] For copy-initialization, the candidate 1095 // functions are all the converting constructors (12.3.1) of 1096 // that class. The argument list is the expression-list within 1097 // the parentheses of the initializer. 1098 CXXRecordDecl *ToRecordDecl = ToRecordType->getDecl(); 1099 DeclarationName ConstructorName 1100 = Context.DeclarationNames.getCXXConstructorName( 1101 Context.getCanonicalType(ToType)); 1102 DeclContext::lookup_result Lookup 1103 = ToRecordDecl->lookup(Context, ConstructorName); 1104 if (Lookup.first == Lookup.second) 1105 /* No constructors. FIXME: Implicit copy constructor? */; 1106 else if (OverloadedFunctionDecl *Constructors 1107 = dyn_cast<OverloadedFunctionDecl>(*Lookup.first)) { 1108 for (OverloadedFunctionDecl::function_const_iterator func 1109 = Constructors->function_begin(); 1110 func != Constructors->function_end(); ++func) { 1111 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(*func); 1112 if (Constructor->isConvertingConstructor()) 1113 AddOverloadCandidate(Constructor, &From, 1, CandidateSet, 1114 /*SuppressUserConversions=*/true); 1115 } 1116 } else if (CXXConstructorDecl *Constructor 1117 = dyn_cast<CXXConstructorDecl>(*Lookup.first)) { 1118 if (Constructor->isConvertingConstructor()) 1119 AddOverloadCandidate(Constructor, &From, 1, CandidateSet, 1120 /*SuppressUserConversions=*/true); 1121 } 1122 } 1123 1124 if (const CXXRecordType *FromRecordType 1125 = dyn_cast_or_null<CXXRecordType>(From->getType()->getAsRecordType())) { 1126 // Add all of the conversion functions as candidates. 1127 // FIXME: Look for conversions in base classes! 1128 CXXRecordDecl *FromRecordDecl = FromRecordType->getDecl(); 1129 OverloadedFunctionDecl *Conversions 1130 = FromRecordDecl->getConversionFunctions(); 1131 for (OverloadedFunctionDecl::function_iterator Func 1132 = Conversions->function_begin(); 1133 Func != Conversions->function_end(); ++Func) { 1134 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func); 1135 AddConversionCandidate(Conv, From, ToType, CandidateSet); 1136 } 1137 } 1138 1139 OverloadCandidateSet::iterator Best; 1140 switch (BestViableFunction(CandidateSet, Best)) { 1141 case OR_Success: 1142 // Record the standard conversion we used and the conversion function. 1143 if (CXXConstructorDecl *Constructor 1144 = dyn_cast<CXXConstructorDecl>(Best->Function)) { 1145 // C++ [over.ics.user]p1: 1146 // If the user-defined conversion is specified by a 1147 // constructor (12.3.1), the initial standard conversion 1148 // sequence converts the source type to the type required by 1149 // the argument of the constructor. 1150 // 1151 // FIXME: What about ellipsis conversions? 1152 QualType ThisType = Constructor->getThisType(Context); 1153 User.Before = Best->Conversions[0].Standard; 1154 User.ConversionFunction = Constructor; 1155 User.After.setAsIdentityConversion(); 1156 User.After.FromTypePtr 1157 = ThisType->getAsPointerType()->getPointeeType().getAsOpaquePtr(); 1158 User.After.ToTypePtr = ToType.getAsOpaquePtr(); 1159 return true; 1160 } else if (CXXConversionDecl *Conversion 1161 = dyn_cast<CXXConversionDecl>(Best->Function)) { 1162 // C++ [over.ics.user]p1: 1163 // 1164 // [...] If the user-defined conversion is specified by a 1165 // conversion function (12.3.2), the initial standard 1166 // conversion sequence converts the source type to the 1167 // implicit object parameter of the conversion function. 1168 User.Before = Best->Conversions[0].Standard; 1169 User.ConversionFunction = Conversion; 1170 1171 // C++ [over.ics.user]p2: 1172 // The second standard conversion sequence converts the 1173 // result of the user-defined conversion to the target type 1174 // for the sequence. Since an implicit conversion sequence 1175 // is an initialization, the special rules for 1176 // initialization by user-defined conversion apply when 1177 // selecting the best user-defined conversion for a 1178 // user-defined conversion sequence (see 13.3.3 and 1179 // 13.3.3.1). 1180 User.After = Best->FinalConversion; 1181 return true; 1182 } else { 1183 assert(false && "Not a constructor or conversion function?"); 1184 return false; 1185 } 1186 1187 case OR_No_Viable_Function: 1188 // No conversion here! We're done. 1189 return false; 1190 1191 case OR_Ambiguous: 1192 // FIXME: See C++ [over.best.ics]p10 for the handling of 1193 // ambiguous conversion sequences. 1194 return false; 1195 } 1196 1197 return false; 1198} 1199 1200/// CompareImplicitConversionSequences - Compare two implicit 1201/// conversion sequences to determine whether one is better than the 1202/// other or if they are indistinguishable (C++ 13.3.3.2). 1203ImplicitConversionSequence::CompareKind 1204Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1, 1205 const ImplicitConversionSequence& ICS2) 1206{ 1207 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit 1208 // conversion sequences (as defined in 13.3.3.1) 1209 // -- a standard conversion sequence (13.3.3.1.1) is a better 1210 // conversion sequence than a user-defined conversion sequence or 1211 // an ellipsis conversion sequence, and 1212 // -- a user-defined conversion sequence (13.3.3.1.2) is a better 1213 // conversion sequence than an ellipsis conversion sequence 1214 // (13.3.3.1.3). 1215 // 1216 if (ICS1.ConversionKind < ICS2.ConversionKind) 1217 return ImplicitConversionSequence::Better; 1218 else if (ICS2.ConversionKind < ICS1.ConversionKind) 1219 return ImplicitConversionSequence::Worse; 1220 1221 // Two implicit conversion sequences of the same form are 1222 // indistinguishable conversion sequences unless one of the 1223 // following rules apply: (C++ 13.3.3.2p3): 1224 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion) 1225 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard); 1226 else if (ICS1.ConversionKind == 1227 ImplicitConversionSequence::UserDefinedConversion) { 1228 // User-defined conversion sequence U1 is a better conversion 1229 // sequence than another user-defined conversion sequence U2 if 1230 // they contain the same user-defined conversion function or 1231 // constructor and if the second standard conversion sequence of 1232 // U1 is better than the second standard conversion sequence of 1233 // U2 (C++ 13.3.3.2p3). 1234 if (ICS1.UserDefined.ConversionFunction == 1235 ICS2.UserDefined.ConversionFunction) 1236 return CompareStandardConversionSequences(ICS1.UserDefined.After, 1237 ICS2.UserDefined.After); 1238 } 1239 1240 return ImplicitConversionSequence::Indistinguishable; 1241} 1242 1243/// CompareStandardConversionSequences - Compare two standard 1244/// conversion sequences to determine whether one is better than the 1245/// other or if they are indistinguishable (C++ 13.3.3.2p3). 1246ImplicitConversionSequence::CompareKind 1247Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1, 1248 const StandardConversionSequence& SCS2) 1249{ 1250 // Standard conversion sequence S1 is a better conversion sequence 1251 // than standard conversion sequence S2 if (C++ 13.3.3.2p3): 1252 1253 // -- S1 is a proper subsequence of S2 (comparing the conversion 1254 // sequences in the canonical form defined by 13.3.3.1.1, 1255 // excluding any Lvalue Transformation; the identity conversion 1256 // sequence is considered to be a subsequence of any 1257 // non-identity conversion sequence) or, if not that, 1258 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third) 1259 // Neither is a proper subsequence of the other. Do nothing. 1260 ; 1261 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) || 1262 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) || 1263 (SCS1.Second == ICK_Identity && 1264 SCS1.Third == ICK_Identity)) 1265 // SCS1 is a proper subsequence of SCS2. 1266 return ImplicitConversionSequence::Better; 1267 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) || 1268 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) || 1269 (SCS2.Second == ICK_Identity && 1270 SCS2.Third == ICK_Identity)) 1271 // SCS2 is a proper subsequence of SCS1. 1272 return ImplicitConversionSequence::Worse; 1273 1274 // -- the rank of S1 is better than the rank of S2 (by the rules 1275 // defined below), or, if not that, 1276 ImplicitConversionRank Rank1 = SCS1.getRank(); 1277 ImplicitConversionRank Rank2 = SCS2.getRank(); 1278 if (Rank1 < Rank2) 1279 return ImplicitConversionSequence::Better; 1280 else if (Rank2 < Rank1) 1281 return ImplicitConversionSequence::Worse; 1282 1283 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank 1284 // are indistinguishable unless one of the following rules 1285 // applies: 1286 1287 // A conversion that is not a conversion of a pointer, or 1288 // pointer to member, to bool is better than another conversion 1289 // that is such a conversion. 1290 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool()) 1291 return SCS2.isPointerConversionToBool() 1292 ? ImplicitConversionSequence::Better 1293 : ImplicitConversionSequence::Worse; 1294 1295 // C++ [over.ics.rank]p4b2: 1296 // 1297 // If class B is derived directly or indirectly from class A, 1298 // conversion of B* to A* is better than conversion of B* to 1299 // void*, and conversion of A* to void* is better than conversion 1300 // of B* to void*. 1301 bool SCS1ConvertsToVoid 1302 = SCS1.isPointerConversionToVoidPointer(Context); 1303 bool SCS2ConvertsToVoid 1304 = SCS2.isPointerConversionToVoidPointer(Context); 1305 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) { 1306 // Exactly one of the conversion sequences is a conversion to 1307 // a void pointer; it's the worse conversion. 1308 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better 1309 : ImplicitConversionSequence::Worse; 1310 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) { 1311 // Neither conversion sequence converts to a void pointer; compare 1312 // their derived-to-base conversions. 1313 if (ImplicitConversionSequence::CompareKind DerivedCK 1314 = CompareDerivedToBaseConversions(SCS1, SCS2)) 1315 return DerivedCK; 1316 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) { 1317 // Both conversion sequences are conversions to void 1318 // pointers. Compare the source types to determine if there's an 1319 // inheritance relationship in their sources. 1320 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr); 1321 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr); 1322 1323 // Adjust the types we're converting from via the array-to-pointer 1324 // conversion, if we need to. 1325 if (SCS1.First == ICK_Array_To_Pointer) 1326 FromType1 = Context.getArrayDecayedType(FromType1); 1327 if (SCS2.First == ICK_Array_To_Pointer) 1328 FromType2 = Context.getArrayDecayedType(FromType2); 1329 1330 QualType FromPointee1 1331 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1332 QualType FromPointee2 1333 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1334 1335 if (IsDerivedFrom(FromPointee2, FromPointee1)) 1336 return ImplicitConversionSequence::Better; 1337 else if (IsDerivedFrom(FromPointee1, FromPointee2)) 1338 return ImplicitConversionSequence::Worse; 1339 1340 // Objective-C++: If one interface is more specific than the 1341 // other, it is the better one. 1342 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType(); 1343 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType(); 1344 if (FromIface1 && FromIface1) { 1345 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1)) 1346 return ImplicitConversionSequence::Better; 1347 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2)) 1348 return ImplicitConversionSequence::Worse; 1349 } 1350 } 1351 1352 // Compare based on qualification conversions (C++ 13.3.3.2p3, 1353 // bullet 3). 1354 if (ImplicitConversionSequence::CompareKind QualCK 1355 = CompareQualificationConversions(SCS1, SCS2)) 1356 return QualCK; 1357 1358 // C++ [over.ics.rank]p3b4: 1359 // -- S1 and S2 are reference bindings (8.5.3), and the types to 1360 // which the references refer are the same type except for 1361 // top-level cv-qualifiers, and the type to which the reference 1362 // initialized by S2 refers is more cv-qualified than the type 1363 // to which the reference initialized by S1 refers. 1364 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) { 1365 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr); 1366 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr); 1367 T1 = Context.getCanonicalType(T1); 1368 T2 = Context.getCanonicalType(T2); 1369 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) { 1370 if (T2.isMoreQualifiedThan(T1)) 1371 return ImplicitConversionSequence::Better; 1372 else if (T1.isMoreQualifiedThan(T2)) 1373 return ImplicitConversionSequence::Worse; 1374 } 1375 } 1376 1377 return ImplicitConversionSequence::Indistinguishable; 1378} 1379 1380/// CompareQualificationConversions - Compares two standard conversion 1381/// sequences to determine whether they can be ranked based on their 1382/// qualification conversions (C++ 13.3.3.2p3 bullet 3). 1383ImplicitConversionSequence::CompareKind 1384Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1, 1385 const StandardConversionSequence& SCS2) 1386{ 1387 // C++ 13.3.3.2p3: 1388 // -- S1 and S2 differ only in their qualification conversion and 1389 // yield similar types T1 and T2 (C++ 4.4), respectively, and the 1390 // cv-qualification signature of type T1 is a proper subset of 1391 // the cv-qualification signature of type T2, and S1 is not the 1392 // deprecated string literal array-to-pointer conversion (4.2). 1393 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second || 1394 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification) 1395 return ImplicitConversionSequence::Indistinguishable; 1396 1397 // FIXME: the example in the standard doesn't use a qualification 1398 // conversion (!) 1399 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr); 1400 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr); 1401 T1 = Context.getCanonicalType(T1); 1402 T2 = Context.getCanonicalType(T2); 1403 1404 // If the types are the same, we won't learn anything by unwrapped 1405 // them. 1406 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) 1407 return ImplicitConversionSequence::Indistinguishable; 1408 1409 ImplicitConversionSequence::CompareKind Result 1410 = ImplicitConversionSequence::Indistinguishable; 1411 while (UnwrapSimilarPointerTypes(T1, T2)) { 1412 // Within each iteration of the loop, we check the qualifiers to 1413 // determine if this still looks like a qualification 1414 // conversion. Then, if all is well, we unwrap one more level of 1415 // pointers or pointers-to-members and do it all again 1416 // until there are no more pointers or pointers-to-members left 1417 // to unwrap. This essentially mimics what 1418 // IsQualificationConversion does, but here we're checking for a 1419 // strict subset of qualifiers. 1420 if (T1.getCVRQualifiers() == T2.getCVRQualifiers()) 1421 // The qualifiers are the same, so this doesn't tell us anything 1422 // about how the sequences rank. 1423 ; 1424 else if (T2.isMoreQualifiedThan(T1)) { 1425 // T1 has fewer qualifiers, so it could be the better sequence. 1426 if (Result == ImplicitConversionSequence::Worse) 1427 // Neither has qualifiers that are a subset of the other's 1428 // qualifiers. 1429 return ImplicitConversionSequence::Indistinguishable; 1430 1431 Result = ImplicitConversionSequence::Better; 1432 } else if (T1.isMoreQualifiedThan(T2)) { 1433 // T2 has fewer qualifiers, so it could be the better sequence. 1434 if (Result == ImplicitConversionSequence::Better) 1435 // Neither has qualifiers that are a subset of the other's 1436 // qualifiers. 1437 return ImplicitConversionSequence::Indistinguishable; 1438 1439 Result = ImplicitConversionSequence::Worse; 1440 } else { 1441 // Qualifiers are disjoint. 1442 return ImplicitConversionSequence::Indistinguishable; 1443 } 1444 1445 // If the types after this point are equivalent, we're done. 1446 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) 1447 break; 1448 } 1449 1450 // Check that the winning standard conversion sequence isn't using 1451 // the deprecated string literal array to pointer conversion. 1452 switch (Result) { 1453 case ImplicitConversionSequence::Better: 1454 if (SCS1.Deprecated) 1455 Result = ImplicitConversionSequence::Indistinguishable; 1456 break; 1457 1458 case ImplicitConversionSequence::Indistinguishable: 1459 break; 1460 1461 case ImplicitConversionSequence::Worse: 1462 if (SCS2.Deprecated) 1463 Result = ImplicitConversionSequence::Indistinguishable; 1464 break; 1465 } 1466 1467 return Result; 1468} 1469 1470/// CompareDerivedToBaseConversions - Compares two standard conversion 1471/// sequences to determine whether they can be ranked based on their 1472/// various kinds of derived-to-base conversions (C++ 1473/// [over.ics.rank]p4b3). As part of these checks, we also look at 1474/// conversions between Objective-C interface types. 1475ImplicitConversionSequence::CompareKind 1476Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1, 1477 const StandardConversionSequence& SCS2) { 1478 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr); 1479 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr); 1480 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr); 1481 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr); 1482 1483 // Adjust the types we're converting from via the array-to-pointer 1484 // conversion, if we need to. 1485 if (SCS1.First == ICK_Array_To_Pointer) 1486 FromType1 = Context.getArrayDecayedType(FromType1); 1487 if (SCS2.First == ICK_Array_To_Pointer) 1488 FromType2 = Context.getArrayDecayedType(FromType2); 1489 1490 // Canonicalize all of the types. 1491 FromType1 = Context.getCanonicalType(FromType1); 1492 ToType1 = Context.getCanonicalType(ToType1); 1493 FromType2 = Context.getCanonicalType(FromType2); 1494 ToType2 = Context.getCanonicalType(ToType2); 1495 1496 // C++ [over.ics.rank]p4b3: 1497 // 1498 // If class B is derived directly or indirectly from class A and 1499 // class C is derived directly or indirectly from B, 1500 // 1501 // For Objective-C, we let A, B, and C also be Objective-C 1502 // interfaces. 1503 1504 // Compare based on pointer conversions. 1505 if (SCS1.Second == ICK_Pointer_Conversion && 1506 SCS2.Second == ICK_Pointer_Conversion && 1507 /*FIXME: Remove if Objective-C id conversions get their own rank*/ 1508 FromType1->isPointerType() && FromType2->isPointerType() && 1509 ToType1->isPointerType() && ToType2->isPointerType()) { 1510 QualType FromPointee1 1511 = FromType1->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1512 QualType ToPointee1 1513 = ToType1->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1514 QualType FromPointee2 1515 = FromType2->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1516 QualType ToPointee2 1517 = ToType2->getAsPointerType()->getPointeeType().getUnqualifiedType(); 1518 1519 const ObjCInterfaceType* FromIface1 = FromPointee1->getAsObjCInterfaceType(); 1520 const ObjCInterfaceType* FromIface2 = FromPointee2->getAsObjCInterfaceType(); 1521 const ObjCInterfaceType* ToIface1 = ToPointee1->getAsObjCInterfaceType(); 1522 const ObjCInterfaceType* ToIface2 = ToPointee2->getAsObjCInterfaceType(); 1523 1524 // -- conversion of C* to B* is better than conversion of C* to A*, 1525 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) { 1526 if (IsDerivedFrom(ToPointee1, ToPointee2)) 1527 return ImplicitConversionSequence::Better; 1528 else if (IsDerivedFrom(ToPointee2, ToPointee1)) 1529 return ImplicitConversionSequence::Worse; 1530 1531 if (ToIface1 && ToIface2) { 1532 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1)) 1533 return ImplicitConversionSequence::Better; 1534 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2)) 1535 return ImplicitConversionSequence::Worse; 1536 } 1537 } 1538 1539 // -- conversion of B* to A* is better than conversion of C* to A*, 1540 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) { 1541 if (IsDerivedFrom(FromPointee2, FromPointee1)) 1542 return ImplicitConversionSequence::Better; 1543 else if (IsDerivedFrom(FromPointee1, FromPointee2)) 1544 return ImplicitConversionSequence::Worse; 1545 1546 if (FromIface1 && FromIface2) { 1547 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2)) 1548 return ImplicitConversionSequence::Better; 1549 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1)) 1550 return ImplicitConversionSequence::Worse; 1551 } 1552 } 1553 } 1554 1555 // Compare based on reference bindings. 1556 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding && 1557 SCS1.Second == ICK_Derived_To_Base) { 1558 // -- binding of an expression of type C to a reference of type 1559 // B& is better than binding an expression of type C to a 1560 // reference of type A&, 1561 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() && 1562 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) { 1563 if (IsDerivedFrom(ToType1, ToType2)) 1564 return ImplicitConversionSequence::Better; 1565 else if (IsDerivedFrom(ToType2, ToType1)) 1566 return ImplicitConversionSequence::Worse; 1567 } 1568 1569 // -- binding of an expression of type B to a reference of type 1570 // A& is better than binding an expression of type C to a 1571 // reference of type A&, 1572 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() && 1573 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) { 1574 if (IsDerivedFrom(FromType2, FromType1)) 1575 return ImplicitConversionSequence::Better; 1576 else if (IsDerivedFrom(FromType1, FromType2)) 1577 return ImplicitConversionSequence::Worse; 1578 } 1579 } 1580 1581 1582 // FIXME: conversion of A::* to B::* is better than conversion of 1583 // A::* to C::*, 1584 1585 // FIXME: conversion of B::* to C::* is better than conversion of 1586 // A::* to C::*, and 1587 1588 if (SCS1.CopyConstructor && SCS2.CopyConstructor && 1589 SCS1.Second == ICK_Derived_To_Base) { 1590 // -- conversion of C to B is better than conversion of C to A, 1591 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() && 1592 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) { 1593 if (IsDerivedFrom(ToType1, ToType2)) 1594 return ImplicitConversionSequence::Better; 1595 else if (IsDerivedFrom(ToType2, ToType1)) 1596 return ImplicitConversionSequence::Worse; 1597 } 1598 1599 // -- conversion of B to A is better than conversion of C to A. 1600 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() && 1601 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) { 1602 if (IsDerivedFrom(FromType2, FromType1)) 1603 return ImplicitConversionSequence::Better; 1604 else if (IsDerivedFrom(FromType1, FromType2)) 1605 return ImplicitConversionSequence::Worse; 1606 } 1607 } 1608 1609 return ImplicitConversionSequence::Indistinguishable; 1610} 1611 1612/// TryCopyInitialization - Try to copy-initialize a value of type 1613/// ToType from the expression From. Return the implicit conversion 1614/// sequence required to pass this argument, which may be a bad 1615/// conversion sequence (meaning that the argument cannot be passed to 1616/// a parameter of this type). If @p SuppressUserConversions, then we 1617/// do not permit any user-defined conversion sequences. 1618ImplicitConversionSequence 1619Sema::TryCopyInitialization(Expr *From, QualType ToType, 1620 bool SuppressUserConversions) { 1621 if (!getLangOptions().CPlusPlus) { 1622 // In C, copy initialization is the same as performing an assignment. 1623 AssignConvertType ConvTy = 1624 CheckSingleAssignmentConstraints(ToType, From); 1625 ImplicitConversionSequence ICS; 1626 if (getLangOptions().NoExtensions? ConvTy != Compatible 1627 : ConvTy == Incompatible) 1628 ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 1629 else 1630 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion; 1631 return ICS; 1632 } else if (ToType->isReferenceType()) { 1633 ImplicitConversionSequence ICS; 1634 CheckReferenceInit(From, ToType, &ICS, SuppressUserConversions); 1635 return ICS; 1636 } else { 1637 return TryImplicitConversion(From, ToType, SuppressUserConversions); 1638 } 1639} 1640 1641/// PerformArgumentPassing - Pass the argument Arg into a parameter of 1642/// type ToType. Returns true (and emits a diagnostic) if there was 1643/// an error, returns false if the initialization succeeded. 1644bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType, 1645 const char* Flavor) { 1646 if (!getLangOptions().CPlusPlus) { 1647 // In C, argument passing is the same as performing an assignment. 1648 QualType FromType = From->getType(); 1649 AssignConvertType ConvTy = 1650 CheckSingleAssignmentConstraints(ToType, From); 1651 1652 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType, 1653 FromType, From, Flavor); 1654 } 1655 1656 if (ToType->isReferenceType()) 1657 return CheckReferenceInit(From, ToType); 1658 1659 if (!PerformImplicitConversion(From, ToType, Flavor)) 1660 return false; 1661 1662 return Diag(From->getSourceRange().getBegin(), 1663 diag::err_typecheck_convert_incompatible) 1664 << ToType << From->getType() << Flavor << From->getSourceRange(); 1665} 1666 1667/// TryObjectArgumentInitialization - Try to initialize the object 1668/// parameter of the given member function (@c Method) from the 1669/// expression @p From. 1670ImplicitConversionSequence 1671Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) { 1672 QualType ClassType = Context.getTypeDeclType(Method->getParent()); 1673 unsigned MethodQuals = Method->getTypeQualifiers(); 1674 QualType ImplicitParamType = ClassType.getQualifiedType(MethodQuals); 1675 1676 // Set up the conversion sequence as a "bad" conversion, to allow us 1677 // to exit early. 1678 ImplicitConversionSequence ICS; 1679 ICS.Standard.setAsIdentityConversion(); 1680 ICS.ConversionKind = ImplicitConversionSequence::BadConversion; 1681 1682 // We need to have an object of class type. 1683 QualType FromType = From->getType(); 1684 if (!FromType->isRecordType()) 1685 return ICS; 1686 1687 // The implicit object parmeter is has the type "reference to cv X", 1688 // where X is the class of which the function is a member 1689 // (C++ [over.match.funcs]p4). However, when finding an implicit 1690 // conversion sequence for the argument, we are not allowed to 1691 // create temporaries or perform user-defined conversions 1692 // (C++ [over.match.funcs]p5). We perform a simplified version of 1693 // reference binding here, that allows class rvalues to bind to 1694 // non-constant references. 1695 1696 // First check the qualifiers. We don't care about lvalue-vs-rvalue 1697 // with the implicit object parameter (C++ [over.match.funcs]p5). 1698 QualType FromTypeCanon = Context.getCanonicalType(FromType); 1699 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() && 1700 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType)) 1701 return ICS; 1702 1703 // Check that we have either the same type or a derived type. It 1704 // affects the conversion rank. 1705 QualType ClassTypeCanon = Context.getCanonicalType(ClassType); 1706 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType()) 1707 ICS.Standard.Second = ICK_Identity; 1708 else if (IsDerivedFrom(FromType, ClassType)) 1709 ICS.Standard.Second = ICK_Derived_To_Base; 1710 else 1711 return ICS; 1712 1713 // Success. Mark this as a reference binding. 1714 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion; 1715 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr(); 1716 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr(); 1717 ICS.Standard.ReferenceBinding = true; 1718 ICS.Standard.DirectBinding = true; 1719 return ICS; 1720} 1721 1722/// PerformObjectArgumentInitialization - Perform initialization of 1723/// the implicit object parameter for the given Method with the given 1724/// expression. 1725bool 1726Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) { 1727 QualType ImplicitParamType 1728 = Method->getThisType(Context)->getAsPointerType()->getPointeeType(); 1729 ImplicitConversionSequence ICS 1730 = TryObjectArgumentInitialization(From, Method); 1731 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion) 1732 return Diag(From->getSourceRange().getBegin(), 1733 diag::err_implicit_object_parameter_init) 1734 << ImplicitParamType << From->getType() << From->getSourceRange(); 1735 1736 if (ICS.Standard.Second == ICK_Derived_To_Base && 1737 CheckDerivedToBaseConversion(From->getType(), ImplicitParamType, 1738 From->getSourceRange().getBegin(), 1739 From->getSourceRange())) 1740 return true; 1741 1742 ImpCastExprToType(From, ImplicitParamType, /*isLvalue=*/true); 1743 return false; 1744} 1745 1746/// AddOverloadCandidate - Adds the given function to the set of 1747/// candidate functions, using the given function call arguments. If 1748/// @p SuppressUserConversions, then don't allow user-defined 1749/// conversions via constructors or conversion operators. 1750void 1751Sema::AddOverloadCandidate(FunctionDecl *Function, 1752 Expr **Args, unsigned NumArgs, 1753 OverloadCandidateSet& CandidateSet, 1754 bool SuppressUserConversions) 1755{ 1756 const FunctionTypeProto* Proto 1757 = dyn_cast<FunctionTypeProto>(Function->getType()->getAsFunctionType()); 1758 assert(Proto && "Functions without a prototype cannot be overloaded"); 1759 assert(!isa<CXXConversionDecl>(Function) && 1760 "Use AddConversionCandidate for conversion functions"); 1761 1762 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) { 1763 // If we get here, it's because we're calling a member function 1764 // that is named without a member access expression (e.g., 1765 // "this->f") that was either written explicitly or created 1766 // implicitly. This can happen with a qualified call to a member 1767 // function, e.g., X::f(). We use a NULL object as the implied 1768 // object argument (C++ [over.call.func]p3). 1769 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet, 1770 SuppressUserConversions); 1771 return; 1772 } 1773 1774 1775 // Add this candidate 1776 CandidateSet.push_back(OverloadCandidate()); 1777 OverloadCandidate& Candidate = CandidateSet.back(); 1778 Candidate.Function = Function; 1779 Candidate.Viable = true; 1780 Candidate.IsSurrogate = false; 1781 Candidate.IgnoreObjectArgument = false; 1782 1783 unsigned NumArgsInProto = Proto->getNumArgs(); 1784 1785 // (C++ 13.3.2p2): A candidate function having fewer than m 1786 // parameters is viable only if it has an ellipsis in its parameter 1787 // list (8.3.5). 1788 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 1789 Candidate.Viable = false; 1790 return; 1791 } 1792 1793 // (C++ 13.3.2p2): A candidate function having more than m parameters 1794 // is viable only if the (m+1)st parameter has a default argument 1795 // (8.3.6). For the purposes of overload resolution, the 1796 // parameter list is truncated on the right, so that there are 1797 // exactly m parameters. 1798 unsigned MinRequiredArgs = Function->getMinRequiredArguments(); 1799 if (NumArgs < MinRequiredArgs) { 1800 // Not enough arguments. 1801 Candidate.Viable = false; 1802 return; 1803 } 1804 1805 // Determine the implicit conversion sequences for each of the 1806 // arguments. 1807 Candidate.Conversions.resize(NumArgs); 1808 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 1809 if (ArgIdx < NumArgsInProto) { 1810 // (C++ 13.3.2p3): for F to be a viable function, there shall 1811 // exist for each argument an implicit conversion sequence 1812 // (13.3.3.1) that converts that argument to the corresponding 1813 // parameter of F. 1814 QualType ParamType = Proto->getArgType(ArgIdx); 1815 Candidate.Conversions[ArgIdx] 1816 = TryCopyInitialization(Args[ArgIdx], ParamType, 1817 SuppressUserConversions); 1818 if (Candidate.Conversions[ArgIdx].ConversionKind 1819 == ImplicitConversionSequence::BadConversion) { 1820 Candidate.Viable = false; 1821 break; 1822 } 1823 } else { 1824 // (C++ 13.3.2p2): For the purposes of overload resolution, any 1825 // argument for which there is no corresponding parameter is 1826 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 1827 Candidate.Conversions[ArgIdx].ConversionKind 1828 = ImplicitConversionSequence::EllipsisConversion; 1829 } 1830 } 1831} 1832 1833/// AddMethodCandidate - Adds the given C++ member function to the set 1834/// of candidate functions, using the given function call arguments 1835/// and the object argument (@c Object). For example, in a call 1836/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain 1837/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't 1838/// allow user-defined conversions via constructors or conversion 1839/// operators. 1840void 1841Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object, 1842 Expr **Args, unsigned NumArgs, 1843 OverloadCandidateSet& CandidateSet, 1844 bool SuppressUserConversions) 1845{ 1846 const FunctionTypeProto* Proto 1847 = dyn_cast<FunctionTypeProto>(Method->getType()->getAsFunctionType()); 1848 assert(Proto && "Methods without a prototype cannot be overloaded"); 1849 assert(!isa<CXXConversionDecl>(Method) && 1850 "Use AddConversionCandidate for conversion functions"); 1851 1852 // Add this candidate 1853 CandidateSet.push_back(OverloadCandidate()); 1854 OverloadCandidate& Candidate = CandidateSet.back(); 1855 Candidate.Function = Method; 1856 Candidate.IsSurrogate = false; 1857 Candidate.IgnoreObjectArgument = false; 1858 1859 unsigned NumArgsInProto = Proto->getNumArgs(); 1860 1861 // (C++ 13.3.2p2): A candidate function having fewer than m 1862 // parameters is viable only if it has an ellipsis in its parameter 1863 // list (8.3.5). 1864 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 1865 Candidate.Viable = false; 1866 return; 1867 } 1868 1869 // (C++ 13.3.2p2): A candidate function having more than m parameters 1870 // is viable only if the (m+1)st parameter has a default argument 1871 // (8.3.6). For the purposes of overload resolution, the 1872 // parameter list is truncated on the right, so that there are 1873 // exactly m parameters. 1874 unsigned MinRequiredArgs = Method->getMinRequiredArguments(); 1875 if (NumArgs < MinRequiredArgs) { 1876 // Not enough arguments. 1877 Candidate.Viable = false; 1878 return; 1879 } 1880 1881 Candidate.Viable = true; 1882 Candidate.Conversions.resize(NumArgs + 1); 1883 1884 if (Method->isStatic() || !Object) 1885 // The implicit object argument is ignored. 1886 Candidate.IgnoreObjectArgument = true; 1887 else { 1888 // Determine the implicit conversion sequence for the object 1889 // parameter. 1890 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method); 1891 if (Candidate.Conversions[0].ConversionKind 1892 == ImplicitConversionSequence::BadConversion) { 1893 Candidate.Viable = false; 1894 return; 1895 } 1896 } 1897 1898 // Determine the implicit conversion sequences for each of the 1899 // arguments. 1900 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 1901 if (ArgIdx < NumArgsInProto) { 1902 // (C++ 13.3.2p3): for F to be a viable function, there shall 1903 // exist for each argument an implicit conversion sequence 1904 // (13.3.3.1) that converts that argument to the corresponding 1905 // parameter of F. 1906 QualType ParamType = Proto->getArgType(ArgIdx); 1907 Candidate.Conversions[ArgIdx + 1] 1908 = TryCopyInitialization(Args[ArgIdx], ParamType, 1909 SuppressUserConversions); 1910 if (Candidate.Conversions[ArgIdx + 1].ConversionKind 1911 == ImplicitConversionSequence::BadConversion) { 1912 Candidate.Viable = false; 1913 break; 1914 } 1915 } else { 1916 // (C++ 13.3.2p2): For the purposes of overload resolution, any 1917 // argument for which there is no corresponding parameter is 1918 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 1919 Candidate.Conversions[ArgIdx + 1].ConversionKind 1920 = ImplicitConversionSequence::EllipsisConversion; 1921 } 1922 } 1923} 1924 1925/// AddConversionCandidate - Add a C++ conversion function as a 1926/// candidate in the candidate set (C++ [over.match.conv], 1927/// C++ [over.match.copy]). From is the expression we're converting from, 1928/// and ToType is the type that we're eventually trying to convert to 1929/// (which may or may not be the same type as the type that the 1930/// conversion function produces). 1931void 1932Sema::AddConversionCandidate(CXXConversionDecl *Conversion, 1933 Expr *From, QualType ToType, 1934 OverloadCandidateSet& CandidateSet) { 1935 // Add this candidate 1936 CandidateSet.push_back(OverloadCandidate()); 1937 OverloadCandidate& Candidate = CandidateSet.back(); 1938 Candidate.Function = Conversion; 1939 Candidate.IsSurrogate = false; 1940 Candidate.IgnoreObjectArgument = false; 1941 Candidate.FinalConversion.setAsIdentityConversion(); 1942 Candidate.FinalConversion.FromTypePtr 1943 = Conversion->getConversionType().getAsOpaquePtr(); 1944 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr(); 1945 1946 // Determine the implicit conversion sequence for the implicit 1947 // object parameter. 1948 Candidate.Viable = true; 1949 Candidate.Conversions.resize(1); 1950 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion); 1951 1952 if (Candidate.Conversions[0].ConversionKind 1953 == ImplicitConversionSequence::BadConversion) { 1954 Candidate.Viable = false; 1955 return; 1956 } 1957 1958 // To determine what the conversion from the result of calling the 1959 // conversion function to the type we're eventually trying to 1960 // convert to (ToType), we need to synthesize a call to the 1961 // conversion function and attempt copy initialization from it. This 1962 // makes sure that we get the right semantics with respect to 1963 // lvalues/rvalues and the type. Fortunately, we can allocate this 1964 // call on the stack and we don't need its arguments to be 1965 // well-formed. 1966 DeclRefExpr ConversionRef(Conversion, Conversion->getType(), 1967 SourceLocation()); 1968 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()), 1969 &ConversionRef, false); 1970 CallExpr Call(&ConversionFn, 0, 0, 1971 Conversion->getConversionType().getNonReferenceType(), 1972 SourceLocation()); 1973 ImplicitConversionSequence ICS = TryCopyInitialization(&Call, ToType, true); 1974 switch (ICS.ConversionKind) { 1975 case ImplicitConversionSequence::StandardConversion: 1976 Candidate.FinalConversion = ICS.Standard; 1977 break; 1978 1979 case ImplicitConversionSequence::BadConversion: 1980 Candidate.Viable = false; 1981 break; 1982 1983 default: 1984 assert(false && 1985 "Can only end up with a standard conversion sequence or failure"); 1986 } 1987} 1988 1989/// AddSurrogateCandidate - Adds a "surrogate" candidate function that 1990/// converts the given @c Object to a function pointer via the 1991/// conversion function @c Conversion, and then attempts to call it 1992/// with the given arguments (C++ [over.call.object]p2-4). Proto is 1993/// the type of function that we'll eventually be calling. 1994void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion, 1995 const FunctionTypeProto *Proto, 1996 Expr *Object, Expr **Args, unsigned NumArgs, 1997 OverloadCandidateSet& CandidateSet) { 1998 CandidateSet.push_back(OverloadCandidate()); 1999 OverloadCandidate& Candidate = CandidateSet.back(); 2000 Candidate.Function = 0; 2001 Candidate.Surrogate = Conversion; 2002 Candidate.Viable = true; 2003 Candidate.IsSurrogate = true; 2004 Candidate.IgnoreObjectArgument = false; 2005 Candidate.Conversions.resize(NumArgs + 1); 2006 2007 // Determine the implicit conversion sequence for the implicit 2008 // object parameter. 2009 ImplicitConversionSequence ObjectInit 2010 = TryObjectArgumentInitialization(Object, Conversion); 2011 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) { 2012 Candidate.Viable = false; 2013 return; 2014 } 2015 2016 // The first conversion is actually a user-defined conversion whose 2017 // first conversion is ObjectInit's standard conversion (which is 2018 // effectively a reference binding). Record it as such. 2019 Candidate.Conversions[0].ConversionKind 2020 = ImplicitConversionSequence::UserDefinedConversion; 2021 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard; 2022 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion; 2023 Candidate.Conversions[0].UserDefined.After 2024 = Candidate.Conversions[0].UserDefined.Before; 2025 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion(); 2026 2027 // Find the 2028 unsigned NumArgsInProto = Proto->getNumArgs(); 2029 2030 // (C++ 13.3.2p2): A candidate function having fewer than m 2031 // parameters is viable only if it has an ellipsis in its parameter 2032 // list (8.3.5). 2033 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) { 2034 Candidate.Viable = false; 2035 return; 2036 } 2037 2038 // Function types don't have any default arguments, so just check if 2039 // we have enough arguments. 2040 if (NumArgs < NumArgsInProto) { 2041 // Not enough arguments. 2042 Candidate.Viable = false; 2043 return; 2044 } 2045 2046 // Determine the implicit conversion sequences for each of the 2047 // arguments. 2048 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 2049 if (ArgIdx < NumArgsInProto) { 2050 // (C++ 13.3.2p3): for F to be a viable function, there shall 2051 // exist for each argument an implicit conversion sequence 2052 // (13.3.3.1) that converts that argument to the corresponding 2053 // parameter of F. 2054 QualType ParamType = Proto->getArgType(ArgIdx); 2055 Candidate.Conversions[ArgIdx + 1] 2056 = TryCopyInitialization(Args[ArgIdx], ParamType, 2057 /*SuppressUserConversions=*/false); 2058 if (Candidate.Conversions[ArgIdx + 1].ConversionKind 2059 == ImplicitConversionSequence::BadConversion) { 2060 Candidate.Viable = false; 2061 break; 2062 } 2063 } else { 2064 // (C++ 13.3.2p2): For the purposes of overload resolution, any 2065 // argument for which there is no corresponding parameter is 2066 // considered to ""match the ellipsis" (C+ 13.3.3.1.3). 2067 Candidate.Conversions[ArgIdx + 1].ConversionKind 2068 = ImplicitConversionSequence::EllipsisConversion; 2069 } 2070 } 2071} 2072 2073/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is 2074/// an acceptable non-member overloaded operator for a call whose 2075/// arguments have types T1 (and, if non-empty, T2). This routine 2076/// implements the check in C++ [over.match.oper]p3b2 concerning 2077/// enumeration types. 2078static bool 2079IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn, 2080 QualType T1, QualType T2, 2081 ASTContext &Context) { 2082 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType())) 2083 return true; 2084 2085 const FunctionTypeProto *Proto = Fn->getType()->getAsFunctionTypeProto(); 2086 if (Proto->getNumArgs() < 1) 2087 return false; 2088 2089 if (T1->isEnumeralType()) { 2090 QualType ArgType = Proto->getArgType(0).getNonReferenceType(); 2091 if (Context.getCanonicalType(T1).getUnqualifiedType() 2092 == Context.getCanonicalType(ArgType).getUnqualifiedType()) 2093 return true; 2094 } 2095 2096 if (Proto->getNumArgs() < 2) 2097 return false; 2098 2099 if (!T2.isNull() && T2->isEnumeralType()) { 2100 QualType ArgType = Proto->getArgType(1).getNonReferenceType(); 2101 if (Context.getCanonicalType(T2).getUnqualifiedType() 2102 == Context.getCanonicalType(ArgType).getUnqualifiedType()) 2103 return true; 2104 } 2105 2106 return false; 2107} 2108 2109/// AddOperatorCandidates - Add the overloaded operator candidates for 2110/// the operator Op that was used in an operator expression such as "x 2111/// Op y". S is the scope in which the expression occurred (used for 2112/// name lookup of the operator), Args/NumArgs provides the operator 2113/// arguments, and CandidateSet will store the added overload 2114/// candidates. (C++ [over.match.oper]). 2115void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S, 2116 Expr **Args, unsigned NumArgs, 2117 OverloadCandidateSet& CandidateSet) { 2118 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); 2119 2120 // C++ [over.match.oper]p3: 2121 // For a unary operator @ with an operand of a type whose 2122 // cv-unqualified version is T1, and for a binary operator @ with 2123 // a left operand of a type whose cv-unqualified version is T1 and 2124 // a right operand of a type whose cv-unqualified version is T2, 2125 // three sets of candidate functions, designated member 2126 // candidates, non-member candidates and built-in candidates, are 2127 // constructed as follows: 2128 QualType T1 = Args[0]->getType(); 2129 QualType T2; 2130 if (NumArgs > 1) 2131 T2 = Args[1]->getType(); 2132 2133 // -- If T1 is a class type, the set of member candidates is the 2134 // result of the qualified lookup of T1::operator@ 2135 // (13.3.1.1.1); otherwise, the set of member candidates is 2136 // empty. 2137 if (const RecordType *T1Rec = T1->getAsRecordType()) { 2138 DeclContext::lookup_const_result Lookup 2139 = T1Rec->getDecl()->lookup(Context, OpName); 2140 NamedDecl *MemberOps = (Lookup.first == Lookup.second)? 0 : *Lookup.first; 2141 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps)) 2142 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet, 2143 /*SuppressUserConversions=*/false); 2144 else if (OverloadedFunctionDecl *Ovl 2145 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) { 2146 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(), 2147 FEnd = Ovl->function_end(); 2148 F != FEnd; ++F) { 2149 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F)) 2150 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet, 2151 /*SuppressUserConversions=*/false); 2152 } 2153 } 2154 } 2155 2156 // -- The set of non-member candidates is the result of the 2157 // unqualified lookup of operator@ in the context of the 2158 // expression according to the usual rules for name lookup in 2159 // unqualified function calls (3.4.2) except that all member 2160 // functions are ignored. However, if no operand has a class 2161 // type, only those non-member functions in the lookup set 2162 // that have a first parameter of type T1 or “reference to 2163 // (possibly cv-qualified) T1”, when T1 is an enumeration 2164 // type, or (if there is a right operand) a second parameter 2165 // of type T2 or “reference to (possibly cv-qualified) T2”, 2166 // when T2 is an enumeration type, are candidate functions. 2167 { 2168 NamedDecl *NonMemberOps = 0; 2169 for (IdentifierResolver::iterator I 2170 = IdResolver.begin(OpName, CurContext, true/*LookInParentCtx*/); 2171 I != IdResolver.end(); ++I) { 2172 // We don't need to check the identifier namespace, because 2173 // operator names can only be ordinary identifiers. 2174 2175 // Ignore member functions. 2176 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(*I)) { 2177 if (SD->getDeclContext()->isCXXRecord()) 2178 continue; 2179 } 2180 2181 // We found something with this name. We're done. 2182 NonMemberOps = *I; 2183 break; 2184 } 2185 2186 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(NonMemberOps)) { 2187 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context)) 2188 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet, 2189 /*SuppressUserConversions=*/false); 2190 } else if (OverloadedFunctionDecl *Ovl 2191 = dyn_cast_or_null<OverloadedFunctionDecl>(NonMemberOps)) { 2192 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(), 2193 FEnd = Ovl->function_end(); 2194 F != FEnd; ++F) { 2195 if (IsAcceptableNonMemberOperatorCandidate(*F, T1, T2, Context)) 2196 AddOverloadCandidate(*F, Args, NumArgs, CandidateSet, 2197 /*SuppressUserConversions=*/false); 2198 } 2199 } 2200 } 2201 2202 // Add builtin overload candidates (C++ [over.built]). 2203 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet); 2204} 2205 2206/// AddBuiltinCandidate - Add a candidate for a built-in 2207/// operator. ResultTy and ParamTys are the result and parameter types 2208/// of the built-in candidate, respectively. Args and NumArgs are the 2209/// arguments being passed to the candidate. 2210void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys, 2211 Expr **Args, unsigned NumArgs, 2212 OverloadCandidateSet& CandidateSet) { 2213 // Add this candidate 2214 CandidateSet.push_back(OverloadCandidate()); 2215 OverloadCandidate& Candidate = CandidateSet.back(); 2216 Candidate.Function = 0; 2217 Candidate.IsSurrogate = false; 2218 Candidate.IgnoreObjectArgument = false; 2219 Candidate.BuiltinTypes.ResultTy = ResultTy; 2220 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 2221 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx]; 2222 2223 // Determine the implicit conversion sequences for each of the 2224 // arguments. 2225 Candidate.Viable = true; 2226 Candidate.Conversions.resize(NumArgs); 2227 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) { 2228 Candidate.Conversions[ArgIdx] 2229 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx], false); 2230 if (Candidate.Conversions[ArgIdx].ConversionKind 2231 == ImplicitConversionSequence::BadConversion) { 2232 Candidate.Viable = false; 2233 break; 2234 } 2235 } 2236} 2237 2238/// BuiltinCandidateTypeSet - A set of types that will be used for the 2239/// candidate operator functions for built-in operators (C++ 2240/// [over.built]). The types are separated into pointer types and 2241/// enumeration types. 2242class BuiltinCandidateTypeSet { 2243 /// TypeSet - A set of types. 2244 typedef llvm::SmallPtrSet<void*, 8> TypeSet; 2245 2246 /// PointerTypes - The set of pointer types that will be used in the 2247 /// built-in candidates. 2248 TypeSet PointerTypes; 2249 2250 /// EnumerationTypes - The set of enumeration types that will be 2251 /// used in the built-in candidates. 2252 TypeSet EnumerationTypes; 2253 2254 /// Context - The AST context in which we will build the type sets. 2255 ASTContext &Context; 2256 2257 bool AddWithMoreQualifiedTypeVariants(QualType Ty); 2258 2259public: 2260 /// iterator - Iterates through the types that are part of the set. 2261 class iterator { 2262 TypeSet::iterator Base; 2263 2264 public: 2265 typedef QualType value_type; 2266 typedef QualType reference; 2267 typedef QualType pointer; 2268 typedef std::ptrdiff_t difference_type; 2269 typedef std::input_iterator_tag iterator_category; 2270 2271 iterator(TypeSet::iterator B) : Base(B) { } 2272 2273 iterator& operator++() { 2274 ++Base; 2275 return *this; 2276 } 2277 2278 iterator operator++(int) { 2279 iterator tmp(*this); 2280 ++(*this); 2281 return tmp; 2282 } 2283 2284 reference operator*() const { 2285 return QualType::getFromOpaquePtr(*Base); 2286 } 2287 2288 pointer operator->() const { 2289 return **this; 2290 } 2291 2292 friend bool operator==(iterator LHS, iterator RHS) { 2293 return LHS.Base == RHS.Base; 2294 } 2295 2296 friend bool operator!=(iterator LHS, iterator RHS) { 2297 return LHS.Base != RHS.Base; 2298 } 2299 }; 2300 2301 BuiltinCandidateTypeSet(ASTContext &Context) : Context(Context) { } 2302 2303 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions = true); 2304 2305 /// pointer_begin - First pointer type found; 2306 iterator pointer_begin() { return PointerTypes.begin(); } 2307 2308 /// pointer_end - Last pointer type found; 2309 iterator pointer_end() { return PointerTypes.end(); } 2310 2311 /// enumeration_begin - First enumeration type found; 2312 iterator enumeration_begin() { return EnumerationTypes.begin(); } 2313 2314 /// enumeration_end - Last enumeration type found; 2315 iterator enumeration_end() { return EnumerationTypes.end(); } 2316}; 2317 2318/// AddWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to 2319/// the set of pointer types along with any more-qualified variants of 2320/// that type. For example, if @p Ty is "int const *", this routine 2321/// will add "int const *", "int const volatile *", "int const 2322/// restrict *", and "int const volatile restrict *" to the set of 2323/// pointer types. Returns true if the add of @p Ty itself succeeded, 2324/// false otherwise. 2325bool BuiltinCandidateTypeSet::AddWithMoreQualifiedTypeVariants(QualType Ty) { 2326 // Insert this type. 2327 if (!PointerTypes.insert(Ty.getAsOpaquePtr())) 2328 return false; 2329 2330 if (const PointerType *PointerTy = Ty->getAsPointerType()) { 2331 QualType PointeeTy = PointerTy->getPointeeType(); 2332 // FIXME: Optimize this so that we don't keep trying to add the same types. 2333 2334 // FIXME: Do we have to add CVR qualifiers at *all* levels to deal 2335 // with all pointer conversions that don't cast away constness? 2336 if (!PointeeTy.isConstQualified()) 2337 AddWithMoreQualifiedTypeVariants 2338 (Context.getPointerType(PointeeTy.withConst())); 2339 if (!PointeeTy.isVolatileQualified()) 2340 AddWithMoreQualifiedTypeVariants 2341 (Context.getPointerType(PointeeTy.withVolatile())); 2342 if (!PointeeTy.isRestrictQualified()) 2343 AddWithMoreQualifiedTypeVariants 2344 (Context.getPointerType(PointeeTy.withRestrict())); 2345 } 2346 2347 return true; 2348} 2349 2350/// AddTypesConvertedFrom - Add each of the types to which the type @p 2351/// Ty can be implicit converted to the given set of @p Types. We're 2352/// primarily interested in pointer types, enumeration types, 2353void BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty, 2354 bool AllowUserConversions) { 2355 // Only deal with canonical types. 2356 Ty = Context.getCanonicalType(Ty); 2357 2358 // Look through reference types; they aren't part of the type of an 2359 // expression for the purposes of conversions. 2360 if (const ReferenceType *RefTy = Ty->getAsReferenceType()) 2361 Ty = RefTy->getPointeeType(); 2362 2363 // We don't care about qualifiers on the type. 2364 Ty = Ty.getUnqualifiedType(); 2365 2366 if (const PointerType *PointerTy = Ty->getAsPointerType()) { 2367 QualType PointeeTy = PointerTy->getPointeeType(); 2368 2369 // Insert our type, and its more-qualified variants, into the set 2370 // of types. 2371 if (!AddWithMoreQualifiedTypeVariants(Ty)) 2372 return; 2373 2374 // Add 'cv void*' to our set of types. 2375 if (!Ty->isVoidType()) { 2376 QualType QualVoid 2377 = Context.VoidTy.getQualifiedType(PointeeTy.getCVRQualifiers()); 2378 AddWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid)); 2379 } 2380 2381 // If this is a pointer to a class type, add pointers to its bases 2382 // (with the same level of cv-qualification as the original 2383 // derived class, of course). 2384 if (const RecordType *PointeeRec = PointeeTy->getAsRecordType()) { 2385 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl()); 2386 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin(); 2387 Base != ClassDecl->bases_end(); ++Base) { 2388 QualType BaseTy = Context.getCanonicalType(Base->getType()); 2389 BaseTy = BaseTy.getQualifiedType(PointeeTy.getCVRQualifiers()); 2390 2391 // Add the pointer type, recursively, so that we get all of 2392 // the indirect base classes, too. 2393 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false); 2394 } 2395 } 2396 } else if (Ty->isEnumeralType()) { 2397 EnumerationTypes.insert(Ty.getAsOpaquePtr()); 2398 } else if (AllowUserConversions) { 2399 if (const RecordType *TyRec = Ty->getAsRecordType()) { 2400 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl()); 2401 // FIXME: Visit conversion functions in the base classes, too. 2402 OverloadedFunctionDecl *Conversions 2403 = ClassDecl->getConversionFunctions(); 2404 for (OverloadedFunctionDecl::function_iterator Func 2405 = Conversions->function_begin(); 2406 Func != Conversions->function_end(); ++Func) { 2407 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func); 2408 AddTypesConvertedFrom(Conv->getConversionType(), false); 2409 } 2410 } 2411 } 2412} 2413 2414/// AddBuiltinOperatorCandidates - Add the appropriate built-in 2415/// operator overloads to the candidate set (C++ [over.built]), based 2416/// on the operator @p Op and the arguments given. For example, if the 2417/// operator is a binary '+', this routine might add "int 2418/// operator+(int, int)" to cover integer addition. 2419void 2420Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, 2421 Expr **Args, unsigned NumArgs, 2422 OverloadCandidateSet& CandidateSet) { 2423 // The set of "promoted arithmetic types", which are the arithmetic 2424 // types are that preserved by promotion (C++ [over.built]p2). Note 2425 // that the first few of these types are the promoted integral 2426 // types; these types need to be first. 2427 // FIXME: What about complex? 2428 const unsigned FirstIntegralType = 0; 2429 const unsigned LastIntegralType = 13; 2430 const unsigned FirstPromotedIntegralType = 7, 2431 LastPromotedIntegralType = 13; 2432 const unsigned FirstPromotedArithmeticType = 7, 2433 LastPromotedArithmeticType = 16; 2434 const unsigned NumArithmeticTypes = 16; 2435 QualType ArithmeticTypes[NumArithmeticTypes] = { 2436 Context.BoolTy, Context.CharTy, Context.WCharTy, 2437 Context.SignedCharTy, Context.ShortTy, 2438 Context.UnsignedCharTy, Context.UnsignedShortTy, 2439 Context.IntTy, Context.LongTy, Context.LongLongTy, 2440 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy, 2441 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy 2442 }; 2443 2444 // Find all of the types that the arguments can convert to, but only 2445 // if the operator we're looking at has built-in operator candidates 2446 // that make use of these types. 2447 BuiltinCandidateTypeSet CandidateTypes(Context); 2448 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual || 2449 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual || 2450 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal || 2451 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript || 2452 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus || 2453 (Op == OO_Star && NumArgs == 1)) { 2454 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 2455 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType()); 2456 } 2457 2458 bool isComparison = false; 2459 switch (Op) { 2460 case OO_None: 2461 case NUM_OVERLOADED_OPERATORS: 2462 assert(false && "Expected an overloaded operator"); 2463 break; 2464 2465 case OO_Star: // '*' is either unary or binary 2466 if (NumArgs == 1) 2467 goto UnaryStar; 2468 else 2469 goto BinaryStar; 2470 break; 2471 2472 case OO_Plus: // '+' is either unary or binary 2473 if (NumArgs == 1) 2474 goto UnaryPlus; 2475 else 2476 goto BinaryPlus; 2477 break; 2478 2479 case OO_Minus: // '-' is either unary or binary 2480 if (NumArgs == 1) 2481 goto UnaryMinus; 2482 else 2483 goto BinaryMinus; 2484 break; 2485 2486 case OO_Amp: // '&' is either unary or binary 2487 if (NumArgs == 1) 2488 goto UnaryAmp; 2489 else 2490 goto BinaryAmp; 2491 2492 case OO_PlusPlus: 2493 case OO_MinusMinus: 2494 // C++ [over.built]p3: 2495 // 2496 // For every pair (T, VQ), where T is an arithmetic type, and VQ 2497 // is either volatile or empty, there exist candidate operator 2498 // functions of the form 2499 // 2500 // VQ T& operator++(VQ T&); 2501 // T operator++(VQ T&, int); 2502 // 2503 // C++ [over.built]p4: 2504 // 2505 // For every pair (T, VQ), where T is an arithmetic type other 2506 // than bool, and VQ is either volatile or empty, there exist 2507 // candidate operator functions of the form 2508 // 2509 // VQ T& operator--(VQ T&); 2510 // T operator--(VQ T&, int); 2511 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1); 2512 Arith < NumArithmeticTypes; ++Arith) { 2513 QualType ArithTy = ArithmeticTypes[Arith]; 2514 QualType ParamTypes[2] 2515 = { Context.getReferenceType(ArithTy), Context.IntTy }; 2516 2517 // Non-volatile version. 2518 if (NumArgs == 1) 2519 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 2520 else 2521 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet); 2522 2523 // Volatile version 2524 ParamTypes[0] = Context.getReferenceType(ArithTy.withVolatile()); 2525 if (NumArgs == 1) 2526 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 2527 else 2528 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet); 2529 } 2530 2531 // C++ [over.built]p5: 2532 // 2533 // For every pair (T, VQ), where T is a cv-qualified or 2534 // cv-unqualified object type, and VQ is either volatile or 2535 // empty, there exist candidate operator functions of the form 2536 // 2537 // T*VQ& operator++(T*VQ&); 2538 // T*VQ& operator--(T*VQ&); 2539 // T* operator++(T*VQ&, int); 2540 // T* operator--(T*VQ&, int); 2541 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2542 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2543 // Skip pointer types that aren't pointers to object types. 2544 if (!(*Ptr)->getAsPointerType()->getPointeeType()->isIncompleteOrObjectType()) 2545 continue; 2546 2547 QualType ParamTypes[2] = { 2548 Context.getReferenceType(*Ptr), Context.IntTy 2549 }; 2550 2551 // Without volatile 2552 if (NumArgs == 1) 2553 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 2554 else 2555 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 2556 2557 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) { 2558 // With volatile 2559 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile()); 2560 if (NumArgs == 1) 2561 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet); 2562 else 2563 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 2564 } 2565 } 2566 break; 2567 2568 UnaryStar: 2569 // C++ [over.built]p6: 2570 // For every cv-qualified or cv-unqualified object type T, there 2571 // exist candidate operator functions of the form 2572 // 2573 // T& operator*(T*); 2574 // 2575 // C++ [over.built]p7: 2576 // For every function type T, there exist candidate operator 2577 // functions of the form 2578 // T& operator*(T*); 2579 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2580 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2581 QualType ParamTy = *Ptr; 2582 QualType PointeeTy = ParamTy->getAsPointerType()->getPointeeType(); 2583 AddBuiltinCandidate(Context.getReferenceType(PointeeTy), 2584 &ParamTy, Args, 1, CandidateSet); 2585 } 2586 break; 2587 2588 UnaryPlus: 2589 // C++ [over.built]p8: 2590 // For every type T, there exist candidate operator functions of 2591 // the form 2592 // 2593 // T* operator+(T*); 2594 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2595 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2596 QualType ParamTy = *Ptr; 2597 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 2598 } 2599 2600 // Fall through 2601 2602 UnaryMinus: 2603 // C++ [over.built]p9: 2604 // For every promoted arithmetic type T, there exist candidate 2605 // operator functions of the form 2606 // 2607 // T operator+(T); 2608 // T operator-(T); 2609 for (unsigned Arith = FirstPromotedArithmeticType; 2610 Arith < LastPromotedArithmeticType; ++Arith) { 2611 QualType ArithTy = ArithmeticTypes[Arith]; 2612 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet); 2613 } 2614 break; 2615 2616 case OO_Tilde: 2617 // C++ [over.built]p10: 2618 // For every promoted integral type T, there exist candidate 2619 // operator functions of the form 2620 // 2621 // T operator~(T); 2622 for (unsigned Int = FirstPromotedIntegralType; 2623 Int < LastPromotedIntegralType; ++Int) { 2624 QualType IntTy = ArithmeticTypes[Int]; 2625 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet); 2626 } 2627 break; 2628 2629 case OO_New: 2630 case OO_Delete: 2631 case OO_Array_New: 2632 case OO_Array_Delete: 2633 case OO_Call: 2634 assert(false && "Special operators don't use AddBuiltinOperatorCandidates"); 2635 break; 2636 2637 case OO_Comma: 2638 UnaryAmp: 2639 case OO_Arrow: 2640 // C++ [over.match.oper]p3: 2641 // -- For the operator ',', the unary operator '&', or the 2642 // operator '->', the built-in candidates set is empty. 2643 break; 2644 2645 case OO_Less: 2646 case OO_Greater: 2647 case OO_LessEqual: 2648 case OO_GreaterEqual: 2649 case OO_EqualEqual: 2650 case OO_ExclaimEqual: 2651 // C++ [over.built]p15: 2652 // 2653 // For every pointer or enumeration type T, there exist 2654 // candidate operator functions of the form 2655 // 2656 // bool operator<(T, T); 2657 // bool operator>(T, T); 2658 // bool operator<=(T, T); 2659 // bool operator>=(T, T); 2660 // bool operator==(T, T); 2661 // bool operator!=(T, T); 2662 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2663 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2664 QualType ParamTypes[2] = { *Ptr, *Ptr }; 2665 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet); 2666 } 2667 for (BuiltinCandidateTypeSet::iterator Enum 2668 = CandidateTypes.enumeration_begin(); 2669 Enum != CandidateTypes.enumeration_end(); ++Enum) { 2670 QualType ParamTypes[2] = { *Enum, *Enum }; 2671 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet); 2672 } 2673 2674 // Fall through. 2675 isComparison = true; 2676 2677 BinaryPlus: 2678 BinaryMinus: 2679 if (!isComparison) { 2680 // We didn't fall through, so we must have OO_Plus or OO_Minus. 2681 2682 // C++ [over.built]p13: 2683 // 2684 // For every cv-qualified or cv-unqualified object type T 2685 // there exist candidate operator functions of the form 2686 // 2687 // T* operator+(T*, ptrdiff_t); 2688 // T& operator[](T*, ptrdiff_t); [BELOW] 2689 // T* operator-(T*, ptrdiff_t); 2690 // T* operator+(ptrdiff_t, T*); 2691 // T& operator[](ptrdiff_t, T*); [BELOW] 2692 // 2693 // C++ [over.built]p14: 2694 // 2695 // For every T, where T is a pointer to object type, there 2696 // exist candidate operator functions of the form 2697 // 2698 // ptrdiff_t operator-(T, T); 2699 for (BuiltinCandidateTypeSet::iterator Ptr 2700 = CandidateTypes.pointer_begin(); 2701 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2702 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() }; 2703 2704 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t) 2705 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 2706 2707 if (Op == OO_Plus) { 2708 // T* operator+(ptrdiff_t, T*); 2709 ParamTypes[0] = ParamTypes[1]; 2710 ParamTypes[1] = *Ptr; 2711 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet); 2712 } else { 2713 // ptrdiff_t operator-(T, T); 2714 ParamTypes[1] = *Ptr; 2715 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes, 2716 Args, 2, CandidateSet); 2717 } 2718 } 2719 } 2720 // Fall through 2721 2722 case OO_Slash: 2723 BinaryStar: 2724 // C++ [over.built]p12: 2725 // 2726 // For every pair of promoted arithmetic types L and R, there 2727 // exist candidate operator functions of the form 2728 // 2729 // LR operator*(L, R); 2730 // LR operator/(L, R); 2731 // LR operator+(L, R); 2732 // LR operator-(L, R); 2733 // bool operator<(L, R); 2734 // bool operator>(L, R); 2735 // bool operator<=(L, R); 2736 // bool operator>=(L, R); 2737 // bool operator==(L, R); 2738 // bool operator!=(L, R); 2739 // 2740 // where LR is the result of the usual arithmetic conversions 2741 // between types L and R. 2742 for (unsigned Left = FirstPromotedArithmeticType; 2743 Left < LastPromotedArithmeticType; ++Left) { 2744 for (unsigned Right = FirstPromotedArithmeticType; 2745 Right < LastPromotedArithmeticType; ++Right) { 2746 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] }; 2747 QualType Result 2748 = isComparison? Context.BoolTy 2749 : UsualArithmeticConversionsType(LandR[0], LandR[1]); 2750 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 2751 } 2752 } 2753 break; 2754 2755 case OO_Percent: 2756 BinaryAmp: 2757 case OO_Caret: 2758 case OO_Pipe: 2759 case OO_LessLess: 2760 case OO_GreaterGreater: 2761 // C++ [over.built]p17: 2762 // 2763 // For every pair of promoted integral types L and R, there 2764 // exist candidate operator functions of the form 2765 // 2766 // LR operator%(L, R); 2767 // LR operator&(L, R); 2768 // LR operator^(L, R); 2769 // LR operator|(L, R); 2770 // L operator<<(L, R); 2771 // L operator>>(L, R); 2772 // 2773 // where LR is the result of the usual arithmetic conversions 2774 // between types L and R. 2775 for (unsigned Left = FirstPromotedIntegralType; 2776 Left < LastPromotedIntegralType; ++Left) { 2777 for (unsigned Right = FirstPromotedIntegralType; 2778 Right < LastPromotedIntegralType; ++Right) { 2779 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] }; 2780 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater) 2781 ? LandR[0] 2782 : UsualArithmeticConversionsType(LandR[0], LandR[1]); 2783 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet); 2784 } 2785 } 2786 break; 2787 2788 case OO_Equal: 2789 // C++ [over.built]p20: 2790 // 2791 // For every pair (T, VQ), where T is an enumeration or 2792 // (FIXME:) pointer to member type and VQ is either volatile or 2793 // empty, there exist candidate operator functions of the form 2794 // 2795 // VQ T& operator=(VQ T&, T); 2796 for (BuiltinCandidateTypeSet::iterator Enum 2797 = CandidateTypes.enumeration_begin(); 2798 Enum != CandidateTypes.enumeration_end(); ++Enum) { 2799 QualType ParamTypes[2]; 2800 2801 // T& operator=(T&, T) 2802 ParamTypes[0] = Context.getReferenceType(*Enum); 2803 ParamTypes[1] = *Enum; 2804 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2805 2806 if (!Context.getCanonicalType(*Enum).isVolatileQualified()) { 2807 // volatile T& operator=(volatile T&, T) 2808 ParamTypes[0] = Context.getReferenceType((*Enum).withVolatile()); 2809 ParamTypes[1] = *Enum; 2810 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2811 } 2812 } 2813 // Fall through. 2814 2815 case OO_PlusEqual: 2816 case OO_MinusEqual: 2817 // C++ [over.built]p19: 2818 // 2819 // For every pair (T, VQ), where T is any type and VQ is either 2820 // volatile or empty, there exist candidate operator functions 2821 // of the form 2822 // 2823 // T*VQ& operator=(T*VQ&, T*); 2824 // 2825 // C++ [over.built]p21: 2826 // 2827 // For every pair (T, VQ), where T is a cv-qualified or 2828 // cv-unqualified object type and VQ is either volatile or 2829 // empty, there exist candidate operator functions of the form 2830 // 2831 // T*VQ& operator+=(T*VQ&, ptrdiff_t); 2832 // T*VQ& operator-=(T*VQ&, ptrdiff_t); 2833 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2834 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2835 QualType ParamTypes[2]; 2836 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType(); 2837 2838 // non-volatile version 2839 ParamTypes[0] = Context.getReferenceType(*Ptr); 2840 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2841 2842 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) { 2843 // volatile version 2844 ParamTypes[0] = Context.getReferenceType((*Ptr).withVolatile()); 2845 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2846 } 2847 } 2848 // Fall through. 2849 2850 case OO_StarEqual: 2851 case OO_SlashEqual: 2852 // C++ [over.built]p18: 2853 // 2854 // For every triple (L, VQ, R), where L is an arithmetic type, 2855 // VQ is either volatile or empty, and R is a promoted 2856 // arithmetic type, there exist candidate operator functions of 2857 // the form 2858 // 2859 // VQ L& operator=(VQ L&, R); 2860 // VQ L& operator*=(VQ L&, R); 2861 // VQ L& operator/=(VQ L&, R); 2862 // VQ L& operator+=(VQ L&, R); 2863 // VQ L& operator-=(VQ L&, R); 2864 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) { 2865 for (unsigned Right = FirstPromotedArithmeticType; 2866 Right < LastPromotedArithmeticType; ++Right) { 2867 QualType ParamTypes[2]; 2868 ParamTypes[1] = ArithmeticTypes[Right]; 2869 2870 // Add this built-in operator as a candidate (VQ is empty). 2871 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]); 2872 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2873 2874 // Add this built-in operator as a candidate (VQ is 'volatile'). 2875 ParamTypes[0] = ArithmeticTypes[Left].withVolatile(); 2876 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]); 2877 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2878 } 2879 } 2880 break; 2881 2882 case OO_PercentEqual: 2883 case OO_LessLessEqual: 2884 case OO_GreaterGreaterEqual: 2885 case OO_AmpEqual: 2886 case OO_CaretEqual: 2887 case OO_PipeEqual: 2888 // C++ [over.built]p22: 2889 // 2890 // For every triple (L, VQ, R), where L is an integral type, VQ 2891 // is either volatile or empty, and R is a promoted integral 2892 // type, there exist candidate operator functions of the form 2893 // 2894 // VQ L& operator%=(VQ L&, R); 2895 // VQ L& operator<<=(VQ L&, R); 2896 // VQ L& operator>>=(VQ L&, R); 2897 // VQ L& operator&=(VQ L&, R); 2898 // VQ L& operator^=(VQ L&, R); 2899 // VQ L& operator|=(VQ L&, R); 2900 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) { 2901 for (unsigned Right = FirstPromotedIntegralType; 2902 Right < LastPromotedIntegralType; ++Right) { 2903 QualType ParamTypes[2]; 2904 ParamTypes[1] = ArithmeticTypes[Right]; 2905 2906 // Add this built-in operator as a candidate (VQ is empty). 2907 // FIXME: We should be caching these declarations somewhere, 2908 // rather than re-building them every time. 2909 ParamTypes[0] = Context.getReferenceType(ArithmeticTypes[Left]); 2910 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2911 2912 // Add this built-in operator as a candidate (VQ is 'volatile'). 2913 ParamTypes[0] = ArithmeticTypes[Left]; 2914 ParamTypes[0].addVolatile(); 2915 ParamTypes[0] = Context.getReferenceType(ParamTypes[0]); 2916 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet); 2917 } 2918 } 2919 break; 2920 2921 case OO_Exclaim: { 2922 // C++ [over.operator]p23: 2923 // 2924 // There also exist candidate operator functions of the form 2925 // 2926 // bool operator!(bool); 2927 // bool operator&&(bool, bool); [BELOW] 2928 // bool operator||(bool, bool); [BELOW] 2929 QualType ParamTy = Context.BoolTy; 2930 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet); 2931 break; 2932 } 2933 2934 case OO_AmpAmp: 2935 case OO_PipePipe: { 2936 // C++ [over.operator]p23: 2937 // 2938 // There also exist candidate operator functions of the form 2939 // 2940 // bool operator!(bool); [ABOVE] 2941 // bool operator&&(bool, bool); 2942 // bool operator||(bool, bool); 2943 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy }; 2944 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet); 2945 break; 2946 } 2947 2948 case OO_Subscript: 2949 // C++ [over.built]p13: 2950 // 2951 // For every cv-qualified or cv-unqualified object type T there 2952 // exist candidate operator functions of the form 2953 // 2954 // T* operator+(T*, ptrdiff_t); [ABOVE] 2955 // T& operator[](T*, ptrdiff_t); 2956 // T* operator-(T*, ptrdiff_t); [ABOVE] 2957 // T* operator+(ptrdiff_t, T*); [ABOVE] 2958 // T& operator[](ptrdiff_t, T*); 2959 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(); 2960 Ptr != CandidateTypes.pointer_end(); ++Ptr) { 2961 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() }; 2962 QualType PointeeType = (*Ptr)->getAsPointerType()->getPointeeType(); 2963 QualType ResultTy = Context.getReferenceType(PointeeType); 2964 2965 // T& operator[](T*, ptrdiff_t) 2966 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 2967 2968 // T& operator[](ptrdiff_t, T*); 2969 ParamTypes[0] = ParamTypes[1]; 2970 ParamTypes[1] = *Ptr; 2971 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet); 2972 } 2973 break; 2974 2975 case OO_ArrowStar: 2976 // FIXME: No support for pointer-to-members yet. 2977 break; 2978 } 2979} 2980 2981/// AddOverloadCandidates - Add all of the function overloads in Ovl 2982/// to the candidate set. 2983void 2984Sema::AddOverloadCandidates(const OverloadedFunctionDecl *Ovl, 2985 Expr **Args, unsigned NumArgs, 2986 OverloadCandidateSet& CandidateSet, 2987 bool SuppressUserConversions) 2988{ 2989 for (OverloadedFunctionDecl::function_const_iterator Func 2990 = Ovl->function_begin(); 2991 Func != Ovl->function_end(); ++Func) 2992 AddOverloadCandidate(*Func, Args, NumArgs, CandidateSet, 2993 SuppressUserConversions); 2994} 2995 2996/// isBetterOverloadCandidate - Determines whether the first overload 2997/// candidate is a better candidate than the second (C++ 13.3.3p1). 2998bool 2999Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1, 3000 const OverloadCandidate& Cand2) 3001{ 3002 // Define viable functions to be better candidates than non-viable 3003 // functions. 3004 if (!Cand2.Viable) 3005 return Cand1.Viable; 3006 else if (!Cand1.Viable) 3007 return false; 3008 3009 // C++ [over.match.best]p1: 3010 // 3011 // -- if F is a static member function, ICS1(F) is defined such 3012 // that ICS1(F) is neither better nor worse than ICS1(G) for 3013 // any function G, and, symmetrically, ICS1(G) is neither 3014 // better nor worse than ICS1(F). 3015 unsigned StartArg = 0; 3016 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument) 3017 StartArg = 1; 3018 3019 // (C++ 13.3.3p1): a viable function F1 is defined to be a better 3020 // function than another viable function F2 if for all arguments i, 3021 // ICSi(F1) is not a worse conversion sequence than ICSi(F2), and 3022 // then... 3023 unsigned NumArgs = Cand1.Conversions.size(); 3024 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch"); 3025 bool HasBetterConversion = false; 3026 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) { 3027 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx], 3028 Cand2.Conversions[ArgIdx])) { 3029 case ImplicitConversionSequence::Better: 3030 // Cand1 has a better conversion sequence. 3031 HasBetterConversion = true; 3032 break; 3033 3034 case ImplicitConversionSequence::Worse: 3035 // Cand1 can't be better than Cand2. 3036 return false; 3037 3038 case ImplicitConversionSequence::Indistinguishable: 3039 // Do nothing. 3040 break; 3041 } 3042 } 3043 3044 if (HasBetterConversion) 3045 return true; 3046 3047 // FIXME: Several other bullets in (C++ 13.3.3p1) need to be 3048 // implemented, but they require template support. 3049 3050 // C++ [over.match.best]p1b4: 3051 // 3052 // -- the context is an initialization by user-defined conversion 3053 // (see 8.5, 13.3.1.5) and the standard conversion sequence 3054 // from the return type of F1 to the destination type (i.e., 3055 // the type of the entity being initialized) is a better 3056 // conversion sequence than the standard conversion sequence 3057 // from the return type of F2 to the destination type. 3058 if (Cand1.Function && Cand2.Function && 3059 isa<CXXConversionDecl>(Cand1.Function) && 3060 isa<CXXConversionDecl>(Cand2.Function)) { 3061 switch (CompareStandardConversionSequences(Cand1.FinalConversion, 3062 Cand2.FinalConversion)) { 3063 case ImplicitConversionSequence::Better: 3064 // Cand1 has a better conversion sequence. 3065 return true; 3066 3067 case ImplicitConversionSequence::Worse: 3068 // Cand1 can't be better than Cand2. 3069 return false; 3070 3071 case ImplicitConversionSequence::Indistinguishable: 3072 // Do nothing 3073 break; 3074 } 3075 } 3076 3077 return false; 3078} 3079 3080/// BestViableFunction - Computes the best viable function (C++ 13.3.3) 3081/// within an overload candidate set. If overloading is successful, 3082/// the result will be OR_Success and Best will be set to point to the 3083/// best viable function within the candidate set. Otherwise, one of 3084/// several kinds of errors will be returned; see 3085/// Sema::OverloadingResult. 3086Sema::OverloadingResult 3087Sema::BestViableFunction(OverloadCandidateSet& CandidateSet, 3088 OverloadCandidateSet::iterator& Best) 3089{ 3090 // Find the best viable function. 3091 Best = CandidateSet.end(); 3092 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 3093 Cand != CandidateSet.end(); ++Cand) { 3094 if (Cand->Viable) { 3095 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best)) 3096 Best = Cand; 3097 } 3098 } 3099 3100 // If we didn't find any viable functions, abort. 3101 if (Best == CandidateSet.end()) 3102 return OR_No_Viable_Function; 3103 3104 // Make sure that this function is better than every other viable 3105 // function. If not, we have an ambiguity. 3106 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(); 3107 Cand != CandidateSet.end(); ++Cand) { 3108 if (Cand->Viable && 3109 Cand != Best && 3110 !isBetterOverloadCandidate(*Best, *Cand)) { 3111 Best = CandidateSet.end(); 3112 return OR_Ambiguous; 3113 } 3114 } 3115 3116 // Best is the best viable function. 3117 return OR_Success; 3118} 3119 3120/// PrintOverloadCandidates - When overload resolution fails, prints 3121/// diagnostic messages containing the candidates in the candidate 3122/// set. If OnlyViable is true, only viable candidates will be printed. 3123void 3124Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet, 3125 bool OnlyViable) 3126{ 3127 OverloadCandidateSet::iterator Cand = CandidateSet.begin(), 3128 LastCand = CandidateSet.end(); 3129 for (; Cand != LastCand; ++Cand) { 3130 if (Cand->Viable || !OnlyViable) { 3131 if (Cand->Function) { 3132 // Normal function 3133 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate); 3134 } else if (Cand->IsSurrogate) { 3135 // Desugar the type of the surrogate down to a function type, 3136 // retaining as many typedefs as possible while still showing 3137 // the function type (and, therefore, its parameter types). 3138 QualType FnType = Cand->Surrogate->getConversionType(); 3139 bool isReference = false; 3140 bool isPointer = false; 3141 if (const ReferenceType *FnTypeRef = FnType->getAsReferenceType()) { 3142 FnType = FnTypeRef->getPointeeType(); 3143 isReference = true; 3144 } 3145 if (const PointerType *FnTypePtr = FnType->getAsPointerType()) { 3146 FnType = FnTypePtr->getPointeeType(); 3147 isPointer = true; 3148 } 3149 // Desugar down to a function type. 3150 FnType = QualType(FnType->getAsFunctionType(), 0); 3151 // Reconstruct the pointer/reference as appropriate. 3152 if (isPointer) FnType = Context.getPointerType(FnType); 3153 if (isReference) FnType = Context.getReferenceType(FnType); 3154 3155 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand) 3156 << FnType; 3157 } else { 3158 // FIXME: We need to get the identifier in here 3159 // FIXME: Do we want the error message to point at the 3160 // operator? (built-ins won't have a location) 3161 QualType FnType 3162 = Context.getFunctionType(Cand->BuiltinTypes.ResultTy, 3163 Cand->BuiltinTypes.ParamTypes, 3164 Cand->Conversions.size(), 3165 false, 0); 3166 3167 Diag(SourceLocation(), diag::err_ovl_builtin_candidate) << FnType; 3168 } 3169 } 3170 } 3171} 3172 3173/// ResolveAddressOfOverloadedFunction - Try to resolve the address of 3174/// an overloaded function (C++ [over.over]), where @p From is an 3175/// expression with overloaded function type and @p ToType is the type 3176/// we're trying to resolve to. For example: 3177/// 3178/// @code 3179/// int f(double); 3180/// int f(int); 3181/// 3182/// int (*pfd)(double) = f; // selects f(double) 3183/// @endcode 3184/// 3185/// This routine returns the resulting FunctionDecl if it could be 3186/// resolved, and NULL otherwise. When @p Complain is true, this 3187/// routine will emit diagnostics if there is an error. 3188FunctionDecl * 3189Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType, 3190 bool Complain) { 3191 QualType FunctionType = ToType; 3192 if (const PointerLikeType *ToTypePtr = ToType->getAsPointerLikeType()) 3193 FunctionType = ToTypePtr->getPointeeType(); 3194 3195 // We only look at pointers or references to functions. 3196 if (!FunctionType->isFunctionType()) 3197 return 0; 3198 3199 // Find the actual overloaded function declaration. 3200 OverloadedFunctionDecl *Ovl = 0; 3201 3202 // C++ [over.over]p1: 3203 // [...] [Note: any redundant set of parentheses surrounding the 3204 // overloaded function name is ignored (5.1). ] 3205 Expr *OvlExpr = From->IgnoreParens(); 3206 3207 // C++ [over.over]p1: 3208 // [...] The overloaded function name can be preceded by the & 3209 // operator. 3210 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) { 3211 if (UnOp->getOpcode() == UnaryOperator::AddrOf) 3212 OvlExpr = UnOp->getSubExpr()->IgnoreParens(); 3213 } 3214 3215 // Try to dig out the overloaded function. 3216 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) 3217 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl()); 3218 3219 // If there's no overloaded function declaration, we're done. 3220 if (!Ovl) 3221 return 0; 3222 3223 // Look through all of the overloaded functions, searching for one 3224 // whose type matches exactly. 3225 // FIXME: When templates or using declarations come along, we'll actually 3226 // have to deal with duplicates, partial ordering, etc. For now, we 3227 // can just do a simple search. 3228 FunctionType = Context.getCanonicalType(FunctionType.getUnqualifiedType()); 3229 for (OverloadedFunctionDecl::function_iterator Fun = Ovl->function_begin(); 3230 Fun != Ovl->function_end(); ++Fun) { 3231 // C++ [over.over]p3: 3232 // Non-member functions and static member functions match 3233 // targets of type “pointer-to-function”or 3234 // “reference-to-function.” 3235 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) 3236 if (!Method->isStatic()) 3237 continue; 3238 3239 if (FunctionType == Context.getCanonicalType((*Fun)->getType())) 3240 return *Fun; 3241 } 3242 3243 return 0; 3244} 3245 3246/// ResolveOverloadedCallFn - Given the call expression that calls Fn 3247/// (which eventually refers to the set of overloaded functions in 3248/// Ovl) and the call arguments Args/NumArgs, attempt to resolve the 3249/// function call down to a specific function. If overload resolution 3250/// succeeds, returns the function declaration produced by overload 3251/// resolution. Otherwise, emits diagnostics, deletes all of the 3252/// arguments and Fn, and returns NULL. 3253FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, OverloadedFunctionDecl *Ovl, 3254 SourceLocation LParenLoc, 3255 Expr **Args, unsigned NumArgs, 3256 SourceLocation *CommaLocs, 3257 SourceLocation RParenLoc) { 3258 OverloadCandidateSet CandidateSet; 3259 AddOverloadCandidates(Ovl, Args, NumArgs, CandidateSet); 3260 OverloadCandidateSet::iterator Best; 3261 switch (BestViableFunction(CandidateSet, Best)) { 3262 case OR_Success: 3263 return Best->Function; 3264 3265 case OR_No_Viable_Function: 3266 Diag(Fn->getSourceRange().getBegin(), 3267 diag::err_ovl_no_viable_function_in_call) 3268 << Ovl->getDeclName() << (unsigned)CandidateSet.size() 3269 << Fn->getSourceRange(); 3270 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 3271 break; 3272 3273 case OR_Ambiguous: 3274 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call) 3275 << Ovl->getDeclName() << Fn->getSourceRange(); 3276 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3277 break; 3278 } 3279 3280 // Overload resolution failed. Destroy all of the subexpressions and 3281 // return NULL. 3282 Fn->Destroy(Context); 3283 for (unsigned Arg = 0; Arg < NumArgs; ++Arg) 3284 Args[Arg]->Destroy(Context); 3285 return 0; 3286} 3287 3288/// BuildCallToMemberFunction - Build a call to a member 3289/// function. MemExpr is the expression that refers to the member 3290/// function (and includes the object parameter), Args/NumArgs are the 3291/// arguments to the function call (not including the object 3292/// parameter). The caller needs to validate that the member 3293/// expression refers to a member function or an overloaded member 3294/// function. 3295Sema::ExprResult 3296Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE, 3297 SourceLocation LParenLoc, Expr **Args, 3298 unsigned NumArgs, SourceLocation *CommaLocs, 3299 SourceLocation RParenLoc) { 3300 // Dig out the member expression. This holds both the object 3301 // argument and the member function we're referring to. 3302 MemberExpr *MemExpr = 0; 3303 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE)) 3304 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr()); 3305 else 3306 MemExpr = dyn_cast<MemberExpr>(MemExprE); 3307 assert(MemExpr && "Building member call without member expression"); 3308 3309 // Extract the object argument. 3310 Expr *ObjectArg = MemExpr->getBase(); 3311 if (MemExpr->isArrow()) 3312 ObjectArg = new UnaryOperator(ObjectArg, UnaryOperator::Deref, 3313 ObjectArg->getType()->getAsPointerType()->getPointeeType(), 3314 SourceLocation()); 3315 CXXMethodDecl *Method = 0; 3316 if (OverloadedFunctionDecl *Ovl 3317 = dyn_cast<OverloadedFunctionDecl>(MemExpr->getMemberDecl())) { 3318 // Add overload candidates 3319 OverloadCandidateSet CandidateSet; 3320 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(), 3321 FuncEnd = Ovl->function_end(); 3322 Func != FuncEnd; ++Func) { 3323 assert(isa<CXXMethodDecl>(*Func) && "Function is not a method"); 3324 Method = cast<CXXMethodDecl>(*Func); 3325 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet, 3326 /*SuppressUserConversions=*/false); 3327 } 3328 3329 OverloadCandidateSet::iterator Best; 3330 switch (BestViableFunction(CandidateSet, Best)) { 3331 case OR_Success: 3332 Method = cast<CXXMethodDecl>(Best->Function); 3333 break; 3334 3335 case OR_No_Viable_Function: 3336 Diag(MemExpr->getSourceRange().getBegin(), 3337 diag::err_ovl_no_viable_member_function_in_call) 3338 << Ovl->getDeclName() << (unsigned)CandidateSet.size() 3339 << MemExprE->getSourceRange(); 3340 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 3341 // FIXME: Leaking incoming expressions! 3342 return true; 3343 3344 case OR_Ambiguous: 3345 Diag(MemExpr->getSourceRange().getBegin(), 3346 diag::err_ovl_ambiguous_member_call) 3347 << Ovl->getDeclName() << MemExprE->getSourceRange(); 3348 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 3349 // FIXME: Leaking incoming expressions! 3350 return true; 3351 } 3352 3353 FixOverloadedFunctionReference(MemExpr, Method); 3354 } else { 3355 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl()); 3356 } 3357 3358 assert(Method && "Member call to something that isn't a method?"); 3359 llvm::OwningPtr<CXXMemberCallExpr> 3360 TheCall(new CXXMemberCallExpr(MemExpr, Args, NumArgs, 3361 Method->getResultType().getNonReferenceType(), 3362 RParenLoc)); 3363 3364 // Convert the object argument (for a non-static member function call). 3365 if (!Method->isStatic() && 3366 PerformObjectArgumentInitialization(ObjectArg, Method)) 3367 return true; 3368 MemExpr->setBase(ObjectArg); 3369 3370 // Convert the rest of the arguments 3371 const FunctionTypeProto *Proto = cast<FunctionTypeProto>(Method->getType()); 3372 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs, 3373 RParenLoc)) 3374 return true; 3375 3376 return CheckFunctionCall(Method, TheCall.take()); 3377} 3378 3379/// BuildCallToObjectOfClassType - Build a call to an object of class 3380/// type (C++ [over.call.object]), which can end up invoking an 3381/// overloaded function call operator (@c operator()) or performing a 3382/// user-defined conversion on the object argument. 3383Sema::ExprResult 3384Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object, 3385 SourceLocation LParenLoc, 3386 Expr **Args, unsigned NumArgs, 3387 SourceLocation *CommaLocs, 3388 SourceLocation RParenLoc) { 3389 assert(Object->getType()->isRecordType() && "Requires object type argument"); 3390 const RecordType *Record = Object->getType()->getAsRecordType(); 3391 3392 // C++ [over.call.object]p1: 3393 // If the primary-expression E in the function call syntax 3394 // evaluates to a class object of type “cv T”, then the set of 3395 // candidate functions includes at least the function call 3396 // operators of T. The function call operators of T are obtained by 3397 // ordinary lookup of the name operator() in the context of 3398 // (E).operator(). 3399 OverloadCandidateSet CandidateSet; 3400 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call); 3401 DeclContext::lookup_const_result Lookup 3402 = Record->getDecl()->lookup(Context, OpName); 3403 NamedDecl *MemberOps = (Lookup.first == Lookup.second)? 0 : *Lookup.first; 3404 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps)) 3405 AddMethodCandidate(Method, Object, Args, NumArgs, CandidateSet, 3406 /*SuppressUserConversions=*/false); 3407 else if (OverloadedFunctionDecl *Ovl 3408 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) { 3409 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(), 3410 FEnd = Ovl->function_end(); 3411 F != FEnd; ++F) { 3412 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F)) 3413 AddMethodCandidate(Method, Object, Args, NumArgs, CandidateSet, 3414 /*SuppressUserConversions=*/false); 3415 } 3416 } 3417 3418 // C++ [over.call.object]p2: 3419 // In addition, for each conversion function declared in T of the 3420 // form 3421 // 3422 // operator conversion-type-id () cv-qualifier; 3423 // 3424 // where cv-qualifier is the same cv-qualification as, or a 3425 // greater cv-qualification than, cv, and where conversion-type-id 3426 // denotes the type "pointer to function of (P1,...,Pn) returning 3427 // R", or the type "reference to pointer to function of 3428 // (P1,...,Pn) returning R", or the type "reference to function 3429 // of (P1,...,Pn) returning R", a surrogate call function [...] 3430 // is also considered as a candidate function. Similarly, 3431 // surrogate call functions are added to the set of candidate 3432 // functions for each conversion function declared in an 3433 // accessible base class provided the function is not hidden 3434 // within T by another intervening declaration. 3435 // 3436 // FIXME: Look in base classes for more conversion operators! 3437 OverloadedFunctionDecl *Conversions 3438 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions(); 3439 for (OverloadedFunctionDecl::function_iterator 3440 Func = Conversions->function_begin(), 3441 FuncEnd = Conversions->function_end(); 3442 Func != FuncEnd; ++Func) { 3443 CXXConversionDecl *Conv = cast<CXXConversionDecl>(*Func); 3444 3445 // Strip the reference type (if any) and then the pointer type (if 3446 // any) to get down to what might be a function type. 3447 QualType ConvType = Conv->getConversionType().getNonReferenceType(); 3448 if (const PointerType *ConvPtrType = ConvType->getAsPointerType()) 3449 ConvType = ConvPtrType->getPointeeType(); 3450 3451 if (const FunctionTypeProto *Proto = ConvType->getAsFunctionTypeProto()) 3452 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet); 3453 } 3454 3455 // Perform overload resolution. 3456 OverloadCandidateSet::iterator Best; 3457 switch (BestViableFunction(CandidateSet, Best)) { 3458 case OR_Success: 3459 // Overload resolution succeeded; we'll build the appropriate call 3460 // below. 3461 break; 3462 3463 case OR_No_Viable_Function: 3464 Diag(Object->getSourceRange().getBegin(), 3465 diag::err_ovl_no_viable_object_call) 3466 << Object->getType() << (unsigned)CandidateSet.size() 3467 << Object->getSourceRange(); 3468 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 3469 break; 3470 3471 case OR_Ambiguous: 3472 Diag(Object->getSourceRange().getBegin(), 3473 diag::err_ovl_ambiguous_object_call) 3474 << Object->getType() << Object->getSourceRange(); 3475 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3476 break; 3477 } 3478 3479 if (Best == CandidateSet.end()) { 3480 // We had an error; delete all of the subexpressions and return 3481 // the error. 3482 delete Object; 3483 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 3484 delete Args[ArgIdx]; 3485 return true; 3486 } 3487 3488 if (Best->Function == 0) { 3489 // Since there is no function declaration, this is one of the 3490 // surrogate candidates. Dig out the conversion function. 3491 CXXConversionDecl *Conv 3492 = cast<CXXConversionDecl>( 3493 Best->Conversions[0].UserDefined.ConversionFunction); 3494 3495 // We selected one of the surrogate functions that converts the 3496 // object parameter to a function pointer. Perform the conversion 3497 // on the object argument, then let ActOnCallExpr finish the job. 3498 // FIXME: Represent the user-defined conversion in the AST! 3499 ImpCastExprToType(Object, 3500 Conv->getConversionType().getNonReferenceType(), 3501 Conv->getConversionType()->isReferenceType()); 3502 return ActOnCallExpr(S, (ExprTy*)Object, LParenLoc, (ExprTy**)Args, NumArgs, 3503 CommaLocs, RParenLoc); 3504 } 3505 3506 // We found an overloaded operator(). Build a CXXOperatorCallExpr 3507 // that calls this method, using Object for the implicit object 3508 // parameter and passing along the remaining arguments. 3509 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 3510 const FunctionTypeProto *Proto = Method->getType()->getAsFunctionTypeProto(); 3511 3512 unsigned NumArgsInProto = Proto->getNumArgs(); 3513 unsigned NumArgsToCheck = NumArgs; 3514 3515 // Build the full argument list for the method call (the 3516 // implicit object parameter is placed at the beginning of the 3517 // list). 3518 Expr **MethodArgs; 3519 if (NumArgs < NumArgsInProto) { 3520 NumArgsToCheck = NumArgsInProto; 3521 MethodArgs = new Expr*[NumArgsInProto + 1]; 3522 } else { 3523 MethodArgs = new Expr*[NumArgs + 1]; 3524 } 3525 MethodArgs[0] = Object; 3526 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) 3527 MethodArgs[ArgIdx + 1] = Args[ArgIdx]; 3528 3529 Expr *NewFn = new DeclRefExpr(Method, Method->getType(), 3530 SourceLocation()); 3531 UsualUnaryConversions(NewFn); 3532 3533 // Once we've built TheCall, all of the expressions are properly 3534 // owned. 3535 QualType ResultTy = Method->getResultType().getNonReferenceType(); 3536 llvm::OwningPtr<CXXOperatorCallExpr> 3537 TheCall(new CXXOperatorCallExpr(NewFn, MethodArgs, NumArgs + 1, 3538 ResultTy, RParenLoc)); 3539 delete [] MethodArgs; 3540 3541 // Initialize the implicit object parameter. 3542 if (!PerformObjectArgumentInitialization(Object, Method)) 3543 return true; 3544 TheCall->setArg(0, Object); 3545 3546 // Check the argument types. 3547 for (unsigned i = 0; i != NumArgsToCheck; i++) { 3548 QualType ProtoArgType = Proto->getArgType(i); 3549 3550 Expr *Arg; 3551 if (i < NumArgs) 3552 Arg = Args[i]; 3553 else 3554 Arg = new CXXDefaultArgExpr(Method->getParamDecl(i)); 3555 QualType ArgType = Arg->getType(); 3556 3557 // Pass the argument. 3558 if (PerformCopyInitialization(Arg, ProtoArgType, "passing")) 3559 return true; 3560 3561 TheCall->setArg(i + 1, Arg); 3562 } 3563 3564 // If this is a variadic call, handle args passed through "...". 3565 if (Proto->isVariadic()) { 3566 // Promote the arguments (C99 6.5.2.2p7). 3567 for (unsigned i = NumArgsInProto; i != NumArgs; i++) { 3568 Expr *Arg = Args[i]; 3569 DefaultArgumentPromotion(Arg); 3570 TheCall->setArg(i + 1, Arg); 3571 } 3572 } 3573 3574 return CheckFunctionCall(Method, TheCall.take()); 3575} 3576 3577/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator-> 3578/// (if one exists), where @c Base is an expression of class type and 3579/// @c Member is the name of the member we're trying to find. 3580Action::ExprResult 3581Sema::BuildOverloadedArrowExpr(Expr *Base, SourceLocation OpLoc, 3582 SourceLocation MemberLoc, 3583 IdentifierInfo &Member) { 3584 assert(Base->getType()->isRecordType() && "left-hand side must have class type"); 3585 3586 // C++ [over.ref]p1: 3587 // 3588 // [...] An expression x->m is interpreted as (x.operator->())->m 3589 // for a class object x of type T if T::operator->() exists and if 3590 // the operator is selected as the best match function by the 3591 // overload resolution mechanism (13.3). 3592 // FIXME: look in base classes. 3593 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow); 3594 OverloadCandidateSet CandidateSet; 3595 const RecordType *BaseRecord = Base->getType()->getAsRecordType(); 3596 DeclContext::lookup_const_result Lookup 3597 = BaseRecord->getDecl()->lookup(Context, OpName); 3598 NamedDecl *MemberOps = (Lookup.first == Lookup.second)? 0 : *Lookup.first; 3599 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(MemberOps)) 3600 AddMethodCandidate(Method, Base, 0, 0, CandidateSet, 3601 /*SuppressUserConversions=*/false); 3602 else if (OverloadedFunctionDecl *Ovl 3603 = dyn_cast_or_null<OverloadedFunctionDecl>(MemberOps)) { 3604 for (OverloadedFunctionDecl::function_iterator F = Ovl->function_begin(), 3605 FEnd = Ovl->function_end(); 3606 F != FEnd; ++F) { 3607 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*F)) 3608 AddMethodCandidate(Method, Base, 0, 0, CandidateSet, 3609 /*SuppressUserConversions=*/false); 3610 } 3611 } 3612 3613 llvm::OwningPtr<Expr> BasePtr(Base); 3614 3615 // Perform overload resolution. 3616 OverloadCandidateSet::iterator Best; 3617 switch (BestViableFunction(CandidateSet, Best)) { 3618 case OR_Success: 3619 // Overload resolution succeeded; we'll build the call below. 3620 break; 3621 3622 case OR_No_Viable_Function: 3623 if (CandidateSet.empty()) 3624 Diag(OpLoc, diag::err_typecheck_member_reference_arrow) 3625 << BasePtr->getType() << BasePtr->getSourceRange(); 3626 else 3627 Diag(OpLoc, diag::err_ovl_no_viable_oper) 3628 << "operator->" << (unsigned)CandidateSet.size() 3629 << BasePtr->getSourceRange(); 3630 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false); 3631 return true; 3632 3633 case OR_Ambiguous: 3634 Diag(OpLoc, diag::err_ovl_ambiguous_oper) 3635 << "operator->" << BasePtr->getSourceRange(); 3636 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true); 3637 return true; 3638 } 3639 3640 // Convert the object parameter. 3641 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function); 3642 if (PerformObjectArgumentInitialization(Base, Method)) 3643 return true; 3644 3645 // No concerns about early exits now. 3646 BasePtr.take(); 3647 3648 // Build the operator call. 3649 Expr *FnExpr = new DeclRefExpr(Method, Method->getType(), SourceLocation()); 3650 UsualUnaryConversions(FnExpr); 3651 Base = new CXXOperatorCallExpr(FnExpr, &Base, 1, 3652 Method->getResultType().getNonReferenceType(), 3653 OpLoc); 3654 return ActOnMemberReferenceExpr(Base, OpLoc, tok::arrow, MemberLoc, Member); 3655} 3656 3657/// FixOverloadedFunctionReference - E is an expression that refers to 3658/// a C++ overloaded function (possibly with some parentheses and 3659/// perhaps a '&' around it). We have resolved the overloaded function 3660/// to the function declaration Fn, so patch up the expression E to 3661/// refer (possibly indirectly) to Fn. 3662void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) { 3663 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 3664 FixOverloadedFunctionReference(PE->getSubExpr(), Fn); 3665 E->setType(PE->getSubExpr()->getType()); 3666 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) { 3667 assert(UnOp->getOpcode() == UnaryOperator::AddrOf && 3668 "Can only take the address of an overloaded function"); 3669 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn); 3670 E->setType(Context.getPointerType(E->getType())); 3671 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) { 3672 assert(isa<OverloadedFunctionDecl>(DR->getDecl()) && 3673 "Expected overloaded function"); 3674 DR->setDecl(Fn); 3675 E->setType(Fn->getType()); 3676 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) { 3677 MemExpr->setMemberDecl(Fn); 3678 E->setType(Fn->getType()); 3679 } else { 3680 assert(false && "Invalid reference to overloaded function"); 3681 } 3682} 3683 3684} // end namespace clang 3685