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