1 //===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file provides Sema routines for C++ overloading.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/Lookup.h"
16 #include "clang/Sema/Initialization.h"
17 #include "clang/Sema/Template.h"
18 #include "clang/Sema/TemplateDeduction.h"
19 #include "clang/Basic/Diagnostic.h"
20 #include "clang/Lex/Preprocessor.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/CXXInheritance.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/ExprObjC.h"
27 #include "clang/AST/TypeOrdering.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "llvm/ADT/DenseSet.h"
30 #include "llvm/ADT/SmallPtrSet.h"
31 #include "llvm/ADT/STLExtras.h"
37 /// A convenience routine for creating a decayed reference to a
40 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
41 SourceLocation Loc = SourceLocation()) {
42 ExprResult E = S.Owned(new (S.Context) DeclRefExpr(Fn, Fn->getType(), VK_LValue, Loc));
43 E = S.DefaultFunctionArrayConversion(E.take());
49 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
50 bool InOverloadResolution,
51 StandardConversionSequence &SCS,
54 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
56 bool InOverloadResolution,
57 StandardConversionSequence &SCS,
59 static OverloadingResult
60 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
61 UserDefinedConversionSequence& User,
62 OverloadCandidateSet& Conversions,
66 static ImplicitConversionSequence::CompareKind
67 CompareStandardConversionSequences(Sema &S,
68 const StandardConversionSequence& SCS1,
69 const StandardConversionSequence& SCS2);
71 static ImplicitConversionSequence::CompareKind
72 CompareQualificationConversions(Sema &S,
73 const StandardConversionSequence& SCS1,
74 const StandardConversionSequence& SCS2);
76 static ImplicitConversionSequence::CompareKind
77 CompareDerivedToBaseConversions(Sema &S,
78 const StandardConversionSequence& SCS1,
79 const StandardConversionSequence& SCS2);
83 /// GetConversionCategory - Retrieve the implicit conversion
84 /// category corresponding to the given implicit conversion kind.
85 ImplicitConversionCategory
86 GetConversionCategory(ImplicitConversionKind Kind) {
87 static const ImplicitConversionCategory
88 Category[(int)ICK_Num_Conversion_Kinds] = {
90 ICC_Lvalue_Transformation,
91 ICC_Lvalue_Transformation,
92 ICC_Lvalue_Transformation,
94 ICC_Qualification_Adjustment,
111 return Category[(int)Kind];
114 /// GetConversionRank - Retrieve the implicit conversion rank
115 /// corresponding to the given implicit conversion kind.
116 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
117 static const ImplicitConversionRank
118 Rank[(int)ICK_Num_Conversion_Kinds] = {
139 ICR_Complex_Real_Conversion,
143 return Rank[(int)Kind];
146 /// GetImplicitConversionName - Return the name of this kind of
147 /// implicit conversion.
148 const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
149 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
153 "Function-to-pointer",
154 "Noreturn adjustment",
156 "Integral promotion",
157 "Floating point promotion",
159 "Integral conversion",
160 "Floating conversion",
161 "Complex conversion",
162 "Floating-integral conversion",
163 "Pointer conversion",
164 "Pointer-to-member conversion",
165 "Boolean conversion",
166 "Compatible-types conversion",
167 "Derived-to-base conversion",
170 "Complex-real conversion",
171 "Block Pointer conversion",
172 "Transparent Union Conversion"
177 /// StandardConversionSequence - Set the standard conversion
178 /// sequence to the identity conversion.
179 void StandardConversionSequence::setAsIdentityConversion() {
180 First = ICK_Identity;
181 Second = ICK_Identity;
182 Third = ICK_Identity;
183 DeprecatedStringLiteralToCharPtr = false;
184 ReferenceBinding = false;
185 DirectBinding = false;
186 IsLvalueReference = true;
187 BindsToFunctionLvalue = false;
188 BindsToRvalue = false;
189 BindsImplicitObjectArgumentWithoutRefQualifier = false;
193 /// getRank - Retrieve the rank of this standard conversion sequence
194 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
195 /// implicit conversions.
196 ImplicitConversionRank StandardConversionSequence::getRank() const {
197 ImplicitConversionRank Rank = ICR_Exact_Match;
198 if (GetConversionRank(First) > Rank)
199 Rank = GetConversionRank(First);
200 if (GetConversionRank(Second) > Rank)
201 Rank = GetConversionRank(Second);
202 if (GetConversionRank(Third) > Rank)
203 Rank = GetConversionRank(Third);
207 /// isPointerConversionToBool - Determines whether this conversion is
208 /// a conversion of a pointer or pointer-to-member to bool. This is
209 /// used as part of the ranking of standard conversion sequences
210 /// (C++ 13.3.3.2p4).
211 bool StandardConversionSequence::isPointerConversionToBool() const {
212 // Note that FromType has not necessarily been transformed by the
213 // array-to-pointer or function-to-pointer implicit conversions, so
214 // check for their presence as well as checking whether FromType is
216 if (getToType(1)->isBooleanType() &&
217 (getFromType()->isPointerType() ||
218 getFromType()->isObjCObjectPointerType() ||
219 getFromType()->isBlockPointerType() ||
220 getFromType()->isNullPtrType() ||
221 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
227 /// isPointerConversionToVoidPointer - Determines whether this
228 /// conversion is a conversion of a pointer to a void pointer. This is
229 /// used as part of the ranking of standard conversion sequences (C++
232 StandardConversionSequence::
233 isPointerConversionToVoidPointer(ASTContext& Context) const {
234 QualType FromType = getFromType();
235 QualType ToType = getToType(1);
237 // Note that FromType has not necessarily been transformed by the
238 // array-to-pointer implicit conversion, so check for its presence
239 // and redo the conversion to get a pointer.
240 if (First == ICK_Array_To_Pointer)
241 FromType = Context.getArrayDecayedType(FromType);
243 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
244 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
245 return ToPtrType->getPointeeType()->isVoidType();
250 /// DebugPrint - Print this standard conversion sequence to standard
251 /// error. Useful for debugging overloading issues.
252 void StandardConversionSequence::DebugPrint() const {
253 llvm::raw_ostream &OS = llvm::errs();
254 bool PrintedSomething = false;
255 if (First != ICK_Identity) {
256 OS << GetImplicitConversionName(First);
257 PrintedSomething = true;
260 if (Second != ICK_Identity) {
261 if (PrintedSomething) {
264 OS << GetImplicitConversionName(Second);
266 if (CopyConstructor) {
267 OS << " (by copy constructor)";
268 } else if (DirectBinding) {
269 OS << " (direct reference binding)";
270 } else if (ReferenceBinding) {
271 OS << " (reference binding)";
273 PrintedSomething = true;
276 if (Third != ICK_Identity) {
277 if (PrintedSomething) {
280 OS << GetImplicitConversionName(Third);
281 PrintedSomething = true;
284 if (!PrintedSomething) {
285 OS << "No conversions required";
289 /// DebugPrint - Print this user-defined conversion sequence to standard
290 /// error. Useful for debugging overloading issues.
291 void UserDefinedConversionSequence::DebugPrint() const {
292 llvm::raw_ostream &OS = llvm::errs();
293 if (Before.First || Before.Second || Before.Third) {
297 OS << '\'' << ConversionFunction << '\'';
298 if (After.First || After.Second || After.Third) {
304 /// DebugPrint - Print this implicit conversion sequence to standard
305 /// error. Useful for debugging overloading issues.
306 void ImplicitConversionSequence::DebugPrint() const {
307 llvm::raw_ostream &OS = llvm::errs();
308 switch (ConversionKind) {
309 case StandardConversion:
310 OS << "Standard conversion: ";
311 Standard.DebugPrint();
313 case UserDefinedConversion:
314 OS << "User-defined conversion: ";
315 UserDefined.DebugPrint();
317 case EllipsisConversion:
318 OS << "Ellipsis conversion";
320 case AmbiguousConversion:
321 OS << "Ambiguous conversion";
324 OS << "Bad conversion";
331 void AmbiguousConversionSequence::construct() {
332 new (&conversions()) ConversionSet();
335 void AmbiguousConversionSequence::destruct() {
336 conversions().~ConversionSet();
340 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
341 FromTypePtr = O.FromTypePtr;
342 ToTypePtr = O.ToTypePtr;
343 new (&conversions()) ConversionSet(O.conversions());
347 // Structure used by OverloadCandidate::DeductionFailureInfo to store
348 // template parameter and template argument information.
349 struct DFIParamWithArguments {
350 TemplateParameter Param;
351 TemplateArgument FirstArg;
352 TemplateArgument SecondArg;
356 /// \brief Convert from Sema's representation of template deduction information
357 /// to the form used in overload-candidate information.
358 OverloadCandidate::DeductionFailureInfo
359 static MakeDeductionFailureInfo(ASTContext &Context,
360 Sema::TemplateDeductionResult TDK,
361 TemplateDeductionInfo &Info) {
362 OverloadCandidate::DeductionFailureInfo Result;
363 Result.Result = static_cast<unsigned>(TDK);
366 case Sema::TDK_Success:
367 case Sema::TDK_InstantiationDepth:
368 case Sema::TDK_TooManyArguments:
369 case Sema::TDK_TooFewArguments:
372 case Sema::TDK_Incomplete:
373 case Sema::TDK_InvalidExplicitArguments:
374 Result.Data = Info.Param.getOpaqueValue();
377 case Sema::TDK_Inconsistent:
378 case Sema::TDK_Underqualified: {
379 // FIXME: Should allocate from normal heap so that we can free this later.
380 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
381 Saved->Param = Info.Param;
382 Saved->FirstArg = Info.FirstArg;
383 Saved->SecondArg = Info.SecondArg;
388 case Sema::TDK_SubstitutionFailure:
389 Result.Data = Info.take();
392 case Sema::TDK_NonDeducedMismatch:
393 case Sema::TDK_FailedOverloadResolution:
400 void OverloadCandidate::DeductionFailureInfo::Destroy() {
401 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
402 case Sema::TDK_Success:
403 case Sema::TDK_InstantiationDepth:
404 case Sema::TDK_Incomplete:
405 case Sema::TDK_TooManyArguments:
406 case Sema::TDK_TooFewArguments:
407 case Sema::TDK_InvalidExplicitArguments:
410 case Sema::TDK_Inconsistent:
411 case Sema::TDK_Underqualified:
412 // FIXME: Destroy the data?
416 case Sema::TDK_SubstitutionFailure:
417 // FIXME: Destroy the template arugment list?
422 case Sema::TDK_NonDeducedMismatch:
423 case Sema::TDK_FailedOverloadResolution:
429 OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
430 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
431 case Sema::TDK_Success:
432 case Sema::TDK_InstantiationDepth:
433 case Sema::TDK_TooManyArguments:
434 case Sema::TDK_TooFewArguments:
435 case Sema::TDK_SubstitutionFailure:
436 return TemplateParameter();
438 case Sema::TDK_Incomplete:
439 case Sema::TDK_InvalidExplicitArguments:
440 return TemplateParameter::getFromOpaqueValue(Data);
442 case Sema::TDK_Inconsistent:
443 case Sema::TDK_Underqualified:
444 return static_cast<DFIParamWithArguments*>(Data)->Param;
447 case Sema::TDK_NonDeducedMismatch:
448 case Sema::TDK_FailedOverloadResolution:
452 return TemplateParameter();
455 TemplateArgumentList *
456 OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
457 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
458 case Sema::TDK_Success:
459 case Sema::TDK_InstantiationDepth:
460 case Sema::TDK_TooManyArguments:
461 case Sema::TDK_TooFewArguments:
462 case Sema::TDK_Incomplete:
463 case Sema::TDK_InvalidExplicitArguments:
464 case Sema::TDK_Inconsistent:
465 case Sema::TDK_Underqualified:
468 case Sema::TDK_SubstitutionFailure:
469 return static_cast<TemplateArgumentList*>(Data);
472 case Sema::TDK_NonDeducedMismatch:
473 case Sema::TDK_FailedOverloadResolution:
480 const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
481 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
482 case Sema::TDK_Success:
483 case Sema::TDK_InstantiationDepth:
484 case Sema::TDK_Incomplete:
485 case Sema::TDK_TooManyArguments:
486 case Sema::TDK_TooFewArguments:
487 case Sema::TDK_InvalidExplicitArguments:
488 case Sema::TDK_SubstitutionFailure:
491 case Sema::TDK_Inconsistent:
492 case Sema::TDK_Underqualified:
493 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
496 case Sema::TDK_NonDeducedMismatch:
497 case Sema::TDK_FailedOverloadResolution:
504 const TemplateArgument *
505 OverloadCandidate::DeductionFailureInfo::getSecondArg() {
506 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
507 case Sema::TDK_Success:
508 case Sema::TDK_InstantiationDepth:
509 case Sema::TDK_Incomplete:
510 case Sema::TDK_TooManyArguments:
511 case Sema::TDK_TooFewArguments:
512 case Sema::TDK_InvalidExplicitArguments:
513 case Sema::TDK_SubstitutionFailure:
516 case Sema::TDK_Inconsistent:
517 case Sema::TDK_Underqualified:
518 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
521 case Sema::TDK_NonDeducedMismatch:
522 case Sema::TDK_FailedOverloadResolution:
529 void OverloadCandidateSet::clear() {
534 // IsOverload - Determine whether the given New declaration is an
535 // overload of the declarations in Old. This routine returns false if
536 // New and Old cannot be overloaded, e.g., if New has the same
537 // signature as some function in Old (C++ 1.3.10) or if the Old
538 // declarations aren't functions (or function templates) at all. When
539 // it does return false, MatchedDecl will point to the decl that New
540 // cannot be overloaded with. This decl may be a UsingShadowDecl on
541 // top of the underlying declaration.
543 // Example: Given the following input:
545 // void f(int, float); // #1
546 // void f(int, int); // #2
547 // int f(int, int); // #3
549 // When we process #1, there is no previous declaration of "f",
550 // so IsOverload will not be used.
552 // When we process #2, Old contains only the FunctionDecl for #1. By
553 // comparing the parameter types, we see that #1 and #2 are overloaded
554 // (since they have different signatures), so this routine returns
555 // false; MatchedDecl is unchanged.
557 // When we process #3, Old is an overload set containing #1 and #2. We
558 // compare the signatures of #3 to #1 (they're overloaded, so we do
559 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
560 // identical (return types of functions are not part of the
561 // signature), IsOverload returns false and MatchedDecl will be set to
562 // point to the FunctionDecl for #2.
564 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
565 // into a class by a using declaration. The rules for whether to hide
566 // shadow declarations ignore some properties which otherwise figure
567 // into a function template's signature.
569 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
570 NamedDecl *&Match, bool NewIsUsingDecl) {
571 for (LookupResult::iterator I = Old.begin(), E = Old.end();
573 NamedDecl *OldD = *I;
575 bool OldIsUsingDecl = false;
576 if (isa<UsingShadowDecl>(OldD)) {
577 OldIsUsingDecl = true;
579 // We can always introduce two using declarations into the same
580 // context, even if they have identical signatures.
581 if (NewIsUsingDecl) continue;
583 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
586 // If either declaration was introduced by a using declaration,
587 // we'll need to use slightly different rules for matching.
588 // Essentially, these rules are the normal rules, except that
589 // function templates hide function templates with different
590 // return types or template parameter lists.
591 bool UseMemberUsingDeclRules =
592 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
594 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
595 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
596 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
597 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
604 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
605 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
606 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
607 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
614 } else if (isa<UsingDecl>(OldD)) {
615 // We can overload with these, which can show up when doing
616 // redeclaration checks for UsingDecls.
617 assert(Old.getLookupKind() == LookupUsingDeclName);
618 } else if (isa<TagDecl>(OldD)) {
619 // We can always overload with tags by hiding them.
620 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
621 // Optimistically assume that an unresolved using decl will
622 // overload; if it doesn't, we'll have to diagnose during
623 // template instantiation.
626 // Only function declarations can be overloaded; object and type
627 // declarations cannot be overloaded.
629 return Ovl_NonFunction;
636 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
637 bool UseUsingDeclRules) {
638 // If both of the functions are extern "C", then they are not
640 if (Old->isExternC() && New->isExternC())
643 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
644 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
647 // A function template can be overloaded with other function templates
648 // and with normal (non-template) functions.
649 if ((OldTemplate == 0) != (NewTemplate == 0))
652 // Is the function New an overload of the function Old?
653 QualType OldQType = Context.getCanonicalType(Old->getType());
654 QualType NewQType = Context.getCanonicalType(New->getType());
656 // Compare the signatures (C++ 1.3.10) of the two functions to
657 // determine whether they are overloads. If we find any mismatch
658 // in the signature, they are overloads.
660 // If either of these functions is a K&R-style function (no
661 // prototype), then we consider them to have matching signatures.
662 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
663 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
666 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
667 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
669 // The signature of a function includes the types of its
670 // parameters (C++ 1.3.10), which includes the presence or absence
671 // of the ellipsis; see C++ DR 357).
672 if (OldQType != NewQType &&
673 (OldType->getNumArgs() != NewType->getNumArgs() ||
674 OldType->isVariadic() != NewType->isVariadic() ||
675 !FunctionArgTypesAreEqual(OldType, NewType)))
678 // C++ [temp.over.link]p4:
679 // The signature of a function template consists of its function
680 // signature, its return type and its template parameter list. The names
681 // of the template parameters are significant only for establishing the
682 // relationship between the template parameters and the rest of the
685 // We check the return type and template parameter lists for function
686 // templates first; the remaining checks follow.
688 // However, we don't consider either of these when deciding whether
689 // a member introduced by a shadow declaration is hidden.
690 if (!UseUsingDeclRules && NewTemplate &&
691 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
692 OldTemplate->getTemplateParameters(),
693 false, TPL_TemplateMatch) ||
694 OldType->getResultType() != NewType->getResultType()))
697 // If the function is a class member, its signature includes the
698 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
700 // As part of this, also check whether one of the member functions
701 // is static, in which case they are not overloads (C++
702 // 13.1p2). While not part of the definition of the signature,
703 // this check is important to determine whether these functions
704 // can be overloaded.
705 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
706 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
707 if (OldMethod && NewMethod &&
708 !OldMethod->isStatic() && !NewMethod->isStatic() &&
709 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
710 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
711 if (!UseUsingDeclRules &&
712 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
713 (OldMethod->getRefQualifier() == RQ_None ||
714 NewMethod->getRefQualifier() == RQ_None)) {
715 // C++0x [over.load]p2:
716 // - Member function declarations with the same name and the same
717 // parameter-type-list as well as member function template
718 // declarations with the same name, the same parameter-type-list, and
719 // the same template parameter lists cannot be overloaded if any of
720 // them, but not all, have a ref-qualifier (8.3.5).
721 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
722 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
723 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
729 // The signatures match; this is not an overload.
733 /// TryImplicitConversion - Attempt to perform an implicit conversion
734 /// from the given expression (Expr) to the given type (ToType). This
735 /// function returns an implicit conversion sequence that can be used
736 /// to perform the initialization. Given
739 /// void g(int i) { f(i); }
741 /// this routine would produce an implicit conversion sequence to
742 /// describe the initialization of f from i, which will be a standard
743 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
744 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
746 /// Note that this routine only determines how the conversion can be
747 /// performed; it does not actually perform the conversion. As such,
748 /// it will not produce any diagnostics if no conversion is available,
749 /// but will instead return an implicit conversion sequence of kind
752 /// If @p SuppressUserConversions, then user-defined conversions are
754 /// If @p AllowExplicit, then explicit user-defined conversions are
756 static ImplicitConversionSequence
757 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
758 bool SuppressUserConversions,
760 bool InOverloadResolution,
762 ImplicitConversionSequence ICS;
763 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
764 ICS.Standard, CStyle)) {
769 if (!S.getLangOptions().CPlusPlus) {
770 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
774 // C++ [over.ics.user]p4:
775 // A conversion of an expression of class type to the same class
776 // type is given Exact Match rank, and a conversion of an
777 // expression of class type to a base class of that type is
778 // given Conversion rank, in spite of the fact that a copy/move
779 // constructor (i.e., a user-defined conversion function) is
780 // called for those cases.
781 QualType FromType = From->getType();
782 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
783 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
784 S.IsDerivedFrom(FromType, ToType))) {
786 ICS.Standard.setAsIdentityConversion();
787 ICS.Standard.setFromType(FromType);
788 ICS.Standard.setAllToTypes(ToType);
790 // We don't actually check at this point whether there is a valid
791 // copy/move constructor, since overloading just assumes that it
792 // exists. When we actually perform initialization, we'll find the
793 // appropriate constructor to copy the returned object, if needed.
794 ICS.Standard.CopyConstructor = 0;
796 // Determine whether this is considered a derived-to-base conversion.
797 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
798 ICS.Standard.Second = ICK_Derived_To_Base;
803 if (SuppressUserConversions) {
804 // We're not in the case above, so there is no conversion that
806 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
810 // Attempt user-defined conversion.
811 OverloadCandidateSet Conversions(From->getExprLoc());
812 OverloadingResult UserDefResult
813 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
816 if (UserDefResult == OR_Success) {
817 ICS.setUserDefined();
818 // C++ [over.ics.user]p4:
819 // A conversion of an expression of class type to the same class
820 // type is given Exact Match rank, and a conversion of an
821 // expression of class type to a base class of that type is
822 // given Conversion rank, in spite of the fact that a copy
823 // constructor (i.e., a user-defined conversion function) is
824 // called for those cases.
825 if (CXXConstructorDecl *Constructor
826 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
828 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
830 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
831 if (Constructor->isCopyConstructor() &&
832 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
833 // Turn this into a "standard" conversion sequence, so that it
834 // gets ranked with standard conversion sequences.
836 ICS.Standard.setAsIdentityConversion();
837 ICS.Standard.setFromType(From->getType());
838 ICS.Standard.setAllToTypes(ToType);
839 ICS.Standard.CopyConstructor = Constructor;
840 if (ToCanon != FromCanon)
841 ICS.Standard.Second = ICK_Derived_To_Base;
845 // C++ [over.best.ics]p4:
846 // However, when considering the argument of a user-defined
847 // conversion function that is a candidate by 13.3.1.3 when
848 // invoked for the copying of the temporary in the second step
849 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
850 // 13.3.1.6 in all cases, only standard conversion sequences and
851 // ellipsis conversion sequences are allowed.
852 if (SuppressUserConversions && ICS.isUserDefined()) {
853 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
855 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
857 ICS.Ambiguous.setFromType(From->getType());
858 ICS.Ambiguous.setToType(ToType);
859 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
860 Cand != Conversions.end(); ++Cand)
862 ICS.Ambiguous.addConversion(Cand->Function);
864 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
870 bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
871 const InitializedEntity &Entity,
873 bool SuppressUserConversions,
874 bool AllowExplicitConversions,
875 bool InOverloadResolution,
877 ImplicitConversionSequence ICS
878 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
879 SuppressUserConversions,
880 AllowExplicitConversions,
881 InOverloadResolution,
883 if (ICS.isBad()) return true;
885 // Perform the actual conversion.
886 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
890 /// PerformImplicitConversion - Perform an implicit conversion of the
891 /// expression From to the type ToType. Returns the
892 /// converted expression. Flavor is the kind of conversion we're
893 /// performing, used in the error message. If @p AllowExplicit,
894 /// explicit user-defined conversions are permitted.
896 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
897 AssignmentAction Action, bool AllowExplicit) {
898 ImplicitConversionSequence ICS;
899 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
903 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
904 AssignmentAction Action, bool AllowExplicit,
905 ImplicitConversionSequence& ICS) {
906 ICS = clang::TryImplicitConversion(*this, From, ToType,
907 /*SuppressUserConversions=*/false,
909 /*InOverloadResolution=*/false,
911 return PerformImplicitConversion(From, ToType, ICS, Action);
914 /// \brief Determine whether the conversion from FromType to ToType is a valid
915 /// conversion that strips "noreturn" off the nested function type.
916 static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
917 QualType ToType, QualType &ResultTy) {
918 if (Context.hasSameUnqualifiedType(FromType, ToType))
921 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
922 // where F adds one of the following at most once:
924 // - a member pointer
926 CanQualType CanTo = Context.getCanonicalType(ToType);
927 CanQualType CanFrom = Context.getCanonicalType(FromType);
928 Type::TypeClass TyClass = CanTo->getTypeClass();
929 if (TyClass != CanFrom->getTypeClass()) return false;
930 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
931 if (TyClass == Type::Pointer) {
932 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
933 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
934 } else if (TyClass == Type::BlockPointer) {
935 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
936 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
937 } else if (TyClass == Type::MemberPointer) {
938 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
939 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
944 TyClass = CanTo->getTypeClass();
945 if (TyClass != CanFrom->getTypeClass()) return false;
946 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
950 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
951 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
952 if (!EInfo.getNoReturn()) return false;
954 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
955 assert(QualType(FromFn, 0).isCanonical());
956 if (QualType(FromFn, 0) != CanTo) return false;
962 /// \brief Determine whether the conversion from FromType to ToType is a valid
963 /// vector conversion.
965 /// \param ICK Will be set to the vector conversion kind, if this is a vector
967 static bool IsVectorConversion(ASTContext &Context, QualType FromType,
968 QualType ToType, ImplicitConversionKind &ICK) {
969 // We need at least one of these types to be a vector type to have a vector
971 if (!ToType->isVectorType() && !FromType->isVectorType())
974 // Identical types require no conversions.
975 if (Context.hasSameUnqualifiedType(FromType, ToType))
978 // There are no conversions between extended vector types, only identity.
979 if (ToType->isExtVectorType()) {
980 // There are no conversions between extended vector types other than the
981 // identity conversion.
982 if (FromType->isExtVectorType())
985 // Vector splat from any arithmetic type to a vector.
986 if (FromType->isArithmeticType()) {
987 ICK = ICK_Vector_Splat;
992 // We can perform the conversion between vector types in the following cases:
993 // 1)vector types are equivalent AltiVec and GCC vector types
994 // 2)lax vector conversions are permitted and the vector types are of the
996 if (ToType->isVectorType() && FromType->isVectorType()) {
997 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
998 (Context.getLangOptions().LaxVectorConversions &&
999 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
1000 ICK = ICK_Vector_Conversion;
1008 /// IsStandardConversion - Determines whether there is a standard
1009 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1010 /// expression From to the type ToType. Standard conversion sequences
1011 /// only consider non-class types; for conversions that involve class
1012 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1013 /// contain the standard conversion sequence required to perform this
1014 /// conversion and this routine will return true. Otherwise, this
1015 /// routine will return false and the value of SCS is unspecified.
1016 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1017 bool InOverloadResolution,
1018 StandardConversionSequence &SCS,
1020 QualType FromType = From->getType();
1022 // Standard conversions (C++ [conv])
1023 SCS.setAsIdentityConversion();
1024 SCS.DeprecatedStringLiteralToCharPtr = false;
1025 SCS.IncompatibleObjC = false;
1026 SCS.setFromType(FromType);
1027 SCS.CopyConstructor = 0;
1029 // There are no standard conversions for class types in C++, so
1030 // abort early. When overloading in C, however, we do permit
1031 if (FromType->isRecordType() || ToType->isRecordType()) {
1032 if (S.getLangOptions().CPlusPlus)
1035 // When we're overloading in C, we allow, as standard conversions,
1038 // The first conversion can be an lvalue-to-rvalue conversion,
1039 // array-to-pointer conversion, or function-to-pointer conversion
1042 if (FromType == S.Context.OverloadTy) {
1043 DeclAccessPair AccessPair;
1044 if (FunctionDecl *Fn
1045 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1047 // We were able to resolve the address of the overloaded function,
1048 // so we can convert to the type of that function.
1049 FromType = Fn->getType();
1051 // we can sometimes resolve &foo<int> regardless of ToType, so check
1052 // if the type matches (identity) or we are converting to bool
1053 if (!S.Context.hasSameUnqualifiedType(
1054 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1056 // if the function type matches except for [[noreturn]], it's ok
1057 if (!IsNoReturnConversion(S.Context, FromType,
1058 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1059 // otherwise, only a boolean conversion is standard
1060 if (!ToType->isBooleanType())
1064 // Check if the "from" expression is taking the address of an overloaded
1065 // function and recompute the FromType accordingly. Take advantage of the
1066 // fact that non-static member functions *must* have such an address-of
1068 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1069 if (Method && !Method->isStatic()) {
1070 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1071 "Non-unary operator on non-static member address");
1072 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1074 "Non-address-of operator on non-static member address");
1075 const Type *ClassType
1076 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1077 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1078 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1079 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1081 "Non-address-of operator for overloaded function expression");
1082 FromType = S.Context.getPointerType(FromType);
1085 // Check that we've computed the proper type after overload resolution.
1086 assert(S.Context.hasSameType(
1088 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1093 // Lvalue-to-rvalue conversion (C++ 4.1):
1094 // An lvalue (3.10) of a non-function, non-array type T can be
1095 // converted to an rvalue.
1096 bool argIsLValue = From->isLValue();
1098 !FromType->isFunctionType() && !FromType->isArrayType() &&
1099 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1100 SCS.First = ICK_Lvalue_To_Rvalue;
1102 // If T is a non-class type, the type of the rvalue is the
1103 // cv-unqualified version of T. Otherwise, the type of the rvalue
1104 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1105 // just strip the qualifiers because they don't matter.
1106 FromType = FromType.getUnqualifiedType();
1107 } else if (FromType->isArrayType()) {
1108 // Array-to-pointer conversion (C++ 4.2)
1109 SCS.First = ICK_Array_To_Pointer;
1111 // An lvalue or rvalue of type "array of N T" or "array of unknown
1112 // bound of T" can be converted to an rvalue of type "pointer to
1114 FromType = S.Context.getArrayDecayedType(FromType);
1116 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1117 // This conversion is deprecated. (C++ D.4).
1118 SCS.DeprecatedStringLiteralToCharPtr = true;
1120 // For the purpose of ranking in overload resolution
1121 // (13.3.3.1.1), this conversion is considered an
1122 // array-to-pointer conversion followed by a qualification
1123 // conversion (4.4). (C++ 4.2p2)
1124 SCS.Second = ICK_Identity;
1125 SCS.Third = ICK_Qualification;
1126 SCS.setAllToTypes(FromType);
1129 } else if (FromType->isFunctionType() && argIsLValue) {
1130 // Function-to-pointer conversion (C++ 4.3).
1131 SCS.First = ICK_Function_To_Pointer;
1133 // An lvalue of function type T can be converted to an rvalue of
1134 // type "pointer to T." The result is a pointer to the
1135 // function. (C++ 4.3p1).
1136 FromType = S.Context.getPointerType(FromType);
1138 // We don't require any conversions for the first step.
1139 SCS.First = ICK_Identity;
1141 SCS.setToType(0, FromType);
1143 // The second conversion can be an integral promotion, floating
1144 // point promotion, integral conversion, floating point conversion,
1145 // floating-integral conversion, pointer conversion,
1146 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1147 // For overloading in C, this can also be a "compatible-type"
1149 bool IncompatibleObjC = false;
1150 ImplicitConversionKind SecondICK = ICK_Identity;
1151 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1152 // The unqualified versions of the types are the same: there's no
1153 // conversion to do.
1154 SCS.Second = ICK_Identity;
1155 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1156 // Integral promotion (C++ 4.5).
1157 SCS.Second = ICK_Integral_Promotion;
1158 FromType = ToType.getUnqualifiedType();
1159 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1160 // Floating point promotion (C++ 4.6).
1161 SCS.Second = ICK_Floating_Promotion;
1162 FromType = ToType.getUnqualifiedType();
1163 } else if (S.IsComplexPromotion(FromType, ToType)) {
1164 // Complex promotion (Clang extension)
1165 SCS.Second = ICK_Complex_Promotion;
1166 FromType = ToType.getUnqualifiedType();
1167 } else if (ToType->isBooleanType() &&
1168 (FromType->isArithmeticType() ||
1169 FromType->isAnyPointerType() ||
1170 FromType->isBlockPointerType() ||
1171 FromType->isMemberPointerType() ||
1172 FromType->isNullPtrType())) {
1173 // Boolean conversions (C++ 4.12).
1174 SCS.Second = ICK_Boolean_Conversion;
1175 FromType = S.Context.BoolTy;
1176 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1177 ToType->isIntegralType(S.Context)) {
1178 // Integral conversions (C++ 4.7).
1179 SCS.Second = ICK_Integral_Conversion;
1180 FromType = ToType.getUnqualifiedType();
1181 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
1182 // Complex conversions (C99 6.3.1.6)
1183 SCS.Second = ICK_Complex_Conversion;
1184 FromType = ToType.getUnqualifiedType();
1185 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1186 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1187 // Complex-real conversions (C99 6.3.1.7)
1188 SCS.Second = ICK_Complex_Real;
1189 FromType = ToType.getUnqualifiedType();
1190 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1191 // Floating point conversions (C++ 4.8).
1192 SCS.Second = ICK_Floating_Conversion;
1193 FromType = ToType.getUnqualifiedType();
1194 } else if ((FromType->isRealFloatingType() &&
1195 ToType->isIntegralType(S.Context)) ||
1196 (FromType->isIntegralOrUnscopedEnumerationType() &&
1197 ToType->isRealFloatingType())) {
1198 // Floating-integral conversions (C++ 4.9).
1199 SCS.Second = ICK_Floating_Integral;
1200 FromType = ToType.getUnqualifiedType();
1201 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1202 SCS.Second = ICK_Block_Pointer_Conversion;
1203 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1204 FromType, IncompatibleObjC)) {
1205 // Pointer conversions (C++ 4.10).
1206 SCS.Second = ICK_Pointer_Conversion;
1207 SCS.IncompatibleObjC = IncompatibleObjC;
1208 FromType = FromType.getUnqualifiedType();
1209 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1210 InOverloadResolution, FromType)) {
1211 // Pointer to member conversions (4.11).
1212 SCS.Second = ICK_Pointer_Member;
1213 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
1214 SCS.Second = SecondICK;
1215 FromType = ToType.getUnqualifiedType();
1216 } else if (!S.getLangOptions().CPlusPlus &&
1217 S.Context.typesAreCompatible(ToType, FromType)) {
1218 // Compatible conversions (Clang extension for C function overloading)
1219 SCS.Second = ICK_Compatible_Conversion;
1220 FromType = ToType.getUnqualifiedType();
1221 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
1222 // Treat a conversion that strips "noreturn" as an identity conversion.
1223 SCS.Second = ICK_NoReturn_Adjustment;
1224 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1225 InOverloadResolution,
1227 SCS.Second = ICK_TransparentUnionConversion;
1230 // No second conversion required.
1231 SCS.Second = ICK_Identity;
1233 SCS.setToType(1, FromType);
1237 // The third conversion can be a qualification conversion (C++ 4p1).
1238 if (S.IsQualificationConversion(FromType, ToType, CStyle)) {
1239 SCS.Third = ICK_Qualification;
1241 CanonFrom = S.Context.getCanonicalType(FromType);
1242 CanonTo = S.Context.getCanonicalType(ToType);
1244 // No conversion required
1245 SCS.Third = ICK_Identity;
1247 // C++ [over.best.ics]p6:
1248 // [...] Any difference in top-level cv-qualification is
1249 // subsumed by the initialization itself and does not constitute
1250 // a conversion. [...]
1251 CanonFrom = S.Context.getCanonicalType(FromType);
1252 CanonTo = S.Context.getCanonicalType(ToType);
1253 if (CanonFrom.getLocalUnqualifiedType()
1254 == CanonTo.getLocalUnqualifiedType() &&
1255 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1256 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
1258 CanonFrom = CanonTo;
1261 SCS.setToType(2, FromType);
1263 // If we have not converted the argument type to the parameter type,
1264 // this is a bad conversion sequence.
1265 if (CanonFrom != CanonTo)
1272 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1274 bool InOverloadResolution,
1275 StandardConversionSequence &SCS,
1278 const RecordType *UT = ToType->getAsUnionType();
1279 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1281 // The field to initialize within the transparent union.
1282 RecordDecl *UD = UT->getDecl();
1283 // It's compatible if the expression matches any of the fields.
1284 for (RecordDecl::field_iterator it = UD->field_begin(),
1285 itend = UD->field_end();
1286 it != itend; ++it) {
1287 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, CStyle)) {
1288 ToType = it->getType();
1295 /// IsIntegralPromotion - Determines whether the conversion from the
1296 /// expression From (whose potentially-adjusted type is FromType) to
1297 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1298 /// sets PromotedType to the promoted type.
1299 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1300 const BuiltinType *To = ToType->getAs<BuiltinType>();
1301 // All integers are built-in.
1306 // An rvalue of type char, signed char, unsigned char, short int, or
1307 // unsigned short int can be converted to an rvalue of type int if
1308 // int can represent all the values of the source type; otherwise,
1309 // the source rvalue can be converted to an rvalue of type unsigned
1311 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1312 !FromType->isEnumeralType()) {
1313 if (// We can promote any signed, promotable integer type to an int
1314 (FromType->isSignedIntegerType() ||
1315 // We can promote any unsigned integer type whose size is
1316 // less than int to an int.
1317 (!FromType->isSignedIntegerType() &&
1318 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1319 return To->getKind() == BuiltinType::Int;
1322 return To->getKind() == BuiltinType::UInt;
1325 // C++0x [conv.prom]p3:
1326 // A prvalue of an unscoped enumeration type whose underlying type is not
1327 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1328 // following types that can represent all the values of the enumeration
1329 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1330 // unsigned int, long int, unsigned long int, long long int, or unsigned
1331 // long long int. If none of the types in that list can represent all the
1332 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1333 // type can be converted to an rvalue a prvalue of the extended integer type
1334 // with lowest integer conversion rank (4.13) greater than the rank of long
1335 // long in which all the values of the enumeration can be represented. If
1336 // there are two such extended types, the signed one is chosen.
1337 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1338 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1339 // provided for a scoped enumeration.
1340 if (FromEnumType->getDecl()->isScoped())
1343 // We have already pre-calculated the promotion type, so this is trivial.
1344 if (ToType->isIntegerType() &&
1345 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
1346 return Context.hasSameUnqualifiedType(ToType,
1347 FromEnumType->getDecl()->getPromotionType());
1350 // C++0x [conv.prom]p2:
1351 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1352 // to an rvalue a prvalue of the first of the following types that can
1353 // represent all the values of its underlying type: int, unsigned int,
1354 // long int, unsigned long int, long long int, or unsigned long long int.
1355 // If none of the types in that list can represent all the values of its
1356 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1357 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1359 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1360 ToType->isIntegerType()) {
1361 // Determine whether the type we're converting from is signed or
1364 uint64_t FromSize = Context.getTypeSize(FromType);
1366 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1367 FromIsSigned = true;
1369 // The types we'll try to promote to, in the appropriate
1370 // order. Try each of these types.
1371 QualType PromoteTypes[6] = {
1372 Context.IntTy, Context.UnsignedIntTy,
1373 Context.LongTy, Context.UnsignedLongTy ,
1374 Context.LongLongTy, Context.UnsignedLongLongTy
1376 for (int Idx = 0; Idx < 6; ++Idx) {
1377 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1378 if (FromSize < ToSize ||
1379 (FromSize == ToSize &&
1380 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1381 // We found the type that we can promote to. If this is the
1382 // type we wanted, we have a promotion. Otherwise, no
1384 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1389 // An rvalue for an integral bit-field (9.6) can be converted to an
1390 // rvalue of type int if int can represent all the values of the
1391 // bit-field; otherwise, it can be converted to unsigned int if
1392 // unsigned int can represent all the values of the bit-field. If
1393 // the bit-field is larger yet, no integral promotion applies to
1394 // it. If the bit-field has an enumerated type, it is treated as any
1395 // other value of that type for promotion purposes (C++ 4.5p3).
1396 // FIXME: We should delay checking of bit-fields until we actually perform the
1400 if (FieldDecl *MemberDecl = From->getBitField()) {
1402 if (FromType->isIntegralType(Context) &&
1403 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1404 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1405 ToSize = Context.getTypeSize(ToType);
1407 // Are we promoting to an int from a bitfield that fits in an int?
1408 if (BitWidth < ToSize ||
1409 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1410 return To->getKind() == BuiltinType::Int;
1413 // Are we promoting to an unsigned int from an unsigned bitfield
1414 // that fits into an unsigned int?
1415 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1416 return To->getKind() == BuiltinType::UInt;
1423 // An rvalue of type bool can be converted to an rvalue of type int,
1424 // with false becoming zero and true becoming one (C++ 4.5p4).
1425 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1432 /// IsFloatingPointPromotion - Determines whether the conversion from
1433 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1434 /// returns true and sets PromotedType to the promoted type.
1435 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1436 /// An rvalue of type float can be converted to an rvalue of type
1437 /// double. (C++ 4.6p1).
1438 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1439 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1440 if (FromBuiltin->getKind() == BuiltinType::Float &&
1441 ToBuiltin->getKind() == BuiltinType::Double)
1445 // When a float is promoted to double or long double, or a
1446 // double is promoted to long double [...].
1447 if (!getLangOptions().CPlusPlus &&
1448 (FromBuiltin->getKind() == BuiltinType::Float ||
1449 FromBuiltin->getKind() == BuiltinType::Double) &&
1450 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1457 /// \brief Determine if a conversion is a complex promotion.
1459 /// A complex promotion is defined as a complex -> complex conversion
1460 /// where the conversion between the underlying real types is a
1461 /// floating-point or integral promotion.
1462 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1463 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1467 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1471 return IsFloatingPointPromotion(FromComplex->getElementType(),
1472 ToComplex->getElementType()) ||
1473 IsIntegralPromotion(0, FromComplex->getElementType(),
1474 ToComplex->getElementType());
1477 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1478 /// the pointer type FromPtr to a pointer to type ToPointee, with the
1479 /// same type qualifiers as FromPtr has on its pointee type. ToType,
1480 /// if non-empty, will be a pointer to ToType that may or may not have
1481 /// the right set of qualifiers on its pointee.
1483 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1484 QualType ToPointee, QualType ToType,
1485 ASTContext &Context) {
1486 assert((FromPtr->getTypeClass() == Type::Pointer ||
1487 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1488 "Invalid similarly-qualified pointer type");
1490 /// \brief Conversions to 'id' subsume cv-qualifier conversions.
1491 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1492 return ToType.getUnqualifiedType();
1494 QualType CanonFromPointee
1495 = Context.getCanonicalType(FromPtr->getPointeeType());
1496 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1497 Qualifiers Quals = CanonFromPointee.getQualifiers();
1499 // Exact qualifier match -> return the pointer type we're converting to.
1500 if (CanonToPointee.getLocalQualifiers() == Quals) {
1501 // ToType is exactly what we need. Return it.
1502 if (!ToType.isNull())
1503 return ToType.getUnqualifiedType();
1505 // Build a pointer to ToPointee. It has the right qualifiers
1507 if (isa<ObjCObjectPointerType>(ToType))
1508 return Context.getObjCObjectPointerType(ToPointee);
1509 return Context.getPointerType(ToPointee);
1512 // Just build a canonical type that has the right qualifiers.
1513 QualType QualifiedCanonToPointee
1514 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1516 if (isa<ObjCObjectPointerType>(ToType))
1517 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1518 return Context.getPointerType(QualifiedCanonToPointee);
1521 static bool isNullPointerConstantForConversion(Expr *Expr,
1522 bool InOverloadResolution,
1523 ASTContext &Context) {
1524 // Handle value-dependent integral null pointer constants correctly.
1525 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1526 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1527 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1528 return !InOverloadResolution;
1530 return Expr->isNullPointerConstant(Context,
1531 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1532 : Expr::NPC_ValueDependentIsNull);
1535 /// IsPointerConversion - Determines whether the conversion of the
1536 /// expression From, which has the (possibly adjusted) type FromType,
1537 /// can be converted to the type ToType via a pointer conversion (C++
1538 /// 4.10). If so, returns true and places the converted type (that
1539 /// might differ from ToType in its cv-qualifiers at some level) into
1542 /// This routine also supports conversions to and from block pointers
1543 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
1544 /// pointers to interfaces. FIXME: Once we've determined the
1545 /// appropriate overloading rules for Objective-C, we may want to
1546 /// split the Objective-C checks into a different routine; however,
1547 /// GCC seems to consider all of these conversions to be pointer
1548 /// conversions, so for now they live here. IncompatibleObjC will be
1549 /// set if the conversion is an allowed Objective-C conversion that
1550 /// should result in a warning.
1551 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1552 bool InOverloadResolution,
1553 QualType& ConvertedType,
1554 bool &IncompatibleObjC) {
1555 IncompatibleObjC = false;
1556 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1560 // Conversion from a null pointer constant to any Objective-C pointer type.
1561 if (ToType->isObjCObjectPointerType() &&
1562 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1563 ConvertedType = ToType;
1567 // Blocks: Block pointers can be converted to void*.
1568 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
1569 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
1570 ConvertedType = ToType;
1573 // Blocks: A null pointer constant can be converted to a block
1575 if (ToType->isBlockPointerType() &&
1576 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1577 ConvertedType = ToType;
1581 // If the left-hand-side is nullptr_t, the right side can be a null
1582 // pointer constant.
1583 if (ToType->isNullPtrType() &&
1584 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1585 ConvertedType = ToType;
1589 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
1593 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
1594 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
1595 ConvertedType = ToType;
1599 // Beyond this point, both types need to be pointers
1600 // , including objective-c pointers.
1601 QualType ToPointeeType = ToTypePtr->getPointeeType();
1602 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1603 ConvertedType = BuildSimilarlyQualifiedPointerType(
1604 FromType->getAs<ObjCObjectPointerType>(),
1609 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
1613 QualType FromPointeeType = FromTypePtr->getPointeeType();
1615 // If the unqualified pointee types are the same, this can't be a
1616 // pointer conversion, so don't do all of the work below.
1617 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1620 // An rvalue of type "pointer to cv T," where T is an object type,
1621 // can be converted to an rvalue of type "pointer to cv void" (C++
1623 if (FromPointeeType->isIncompleteOrObjectType() &&
1624 ToPointeeType->isVoidType()) {
1625 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1631 // MSVC allows implicit function to void* type conversion.
1632 if (getLangOptions().Microsoft && FromPointeeType->isFunctionType() &&
1633 ToPointeeType->isVoidType()) {
1634 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1640 // When we're overloading in C, we allow a special kind of pointer
1641 // conversion for compatible-but-not-identical pointee types.
1642 if (!getLangOptions().CPlusPlus &&
1643 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
1644 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1650 // C++ [conv.ptr]p3:
1652 // An rvalue of type "pointer to cv D," where D is a class type,
1653 // can be converted to an rvalue of type "pointer to cv B," where
1654 // B is a base class (clause 10) of D. If B is an inaccessible
1655 // (clause 11) or ambiguous (10.2) base class of D, a program that
1656 // necessitates this conversion is ill-formed. The result of the
1657 // conversion is a pointer to the base class sub-object of the
1658 // derived class object. The null pointer value is converted to
1659 // the null pointer value of the destination type.
1661 // Note that we do not check for ambiguity or inaccessibility
1662 // here. That is handled by CheckPointerConversion.
1663 if (getLangOptions().CPlusPlus &&
1664 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1665 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
1666 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
1667 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
1668 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1674 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1675 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1676 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1685 /// \brief Adopt the given qualifiers for the given type.
1686 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1687 Qualifiers TQs = T.getQualifiers();
1689 // Check whether qualifiers already match.
1693 if (Qs.compatiblyIncludes(TQs))
1694 return Context.getQualifiedType(T, Qs);
1696 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1699 /// isObjCPointerConversion - Determines whether this is an
1700 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1701 /// with the same arguments and return values.
1702 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
1703 QualType& ConvertedType,
1704 bool &IncompatibleObjC) {
1705 if (!getLangOptions().ObjC1)
1708 // The set of qualifiers on the type we're converting from.
1709 Qualifiers FromQualifiers = FromType.getQualifiers();
1711 // First, we handle all conversions on ObjC object pointer types.
1712 const ObjCObjectPointerType* ToObjCPtr =
1713 ToType->getAs<ObjCObjectPointerType>();
1714 const ObjCObjectPointerType *FromObjCPtr =
1715 FromType->getAs<ObjCObjectPointerType>();
1717 if (ToObjCPtr && FromObjCPtr) {
1718 // If the pointee types are the same (ignoring qualifications),
1719 // then this is not a pointer conversion.
1720 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1721 FromObjCPtr->getPointeeType()))
1724 // Check for compatible
1725 // Objective C++: We're able to convert between "id" or "Class" and a
1726 // pointer to any interface (in both directions).
1727 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
1728 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
1731 // Conversions with Objective-C's id<...>.
1732 if ((FromObjCPtr->isObjCQualifiedIdType() ||
1733 ToObjCPtr->isObjCQualifiedIdType()) &&
1734 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
1735 /*compare=*/false)) {
1736 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
1739 // Objective C++: We're able to convert from a pointer to an
1740 // interface to a pointer to a different interface.
1741 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1742 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1743 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1744 if (getLangOptions().CPlusPlus && LHS && RHS &&
1745 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1746 FromObjCPtr->getPointeeType()))
1748 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1749 ToObjCPtr->getPointeeType(),
1751 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
1755 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1756 // Okay: this is some kind of implicit downcast of Objective-C
1757 // interfaces, which is permitted. However, we're going to
1758 // complain about it.
1759 IncompatibleObjC = true;
1760 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1761 ToObjCPtr->getPointeeType(),
1763 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
1767 // Beyond this point, both types need to be C pointers or block pointers.
1768 QualType ToPointeeType;
1769 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
1770 ToPointeeType = ToCPtr->getPointeeType();
1771 else if (const BlockPointerType *ToBlockPtr =
1772 ToType->getAs<BlockPointerType>()) {
1773 // Objective C++: We're able to convert from a pointer to any object
1774 // to a block pointer type.
1775 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1776 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
1779 ToPointeeType = ToBlockPtr->getPointeeType();
1781 else if (FromType->getAs<BlockPointerType>() &&
1782 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1783 // Objective C++: We're able to convert from a block pointer type to a
1784 // pointer to any object.
1785 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
1791 QualType FromPointeeType;
1792 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
1793 FromPointeeType = FromCPtr->getPointeeType();
1794 else if (const BlockPointerType *FromBlockPtr =
1795 FromType->getAs<BlockPointerType>())
1796 FromPointeeType = FromBlockPtr->getPointeeType();
1800 // If we have pointers to pointers, recursively check whether this
1801 // is an Objective-C conversion.
1802 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1803 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1804 IncompatibleObjC)) {
1805 // We always complain about this conversion.
1806 IncompatibleObjC = true;
1807 ConvertedType = Context.getPointerType(ConvertedType);
1808 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
1811 // Allow conversion of pointee being objective-c pointer to another one;
1813 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1814 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1815 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1816 IncompatibleObjC)) {
1817 ConvertedType = Context.getPointerType(ConvertedType);
1818 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
1822 // If we have pointers to functions or blocks, check whether the only
1823 // differences in the argument and result types are in Objective-C
1824 // pointer conversions. If so, we permit the conversion (but
1825 // complain about it).
1826 const FunctionProtoType *FromFunctionType
1827 = FromPointeeType->getAs<FunctionProtoType>();
1828 const FunctionProtoType *ToFunctionType
1829 = ToPointeeType->getAs<FunctionProtoType>();
1830 if (FromFunctionType && ToFunctionType) {
1831 // If the function types are exactly the same, this isn't an
1832 // Objective-C pointer conversion.
1833 if (Context.getCanonicalType(FromPointeeType)
1834 == Context.getCanonicalType(ToPointeeType))
1837 // Perform the quick checks that will tell us whether these
1838 // function types are obviously different.
1839 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1840 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1841 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1844 bool HasObjCConversion = false;
1845 if (Context.getCanonicalType(FromFunctionType->getResultType())
1846 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1847 // Okay, the types match exactly. Nothing to do.
1848 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1849 ToFunctionType->getResultType(),
1850 ConvertedType, IncompatibleObjC)) {
1851 // Okay, we have an Objective-C pointer conversion.
1852 HasObjCConversion = true;
1854 // Function types are too different. Abort.
1858 // Check argument types.
1859 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1860 ArgIdx != NumArgs; ++ArgIdx) {
1861 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1862 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1863 if (Context.getCanonicalType(FromArgType)
1864 == Context.getCanonicalType(ToArgType)) {
1865 // Okay, the types match exactly. Nothing to do.
1866 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1867 ConvertedType, IncompatibleObjC)) {
1868 // Okay, we have an Objective-C pointer conversion.
1869 HasObjCConversion = true;
1871 // Argument types are too different. Abort.
1876 if (HasObjCConversion) {
1877 // We had an Objective-C conversion. Allow this pointer
1878 // conversion, but complain about it.
1879 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
1880 IncompatibleObjC = true;
1888 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
1889 QualType& ConvertedType) {
1890 QualType ToPointeeType;
1891 if (const BlockPointerType *ToBlockPtr =
1892 ToType->getAs<BlockPointerType>())
1893 ToPointeeType = ToBlockPtr->getPointeeType();
1897 QualType FromPointeeType;
1898 if (const BlockPointerType *FromBlockPtr =
1899 FromType->getAs<BlockPointerType>())
1900 FromPointeeType = FromBlockPtr->getPointeeType();
1903 // We have pointer to blocks, check whether the only
1904 // differences in the argument and result types are in Objective-C
1905 // pointer conversions. If so, we permit the conversion.
1907 const FunctionProtoType *FromFunctionType
1908 = FromPointeeType->getAs<FunctionProtoType>();
1909 const FunctionProtoType *ToFunctionType
1910 = ToPointeeType->getAs<FunctionProtoType>();
1912 if (!FromFunctionType || !ToFunctionType)
1915 if (Context.hasSameType(FromPointeeType, ToPointeeType))
1918 // Perform the quick checks that will tell us whether these
1919 // function types are obviously different.
1920 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1921 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
1924 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
1925 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
1926 if (FromEInfo != ToEInfo)
1929 bool IncompatibleObjC = false;
1930 if (Context.hasSameType(FromFunctionType->getResultType(),
1931 ToFunctionType->getResultType())) {
1932 // Okay, the types match exactly. Nothing to do.
1934 QualType RHS = FromFunctionType->getResultType();
1935 QualType LHS = ToFunctionType->getResultType();
1936 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
1937 !RHS.hasQualifiers() && LHS.hasQualifiers())
1938 LHS = LHS.getUnqualifiedType();
1940 if (Context.hasSameType(RHS,LHS)) {
1942 } else if (isObjCPointerConversion(RHS, LHS,
1943 ConvertedType, IncompatibleObjC)) {
1944 if (IncompatibleObjC)
1946 // Okay, we have an Objective-C pointer conversion.
1952 // Check argument types.
1953 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1954 ArgIdx != NumArgs; ++ArgIdx) {
1955 IncompatibleObjC = false;
1956 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1957 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1958 if (Context.hasSameType(FromArgType, ToArgType)) {
1959 // Okay, the types match exactly. Nothing to do.
1960 } else if (isObjCPointerConversion(ToArgType, FromArgType,
1961 ConvertedType, IncompatibleObjC)) {
1962 if (IncompatibleObjC)
1964 // Okay, we have an Objective-C pointer conversion.
1966 // Argument types are too different. Abort.
1969 ConvertedType = ToType;
1973 /// FunctionArgTypesAreEqual - This routine checks two function proto types
1974 /// for equlity of their argument types. Caller has already checked that
1975 /// they have same number of arguments. This routine assumes that Objective-C
1976 /// pointer types which only differ in their protocol qualifiers are equal.
1977 bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
1978 const FunctionProtoType *NewType) {
1979 if (!getLangOptions().ObjC1)
1980 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1981 NewType->arg_type_begin());
1983 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1984 N = NewType->arg_type_begin(),
1985 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1986 QualType ToType = (*O);
1987 QualType FromType = (*N);
1988 if (ToType != FromType) {
1989 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1990 if (const PointerType *PTFr = FromType->getAs<PointerType>())
1991 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1992 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1993 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1994 PTFr->getPointeeType()->isObjCQualifiedClassType()))
1997 else if (const ObjCObjectPointerType *PTTo =
1998 ToType->getAs<ObjCObjectPointerType>()) {
1999 if (const ObjCObjectPointerType *PTFr =
2000 FromType->getAs<ObjCObjectPointerType>())
2001 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
2010 /// CheckPointerConversion - Check the pointer conversion from the
2011 /// expression From to the type ToType. This routine checks for
2012 /// ambiguous or inaccessible derived-to-base pointer
2013 /// conversions for which IsPointerConversion has already returned
2014 /// true. It returns true and produces a diagnostic if there was an
2015 /// error, or returns false otherwise.
2016 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2018 CXXCastPath& BasePath,
2019 bool IgnoreBaseAccess) {
2020 QualType FromType = From->getType();
2021 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2025 if (!IsCStyleOrFunctionalCast &&
2026 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2027 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2028 DiagRuntimeBehavior(From->getExprLoc(), From,
2029 PDiag(diag::warn_impcast_bool_to_null_pointer)
2030 << ToType << From->getSourceRange());
2032 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
2033 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2034 QualType FromPointeeType = FromPtrType->getPointeeType(),
2035 ToPointeeType = ToPtrType->getPointeeType();
2037 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2038 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2039 // We must have a derived-to-base conversion. Check an
2040 // ambiguous or inaccessible conversion.
2041 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2043 From->getSourceRange(), &BasePath,
2047 // The conversion was successful.
2048 Kind = CK_DerivedToBase;
2051 if (const ObjCObjectPointerType *FromPtrType =
2052 FromType->getAs<ObjCObjectPointerType>()) {
2053 if (const ObjCObjectPointerType *ToPtrType =
2054 ToType->getAs<ObjCObjectPointerType>()) {
2055 // Objective-C++ conversions are always okay.
2056 // FIXME: We should have a different class of conversions for the
2057 // Objective-C++ implicit conversions.
2058 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2063 // We shouldn't fall into this case unless it's valid for other
2065 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2066 Kind = CK_NullToPointer;
2071 /// IsMemberPointerConversion - Determines whether the conversion of the
2072 /// expression From, which has the (possibly adjusted) type FromType, can be
2073 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2074 /// If so, returns true and places the converted type (that might differ from
2075 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2076 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2078 bool InOverloadResolution,
2079 QualType &ConvertedType) {
2080 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2084 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2085 if (From->isNullPointerConstant(Context,
2086 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2087 : Expr::NPC_ValueDependentIsNull)) {
2088 ConvertedType = ToType;
2092 // Otherwise, both types have to be member pointers.
2093 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2097 // A pointer to member of B can be converted to a pointer to member of D,
2098 // where D is derived from B (C++ 4.11p2).
2099 QualType FromClass(FromTypePtr->getClass(), 0);
2100 QualType ToClass(ToTypePtr->getClass(), 0);
2102 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2103 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2104 IsDerivedFrom(ToClass, FromClass)) {
2105 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2106 ToClass.getTypePtr());
2113 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2114 /// expression From to the type ToType. This routine checks for ambiguous or
2115 /// virtual or inaccessible base-to-derived member pointer conversions
2116 /// for which IsMemberPointerConversion has already returned true. It returns
2117 /// true and produces a diagnostic if there was an error, or returns false
2119 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2121 CXXCastPath &BasePath,
2122 bool IgnoreBaseAccess) {
2123 QualType FromType = From->getType();
2124 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2126 // This must be a null pointer to member pointer conversion
2127 assert(From->isNullPointerConstant(Context,
2128 Expr::NPC_ValueDependentIsNull) &&
2129 "Expr must be null pointer constant!");
2130 Kind = CK_NullToMemberPointer;
2134 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2135 assert(ToPtrType && "No member pointer cast has a target type "
2136 "that is not a member pointer.");
2138 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2139 QualType ToClass = QualType(ToPtrType->getClass(), 0);
2141 // FIXME: What about dependent types?
2142 assert(FromClass->isRecordType() && "Pointer into non-class.");
2143 assert(ToClass->isRecordType() && "Pointer into non-class.");
2145 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2146 /*DetectVirtual=*/true);
2147 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2148 assert(DerivationOkay &&
2149 "Should not have been called if derivation isn't OK.");
2150 (void)DerivationOkay;
2152 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2153 getUnqualifiedType())) {
2154 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2155 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2156 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2160 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2161 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2162 << FromClass << ToClass << QualType(VBase, 0)
2163 << From->getSourceRange();
2167 if (!IgnoreBaseAccess)
2168 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2170 diag::err_downcast_from_inaccessible_base);
2172 // Must be a base to derived member conversion.
2173 BuildBasePathArray(Paths, BasePath);
2174 Kind = CK_BaseToDerivedMemberPointer;
2178 /// IsQualificationConversion - Determines whether the conversion from
2179 /// an rvalue of type FromType to ToType is a qualification conversion
2182 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2184 FromType = Context.getCanonicalType(FromType);
2185 ToType = Context.getCanonicalType(ToType);
2187 // If FromType and ToType are the same type, this is not a
2188 // qualification conversion.
2189 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2193 // A conversion can add cv-qualifiers at levels other than the first
2194 // in multi-level pointers, subject to the following rules: [...]
2195 bool PreviousToQualsIncludeConst = true;
2196 bool UnwrappedAnyPointer = false;
2197 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2198 // Within each iteration of the loop, we check the qualifiers to
2199 // determine if this still looks like a qualification
2200 // conversion. Then, if all is well, we unwrap one more level of
2201 // pointers or pointers-to-members and do it all again
2202 // until there are no more pointers or pointers-to-members left to
2204 UnwrappedAnyPointer = true;
2206 Qualifiers FromQuals = FromType.getQualifiers();
2207 Qualifiers ToQuals = ToType.getQualifiers();
2209 // Allow addition/removal of GC attributes but not changing GC attributes.
2210 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2211 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2212 FromQuals.removeObjCGCAttr();
2213 ToQuals.removeObjCGCAttr();
2216 // -- for every j > 0, if const is in cv 1,j then const is in cv
2217 // 2,j, and similarly for volatile.
2218 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2221 // -- if the cv 1,j and cv 2,j are different, then const is in
2222 // every cv for 0 < k < j.
2223 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2224 && !PreviousToQualsIncludeConst)
2227 // Keep track of whether all prior cv-qualifiers in the "to" type
2229 PreviousToQualsIncludeConst
2230 = PreviousToQualsIncludeConst && ToQuals.hasConst();
2233 // We are left with FromType and ToType being the pointee types
2234 // after unwrapping the original FromType and ToType the same number
2235 // of types. If we unwrapped any pointers, and if FromType and
2236 // ToType have the same unqualified type (since we checked
2237 // qualifiers above), then this is a qualification conversion.
2238 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2241 /// Determines whether there is a user-defined conversion sequence
2242 /// (C++ [over.ics.user]) that converts expression From to the type
2243 /// ToType. If such a conversion exists, User will contain the
2244 /// user-defined conversion sequence that performs such a conversion
2245 /// and this routine will return true. Otherwise, this routine returns
2246 /// false and User is unspecified.
2248 /// \param AllowExplicit true if the conversion should consider C++0x
2249 /// "explicit" conversion functions as well as non-explicit conversion
2250 /// functions (C++0x [class.conv.fct]p2).
2251 static OverloadingResult
2252 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2253 UserDefinedConversionSequence& User,
2254 OverloadCandidateSet& CandidateSet,
2255 bool AllowExplicit) {
2256 // Whether we will only visit constructors.
2257 bool ConstructorsOnly = false;
2259 // If the type we are conversion to is a class type, enumerate its
2261 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
2262 // C++ [over.match.ctor]p1:
2263 // When objects of class type are direct-initialized (8.5), or
2264 // copy-initialized from an expression of the same or a
2265 // derived class type (8.5), overload resolution selects the
2266 // constructor. [...] For copy-initialization, the candidate
2267 // functions are all the converting constructors (12.3.1) of
2268 // that class. The argument list is the expression-list within
2269 // the parentheses of the initializer.
2270 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
2271 (From->getType()->getAs<RecordType>() &&
2272 S.IsDerivedFrom(From->getType(), ToType)))
2273 ConstructorsOnly = true;
2275 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2276 // RequireCompleteType may have returned true due to some invalid decl
2277 // during template instantiation, but ToType may be complete enough now
2278 // to try to recover.
2279 if (ToType->isIncompleteType()) {
2280 // We're not going to find any constructors.
2281 } else if (CXXRecordDecl *ToRecordDecl
2282 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
2283 DeclContext::lookup_iterator Con, ConEnd;
2284 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
2285 Con != ConEnd; ++Con) {
2286 NamedDecl *D = *Con;
2287 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2289 // Find the constructor (which may be a template).
2290 CXXConstructorDecl *Constructor = 0;
2291 FunctionTemplateDecl *ConstructorTmpl
2292 = dyn_cast<FunctionTemplateDecl>(D);
2293 if (ConstructorTmpl)
2295 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2297 Constructor = cast<CXXConstructorDecl>(D);
2299 if (!Constructor->isInvalidDecl() &&
2300 Constructor->isConvertingConstructor(AllowExplicit)) {
2301 if (ConstructorTmpl)
2302 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2304 &From, 1, CandidateSet,
2305 /*SuppressUserConversions=*/
2308 // Allow one user-defined conversion when user specifies a
2309 // From->ToType conversion via an static cast (c-style, etc).
2310 S.AddOverloadCandidate(Constructor, FoundDecl,
2311 &From, 1, CandidateSet,
2312 /*SuppressUserConversions=*/
2319 // Enumerate conversion functions, if we're allowed to.
2320 if (ConstructorsOnly) {
2321 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2322 S.PDiag(0) << From->getSourceRange())) {
2323 // No conversion functions from incomplete types.
2324 } else if (const RecordType *FromRecordType
2325 = From->getType()->getAs<RecordType>()) {
2326 if (CXXRecordDecl *FromRecordDecl
2327 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2328 // Add all of the conversion functions as candidates.
2329 const UnresolvedSetImpl *Conversions
2330 = FromRecordDecl->getVisibleConversionFunctions();
2331 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2332 E = Conversions->end(); I != E; ++I) {
2333 DeclAccessPair FoundDecl = I.getPair();
2334 NamedDecl *D = FoundDecl.getDecl();
2335 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2336 if (isa<UsingShadowDecl>(D))
2337 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2339 CXXConversionDecl *Conv;
2340 FunctionTemplateDecl *ConvTemplate;
2341 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2342 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2344 Conv = cast<CXXConversionDecl>(D);
2346 if (AllowExplicit || !Conv->isExplicit()) {
2348 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2349 ActingContext, From, ToType,
2352 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2353 From, ToType, CandidateSet);
2359 OverloadCandidateSet::iterator Best;
2360 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2362 // Record the standard conversion we used and the conversion function.
2363 if (CXXConstructorDecl *Constructor
2364 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2365 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2367 // C++ [over.ics.user]p1:
2368 // If the user-defined conversion is specified by a
2369 // constructor (12.3.1), the initial standard conversion
2370 // sequence converts the source type to the type required by
2371 // the argument of the constructor.
2373 QualType ThisType = Constructor->getThisType(S.Context);
2374 if (Best->Conversions[0].isEllipsis())
2375 User.EllipsisConversion = true;
2377 User.Before = Best->Conversions[0].Standard;
2378 User.EllipsisConversion = false;
2380 User.ConversionFunction = Constructor;
2381 User.FoundConversionFunction = Best->FoundDecl.getDecl();
2382 User.After.setAsIdentityConversion();
2383 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2384 User.After.setAllToTypes(ToType);
2386 } else if (CXXConversionDecl *Conversion
2387 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2388 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2390 // C++ [over.ics.user]p1:
2392 // [...] If the user-defined conversion is specified by a
2393 // conversion function (12.3.2), the initial standard
2394 // conversion sequence converts the source type to the
2395 // implicit object parameter of the conversion function.
2396 User.Before = Best->Conversions[0].Standard;
2397 User.ConversionFunction = Conversion;
2398 User.FoundConversionFunction = Best->FoundDecl.getDecl();
2399 User.EllipsisConversion = false;
2401 // C++ [over.ics.user]p2:
2402 // The second standard conversion sequence converts the
2403 // result of the user-defined conversion to the target type
2404 // for the sequence. Since an implicit conversion sequence
2405 // is an initialization, the special rules for
2406 // initialization by user-defined conversion apply when
2407 // selecting the best user-defined conversion for a
2408 // user-defined conversion sequence (see 13.3.3 and
2410 User.After = Best->FinalConversion;
2413 llvm_unreachable("Not a constructor or conversion function?");
2414 return OR_No_Viable_Function;
2417 case OR_No_Viable_Function:
2418 return OR_No_Viable_Function;
2420 // No conversion here! We're done.
2424 return OR_Ambiguous;
2427 return OR_No_Viable_Function;
2431 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
2432 ImplicitConversionSequence ICS;
2433 OverloadCandidateSet CandidateSet(From->getExprLoc());
2434 OverloadingResult OvResult =
2435 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
2436 CandidateSet, false);
2437 if (OvResult == OR_Ambiguous)
2438 Diag(From->getSourceRange().getBegin(),
2439 diag::err_typecheck_ambiguous_condition)
2440 << From->getType() << ToType << From->getSourceRange();
2441 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2442 Diag(From->getSourceRange().getBegin(),
2443 diag::err_typecheck_nonviable_condition)
2444 << From->getType() << ToType << From->getSourceRange();
2447 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
2451 /// CompareImplicitConversionSequences - Compare two implicit
2452 /// conversion sequences to determine whether one is better than the
2453 /// other or if they are indistinguishable (C++ 13.3.3.2).
2454 static ImplicitConversionSequence::CompareKind
2455 CompareImplicitConversionSequences(Sema &S,
2456 const ImplicitConversionSequence& ICS1,
2457 const ImplicitConversionSequence& ICS2)
2459 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2460 // conversion sequences (as defined in 13.3.3.1)
2461 // -- a standard conversion sequence (13.3.3.1.1) is a better
2462 // conversion sequence than a user-defined conversion sequence or
2463 // an ellipsis conversion sequence, and
2464 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2465 // conversion sequence than an ellipsis conversion sequence
2468 // C++0x [over.best.ics]p10:
2469 // For the purpose of ranking implicit conversion sequences as
2470 // described in 13.3.3.2, the ambiguous conversion sequence is
2471 // treated as a user-defined sequence that is indistinguishable
2472 // from any other user-defined conversion sequence.
2473 if (ICS1.getKindRank() < ICS2.getKindRank())
2474 return ImplicitConversionSequence::Better;
2475 else if (ICS2.getKindRank() < ICS1.getKindRank())
2476 return ImplicitConversionSequence::Worse;
2478 // The following checks require both conversion sequences to be of
2480 if (ICS1.getKind() != ICS2.getKind())
2481 return ImplicitConversionSequence::Indistinguishable;
2483 // Two implicit conversion sequences of the same form are
2484 // indistinguishable conversion sequences unless one of the
2485 // following rules apply: (C++ 13.3.3.2p3):
2486 if (ICS1.isStandard())
2487 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
2488 else if (ICS1.isUserDefined()) {
2489 // User-defined conversion sequence U1 is a better conversion
2490 // sequence than another user-defined conversion sequence U2 if
2491 // they contain the same user-defined conversion function or
2492 // constructor and if the second standard conversion sequence of
2493 // U1 is better than the second standard conversion sequence of
2494 // U2 (C++ 13.3.3.2p3).
2495 if (ICS1.UserDefined.ConversionFunction ==
2496 ICS2.UserDefined.ConversionFunction)
2497 return CompareStandardConversionSequences(S,
2498 ICS1.UserDefined.After,
2499 ICS2.UserDefined.After);
2502 return ImplicitConversionSequence::Indistinguishable;
2505 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2506 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2508 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2509 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2512 return Context.hasSameUnqualifiedType(T1, T2);
2515 // Per 13.3.3.2p3, compare the given standard conversion sequences to
2516 // determine if one is a proper subset of the other.
2517 static ImplicitConversionSequence::CompareKind
2518 compareStandardConversionSubsets(ASTContext &Context,
2519 const StandardConversionSequence& SCS1,
2520 const StandardConversionSequence& SCS2) {
2521 ImplicitConversionSequence::CompareKind Result
2522 = ImplicitConversionSequence::Indistinguishable;
2524 // the identity conversion sequence is considered to be a subsequence of
2525 // any non-identity conversion sequence
2526 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2527 return ImplicitConversionSequence::Better;
2528 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2529 return ImplicitConversionSequence::Worse;
2531 if (SCS1.Second != SCS2.Second) {
2532 if (SCS1.Second == ICK_Identity)
2533 Result = ImplicitConversionSequence::Better;
2534 else if (SCS2.Second == ICK_Identity)
2535 Result = ImplicitConversionSequence::Worse;
2537 return ImplicitConversionSequence::Indistinguishable;
2538 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
2539 return ImplicitConversionSequence::Indistinguishable;
2541 if (SCS1.Third == SCS2.Third) {
2542 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2543 : ImplicitConversionSequence::Indistinguishable;
2546 if (SCS1.Third == ICK_Identity)
2547 return Result == ImplicitConversionSequence::Worse
2548 ? ImplicitConversionSequence::Indistinguishable
2549 : ImplicitConversionSequence::Better;
2551 if (SCS2.Third == ICK_Identity)
2552 return Result == ImplicitConversionSequence::Better
2553 ? ImplicitConversionSequence::Indistinguishable
2554 : ImplicitConversionSequence::Worse;
2556 return ImplicitConversionSequence::Indistinguishable;
2559 /// \brief Determine whether one of the given reference bindings is better
2560 /// than the other based on what kind of bindings they are.
2561 static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2562 const StandardConversionSequence &SCS2) {
2563 // C++0x [over.ics.rank]p3b4:
2564 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2565 // implicit object parameter of a non-static member function declared
2566 // without a ref-qualifier, and *either* S1 binds an rvalue reference
2567 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
2568 // lvalue reference to a function lvalue and S2 binds an rvalue
2571 // FIXME: Rvalue references. We're going rogue with the above edits,
2572 // because the semantics in the current C++0x working paper (N3225 at the
2573 // time of this writing) break the standard definition of std::forward
2574 // and std::reference_wrapper when dealing with references to functions.
2575 // Proposed wording changes submitted to CWG for consideration.
2576 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2577 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2580 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2581 SCS2.IsLvalueReference) ||
2582 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2583 !SCS2.IsLvalueReference);
2586 /// CompareStandardConversionSequences - Compare two standard
2587 /// conversion sequences to determine whether one is better than the
2588 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
2589 static ImplicitConversionSequence::CompareKind
2590 CompareStandardConversionSequences(Sema &S,
2591 const StandardConversionSequence& SCS1,
2592 const StandardConversionSequence& SCS2)
2594 // Standard conversion sequence S1 is a better conversion sequence
2595 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2597 // -- S1 is a proper subsequence of S2 (comparing the conversion
2598 // sequences in the canonical form defined by 13.3.3.1.1,
2599 // excluding any Lvalue Transformation; the identity conversion
2600 // sequence is considered to be a subsequence of any
2601 // non-identity conversion sequence) or, if not that,
2602 if (ImplicitConversionSequence::CompareKind CK
2603 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
2606 // -- the rank of S1 is better than the rank of S2 (by the rules
2607 // defined below), or, if not that,
2608 ImplicitConversionRank Rank1 = SCS1.getRank();
2609 ImplicitConversionRank Rank2 = SCS2.getRank();
2611 return ImplicitConversionSequence::Better;
2612 else if (Rank2 < Rank1)
2613 return ImplicitConversionSequence::Worse;
2615 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2616 // are indistinguishable unless one of the following rules
2619 // A conversion that is not a conversion of a pointer, or
2620 // pointer to member, to bool is better than another conversion
2621 // that is such a conversion.
2622 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2623 return SCS2.isPointerConversionToBool()
2624 ? ImplicitConversionSequence::Better
2625 : ImplicitConversionSequence::Worse;
2627 // C++ [over.ics.rank]p4b2:
2629 // If class B is derived directly or indirectly from class A,
2630 // conversion of B* to A* is better than conversion of B* to
2631 // void*, and conversion of A* to void* is better than conversion
2633 bool SCS1ConvertsToVoid
2634 = SCS1.isPointerConversionToVoidPointer(S.Context);
2635 bool SCS2ConvertsToVoid
2636 = SCS2.isPointerConversionToVoidPointer(S.Context);
2637 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2638 // Exactly one of the conversion sequences is a conversion to
2639 // a void pointer; it's the worse conversion.
2640 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2641 : ImplicitConversionSequence::Worse;
2642 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2643 // Neither conversion sequence converts to a void pointer; compare
2644 // their derived-to-base conversions.
2645 if (ImplicitConversionSequence::CompareKind DerivedCK
2646 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
2648 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
2649 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
2650 // Both conversion sequences are conversions to void
2651 // pointers. Compare the source types to determine if there's an
2652 // inheritance relationship in their sources.
2653 QualType FromType1 = SCS1.getFromType();
2654 QualType FromType2 = SCS2.getFromType();
2656 // Adjust the types we're converting from via the array-to-pointer
2657 // conversion, if we need to.
2658 if (SCS1.First == ICK_Array_To_Pointer)
2659 FromType1 = S.Context.getArrayDecayedType(FromType1);
2660 if (SCS2.First == ICK_Array_To_Pointer)
2661 FromType2 = S.Context.getArrayDecayedType(FromType2);
2663 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
2664 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
2666 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
2667 return ImplicitConversionSequence::Better;
2668 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
2669 return ImplicitConversionSequence::Worse;
2671 // Objective-C++: If one interface is more specific than the
2672 // other, it is the better one.
2673 const ObjCObjectPointerType* FromObjCPtr1
2674 = FromType1->getAs<ObjCObjectPointerType>();
2675 const ObjCObjectPointerType* FromObjCPtr2
2676 = FromType2->getAs<ObjCObjectPointerType>();
2677 if (FromObjCPtr1 && FromObjCPtr2) {
2678 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
2680 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
2682 if (AssignLeft != AssignRight) {
2683 return AssignLeft? ImplicitConversionSequence::Better
2684 : ImplicitConversionSequence::Worse;
2689 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2691 if (ImplicitConversionSequence::CompareKind QualCK
2692 = CompareQualificationConversions(S, SCS1, SCS2))
2695 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
2696 // Check for a better reference binding based on the kind of bindings.
2697 if (isBetterReferenceBindingKind(SCS1, SCS2))
2698 return ImplicitConversionSequence::Better;
2699 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2700 return ImplicitConversionSequence::Worse;
2702 // C++ [over.ics.rank]p3b4:
2703 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2704 // which the references refer are the same type except for
2705 // top-level cv-qualifiers, and the type to which the reference
2706 // initialized by S2 refers is more cv-qualified than the type
2707 // to which the reference initialized by S1 refers.
2708 QualType T1 = SCS1.getToType(2);
2709 QualType T2 = SCS2.getToType(2);
2710 T1 = S.Context.getCanonicalType(T1);
2711 T2 = S.Context.getCanonicalType(T2);
2712 Qualifiers T1Quals, T2Quals;
2713 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2714 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
2715 if (UnqualT1 == UnqualT2) {
2716 // If the type is an array type, promote the element qualifiers to the
2717 // type for comparison.
2718 if (isa<ArrayType>(T1) && T1Quals)
2719 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
2720 if (isa<ArrayType>(T2) && T2Quals)
2721 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
2722 if (T2.isMoreQualifiedThan(T1))
2723 return ImplicitConversionSequence::Better;
2724 else if (T1.isMoreQualifiedThan(T2))
2725 return ImplicitConversionSequence::Worse;
2729 return ImplicitConversionSequence::Indistinguishable;
2732 /// CompareQualificationConversions - Compares two standard conversion
2733 /// sequences to determine whether they can be ranked based on their
2734 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2735 ImplicitConversionSequence::CompareKind
2736 CompareQualificationConversions(Sema &S,
2737 const StandardConversionSequence& SCS1,
2738 const StandardConversionSequence& SCS2) {
2740 // -- S1 and S2 differ only in their qualification conversion and
2741 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2742 // cv-qualification signature of type T1 is a proper subset of
2743 // the cv-qualification signature of type T2, and S1 is not the
2744 // deprecated string literal array-to-pointer conversion (4.2).
2745 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2746 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2747 return ImplicitConversionSequence::Indistinguishable;
2749 // FIXME: the example in the standard doesn't use a qualification
2751 QualType T1 = SCS1.getToType(2);
2752 QualType T2 = SCS2.getToType(2);
2753 T1 = S.Context.getCanonicalType(T1);
2754 T2 = S.Context.getCanonicalType(T2);
2755 Qualifiers T1Quals, T2Quals;
2756 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2757 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
2759 // If the types are the same, we won't learn anything by unwrapped
2761 if (UnqualT1 == UnqualT2)
2762 return ImplicitConversionSequence::Indistinguishable;
2764 // If the type is an array type, promote the element qualifiers to the type
2766 if (isa<ArrayType>(T1) && T1Quals)
2767 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
2768 if (isa<ArrayType>(T2) && T2Quals)
2769 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
2771 ImplicitConversionSequence::CompareKind Result
2772 = ImplicitConversionSequence::Indistinguishable;
2773 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
2774 // Within each iteration of the loop, we check the qualifiers to
2775 // determine if this still looks like a qualification
2776 // conversion. Then, if all is well, we unwrap one more level of
2777 // pointers or pointers-to-members and do it all again
2778 // until there are no more pointers or pointers-to-members left
2779 // to unwrap. This essentially mimics what
2780 // IsQualificationConversion does, but here we're checking for a
2781 // strict subset of qualifiers.
2782 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2783 // The qualifiers are the same, so this doesn't tell us anything
2784 // about how the sequences rank.
2786 else if (T2.isMoreQualifiedThan(T1)) {
2787 // T1 has fewer qualifiers, so it could be the better sequence.
2788 if (Result == ImplicitConversionSequence::Worse)
2789 // Neither has qualifiers that are a subset of the other's
2791 return ImplicitConversionSequence::Indistinguishable;
2793 Result = ImplicitConversionSequence::Better;
2794 } else if (T1.isMoreQualifiedThan(T2)) {
2795 // T2 has fewer qualifiers, so it could be the better sequence.
2796 if (Result == ImplicitConversionSequence::Better)
2797 // Neither has qualifiers that are a subset of the other's
2799 return ImplicitConversionSequence::Indistinguishable;
2801 Result = ImplicitConversionSequence::Worse;
2803 // Qualifiers are disjoint.
2804 return ImplicitConversionSequence::Indistinguishable;
2807 // If the types after this point are equivalent, we're done.
2808 if (S.Context.hasSameUnqualifiedType(T1, T2))
2812 // Check that the winning standard conversion sequence isn't using
2813 // the deprecated string literal array to pointer conversion.
2815 case ImplicitConversionSequence::Better:
2816 if (SCS1.DeprecatedStringLiteralToCharPtr)
2817 Result = ImplicitConversionSequence::Indistinguishable;
2820 case ImplicitConversionSequence::Indistinguishable:
2823 case ImplicitConversionSequence::Worse:
2824 if (SCS2.DeprecatedStringLiteralToCharPtr)
2825 Result = ImplicitConversionSequence::Indistinguishable;
2832 /// CompareDerivedToBaseConversions - Compares two standard conversion
2833 /// sequences to determine whether they can be ranked based on their
2834 /// various kinds of derived-to-base conversions (C++
2835 /// [over.ics.rank]p4b3). As part of these checks, we also look at
2836 /// conversions between Objective-C interface types.
2837 ImplicitConversionSequence::CompareKind
2838 CompareDerivedToBaseConversions(Sema &S,
2839 const StandardConversionSequence& SCS1,
2840 const StandardConversionSequence& SCS2) {
2841 QualType FromType1 = SCS1.getFromType();
2842 QualType ToType1 = SCS1.getToType(1);
2843 QualType FromType2 = SCS2.getFromType();
2844 QualType ToType2 = SCS2.getToType(1);
2846 // Adjust the types we're converting from via the array-to-pointer
2847 // conversion, if we need to.
2848 if (SCS1.First == ICK_Array_To_Pointer)
2849 FromType1 = S.Context.getArrayDecayedType(FromType1);
2850 if (SCS2.First == ICK_Array_To_Pointer)
2851 FromType2 = S.Context.getArrayDecayedType(FromType2);
2853 // Canonicalize all of the types.
2854 FromType1 = S.Context.getCanonicalType(FromType1);
2855 ToType1 = S.Context.getCanonicalType(ToType1);
2856 FromType2 = S.Context.getCanonicalType(FromType2);
2857 ToType2 = S.Context.getCanonicalType(ToType2);
2859 // C++ [over.ics.rank]p4b3:
2861 // If class B is derived directly or indirectly from class A and
2862 // class C is derived directly or indirectly from B,
2864 // Compare based on pointer conversions.
2865 if (SCS1.Second == ICK_Pointer_Conversion &&
2866 SCS2.Second == ICK_Pointer_Conversion &&
2867 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2868 FromType1->isPointerType() && FromType2->isPointerType() &&
2869 ToType1->isPointerType() && ToType2->isPointerType()) {
2870 QualType FromPointee1
2871 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2873 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2874 QualType FromPointee2
2875 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2877 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2879 // -- conversion of C* to B* is better than conversion of C* to A*,
2880 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2881 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
2882 return ImplicitConversionSequence::Better;
2883 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
2884 return ImplicitConversionSequence::Worse;
2887 // -- conversion of B* to A* is better than conversion of C* to A*,
2888 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2889 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
2890 return ImplicitConversionSequence::Better;
2891 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
2892 return ImplicitConversionSequence::Worse;
2894 } else if (SCS1.Second == ICK_Pointer_Conversion &&
2895 SCS2.Second == ICK_Pointer_Conversion) {
2896 const ObjCObjectPointerType *FromPtr1
2897 = FromType1->getAs<ObjCObjectPointerType>();
2898 const ObjCObjectPointerType *FromPtr2
2899 = FromType2->getAs<ObjCObjectPointerType>();
2900 const ObjCObjectPointerType *ToPtr1
2901 = ToType1->getAs<ObjCObjectPointerType>();
2902 const ObjCObjectPointerType *ToPtr2
2903 = ToType2->getAs<ObjCObjectPointerType>();
2905 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
2906 // Apply the same conversion ranking rules for Objective-C pointer types
2907 // that we do for C++ pointers to class types. However, we employ the
2908 // Objective-C pseudo-subtyping relationship used for assignment of
2909 // Objective-C pointer types.
2911 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
2912 bool FromAssignRight
2913 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
2915 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
2917 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
2919 // A conversion to an a non-id object pointer type or qualified 'id'
2920 // type is better than a conversion to 'id'.
2921 if (ToPtr1->isObjCIdType() &&
2922 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
2923 return ImplicitConversionSequence::Worse;
2924 if (ToPtr2->isObjCIdType() &&
2925 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
2926 return ImplicitConversionSequence::Better;
2928 // A conversion to a non-id object pointer type is better than a
2929 // conversion to a qualified 'id' type
2930 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
2931 return ImplicitConversionSequence::Worse;
2932 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
2933 return ImplicitConversionSequence::Better;
2935 // A conversion to an a non-Class object pointer type or qualified 'Class'
2936 // type is better than a conversion to 'Class'.
2937 if (ToPtr1->isObjCClassType() &&
2938 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
2939 return ImplicitConversionSequence::Worse;
2940 if (ToPtr2->isObjCClassType() &&
2941 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
2942 return ImplicitConversionSequence::Better;
2944 // A conversion to a non-Class object pointer type is better than a
2945 // conversion to a qualified 'Class' type.
2946 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
2947 return ImplicitConversionSequence::Worse;
2948 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
2949 return ImplicitConversionSequence::Better;
2951 // -- "conversion of C* to B* is better than conversion of C* to A*,"
2952 if (S.Context.hasSameType(FromType1, FromType2) &&
2953 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
2954 (ToAssignLeft != ToAssignRight))
2955 return ToAssignLeft? ImplicitConversionSequence::Worse
2956 : ImplicitConversionSequence::Better;
2958 // -- "conversion of B* to A* is better than conversion of C* to A*,"
2959 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
2960 (FromAssignLeft != FromAssignRight))
2961 return FromAssignLeft? ImplicitConversionSequence::Better
2962 : ImplicitConversionSequence::Worse;
2966 // Ranking of member-pointer types.
2967 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2968 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2969 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2970 const MemberPointerType * FromMemPointer1 =
2971 FromType1->getAs<MemberPointerType>();
2972 const MemberPointerType * ToMemPointer1 =
2973 ToType1->getAs<MemberPointerType>();
2974 const MemberPointerType * FromMemPointer2 =
2975 FromType2->getAs<MemberPointerType>();
2976 const MemberPointerType * ToMemPointer2 =
2977 ToType2->getAs<MemberPointerType>();
2978 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2979 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2980 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2981 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2982 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2983 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2984 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2985 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
2986 // conversion of A::* to B::* is better than conversion of A::* to C::*,
2987 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2988 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
2989 return ImplicitConversionSequence::Worse;
2990 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
2991 return ImplicitConversionSequence::Better;
2993 // conversion of B::* to C::* is better than conversion of A::* to C::*
2994 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2995 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
2996 return ImplicitConversionSequence::Better;
2997 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
2998 return ImplicitConversionSequence::Worse;
3002 if (SCS1.Second == ICK_Derived_To_Base) {
3003 // -- conversion of C to B is better than conversion of C to A,
3004 // -- binding of an expression of type C to a reference of type
3005 // B& is better than binding an expression of type C to a
3006 // reference of type A&,
3007 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3008 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3009 if (S.IsDerivedFrom(ToType1, ToType2))
3010 return ImplicitConversionSequence::Better;
3011 else if (S.IsDerivedFrom(ToType2, ToType1))
3012 return ImplicitConversionSequence::Worse;
3015 // -- conversion of B to A is better than conversion of C to A.
3016 // -- binding of an expression of type B to a reference of type
3017 // A& is better than binding an expression of type C to a
3018 // reference of type A&,
3019 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3020 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3021 if (S.IsDerivedFrom(FromType2, FromType1))
3022 return ImplicitConversionSequence::Better;
3023 else if (S.IsDerivedFrom(FromType1, FromType2))
3024 return ImplicitConversionSequence::Worse;
3028 return ImplicitConversionSequence::Indistinguishable;
3031 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
3032 /// determine whether they are reference-related,
3033 /// reference-compatible, reference-compatible with added
3034 /// qualification, or incompatible, for use in C++ initialization by
3035 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3036 /// type, and the first type (T1) is the pointee type of the reference
3037 /// type being initialized.
3038 Sema::ReferenceCompareResult
3039 Sema::CompareReferenceRelationship(SourceLocation Loc,
3040 QualType OrigT1, QualType OrigT2,
3041 bool &DerivedToBase,
3042 bool &ObjCConversion) {
3043 assert(!OrigT1->isReferenceType() &&
3044 "T1 must be the pointee type of the reference type");
3045 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3047 QualType T1 = Context.getCanonicalType(OrigT1);
3048 QualType T2 = Context.getCanonicalType(OrigT2);
3049 Qualifiers T1Quals, T2Quals;
3050 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3051 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3053 // C++ [dcl.init.ref]p4:
3054 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3055 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3056 // T1 is a base class of T2.
3057 DerivedToBase = false;
3058 ObjCConversion = false;
3059 if (UnqualT1 == UnqualT2) {
3061 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
3062 IsDerivedFrom(UnqualT2, UnqualT1))
3063 DerivedToBase = true;
3064 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3065 UnqualT2->isObjCObjectOrInterfaceType() &&
3066 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3067 ObjCConversion = true;
3069 return Ref_Incompatible;
3071 // At this point, we know that T1 and T2 are reference-related (at
3074 // If the type is an array type, promote the element qualifiers to the type
3076 if (isa<ArrayType>(T1) && T1Quals)
3077 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3078 if (isa<ArrayType>(T2) && T2Quals)
3079 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3081 // C++ [dcl.init.ref]p4:
3082 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3083 // reference-related to T2 and cv1 is the same cv-qualification
3084 // as, or greater cv-qualification than, cv2. For purposes of
3085 // overload resolution, cases for which cv1 is greater
3086 // cv-qualification than cv2 are identified as
3087 // reference-compatible with added qualification (see 13.3.3.2).
3089 // Note that we also require equivalence of Objective-C GC and address-space
3090 // qualifiers when performing these computations, so that e.g., an int in
3091 // address space 1 is not reference-compatible with an int in address
3093 if (T1Quals == T2Quals)
3094 return Ref_Compatible;
3095 else if (T1.isMoreQualifiedThan(T2))
3096 return Ref_Compatible_With_Added_Qualification;
3101 /// \brief Look for a user-defined conversion to an value reference-compatible
3102 /// with DeclType. Return true if something definite is found.
3104 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3105 QualType DeclType, SourceLocation DeclLoc,
3106 Expr *Init, QualType T2, bool AllowRvalues,
3107 bool AllowExplicit) {
3108 assert(T2->isRecordType() && "Can only find conversions of record types.");
3109 CXXRecordDecl *T2RecordDecl
3110 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3112 OverloadCandidateSet CandidateSet(DeclLoc);
3113 const UnresolvedSetImpl *Conversions
3114 = T2RecordDecl->getVisibleConversionFunctions();
3115 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3116 E = Conversions->end(); I != E; ++I) {
3118 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3119 if (isa<UsingShadowDecl>(D))
3120 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3122 FunctionTemplateDecl *ConvTemplate
3123 = dyn_cast<FunctionTemplateDecl>(D);
3124 CXXConversionDecl *Conv;
3126 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3128 Conv = cast<CXXConversionDecl>(D);
3130 // If this is an explicit conversion, and we're not allowed to consider
3131 // explicit conversions, skip it.
3132 if (!AllowExplicit && Conv->isExplicit())
3136 bool DerivedToBase = false;
3137 bool ObjCConversion = false;
3138 if (!ConvTemplate &&
3139 S.CompareReferenceRelationship(
3141 Conv->getConversionType().getNonReferenceType()
3142 .getUnqualifiedType(),
3143 DeclType.getNonReferenceType().getUnqualifiedType(),
3144 DerivedToBase, ObjCConversion) ==
3145 Sema::Ref_Incompatible)
3148 // If the conversion function doesn't return a reference type,
3149 // it can't be considered for this conversion. An rvalue reference
3150 // is only acceptable if its referencee is a function type.
3152 const ReferenceType *RefType =
3153 Conv->getConversionType()->getAs<ReferenceType>();
3155 (!RefType->isLValueReferenceType() &&
3156 !RefType->getPointeeType()->isFunctionType()))
3161 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
3162 Init, DeclType, CandidateSet);
3164 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
3165 DeclType, CandidateSet);
3168 OverloadCandidateSet::iterator Best;
3169 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
3171 // C++ [over.ics.ref]p1:
3173 // [...] If the parameter binds directly to the result of
3174 // applying a conversion function to the argument
3175 // expression, the implicit conversion sequence is a
3176 // user-defined conversion sequence (13.3.3.1.2), with the
3177 // second standard conversion sequence either an identity
3178 // conversion or, if the conversion function returns an
3179 // entity of a type that is a derived class of the parameter
3180 // type, a derived-to-base Conversion.
3181 if (!Best->FinalConversion.DirectBinding)
3185 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
3186 ICS.setUserDefined();
3187 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3188 ICS.UserDefined.After = Best->FinalConversion;
3189 ICS.UserDefined.ConversionFunction = Best->Function;
3190 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl();
3191 ICS.UserDefined.EllipsisConversion = false;
3192 assert(ICS.UserDefined.After.ReferenceBinding &&
3193 ICS.UserDefined.After.DirectBinding &&
3194 "Expected a direct reference binding!");
3199 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3200 Cand != CandidateSet.end(); ++Cand)
3202 ICS.Ambiguous.addConversion(Cand->Function);
3205 case OR_No_Viable_Function:
3207 // There was no suitable conversion, or we found a deleted
3208 // conversion; continue with other checks.
3215 /// \brief Compute an implicit conversion sequence for reference
3217 static ImplicitConversionSequence
3218 TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3219 SourceLocation DeclLoc,
3220 bool SuppressUserConversions,
3221 bool AllowExplicit) {
3222 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3224 // Most paths end in a failed conversion.
3225 ImplicitConversionSequence ICS;
3226 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3228 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3229 QualType T2 = Init->getType();
3231 // If the initializer is the address of an overloaded function, try
3232 // to resolve the overloaded function. If all goes well, T2 is the
3233 // type of the resulting function.
3234 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3235 DeclAccessPair Found;
3236 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3241 // Compute some basic properties of the types and the initializer.
3242 bool isRValRef = DeclType->isRValueReferenceType();
3243 bool DerivedToBase = false;
3244 bool ObjCConversion = false;
3245 Expr::Classification InitCategory = Init->Classify(S.Context);
3246 Sema::ReferenceCompareResult RefRelationship
3247 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
3251 // C++0x [dcl.init.ref]p5:
3252 // A reference to type "cv1 T1" is initialized by an expression
3253 // of type "cv2 T2" as follows:
3255 // -- If reference is an lvalue reference and the initializer expression
3257 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3258 // reference-compatible with "cv2 T2," or
3260 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3261 if (InitCategory.isLValue() &&
3262 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
3263 // C++ [over.ics.ref]p1:
3264 // When a parameter of reference type binds directly (8.5.3)
3265 // to an argument expression, the implicit conversion sequence
3266 // is the identity conversion, unless the argument expression
3267 // has a type that is a derived class of the parameter type,
3268 // in which case the implicit conversion sequence is a
3269 // derived-to-base Conversion (13.3.3.1).
3271 ICS.Standard.First = ICK_Identity;
3272 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3273 : ObjCConversion? ICK_Compatible_Conversion
3275 ICS.Standard.Third = ICK_Identity;
3276 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3277 ICS.Standard.setToType(0, T2);
3278 ICS.Standard.setToType(1, T1);
3279 ICS.Standard.setToType(2, T1);
3280 ICS.Standard.ReferenceBinding = true;
3281 ICS.Standard.DirectBinding = true;
3282 ICS.Standard.IsLvalueReference = !isRValRef;
3283 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3284 ICS.Standard.BindsToRvalue = false;
3285 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3286 ICS.Standard.CopyConstructor = 0;
3288 // Nothing more to do: the inaccessibility/ambiguity check for
3289 // derived-to-base conversions is suppressed when we're
3290 // computing the implicit conversion sequence (C++
3291 // [over.best.ics]p2).
3295 // -- has a class type (i.e., T2 is a class type), where T1 is
3296 // not reference-related to T2, and can be implicitly
3297 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3298 // is reference-compatible with "cv3 T3" 92) (this
3299 // conversion is selected by enumerating the applicable
3300 // conversion functions (13.3.1.6) and choosing the best
3301 // one through overload resolution (13.3)),
3302 if (!SuppressUserConversions && T2->isRecordType() &&
3303 !S.RequireCompleteType(DeclLoc, T2, 0) &&
3304 RefRelationship == Sema::Ref_Incompatible) {
3305 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3306 Init, T2, /*AllowRvalues=*/false,
3312 // -- Otherwise, the reference shall be an lvalue reference to a
3313 // non-volatile const type (i.e., cv1 shall be const), or the reference
3314 // shall be an rvalue reference.
3316 // We actually handle one oddity of C++ [over.ics.ref] at this
3317 // point, which is that, due to p2 (which short-circuits reference
3318 // binding by only attempting a simple conversion for non-direct
3319 // bindings) and p3's strange wording, we allow a const volatile
3320 // reference to bind to an rvalue. Hence the check for the presence
3321 // of "const" rather than checking for "const" being the only
3323 // This is also the point where rvalue references and lvalue inits no longer
3325 if (!isRValRef && !T1.isConstQualified())
3328 // -- If the initializer expression
3330 // -- is an xvalue, class prvalue, array prvalue or function
3331 // lvalue and "cv1T1" is reference-compatible with "cv2 T2", or
3332 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3333 (InitCategory.isXValue() ||
3334 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3335 (InitCategory.isLValue() && T2->isFunctionType()))) {
3337 ICS.Standard.First = ICK_Identity;
3338 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3339 : ObjCConversion? ICK_Compatible_Conversion
3341 ICS.Standard.Third = ICK_Identity;
3342 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3343 ICS.Standard.setToType(0, T2);
3344 ICS.Standard.setToType(1, T1);
3345 ICS.Standard.setToType(2, T1);
3346 ICS.Standard.ReferenceBinding = true;
3347 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3348 // binding unless we're binding to a class prvalue.
3349 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3350 // allow the use of rvalue references in C++98/03 for the benefit of
3351 // standard library implementors; therefore, we need the xvalue check here.
3352 ICS.Standard.DirectBinding =
3353 S.getLangOptions().CPlusPlus0x ||
3354 (InitCategory.isPRValue() && !T2->isRecordType());
3355 ICS.Standard.IsLvalueReference = !isRValRef;
3356 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3357 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
3358 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3359 ICS.Standard.CopyConstructor = 0;
3363 // -- has a class type (i.e., T2 is a class type), where T1 is not
3364 // reference-related to T2, and can be implicitly converted to
3365 // an xvalue, class prvalue, or function lvalue of type
3366 // "cv3 T3", where "cv1 T1" is reference-compatible with
3369 // then the reference is bound to the value of the initializer
3370 // expression in the first case and to the result of the conversion
3371 // in the second case (or, in either case, to an appropriate base
3372 // class subobject).
3373 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3374 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
3375 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3376 Init, T2, /*AllowRvalues=*/true,
3378 // In the second case, if the reference is an rvalue reference
3379 // and the second standard conversion sequence of the
3380 // user-defined conversion sequence includes an lvalue-to-rvalue
3381 // conversion, the program is ill-formed.
3382 if (ICS.isUserDefined() && isRValRef &&
3383 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3384 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3389 // -- Otherwise, a temporary of type "cv1 T1" is created and
3390 // initialized from the initializer expression using the
3391 // rules for a non-reference copy initialization (8.5). The
3392 // reference is then bound to the temporary. If T1 is
3393 // reference-related to T2, cv1 must be the same
3394 // cv-qualification as, or greater cv-qualification than,
3395 // cv2; otherwise, the program is ill-formed.
3396 if (RefRelationship == Sema::Ref_Related) {
3397 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3398 // we would be reference-compatible or reference-compatible with
3399 // added qualification. But that wasn't the case, so the reference
3400 // initialization fails.
3404 // If at least one of the types is a class type, the types are not
3405 // related, and we aren't allowed any user conversions, the
3406 // reference binding fails. This case is important for breaking
3407 // recursion, since TryImplicitConversion below will attempt to
3408 // create a temporary through the use of a copy constructor.
3409 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3410 (T1->isRecordType() || T2->isRecordType()))
3413 // If T1 is reference-related to T2 and the reference is an rvalue
3414 // reference, the initializer expression shall not be an lvalue.
3415 if (RefRelationship >= Sema::Ref_Related &&
3416 isRValRef && Init->Classify(S.Context).isLValue())
3419 // C++ [over.ics.ref]p2:
3420 // When a parameter of reference type is not bound directly to
3421 // an argument expression, the conversion sequence is the one
3422 // required to convert the argument expression to the
3423 // underlying type of the reference according to
3424 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3425 // to copy-initializing a temporary of the underlying type with
3426 // the argument expression. Any difference in top-level
3427 // cv-qualification is subsumed by the initialization itself
3428 // and does not constitute a conversion.
3429 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3430 /*AllowExplicit=*/false,
3431 /*InOverloadResolution=*/false,
3434 // Of course, that's still a reference binding.
3435 if (ICS.isStandard()) {
3436 ICS.Standard.ReferenceBinding = true;
3437 ICS.Standard.IsLvalueReference = !isRValRef;
3438 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3439 ICS.Standard.BindsToRvalue = true;
3440 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3441 } else if (ICS.isUserDefined()) {
3442 ICS.UserDefined.After.ReferenceBinding = true;
3443 ICS.Standard.IsLvalueReference = !isRValRef;
3444 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3445 ICS.Standard.BindsToRvalue = true;
3446 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3452 /// TryCopyInitialization - Try to copy-initialize a value of type
3453 /// ToType from the expression From. Return the implicit conversion
3454 /// sequence required to pass this argument, which may be a bad
3455 /// conversion sequence (meaning that the argument cannot be passed to
3456 /// a parameter of this type). If @p SuppressUserConversions, then we
3457 /// do not permit any user-defined conversion sequences.
3458 static ImplicitConversionSequence
3459 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
3460 bool SuppressUserConversions,
3461 bool InOverloadResolution) {
3462 if (ToType->isReferenceType())
3463 return TryReferenceInit(S, From, ToType,
3464 /*FIXME:*/From->getLocStart(),
3465 SuppressUserConversions,
3466 /*AllowExplicit=*/false);
3468 return TryImplicitConversion(S, From, ToType,
3469 SuppressUserConversions,
3470 /*AllowExplicit=*/false,
3471 InOverloadResolution,
3475 /// TryObjectArgumentInitialization - Try to initialize the object
3476 /// parameter of the given member function (@c Method) from the
3477 /// expression @p From.
3478 static ImplicitConversionSequence
3479 TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
3480 Expr::Classification FromClassification,
3481 CXXMethodDecl *Method,
3482 CXXRecordDecl *ActingContext) {
3483 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
3484 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3485 // const volatile object.
3486 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3487 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
3488 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
3490 // Set up the conversion sequence as a "bad" conversion, to allow us
3492 ImplicitConversionSequence ICS;
3494 // We need to have an object of class type.
3495 QualType FromType = OrigFromType;
3496 if (const PointerType *PT = FromType->getAs<PointerType>()) {
3497 FromType = PT->getPointeeType();
3499 // When we had a pointer, it's implicitly dereferenced, so we
3500 // better have an lvalue.
3501 assert(FromClassification.isLValue());
3504 assert(FromType->isRecordType());
3506 // C++0x [over.match.funcs]p4:
3507 // For non-static member functions, the type of the implicit object
3510 // - "lvalue reference to cv X" for functions declared without a
3511 // ref-qualifier or with the & ref-qualifier
3512 // - "rvalue reference to cv X" for functions declared with the &&
3515 // where X is the class of which the function is a member and cv is the
3516 // cv-qualification on the member function declaration.
3518 // However, when finding an implicit conversion sequence for the argument, we
3519 // are not allowed to create temporaries or perform user-defined conversions
3520 // (C++ [over.match.funcs]p5). We perform a simplified version of
3521 // reference binding here, that allows class rvalues to bind to
3522 // non-constant references.
3524 // First check the qualifiers.
3525 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
3526 if (ImplicitParamType.getCVRQualifiers()
3527 != FromTypeCanon.getLocalCVRQualifiers() &&
3528 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
3529 ICS.setBad(BadConversionSequence::bad_qualifiers,
3530 OrigFromType, ImplicitParamType);
3534 // Check that we have either the same type or a derived type. It
3535 // affects the conversion rank.
3536 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
3537 ImplicitConversionKind SecondKind;
3538 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3539 SecondKind = ICK_Identity;
3540 } else if (S.IsDerivedFrom(FromType, ClassType))
3541 SecondKind = ICK_Derived_To_Base;
3543 ICS.setBad(BadConversionSequence::unrelated_class,
3544 FromType, ImplicitParamType);
3548 // Check the ref-qualifier.
3549 switch (Method->getRefQualifier()) {
3551 // Do nothing; we don't care about lvalueness or rvalueness.
3555 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3556 // non-const lvalue reference cannot bind to an rvalue
3557 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
3564 if (!FromClassification.isRValue()) {
3565 // rvalue reference cannot bind to an lvalue
3566 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
3573 // Success. Mark this as a reference binding.
3575 ICS.Standard.setAsIdentityConversion();
3576 ICS.Standard.Second = SecondKind;
3577 ICS.Standard.setFromType(FromType);
3578 ICS.Standard.setAllToTypes(ImplicitParamType);
3579 ICS.Standard.ReferenceBinding = true;
3580 ICS.Standard.DirectBinding = true;
3581 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
3582 ICS.Standard.BindsToFunctionLvalue = false;
3583 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3584 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3585 = (Method->getRefQualifier() == RQ_None);
3589 /// PerformObjectArgumentInitialization - Perform initialization of
3590 /// the implicit object parameter for the given Method with the given
3593 Sema::PerformObjectArgumentInitialization(Expr *From,
3594 NestedNameSpecifier *Qualifier,
3595 NamedDecl *FoundDecl,
3596 CXXMethodDecl *Method) {
3597 QualType FromRecordType, DestType;
3598 QualType ImplicitParamRecordType =
3599 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
3601 Expr::Classification FromClassification;
3602 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
3603 FromRecordType = PT->getPointeeType();
3604 DestType = Method->getThisType(Context);
3605 FromClassification = Expr::Classification::makeSimpleLValue();
3607 FromRecordType = From->getType();
3608 DestType = ImplicitParamRecordType;
3609 FromClassification = From->Classify(Context);
3612 // Note that we always use the true parent context when performing
3613 // the actual argument initialization.
3614 ImplicitConversionSequence ICS
3615 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3616 Method, Method->getParent());
3618 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3619 Qualifiers FromQs = FromRecordType.getQualifiers();
3620 Qualifiers ToQs = DestType.getQualifiers();
3621 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3623 Diag(From->getSourceRange().getBegin(),
3624 diag::err_member_function_call_bad_cvr)
3625 << Method->getDeclName() << FromRecordType << (CVR - 1)
3626 << From->getSourceRange();
3627 Diag(Method->getLocation(), diag::note_previous_decl)
3628 << Method->getDeclName();
3633 return Diag(From->getSourceRange().getBegin(),
3634 diag::err_implicit_object_parameter_init)
3635 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
3638 if (ICS.Standard.Second == ICK_Derived_To_Base) {
3639 ExprResult FromRes =
3640 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
3641 if (FromRes.isInvalid())
3643 From = FromRes.take();
3646 if (!Context.hasSameType(From->getType(), DestType))
3647 From = ImpCastExprToType(From, DestType, CK_NoOp,
3648 From->getType()->isPointerType() ? VK_RValue : VK_LValue).take();
3652 /// TryContextuallyConvertToBool - Attempt to contextually convert the
3653 /// expression From to bool (C++0x [conv]p3).
3654 static ImplicitConversionSequence
3655 TryContextuallyConvertToBool(Sema &S, Expr *From) {
3656 // FIXME: This is pretty broken.
3657 return TryImplicitConversion(S, From, S.Context.BoolTy,
3658 // FIXME: Are these flags correct?
3659 /*SuppressUserConversions=*/false,
3660 /*AllowExplicit=*/true,
3661 /*InOverloadResolution=*/false,
3665 /// PerformContextuallyConvertToBool - Perform a contextual conversion
3666 /// of the expression From to bool (C++0x [conv]p3).
3667 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
3668 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
3670 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
3672 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
3673 return Diag(From->getSourceRange().getBegin(),
3674 diag::err_typecheck_bool_condition)
3675 << From->getType() << From->getSourceRange();
3679 /// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3680 /// expression From to 'id'.
3681 static ImplicitConversionSequence
3682 TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3683 QualType Ty = S.Context.getObjCIdType();
3684 return TryImplicitConversion(S, From, Ty,
3685 // FIXME: Are these flags correct?
3686 /*SuppressUserConversions=*/false,
3687 /*AllowExplicit=*/true,
3688 /*InOverloadResolution=*/false,
3692 /// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3693 /// of the expression From to 'id'.
3694 ExprResult Sema::PerformContextuallyConvertToObjCId(Expr *From) {
3695 QualType Ty = Context.getObjCIdType();
3696 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
3698 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3702 /// \brief Attempt to convert the given expression to an integral or
3703 /// enumeration type.
3705 /// This routine will attempt to convert an expression of class type to an
3706 /// integral or enumeration type, if that class type only has a single
3707 /// conversion to an integral or enumeration type.
3709 /// \param Loc The source location of the construct that requires the
3712 /// \param FromE The expression we're converting from.
3714 /// \param NotIntDiag The diagnostic to be emitted if the expression does not
3715 /// have integral or enumeration type.
3717 /// \param IncompleteDiag The diagnostic to be emitted if the expression has
3718 /// incomplete class type.
3720 /// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3721 /// explicit conversion function (because no implicit conversion functions
3722 /// were available). This is a recovery mode.
3724 /// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3725 /// showing which conversion was picked.
3727 /// \param AmbigDiag The diagnostic to be emitted if there is more than one
3728 /// conversion function that could convert to integral or enumeration type.
3730 /// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3731 /// usable conversion function.
3733 /// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3734 /// function, which may be an extension in this case.
3736 /// \returns The expression, converted to an integral or enumeration type if
3739 Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
3740 const PartialDiagnostic &NotIntDiag,
3741 const PartialDiagnostic &IncompleteDiag,
3742 const PartialDiagnostic &ExplicitConvDiag,
3743 const PartialDiagnostic &ExplicitConvNote,
3744 const PartialDiagnostic &AmbigDiag,
3745 const PartialDiagnostic &AmbigNote,
3746 const PartialDiagnostic &ConvDiag) {
3747 // We can't perform any more checking for type-dependent expressions.
3748 if (From->isTypeDependent())
3751 // If the expression already has integral or enumeration type, we're golden.
3752 QualType T = From->getType();
3753 if (T->isIntegralOrEnumerationType())
3756 // FIXME: Check for missing '()' if T is a function type?
3758 // If we don't have a class type in C++, there's no way we can get an
3759 // expression of integral or enumeration type.
3760 const RecordType *RecordTy = T->getAs<RecordType>();
3761 if (!RecordTy || !getLangOptions().CPlusPlus) {
3762 Diag(Loc, NotIntDiag)
3763 << T << From->getSourceRange();
3767 // We must have a complete class type.
3768 if (RequireCompleteType(Loc, T, IncompleteDiag))
3771 // Look for a conversion to an integral or enumeration type.
3772 UnresolvedSet<4> ViableConversions;
3773 UnresolvedSet<4> ExplicitConversions;
3774 const UnresolvedSetImpl *Conversions
3775 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3777 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3778 E = Conversions->end();
3781 if (CXXConversionDecl *Conversion
3782 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3783 if (Conversion->getConversionType().getNonReferenceType()
3784 ->isIntegralOrEnumerationType()) {
3785 if (Conversion->isExplicit())
3786 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3788 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3792 switch (ViableConversions.size()) {
3794 if (ExplicitConversions.size() == 1) {
3795 DeclAccessPair Found = ExplicitConversions[0];
3796 CXXConversionDecl *Conversion
3797 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3799 // The user probably meant to invoke the given explicit
3800 // conversion; use it.
3802 = Conversion->getConversionType().getNonReferenceType();
3803 std::string TypeStr;
3804 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3806 Diag(Loc, ExplicitConvDiag)
3808 << FixItHint::CreateInsertion(From->getLocStart(),
3809 "static_cast<" + TypeStr + ">(")
3810 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3812 Diag(Conversion->getLocation(), ExplicitConvNote)
3813 << ConvTy->isEnumeralType() << ConvTy;
3815 // If we aren't in a SFINAE context, build a call to the
3816 // explicit conversion function.
3817 if (isSFINAEContext())
3820 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
3821 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
3822 if (Result.isInvalid())
3825 From = Result.get();
3828 // We'll complain below about a non-integral condition type.
3832 // Apply this conversion.
3833 DeclAccessPair Found = ViableConversions[0];
3834 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
3836 CXXConversionDecl *Conversion
3837 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3839 = Conversion->getConversionType().getNonReferenceType();
3840 if (ConvDiag.getDiagID()) {
3841 if (isSFINAEContext())
3845 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3848 ExprResult Result = BuildCXXMemberCallExpr(From, Found,
3849 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
3850 if (Result.isInvalid())
3853 From = Result.get();
3858 Diag(Loc, AmbigDiag)
3859 << T << From->getSourceRange();
3860 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3861 CXXConversionDecl *Conv
3862 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3863 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3864 Diag(Conv->getLocation(), AmbigNote)
3865 << ConvTy->isEnumeralType() << ConvTy;
3870 if (!From->getType()->isIntegralOrEnumerationType())
3871 Diag(Loc, NotIntDiag)
3872 << From->getType() << From->getSourceRange();
3877 /// AddOverloadCandidate - Adds the given function to the set of
3878 /// candidate functions, using the given function call arguments. If
3879 /// @p SuppressUserConversions, then don't allow user-defined
3880 /// conversions via constructors or conversion operators.
3882 /// \para PartialOverloading true if we are performing "partial" overloading
3883 /// based on an incomplete set of function arguments. This feature is used by
3884 /// code completion.
3886 Sema::AddOverloadCandidate(FunctionDecl *Function,
3887 DeclAccessPair FoundDecl,
3888 Expr **Args, unsigned NumArgs,
3889 OverloadCandidateSet& CandidateSet,
3890 bool SuppressUserConversions,
3891 bool PartialOverloading) {
3892 const FunctionProtoType* Proto
3893 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
3894 assert(Proto && "Functions without a prototype cannot be overloaded");
3895 assert(!Function->getDescribedFunctionTemplate() &&
3896 "Use AddTemplateOverloadCandidate for function templates");
3898 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
3899 if (!isa<CXXConstructorDecl>(Method)) {
3900 // If we get here, it's because we're calling a member function
3901 // that is named without a member access expression (e.g.,
3902 // "this->f") that was either written explicitly or created
3903 // implicitly. This can happen with a qualified call to a member
3904 // function, e.g., X::f(). We use an empty type for the implied
3905 // object argument (C++ [over.call.func]p3), and the acting context
3907 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
3908 QualType(), Expr::Classification::makeSimpleLValue(),
3909 Args, NumArgs, CandidateSet,
3910 SuppressUserConversions);
3913 // We treat a constructor like a non-member function, since its object
3914 // argument doesn't participate in overload resolution.
3917 if (!CandidateSet.isNewCandidate(Function))
3920 // Overload resolution is always an unevaluated context.
3921 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
3923 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3924 // C++ [class.copy]p3:
3925 // A member function template is never instantiated to perform the copy
3926 // of a class object to an object of its class type.
3927 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3929 Constructor->isSpecializationCopyingObject() &&
3930 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3931 IsDerivedFrom(Args[0]->getType(), ClassType)))
3935 // Add this candidate
3936 CandidateSet.push_back(OverloadCandidate());
3937 OverloadCandidate& Candidate = CandidateSet.back();
3938 Candidate.FoundDecl = FoundDecl;
3939 Candidate.Function = Function;
3940 Candidate.Viable = true;
3941 Candidate.IsSurrogate = false;
3942 Candidate.IgnoreObjectArgument = false;
3943 Candidate.ExplicitCallArguments = NumArgs;
3945 unsigned NumArgsInProto = Proto->getNumArgs();
3947 // (C++ 13.3.2p2): A candidate function having fewer than m
3948 // parameters is viable only if it has an ellipsis in its parameter
3950 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3951 !Proto->isVariadic()) {
3952 Candidate.Viable = false;
3953 Candidate.FailureKind = ovl_fail_too_many_arguments;
3957 // (C++ 13.3.2p2): A candidate function having more than m parameters
3958 // is viable only if the (m+1)st parameter has a default argument
3959 // (8.3.6). For the purposes of overload resolution, the
3960 // parameter list is truncated on the right, so that there are
3961 // exactly m parameters.
3962 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
3963 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
3964 // Not enough arguments.
3965 Candidate.Viable = false;
3966 Candidate.FailureKind = ovl_fail_too_few_arguments;
3970 // Determine the implicit conversion sequences for each of the
3972 Candidate.Conversions.resize(NumArgs);
3973 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3974 if (ArgIdx < NumArgsInProto) {
3975 // (C++ 13.3.2p3): for F to be a viable function, there shall
3976 // exist for each argument an implicit conversion sequence
3977 // (13.3.3.1) that converts that argument to the corresponding
3979 QualType ParamType = Proto->getArgType(ArgIdx);
3980 Candidate.Conversions[ArgIdx]
3981 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
3982 SuppressUserConversions,
3983 /*InOverloadResolution=*/true);
3984 if (Candidate.Conversions[ArgIdx].isBad()) {
3985 Candidate.Viable = false;
3986 Candidate.FailureKind = ovl_fail_bad_conversion;
3990 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3991 // argument for which there is no corresponding parameter is
3992 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
3993 Candidate.Conversions[ArgIdx].setEllipsis();
3998 /// \brief Add all of the function declarations in the given function set to
3999 /// the overload canddiate set.
4000 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
4001 Expr **Args, unsigned NumArgs,
4002 OverloadCandidateSet& CandidateSet,
4003 bool SuppressUserConversions) {
4004 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
4005 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4006 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
4007 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
4008 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
4009 cast<CXXMethodDecl>(FD)->getParent(),
4010 Args[0]->getType(), Args[0]->Classify(Context),
4011 Args + 1, NumArgs - 1,
4012 CandidateSet, SuppressUserConversions);
4014 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
4015 SuppressUserConversions);
4017 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
4018 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4019 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
4020 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
4021 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
4022 /*FIXME: explicit args */ 0,
4024 Args[0]->Classify(Context),
4025 Args + 1, NumArgs - 1,
4027 SuppressUserConversions);
4029 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
4030 /*FIXME: explicit args */ 0,
4031 Args, NumArgs, CandidateSet,
4032 SuppressUserConversions);
4037 /// AddMethodCandidate - Adds a named decl (which is some kind of
4038 /// method) as a method candidate to the given overload set.
4039 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
4040 QualType ObjectType,
4041 Expr::Classification ObjectClassification,
4042 Expr **Args, unsigned NumArgs,
4043 OverloadCandidateSet& CandidateSet,
4044 bool SuppressUserConversions) {
4045 NamedDecl *Decl = FoundDecl.getDecl();
4046 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
4048 if (isa<UsingShadowDecl>(Decl))
4049 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
4051 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4052 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4053 "Expected a member function template");
4054 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4056 ObjectType, ObjectClassification, Args, NumArgs,
4058 SuppressUserConversions);
4060 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
4061 ObjectType, ObjectClassification, Args, NumArgs,
4062 CandidateSet, SuppressUserConversions);
4066 /// AddMethodCandidate - Adds the given C++ member function to the set
4067 /// of candidate functions, using the given function call arguments
4068 /// and the object argument (@c Object). For example, in a call
4069 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4070 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4071 /// allow user-defined conversions via constructors or conversion
4074 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
4075 CXXRecordDecl *ActingContext, QualType ObjectType,
4076 Expr::Classification ObjectClassification,
4077 Expr **Args, unsigned NumArgs,
4078 OverloadCandidateSet& CandidateSet,
4079 bool SuppressUserConversions) {
4080 const FunctionProtoType* Proto
4081 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
4082 assert(Proto && "Methods without a prototype cannot be overloaded");
4083 assert(!isa<CXXConstructorDecl>(Method) &&
4084 "Use AddOverloadCandidate for constructors");
4086 if (!CandidateSet.isNewCandidate(Method))
4089 // Overload resolution is always an unevaluated context.
4090 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
4092 // Add this candidate
4093 CandidateSet.push_back(OverloadCandidate());
4094 OverloadCandidate& Candidate = CandidateSet.back();
4095 Candidate.FoundDecl = FoundDecl;
4096 Candidate.Function = Method;
4097 Candidate.IsSurrogate = false;
4098 Candidate.IgnoreObjectArgument = false;
4099 Candidate.ExplicitCallArguments = NumArgs;
4101 unsigned NumArgsInProto = Proto->getNumArgs();
4103 // (C++ 13.3.2p2): A candidate function having fewer than m
4104 // parameters is viable only if it has an ellipsis in its parameter
4106 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4107 Candidate.Viable = false;
4108 Candidate.FailureKind = ovl_fail_too_many_arguments;
4112 // (C++ 13.3.2p2): A candidate function having more than m parameters
4113 // is viable only if the (m+1)st parameter has a default argument
4114 // (8.3.6). For the purposes of overload resolution, the
4115 // parameter list is truncated on the right, so that there are
4116 // exactly m parameters.
4117 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4118 if (NumArgs < MinRequiredArgs) {
4119 // Not enough arguments.
4120 Candidate.Viable = false;
4121 Candidate.FailureKind = ovl_fail_too_few_arguments;
4125 Candidate.Viable = true;
4126 Candidate.Conversions.resize(NumArgs + 1);
4128 if (Method->isStatic() || ObjectType.isNull())
4129 // The implicit object argument is ignored.
4130 Candidate.IgnoreObjectArgument = true;
4132 // Determine the implicit conversion sequence for the object
4134 Candidate.Conversions[0]
4135 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4136 Method, ActingContext);
4137 if (Candidate.Conversions[0].isBad()) {
4138 Candidate.Viable = false;
4139 Candidate.FailureKind = ovl_fail_bad_conversion;
4144 // Determine the implicit conversion sequences for each of the
4146 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4147 if (ArgIdx < NumArgsInProto) {
4148 // (C++ 13.3.2p3): for F to be a viable function, there shall
4149 // exist for each argument an implicit conversion sequence
4150 // (13.3.3.1) that converts that argument to the corresponding
4152 QualType ParamType = Proto->getArgType(ArgIdx);
4153 Candidate.Conversions[ArgIdx + 1]
4154 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
4155 SuppressUserConversions,
4156 /*InOverloadResolution=*/true);
4157 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
4158 Candidate.Viable = false;
4159 Candidate.FailureKind = ovl_fail_bad_conversion;
4163 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4164 // argument for which there is no corresponding parameter is
4165 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
4166 Candidate.Conversions[ArgIdx + 1].setEllipsis();
4171 /// \brief Add a C++ member function template as a candidate to the candidate
4172 /// set, using template argument deduction to produce an appropriate member
4173 /// function template specialization.
4175 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
4176 DeclAccessPair FoundDecl,
4177 CXXRecordDecl *ActingContext,
4178 TemplateArgumentListInfo *ExplicitTemplateArgs,
4179 QualType ObjectType,
4180 Expr::Classification ObjectClassification,
4181 Expr **Args, unsigned NumArgs,
4182 OverloadCandidateSet& CandidateSet,
4183 bool SuppressUserConversions) {
4184 if (!CandidateSet.isNewCandidate(MethodTmpl))
4187 // C++ [over.match.funcs]p7:
4188 // In each case where a candidate is a function template, candidate
4189 // function template specializations are generated using template argument
4190 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
4191 // candidate functions in the usual way.113) A given name can refer to one
4192 // or more function templates and also to a set of overloaded non-template
4193 // functions. In such a case, the candidate functions generated from each
4194 // function template are combined with the set of non-template candidate
4196 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
4197 FunctionDecl *Specialization = 0;
4198 if (TemplateDeductionResult Result
4199 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
4200 Args, NumArgs, Specialization, Info)) {
4201 CandidateSet.push_back(OverloadCandidate());
4202 OverloadCandidate &Candidate = CandidateSet.back();
4203 Candidate.FoundDecl = FoundDecl;
4204 Candidate.Function = MethodTmpl->getTemplatedDecl();
4205 Candidate.Viable = false;
4206 Candidate.FailureKind = ovl_fail_bad_deduction;
4207 Candidate.IsSurrogate = false;
4208 Candidate.IgnoreObjectArgument = false;
4209 Candidate.ExplicitCallArguments = NumArgs;
4210 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
4215 // Add the function template specialization produced by template argument
4216 // deduction as a candidate.
4217 assert(Specialization && "Missing member function template specialization?");
4218 assert(isa<CXXMethodDecl>(Specialization) &&
4219 "Specialization is not a member function?");
4220 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
4221 ActingContext, ObjectType, ObjectClassification,
4222 Args, NumArgs, CandidateSet, SuppressUserConversions);
4225 /// \brief Add a C++ function template specialization as a candidate
4226 /// in the candidate set, using template argument deduction to produce
4227 /// an appropriate function template specialization.
4229 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
4230 DeclAccessPair FoundDecl,
4231 TemplateArgumentListInfo *ExplicitTemplateArgs,
4232 Expr **Args, unsigned NumArgs,
4233 OverloadCandidateSet& CandidateSet,
4234 bool SuppressUserConversions) {
4235 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4238 // C++ [over.match.funcs]p7:
4239 // In each case where a candidate is a function template, candidate
4240 // function template specializations are generated using template argument
4241 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
4242 // candidate functions in the usual way.113) A given name can refer to one
4243 // or more function templates and also to a set of overloaded non-template
4244 // functions. In such a case, the candidate functions generated from each
4245 // function template are combined with the set of non-template candidate
4247 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
4248 FunctionDecl *Specialization = 0;
4249 if (TemplateDeductionResult Result
4250 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
4251 Args, NumArgs, Specialization, Info)) {
4252 CandidateSet.push_back(OverloadCandidate());
4253 OverloadCandidate &Candidate = CandidateSet.back();
4254 Candidate.FoundDecl = FoundDecl;
4255 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4256 Candidate.Viable = false;
4257 Candidate.FailureKind = ovl_fail_bad_deduction;
4258 Candidate.IsSurrogate = false;
4259 Candidate.IgnoreObjectArgument = false;
4260 Candidate.ExplicitCallArguments = NumArgs;
4261 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
4266 // Add the function template specialization produced by template argument
4267 // deduction as a candidate.
4268 assert(Specialization && "Missing function template specialization?");
4269 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
4270 SuppressUserConversions);
4273 /// AddConversionCandidate - Add a C++ conversion function as a
4274 /// candidate in the candidate set (C++ [over.match.conv],
4275 /// C++ [over.match.copy]). From is the expression we're converting from,
4276 /// and ToType is the type that we're eventually trying to convert to
4277 /// (which may or may not be the same type as the type that the
4278 /// conversion function produces).
4280 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
4281 DeclAccessPair FoundDecl,
4282 CXXRecordDecl *ActingContext,
4283 Expr *From, QualType ToType,
4284 OverloadCandidateSet& CandidateSet) {
4285 assert(!Conversion->getDescribedFunctionTemplate() &&
4286 "Conversion function templates use AddTemplateConversionCandidate");
4287 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
4288 if (!CandidateSet.isNewCandidate(Conversion))
4291 // Overload resolution is always an unevaluated context.
4292 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
4294 // Add this candidate
4295 CandidateSet.push_back(OverloadCandidate());
4296 OverloadCandidate& Candidate = CandidateSet.back();
4297 Candidate.FoundDecl = FoundDecl;
4298 Candidate.Function = Conversion;
4299 Candidate.IsSurrogate = false;
4300 Candidate.IgnoreObjectArgument = false;
4301 Candidate.FinalConversion.setAsIdentityConversion();
4302 Candidate.FinalConversion.setFromType(ConvType);
4303 Candidate.FinalConversion.setAllToTypes(ToType);
4304 Candidate.Viable = true;
4305 Candidate.Conversions.resize(1);
4306 Candidate.ExplicitCallArguments = 1;
4308 // C++ [over.match.funcs]p4:
4309 // For conversion functions, the function is considered to be a member of
4310 // the class of the implicit implied object argument for the purpose of
4311 // defining the type of the implicit object parameter.
4313 // Determine the implicit conversion sequence for the implicit
4314 // object parameter.
4315 QualType ImplicitParamType = From->getType();
4316 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4317 ImplicitParamType = FromPtrType->getPointeeType();
4318 CXXRecordDecl *ConversionContext
4319 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
4321 Candidate.Conversions[0]
4322 = TryObjectArgumentInitialization(*this, From->getType(),
4323 From->Classify(Context),
4324 Conversion, ConversionContext);
4326 if (Candidate.Conversions[0].isBad()) {
4327 Candidate.Viable = false;
4328 Candidate.FailureKind = ovl_fail_bad_conversion;
4332 // We won't go through a user-define type conversion function to convert a
4333 // derived to base as such conversions are given Conversion Rank. They only
4334 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4336 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4337 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4338 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4339 Candidate.Viable = false;
4340 Candidate.FailureKind = ovl_fail_trivial_conversion;
4344 // To determine what the conversion from the result of calling the
4345 // conversion function to the type we're eventually trying to
4346 // convert to (ToType), we need to synthesize a call to the
4347 // conversion function and attempt copy initialization from it. This
4348 // makes sure that we get the right semantics with respect to
4349 // lvalues/rvalues and the type. Fortunately, we can allocate this
4350 // call on the stack and we don't need its arguments to be
4352 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
4353 VK_LValue, From->getLocStart());
4354 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4355 Context.getPointerType(Conversion->getType()),
4356 CK_FunctionToPointerDecay,
4357 &ConversionRef, VK_RValue);
4359 QualType CallResultType
4360 = Conversion->getConversionType().getNonLValueExprType(Context);
4361 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
4362 Candidate.Viable = false;
4363 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4367 ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
4369 // Note that it is safe to allocate CallExpr on the stack here because
4370 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4372 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
4373 From->getLocStart());
4374 ImplicitConversionSequence ICS =
4375 TryCopyInitialization(*this, &Call, ToType,
4376 /*SuppressUserConversions=*/true,
4377 /*InOverloadResolution=*/false);
4379 switch (ICS.getKind()) {
4380 case ImplicitConversionSequence::StandardConversion:
4381 Candidate.FinalConversion = ICS.Standard;
4383 // C++ [over.ics.user]p3:
4384 // If the user-defined conversion is specified by a specialization of a
4385 // conversion function template, the second standard conversion sequence
4386 // shall have exact match rank.
4387 if (Conversion->getPrimaryTemplate() &&
4388 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4389 Candidate.Viable = false;
4390 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4393 // C++0x [dcl.init.ref]p5:
4394 // In the second case, if the reference is an rvalue reference and
4395 // the second standard conversion sequence of the user-defined
4396 // conversion sequence includes an lvalue-to-rvalue conversion, the
4397 // program is ill-formed.
4398 if (ToType->isRValueReferenceType() &&
4399 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4400 Candidate.Viable = false;
4401 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4405 case ImplicitConversionSequence::BadConversion:
4406 Candidate.Viable = false;
4407 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4412 "Can only end up with a standard conversion sequence or failure");
4416 /// \brief Adds a conversion function template specialization
4417 /// candidate to the overload set, using template argument deduction
4418 /// to deduce the template arguments of the conversion function
4419 /// template from the type that we are converting to (C++
4420 /// [temp.deduct.conv]).
4422 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
4423 DeclAccessPair FoundDecl,
4424 CXXRecordDecl *ActingDC,
4425 Expr *From, QualType ToType,
4426 OverloadCandidateSet &CandidateSet) {
4427 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4428 "Only conversion function templates permitted here");
4430 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4433 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
4434 CXXConversionDecl *Specialization = 0;
4435 if (TemplateDeductionResult Result
4436 = DeduceTemplateArguments(FunctionTemplate, ToType,
4437 Specialization, Info)) {
4438 CandidateSet.push_back(OverloadCandidate());
4439 OverloadCandidate &Candidate = CandidateSet.back();
4440 Candidate.FoundDecl = FoundDecl;
4441 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4442 Candidate.Viable = false;
4443 Candidate.FailureKind = ovl_fail_bad_deduction;
4444 Candidate.IsSurrogate = false;
4445 Candidate.IgnoreObjectArgument = false;
4446 Candidate.ExplicitCallArguments = 1;
4447 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
4452 // Add the conversion function template specialization produced by
4453 // template argument deduction as a candidate.
4454 assert(Specialization && "Missing function template specialization?");
4455 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
4459 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4460 /// converts the given @c Object to a function pointer via the
4461 /// conversion function @c Conversion, and then attempts to call it
4462 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
4463 /// the type of function that we'll eventually be calling.
4464 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
4465 DeclAccessPair FoundDecl,
4466 CXXRecordDecl *ActingContext,
4467 const FunctionProtoType *Proto,
4469 Expr **Args, unsigned NumArgs,
4470 OverloadCandidateSet& CandidateSet) {
4471 if (!CandidateSet.isNewCandidate(Conversion))
4474 // Overload resolution is always an unevaluated context.
4475 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
4477 CandidateSet.push_back(OverloadCandidate());
4478 OverloadCandidate& Candidate = CandidateSet.back();
4479 Candidate.FoundDecl = FoundDecl;
4480 Candidate.Function = 0;
4481 Candidate.Surrogate = Conversion;
4482 Candidate.Viable = true;
4483 Candidate.IsSurrogate = true;
4484 Candidate.IgnoreObjectArgument = false;
4485 Candidate.Conversions.resize(NumArgs + 1);
4486 Candidate.ExplicitCallArguments = NumArgs;
4488 // Determine the implicit conversion sequence for the implicit
4489 // object parameter.
4490 ImplicitConversionSequence ObjectInit
4491 = TryObjectArgumentInitialization(*this, Object->getType(),
4492 Object->Classify(Context),
4493 Conversion, ActingContext);
4494 if (ObjectInit.isBad()) {
4495 Candidate.Viable = false;
4496 Candidate.FailureKind = ovl_fail_bad_conversion;
4497 Candidate.Conversions[0] = ObjectInit;
4501 // The first conversion is actually a user-defined conversion whose
4502 // first conversion is ObjectInit's standard conversion (which is
4503 // effectively a reference binding). Record it as such.
4504 Candidate.Conversions[0].setUserDefined();
4505 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
4506 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
4507 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
4508 Candidate.Conversions[0].UserDefined.FoundConversionFunction
4509 = FoundDecl.getDecl();
4510 Candidate.Conversions[0].UserDefined.After
4511 = Candidate.Conversions[0].UserDefined.Before;
4512 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4515 unsigned NumArgsInProto = Proto->getNumArgs();
4517 // (C++ 13.3.2p2): A candidate function having fewer than m
4518 // parameters is viable only if it has an ellipsis in its parameter
4520 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4521 Candidate.Viable = false;
4522 Candidate.FailureKind = ovl_fail_too_many_arguments;
4526 // Function types don't have any default arguments, so just check if
4527 // we have enough arguments.
4528 if (NumArgs < NumArgsInProto) {
4529 // Not enough arguments.
4530 Candidate.Viable = false;
4531 Candidate.FailureKind = ovl_fail_too_few_arguments;
4535 // Determine the implicit conversion sequences for each of the
4537 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4538 if (ArgIdx < NumArgsInProto) {
4539 // (C++ 13.3.2p3): for F to be a viable function, there shall
4540 // exist for each argument an implicit conversion sequence
4541 // (13.3.3.1) that converts that argument to the corresponding
4543 QualType ParamType = Proto->getArgType(ArgIdx);
4544 Candidate.Conversions[ArgIdx + 1]
4545 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
4546 /*SuppressUserConversions=*/false,
4547 /*InOverloadResolution=*/false);
4548 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
4549 Candidate.Viable = false;
4550 Candidate.FailureKind = ovl_fail_bad_conversion;
4554 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4555 // argument for which there is no corresponding parameter is
4556 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
4557 Candidate.Conversions[ArgIdx + 1].setEllipsis();
4562 /// \brief Add overload candidates for overloaded operators that are
4563 /// member functions.
4565 /// Add the overloaded operator candidates that are member functions
4566 /// for the operator Op that was used in an operator expression such
4567 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
4568 /// CandidateSet will store the added overload candidates. (C++
4569 /// [over.match.oper]).
4570 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4571 SourceLocation OpLoc,
4572 Expr **Args, unsigned NumArgs,
4573 OverloadCandidateSet& CandidateSet,
4574 SourceRange OpRange) {
4575 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4577 // C++ [over.match.oper]p3:
4578 // For a unary operator @ with an operand of a type whose
4579 // cv-unqualified version is T1, and for a binary operator @ with
4580 // a left operand of a type whose cv-unqualified version is T1 and
4581 // a right operand of a type whose cv-unqualified version is T2,
4582 // three sets of candidate functions, designated member
4583 // candidates, non-member candidates and built-in candidates, are
4584 // constructed as follows:
4585 QualType T1 = Args[0]->getType();
4587 // -- If T1 is a class type, the set of member candidates is the
4588 // result of the qualified lookup of T1::operator@
4589 // (13.3.1.1.1); otherwise, the set of member candidates is
4591 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
4592 // Complete the type if it can be completed. Otherwise, we're done.
4593 if (RequireCompleteType(OpLoc, T1, PDiag()))
4596 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4597 LookupQualifiedName(Operators, T1Rec->getDecl());
4598 Operators.suppressDiagnostics();
4600 for (LookupResult::iterator Oper = Operators.begin(),
4601 OperEnd = Operators.end();
4604 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
4605 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
4607 /* SuppressUserConversions = */ false);
4611 /// AddBuiltinCandidate - Add a candidate for a built-in
4612 /// operator. ResultTy and ParamTys are the result and parameter types
4613 /// of the built-in candidate, respectively. Args and NumArgs are the
4614 /// arguments being passed to the candidate. IsAssignmentOperator
4615 /// should be true when this built-in candidate is an assignment
4616 /// operator. NumContextualBoolArguments is the number of arguments
4617 /// (at the beginning of the argument list) that will be contextually
4618 /// converted to bool.
4619 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
4620 Expr **Args, unsigned NumArgs,
4621 OverloadCandidateSet& CandidateSet,
4622 bool IsAssignmentOperator,
4623 unsigned NumContextualBoolArguments) {
4624 // Overload resolution is always an unevaluated context.
4625 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
4627 // Add this candidate
4628 CandidateSet.push_back(OverloadCandidate());
4629 OverloadCandidate& Candidate = CandidateSet.back();
4630 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
4631 Candidate.Function = 0;
4632 Candidate.IsSurrogate = false;
4633 Candidate.IgnoreObjectArgument = false;
4634 Candidate.BuiltinTypes.ResultTy = ResultTy;
4635 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4636 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4638 // Determine the implicit conversion sequences for each of the
4640 Candidate.Viable = true;
4641 Candidate.Conversions.resize(NumArgs);
4642 Candidate.ExplicitCallArguments = NumArgs;
4643 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4644 // C++ [over.match.oper]p4:
4645 // For the built-in assignment operators, conversions of the
4646 // left operand are restricted as follows:
4647 // -- no temporaries are introduced to hold the left operand, and
4648 // -- no user-defined conversions are applied to the left
4649 // operand to achieve a type match with the left-most
4650 // parameter of a built-in candidate.
4652 // We block these conversions by turning off user-defined
4653 // conversions, since that is the only way that initialization of
4654 // a reference to a non-class type can occur from something that
4655 // is not of the same type.
4656 if (ArgIdx < NumContextualBoolArguments) {
4657 assert(ParamTys[ArgIdx] == Context.BoolTy &&
4658 "Contextual conversion to bool requires bool type");
4659 Candidate.Conversions[ArgIdx]
4660 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
4662 Candidate.Conversions[ArgIdx]
4663 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
4664 ArgIdx == 0 && IsAssignmentOperator,
4665 /*InOverloadResolution=*/false);
4667 if (Candidate.Conversions[ArgIdx].isBad()) {
4668 Candidate.Viable = false;
4669 Candidate.FailureKind = ovl_fail_bad_conversion;
4675 /// BuiltinCandidateTypeSet - A set of types that will be used for the
4676 /// candidate operator functions for built-in operators (C++
4677 /// [over.built]). The types are separated into pointer types and
4678 /// enumeration types.
4679 class BuiltinCandidateTypeSet {
4680 /// TypeSet - A set of types.
4681 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
4683 /// PointerTypes - The set of pointer types that will be used in the
4684 /// built-in candidates.
4685 TypeSet PointerTypes;
4687 /// MemberPointerTypes - The set of member pointer types that will be
4688 /// used in the built-in candidates.
4689 TypeSet MemberPointerTypes;
4691 /// EnumerationTypes - The set of enumeration types that will be
4692 /// used in the built-in candidates.
4693 TypeSet EnumerationTypes;
4695 /// \brief The set of vector types that will be used in the built-in
4697 TypeSet VectorTypes;
4699 /// \brief A flag indicating non-record types are viable candidates
4700 bool HasNonRecordTypes;
4702 /// \brief A flag indicating whether either arithmetic or enumeration types
4703 /// were present in the candidate set.
4704 bool HasArithmeticOrEnumeralTypes;
4706 /// \brief A flag indicating whether the nullptr type was present in the
4708 bool HasNullPtrType;
4710 /// Sema - The semantic analysis instance where we are building the
4711 /// candidate type set.
4714 /// Context - The AST context in which we will build the type sets.
4715 ASTContext &Context;
4717 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4718 const Qualifiers &VisibleQuals);
4719 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
4722 /// iterator - Iterates through the types that are part of the set.
4723 typedef TypeSet::iterator iterator;
4725 BuiltinCandidateTypeSet(Sema &SemaRef)
4726 : HasNonRecordTypes(false),
4727 HasArithmeticOrEnumeralTypes(false),
4728 HasNullPtrType(false),
4730 Context(SemaRef.Context) { }
4732 void AddTypesConvertedFrom(QualType Ty,
4734 bool AllowUserConversions,
4735 bool AllowExplicitConversions,
4736 const Qualifiers &VisibleTypeConversionsQuals);
4738 /// pointer_begin - First pointer type found;
4739 iterator pointer_begin() { return PointerTypes.begin(); }
4741 /// pointer_end - Past the last pointer type found;
4742 iterator pointer_end() { return PointerTypes.end(); }
4744 /// member_pointer_begin - First member pointer type found;
4745 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4747 /// member_pointer_end - Past the last member pointer type found;
4748 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4750 /// enumeration_begin - First enumeration type found;
4751 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4753 /// enumeration_end - Past the last enumeration type found;
4754 iterator enumeration_end() { return EnumerationTypes.end(); }
4756 iterator vector_begin() { return VectorTypes.begin(); }
4757 iterator vector_end() { return VectorTypes.end(); }
4759 bool hasNonRecordTypes() { return HasNonRecordTypes; }
4760 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
4761 bool hasNullPtrType() const { return HasNullPtrType; }
4764 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
4765 /// the set of pointer types along with any more-qualified variants of
4766 /// that type. For example, if @p Ty is "int const *", this routine
4767 /// will add "int const *", "int const volatile *", "int const
4768 /// restrict *", and "int const volatile restrict *" to the set of
4769 /// pointer types. Returns true if the add of @p Ty itself succeeded,
4770 /// false otherwise.
4772 /// FIXME: what to do about extended qualifiers?
4774 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4775 const Qualifiers &VisibleQuals) {
4777 // Insert this type.
4778 if (!PointerTypes.insert(Ty))
4782 const PointerType *PointerTy = Ty->getAs<PointerType>();
4783 bool buildObjCPtr = false;
4785 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
4786 PointeeTy = PTy->getPointeeType();
4787 buildObjCPtr = true;
4790 assert(false && "type was not a pointer type!");
4793 PointeeTy = PointerTy->getPointeeType();
4795 // Don't add qualified variants of arrays. For one, they're not allowed
4796 // (the qualifier would sink to the element type), and for another, the
4797 // only overload situation where it matters is subscript or pointer +- int,
4798 // and those shouldn't have qualifier variants anyway.
4799 if (PointeeTy->isArrayType())
4801 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4802 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
4803 BaseCVR = Array->getElementType().getCVRQualifiers();
4804 bool hasVolatile = VisibleQuals.hasVolatile();
4805 bool hasRestrict = VisibleQuals.hasRestrict();
4807 // Iterate through all strict supersets of BaseCVR.
4808 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4809 if ((CVR | BaseCVR) != CVR) continue;
4810 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4812 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4813 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
4814 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4816 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4818 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
4824 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4825 /// to the set of pointer types along with any more-qualified variants of
4826 /// that type. For example, if @p Ty is "int const *", this routine
4827 /// will add "int const *", "int const volatile *", "int const
4828 /// restrict *", and "int const volatile restrict *" to the set of
4829 /// pointer types. Returns true if the add of @p Ty itself succeeded,
4830 /// false otherwise.
4832 /// FIXME: what to do about extended qualifiers?
4834 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4836 // Insert this type.
4837 if (!MemberPointerTypes.insert(Ty))
4840 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4841 assert(PointerTy && "type was not a member pointer type!");
4843 QualType PointeeTy = PointerTy->getPointeeType();
4844 // Don't add qualified variants of arrays. For one, they're not allowed
4845 // (the qualifier would sink to the element type), and for another, the
4846 // only overload situation where it matters is subscript or pointer +- int,
4847 // and those shouldn't have qualifier variants anyway.
4848 if (PointeeTy->isArrayType())
4850 const Type *ClassTy = PointerTy->getClass();
4852 // Iterate through all strict supersets of the pointee type's CVR
4854 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4855 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4856 if ((CVR | BaseCVR) != CVR) continue;
4858 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4859 MemberPointerTypes.insert(
4860 Context.getMemberPointerType(QPointeeTy, ClassTy));
4866 /// AddTypesConvertedFrom - Add each of the types to which the type @p
4867 /// Ty can be implicit converted to the given set of @p Types. We're
4868 /// primarily interested in pointer types and enumeration types. We also
4869 /// take member pointer types, for the conditional operator.
4870 /// AllowUserConversions is true if we should look at the conversion
4871 /// functions of a class type, and AllowExplicitConversions if we
4872 /// should also include the explicit conversion functions of a class
4875 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
4877 bool AllowUserConversions,
4878 bool AllowExplicitConversions,
4879 const Qualifiers &VisibleQuals) {
4880 // Only deal with canonical types.
4881 Ty = Context.getCanonicalType(Ty);
4883 // Look through reference types; they aren't part of the type of an
4884 // expression for the purposes of conversions.
4885 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
4886 Ty = RefTy->getPointeeType();
4888 // If we're dealing with an array type, decay to the pointer.
4889 if (Ty->isArrayType())
4890 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4892 // Otherwise, we don't care about qualifiers on the type.
4893 Ty = Ty.getLocalUnqualifiedType();
4895 // Flag if we ever add a non-record type.
4896 const RecordType *TyRec = Ty->getAs<RecordType>();
4897 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
4899 // Flag if we encounter an arithmetic type.
4900 HasArithmeticOrEnumeralTypes =
4901 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
4903 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4904 PointerTypes.insert(Ty);
4905 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
4906 // Insert our type, and its more-qualified variants, into the set
4908 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
4910 } else if (Ty->isMemberPointerType()) {
4911 // Member pointers are far easier, since the pointee can't be converted.
4912 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4914 } else if (Ty->isEnumeralType()) {
4915 HasArithmeticOrEnumeralTypes = true;
4916 EnumerationTypes.insert(Ty);
4917 } else if (Ty->isVectorType()) {
4918 // We treat vector types as arithmetic types in many contexts as an
4920 HasArithmeticOrEnumeralTypes = true;
4921 VectorTypes.insert(Ty);
4922 } else if (Ty->isNullPtrType()) {
4923 HasNullPtrType = true;
4924 } else if (AllowUserConversions && TyRec) {
4925 // No conversion functions in incomplete types.
4926 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
4929 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
4930 const UnresolvedSetImpl *Conversions
4931 = ClassDecl->getVisibleConversionFunctions();
4932 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4933 E = Conversions->end(); I != E; ++I) {
4934 NamedDecl *D = I.getDecl();
4935 if (isa<UsingShadowDecl>(D))
4936 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4938 // Skip conversion function templates; they don't tell us anything
4939 // about which builtin types we can convert to.
4940 if (isa<FunctionTemplateDecl>(D))
4943 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
4944 if (AllowExplicitConversions || !Conv->isExplicit()) {
4945 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
4952 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4953 /// the volatile- and non-volatile-qualified assignment operators for the
4954 /// given type to the candidate set.
4955 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4959 OverloadCandidateSet &CandidateSet) {
4960 QualType ParamTypes[2];
4962 // T& operator=(T&, T)
4963 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4965 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4966 /*IsAssignmentOperator=*/true);
4968 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4969 // volatile T& operator=(volatile T&, T)
4971 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
4973 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4974 /*IsAssignmentOperator=*/true);
4978 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4979 /// if any, found in visible type conversion functions found in ArgExpr's type.
4980 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4982 const RecordType *TyRec;
4983 if (const MemberPointerType *RHSMPType =
4984 ArgExpr->getType()->getAs<MemberPointerType>())
4985 TyRec = RHSMPType->getClass()->getAs<RecordType>();
4987 TyRec = ArgExpr->getType()->getAs<RecordType>();
4989 // Just to be safe, assume the worst case.
4990 VRQuals.addVolatile();
4991 VRQuals.addRestrict();
4995 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
4996 if (!ClassDecl->hasDefinition())
4999 const UnresolvedSetImpl *Conversions =
5000 ClassDecl->getVisibleConversionFunctions();
5002 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5003 E = Conversions->end(); I != E; ++I) {
5004 NamedDecl *D = I.getDecl();
5005 if (isa<UsingShadowDecl>(D))
5006 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5007 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
5008 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5009 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5010 CanTy = ResTypeRef->getPointeeType();
5011 // Need to go down the pointer/mempointer chain and add qualifiers
5015 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5016 CanTy = ResTypePtr->getPointeeType();
5017 else if (const MemberPointerType *ResTypeMPtr =
5018 CanTy->getAs<MemberPointerType>())
5019 CanTy = ResTypeMPtr->getPointeeType();
5022 if (CanTy.isVolatileQualified())
5023 VRQuals.addVolatile();
5024 if (CanTy.isRestrictQualified())
5025 VRQuals.addRestrict();
5026 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5036 /// \brief Helper class to manage the addition of builtin operator overload
5037 /// candidates. It provides shared state and utility methods used throughout
5038 /// the process, as well as a helper method to add each group of builtin
5039 /// operator overloads from the standard to a candidate set.
5040 class BuiltinOperatorOverloadBuilder {
5041 // Common instance state available to all overload candidate addition methods.
5045 Qualifiers VisibleTypeConversionsQuals;
5046 bool HasArithmeticOrEnumeralCandidateType;
5047 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
5048 OverloadCandidateSet &CandidateSet;
5050 // Define some constants used to index and iterate over the arithemetic types
5051 // provided via the getArithmeticType() method below.
5052 // The "promoted arithmetic types" are the arithmetic
5053 // types are that preserved by promotion (C++ [over.built]p2).
5054 static const unsigned FirstIntegralType = 3;
5055 static const unsigned LastIntegralType = 18;
5056 static const unsigned FirstPromotedIntegralType = 3,
5057 LastPromotedIntegralType = 9;
5058 static const unsigned FirstPromotedArithmeticType = 0,
5059 LastPromotedArithmeticType = 9;
5060 static const unsigned NumArithmeticTypes = 18;
5062 /// \brief Get the canonical type for a given arithmetic type index.
5063 CanQualType getArithmeticType(unsigned index) {
5064 assert(index < NumArithmeticTypes);
5065 static CanQualType ASTContext::* const
5066 ArithmeticTypes[NumArithmeticTypes] = {
5067 // Start of promoted types.
5068 &ASTContext::FloatTy,
5069 &ASTContext::DoubleTy,
5070 &ASTContext::LongDoubleTy,
5072 // Start of integral types.
5074 &ASTContext::LongTy,
5075 &ASTContext::LongLongTy,
5076 &ASTContext::UnsignedIntTy,
5077 &ASTContext::UnsignedLongTy,
5078 &ASTContext::UnsignedLongLongTy,
5079 // End of promoted types.
5081 &ASTContext::BoolTy,
5082 &ASTContext::CharTy,
5083 &ASTContext::WCharTy,
5084 &ASTContext::Char16Ty,
5085 &ASTContext::Char32Ty,
5086 &ASTContext::SignedCharTy,
5087 &ASTContext::ShortTy,
5088 &ASTContext::UnsignedCharTy,
5089 &ASTContext::UnsignedShortTy,
5090 // End of integral types.
5091 // FIXME: What about complex?
5093 return S.Context.*ArithmeticTypes[index];
5096 /// \brief Gets the canonical type resulting from the usual arithemetic
5097 /// converions for the given arithmetic types.
5098 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5099 // Accelerator table for performing the usual arithmetic conversions.
5100 // The rules are basically:
5101 // - if either is floating-point, use the wider floating-point
5102 // - if same signedness, use the higher rank
5103 // - if same size, use unsigned of the higher rank
5104 // - use the larger type
5105 // These rules, together with the axiom that higher ranks are
5106 // never smaller, are sufficient to precompute all of these results
5107 // *except* when dealing with signed types of higher rank.
5108 // (we could precompute SLL x UI for all known platforms, but it's
5109 // better not to make any assumptions).
5111 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5113 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5114 [LastPromotedArithmeticType] = {
5115 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5116 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5117 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5118 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5119 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5120 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5121 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5122 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5123 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5126 assert(L < LastPromotedArithmeticType);
5127 assert(R < LastPromotedArithmeticType);
5128 int Idx = ConversionsTable[L][R];
5130 // Fast path: the table gives us a concrete answer.
5131 if (Idx != Dep) return getArithmeticType(Idx);
5133 // Slow path: we need to compare widths.
5134 // An invariant is that the signed type has higher rank.
5135 CanQualType LT = getArithmeticType(L),
5136 RT = getArithmeticType(R);
5137 unsigned LW = S.Context.getIntWidth(LT),
5138 RW = S.Context.getIntWidth(RT);
5140 // If they're different widths, use the signed type.
5141 if (LW > RW) return LT;
5142 else if (LW < RW) return RT;
5144 // Otherwise, use the unsigned type of the signed type's rank.
5145 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5146 assert(L == SLL || R == SLL);
5147 return S.Context.UnsignedLongLongTy;
5150 /// \brief Helper method to factor out the common pattern of adding overloads
5151 /// for '++' and '--' builtin operators.
5152 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5154 QualType ParamTypes[2] = {
5155 S.Context.getLValueReferenceType(CandidateTy),
5159 // Non-volatile version.
5161 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5163 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5165 // Use a heuristic to reduce number of builtin candidates in the set:
5166 // add volatile version only if there are conversions to a volatile type.
5169 S.Context.getLValueReferenceType(
5170 S.Context.getVolatileType(CandidateTy));
5172 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5174 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5179 BuiltinOperatorOverloadBuilder(
5180 Sema &S, Expr **Args, unsigned NumArgs,
5181 Qualifiers VisibleTypeConversionsQuals,
5182 bool HasArithmeticOrEnumeralCandidateType,
5183 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
5184 OverloadCandidateSet &CandidateSet)
5185 : S(S), Args(Args), NumArgs(NumArgs),
5186 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
5187 HasArithmeticOrEnumeralCandidateType(
5188 HasArithmeticOrEnumeralCandidateType),
5189 CandidateTypes(CandidateTypes),
5190 CandidateSet(CandidateSet) {
5191 // Validate some of our static helper constants in debug builds.
5192 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
5193 "Invalid first promoted integral type");
5194 assert(getArithmeticType(LastPromotedIntegralType - 1)
5195 == S.Context.UnsignedLongLongTy &&
5196 "Invalid last promoted integral type");
5197 assert(getArithmeticType(FirstPromotedArithmeticType)
5198 == S.Context.FloatTy &&
5199 "Invalid first promoted arithmetic type");
5200 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5201 == S.Context.UnsignedLongLongTy &&
5202 "Invalid last promoted arithmetic type");
5205 // C++ [over.built]p3:
5207 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5208 // is either volatile or empty, there exist candidate operator
5209 // functions of the form
5211 // VQ T& operator++(VQ T&);
5212 // T operator++(VQ T&, int);
5214 // C++ [over.built]p4:
5216 // For every pair (T, VQ), where T is an arithmetic type other
5217 // than bool, and VQ is either volatile or empty, there exist
5218 // candidate operator functions of the form
5220 // VQ T& operator--(VQ T&);
5221 // T operator--(VQ T&, int);
5222 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
5223 if (!HasArithmeticOrEnumeralCandidateType)
5226 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5227 Arith < NumArithmeticTypes; ++Arith) {
5228 addPlusPlusMinusMinusStyleOverloads(
5229 getArithmeticType(Arith),
5230 VisibleTypeConversionsQuals.hasVolatile());
5234 // C++ [over.built]p5:
5236 // For every pair (T, VQ), where T is a cv-qualified or
5237 // cv-unqualified object type, and VQ is either volatile or
5238 // empty, there exist candidate operator functions of the form
5240 // T*VQ& operator++(T*VQ&);
5241 // T*VQ& operator--(T*VQ&);
5242 // T* operator++(T*VQ&, int);
5243 // T* operator--(T*VQ&, int);
5244 void addPlusPlusMinusMinusPointerOverloads() {
5245 for (BuiltinCandidateTypeSet::iterator
5246 Ptr = CandidateTypes[0].pointer_begin(),
5247 PtrEnd = CandidateTypes[0].pointer_end();
5248 Ptr != PtrEnd; ++Ptr) {
5249 // Skip pointer types that aren't pointers to object types.
5250 if (!(*Ptr)->getPointeeType()->isObjectType())
5253 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5254 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5255 VisibleTypeConversionsQuals.hasVolatile()));
5259 // C++ [over.built]p6:
5260 // For every cv-qualified or cv-unqualified object type T, there
5261 // exist candidate operator functions of the form
5263 // T& operator*(T*);
5265 // C++ [over.built]p7:
5266 // For every function type T that does not have cv-qualifiers or a
5267 // ref-qualifier, there exist candidate operator functions of the form
5268 // T& operator*(T*);
5269 void addUnaryStarPointerOverloads() {
5270 for (BuiltinCandidateTypeSet::iterator
5271 Ptr = CandidateTypes[0].pointer_begin(),
5272 PtrEnd = CandidateTypes[0].pointer_end();
5273 Ptr != PtrEnd; ++Ptr) {
5274 QualType ParamTy = *Ptr;
5275 QualType PointeeTy = ParamTy->getPointeeType();
5276 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5279 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5280 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5283 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5284 &ParamTy, Args, 1, CandidateSet);
5288 // C++ [over.built]p9:
5289 // For every promoted arithmetic type T, there exist candidate
5290 // operator functions of the form
5294 void addUnaryPlusOrMinusArithmeticOverloads() {
5295 if (!HasArithmeticOrEnumeralCandidateType)
5298 for (unsigned Arith = FirstPromotedArithmeticType;
5299 Arith < LastPromotedArithmeticType; ++Arith) {
5300 QualType ArithTy = getArithmeticType(Arith);
5301 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5304 // Extension: We also add these operators for vector types.
5305 for (BuiltinCandidateTypeSet::iterator
5306 Vec = CandidateTypes[0].vector_begin(),
5307 VecEnd = CandidateTypes[0].vector_end();
5308 Vec != VecEnd; ++Vec) {
5309 QualType VecTy = *Vec;
5310 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5314 // C++ [over.built]p8:
5315 // For every type T, there exist candidate operator functions of
5318 // T* operator+(T*);
5319 void addUnaryPlusPointerOverloads() {
5320 for (BuiltinCandidateTypeSet::iterator
5321 Ptr = CandidateTypes[0].pointer_begin(),
5322 PtrEnd = CandidateTypes[0].pointer_end();
5323 Ptr != PtrEnd; ++Ptr) {
5324 QualType ParamTy = *Ptr;
5325 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5329 // C++ [over.built]p10:
5330 // For every promoted integral type T, there exist candidate
5331 // operator functions of the form
5334 void addUnaryTildePromotedIntegralOverloads() {
5335 if (!HasArithmeticOrEnumeralCandidateType)
5338 for (unsigned Int = FirstPromotedIntegralType;
5339 Int < LastPromotedIntegralType; ++Int) {
5340 QualType IntTy = getArithmeticType(Int);
5341 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5344 // Extension: We also add this operator for vector types.
5345 for (BuiltinCandidateTypeSet::iterator
5346 Vec = CandidateTypes[0].vector_begin(),
5347 VecEnd = CandidateTypes[0].vector_end();
5348 Vec != VecEnd; ++Vec) {
5349 QualType VecTy = *Vec;
5350 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5354 // C++ [over.match.oper]p16:
5355 // For every pointer to member type T, there exist candidate operator
5356 // functions of the form
5358 // bool operator==(T,T);
5359 // bool operator!=(T,T);
5360 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5361 /// Set of (canonical) types that we've already handled.
5362 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5364 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5365 for (BuiltinCandidateTypeSet::iterator
5366 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5367 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5368 MemPtr != MemPtrEnd;
5370 // Don't add the same builtin candidate twice.
5371 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5374 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5375 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5381 // C++ [over.built]p15:
5383 // For every T, where T is an enumeration type, a pointer type, or
5384 // std::nullptr_t, there exist candidate operator functions of the form
5386 // bool operator<(T, T);
5387 // bool operator>(T, T);
5388 // bool operator<=(T, T);
5389 // bool operator>=(T, T);
5390 // bool operator==(T, T);
5391 // bool operator!=(T, T);
5392 void addRelationalPointerOrEnumeralOverloads() {
5393 // C++ [over.built]p1:
5394 // If there is a user-written candidate with the same name and parameter
5395 // types as a built-in candidate operator function, the built-in operator
5396 // function is hidden and is not included in the set of candidate
5399 // The text is actually in a note, but if we don't implement it then we end
5400 // up with ambiguities when the user provides an overloaded operator for
5401 // an enumeration type. Note that only enumeration types have this problem,
5402 // so we track which enumeration types we've seen operators for. Also, the
5403 // only other overloaded operator with enumeration argumenst, operator=,
5404 // cannot be overloaded for enumeration types, so this is the only place
5405 // where we must suppress candidates like this.
5406 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5407 UserDefinedBinaryOperators;
5409 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5410 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5411 CandidateTypes[ArgIdx].enumeration_end()) {
5412 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5413 CEnd = CandidateSet.end();
5415 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5418 QualType FirstParamType =
5419 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5420 QualType SecondParamType =
5421 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5423 // Skip if either parameter isn't of enumeral type.
5424 if (!FirstParamType->isEnumeralType() ||
5425 !SecondParamType->isEnumeralType())
5428 // Add this operator to the set of known user-defined operators.
5429 UserDefinedBinaryOperators.insert(
5430 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5431 S.Context.getCanonicalType(SecondParamType)));
5436 /// Set of (canonical) types that we've already handled.
5437 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5439 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5440 for (BuiltinCandidateTypeSet::iterator
5441 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5442 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5443 Ptr != PtrEnd; ++Ptr) {
5444 // Don't add the same builtin candidate twice.
5445 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5448 QualType ParamTypes[2] = { *Ptr, *Ptr };
5449 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5452 for (BuiltinCandidateTypeSet::iterator
5453 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5454 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5455 Enum != EnumEnd; ++Enum) {
5456 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5458 // Don't add the same builtin candidate twice, or if a user defined
5459 // candidate exists.
5460 if (!AddedTypes.insert(CanonType) ||
5461 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5465 QualType ParamTypes[2] = { *Enum, *Enum };
5466 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5470 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
5471 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
5472 if (AddedTypes.insert(NullPtrTy) &&
5473 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
5475 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
5476 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5483 // C++ [over.built]p13:
5485 // For every cv-qualified or cv-unqualified object type T
5486 // there exist candidate operator functions of the form
5488 // T* operator+(T*, ptrdiff_t);
5489 // T& operator[](T*, ptrdiff_t); [BELOW]
5490 // T* operator-(T*, ptrdiff_t);
5491 // T* operator+(ptrdiff_t, T*);
5492 // T& operator[](ptrdiff_t, T*); [BELOW]
5494 // C++ [over.built]p14:
5496 // For every T, where T is a pointer to object type, there
5497 // exist candidate operator functions of the form
5499 // ptrdiff_t operator-(T, T);
5500 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5501 /// Set of (canonical) types that we've already handled.
5502 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5504 for (int Arg = 0; Arg < 2; ++Arg) {
5505 QualType AsymetricParamTypes[2] = {
5506 S.Context.getPointerDiffType(),
5507 S.Context.getPointerDiffType(),
5509 for (BuiltinCandidateTypeSet::iterator
5510 Ptr = CandidateTypes[Arg].pointer_begin(),
5511 PtrEnd = CandidateTypes[Arg].pointer_end();
5512 Ptr != PtrEnd; ++Ptr) {
5513 QualType PointeeTy = (*Ptr)->getPointeeType();
5514 if (!PointeeTy->isObjectType())
5517 AsymetricParamTypes[Arg] = *Ptr;
5518 if (Arg == 0 || Op == OO_Plus) {
5519 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5520 // T* operator+(ptrdiff_t, T*);
5521 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5524 if (Op == OO_Minus) {
5525 // ptrdiff_t operator-(T, T);
5526 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5529 QualType ParamTypes[2] = { *Ptr, *Ptr };
5530 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5531 Args, 2, CandidateSet);
5537 // C++ [over.built]p12:
5539 // For every pair of promoted arithmetic types L and R, there
5540 // exist candidate operator functions of the form
5542 // LR operator*(L, R);
5543 // LR operator/(L, R);
5544 // LR operator+(L, R);
5545 // LR operator-(L, R);
5546 // bool operator<(L, R);
5547 // bool operator>(L, R);
5548 // bool operator<=(L, R);
5549 // bool operator>=(L, R);
5550 // bool operator==(L, R);
5551 // bool operator!=(L, R);
5553 // where LR is the result of the usual arithmetic conversions
5554 // between types L and R.
5556 // C++ [over.built]p24:
5558 // For every pair of promoted arithmetic types L and R, there exist
5559 // candidate operator functions of the form
5561 // LR operator?(bool, L, R);
5563 // where LR is the result of the usual arithmetic conversions
5564 // between types L and R.
5565 // Our candidates ignore the first parameter.
5566 void addGenericBinaryArithmeticOverloads(bool isComparison) {
5567 if (!HasArithmeticOrEnumeralCandidateType)
5570 for (unsigned Left = FirstPromotedArithmeticType;
5571 Left < LastPromotedArithmeticType; ++Left) {
5572 for (unsigned Right = FirstPromotedArithmeticType;
5573 Right < LastPromotedArithmeticType; ++Right) {
5574 QualType LandR[2] = { getArithmeticType(Left),
5575 getArithmeticType(Right) };
5577 isComparison ? S.Context.BoolTy
5578 : getUsualArithmeticConversions(Left, Right);
5579 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5583 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5584 // conditional operator for vector types.
5585 for (BuiltinCandidateTypeSet::iterator
5586 Vec1 = CandidateTypes[0].vector_begin(),
5587 Vec1End = CandidateTypes[0].vector_end();
5588 Vec1 != Vec1End; ++Vec1) {
5589 for (BuiltinCandidateTypeSet::iterator
5590 Vec2 = CandidateTypes[1].vector_begin(),
5591 Vec2End = CandidateTypes[1].vector_end();
5592 Vec2 != Vec2End; ++Vec2) {
5593 QualType LandR[2] = { *Vec1, *Vec2 };
5594 QualType Result = S.Context.BoolTy;
5595 if (!isComparison) {
5596 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5602 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5607 // C++ [over.built]p17:
5609 // For every pair of promoted integral types L and R, there
5610 // exist candidate operator functions of the form
5612 // LR operator%(L, R);
5613 // LR operator&(L, R);
5614 // LR operator^(L, R);
5615 // LR operator|(L, R);
5616 // L operator<<(L, R);
5617 // L operator>>(L, R);
5619 // where LR is the result of the usual arithmetic conversions
5620 // between types L and R.
5621 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
5622 if (!HasArithmeticOrEnumeralCandidateType)
5625 for (unsigned Left = FirstPromotedIntegralType;
5626 Left < LastPromotedIntegralType; ++Left) {
5627 for (unsigned Right = FirstPromotedIntegralType;
5628 Right < LastPromotedIntegralType; ++Right) {
5629 QualType LandR[2] = { getArithmeticType(Left),
5630 getArithmeticType(Right) };
5631 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5633 : getUsualArithmeticConversions(Left, Right);
5634 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5639 // C++ [over.built]p20:
5641 // For every pair (T, VQ), where T is an enumeration or
5642 // pointer to member type and VQ is either volatile or
5643 // empty, there exist candidate operator functions of the form
5645 // VQ T& operator=(VQ T&, T);
5646 void addAssignmentMemberPointerOrEnumeralOverloads() {
5647 /// Set of (canonical) types that we've already handled.
5648 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5650 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5651 for (BuiltinCandidateTypeSet::iterator
5652 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5653 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5654 Enum != EnumEnd; ++Enum) {
5655 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5658 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5662 for (BuiltinCandidateTypeSet::iterator
5663 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5664 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5665 MemPtr != MemPtrEnd; ++MemPtr) {
5666 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5669 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5675 // C++ [over.built]p19:
5677 // For every pair (T, VQ), where T is any type and VQ is either
5678 // volatile or empty, there exist candidate operator functions
5681 // T*VQ& operator=(T*VQ&, T*);
5683 // C++ [over.built]p21:
5685 // For every pair (T, VQ), where T is a cv-qualified or
5686 // cv-unqualified object type and VQ is either volatile or
5687 // empty, there exist candidate operator functions of the form
5689 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5690 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5691 void addAssignmentPointerOverloads(bool isEqualOp) {
5692 /// Set of (canonical) types that we've already handled.
5693 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5695 for (BuiltinCandidateTypeSet::iterator
5696 Ptr = CandidateTypes[0].pointer_begin(),
5697 PtrEnd = CandidateTypes[0].pointer_end();
5698 Ptr != PtrEnd; ++Ptr) {
5699 // If this is operator=, keep track of the builtin candidates we added.
5701 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
5702 else if (!(*Ptr)->getPointeeType()->isObjectType())
5705 // non-volatile version
5706 QualType ParamTypes[2] = {
5707 S.Context.getLValueReferenceType(*Ptr),
5708 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5710 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5711 /*IsAssigmentOperator=*/ isEqualOp);
5713 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5714 VisibleTypeConversionsQuals.hasVolatile()) {
5717 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5718 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5719 /*IsAssigmentOperator=*/isEqualOp);
5724 for (BuiltinCandidateTypeSet::iterator
5725 Ptr = CandidateTypes[1].pointer_begin(),
5726 PtrEnd = CandidateTypes[1].pointer_end();
5727 Ptr != PtrEnd; ++Ptr) {
5728 // Make sure we don't add the same candidate twice.
5729 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5732 QualType ParamTypes[2] = {
5733 S.Context.getLValueReferenceType(*Ptr),
5737 // non-volatile version
5738 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5739 /*IsAssigmentOperator=*/true);
5741 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5742 VisibleTypeConversionsQuals.hasVolatile()) {
5745 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5746 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5747 CandidateSet, /*IsAssigmentOperator=*/true);
5753 // C++ [over.built]p18:
5755 // For every triple (L, VQ, R), where L is an arithmetic type,
5756 // VQ is either volatile or empty, and R is a promoted
5757 // arithmetic type, there exist candidate operator functions of
5760 // VQ L& operator=(VQ L&, R);
5761 // VQ L& operator*=(VQ L&, R);
5762 // VQ L& operator/=(VQ L&, R);
5763 // VQ L& operator+=(VQ L&, R);
5764 // VQ L& operator-=(VQ L&, R);
5765 void addAssignmentArithmeticOverloads(bool isEqualOp) {
5766 if (!HasArithmeticOrEnumeralCandidateType)
5769 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5770 for (unsigned Right = FirstPromotedArithmeticType;
5771 Right < LastPromotedArithmeticType; ++Right) {
5772 QualType ParamTypes[2];
5773 ParamTypes[1] = getArithmeticType(Right);
5775 // Add this built-in operator as a candidate (VQ is empty).
5777 S.Context.getLValueReferenceType(getArithmeticType(Left));
5778 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5779 /*IsAssigmentOperator=*/isEqualOp);
5781 // Add this built-in operator as a candidate (VQ is 'volatile').
5782 if (VisibleTypeConversionsQuals.hasVolatile()) {
5784 S.Context.getVolatileType(getArithmeticType(Left));
5785 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5786 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5788 /*IsAssigmentOperator=*/isEqualOp);
5793 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5794 for (BuiltinCandidateTypeSet::iterator
5795 Vec1 = CandidateTypes[0].vector_begin(),
5796 Vec1End = CandidateTypes[0].vector_end();
5797 Vec1 != Vec1End; ++Vec1) {
5798 for (BuiltinCandidateTypeSet::iterator
5799 Vec2 = CandidateTypes[1].vector_begin(),
5800 Vec2End = CandidateTypes[1].vector_end();
5801 Vec2 != Vec2End; ++Vec2) {
5802 QualType ParamTypes[2];
5803 ParamTypes[1] = *Vec2;
5804 // Add this built-in operator as a candidate (VQ is empty).
5805 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
5806 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5807 /*IsAssigmentOperator=*/isEqualOp);
5809 // Add this built-in operator as a candidate (VQ is 'volatile').
5810 if (VisibleTypeConversionsQuals.hasVolatile()) {
5811 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
5812 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5813 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5815 /*IsAssigmentOperator=*/isEqualOp);
5821 // C++ [over.built]p22:
5823 // For every triple (L, VQ, R), where L is an integral type, VQ
5824 // is either volatile or empty, and R is a promoted integral
5825 // type, there exist candidate operator functions of the form
5827 // VQ L& operator%=(VQ L&, R);
5828 // VQ L& operator<<=(VQ L&, R);
5829 // VQ L& operator>>=(VQ L&, R);
5830 // VQ L& operator&=(VQ L&, R);
5831 // VQ L& operator^=(VQ L&, R);
5832 // VQ L& operator|=(VQ L&, R);
5833 void addAssignmentIntegralOverloads() {
5834 if (!HasArithmeticOrEnumeralCandidateType)
5837 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
5838 for (unsigned Right = FirstPromotedIntegralType;
5839 Right < LastPromotedIntegralType; ++Right) {
5840 QualType ParamTypes[2];
5841 ParamTypes[1] = getArithmeticType(Right);
5843 // Add this built-in operator as a candidate (VQ is empty).
5845 S.Context.getLValueReferenceType(getArithmeticType(Left));
5846 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5847 if (VisibleTypeConversionsQuals.hasVolatile()) {
5848 // Add this built-in operator as a candidate (VQ is 'volatile').
5849 ParamTypes[0] = getArithmeticType(Left);
5850 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
5851 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5852 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5859 // C++ [over.operator]p23:
5861 // There also exist candidate operator functions of the form
5863 // bool operator!(bool);
5864 // bool operator&&(bool, bool);
5865 // bool operator||(bool, bool);
5866 void addExclaimOverload() {
5867 QualType ParamTy = S.Context.BoolTy;
5868 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5869 /*IsAssignmentOperator=*/false,
5870 /*NumContextualBoolArguments=*/1);
5872 void addAmpAmpOrPipePipeOverload() {
5873 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
5874 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5875 /*IsAssignmentOperator=*/false,
5876 /*NumContextualBoolArguments=*/2);
5879 // C++ [over.built]p13:
5881 // For every cv-qualified or cv-unqualified object type T there
5882 // exist candidate operator functions of the form
5884 // T* operator+(T*, ptrdiff_t); [ABOVE]
5885 // T& operator[](T*, ptrdiff_t);
5886 // T* operator-(T*, ptrdiff_t); [ABOVE]
5887 // T* operator+(ptrdiff_t, T*); [ABOVE]
5888 // T& operator[](ptrdiff_t, T*);
5889 void addSubscriptOverloads() {
5890 for (BuiltinCandidateTypeSet::iterator
5891 Ptr = CandidateTypes[0].pointer_begin(),
5892 PtrEnd = CandidateTypes[0].pointer_end();
5893 Ptr != PtrEnd; ++Ptr) {
5894 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
5895 QualType PointeeType = (*Ptr)->getPointeeType();
5896 if (!PointeeType->isObjectType())
5899 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5901 // T& operator[](T*, ptrdiff_t)
5902 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5905 for (BuiltinCandidateTypeSet::iterator
5906 Ptr = CandidateTypes[1].pointer_begin(),
5907 PtrEnd = CandidateTypes[1].pointer_end();
5908 Ptr != PtrEnd; ++Ptr) {
5909 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
5910 QualType PointeeType = (*Ptr)->getPointeeType();
5911 if (!PointeeType->isObjectType())
5914 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5916 // T& operator[](ptrdiff_t, T*)
5917 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5921 // C++ [over.built]p11:
5922 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5923 // C1 is the same type as C2 or is a derived class of C2, T is an object
5924 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5925 // there exist candidate operator functions of the form
5927 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5929 // where CV12 is the union of CV1 and CV2.
5930 void addArrowStarOverloads() {
5931 for (BuiltinCandidateTypeSet::iterator
5932 Ptr = CandidateTypes[0].pointer_begin(),
5933 PtrEnd = CandidateTypes[0].pointer_end();
5934 Ptr != PtrEnd; ++Ptr) {
5935 QualType C1Ty = (*Ptr);
5937 QualifierCollector Q1;
5938 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5939 if (!isa<RecordType>(C1))
5941 // heuristic to reduce number of builtin candidates in the set.
5942 // Add volatile/restrict version only if there are conversions to a
5943 // volatile/restrict type.
5944 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5946 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5948 for (BuiltinCandidateTypeSet::iterator
5949 MemPtr = CandidateTypes[1].member_pointer_begin(),
5950 MemPtrEnd = CandidateTypes[1].member_pointer_end();
5951 MemPtr != MemPtrEnd; ++MemPtr) {
5952 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5953 QualType C2 = QualType(mptr->getClass(), 0);
5954 C2 = C2.getUnqualifiedType();
5955 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
5957 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5959 QualType T = mptr->getPointeeType();
5960 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5961 T.isVolatileQualified())
5963 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5964 T.isRestrictQualified())
5966 T = Q1.apply(S.Context, T);
5967 QualType ResultTy = S.Context.getLValueReferenceType(T);
5968 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5973 // Note that we don't consider the first argument, since it has been
5974 // contextually converted to bool long ago. The candidates below are
5975 // therefore added as binary.
5977 // C++ [over.built]p25:
5978 // For every type T, where T is a pointer, pointer-to-member, or scoped
5979 // enumeration type, there exist candidate operator functions of the form
5981 // T operator?(bool, T, T);
5983 void addConditionalOperatorOverloads() {
5984 /// Set of (canonical) types that we've already handled.
5985 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5987 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5988 for (BuiltinCandidateTypeSet::iterator
5989 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5990 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5991 Ptr != PtrEnd; ++Ptr) {
5992 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5995 QualType ParamTypes[2] = { *Ptr, *Ptr };
5996 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5999 for (BuiltinCandidateTypeSet::iterator
6000 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6001 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6002 MemPtr != MemPtrEnd; ++MemPtr) {
6003 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6006 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6007 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6010 if (S.getLangOptions().CPlusPlus0x) {
6011 for (BuiltinCandidateTypeSet::iterator
6012 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6013 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6014 Enum != EnumEnd; ++Enum) {
6015 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6018 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6021 QualType ParamTypes[2] = { *Enum, *Enum };
6022 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6029 } // end anonymous namespace
6031 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
6032 /// operator overloads to the candidate set (C++ [over.built]), based
6033 /// on the operator @p Op and the arguments given. For example, if the
6034 /// operator is a binary '+', this routine might add "int
6035 /// operator+(int, int)" to cover integer addition.
6037 Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6038 SourceLocation OpLoc,
6039 Expr **Args, unsigned NumArgs,
6040 OverloadCandidateSet& CandidateSet) {
6041 // Find all of the types that the arguments can convert to, but only
6042 // if the operator we're looking at has built-in operator candidates
6043 // that make use of these types. Also record whether we encounter non-record
6044 // candidate types or either arithmetic or enumeral candidate types.
6045 Qualifiers VisibleTypeConversionsQuals;
6046 VisibleTypeConversionsQuals.addConst();
6047 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6048 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
6050 bool HasNonRecordCandidateType = false;
6051 bool HasArithmeticOrEnumeralCandidateType = false;
6052 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
6053 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6054 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6055 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6058 (Op == OO_Exclaim ||
6061 VisibleTypeConversionsQuals);
6062 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6063 CandidateTypes[ArgIdx].hasNonRecordTypes();
6064 HasArithmeticOrEnumeralCandidateType =
6065 HasArithmeticOrEnumeralCandidateType ||
6066 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
6069 // Exit early when no non-record types have been added to the candidate set
6070 // for any of the arguments to the operator.
6071 if (!HasNonRecordCandidateType)
6074 // Setup an object to manage the common state for building overloads.
6075 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6076 VisibleTypeConversionsQuals,
6077 HasArithmeticOrEnumeralCandidateType,
6078 CandidateTypes, CandidateSet);
6080 // Dispatch over the operation to add in only those overloads which apply.
6083 case NUM_OVERLOADED_OPERATORS:
6084 assert(false && "Expected an overloaded operator");
6090 case OO_Array_Delete:
6092 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
6097 // C++ [over.match.oper]p3:
6098 // -- For the operator ',', the unary operator '&', or the
6099 // operator '->', the built-in candidates set is empty.
6102 case OO_Plus: // '+' is either unary or binary
6104 OpBuilder.addUnaryPlusPointerOverloads();
6107 case OO_Minus: // '-' is either unary or binary
6109 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
6111 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6112 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6116 case OO_Star: // '*' is either unary or binary
6118 OpBuilder.addUnaryStarPointerOverloads();
6120 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6124 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6129 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6130 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
6134 case OO_ExclaimEqual:
6135 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
6141 case OO_GreaterEqual:
6142 OpBuilder.addRelationalPointerOrEnumeralOverloads();
6143 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6150 case OO_GreaterGreater:
6151 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6154 case OO_Amp: // '&' is either unary or binary
6156 // C++ [over.match.oper]p3:
6157 // -- For the operator ',', the unary operator '&', or the
6158 // operator '->', the built-in candidates set is empty.
6161 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6165 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6169 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
6174 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
6179 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
6182 case OO_PercentEqual:
6183 case OO_LessLessEqual:
6184 case OO_GreaterGreaterEqual:
6188 OpBuilder.addAssignmentIntegralOverloads();
6192 OpBuilder.addExclaimOverload();
6197 OpBuilder.addAmpAmpOrPipePipeOverload();
6201 OpBuilder.addSubscriptOverloads();
6205 OpBuilder.addArrowStarOverloads();
6208 case OO_Conditional:
6209 OpBuilder.addConditionalOperatorOverloads();
6210 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6215 /// \brief Add function candidates found via argument-dependent lookup
6216 /// to the set of overloading candidates.
6218 /// This routine performs argument-dependent name lookup based on the
6219 /// given function name (which may also be an operator name) and adds
6220 /// all of the overload candidates found by ADL to the overload
6221 /// candidate set (C++ [basic.lookup.argdep]).
6223 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
6225 Expr **Args, unsigned NumArgs,
6226 TemplateArgumentListInfo *ExplicitTemplateArgs,
6227 OverloadCandidateSet& CandidateSet,
6228 bool PartialOverloading,
6229 bool StdNamespaceIsAssociated) {
6232 // FIXME: This approach for uniquing ADL results (and removing
6233 // redundant candidates from the set) relies on pointer-equality,
6234 // which means we need to key off the canonical decl. However,
6235 // always going back to the canonical decl might not get us the
6236 // right set of default arguments. What default arguments are
6237 // we supposed to consider on ADL candidates, anyway?
6239 // FIXME: Pass in the explicit template arguments?
6240 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6241 StdNamespaceIsAssociated);
6243 // Erase all of the candidates we already knew about.
6244 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6245 CandEnd = CandidateSet.end();
6246 Cand != CandEnd; ++Cand)
6247 if (Cand->Function) {
6248 Fns.erase(Cand->Function);
6249 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
6253 // For each of the ADL candidates we found, add it to the overload
6255 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
6256 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
6257 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
6258 if (ExplicitTemplateArgs)
6261 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
6262 false, PartialOverloading);
6264 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
6265 FoundDecl, ExplicitTemplateArgs,
6266 Args, NumArgs, CandidateSet);
6270 /// isBetterOverloadCandidate - Determines whether the first overload
6271 /// candidate is a better candidate than the second (C++ 13.3.3p1).
6273 isBetterOverloadCandidate(Sema &S,
6274 const OverloadCandidate &Cand1,
6275 const OverloadCandidate &Cand2,
6277 bool UserDefinedConversion) {
6278 // Define viable functions to be better candidates than non-viable
6281 return Cand1.Viable;
6282 else if (!Cand1.Viable)
6285 // C++ [over.match.best]p1:
6287 // -- if F is a static member function, ICS1(F) is defined such
6288 // that ICS1(F) is neither better nor worse than ICS1(G) for
6289 // any function G, and, symmetrically, ICS1(G) is neither
6290 // better nor worse than ICS1(F).
6291 unsigned StartArg = 0;
6292 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6295 // C++ [over.match.best]p1:
6296 // A viable function F1 is defined to be a better function than another
6297 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
6298 // conversion sequence than ICSi(F2), and then...
6299 unsigned NumArgs = Cand1.Conversions.size();
6300 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6301 bool HasBetterConversion = false;
6302 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
6303 switch (CompareImplicitConversionSequences(S,
6304 Cand1.Conversions[ArgIdx],
6305 Cand2.Conversions[ArgIdx])) {
6306 case ImplicitConversionSequence::Better:
6307 // Cand1 has a better conversion sequence.
6308 HasBetterConversion = true;
6311 case ImplicitConversionSequence::Worse:
6312 // Cand1 can't be better than Cand2.
6315 case ImplicitConversionSequence::Indistinguishable:
6321 // -- for some argument j, ICSj(F1) is a better conversion sequence than
6322 // ICSj(F2), or, if not that,
6323 if (HasBetterConversion)
6326 // - F1 is a non-template function and F2 is a function template
6327 // specialization, or, if not that,
6328 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
6329 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6332 // -- F1 and F2 are function template specializations, and the function
6333 // template for F1 is more specialized than the template for F2
6334 // according to the partial ordering rules described in 14.5.5.2, or,
6336 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
6337 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
6338 if (FunctionTemplateDecl *BetterTemplate
6339 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6340 Cand2.Function->getPrimaryTemplate(),
6342 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
6344 Cand1.ExplicitCallArguments))
6345 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
6348 // -- the context is an initialization by user-defined conversion
6349 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6350 // from the return type of F1 to the destination type (i.e.,
6351 // the type of the entity being initialized) is a better
6352 // conversion sequence than the standard conversion sequence
6353 // from the return type of F2 to the destination type.
6354 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
6355 isa<CXXConversionDecl>(Cand1.Function) &&
6356 isa<CXXConversionDecl>(Cand2.Function)) {
6357 switch (CompareStandardConversionSequences(S,
6358 Cand1.FinalConversion,
6359 Cand2.FinalConversion)) {
6360 case ImplicitConversionSequence::Better:
6361 // Cand1 has a better conversion sequence.
6364 case ImplicitConversionSequence::Worse:
6365 // Cand1 can't be better than Cand2.
6368 case ImplicitConversionSequence::Indistinguishable:
6377 /// \brief Computes the best viable function (C++ 13.3.3)
6378 /// within an overload candidate set.
6380 /// \param CandidateSet the set of candidate functions.
6382 /// \param Loc the location of the function name (or operator symbol) for
6383 /// which overload resolution occurs.
6385 /// \param Best f overload resolution was successful or found a deleted
6386 /// function, Best points to the candidate function found.
6388 /// \returns The result of overload resolution.
6390 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
6392 bool UserDefinedConversion) {
6393 // Find the best viable function.
6395 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6397 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
6398 UserDefinedConversion))
6402 // If we didn't find any viable functions, abort.
6404 return OR_No_Viable_Function;
6406 // Make sure that this function is better than every other viable
6407 // function. If not, we have an ambiguity.
6408 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6411 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
6412 UserDefinedConversion)) {
6414 return OR_Ambiguous;
6418 // Best is the best viable function.
6419 if (Best->Function &&
6420 (Best->Function->isDeleted() || Best->Function->isUnavailable()))
6428 enum OverloadCandidateKind {
6432 oc_function_template,
6434 oc_constructor_template,
6435 oc_implicit_default_constructor,
6436 oc_implicit_copy_constructor,
6437 oc_implicit_move_constructor,
6438 oc_implicit_copy_assignment,
6439 oc_implicit_move_assignment,
6440 oc_implicit_inherited_constructor
6443 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6445 std::string &Description) {
6446 bool isTemplate = false;
6448 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6450 Description = S.getTemplateArgumentBindingsText(
6451 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6454 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
6455 if (!Ctor->isImplicit())
6456 return isTemplate ? oc_constructor_template : oc_constructor;
6458 if (Ctor->getInheritedConstructor())
6459 return oc_implicit_inherited_constructor;
6461 if (Ctor->isDefaultConstructor())
6462 return oc_implicit_default_constructor;
6464 if (Ctor->isMoveConstructor())
6465 return oc_implicit_move_constructor;
6467 assert(Ctor->isCopyConstructor() &&
6468 "unexpected sort of implicit constructor");
6469 return oc_implicit_copy_constructor;
6472 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6473 // This actually gets spelled 'candidate function' for now, but
6474 // it doesn't hurt to split it out.
6475 if (!Meth->isImplicit())
6476 return isTemplate ? oc_method_template : oc_method;
6478 if (Meth->isMoveAssignmentOperator())
6479 return oc_implicit_move_assignment;
6481 assert(Meth->isCopyAssignmentOperator()
6482 && "implicit method is not copy assignment operator?");
6483 return oc_implicit_copy_assignment;
6486 return isTemplate ? oc_function_template : oc_function;
6489 void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
6490 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
6493 Ctor = Ctor->getInheritedConstructor();
6496 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
6499 } // end anonymous namespace
6501 // Notes the location of an overload candidate.
6502 void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
6504 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6505 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6506 << (unsigned) K << FnDesc;
6507 MaybeEmitInheritedConstructorNote(*this, Fn);
6510 //Notes the location of all overload candidates designated through
6512 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) {
6513 assert(OverloadedExpr->getType() == Context.OverloadTy);
6515 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
6516 OverloadExpr *OvlExpr = Ovl.Expression;
6518 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6519 IEnd = OvlExpr->decls_end();
6521 if (FunctionTemplateDecl *FunTmpl =
6522 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
6523 NoteOverloadCandidate(FunTmpl->getTemplatedDecl());
6524 } else if (FunctionDecl *Fun
6525 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
6526 NoteOverloadCandidate(Fun);
6531 /// Diagnoses an ambiguous conversion. The partial diagnostic is the
6532 /// "lead" diagnostic; it will be given two arguments, the source and
6533 /// target types of the conversion.
6534 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6536 SourceLocation CaretLoc,
6537 const PartialDiagnostic &PDiag) const {
6538 S.Diag(CaretLoc, PDiag)
6539 << Ambiguous.getFromType() << Ambiguous.getToType();
6540 for (AmbiguousConversionSequence::const_iterator
6541 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6542 S.NoteOverloadCandidate(*I);
6548 void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6549 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6550 assert(Conv.isBad());
6551 assert(Cand->Function && "for now, candidate must be a function");
6552 FunctionDecl *Fn = Cand->Function;
6554 // There's a conversion slot for the object argument if this is a
6555 // non-constructor method. Note that 'I' corresponds the
6556 // conversion-slot index.
6557 bool isObjectArgument = false;
6558 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
6560 isObjectArgument = true;
6566 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6568 Expr *FromExpr = Conv.Bad.FromExpr;
6569 QualType FromTy = Conv.Bad.getFromType();
6570 QualType ToTy = Conv.Bad.getToType();
6572 if (FromTy == S.Context.OverloadTy) {
6573 assert(FromExpr && "overload set argument came from implicit argument?");
6574 Expr *E = FromExpr->IgnoreParens();
6575 if (isa<UnaryOperator>(E))
6576 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
6577 DeclarationName Name = cast<OverloadExpr>(E)->getName();
6579 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6580 << (unsigned) FnKind << FnDesc
6581 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6582 << ToTy << Name << I+1;
6583 MaybeEmitInheritedConstructorNote(S, Fn);
6587 // Do some hand-waving analysis to see if the non-viability is due
6588 // to a qualifier mismatch.
6589 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6590 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6591 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6592 CToTy = RT->getPointeeType();
6594 // TODO: detect and diagnose the full richness of const mismatches.
6595 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6596 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6597 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6600 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6601 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6602 // It is dumb that we have to do this here.
6603 while (isa<ArrayType>(CFromTy))
6604 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6605 while (isa<ArrayType>(CToTy))
6606 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6608 Qualifiers FromQs = CFromTy.getQualifiers();
6609 Qualifiers ToQs = CToTy.getQualifiers();
6611 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6612 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6613 << (unsigned) FnKind << FnDesc
6614 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6616 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6617 << (unsigned) isObjectArgument << I+1;
6618 MaybeEmitInheritedConstructorNote(S, Fn);
6622 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
6623 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
6624 << (unsigned) FnKind << FnDesc
6625 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6627 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
6628 << (unsigned) isObjectArgument << I+1;
6629 MaybeEmitInheritedConstructorNote(S, Fn);
6633 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6634 assert(CVR && "unexpected qualifiers mismatch");
6636 if (isObjectArgument) {
6637 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6638 << (unsigned) FnKind << FnDesc
6639 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6640 << FromTy << (CVR - 1);
6642 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6643 << (unsigned) FnKind << FnDesc
6644 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6645 << FromTy << (CVR - 1) << I+1;
6647 MaybeEmitInheritedConstructorNote(S, Fn);
6651 // Diagnose references or pointers to incomplete types differently,
6652 // since it's far from impossible that the incompleteness triggered
6654 QualType TempFromTy = FromTy.getNonReferenceType();
6655 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6656 TempFromTy = PTy->getPointeeType();
6657 if (TempFromTy->isIncompleteType()) {
6658 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6659 << (unsigned) FnKind << FnDesc
6660 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6661 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6662 MaybeEmitInheritedConstructorNote(S, Fn);
6666 // Diagnose base -> derived pointer conversions.
6667 unsigned BaseToDerivedConversion = 0;
6668 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6669 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6670 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6671 FromPtrTy->getPointeeType()) &&
6672 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6673 !ToPtrTy->getPointeeType()->isIncompleteType() &&
6674 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
6675 FromPtrTy->getPointeeType()))
6676 BaseToDerivedConversion = 1;
6678 } else if (const ObjCObjectPointerType *FromPtrTy
6679 = FromTy->getAs<ObjCObjectPointerType>()) {
6680 if (const ObjCObjectPointerType *ToPtrTy
6681 = ToTy->getAs<ObjCObjectPointerType>())
6682 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6683 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6684 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6685 FromPtrTy->getPointeeType()) &&
6686 FromIface->isSuperClassOf(ToIface))
6687 BaseToDerivedConversion = 2;
6688 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6689 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6690 !FromTy->isIncompleteType() &&
6691 !ToRefTy->getPointeeType()->isIncompleteType() &&
6692 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6693 BaseToDerivedConversion = 3;
6696 if (BaseToDerivedConversion) {
6697 S.Diag(Fn->getLocation(),
6698 diag::note_ovl_candidate_bad_base_to_derived_conv)
6699 << (unsigned) FnKind << FnDesc
6700 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6701 << (BaseToDerivedConversion - 1)
6702 << FromTy << ToTy << I+1;
6703 MaybeEmitInheritedConstructorNote(S, Fn);
6707 // TODO: specialize more based on the kind of mismatch
6708 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
6709 << (unsigned) FnKind << FnDesc
6710 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6711 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6712 MaybeEmitInheritedConstructorNote(S, Fn);
6715 void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6716 unsigned NumFormalArgs) {
6717 // TODO: treat calls to a missing default constructor as a special case
6719 FunctionDecl *Fn = Cand->Function;
6720 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6722 unsigned MinParams = Fn->getMinRequiredArguments();
6724 // With invalid overloaded operators, it's possible that we think we
6725 // have an arity mismatch when it fact it looks like we have the
6726 // right number of arguments, because only overloaded operators have
6727 // the weird behavior of overloading member and non-member functions.
6728 // Just don't report anything.
6729 if (Fn->isInvalidDecl() &&
6730 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
6733 // at least / at most / exactly
6734 unsigned mode, modeCount;
6735 if (NumFormalArgs < MinParams) {
6736 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6737 (Cand->FailureKind == ovl_fail_bad_deduction &&
6738 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
6739 if (MinParams != FnTy->getNumArgs() ||
6740 FnTy->isVariadic() || FnTy->isTemplateVariadic())
6741 mode = 0; // "at least"
6743 mode = 2; // "exactly"
6744 modeCount = MinParams;
6746 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6747 (Cand->FailureKind == ovl_fail_bad_deduction &&
6748 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
6749 if (MinParams != FnTy->getNumArgs())
6750 mode = 1; // "at most"
6752 mode = 2; // "exactly"
6753 modeCount = FnTy->getNumArgs();
6756 std::string Description;
6757 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6759 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
6760 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
6761 << modeCount << NumFormalArgs;
6762 MaybeEmitInheritedConstructorNote(S, Fn);
6765 /// Diagnose a failed template-argument deduction.
6766 void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6767 Expr **Args, unsigned NumArgs) {
6768 FunctionDecl *Fn = Cand->Function; // pattern
6770 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
6772 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6773 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6774 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
6775 switch (Cand->DeductionFailure.Result) {
6776 case Sema::TDK_Success:
6777 llvm_unreachable("TDK_success while diagnosing bad deduction");
6779 case Sema::TDK_Incomplete: {
6780 assert(ParamD && "no parameter found for incomplete deduction result");
6781 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6782 << ParamD->getDeclName();
6783 MaybeEmitInheritedConstructorNote(S, Fn);
6787 case Sema::TDK_Underqualified: {
6788 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6789 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6791 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6793 // Param will have been canonicalized, but it should just be a
6794 // qualified version of ParamD, so move the qualifiers to that.
6795 QualifierCollector Qs;
6797 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
6798 assert(S.Context.hasSameType(Param, NonCanonParam));
6800 // Arg has also been canonicalized, but there's nothing we can do
6801 // about that. It also doesn't matter as much, because it won't
6802 // have any template parameters in it (because deduction isn't
6803 // done on dependent types).
6804 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6806 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6807 << ParamD->getDeclName() << Arg << NonCanonParam;
6808 MaybeEmitInheritedConstructorNote(S, Fn);
6812 case Sema::TDK_Inconsistent: {
6813 assert(ParamD && "no parameter found for inconsistent deduction result");
6815 if (isa<TemplateTypeParmDecl>(ParamD))
6817 else if (isa<NonTypeTemplateParmDecl>(ParamD))
6823 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
6824 << which << ParamD->getDeclName()
6825 << *Cand->DeductionFailure.getFirstArg()
6826 << *Cand->DeductionFailure.getSecondArg();
6827 MaybeEmitInheritedConstructorNote(S, Fn);
6831 case Sema::TDK_InvalidExplicitArguments:
6832 assert(ParamD && "no parameter found for invalid explicit arguments");
6833 if (ParamD->getDeclName())
6834 S.Diag(Fn->getLocation(),
6835 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6836 << ParamD->getDeclName();
6839 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6840 index = TTP->getIndex();
6841 else if (NonTypeTemplateParmDecl *NTTP
6842 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6843 index = NTTP->getIndex();
6845 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
6846 S.Diag(Fn->getLocation(),
6847 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6850 MaybeEmitInheritedConstructorNote(S, Fn);
6853 case Sema::TDK_TooManyArguments:
6854 case Sema::TDK_TooFewArguments:
6855 DiagnoseArityMismatch(S, Cand, NumArgs);
6858 case Sema::TDK_InstantiationDepth:
6859 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
6860 MaybeEmitInheritedConstructorNote(S, Fn);
6863 case Sema::TDK_SubstitutionFailure: {
6864 std::string ArgString;
6865 if (TemplateArgumentList *Args
6866 = Cand->DeductionFailure.getTemplateArgumentList())
6867 ArgString = S.getTemplateArgumentBindingsText(
6868 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6870 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6872 MaybeEmitInheritedConstructorNote(S, Fn);
6876 // TODO: diagnose these individually, then kill off
6877 // note_ovl_candidate_bad_deduction, which is uselessly vague.
6878 case Sema::TDK_NonDeducedMismatch:
6879 case Sema::TDK_FailedOverloadResolution:
6880 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
6881 MaybeEmitInheritedConstructorNote(S, Fn);
6886 /// Generates a 'note' diagnostic for an overload candidate. We've
6887 /// already generated a primary error at the call site.
6889 /// It really does need to be a single diagnostic with its caret
6890 /// pointed at the candidate declaration. Yes, this creates some
6891 /// major challenges of technical writing. Yes, this makes pointing
6892 /// out problems with specific arguments quite awkward. It's still
6893 /// better than generating twenty screens of text for every failed
6896 /// It would be great to be able to express per-candidate problems
6897 /// more richly for those diagnostic clients that cared, but we'd
6898 /// still have to be just as careful with the default diagnostics.
6899 void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6900 Expr **Args, unsigned NumArgs) {
6901 FunctionDecl *Fn = Cand->Function;
6903 // Note deleted candidates, but only if they're viable.
6904 if (Cand->Viable && (Fn->isDeleted() || Fn->isUnavailable())) {
6906 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6908 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
6909 << FnKind << FnDesc << Fn->isDeleted();
6910 MaybeEmitInheritedConstructorNote(S, Fn);
6914 // We don't really have anything else to say about viable candidates.
6916 S.NoteOverloadCandidate(Fn);
6920 switch (Cand->FailureKind) {
6921 case ovl_fail_too_many_arguments:
6922 case ovl_fail_too_few_arguments:
6923 return DiagnoseArityMismatch(S, Cand, NumArgs);
6925 case ovl_fail_bad_deduction:
6926 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6928 case ovl_fail_trivial_conversion:
6929 case ovl_fail_bad_final_conversion:
6930 case ovl_fail_final_conversion_not_exact:
6931 return S.NoteOverloadCandidate(Fn);
6933 case ovl_fail_bad_conversion: {
6934 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6935 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
6936 if (Cand->Conversions[I].isBad())
6937 return DiagnoseBadConversion(S, Cand, I);
6939 // FIXME: this currently happens when we're called from SemaInit
6940 // when user-conversion overload fails. Figure out how to handle
6941 // those conditions and diagnose them well.
6942 return S.NoteOverloadCandidate(Fn);
6947 void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6948 // Desugar the type of the surrogate down to a function type,
6949 // retaining as many typedefs as possible while still showing
6950 // the function type (and, therefore, its parameter types).
6951 QualType FnType = Cand->Surrogate->getConversionType();
6952 bool isLValueReference = false;
6953 bool isRValueReference = false;
6954 bool isPointer = false;
6955 if (const LValueReferenceType *FnTypeRef =
6956 FnType->getAs<LValueReferenceType>()) {
6957 FnType = FnTypeRef->getPointeeType();
6958 isLValueReference = true;
6959 } else if (const RValueReferenceType *FnTypeRef =
6960 FnType->getAs<RValueReferenceType>()) {
6961 FnType = FnTypeRef->getPointeeType();
6962 isRValueReference = true;
6964 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6965 FnType = FnTypePtr->getPointeeType();
6968 // Desugar down to a function type.
6969 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6970 // Reconstruct the pointer/reference as appropriate.
6971 if (isPointer) FnType = S.Context.getPointerType(FnType);
6972 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6973 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6975 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6977 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
6980 void NoteBuiltinOperatorCandidate(Sema &S,
6982 SourceLocation OpLoc,
6983 OverloadCandidate *Cand) {
6984 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6985 std::string TypeStr("operator");
6988 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6989 if (Cand->Conversions.size() == 1) {
6991 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6994 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6996 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
7000 void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7001 OverloadCandidate *Cand) {
7002 unsigned NoOperands = Cand->Conversions.size();
7003 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7004 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
7005 if (ICS.isBad()) break; // all meaningless after first invalid
7006 if (!ICS.isAmbiguous()) continue;
7008 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
7009 S.PDiag(diag::note_ambiguous_type_conversion));
7013 SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7015 return Cand->Function->getLocation();
7016 if (Cand->IsSurrogate)
7017 return Cand->Surrogate->getLocation();
7018 return SourceLocation();
7021 struct CompareOverloadCandidatesForDisplay {
7023 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
7025 bool operator()(const OverloadCandidate *L,
7026 const OverloadCandidate *R) {
7027 // Fast-path this check.
7028 if (L == R) return false;
7030 // Order first by viability.
7032 if (!R->Viable) return true;
7034 // TODO: introduce a tri-valued comparison for overload
7035 // candidates. Would be more worthwhile if we had a sort
7036 // that could exploit it.
7037 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7038 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
7039 } else if (R->Viable)
7042 assert(L->Viable == R->Viable);
7044 // Criteria by which we can sort non-viable candidates:
7046 // 1. Arity mismatches come after other candidates.
7047 if (L->FailureKind == ovl_fail_too_many_arguments ||
7048 L->FailureKind == ovl_fail_too_few_arguments)
7050 if (R->FailureKind == ovl_fail_too_many_arguments ||
7051 R->FailureKind == ovl_fail_too_few_arguments)
7054 // 2. Bad conversions come first and are ordered by the number
7055 // of bad conversions and quality of good conversions.
7056 if (L->FailureKind == ovl_fail_bad_conversion) {
7057 if (R->FailureKind != ovl_fail_bad_conversion)
7060 // If there's any ordering between the defined conversions...
7061 // FIXME: this might not be transitive.
7062 assert(L->Conversions.size() == R->Conversions.size());
7065 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
7066 for (unsigned E = L->Conversions.size(); I != E; ++I) {
7067 switch (CompareImplicitConversionSequences(S,
7069 R->Conversions[I])) {
7070 case ImplicitConversionSequence::Better:
7074 case ImplicitConversionSequence::Worse:
7078 case ImplicitConversionSequence::Indistinguishable:
7082 if (leftBetter > 0) return true;
7083 if (leftBetter < 0) return false;
7085 } else if (R->FailureKind == ovl_fail_bad_conversion)
7091 // Sort everything else by location.
7092 SourceLocation LLoc = GetLocationForCandidate(L);
7093 SourceLocation RLoc = GetLocationForCandidate(R);
7095 // Put candidates without locations (e.g. builtins) at the end.
7096 if (LLoc.isInvalid()) return false;
7097 if (RLoc.isInvalid()) return true;
7099 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
7103 /// CompleteNonViableCandidate - Normally, overload resolution only
7104 /// computes up to the first
7105 void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7106 Expr **Args, unsigned NumArgs) {
7107 assert(!Cand->Viable);
7109 // Don't do anything on failures other than bad conversion.
7110 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7112 // Skip forward to the first bad conversion.
7113 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
7114 unsigned ConvCount = Cand->Conversions.size();
7116 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7118 if (Cand->Conversions[ConvIdx - 1].isBad())
7122 if (ConvIdx == ConvCount)
7125 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7126 "remaining conversion is initialized?");
7128 // FIXME: this should probably be preserved from the overload
7129 // operation somehow.
7130 bool SuppressUserConversions = false;
7132 const FunctionProtoType* Proto;
7133 unsigned ArgIdx = ConvIdx;
7135 if (Cand->IsSurrogate) {
7137 = Cand->Surrogate->getConversionType().getNonReferenceType();
7138 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7139 ConvType = ConvPtrType->getPointeeType();
7140 Proto = ConvType->getAs<FunctionProtoType>();
7142 } else if (Cand->Function) {
7143 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7144 if (isa<CXXMethodDecl>(Cand->Function) &&
7145 !isa<CXXConstructorDecl>(Cand->Function))
7148 // Builtin binary operator with a bad first conversion.
7149 assert(ConvCount <= 3);
7150 for (; ConvIdx != ConvCount; ++ConvIdx)
7151 Cand->Conversions[ConvIdx]
7152 = TryCopyInitialization(S, Args[ConvIdx],
7153 Cand->BuiltinTypes.ParamTypes[ConvIdx],
7154 SuppressUserConversions,
7155 /*InOverloadResolution*/ true);
7159 // Fill in the rest of the conversions.
7160 unsigned NumArgsInProto = Proto->getNumArgs();
7161 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
7162 if (ArgIdx < NumArgsInProto)
7163 Cand->Conversions[ConvIdx]
7164 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
7165 SuppressUserConversions,
7166 /*InOverloadResolution=*/true);
7168 Cand->Conversions[ConvIdx].setEllipsis();
7172 } // end anonymous namespace
7174 /// PrintOverloadCandidates - When overload resolution fails, prints
7175 /// diagnostic messages containing the candidates in the candidate
7177 void OverloadCandidateSet::NoteCandidates(Sema &S,
7178 OverloadCandidateDisplayKind OCD,
7179 Expr **Args, unsigned NumArgs,
7181 SourceLocation OpLoc) {
7182 // Sort the candidates by viability and position. Sorting directly would
7183 // be prohibitive, so we make a set of pointers and sort those.
7184 llvm::SmallVector<OverloadCandidate*, 32> Cands;
7185 if (OCD == OCD_AllCandidates) Cands.reserve(size());
7186 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
7188 Cands.push_back(Cand);
7189 else if (OCD == OCD_AllCandidates) {
7190 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
7191 if (Cand->Function || Cand->IsSurrogate)
7192 Cands.push_back(Cand);
7193 // Otherwise, this a non-viable builtin candidate. We do not, in general,
7194 // want to list every possible builtin candidate.
7198 std::sort(Cands.begin(), Cands.end(),
7199 CompareOverloadCandidatesForDisplay(S));
7201 bool ReportedAmbiguousConversions = false;
7203 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
7204 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
7205 unsigned CandsShown = 0;
7206 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7207 OverloadCandidate *Cand = *I;
7209 // Set an arbitrary limit on the number of candidate functions we'll spam
7210 // the user with. FIXME: This limit should depend on details of the
7212 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
7218 NoteFunctionCandidate(S, Cand, Args, NumArgs);
7219 else if (Cand->IsSurrogate)
7220 NoteSurrogateCandidate(S, Cand);
7222 assert(Cand->Viable &&
7223 "Non-viable built-in candidates are not added to Cands.");
7224 // Generally we only see ambiguities including viable builtin
7225 // operators if overload resolution got screwed up by an
7226 // ambiguous user-defined conversion.
7228 // FIXME: It's quite possible for different conversions to see
7229 // different ambiguities, though.
7230 if (!ReportedAmbiguousConversions) {
7231 NoteAmbiguousUserConversions(S, OpLoc, Cand);
7232 ReportedAmbiguousConversions = true;
7235 // If this is a viable builtin, print it.
7236 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
7241 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
7244 // [PossiblyAFunctionType] --> [Return]
7245 // NonFunctionType --> NonFunctionType
7247 // R (*)(A) --> R (A)
7248 // R (&)(A) --> R (A)
7249 // R (S::*)(A) --> R (A)
7250 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
7251 QualType Ret = PossiblyAFunctionType;
7252 if (const PointerType *ToTypePtr =
7253 PossiblyAFunctionType->getAs<PointerType>())
7254 Ret = ToTypePtr->getPointeeType();
7255 else if (const ReferenceType *ToTypeRef =
7256 PossiblyAFunctionType->getAs<ReferenceType>())
7257 Ret = ToTypeRef->getPointeeType();
7258 else if (const MemberPointerType *MemTypePtr =
7259 PossiblyAFunctionType->getAs<MemberPointerType>())
7260 Ret = MemTypePtr->getPointeeType();
7262 Context.getCanonicalType(Ret).getUnqualifiedType();
7266 // A helper class to help with address of function resolution
7267 // - allows us to avoid passing around all those ugly parameters
7268 class AddressOfFunctionResolver
7272 const QualType& TargetType;
7273 QualType TargetFunctionType; // Extracted function type from target type
7276 //DeclAccessPair& ResultFunctionAccessPair;
7277 ASTContext& Context;
7279 bool TargetTypeIsNonStaticMemberFunction;
7280 bool FoundNonTemplateFunction;
7282 OverloadExpr::FindResult OvlExprInfo;
7283 OverloadExpr *OvlExpr;
7284 TemplateArgumentListInfo OvlExplicitTemplateArgs;
7285 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
7288 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
7289 const QualType& TargetType, bool Complain)
7290 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
7291 Complain(Complain), Context(S.getASTContext()),
7292 TargetTypeIsNonStaticMemberFunction(
7293 !!TargetType->getAs<MemberPointerType>()),
7294 FoundNonTemplateFunction(false),
7295 OvlExprInfo(OverloadExpr::find(SourceExpr)),
7296 OvlExpr(OvlExprInfo.Expression)
7298 ExtractUnqualifiedFunctionTypeFromTargetType();
7300 if (!TargetFunctionType->isFunctionType()) {
7301 if (OvlExpr->hasExplicitTemplateArgs()) {
7303 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
7304 OvlExpr, false, &dap) ) {
7306 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7307 if (!Method->isStatic()) {
7308 // If the target type is a non-function type and the function
7309 // found is a non-static member function, pretend as if that was
7310 // the target, it's the only possible type to end up with.
7311 TargetTypeIsNonStaticMemberFunction = true;
7313 // And skip adding the function if its not in the proper form.
7314 // We'll diagnose this due to an empty set of functions.
7315 if (!OvlExprInfo.HasFormOfMemberPointer)
7320 Matches.push_back(std::make_pair(dap,Fn));
7326 if (OvlExpr->hasExplicitTemplateArgs())
7327 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
7329 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
7330 // C++ [over.over]p4:
7331 // If more than one function is selected, [...]
7332 if (Matches.size() > 1) {
7333 if (FoundNonTemplateFunction)
7334 EliminateAllTemplateMatches();
7336 EliminateAllExceptMostSpecializedTemplate();
7342 bool isTargetTypeAFunction() const {
7343 return TargetFunctionType->isFunctionType();
7346 // [ToType] [Return]
7348 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
7349 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
7350 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
7351 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
7352 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
7355 // return true if any matching specializations were found
7356 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
7357 const DeclAccessPair& CurAccessFunPair) {
7358 if (CXXMethodDecl *Method
7359 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
7360 // Skip non-static function templates when converting to pointer, and
7361 // static when converting to member pointer.
7362 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7365 else if (TargetTypeIsNonStaticMemberFunction)
7368 // C++ [over.over]p2:
7369 // If the name is a function template, template argument deduction is
7370 // done (14.8.2.2), and if the argument deduction succeeds, the
7371 // resulting template argument list is used to generate a single
7372 // function template specialization, which is added to the set of
7373 // overloaded functions considered.
7374 FunctionDecl *Specialization = 0;
7375 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
7376 if (Sema::TemplateDeductionResult Result
7377 = S.DeduceTemplateArguments(FunctionTemplate,
7378 &OvlExplicitTemplateArgs,
7379 TargetFunctionType, Specialization,
7381 // FIXME: make a note of the failed deduction for diagnostics.
7386 // Template argument deduction ensures that we have an exact match.
7387 // This function template specicalization works.
7388 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
7389 assert(TargetFunctionType
7390 == Context.getCanonicalType(Specialization->getType()));
7391 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
7395 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
7396 const DeclAccessPair& CurAccessFunPair) {
7397 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7398 // Skip non-static functions when converting to pointer, and static
7399 // when converting to member pointer.
7400 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7403 else if (TargetTypeIsNonStaticMemberFunction)
7406 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
7408 if (Context.hasSameUnqualifiedType(TargetFunctionType,
7409 FunDecl->getType()) ||
7410 IsNoReturnConversion(Context, FunDecl->getType(), TargetFunctionType,
7412 Matches.push_back(std::make_pair(CurAccessFunPair,
7413 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
7414 FoundNonTemplateFunction = true;
7422 bool FindAllFunctionsThatMatchTargetTypeExactly() {
7425 // If the overload expression doesn't have the form of a pointer to
7426 // member, don't try to convert it to a pointer-to-member type.
7427 if (IsInvalidFormOfPointerToMemberFunction())
7430 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7431 E = OvlExpr->decls_end();
7433 // Look through any using declarations to find the underlying function.
7434 NamedDecl *Fn = (*I)->getUnderlyingDecl();
7436 // C++ [over.over]p3:
7437 // Non-member functions and static member functions match
7438 // targets of type "pointer-to-function" or "reference-to-function."
7439 // Nonstatic member functions match targets of
7440 // type "pointer-to-member-function."
7441 // Note that according to DR 247, the containing class does not matter.
7442 if (FunctionTemplateDecl *FunctionTemplate
7443 = dyn_cast<FunctionTemplateDecl>(Fn)) {
7444 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
7447 // If we have explicit template arguments supplied, skip non-templates.
7448 else if (!OvlExpr->hasExplicitTemplateArgs() &&
7449 AddMatchingNonTemplateFunction(Fn, I.getPair()))
7452 assert(Ret || Matches.empty());
7456 void EliminateAllExceptMostSpecializedTemplate() {
7457 // [...] and any given function template specialization F1 is
7458 // eliminated if the set contains a second function template
7459 // specialization whose function template is more specialized
7460 // than the function template of F1 according to the partial
7461 // ordering rules of 14.5.5.2.
7463 // The algorithm specified above is quadratic. We instead use a
7464 // two-pass algorithm (similar to the one used to identify the
7465 // best viable function in an overload set) that identifies the
7466 // best function template (if it exists).
7468 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7469 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7470 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
7472 UnresolvedSetIterator Result =
7473 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
7474 TPOC_Other, 0, SourceExpr->getLocStart(),
7476 S.PDiag(diag::err_addr_ovl_ambiguous)
7477 << Matches[0].second->getDeclName(),
7478 S.PDiag(diag::note_ovl_candidate)
7479 << (unsigned) oc_function_template,
7482 if (Result != MatchesCopy.end()) {
7483 // Make it the first and only element
7484 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
7485 Matches[0].second = cast<FunctionDecl>(*Result);
7490 void EliminateAllTemplateMatches() {
7491 // [...] any function template specializations in the set are
7492 // eliminated if the set also contains a non-template function, [...]
7493 for (unsigned I = 0, N = Matches.size(); I != N; ) {
7494 if (Matches[I].second->getPrimaryTemplate() == 0)
7497 Matches[I] = Matches[--N];
7498 Matches.set_size(N);
7504 void ComplainNoMatchesFound() const {
7505 assert(Matches.empty());
7506 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
7507 << OvlExpr->getName() << TargetFunctionType
7508 << OvlExpr->getSourceRange();
7509 S.NoteAllOverloadCandidates(OvlExpr);
7512 bool IsInvalidFormOfPointerToMemberFunction() const {
7513 return TargetTypeIsNonStaticMemberFunction &&
7514 !OvlExprInfo.HasFormOfMemberPointer;
7517 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
7518 // TODO: Should we condition this on whether any functions might
7519 // have matched, or is it more appropriate to do that in callers?
7520 // TODO: a fixit wouldn't hurt.
7521 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
7522 << TargetType << OvlExpr->getSourceRange();
7525 void ComplainOfInvalidConversion() const {
7526 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
7527 << OvlExpr->getName() << TargetType;
7530 void ComplainMultipleMatchesFound() const {
7531 assert(Matches.size() > 1);
7532 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
7533 << OvlExpr->getName()
7534 << OvlExpr->getSourceRange();
7535 S.NoteAllOverloadCandidates(OvlExpr);
7538 int getNumMatches() const { return Matches.size(); }
7540 FunctionDecl* getMatchingFunctionDecl() const {
7541 if (Matches.size() != 1) return 0;
7542 return Matches[0].second;
7545 const DeclAccessPair* getMatchingFunctionAccessPair() const {
7546 if (Matches.size() != 1) return 0;
7547 return &Matches[0].first;
7551 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
7552 /// an overloaded function (C++ [over.over]), where @p From is an
7553 /// expression with overloaded function type and @p ToType is the type
7554 /// we're trying to resolve to. For example:
7560 /// int (*pfd)(double) = f; // selects f(double)
7563 /// This routine returns the resulting FunctionDecl if it could be
7564 /// resolved, and NULL otherwise. When @p Complain is true, this
7565 /// routine will emit diagnostics if there is an error.
7567 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
7569 DeclAccessPair &FoundResult) {
7571 assert(AddressOfExpr->getType() == Context.OverloadTy);
7573 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain);
7574 int NumMatches = Resolver.getNumMatches();
7575 FunctionDecl* Fn = 0;
7576 if ( NumMatches == 0 && Complain) {
7577 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
7578 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
7580 Resolver.ComplainNoMatchesFound();
7582 else if (NumMatches > 1 && Complain)
7583 Resolver.ComplainMultipleMatchesFound();
7584 else if (NumMatches == 1) {
7585 Fn = Resolver.getMatchingFunctionDecl();
7587 FoundResult = *Resolver.getMatchingFunctionAccessPair();
7588 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
7590 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
7596 /// \brief Given an expression that refers to an overloaded function, try to
7597 /// resolve that overloaded function expression down to a single function.
7599 /// This routine can only resolve template-ids that refer to a single function
7600 /// template, where that template-id refers to a single template whose template
7601 /// arguments are either provided by the template-id or have defaults,
7602 /// as described in C++0x [temp.arg.explicit]p3.
7604 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
7606 DeclAccessPair *FoundResult) {
7607 // C++ [over.over]p1:
7608 // [...] [Note: any redundant set of parentheses surrounding the
7609 // overloaded function name is ignored (5.1). ]
7610 // C++ [over.over]p1:
7611 // [...] The overloaded function name can be preceded by the &
7614 // If we didn't actually find any template-ids, we're done.
7615 if (!ovl->hasExplicitTemplateArgs())
7618 TemplateArgumentListInfo ExplicitTemplateArgs;
7619 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
7621 // Look through all of the overloaded functions, searching for one
7622 // whose type matches exactly.
7623 FunctionDecl *Matched = 0;
7624 for (UnresolvedSetIterator I = ovl->decls_begin(),
7625 E = ovl->decls_end(); I != E; ++I) {
7626 // C++0x [temp.arg.explicit]p3:
7627 // [...] In contexts where deduction is done and fails, or in contexts
7628 // where deduction is not done, if a template argument list is
7629 // specified and it, along with any default template arguments,
7630 // identifies a single function template specialization, then the
7631 // template-id is an lvalue for the function template specialization.
7632 FunctionTemplateDecl *FunctionTemplate
7633 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
7635 // C++ [over.over]p2:
7636 // If the name is a function template, template argument deduction is
7637 // done (14.8.2.2), and if the argument deduction succeeds, the
7638 // resulting template argument list is used to generate a single
7639 // function template specialization, which is added to the set of
7640 // overloaded functions considered.
7641 FunctionDecl *Specialization = 0;
7642 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
7643 if (TemplateDeductionResult Result
7644 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
7645 Specialization, Info)) {
7646 // FIXME: make a note of the failed deduction for diagnostics.
7651 assert(Specialization && "no specialization and no error?");
7653 // Multiple matches; we can't resolve to a single declaration.
7656 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
7658 NoteAllOverloadCandidates(ovl);
7663 Matched = Specialization;
7664 if (FoundResult) *FoundResult = I.getPair();
7673 // Resolve and fix an overloaded expression that
7674 // can be resolved because it identifies a single function
7675 // template specialization
7676 // Last three arguments should only be supplied if Complain = true
7677 ExprResult Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
7678 Expr *SrcExpr, bool doFunctionPointerConverion, bool complain,
7679 const SourceRange& OpRangeForComplaining,
7680 QualType DestTypeForComplaining,
7681 unsigned DiagIDForComplaining) {
7682 assert(SrcExpr->getType() == Context.OverloadTy);
7684 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr);
7686 DeclAccessPair found;
7687 ExprResult SingleFunctionExpression;
7688 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
7689 ovl.Expression, /*complain*/ false, &found)) {
7690 if (DiagnoseUseOfDecl(fn, SrcExpr->getSourceRange().getBegin()))
7693 // It is only correct to resolve to an instance method if we're
7694 // resolving a form that's permitted to be a pointer to member.
7695 // Otherwise we'll end up making a bound member expression, which
7696 // is illegal in all the contexts we resolve like this.
7697 if (!ovl.HasFormOfMemberPointer &&
7698 isa<CXXMethodDecl>(fn) &&
7699 cast<CXXMethodDecl>(fn)->isInstance()) {
7701 Diag(ovl.Expression->getExprLoc(),
7702 diag::err_invalid_use_of_bound_member_func)
7703 << ovl.Expression->getSourceRange();
7704 // TODO: I believe we only end up here if there's a mix of
7705 // static and non-static candidates (otherwise the expression
7706 // would have 'bound member' type, not 'overload' type).
7707 // Ideally we would note which candidate was chosen and why
7708 // the static candidates were rejected.
7714 // Fix the expresion to refer to 'fn'.
7715 SingleFunctionExpression =
7716 Owned(FixOverloadedFunctionReference(SrcExpr, found, fn));
7718 // If desired, do function-to-pointer decay.
7719 if (doFunctionPointerConverion)
7720 SingleFunctionExpression =
7721 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
7724 if (!SingleFunctionExpression.isUsable()) {
7726 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
7727 << ovl.Expression->getName()
7728 << DestTypeForComplaining
7729 << OpRangeForComplaining
7730 << ovl.Expression->getQualifierLoc().getSourceRange();
7731 NoteAllOverloadCandidates(SrcExpr);
7736 return SingleFunctionExpression;
7739 /// \brief Add a single candidate to the overload set.
7740 static void AddOverloadedCallCandidate(Sema &S,
7741 DeclAccessPair FoundDecl,
7742 TemplateArgumentListInfo *ExplicitTemplateArgs,
7743 Expr **Args, unsigned NumArgs,
7744 OverloadCandidateSet &CandidateSet,
7745 bool PartialOverloading) {
7746 NamedDecl *Callee = FoundDecl.getDecl();
7747 if (isa<UsingShadowDecl>(Callee))
7748 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
7750 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
7751 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
7752 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
7753 false, PartialOverloading);
7757 if (FunctionTemplateDecl *FuncTemplate
7758 = dyn_cast<FunctionTemplateDecl>(Callee)) {
7759 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
7760 ExplicitTemplateArgs,
7761 Args, NumArgs, CandidateSet);
7765 assert(false && "unhandled case in overloaded call candidate");
7770 /// \brief Add the overload candidates named by callee and/or found by argument
7771 /// dependent lookup to the given overload set.
7772 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
7773 Expr **Args, unsigned NumArgs,
7774 OverloadCandidateSet &CandidateSet,
7775 bool PartialOverloading) {
7778 // Verify that ArgumentDependentLookup is consistent with the rules
7779 // in C++0x [basic.lookup.argdep]p3:
7781 // Let X be the lookup set produced by unqualified lookup (3.4.1)
7782 // and let Y be the lookup set produced by argument dependent
7783 // lookup (defined as follows). If X contains
7785 // -- a declaration of a class member, or
7787 // -- a block-scope function declaration that is not a
7788 // using-declaration, or
7790 // -- a declaration that is neither a function or a function
7795 if (ULE->requiresADL()) {
7796 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7797 E = ULE->decls_end(); I != E; ++I) {
7798 assert(!(*I)->getDeclContext()->isRecord());
7799 assert(isa<UsingShadowDecl>(*I) ||
7800 !(*I)->getDeclContext()->isFunctionOrMethod());
7801 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
7806 // It would be nice to avoid this copy.
7807 TemplateArgumentListInfo TABuffer;
7808 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7809 if (ULE->hasExplicitTemplateArgs()) {
7810 ULE->copyTemplateArgumentsInto(TABuffer);
7811 ExplicitTemplateArgs = &TABuffer;
7814 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7815 E = ULE->decls_end(); I != E; ++I)
7816 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
7817 Args, NumArgs, CandidateSet,
7818 PartialOverloading);
7820 if (ULE->requiresADL())
7821 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
7823 ExplicitTemplateArgs,
7826 ULE->isStdAssociatedNamespace());
7829 /// Attempt to recover from an ill-formed use of a non-dependent name in a
7830 /// template, where the non-dependent name was declared after the template
7831 /// was defined. This is common in code written for a compilers which do not
7832 /// correctly implement two-stage name lookup.
7834 /// Returns true if a viable candidate was found and a diagnostic was issued.
7836 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
7837 const CXXScopeSpec &SS, LookupResult &R,
7838 TemplateArgumentListInfo *ExplicitTemplateArgs,
7839 Expr **Args, unsigned NumArgs) {
7840 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
7843 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
7844 SemaRef.LookupQualifiedName(R, DC);
7847 R.suppressDiagnostics();
7849 if (isa<CXXRecordDecl>(DC)) {
7850 // Don't diagnose names we find in classes; we get much better
7851 // diagnostics for these from DiagnoseEmptyLookup.
7856 OverloadCandidateSet Candidates(FnLoc);
7857 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
7858 AddOverloadedCallCandidate(SemaRef, I.getPair(),
7859 ExplicitTemplateArgs, Args, NumArgs,
7862 OverloadCandidateSet::iterator Best;
7863 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success)
7864 // No viable functions. Don't bother the user with notes for functions
7865 // which don't work and shouldn't be found anyway.
7868 // Find the namespaces where ADL would have looked, and suggest
7869 // declaring the function there instead.
7870 Sema::AssociatedNamespaceSet AssociatedNamespaces;
7871 Sema::AssociatedClassSet AssociatedClasses;
7872 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
7873 AssociatedNamespaces,
7875 // Never suggest declaring a function within namespace 'std'.
7876 Sema::AssociatedNamespaceSet SuggestedNamespaces;
7877 if (DeclContext *Std = SemaRef.getStdNamespace()) {
7878 for (Sema::AssociatedNamespaceSet::iterator
7879 it = AssociatedNamespaces.begin(),
7880 end = AssociatedNamespaces.end(); it != end; ++it) {
7881 if (!Std->Encloses(*it))
7882 SuggestedNamespaces.insert(*it);
7885 // Lacking the 'std::' namespace, use all of the associated namespaces.
7886 SuggestedNamespaces = AssociatedNamespaces;
7889 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
7890 << R.getLookupName();
7891 if (SuggestedNamespaces.empty()) {
7892 SemaRef.Diag(Best->Function->getLocation(),
7893 diag::note_not_found_by_two_phase_lookup)
7894 << R.getLookupName() << 0;
7895 } else if (SuggestedNamespaces.size() == 1) {
7896 SemaRef.Diag(Best->Function->getLocation(),
7897 diag::note_not_found_by_two_phase_lookup)
7898 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
7900 // FIXME: It would be useful to list the associated namespaces here,
7901 // but the diagnostics infrastructure doesn't provide a way to produce
7902 // a localized representation of a list of items.
7903 SemaRef.Diag(Best->Function->getLocation(),
7904 diag::note_not_found_by_two_phase_lookup)
7905 << R.getLookupName() << 2;
7908 // Try to recover by calling this function.
7918 /// Attempt to recover from ill-formed use of a non-dependent operator in a
7919 /// template, where the non-dependent operator was declared after the template
7922 /// Returns true if a viable candidate was found and a diagnostic was issued.
7924 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
7925 SourceLocation OpLoc,
7926 Expr **Args, unsigned NumArgs) {
7927 DeclarationName OpName =
7928 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
7929 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
7930 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
7931 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
7934 /// Attempts to recover from a call where no functions were found.
7936 /// Returns true if new candidates were found.
7938 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
7939 UnresolvedLookupExpr *ULE,
7940 SourceLocation LParenLoc,
7941 Expr **Args, unsigned NumArgs,
7942 SourceLocation RParenLoc,
7946 SS.Adopt(ULE->getQualifierLoc());
7948 TemplateArgumentListInfo TABuffer;
7949 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7950 if (ULE->hasExplicitTemplateArgs()) {
7951 ULE->copyTemplateArgumentsInto(TABuffer);
7952 ExplicitTemplateArgs = &TABuffer;
7955 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
7956 Sema::LookupOrdinaryName);
7957 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
7958 ExplicitTemplateArgs, Args, NumArgs) &&
7960 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression)))
7963 assert(!R.empty() && "lookup results empty despite recovery");
7965 // Build an implicit member call if appropriate. Just drop the
7966 // casts and such from the call, we don't really care.
7967 ExprResult NewFn = ExprError();
7968 if ((*R.begin())->isCXXClassMember())
7969 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
7970 ExplicitTemplateArgs);
7971 else if (ExplicitTemplateArgs)
7972 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
7974 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
7976 if (NewFn.isInvalid())
7979 // This shouldn't cause an infinite loop because we're giving it
7980 // an expression with viable lookup results, which should never
7982 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
7983 MultiExprArg(Args, NumArgs), RParenLoc);
7986 /// ResolveOverloadedCallFn - Given the call expression that calls Fn
7987 /// (which eventually refers to the declaration Func) and the call
7988 /// arguments Args/NumArgs, attempt to resolve the function call down
7989 /// to a specific function. If overload resolution succeeds, returns
7990 /// the function declaration produced by overload
7991 /// resolution. Otherwise, emits diagnostics, deletes all of the
7992 /// arguments and Fn, and returns NULL.
7994 Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
7995 SourceLocation LParenLoc,
7996 Expr **Args, unsigned NumArgs,
7997 SourceLocation RParenLoc,
8000 if (ULE->requiresADL()) {
8001 // To do ADL, we must have found an unqualified name.
8002 assert(!ULE->getQualifier() && "qualified name with ADL");
8004 // We don't perform ADL for implicit declarations of builtins.
8005 // Verify that this was correctly set up.
8007 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
8008 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
8009 F->getBuiltinID() && F->isImplicit())
8010 assert(0 && "performing ADL for builtin");
8012 // We don't perform ADL in C.
8013 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
8015 assert(!ULE->isStdAssociatedNamespace() &&
8016 "std is associated namespace but not doing ADL");
8019 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
8021 // Add the functions denoted by the callee to the set of candidate
8022 // functions, including those from argument-dependent lookup.
8023 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
8025 // If we found nothing, try to recover.
8026 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
8028 if (CandidateSet.empty())
8029 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
8030 RParenLoc, /*EmptyLookup=*/true);
8032 OverloadCandidateSet::iterator Best;
8033 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
8035 FunctionDecl *FDecl = Best->Function;
8036 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
8037 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
8038 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
8040 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
8041 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
8045 case OR_No_Viable_Function: {
8046 // Try to recover by looking for viable functions which the user might
8047 // have meant to call.
8048 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
8049 Args, NumArgs, RParenLoc,
8050 /*EmptyLookup=*/false);
8051 if (!Recovery.isInvalid())
8054 Diag(Fn->getSourceRange().getBegin(),
8055 diag::err_ovl_no_viable_function_in_call)
8056 << ULE->getName() << Fn->getSourceRange();
8057 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8062 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
8063 << ULE->getName() << Fn->getSourceRange();
8064 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
8069 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
8070 << Best->Function->isDeleted()
8072 << getDeletedOrUnavailableSuffix(Best->Function)
8073 << Fn->getSourceRange();
8074 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8079 // Overload resolution failed.
8083 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
8084 return Functions.size() > 1 ||
8085 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
8088 /// \brief Create a unary operation that may resolve to an overloaded
8091 /// \param OpLoc The location of the operator itself (e.g., '*').
8093 /// \param OpcIn The UnaryOperator::Opcode that describes this
8096 /// \param Functions The set of non-member functions that will be
8097 /// considered by overload resolution. The caller needs to build this
8098 /// set based on the context using, e.g.,
8099 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8100 /// set should not contain any member functions; those will be added
8101 /// by CreateOverloadedUnaryOp().
8103 /// \param input The input argument.
8105 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
8106 const UnresolvedSetImpl &Fns,
8108 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
8110 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
8111 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
8112 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8113 // TODO: provide better source location info.
8114 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
8116 if (Input->getObjectKind() == OK_ObjCProperty) {
8117 ExprResult Result = ConvertPropertyForRValue(Input);
8118 if (Result.isInvalid())
8120 Input = Result.take();
8123 Expr *Args[2] = { Input, 0 };
8124 unsigned NumArgs = 1;
8126 // For post-increment and post-decrement, add the implicit '0' as
8127 // the second argument, so that we know this is a post-increment or
8129 if (Opc == UO_PostInc || Opc == UO_PostDec) {
8130 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
8131 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
8136 if (Input->isTypeDependent()) {
8138 return Owned(new (Context) UnaryOperator(Input,
8140 Context.DependentTy,
8141 VK_RValue, OK_Ordinary,
8144 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
8145 UnresolvedLookupExpr *Fn
8146 = UnresolvedLookupExpr::Create(Context, NamingClass,
8147 NestedNameSpecifierLoc(), OpNameInfo,
8148 /*ADL*/ true, IsOverloaded(Fns),
8149 Fns.begin(), Fns.end());
8150 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
8152 Context.DependentTy,
8157 // Build an empty overload set.
8158 OverloadCandidateSet CandidateSet(OpLoc);
8160 // Add the candidates from the given function set.
8161 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
8163 // Add operator candidates that are member functions.
8164 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
8166 // Add candidates from ADL.
8167 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
8169 /*ExplicitTemplateArgs*/ 0,
8172 // Add builtin operator candidates.
8173 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
8175 // Perform overload resolution.
8176 OverloadCandidateSet::iterator Best;
8177 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
8179 // We found a built-in operator or an overloaded operator.
8180 FunctionDecl *FnDecl = Best->Function;
8183 // We matched an overloaded operator. Build a call to that
8186 MarkDeclarationReferenced(OpLoc, FnDecl);
8188 // Convert the arguments.
8189 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
8190 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
8192 ExprResult InputRes =
8193 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
8194 Best->FoundDecl, Method);
8195 if (InputRes.isInvalid())
8197 Input = InputRes.take();
8199 // Convert the arguments.
8200 ExprResult InputInit
8201 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
8203 FnDecl->getParamDecl(0)),
8206 if (InputInit.isInvalid())
8208 Input = InputInit.take();
8211 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8213 // Determine the result type.
8214 QualType ResultTy = FnDecl->getResultType();
8215 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8216 ResultTy = ResultTy.getNonLValueExprType(Context);
8218 // Build the actual expression node.
8219 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl);
8220 if (FnExpr.isInvalid())
8225 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
8226 Args, NumArgs, ResultTy, VK, OpLoc);
8228 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
8232 return MaybeBindToTemporary(TheCall);
8234 // We matched a built-in operator. Convert the arguments, then
8235 // break out so that we will build the appropriate built-in
8237 ExprResult InputRes =
8238 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
8239 Best->Conversions[0], AA_Passing);
8240 if (InputRes.isInvalid())
8242 Input = InputRes.take();
8247 case OR_No_Viable_Function:
8248 // This is an erroneous use of an operator which can be overloaded by
8249 // a non-member function. Check for non-member operators which were
8250 // defined too late to be candidates.
8251 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
8252 // FIXME: Recover by calling the found function.
8255 // No viable function; fall through to handling this as a
8256 // built-in operator, which will produce an error message for us.
8260 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8261 << UnaryOperator::getOpcodeStr(Opc)
8263 << Input->getSourceRange();
8264 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
8266 UnaryOperator::getOpcodeStr(Opc), OpLoc);
8270 Diag(OpLoc, diag::err_ovl_deleted_oper)
8271 << Best->Function->isDeleted()
8272 << UnaryOperator::getOpcodeStr(Opc)
8273 << getDeletedOrUnavailableSuffix(Best->Function)
8274 << Input->getSourceRange();
8275 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8279 // Either we found no viable overloaded operator or we matched a
8280 // built-in operator. In either case, fall through to trying to
8281 // build a built-in operation.
8282 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
8285 /// \brief Create a binary operation that may resolve to an overloaded
8288 /// \param OpLoc The location of the operator itself (e.g., '+').
8290 /// \param OpcIn The BinaryOperator::Opcode that describes this
8293 /// \param Functions The set of non-member functions that will be
8294 /// considered by overload resolution. The caller needs to build this
8295 /// set based on the context using, e.g.,
8296 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8297 /// set should not contain any member functions; those will be added
8298 /// by CreateOverloadedBinOp().
8300 /// \param LHS Left-hand argument.
8301 /// \param RHS Right-hand argument.
8303 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
8305 const UnresolvedSetImpl &Fns,
8306 Expr *LHS, Expr *RHS) {
8307 Expr *Args[2] = { LHS, RHS };
8308 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
8310 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
8311 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
8312 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8314 // If either side is type-dependent, create an appropriate dependent
8316 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
8318 // If there are no functions to store, just build a dependent
8319 // BinaryOperator or CompoundAssignment.
8320 if (Opc <= BO_Assign || Opc > BO_OrAssign)
8321 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
8322 Context.DependentTy,
8323 VK_RValue, OK_Ordinary,
8326 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
8327 Context.DependentTy,
8330 Context.DependentTy,
8331 Context.DependentTy,
8335 // FIXME: save results of ADL from here?
8336 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
8337 // TODO: provide better source location info in DNLoc component.
8338 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
8339 UnresolvedLookupExpr *Fn
8340 = UnresolvedLookupExpr::Create(Context, NamingClass,
8341 NestedNameSpecifierLoc(), OpNameInfo,
8342 /*ADL*/ true, IsOverloaded(Fns),
8343 Fns.begin(), Fns.end());
8344 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
8346 Context.DependentTy,
8351 // Always do property rvalue conversions on the RHS.
8352 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8353 ExprResult Result = ConvertPropertyForRValue(Args[1]);
8354 if (Result.isInvalid())
8356 Args[1] = Result.take();
8359 // The LHS is more complicated.
8360 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8362 // There's a tension for assignment operators between primitive
8363 // property assignment and the overloaded operators.
8364 if (BinaryOperator::isAssignmentOp(Opc)) {
8365 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
8367 // Is the property "logically" settable?
8368 bool Settable = (PRE->isExplicitProperty() ||
8369 PRE->getImplicitPropertySetter());
8371 // To avoid gratuitously inventing semantics, use the primitive
8372 // unless it isn't. Thoughts in case we ever really care:
8373 // - If the property isn't logically settable, we have to
8375 // - If the property is settable and this is simple assignment,
8376 // we really should use the primitive.
8377 // - If the property is settable, then we could try overloading
8378 // on a generic lvalue of the appropriate type; if it works
8379 // out to a builtin candidate, we would do that same operation
8380 // on the property, and otherwise just error.
8382 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8385 ExprResult Result = ConvertPropertyForRValue(Args[0]);
8386 if (Result.isInvalid())
8388 Args[0] = Result.take();
8391 // If this is the assignment operator, we only perform overload resolution
8392 // if the left-hand side is a class or enumeration type. This is actually
8393 // a hack. The standard requires that we do overload resolution between the
8394 // various built-in candidates, but as DR507 points out, this can lead to
8395 // problems. So we do it this way, which pretty much follows what GCC does.
8396 // Note that we go the traditional code path for compound assignment forms.
8397 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
8398 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8400 // If this is the .* operator, which is not overloadable, just
8401 // create a built-in binary operator.
8402 if (Opc == BO_PtrMemD)
8403 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8405 // Build an empty overload set.
8406 OverloadCandidateSet CandidateSet(OpLoc);
8408 // Add the candidates from the given function set.
8409 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
8411 // Add operator candidates that are member functions.
8412 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
8414 // Add candidates from ADL.
8415 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
8417 /*ExplicitTemplateArgs*/ 0,
8420 // Add builtin operator candidates.
8421 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
8423 // Perform overload resolution.
8424 OverloadCandidateSet::iterator Best;
8425 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
8427 // We found a built-in operator or an overloaded operator.
8428 FunctionDecl *FnDecl = Best->Function;
8431 // We matched an overloaded operator. Build a call to that
8434 MarkDeclarationReferenced(OpLoc, FnDecl);
8436 // Convert the arguments.
8437 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
8438 // Best->Access is only meaningful for class members.
8439 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
8442 PerformCopyInitialization(
8443 InitializedEntity::InitializeParameter(Context,
8444 FnDecl->getParamDecl(0)),
8445 SourceLocation(), Owned(Args[1]));
8446 if (Arg1.isInvalid())
8450 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8451 Best->FoundDecl, Method);
8452 if (Arg0.isInvalid())
8454 Args[0] = Arg0.takeAs<Expr>();
8455 Args[1] = RHS = Arg1.takeAs<Expr>();
8457 // Convert the arguments.
8458 ExprResult Arg0 = PerformCopyInitialization(
8459 InitializedEntity::InitializeParameter(Context,
8460 FnDecl->getParamDecl(0)),
8461 SourceLocation(), Owned(Args[0]));
8462 if (Arg0.isInvalid())
8466 PerformCopyInitialization(
8467 InitializedEntity::InitializeParameter(Context,
8468 FnDecl->getParamDecl(1)),
8469 SourceLocation(), Owned(Args[1]));
8470 if (Arg1.isInvalid())
8472 Args[0] = LHS = Arg0.takeAs<Expr>();
8473 Args[1] = RHS = Arg1.takeAs<Expr>();
8476 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8478 // Determine the result type.
8479 QualType ResultTy = FnDecl->getResultType();
8480 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8481 ResultTy = ResultTy.getNonLValueExprType(Context);
8483 // Build the actual expression node.
8484 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
8485 if (FnExpr.isInvalid())
8488 CXXOperatorCallExpr *TheCall =
8489 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
8490 Args, 2, ResultTy, VK, OpLoc);
8492 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
8496 return MaybeBindToTemporary(TheCall);
8498 // We matched a built-in operator. Convert the arguments, then
8499 // break out so that we will build the appropriate built-in
8501 ExprResult ArgsRes0 =
8502 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8503 Best->Conversions[0], AA_Passing);
8504 if (ArgsRes0.isInvalid())
8506 Args[0] = ArgsRes0.take();
8508 ExprResult ArgsRes1 =
8509 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8510 Best->Conversions[1], AA_Passing);
8511 if (ArgsRes1.isInvalid())
8513 Args[1] = ArgsRes1.take();
8518 case OR_No_Viable_Function: {
8519 // C++ [over.match.oper]p9:
8520 // If the operator is the operator , [...] and there are no
8521 // viable functions, then the operator is assumed to be the
8522 // built-in operator and interpreted according to clause 5.
8523 if (Opc == BO_Comma)
8526 // For class as left operand for assignment or compound assigment
8527 // operator do not fall through to handling in built-in, but report that
8528 // no overloaded assignment operator found
8529 ExprResult Result = ExprError();
8530 if (Args[0]->getType()->isRecordType() &&
8531 Opc >= BO_Assign && Opc <= BO_OrAssign) {
8532 Diag(OpLoc, diag::err_ovl_no_viable_oper)
8533 << BinaryOperator::getOpcodeStr(Opc)
8534 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8536 // This is an erroneous use of an operator which can be overloaded by
8537 // a non-member function. Check for non-member operators which were
8538 // defined too late to be candidates.
8539 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
8540 // FIXME: Recover by calling the found function.
8543 // No viable function; try to create a built-in operation, which will
8544 // produce an error. Then, show the non-viable candidates.
8545 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8547 assert(Result.isInvalid() &&
8548 "C++ binary operator overloading is missing candidates!");
8549 if (Result.isInvalid())
8550 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8551 BinaryOperator::getOpcodeStr(Opc), OpLoc);
8552 return move(Result);
8556 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
8557 << BinaryOperator::getOpcodeStr(Opc)
8558 << Args[0]->getType() << Args[1]->getType()
8559 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8560 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8561 BinaryOperator::getOpcodeStr(Opc), OpLoc);
8565 Diag(OpLoc, diag::err_ovl_deleted_oper)
8566 << Best->Function->isDeleted()
8567 << BinaryOperator::getOpcodeStr(Opc)
8568 << getDeletedOrUnavailableSuffix(Best->Function)
8569 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8570 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
8574 // We matched a built-in operator; build it.
8575 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8579 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
8580 SourceLocation RLoc,
8581 Expr *Base, Expr *Idx) {
8582 Expr *Args[2] = { Base, Idx };
8583 DeclarationName OpName =
8584 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
8586 // If either side is type-dependent, create an appropriate dependent
8588 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
8590 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
8591 // CHECKME: no 'operator' keyword?
8592 DeclarationNameInfo OpNameInfo(OpName, LLoc);
8593 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
8594 UnresolvedLookupExpr *Fn
8595 = UnresolvedLookupExpr::Create(Context, NamingClass,
8596 NestedNameSpecifierLoc(), OpNameInfo,
8597 /*ADL*/ true, /*Overloaded*/ false,
8598 UnresolvedSetIterator(),
8599 UnresolvedSetIterator());
8600 // Can't add any actual overloads yet
8602 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
8604 Context.DependentTy,
8609 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8610 ExprResult Result = ConvertPropertyForRValue(Args[0]);
8611 if (Result.isInvalid())
8613 Args[0] = Result.take();
8615 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8616 ExprResult Result = ConvertPropertyForRValue(Args[1]);
8617 if (Result.isInvalid())
8619 Args[1] = Result.take();
8622 // Build an empty overload set.
8623 OverloadCandidateSet CandidateSet(LLoc);
8625 // Subscript can only be overloaded as a member function.
8627 // Add operator candidates that are member functions.
8628 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8630 // Add builtin operator candidates.
8631 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8633 // Perform overload resolution.
8634 OverloadCandidateSet::iterator Best;
8635 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
8637 // We found a built-in operator or an overloaded operator.
8638 FunctionDecl *FnDecl = Best->Function;
8641 // We matched an overloaded operator. Build a call to that
8644 MarkDeclarationReferenced(LLoc, FnDecl);
8646 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
8647 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
8649 // Convert the arguments.
8650 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
8652 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8653 Best->FoundDecl, Method);
8654 if (Arg0.isInvalid())
8656 Args[0] = Arg0.take();
8658 // Convert the arguments.
8659 ExprResult InputInit
8660 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
8662 FnDecl->getParamDecl(0)),
8665 if (InputInit.isInvalid())
8668 Args[1] = InputInit.takeAs<Expr>();
8670 // Determine the result type
8671 QualType ResultTy = FnDecl->getResultType();
8672 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8673 ResultTy = ResultTy.getNonLValueExprType(Context);
8675 // Build the actual expression node.
8676 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
8677 if (FnExpr.isInvalid())
8680 CXXOperatorCallExpr *TheCall =
8681 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
8682 FnExpr.take(), Args, 2,
8683 ResultTy, VK, RLoc);
8685 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
8689 return MaybeBindToTemporary(TheCall);
8691 // We matched a built-in operator. Convert the arguments, then
8692 // break out so that we will build the appropriate built-in
8694 ExprResult ArgsRes0 =
8695 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8696 Best->Conversions[0], AA_Passing);
8697 if (ArgsRes0.isInvalid())
8699 Args[0] = ArgsRes0.take();
8701 ExprResult ArgsRes1 =
8702 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8703 Best->Conversions[1], AA_Passing);
8704 if (ArgsRes1.isInvalid())
8706 Args[1] = ArgsRes1.take();
8712 case OR_No_Viable_Function: {
8713 if (CandidateSet.empty())
8714 Diag(LLoc, diag::err_ovl_no_oper)
8715 << Args[0]->getType() << /*subscript*/ 0
8716 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8718 Diag(LLoc, diag::err_ovl_no_viable_subscript)
8719 << Args[0]->getType()
8720 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8721 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8727 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
8729 << Args[0]->getType() << Args[1]->getType()
8730 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8731 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8736 Diag(LLoc, diag::err_ovl_deleted_oper)
8737 << Best->Function->isDeleted() << "[]"
8738 << getDeletedOrUnavailableSuffix(Best->Function)
8739 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8740 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8745 // We matched a built-in operator; build it.
8746 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
8749 /// BuildCallToMemberFunction - Build a call to a member
8750 /// function. MemExpr is the expression that refers to the member
8751 /// function (and includes the object parameter), Args/NumArgs are the
8752 /// arguments to the function call (not including the object
8753 /// parameter). The caller needs to validate that the member
8754 /// expression refers to a non-static member function or an overloaded
8755 /// member function.
8757 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
8758 SourceLocation LParenLoc, Expr **Args,
8759 unsigned NumArgs, SourceLocation RParenLoc) {
8760 assert(MemExprE->getType() == Context.BoundMemberTy ||
8761 MemExprE->getType() == Context.OverloadTy);
8763 // Dig out the member expression. This holds both the object
8764 // argument and the member function we're referring to.
8765 Expr *NakedMemExpr = MemExprE->IgnoreParens();
8767 // Determine whether this is a call to a pointer-to-member function.
8768 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
8769 assert(op->getType() == Context.BoundMemberTy);
8770 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
8773 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
8775 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
8776 QualType resultType = proto->getCallResultType(Context);
8777 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
8779 // Check that the object type isn't more qualified than the
8780 // member function we're calling.
8781 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
8783 QualType objectType = op->getLHS()->getType();
8784 if (op->getOpcode() == BO_PtrMemI)
8785 objectType = objectType->castAs<PointerType>()->getPointeeType();
8786 Qualifiers objectQuals = objectType.getQualifiers();
8788 Qualifiers difference = objectQuals - funcQuals;
8789 difference.removeObjCGCAttr();
8790 difference.removeAddressSpace();
8792 std::string qualsString = difference.getAsString();
8793 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
8794 << fnType.getUnqualifiedType()
8796 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
8799 CXXMemberCallExpr *call
8800 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
8801 resultType, valueKind, RParenLoc);
8803 if (CheckCallReturnType(proto->getResultType(),
8804 op->getRHS()->getSourceRange().getBegin(),
8808 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
8811 return MaybeBindToTemporary(call);
8814 MemberExpr *MemExpr;
8815 CXXMethodDecl *Method = 0;
8816 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
8817 NestedNameSpecifier *Qualifier = 0;
8818 if (isa<MemberExpr>(NakedMemExpr)) {
8819 MemExpr = cast<MemberExpr>(NakedMemExpr);
8820 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
8821 FoundDecl = MemExpr->getFoundDecl();
8822 Qualifier = MemExpr->getQualifier();
8824 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
8825 Qualifier = UnresExpr->getQualifier();
8827 QualType ObjectType = UnresExpr->getBaseType();
8828 Expr::Classification ObjectClassification
8829 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
8830 : UnresExpr->getBase()->Classify(Context);
8832 // Add overload candidates
8833 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
8835 // FIXME: avoid copy.
8836 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8837 if (UnresExpr->hasExplicitTemplateArgs()) {
8838 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8839 TemplateArgs = &TemplateArgsBuffer;
8842 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
8843 E = UnresExpr->decls_end(); I != E; ++I) {
8845 NamedDecl *Func = *I;
8846 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
8847 if (isa<UsingShadowDecl>(Func))
8848 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
8851 // Microsoft supports direct constructor calls.
8852 if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) {
8853 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
8855 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
8856 // If explicit template arguments were provided, we can't call a
8857 // non-template member function.
8861 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
8862 ObjectClassification,
8863 Args, NumArgs, CandidateSet,
8864 /*SuppressUserConversions=*/false);
8866 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
8867 I.getPair(), ActingDC, TemplateArgs,
8868 ObjectType, ObjectClassification,
8869 Args, NumArgs, CandidateSet,
8870 /*SuppressUsedConversions=*/false);
8874 DeclarationName DeclName = UnresExpr->getMemberName();
8876 OverloadCandidateSet::iterator Best;
8877 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
8880 Method = cast<CXXMethodDecl>(Best->Function);
8881 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
8882 FoundDecl = Best->FoundDecl;
8883 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
8884 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
8887 case OR_No_Viable_Function:
8888 Diag(UnresExpr->getMemberLoc(),
8889 diag::err_ovl_no_viable_member_function_in_call)
8890 << DeclName << MemExprE->getSourceRange();
8891 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8892 // FIXME: Leaking incoming expressions!
8896 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
8897 << DeclName << MemExprE->getSourceRange();
8898 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8899 // FIXME: Leaking incoming expressions!
8903 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
8904 << Best->Function->isDeleted()
8906 << getDeletedOrUnavailableSuffix(Best->Function)
8907 << MemExprE->getSourceRange();
8908 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8909 // FIXME: Leaking incoming expressions!
8913 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
8915 // If overload resolution picked a static member, build a
8916 // non-member call based on that function.
8917 if (Method->isStatic()) {
8918 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
8919 Args, NumArgs, RParenLoc);
8922 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
8925 QualType ResultType = Method->getResultType();
8926 ExprValueKind VK = Expr::getValueKindForType(ResultType);
8927 ResultType = ResultType.getNonLValueExprType(Context);
8929 assert(Method && "Member call to something that isn't a method?");
8930 CXXMemberCallExpr *TheCall =
8931 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
8932 ResultType, VK, RParenLoc);
8934 // Check for a valid return type.
8935 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
8939 // Convert the object argument (for a non-static member function call).
8940 // We only need to do this if there was actually an overload; otherwise
8941 // it was done at lookup.
8942 if (!Method->isStatic()) {
8943 ExprResult ObjectArg =
8944 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
8946 if (ObjectArg.isInvalid())
8948 MemExpr->setBase(ObjectArg.take());
8951 // Convert the rest of the arguments
8952 const FunctionProtoType *Proto =
8953 Method->getType()->getAs<FunctionProtoType>();
8954 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
8958 if (CheckFunctionCall(Method, TheCall))
8961 if ((isa<CXXConstructorDecl>(CurContext) ||
8962 isa<CXXDestructorDecl>(CurContext)) &&
8963 TheCall->getMethodDecl()->isPure()) {
8964 const CXXMethodDecl *MD = TheCall->getMethodDecl();
8966 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()))
8967 Diag(MemExpr->getLocStart(),
8968 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
8969 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
8970 << MD->getParent()->getDeclName();
8972 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
8974 return MaybeBindToTemporary(TheCall);
8977 /// BuildCallToObjectOfClassType - Build a call to an object of class
8978 /// type (C++ [over.call.object]), which can end up invoking an
8979 /// overloaded function call operator (@c operator()) or performing a
8980 /// user-defined conversion on the object argument.
8982 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
8983 SourceLocation LParenLoc,
8984 Expr **Args, unsigned NumArgs,
8985 SourceLocation RParenLoc) {
8986 ExprResult Object = Owned(Obj);
8987 if (Object.get()->getObjectKind() == OK_ObjCProperty) {
8988 Object = ConvertPropertyForRValue(Object.take());
8989 if (Object.isInvalid())
8993 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
8994 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
8996 // C++ [over.call.object]p1:
8997 // If the primary-expression E in the function call syntax
8998 // evaluates to a class object of type "cv T", then the set of
8999 // candidate functions includes at least the function call
9000 // operators of T. The function call operators of T are obtained by
9001 // ordinary lookup of the name operator() in the context of
9003 OverloadCandidateSet CandidateSet(LParenLoc);
9004 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
9006 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
9007 PDiag(diag::err_incomplete_object_call)
9008 << Object.get()->getSourceRange()))
9011 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
9012 LookupQualifiedName(R, Record->getDecl());
9013 R.suppressDiagnostics();
9015 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
9016 Oper != OperEnd; ++Oper) {
9017 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
9018 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
9019 /*SuppressUserConversions=*/ false);
9022 // C++ [over.call.object]p2:
9023 // In addition, for each conversion function declared in T of the
9026 // operator conversion-type-id () cv-qualifier;
9028 // where cv-qualifier is the same cv-qualification as, or a
9029 // greater cv-qualification than, cv, and where conversion-type-id
9030 // denotes the type "pointer to function of (P1,...,Pn) returning
9031 // R", or the type "reference to pointer to function of
9032 // (P1,...,Pn) returning R", or the type "reference to function
9033 // of (P1,...,Pn) returning R", a surrogate call function [...]
9034 // is also considered as a candidate function. Similarly,
9035 // surrogate call functions are added to the set of candidate
9036 // functions for each conversion function declared in an
9037 // accessible base class provided the function is not hidden
9038 // within T by another intervening declaration.
9039 const UnresolvedSetImpl *Conversions
9040 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
9041 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
9042 E = Conversions->end(); I != E; ++I) {
9044 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
9045 if (isa<UsingShadowDecl>(D))
9046 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9048 // Skip over templated conversion functions; they aren't
9050 if (isa<FunctionTemplateDecl>(D))
9053 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9055 // Strip the reference type (if any) and then the pointer type (if
9056 // any) to get down to what might be a function type.
9057 QualType ConvType = Conv->getConversionType().getNonReferenceType();
9058 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9059 ConvType = ConvPtrType->getPointeeType();
9061 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
9062 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
9063 Object.get(), Args, NumArgs, CandidateSet);
9066 // Perform overload resolution.
9067 OverloadCandidateSet::iterator Best;
9068 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
9071 // Overload resolution succeeded; we'll build the appropriate call
9075 case OR_No_Viable_Function:
9076 if (CandidateSet.empty())
9077 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
9078 << Object.get()->getType() << /*call*/ 1
9079 << Object.get()->getSourceRange();
9081 Diag(Object.get()->getSourceRange().getBegin(),
9082 diag::err_ovl_no_viable_object_call)
9083 << Object.get()->getType() << Object.get()->getSourceRange();
9084 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
9088 Diag(Object.get()->getSourceRange().getBegin(),
9089 diag::err_ovl_ambiguous_object_call)
9090 << Object.get()->getType() << Object.get()->getSourceRange();
9091 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
9095 Diag(Object.get()->getSourceRange().getBegin(),
9096 diag::err_ovl_deleted_object_call)
9097 << Best->Function->isDeleted()
9098 << Object.get()->getType()
9099 << getDeletedOrUnavailableSuffix(Best->Function)
9100 << Object.get()->getSourceRange();
9101 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
9105 if (Best == CandidateSet.end())
9108 if (Best->Function == 0) {
9109 // Since there is no function declaration, this is one of the
9110 // surrogate candidates. Dig out the conversion function.
9111 CXXConversionDecl *Conv
9112 = cast<CXXConversionDecl>(
9113 Best->Conversions[0].UserDefined.ConversionFunction);
9115 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
9116 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
9118 // We selected one of the surrogate functions that converts the
9119 // object parameter to a function pointer. Perform the conversion
9120 // on the object argument, then let ActOnCallExpr finish the job.
9122 // Create an implicit member expr to refer to the conversion operator.
9123 // and then call it.
9124 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, Conv);
9125 if (Call.isInvalid())
9128 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
9132 MarkDeclarationReferenced(LParenLoc, Best->Function);
9133 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
9134 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
9136 // We found an overloaded operator(). Build a CXXOperatorCallExpr
9137 // that calls this method, using Object for the implicit object
9138 // parameter and passing along the remaining arguments.
9139 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
9140 const FunctionProtoType *Proto =
9141 Method->getType()->getAs<FunctionProtoType>();
9143 unsigned NumArgsInProto = Proto->getNumArgs();
9144 unsigned NumArgsToCheck = NumArgs;
9146 // Build the full argument list for the method call (the
9147 // implicit object parameter is placed at the beginning of the
9150 if (NumArgs < NumArgsInProto) {
9151 NumArgsToCheck = NumArgsInProto;
9152 MethodArgs = new Expr*[NumArgsInProto + 1];
9154 MethodArgs = new Expr*[NumArgs + 1];
9156 MethodArgs[0] = Object.get();
9157 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
9158 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
9160 ExprResult NewFn = CreateFunctionRefExpr(*this, Method);
9161 if (NewFn.isInvalid())
9164 // Once we've built TheCall, all of the expressions are properly
9166 QualType ResultTy = Method->getResultType();
9167 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9168 ResultTy = ResultTy.getNonLValueExprType(Context);
9170 CXXOperatorCallExpr *TheCall =
9171 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
9172 MethodArgs, NumArgs + 1,
9173 ResultTy, VK, RParenLoc);
9174 delete [] MethodArgs;
9176 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
9180 // We may have default arguments. If so, we need to allocate more
9181 // slots in the call for them.
9182 if (NumArgs < NumArgsInProto)
9183 TheCall->setNumArgs(Context, NumArgsInProto + 1);
9184 else if (NumArgs > NumArgsInProto)
9185 NumArgsToCheck = NumArgsInProto;
9187 bool IsError = false;
9189 // Initialize the implicit object parameter.
9191 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
9192 Best->FoundDecl, Method);
9193 if (ObjRes.isInvalid())
9196 Object = move(ObjRes);
9197 TheCall->setArg(0, Object.take());
9199 // Check the argument types.
9200 for (unsigned i = 0; i != NumArgsToCheck; i++) {
9205 // Pass the argument.
9207 ExprResult InputInit
9208 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
9210 Method->getParamDecl(i)),
9211 SourceLocation(), Arg);
9213 IsError |= InputInit.isInvalid();
9214 Arg = InputInit.takeAs<Expr>();
9217 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
9218 if (DefArg.isInvalid()) {
9223 Arg = DefArg.takeAs<Expr>();
9226 TheCall->setArg(i + 1, Arg);
9229 // If this is a variadic call, handle args passed through "...".
9230 if (Proto->isVariadic()) {
9231 // Promote the arguments (C99 6.5.2.2p7).
9232 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
9233 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
9234 IsError |= Arg.isInvalid();
9235 TheCall->setArg(i + 1, Arg.take());
9239 if (IsError) return true;
9241 if (CheckFunctionCall(Method, TheCall))
9244 return MaybeBindToTemporary(TheCall);
9247 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
9248 /// (if one exists), where @c Base is an expression of class type and
9249 /// @c Member is the name of the member we're trying to find.
9251 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
9252 assert(Base->getType()->isRecordType() &&
9253 "left-hand side must have class type");
9255 if (Base->getObjectKind() == OK_ObjCProperty) {
9256 ExprResult Result = ConvertPropertyForRValue(Base);
9257 if (Result.isInvalid())
9259 Base = Result.take();
9262 SourceLocation Loc = Base->getExprLoc();
9264 // C++ [over.ref]p1:
9266 // [...] An expression x->m is interpreted as (x.operator->())->m
9267 // for a class object x of type T if T::operator->() exists and if
9268 // the operator is selected as the best match function by the
9269 // overload resolution mechanism (13.3).
9270 DeclarationName OpName =
9271 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
9272 OverloadCandidateSet CandidateSet(Loc);
9273 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
9275 if (RequireCompleteType(Loc, Base->getType(),
9276 PDiag(diag::err_typecheck_incomplete_tag)
9277 << Base->getSourceRange()))
9280 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
9281 LookupQualifiedName(R, BaseRecord->getDecl());
9282 R.suppressDiagnostics();
9284 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
9285 Oper != OperEnd; ++Oper) {
9286 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
9287 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
9290 // Perform overload resolution.
9291 OverloadCandidateSet::iterator Best;
9292 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
9294 // Overload resolution succeeded; we'll build the call below.
9297 case OR_No_Viable_Function:
9298 if (CandidateSet.empty())
9299 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
9300 << Base->getType() << Base->getSourceRange();
9302 Diag(OpLoc, diag::err_ovl_no_viable_oper)
9303 << "operator->" << Base->getSourceRange();
9304 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
9308 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9309 << "->" << Base->getType() << Base->getSourceRange();
9310 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
9314 Diag(OpLoc, diag::err_ovl_deleted_oper)
9315 << Best->Function->isDeleted()
9317 << getDeletedOrUnavailableSuffix(Best->Function)
9318 << Base->getSourceRange();
9319 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
9323 MarkDeclarationReferenced(OpLoc, Best->Function);
9324 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
9325 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9327 // Convert the object parameter.
9328 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
9329 ExprResult BaseResult =
9330 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
9331 Best->FoundDecl, Method);
9332 if (BaseResult.isInvalid())
9334 Base = BaseResult.take();
9336 // Build the operator call.
9337 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method);
9338 if (FnExpr.isInvalid())
9341 QualType ResultTy = Method->getResultType();
9342 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9343 ResultTy = ResultTy.getNonLValueExprType(Context);
9344 CXXOperatorCallExpr *TheCall =
9345 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
9346 &Base, 1, ResultTy, VK, OpLoc);
9348 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
9352 return MaybeBindToTemporary(TheCall);
9355 /// FixOverloadedFunctionReference - E is an expression that refers to
9356 /// a C++ overloaded function (possibly with some parentheses and
9357 /// perhaps a '&' around it). We have resolved the overloaded function
9358 /// to the function declaration Fn, so patch up the expression E to
9359 /// refer (possibly indirectly) to Fn. Returns the new expr.
9360 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
9362 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
9363 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
9365 if (SubExpr == PE->getSubExpr())
9368 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
9371 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9372 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
9374 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
9375 SubExpr->getType()) &&
9376 "Implicit cast type cannot be determined from overload");
9377 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
9378 if (SubExpr == ICE->getSubExpr())
9381 return ImplicitCastExpr::Create(Context, ICE->getType(),
9384 ICE->getValueKind());
9387 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
9388 assert(UnOp->getOpcode() == UO_AddrOf &&
9389 "Can only take the address of an overloaded function");
9390 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9391 if (Method->isStatic()) {
9392 // Do nothing: static member functions aren't any different
9393 // from non-member functions.
9395 // Fix the sub expression, which really has to be an
9396 // UnresolvedLookupExpr holding an overloaded member function
9398 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9400 if (SubExpr == UnOp->getSubExpr())
9403 assert(isa<DeclRefExpr>(SubExpr)
9404 && "fixed to something other than a decl ref");
9405 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
9406 && "fixed to a member ref with no nested name qualifier");
9408 // We have taken the address of a pointer to member
9409 // function. Perform the computation here so that we get the
9410 // appropriate pointer to member type.
9412 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
9414 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
9416 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
9417 VK_RValue, OK_Ordinary,
9418 UnOp->getOperatorLoc());
9421 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9423 if (SubExpr == UnOp->getSubExpr())
9426 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
9427 Context.getPointerType(SubExpr->getType()),
9428 VK_RValue, OK_Ordinary,
9429 UnOp->getOperatorLoc());
9432 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
9433 // FIXME: avoid copy.
9434 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9435 if (ULE->hasExplicitTemplateArgs()) {
9436 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
9437 TemplateArgs = &TemplateArgsBuffer;
9440 return DeclRefExpr::Create(Context,
9441 ULE->getQualifierLoc(),
9450 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
9451 // FIXME: avoid copy.
9452 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9453 if (MemExpr->hasExplicitTemplateArgs()) {
9454 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9455 TemplateArgs = &TemplateArgsBuffer;
9460 // If we're filling in a static method where we used to have an
9461 // implicit member access, rewrite to a simple decl ref.
9462 if (MemExpr->isImplicitAccess()) {
9463 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9464 return DeclRefExpr::Create(Context,
9465 MemExpr->getQualifierLoc(),
9467 MemExpr->getMemberLoc(),
9473 SourceLocation Loc = MemExpr->getMemberLoc();
9474 if (MemExpr->getQualifier())
9475 Loc = MemExpr->getQualifierLoc().getBeginLoc();
9476 Base = new (Context) CXXThisExpr(Loc,
9477 MemExpr->getBaseType(),
9478 /*isImplicit=*/true);
9481 Base = MemExpr->getBase();
9483 ExprValueKind valueKind;
9485 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9486 valueKind = VK_LValue;
9487 type = Fn->getType();
9489 valueKind = VK_RValue;
9490 type = Context.BoundMemberTy;
9493 return MemberExpr::Create(Context, Base,
9495 MemExpr->getQualifierLoc(),
9498 MemExpr->getMemberNameInfo(),
9500 type, valueKind, OK_Ordinary);
9503 llvm_unreachable("Invalid reference to overloaded function");
9507 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
9508 DeclAccessPair Found,
9510 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
9513 } // end namespace clang