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