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