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