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