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