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