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