1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
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/Overload.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/TypeOrdering.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "clang/Basic/DiagnosticOptions.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Sema/Initialization.h"
27 #include "clang/Sema/Lookup.h"
28 #include "clang/Sema/SemaInternal.h"
29 #include "clang/Sema/Template.h"
30 #include "clang/Sema/TemplateDeduction.h"
31 #include "llvm/ADT/DenseSet.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
41 /// A convenience routine for creating a decayed reference to a function.
43 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
44 bool HadMultipleCandidates,
45 SourceLocation Loc = SourceLocation(),
46 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
47 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
49 // If FoundDecl is different from Fn (such as if one is a template
50 // and the other a specialization), make sure DiagnoseUseOfDecl is
52 // FIXME: This would be more comprehensively addressed by modifying
53 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
55 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
57 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
58 VK_LValue, Loc, LocInfo);
59 if (HadMultipleCandidates)
60 DRE->setHadMultipleCandidates(true);
62 S.MarkDeclRefReferenced(DRE);
65 E = S.DefaultFunctionArrayConversion(E.get());
71 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
72 bool InOverloadResolution,
73 StandardConversionSequence &SCS,
75 bool AllowObjCWritebackConversion);
77 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
79 bool InOverloadResolution,
80 StandardConversionSequence &SCS,
82 static OverloadingResult
83 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
84 UserDefinedConversionSequence& User,
85 OverloadCandidateSet& Conversions,
87 bool AllowObjCConversionOnExplicit);
90 static ImplicitConversionSequence::CompareKind
91 CompareStandardConversionSequences(Sema &S,
92 const StandardConversionSequence& SCS1,
93 const StandardConversionSequence& SCS2);
95 static ImplicitConversionSequence::CompareKind
96 CompareQualificationConversions(Sema &S,
97 const StandardConversionSequence& SCS1,
98 const StandardConversionSequence& SCS2);
100 static ImplicitConversionSequence::CompareKind
101 CompareDerivedToBaseConversions(Sema &S,
102 const StandardConversionSequence& SCS1,
103 const StandardConversionSequence& SCS2);
107 /// GetConversionCategory - Retrieve the implicit conversion
108 /// category corresponding to the given implicit conversion kind.
109 ImplicitConversionCategory
110 GetConversionCategory(ImplicitConversionKind Kind) {
111 static const ImplicitConversionCategory
112 Category[(int)ICK_Num_Conversion_Kinds] = {
114 ICC_Lvalue_Transformation,
115 ICC_Lvalue_Transformation,
116 ICC_Lvalue_Transformation,
118 ICC_Qualification_Adjustment,
136 return Category[(int)Kind];
139 /// GetConversionRank - Retrieve the implicit conversion rank
140 /// corresponding to the given implicit conversion kind.
141 ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
142 static const ImplicitConversionRank
143 Rank[(int)ICK_Num_Conversion_Kinds] = {
164 ICR_Complex_Real_Conversion,
167 ICR_Writeback_Conversion
169 return Rank[(int)Kind];
172 /// GetImplicitConversionName - Return the name of this kind of
173 /// implicit conversion.
174 const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
175 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
179 "Function-to-pointer",
180 "Noreturn adjustment",
182 "Integral promotion",
183 "Floating point promotion",
185 "Integral conversion",
186 "Floating conversion",
187 "Complex conversion",
188 "Floating-integral conversion",
189 "Pointer conversion",
190 "Pointer-to-member conversion",
191 "Boolean conversion",
192 "Compatible-types conversion",
193 "Derived-to-base conversion",
196 "Complex-real conversion",
197 "Block Pointer conversion",
198 "Transparent Union Conversion"
199 "Writeback conversion"
204 /// StandardConversionSequence - Set the standard conversion
205 /// sequence to the identity conversion.
206 void StandardConversionSequence::setAsIdentityConversion() {
207 First = ICK_Identity;
208 Second = ICK_Identity;
209 Third = ICK_Identity;
210 DeprecatedStringLiteralToCharPtr = false;
211 QualificationIncludesObjCLifetime = false;
212 ReferenceBinding = false;
213 DirectBinding = false;
214 IsLvalueReference = true;
215 BindsToFunctionLvalue = false;
216 BindsToRvalue = false;
217 BindsImplicitObjectArgumentWithoutRefQualifier = false;
218 ObjCLifetimeConversionBinding = false;
219 CopyConstructor = nullptr;
222 /// getRank - Retrieve the rank of this standard conversion sequence
223 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
224 /// implicit conversions.
225 ImplicitConversionRank StandardConversionSequence::getRank() const {
226 ImplicitConversionRank Rank = ICR_Exact_Match;
227 if (GetConversionRank(First) > Rank)
228 Rank = GetConversionRank(First);
229 if (GetConversionRank(Second) > Rank)
230 Rank = GetConversionRank(Second);
231 if (GetConversionRank(Third) > Rank)
232 Rank = GetConversionRank(Third);
236 /// isPointerConversionToBool - Determines whether this conversion is
237 /// a conversion of a pointer or pointer-to-member to bool. This is
238 /// used as part of the ranking of standard conversion sequences
239 /// (C++ 13.3.3.2p4).
240 bool StandardConversionSequence::isPointerConversionToBool() const {
241 // Note that FromType has not necessarily been transformed by the
242 // array-to-pointer or function-to-pointer implicit conversions, so
243 // check for their presence as well as checking whether FromType is
245 if (getToType(1)->isBooleanType() &&
246 (getFromType()->isPointerType() ||
247 getFromType()->isObjCObjectPointerType() ||
248 getFromType()->isBlockPointerType() ||
249 getFromType()->isNullPtrType() ||
250 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
256 /// isPointerConversionToVoidPointer - Determines whether this
257 /// conversion is a conversion of a pointer to a void pointer. This is
258 /// used as part of the ranking of standard conversion sequences (C++
261 StandardConversionSequence::
262 isPointerConversionToVoidPointer(ASTContext& Context) const {
263 QualType FromType = getFromType();
264 QualType ToType = getToType(1);
266 // Note that FromType has not necessarily been transformed by the
267 // array-to-pointer implicit conversion, so check for its presence
268 // and redo the conversion to get a pointer.
269 if (First == ICK_Array_To_Pointer)
270 FromType = Context.getArrayDecayedType(FromType);
272 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
273 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
274 return ToPtrType->getPointeeType()->isVoidType();
279 /// Skip any implicit casts which could be either part of a narrowing conversion
280 /// or after one in an implicit conversion.
281 static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
282 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
283 switch (ICE->getCastKind()) {
285 case CK_IntegralCast:
286 case CK_IntegralToBoolean:
287 case CK_IntegralToFloating:
288 case CK_FloatingToIntegral:
289 case CK_FloatingToBoolean:
290 case CK_FloatingCast:
291 Converted = ICE->getSubExpr();
302 /// Check if this standard conversion sequence represents a narrowing
303 /// conversion, according to C++11 [dcl.init.list]p7.
305 /// \param Ctx The AST context.
306 /// \param Converted The result of applying this standard conversion sequence.
307 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
308 /// value of the expression prior to the narrowing conversion.
309 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
310 /// type of the expression prior to the narrowing conversion.
312 StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
313 const Expr *Converted,
314 APValue &ConstantValue,
315 QualType &ConstantType) const {
316 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
318 // C++11 [dcl.init.list]p7:
319 // A narrowing conversion is an implicit conversion ...
320 QualType FromType = getToType(0);
321 QualType ToType = getToType(1);
323 // -- from a floating-point type to an integer type, or
325 // -- from an integer type or unscoped enumeration type to a floating-point
326 // type, except where the source is a constant expression and the actual
327 // value after conversion will fit into the target type and will produce
328 // the original value when converted back to the original type, or
329 case ICK_Floating_Integral:
330 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
331 return NK_Type_Narrowing;
332 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
333 llvm::APSInt IntConstantValue;
334 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
336 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
337 // Convert the integer to the floating type.
338 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
339 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
340 llvm::APFloat::rmNearestTiesToEven);
342 llvm::APSInt ConvertedValue = IntConstantValue;
344 Result.convertToInteger(ConvertedValue,
345 llvm::APFloat::rmTowardZero, &ignored);
346 // If the resulting value is different, this was a narrowing conversion.
347 if (IntConstantValue != ConvertedValue) {
348 ConstantValue = APValue(IntConstantValue);
349 ConstantType = Initializer->getType();
350 return NK_Constant_Narrowing;
353 // Variables are always narrowings.
354 return NK_Variable_Narrowing;
357 return NK_Not_Narrowing;
359 // -- from long double to double or float, or from double to float, except
360 // where the source is a constant expression and the actual value after
361 // conversion is within the range of values that can be represented (even
362 // if it cannot be represented exactly), or
363 case ICK_Floating_Conversion:
364 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
365 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
366 // FromType is larger than ToType.
367 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
368 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
370 assert(ConstantValue.isFloat());
371 llvm::APFloat FloatVal = ConstantValue.getFloat();
372 // Convert the source value into the target type.
374 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
375 Ctx.getFloatTypeSemantics(ToType),
376 llvm::APFloat::rmNearestTiesToEven, &ignored);
377 // If there was no overflow, the source value is within the range of
378 // values that can be represented.
379 if (ConvertStatus & llvm::APFloat::opOverflow) {
380 ConstantType = Initializer->getType();
381 return NK_Constant_Narrowing;
384 return NK_Variable_Narrowing;
387 return NK_Not_Narrowing;
389 // -- from an integer type or unscoped enumeration type to an integer type
390 // that cannot represent all the values of the original type, except where
391 // the source is a constant expression and the actual value after
392 // conversion will fit into the target type and will produce the original
393 // value when converted back to the original type.
394 case ICK_Boolean_Conversion: // Bools are integers too.
395 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
396 // Boolean conversions can be from pointers and pointers to members
397 // [conv.bool], and those aren't considered narrowing conversions.
398 return NK_Not_Narrowing;
399 } // Otherwise, fall through to the integral case.
400 case ICK_Integral_Conversion: {
401 assert(FromType->isIntegralOrUnscopedEnumerationType());
402 assert(ToType->isIntegralOrUnscopedEnumerationType());
403 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
404 const unsigned FromWidth = Ctx.getIntWidth(FromType);
405 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
406 const unsigned ToWidth = Ctx.getIntWidth(ToType);
408 if (FromWidth > ToWidth ||
409 (FromWidth == ToWidth && FromSigned != ToSigned) ||
410 (FromSigned && !ToSigned)) {
411 // Not all values of FromType can be represented in ToType.
412 llvm::APSInt InitializerValue;
413 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
414 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
415 // Such conversions on variables are always narrowing.
416 return NK_Variable_Narrowing;
418 bool Narrowing = false;
419 if (FromWidth < ToWidth) {
420 // Negative -> unsigned is narrowing. Otherwise, more bits is never
422 if (InitializerValue.isSigned() && InitializerValue.isNegative())
425 // Add a bit to the InitializerValue so we don't have to worry about
426 // signed vs. unsigned comparisons.
427 InitializerValue = InitializerValue.extend(
428 InitializerValue.getBitWidth() + 1);
429 // Convert the initializer to and from the target width and signed-ness.
430 llvm::APSInt ConvertedValue = InitializerValue;
431 ConvertedValue = ConvertedValue.trunc(ToWidth);
432 ConvertedValue.setIsSigned(ToSigned);
433 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
434 ConvertedValue.setIsSigned(InitializerValue.isSigned());
435 // If the result is different, this was a narrowing conversion.
436 if (ConvertedValue != InitializerValue)
440 ConstantType = Initializer->getType();
441 ConstantValue = APValue(InitializerValue);
442 return NK_Constant_Narrowing;
445 return NK_Not_Narrowing;
449 // Other kinds of conversions are not narrowings.
450 return NK_Not_Narrowing;
454 /// dump - Print this standard conversion sequence to standard
455 /// error. Useful for debugging overloading issues.
456 void StandardConversionSequence::dump() const {
457 raw_ostream &OS = llvm::errs();
458 bool PrintedSomething = false;
459 if (First != ICK_Identity) {
460 OS << GetImplicitConversionName(First);
461 PrintedSomething = true;
464 if (Second != ICK_Identity) {
465 if (PrintedSomething) {
468 OS << GetImplicitConversionName(Second);
470 if (CopyConstructor) {
471 OS << " (by copy constructor)";
472 } else if (DirectBinding) {
473 OS << " (direct reference binding)";
474 } else if (ReferenceBinding) {
475 OS << " (reference binding)";
477 PrintedSomething = true;
480 if (Third != ICK_Identity) {
481 if (PrintedSomething) {
484 OS << GetImplicitConversionName(Third);
485 PrintedSomething = true;
488 if (!PrintedSomething) {
489 OS << "No conversions required";
493 /// dump - Print this user-defined conversion sequence to standard
494 /// error. Useful for debugging overloading issues.
495 void UserDefinedConversionSequence::dump() const {
496 raw_ostream &OS = llvm::errs();
497 if (Before.First || Before.Second || Before.Third) {
501 if (ConversionFunction)
502 OS << '\'' << *ConversionFunction << '\'';
504 OS << "aggregate initialization";
505 if (After.First || After.Second || After.Third) {
511 /// dump - Print this implicit conversion sequence to standard
512 /// error. Useful for debugging overloading issues.
513 void ImplicitConversionSequence::dump() const {
514 raw_ostream &OS = llvm::errs();
515 if (isStdInitializerListElement())
516 OS << "Worst std::initializer_list element conversion: ";
517 switch (ConversionKind) {
518 case StandardConversion:
519 OS << "Standard conversion: ";
522 case UserDefinedConversion:
523 OS << "User-defined conversion: ";
526 case EllipsisConversion:
527 OS << "Ellipsis conversion";
529 case AmbiguousConversion:
530 OS << "Ambiguous conversion";
533 OS << "Bad conversion";
540 void AmbiguousConversionSequence::construct() {
541 new (&conversions()) ConversionSet();
544 void AmbiguousConversionSequence::destruct() {
545 conversions().~ConversionSet();
549 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
550 FromTypePtr = O.FromTypePtr;
551 ToTypePtr = O.ToTypePtr;
552 new (&conversions()) ConversionSet(O.conversions());
556 // Structure used by DeductionFailureInfo to store
557 // template argument information.
558 struct DFIArguments {
559 TemplateArgument FirstArg;
560 TemplateArgument SecondArg;
562 // Structure used by DeductionFailureInfo to store
563 // template parameter and template argument information.
564 struct DFIParamWithArguments : DFIArguments {
565 TemplateParameter Param;
569 /// \brief Convert from Sema's representation of template deduction information
570 /// to the form used in overload-candidate information.
571 DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context,
572 Sema::TemplateDeductionResult TDK,
573 TemplateDeductionInfo &Info) {
574 DeductionFailureInfo Result;
575 Result.Result = static_cast<unsigned>(TDK);
576 Result.HasDiagnostic = false;
577 Result.Data = nullptr;
579 case Sema::TDK_Success:
580 case Sema::TDK_Invalid:
581 case Sema::TDK_InstantiationDepth:
582 case Sema::TDK_TooManyArguments:
583 case Sema::TDK_TooFewArguments:
586 case Sema::TDK_Incomplete:
587 case Sema::TDK_InvalidExplicitArguments:
588 Result.Data = Info.Param.getOpaqueValue();
591 case Sema::TDK_NonDeducedMismatch: {
592 // FIXME: Should allocate from normal heap so that we can free this later.
593 DFIArguments *Saved = new (Context) DFIArguments;
594 Saved->FirstArg = Info.FirstArg;
595 Saved->SecondArg = Info.SecondArg;
600 case Sema::TDK_Inconsistent:
601 case Sema::TDK_Underqualified: {
602 // FIXME: Should allocate from normal heap so that we can free this later.
603 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
604 Saved->Param = Info.Param;
605 Saved->FirstArg = Info.FirstArg;
606 Saved->SecondArg = Info.SecondArg;
611 case Sema::TDK_SubstitutionFailure:
612 Result.Data = Info.take();
613 if (Info.hasSFINAEDiagnostic()) {
614 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
615 SourceLocation(), PartialDiagnostic::NullDiagnostic());
616 Info.takeSFINAEDiagnostic(*Diag);
617 Result.HasDiagnostic = true;
621 case Sema::TDK_FailedOverloadResolution:
622 Result.Data = Info.Expression;
625 case Sema::TDK_MiscellaneousDeductionFailure:
632 void DeductionFailureInfo::Destroy() {
633 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
634 case Sema::TDK_Success:
635 case Sema::TDK_Invalid:
636 case Sema::TDK_InstantiationDepth:
637 case Sema::TDK_Incomplete:
638 case Sema::TDK_TooManyArguments:
639 case Sema::TDK_TooFewArguments:
640 case Sema::TDK_InvalidExplicitArguments:
641 case Sema::TDK_FailedOverloadResolution:
644 case Sema::TDK_Inconsistent:
645 case Sema::TDK_Underqualified:
646 case Sema::TDK_NonDeducedMismatch:
647 // FIXME: Destroy the data?
651 case Sema::TDK_SubstitutionFailure:
652 // FIXME: Destroy the template argument list?
654 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
655 Diag->~PartialDiagnosticAt();
656 HasDiagnostic = false;
661 case Sema::TDK_MiscellaneousDeductionFailure:
666 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
668 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
672 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
673 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
674 case Sema::TDK_Success:
675 case Sema::TDK_Invalid:
676 case Sema::TDK_InstantiationDepth:
677 case Sema::TDK_TooManyArguments:
678 case Sema::TDK_TooFewArguments:
679 case Sema::TDK_SubstitutionFailure:
680 case Sema::TDK_NonDeducedMismatch:
681 case Sema::TDK_FailedOverloadResolution:
682 return TemplateParameter();
684 case Sema::TDK_Incomplete:
685 case Sema::TDK_InvalidExplicitArguments:
686 return TemplateParameter::getFromOpaqueValue(Data);
688 case Sema::TDK_Inconsistent:
689 case Sema::TDK_Underqualified:
690 return static_cast<DFIParamWithArguments*>(Data)->Param;
693 case Sema::TDK_MiscellaneousDeductionFailure:
697 return TemplateParameter();
700 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
701 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
702 case Sema::TDK_Success:
703 case Sema::TDK_Invalid:
704 case Sema::TDK_InstantiationDepth:
705 case Sema::TDK_TooManyArguments:
706 case Sema::TDK_TooFewArguments:
707 case Sema::TDK_Incomplete:
708 case Sema::TDK_InvalidExplicitArguments:
709 case Sema::TDK_Inconsistent:
710 case Sema::TDK_Underqualified:
711 case Sema::TDK_NonDeducedMismatch:
712 case Sema::TDK_FailedOverloadResolution:
715 case Sema::TDK_SubstitutionFailure:
716 return static_cast<TemplateArgumentList*>(Data);
719 case Sema::TDK_MiscellaneousDeductionFailure:
726 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
727 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
728 case Sema::TDK_Success:
729 case Sema::TDK_Invalid:
730 case Sema::TDK_InstantiationDepth:
731 case Sema::TDK_Incomplete:
732 case Sema::TDK_TooManyArguments:
733 case Sema::TDK_TooFewArguments:
734 case Sema::TDK_InvalidExplicitArguments:
735 case Sema::TDK_SubstitutionFailure:
736 case Sema::TDK_FailedOverloadResolution:
739 case Sema::TDK_Inconsistent:
740 case Sema::TDK_Underqualified:
741 case Sema::TDK_NonDeducedMismatch:
742 return &static_cast<DFIArguments*>(Data)->FirstArg;
745 case Sema::TDK_MiscellaneousDeductionFailure:
752 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
753 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
754 case Sema::TDK_Success:
755 case Sema::TDK_Invalid:
756 case Sema::TDK_InstantiationDepth:
757 case Sema::TDK_Incomplete:
758 case Sema::TDK_TooManyArguments:
759 case Sema::TDK_TooFewArguments:
760 case Sema::TDK_InvalidExplicitArguments:
761 case Sema::TDK_SubstitutionFailure:
762 case Sema::TDK_FailedOverloadResolution:
765 case Sema::TDK_Inconsistent:
766 case Sema::TDK_Underqualified:
767 case Sema::TDK_NonDeducedMismatch:
768 return &static_cast<DFIArguments*>(Data)->SecondArg;
771 case Sema::TDK_MiscellaneousDeductionFailure:
778 Expr *DeductionFailureInfo::getExpr() {
779 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
780 Sema::TDK_FailedOverloadResolution)
781 return static_cast<Expr*>(Data);
786 void OverloadCandidateSet::destroyCandidates() {
787 for (iterator i = begin(), e = end(); i != e; ++i) {
788 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
789 i->Conversions[ii].~ImplicitConversionSequence();
790 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
791 i->DeductionFailure.Destroy();
795 void OverloadCandidateSet::clear() {
797 NumInlineSequences = 0;
803 class UnbridgedCastsSet {
808 SmallVector<Entry, 2> Entries;
811 void save(Sema &S, Expr *&E) {
812 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
813 Entry entry = { &E, E };
814 Entries.push_back(entry);
815 E = S.stripARCUnbridgedCast(E);
819 for (SmallVectorImpl<Entry>::iterator
820 i = Entries.begin(), e = Entries.end(); i != e; ++i)
826 /// checkPlaceholderForOverload - Do any interesting placeholder-like
827 /// preprocessing on the given expression.
829 /// \param unbridgedCasts a collection to which to add unbridged casts;
830 /// without this, they will be immediately diagnosed as errors
832 /// Return true on unrecoverable error.
834 checkPlaceholderForOverload(Sema &S, Expr *&E,
835 UnbridgedCastsSet *unbridgedCasts = nullptr) {
836 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
837 // We can't handle overloaded expressions here because overload
838 // resolution might reasonably tweak them.
839 if (placeholder->getKind() == BuiltinType::Overload) return false;
841 // If the context potentially accepts unbridged ARC casts, strip
842 // the unbridged cast and add it to the collection for later restoration.
843 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
845 unbridgedCasts->save(S, E);
849 // Go ahead and check everything else.
850 ExprResult result = S.CheckPlaceholderExpr(E);
851 if (result.isInvalid())
862 /// checkArgPlaceholdersForOverload - Check a set of call operands for
864 static bool checkArgPlaceholdersForOverload(Sema &S,
866 UnbridgedCastsSet &unbridged) {
867 for (unsigned i = 0, e = Args.size(); i != e; ++i)
868 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
874 // IsOverload - Determine whether the given New declaration is an
875 // overload of the declarations in Old. This routine returns false if
876 // New and Old cannot be overloaded, e.g., if New has the same
877 // signature as some function in Old (C++ 1.3.10) or if the Old
878 // declarations aren't functions (or function templates) at all. When
879 // it does return false, MatchedDecl will point to the decl that New
880 // cannot be overloaded with. This decl may be a UsingShadowDecl on
881 // top of the underlying declaration.
883 // Example: Given the following input:
885 // void f(int, float); // #1
886 // void f(int, int); // #2
887 // int f(int, int); // #3
889 // When we process #1, there is no previous declaration of "f",
890 // so IsOverload will not be used.
892 // When we process #2, Old contains only the FunctionDecl for #1. By
893 // comparing the parameter types, we see that #1 and #2 are overloaded
894 // (since they have different signatures), so this routine returns
895 // false; MatchedDecl is unchanged.
897 // When we process #3, Old is an overload set containing #1 and #2. We
898 // compare the signatures of #3 to #1 (they're overloaded, so we do
899 // nothing) and then #3 to #2. Since the signatures of #3 and #2 are
900 // identical (return types of functions are not part of the
901 // signature), IsOverload returns false and MatchedDecl will be set to
902 // point to the FunctionDecl for #2.
904 // 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
905 // into a class by a using declaration. The rules for whether to hide
906 // shadow declarations ignore some properties which otherwise figure
907 // into a function template's signature.
909 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
910 NamedDecl *&Match, bool NewIsUsingDecl) {
911 for (LookupResult::iterator I = Old.begin(), E = Old.end();
913 NamedDecl *OldD = *I;
915 bool OldIsUsingDecl = false;
916 if (isa<UsingShadowDecl>(OldD)) {
917 OldIsUsingDecl = true;
919 // We can always introduce two using declarations into the same
920 // context, even if they have identical signatures.
921 if (NewIsUsingDecl) continue;
923 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
926 // If either declaration was introduced by a using declaration,
927 // we'll need to use slightly different rules for matching.
928 // Essentially, these rules are the normal rules, except that
929 // function templates hide function templates with different
930 // return types or template parameter lists.
931 bool UseMemberUsingDeclRules =
932 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
933 !New->getFriendObjectKind();
935 if (FunctionDecl *OldF = OldD->getAsFunction()) {
936 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
937 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
938 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
942 if (!isa<FunctionTemplateDecl>(OldD) &&
943 !shouldLinkPossiblyHiddenDecl(*I, New))
949 } else if (isa<UsingDecl>(OldD)) {
950 // We can overload with these, which can show up when doing
951 // redeclaration checks for UsingDecls.
952 assert(Old.getLookupKind() == LookupUsingDeclName);
953 } else if (isa<TagDecl>(OldD)) {
954 // We can always overload with tags by hiding them.
955 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
956 // Optimistically assume that an unresolved using decl will
957 // overload; if it doesn't, we'll have to diagnose during
958 // template instantiation.
961 // Only function declarations can be overloaded; object and type
962 // declarations cannot be overloaded.
964 return Ovl_NonFunction;
971 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
972 bool UseUsingDeclRules) {
973 // C++ [basic.start.main]p2: This function shall not be overloaded.
977 // MSVCRT user defined entry points cannot be overloaded.
978 if (New->isMSVCRTEntryPoint())
981 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
982 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
985 // A function template can be overloaded with other function templates
986 // and with normal (non-template) functions.
987 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
990 // Is the function New an overload of the function Old?
991 QualType OldQType = Context.getCanonicalType(Old->getType());
992 QualType NewQType = Context.getCanonicalType(New->getType());
994 // Compare the signatures (C++ 1.3.10) of the two functions to
995 // determine whether they are overloads. If we find any mismatch
996 // in the signature, they are overloads.
998 // If either of these functions is a K&R-style function (no
999 // prototype), then we consider them to have matching signatures.
1000 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1001 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1004 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1005 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1007 // The signature of a function includes the types of its
1008 // parameters (C++ 1.3.10), which includes the presence or absence
1009 // of the ellipsis; see C++ DR 357).
1010 if (OldQType != NewQType &&
1011 (OldType->getNumParams() != NewType->getNumParams() ||
1012 OldType->isVariadic() != NewType->isVariadic() ||
1013 !FunctionParamTypesAreEqual(OldType, NewType)))
1016 // C++ [temp.over.link]p4:
1017 // The signature of a function template consists of its function
1018 // signature, its return type and its template parameter list. The names
1019 // of the template parameters are significant only for establishing the
1020 // relationship between the template parameters and the rest of the
1023 // We check the return type and template parameter lists for function
1024 // templates first; the remaining checks follow.
1026 // However, we don't consider either of these when deciding whether
1027 // a member introduced by a shadow declaration is hidden.
1028 if (!UseUsingDeclRules && NewTemplate &&
1029 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1030 OldTemplate->getTemplateParameters(),
1031 false, TPL_TemplateMatch) ||
1032 OldType->getReturnType() != NewType->getReturnType()))
1035 // If the function is a class member, its signature includes the
1036 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1038 // As part of this, also check whether one of the member functions
1039 // is static, in which case they are not overloads (C++
1040 // 13.1p2). While not part of the definition of the signature,
1041 // this check is important to determine whether these functions
1042 // can be overloaded.
1043 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1044 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1045 if (OldMethod && NewMethod &&
1046 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1047 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1048 if (!UseUsingDeclRules &&
1049 (OldMethod->getRefQualifier() == RQ_None ||
1050 NewMethod->getRefQualifier() == RQ_None)) {
1051 // C++0x [over.load]p2:
1052 // - Member function declarations with the same name and the same
1053 // parameter-type-list as well as member function template
1054 // declarations with the same name, the same parameter-type-list, and
1055 // the same template parameter lists cannot be overloaded if any of
1056 // them, but not all, have a ref-qualifier (8.3.5).
1057 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1058 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1059 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1064 // We may not have applied the implicit const for a constexpr member
1065 // function yet (because we haven't yet resolved whether this is a static
1066 // or non-static member function). Add it now, on the assumption that this
1067 // is a redeclaration of OldMethod.
1068 unsigned OldQuals = OldMethod->getTypeQualifiers();
1069 unsigned NewQuals = NewMethod->getTypeQualifiers();
1070 if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() &&
1071 !isa<CXXConstructorDecl>(NewMethod))
1072 NewQuals |= Qualifiers::Const;
1074 // We do not allow overloading based off of '__restrict'.
1075 OldQuals &= ~Qualifiers::Restrict;
1076 NewQuals &= ~Qualifiers::Restrict;
1077 if (OldQuals != NewQuals)
1081 // enable_if attributes are an order-sensitive part of the signature.
1082 for (specific_attr_iterator<EnableIfAttr>
1083 NewI = New->specific_attr_begin<EnableIfAttr>(),
1084 NewE = New->specific_attr_end<EnableIfAttr>(),
1085 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1086 OldE = Old->specific_attr_end<EnableIfAttr>();
1087 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1088 if (NewI == NewE || OldI == OldE)
1090 llvm::FoldingSetNodeID NewID, OldID;
1091 NewI->getCond()->Profile(NewID, Context, true);
1092 OldI->getCond()->Profile(OldID, Context, true);
1097 // The signatures match; this is not an overload.
1101 /// \brief Checks availability of the function depending on the current
1102 /// function context. Inside an unavailable function, unavailability is ignored.
1104 /// \returns true if \arg FD is unavailable and current context is inside
1105 /// an available function, false otherwise.
1106 bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1107 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1110 /// \brief Tries a user-defined conversion from From to ToType.
1112 /// Produces an implicit conversion sequence for when a standard conversion
1113 /// is not an option. See TryImplicitConversion for more information.
1114 static ImplicitConversionSequence
1115 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1116 bool SuppressUserConversions,
1118 bool InOverloadResolution,
1120 bool AllowObjCWritebackConversion,
1121 bool AllowObjCConversionOnExplicit) {
1122 ImplicitConversionSequence ICS;
1124 if (SuppressUserConversions) {
1125 // We're not in the case above, so there is no conversion that
1127 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1131 // Attempt user-defined conversion.
1132 OverloadCandidateSet Conversions(From->getExprLoc(),
1133 OverloadCandidateSet::CSK_Normal);
1134 OverloadingResult UserDefResult
1135 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1136 AllowExplicit, AllowObjCConversionOnExplicit);
1138 if (UserDefResult == OR_Success) {
1139 ICS.setUserDefined();
1140 ICS.UserDefined.Before.setAsIdentityConversion();
1141 // C++ [over.ics.user]p4:
1142 // A conversion of an expression of class type to the same class
1143 // type is given Exact Match rank, and a conversion of an
1144 // expression of class type to a base class of that type is
1145 // given Conversion rank, in spite of the fact that a copy
1146 // constructor (i.e., a user-defined conversion function) is
1147 // called for those cases.
1148 if (CXXConstructorDecl *Constructor
1149 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1151 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1153 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1154 if (Constructor->isCopyConstructor() &&
1155 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1156 // Turn this into a "standard" conversion sequence, so that it
1157 // gets ranked with standard conversion sequences.
1159 ICS.Standard.setAsIdentityConversion();
1160 ICS.Standard.setFromType(From->getType());
1161 ICS.Standard.setAllToTypes(ToType);
1162 ICS.Standard.CopyConstructor = Constructor;
1163 if (ToCanon != FromCanon)
1164 ICS.Standard.Second = ICK_Derived_To_Base;
1167 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1169 ICS.Ambiguous.setFromType(From->getType());
1170 ICS.Ambiguous.setToType(ToType);
1171 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1172 Cand != Conversions.end(); ++Cand)
1174 ICS.Ambiguous.addConversion(Cand->Function);
1176 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1182 /// TryImplicitConversion - Attempt to perform an implicit conversion
1183 /// from the given expression (Expr) to the given type (ToType). This
1184 /// function returns an implicit conversion sequence that can be used
1185 /// to perform the initialization. Given
1187 /// void f(float f);
1188 /// void g(int i) { f(i); }
1190 /// this routine would produce an implicit conversion sequence to
1191 /// describe the initialization of f from i, which will be a standard
1192 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1193 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1195 /// Note that this routine only determines how the conversion can be
1196 /// performed; it does not actually perform the conversion. As such,
1197 /// it will not produce any diagnostics if no conversion is available,
1198 /// but will instead return an implicit conversion sequence of kind
1199 /// "BadConversion".
1201 /// If @p SuppressUserConversions, then user-defined conversions are
1203 /// If @p AllowExplicit, then explicit user-defined conversions are
1206 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1207 /// writeback conversion, which allows __autoreleasing id* parameters to
1208 /// be initialized with __strong id* or __weak id* arguments.
1209 static ImplicitConversionSequence
1210 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1211 bool SuppressUserConversions,
1213 bool InOverloadResolution,
1215 bool AllowObjCWritebackConversion,
1216 bool AllowObjCConversionOnExplicit) {
1217 ImplicitConversionSequence ICS;
1218 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1219 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1224 if (!S.getLangOpts().CPlusPlus) {
1225 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1229 // C++ [over.ics.user]p4:
1230 // A conversion of an expression of class type to the same class
1231 // type is given Exact Match rank, and a conversion of an
1232 // expression of class type to a base class of that type is
1233 // given Conversion rank, in spite of the fact that a copy/move
1234 // constructor (i.e., a user-defined conversion function) is
1235 // called for those cases.
1236 QualType FromType = From->getType();
1237 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1238 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1239 S.IsDerivedFrom(FromType, ToType))) {
1241 ICS.Standard.setAsIdentityConversion();
1242 ICS.Standard.setFromType(FromType);
1243 ICS.Standard.setAllToTypes(ToType);
1245 // We don't actually check at this point whether there is a valid
1246 // copy/move constructor, since overloading just assumes that it
1247 // exists. When we actually perform initialization, we'll find the
1248 // appropriate constructor to copy the returned object, if needed.
1249 ICS.Standard.CopyConstructor = nullptr;
1251 // Determine whether this is considered a derived-to-base conversion.
1252 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1253 ICS.Standard.Second = ICK_Derived_To_Base;
1258 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1259 AllowExplicit, InOverloadResolution, CStyle,
1260 AllowObjCWritebackConversion,
1261 AllowObjCConversionOnExplicit);
1264 ImplicitConversionSequence
1265 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1266 bool SuppressUserConversions,
1268 bool InOverloadResolution,
1270 bool AllowObjCWritebackConversion) {
1271 return clang::TryImplicitConversion(*this, From, ToType,
1272 SuppressUserConversions, AllowExplicit,
1273 InOverloadResolution, CStyle,
1274 AllowObjCWritebackConversion,
1275 /*AllowObjCConversionOnExplicit=*/false);
1278 /// PerformImplicitConversion - Perform an implicit conversion of the
1279 /// expression From to the type ToType. Returns the
1280 /// converted expression. Flavor is the kind of conversion we're
1281 /// performing, used in the error message. If @p AllowExplicit,
1282 /// explicit user-defined conversions are permitted.
1284 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1285 AssignmentAction Action, bool AllowExplicit) {
1286 ImplicitConversionSequence ICS;
1287 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1291 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1292 AssignmentAction Action, bool AllowExplicit,
1293 ImplicitConversionSequence& ICS) {
1294 if (checkPlaceholderForOverload(*this, From))
1297 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1298 bool AllowObjCWritebackConversion
1299 = getLangOpts().ObjCAutoRefCount &&
1300 (Action == AA_Passing || Action == AA_Sending);
1301 if (getLangOpts().ObjC1)
1302 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1303 ToType, From->getType(), From);
1304 ICS = clang::TryImplicitConversion(*this, From, ToType,
1305 /*SuppressUserConversions=*/false,
1307 /*InOverloadResolution=*/false,
1309 AllowObjCWritebackConversion,
1310 /*AllowObjCConversionOnExplicit=*/false);
1311 return PerformImplicitConversion(From, ToType, ICS, Action);
1314 /// \brief Determine whether the conversion from FromType to ToType is a valid
1315 /// conversion that strips "noreturn" off the nested function type.
1316 bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1317 QualType &ResultTy) {
1318 if (Context.hasSameUnqualifiedType(FromType, ToType))
1321 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1322 // where F adds one of the following at most once:
1324 // - a member pointer
1325 // - a block pointer
1326 CanQualType CanTo = Context.getCanonicalType(ToType);
1327 CanQualType CanFrom = Context.getCanonicalType(FromType);
1328 Type::TypeClass TyClass = CanTo->getTypeClass();
1329 if (TyClass != CanFrom->getTypeClass()) return false;
1330 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1331 if (TyClass == Type::Pointer) {
1332 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1333 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1334 } else if (TyClass == Type::BlockPointer) {
1335 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1336 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1337 } else if (TyClass == Type::MemberPointer) {
1338 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1339 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1344 TyClass = CanTo->getTypeClass();
1345 if (TyClass != CanFrom->getTypeClass()) return false;
1346 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1350 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1351 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1352 if (!EInfo.getNoReturn()) return false;
1354 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1355 assert(QualType(FromFn, 0).isCanonical());
1356 if (QualType(FromFn, 0) != CanTo) return false;
1362 /// \brief Determine whether the conversion from FromType to ToType is a valid
1363 /// vector conversion.
1365 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1367 static bool IsVectorConversion(Sema &S, QualType FromType,
1368 QualType ToType, ImplicitConversionKind &ICK) {
1369 // We need at least one of these types to be a vector type to have a vector
1371 if (!ToType->isVectorType() && !FromType->isVectorType())
1374 // Identical types require no conversions.
1375 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1378 // There are no conversions between extended vector types, only identity.
1379 if (ToType->isExtVectorType()) {
1380 // There are no conversions between extended vector types other than the
1381 // identity conversion.
1382 if (FromType->isExtVectorType())
1385 // Vector splat from any arithmetic type to a vector.
1386 if (FromType->isArithmeticType()) {
1387 ICK = ICK_Vector_Splat;
1392 // We can perform the conversion between vector types in the following cases:
1393 // 1)vector types are equivalent AltiVec and GCC vector types
1394 // 2)lax vector conversions are permitted and the vector types are of the
1396 if (ToType->isVectorType() && FromType->isVectorType()) {
1397 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1398 S.isLaxVectorConversion(FromType, ToType)) {
1399 ICK = ICK_Vector_Conversion;
1407 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1408 bool InOverloadResolution,
1409 StandardConversionSequence &SCS,
1412 /// IsStandardConversion - Determines whether there is a standard
1413 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1414 /// expression From to the type ToType. Standard conversion sequences
1415 /// only consider non-class types; for conversions that involve class
1416 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1417 /// contain the standard conversion sequence required to perform this
1418 /// conversion and this routine will return true. Otherwise, this
1419 /// routine will return false and the value of SCS is unspecified.
1420 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1421 bool InOverloadResolution,
1422 StandardConversionSequence &SCS,
1424 bool AllowObjCWritebackConversion) {
1425 QualType FromType = From->getType();
1427 // Standard conversions (C++ [conv])
1428 SCS.setAsIdentityConversion();
1429 SCS.IncompatibleObjC = false;
1430 SCS.setFromType(FromType);
1431 SCS.CopyConstructor = nullptr;
1433 // There are no standard conversions for class types in C++, so
1434 // abort early. When overloading in C, however, we do permit
1435 if (FromType->isRecordType() || ToType->isRecordType()) {
1436 if (S.getLangOpts().CPlusPlus)
1439 // When we're overloading in C, we allow, as standard conversions,
1442 // The first conversion can be an lvalue-to-rvalue conversion,
1443 // array-to-pointer conversion, or function-to-pointer conversion
1446 if (FromType == S.Context.OverloadTy) {
1447 DeclAccessPair AccessPair;
1448 if (FunctionDecl *Fn
1449 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1451 // We were able to resolve the address of the overloaded function,
1452 // so we can convert to the type of that function.
1453 FromType = Fn->getType();
1455 // we can sometimes resolve &foo<int> regardless of ToType, so check
1456 // if the type matches (identity) or we are converting to bool
1457 if (!S.Context.hasSameUnqualifiedType(
1458 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1460 // if the function type matches except for [[noreturn]], it's ok
1461 if (!S.IsNoReturnConversion(FromType,
1462 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1463 // otherwise, only a boolean conversion is standard
1464 if (!ToType->isBooleanType())
1468 // Check if the "from" expression is taking the address of an overloaded
1469 // function and recompute the FromType accordingly. Take advantage of the
1470 // fact that non-static member functions *must* have such an address-of
1472 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1473 if (Method && !Method->isStatic()) {
1474 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1475 "Non-unary operator on non-static member address");
1476 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1478 "Non-address-of operator on non-static member address");
1479 const Type *ClassType
1480 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1481 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1482 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1483 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1485 "Non-address-of operator for overloaded function expression");
1486 FromType = S.Context.getPointerType(FromType);
1489 // Check that we've computed the proper type after overload resolution.
1490 assert(S.Context.hasSameType(
1492 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1497 // Lvalue-to-rvalue conversion (C++11 4.1):
1498 // A glvalue (3.10) of a non-function, non-array type T can
1499 // be converted to a prvalue.
1500 bool argIsLValue = From->isGLValue();
1502 !FromType->isFunctionType() && !FromType->isArrayType() &&
1503 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1504 SCS.First = ICK_Lvalue_To_Rvalue;
1507 // ... if the lvalue has atomic type, the value has the non-atomic version
1508 // of the type of the lvalue ...
1509 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1510 FromType = Atomic->getValueType();
1512 // If T is a non-class type, the type of the rvalue is the
1513 // cv-unqualified version of T. Otherwise, the type of the rvalue
1514 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1515 // just strip the qualifiers because they don't matter.
1516 FromType = FromType.getUnqualifiedType();
1517 } else if (FromType->isArrayType()) {
1518 // Array-to-pointer conversion (C++ 4.2)
1519 SCS.First = ICK_Array_To_Pointer;
1521 // An lvalue or rvalue of type "array of N T" or "array of unknown
1522 // bound of T" can be converted to an rvalue of type "pointer to
1524 FromType = S.Context.getArrayDecayedType(FromType);
1526 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1527 // This conversion is deprecated in C++03 (D.4)
1528 SCS.DeprecatedStringLiteralToCharPtr = true;
1530 // For the purpose of ranking in overload resolution
1531 // (13.3.3.1.1), this conversion is considered an
1532 // array-to-pointer conversion followed by a qualification
1533 // conversion (4.4). (C++ 4.2p2)
1534 SCS.Second = ICK_Identity;
1535 SCS.Third = ICK_Qualification;
1536 SCS.QualificationIncludesObjCLifetime = false;
1537 SCS.setAllToTypes(FromType);
1540 } else if (FromType->isFunctionType() && argIsLValue) {
1541 // Function-to-pointer conversion (C++ 4.3).
1542 SCS.First = ICK_Function_To_Pointer;
1544 // An lvalue of function type T can be converted to an rvalue of
1545 // type "pointer to T." The result is a pointer to the
1546 // function. (C++ 4.3p1).
1547 FromType = S.Context.getPointerType(FromType);
1549 // We don't require any conversions for the first step.
1550 SCS.First = ICK_Identity;
1552 SCS.setToType(0, FromType);
1554 // The second conversion can be an integral promotion, floating
1555 // point promotion, integral conversion, floating point conversion,
1556 // floating-integral conversion, pointer conversion,
1557 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1558 // For overloading in C, this can also be a "compatible-type"
1560 bool IncompatibleObjC = false;
1561 ImplicitConversionKind SecondICK = ICK_Identity;
1562 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1563 // The unqualified versions of the types are the same: there's no
1564 // conversion to do.
1565 SCS.Second = ICK_Identity;
1566 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1567 // Integral promotion (C++ 4.5).
1568 SCS.Second = ICK_Integral_Promotion;
1569 FromType = ToType.getUnqualifiedType();
1570 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1571 // Floating point promotion (C++ 4.6).
1572 SCS.Second = ICK_Floating_Promotion;
1573 FromType = ToType.getUnqualifiedType();
1574 } else if (S.IsComplexPromotion(FromType, ToType)) {
1575 // Complex promotion (Clang extension)
1576 SCS.Second = ICK_Complex_Promotion;
1577 FromType = ToType.getUnqualifiedType();
1578 } else if (ToType->isBooleanType() &&
1579 (FromType->isArithmeticType() ||
1580 FromType->isAnyPointerType() ||
1581 FromType->isBlockPointerType() ||
1582 FromType->isMemberPointerType() ||
1583 FromType->isNullPtrType())) {
1584 // Boolean conversions (C++ 4.12).
1585 SCS.Second = ICK_Boolean_Conversion;
1586 FromType = S.Context.BoolTy;
1587 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1588 ToType->isIntegralType(S.Context)) {
1589 // Integral conversions (C++ 4.7).
1590 SCS.Second = ICK_Integral_Conversion;
1591 FromType = ToType.getUnqualifiedType();
1592 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1593 // Complex conversions (C99 6.3.1.6)
1594 SCS.Second = ICK_Complex_Conversion;
1595 FromType = ToType.getUnqualifiedType();
1596 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1597 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1598 // Complex-real conversions (C99 6.3.1.7)
1599 SCS.Second = ICK_Complex_Real;
1600 FromType = ToType.getUnqualifiedType();
1601 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1602 // Floating point conversions (C++ 4.8).
1603 SCS.Second = ICK_Floating_Conversion;
1604 FromType = ToType.getUnqualifiedType();
1605 } else if ((FromType->isRealFloatingType() &&
1606 ToType->isIntegralType(S.Context)) ||
1607 (FromType->isIntegralOrUnscopedEnumerationType() &&
1608 ToType->isRealFloatingType())) {
1609 // Floating-integral conversions (C++ 4.9).
1610 SCS.Second = ICK_Floating_Integral;
1611 FromType = ToType.getUnqualifiedType();
1612 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1613 SCS.Second = ICK_Block_Pointer_Conversion;
1614 } else if (AllowObjCWritebackConversion &&
1615 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1616 SCS.Second = ICK_Writeback_Conversion;
1617 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1618 FromType, IncompatibleObjC)) {
1619 // Pointer conversions (C++ 4.10).
1620 SCS.Second = ICK_Pointer_Conversion;
1621 SCS.IncompatibleObjC = IncompatibleObjC;
1622 FromType = FromType.getUnqualifiedType();
1623 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1624 InOverloadResolution, FromType)) {
1625 // Pointer to member conversions (4.11).
1626 SCS.Second = ICK_Pointer_Member;
1627 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1628 SCS.Second = SecondICK;
1629 FromType = ToType.getUnqualifiedType();
1630 } else if (!S.getLangOpts().CPlusPlus &&
1631 S.Context.typesAreCompatible(ToType, FromType)) {
1632 // Compatible conversions (Clang extension for C function overloading)
1633 SCS.Second = ICK_Compatible_Conversion;
1634 FromType = ToType.getUnqualifiedType();
1635 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
1636 // Treat a conversion that strips "noreturn" as an identity conversion.
1637 SCS.Second = ICK_NoReturn_Adjustment;
1638 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1639 InOverloadResolution,
1641 SCS.Second = ICK_TransparentUnionConversion;
1643 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1645 // tryAtomicConversion has updated the standard conversion sequence
1648 } else if (ToType->isEventT() &&
1649 From->isIntegerConstantExpr(S.getASTContext()) &&
1650 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1651 SCS.Second = ICK_Zero_Event_Conversion;
1654 // No second conversion required.
1655 SCS.Second = ICK_Identity;
1657 SCS.setToType(1, FromType);
1661 // The third conversion can be a qualification conversion (C++ 4p1).
1662 bool ObjCLifetimeConversion;
1663 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1664 ObjCLifetimeConversion)) {
1665 SCS.Third = ICK_Qualification;
1666 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1668 CanonFrom = S.Context.getCanonicalType(FromType);
1669 CanonTo = S.Context.getCanonicalType(ToType);
1671 // No conversion required
1672 SCS.Third = ICK_Identity;
1674 // C++ [over.best.ics]p6:
1675 // [...] Any difference in top-level cv-qualification is
1676 // subsumed by the initialization itself and does not constitute
1677 // a conversion. [...]
1678 CanonFrom = S.Context.getCanonicalType(FromType);
1679 CanonTo = S.Context.getCanonicalType(ToType);
1680 if (CanonFrom.getLocalUnqualifiedType()
1681 == CanonTo.getLocalUnqualifiedType() &&
1682 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1684 CanonFrom = CanonTo;
1687 SCS.setToType(2, FromType);
1689 // If we have not converted the argument type to the parameter type,
1690 // this is a bad conversion sequence.
1691 if (CanonFrom != CanonTo)
1698 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1700 bool InOverloadResolution,
1701 StandardConversionSequence &SCS,
1704 const RecordType *UT = ToType->getAsUnionType();
1705 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1707 // The field to initialize within the transparent union.
1708 RecordDecl *UD = UT->getDecl();
1709 // It's compatible if the expression matches any of the fields.
1710 for (const auto *it : UD->fields()) {
1711 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1712 CStyle, /*ObjCWritebackConversion=*/false)) {
1713 ToType = it->getType();
1720 /// IsIntegralPromotion - Determines whether the conversion from the
1721 /// expression From (whose potentially-adjusted type is FromType) to
1722 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
1723 /// sets PromotedType to the promoted type.
1724 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1725 const BuiltinType *To = ToType->getAs<BuiltinType>();
1726 // All integers are built-in.
1731 // An rvalue of type char, signed char, unsigned char, short int, or
1732 // unsigned short int can be converted to an rvalue of type int if
1733 // int can represent all the values of the source type; otherwise,
1734 // the source rvalue can be converted to an rvalue of type unsigned
1736 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1737 !FromType->isEnumeralType()) {
1738 if (// We can promote any signed, promotable integer type to an int
1739 (FromType->isSignedIntegerType() ||
1740 // We can promote any unsigned integer type whose size is
1741 // less than int to an int.
1742 (!FromType->isSignedIntegerType() &&
1743 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
1744 return To->getKind() == BuiltinType::Int;
1747 return To->getKind() == BuiltinType::UInt;
1750 // C++11 [conv.prom]p3:
1751 // A prvalue of an unscoped enumeration type whose underlying type is not
1752 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1753 // following types that can represent all the values of the enumeration
1754 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1755 // unsigned int, long int, unsigned long int, long long int, or unsigned
1756 // long long int. If none of the types in that list can represent all the
1757 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1758 // type can be converted to an rvalue a prvalue of the extended integer type
1759 // with lowest integer conversion rank (4.13) greater than the rank of long
1760 // long in which all the values of the enumeration can be represented. If
1761 // there are two such extended types, the signed one is chosen.
1762 // C++11 [conv.prom]p4:
1763 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1764 // can be converted to a prvalue of its underlying type. Moreover, if
1765 // integral promotion can be applied to its underlying type, a prvalue of an
1766 // unscoped enumeration type whose underlying type is fixed can also be
1767 // converted to a prvalue of the promoted underlying type.
1768 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1769 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1770 // provided for a scoped enumeration.
1771 if (FromEnumType->getDecl()->isScoped())
1774 // We can perform an integral promotion to the underlying type of the enum,
1775 // even if that's not the promoted type.
1776 if (FromEnumType->getDecl()->isFixed()) {
1777 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1778 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1779 IsIntegralPromotion(From, Underlying, ToType);
1782 // We have already pre-calculated the promotion type, so this is trivial.
1783 if (ToType->isIntegerType() &&
1784 !RequireCompleteType(From->getLocStart(), FromType, 0))
1785 return Context.hasSameUnqualifiedType(ToType,
1786 FromEnumType->getDecl()->getPromotionType());
1789 // C++0x [conv.prom]p2:
1790 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1791 // to an rvalue a prvalue of the first of the following types that can
1792 // represent all the values of its underlying type: int, unsigned int,
1793 // long int, unsigned long int, long long int, or unsigned long long int.
1794 // If none of the types in that list can represent all the values of its
1795 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1796 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1798 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1799 ToType->isIntegerType()) {
1800 // Determine whether the type we're converting from is signed or
1802 bool FromIsSigned = FromType->isSignedIntegerType();
1803 uint64_t FromSize = Context.getTypeSize(FromType);
1805 // The types we'll try to promote to, in the appropriate
1806 // order. Try each of these types.
1807 QualType PromoteTypes[6] = {
1808 Context.IntTy, Context.UnsignedIntTy,
1809 Context.LongTy, Context.UnsignedLongTy ,
1810 Context.LongLongTy, Context.UnsignedLongLongTy
1812 for (int Idx = 0; Idx < 6; ++Idx) {
1813 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1814 if (FromSize < ToSize ||
1815 (FromSize == ToSize &&
1816 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1817 // We found the type that we can promote to. If this is the
1818 // type we wanted, we have a promotion. Otherwise, no
1820 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
1825 // An rvalue for an integral bit-field (9.6) can be converted to an
1826 // rvalue of type int if int can represent all the values of the
1827 // bit-field; otherwise, it can be converted to unsigned int if
1828 // unsigned int can represent all the values of the bit-field. If
1829 // the bit-field is larger yet, no integral promotion applies to
1830 // it. If the bit-field has an enumerated type, it is treated as any
1831 // other value of that type for promotion purposes (C++ 4.5p3).
1832 // FIXME: We should delay checking of bit-fields until we actually perform the
1836 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
1838 if (FromType->isIntegralType(Context) &&
1839 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1840 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1841 ToSize = Context.getTypeSize(ToType);
1843 // Are we promoting to an int from a bitfield that fits in an int?
1844 if (BitWidth < ToSize ||
1845 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1846 return To->getKind() == BuiltinType::Int;
1849 // Are we promoting to an unsigned int from an unsigned bitfield
1850 // that fits into an unsigned int?
1851 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1852 return To->getKind() == BuiltinType::UInt;
1859 // An rvalue of type bool can be converted to an rvalue of type int,
1860 // with false becoming zero and true becoming one (C++ 4.5p4).
1861 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
1868 /// IsFloatingPointPromotion - Determines whether the conversion from
1869 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1870 /// returns true and sets PromotedType to the promoted type.
1871 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
1872 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1873 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
1874 /// An rvalue of type float can be converted to an rvalue of type
1875 /// double. (C++ 4.6p1).
1876 if (FromBuiltin->getKind() == BuiltinType::Float &&
1877 ToBuiltin->getKind() == BuiltinType::Double)
1881 // When a float is promoted to double or long double, or a
1882 // double is promoted to long double [...].
1883 if (!getLangOpts().CPlusPlus &&
1884 (FromBuiltin->getKind() == BuiltinType::Float ||
1885 FromBuiltin->getKind() == BuiltinType::Double) &&
1886 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1889 // Half can be promoted to float.
1890 if (!getLangOpts().NativeHalfType &&
1891 FromBuiltin->getKind() == BuiltinType::Half &&
1892 ToBuiltin->getKind() == BuiltinType::Float)
1899 /// \brief Determine if a conversion is a complex promotion.
1901 /// A complex promotion is defined as a complex -> complex conversion
1902 /// where the conversion between the underlying real types is a
1903 /// floating-point or integral promotion.
1904 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
1905 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
1909 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
1913 return IsFloatingPointPromotion(FromComplex->getElementType(),
1914 ToComplex->getElementType()) ||
1915 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
1916 ToComplex->getElementType());
1919 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1920 /// the pointer type FromPtr to a pointer to type ToPointee, with the
1921 /// same type qualifiers as FromPtr has on its pointee type. ToType,
1922 /// if non-empty, will be a pointer to ToType that may or may not have
1923 /// the right set of qualifiers on its pointee.
1926 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
1927 QualType ToPointee, QualType ToType,
1928 ASTContext &Context,
1929 bool StripObjCLifetime = false) {
1930 assert((FromPtr->getTypeClass() == Type::Pointer ||
1931 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1932 "Invalid similarly-qualified pointer type");
1934 /// Conversions to 'id' subsume cv-qualifier conversions.
1935 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1936 return ToType.getUnqualifiedType();
1938 QualType CanonFromPointee
1939 = Context.getCanonicalType(FromPtr->getPointeeType());
1940 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
1941 Qualifiers Quals = CanonFromPointee.getQualifiers();
1943 if (StripObjCLifetime)
1944 Quals.removeObjCLifetime();
1946 // Exact qualifier match -> return the pointer type we're converting to.
1947 if (CanonToPointee.getLocalQualifiers() == Quals) {
1948 // ToType is exactly what we need. Return it.
1949 if (!ToType.isNull())
1950 return ToType.getUnqualifiedType();
1952 // Build a pointer to ToPointee. It has the right qualifiers
1954 if (isa<ObjCObjectPointerType>(ToType))
1955 return Context.getObjCObjectPointerType(ToPointee);
1956 return Context.getPointerType(ToPointee);
1959 // Just build a canonical type that has the right qualifiers.
1960 QualType QualifiedCanonToPointee
1961 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
1963 if (isa<ObjCObjectPointerType>(ToType))
1964 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1965 return Context.getPointerType(QualifiedCanonToPointee);
1968 static bool isNullPointerConstantForConversion(Expr *Expr,
1969 bool InOverloadResolution,
1970 ASTContext &Context) {
1971 // Handle value-dependent integral null pointer constants correctly.
1972 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1973 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1974 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
1975 return !InOverloadResolution;
1977 return Expr->isNullPointerConstant(Context,
1978 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1979 : Expr::NPC_ValueDependentIsNull);
1982 /// IsPointerConversion - Determines whether the conversion of the
1983 /// expression From, which has the (possibly adjusted) type FromType,
1984 /// can be converted to the type ToType via a pointer conversion (C++
1985 /// 4.10). If so, returns true and places the converted type (that
1986 /// might differ from ToType in its cv-qualifiers at some level) into
1989 /// This routine also supports conversions to and from block pointers
1990 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
1991 /// pointers to interfaces. FIXME: Once we've determined the
1992 /// appropriate overloading rules for Objective-C, we may want to
1993 /// split the Objective-C checks into a different routine; however,
1994 /// GCC seems to consider all of these conversions to be pointer
1995 /// conversions, so for now they live here. IncompatibleObjC will be
1996 /// set if the conversion is an allowed Objective-C conversion that
1997 /// should result in a warning.
1998 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
1999 bool InOverloadResolution,
2000 QualType& ConvertedType,
2001 bool &IncompatibleObjC) {
2002 IncompatibleObjC = false;
2003 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2007 // Conversion from a null pointer constant to any Objective-C pointer type.
2008 if (ToType->isObjCObjectPointerType() &&
2009 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2010 ConvertedType = ToType;
2014 // Blocks: Block pointers can be converted to void*.
2015 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2016 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2017 ConvertedType = ToType;
2020 // Blocks: A null pointer constant can be converted to a block
2022 if (ToType->isBlockPointerType() &&
2023 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2024 ConvertedType = ToType;
2028 // If the left-hand-side is nullptr_t, the right side can be a null
2029 // pointer constant.
2030 if (ToType->isNullPtrType() &&
2031 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2032 ConvertedType = ToType;
2036 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2040 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2041 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2042 ConvertedType = ToType;
2046 // Beyond this point, both types need to be pointers
2047 // , including objective-c pointers.
2048 QualType ToPointeeType = ToTypePtr->getPointeeType();
2049 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2050 !getLangOpts().ObjCAutoRefCount) {
2051 ConvertedType = BuildSimilarlyQualifiedPointerType(
2052 FromType->getAs<ObjCObjectPointerType>(),
2057 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2061 QualType FromPointeeType = FromTypePtr->getPointeeType();
2063 // If the unqualified pointee types are the same, this can't be a
2064 // pointer conversion, so don't do all of the work below.
2065 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2068 // An rvalue of type "pointer to cv T," where T is an object type,
2069 // can be converted to an rvalue of type "pointer to cv void" (C++
2071 if (FromPointeeType->isIncompleteOrObjectType() &&
2072 ToPointeeType->isVoidType()) {
2073 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2076 /*StripObjCLifetime=*/true);
2080 // MSVC allows implicit function to void* type conversion.
2081 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
2082 ToPointeeType->isVoidType()) {
2083 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2089 // When we're overloading in C, we allow a special kind of pointer
2090 // conversion for compatible-but-not-identical pointee types.
2091 if (!getLangOpts().CPlusPlus &&
2092 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2093 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2099 // C++ [conv.ptr]p3:
2101 // An rvalue of type "pointer to cv D," where D is a class type,
2102 // can be converted to an rvalue of type "pointer to cv B," where
2103 // B is a base class (clause 10) of D. If B is an inaccessible
2104 // (clause 11) or ambiguous (10.2) base class of D, a program that
2105 // necessitates this conversion is ill-formed. The result of the
2106 // conversion is a pointer to the base class sub-object of the
2107 // derived class object. The null pointer value is converted to
2108 // the null pointer value of the destination type.
2110 // Note that we do not check for ambiguity or inaccessibility
2111 // here. That is handled by CheckPointerConversion.
2112 if (getLangOpts().CPlusPlus &&
2113 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2114 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2115 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
2116 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
2117 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2123 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2124 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2125 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2134 /// \brief Adopt the given qualifiers for the given type.
2135 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2136 Qualifiers TQs = T.getQualifiers();
2138 // Check whether qualifiers already match.
2142 if (Qs.compatiblyIncludes(TQs))
2143 return Context.getQualifiedType(T, Qs);
2145 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2148 /// isObjCPointerConversion - Determines whether this is an
2149 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2150 /// with the same arguments and return values.
2151 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2152 QualType& ConvertedType,
2153 bool &IncompatibleObjC) {
2154 if (!getLangOpts().ObjC1)
2157 // The set of qualifiers on the type we're converting from.
2158 Qualifiers FromQualifiers = FromType.getQualifiers();
2160 // First, we handle all conversions on ObjC object pointer types.
2161 const ObjCObjectPointerType* ToObjCPtr =
2162 ToType->getAs<ObjCObjectPointerType>();
2163 const ObjCObjectPointerType *FromObjCPtr =
2164 FromType->getAs<ObjCObjectPointerType>();
2166 if (ToObjCPtr && FromObjCPtr) {
2167 // If the pointee types are the same (ignoring qualifications),
2168 // then this is not a pointer conversion.
2169 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2170 FromObjCPtr->getPointeeType()))
2173 // Check for compatible
2174 // Objective C++: We're able to convert between "id" or "Class" and a
2175 // pointer to any interface (in both directions).
2176 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
2177 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2180 // Conversions with Objective-C's id<...>.
2181 if ((FromObjCPtr->isObjCQualifiedIdType() ||
2182 ToObjCPtr->isObjCQualifiedIdType()) &&
2183 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
2184 /*compare=*/false)) {
2185 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2188 // Objective C++: We're able to convert from a pointer to an
2189 // interface to a pointer to a different interface.
2190 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2191 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2192 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2193 if (getLangOpts().CPlusPlus && LHS && RHS &&
2194 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2195 FromObjCPtr->getPointeeType()))
2197 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2198 ToObjCPtr->getPointeeType(),
2200 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2204 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2205 // Okay: this is some kind of implicit downcast of Objective-C
2206 // interfaces, which is permitted. However, we're going to
2207 // complain about it.
2208 IncompatibleObjC = true;
2209 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2210 ToObjCPtr->getPointeeType(),
2212 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2216 // Beyond this point, both types need to be C pointers or block pointers.
2217 QualType ToPointeeType;
2218 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2219 ToPointeeType = ToCPtr->getPointeeType();
2220 else if (const BlockPointerType *ToBlockPtr =
2221 ToType->getAs<BlockPointerType>()) {
2222 // Objective C++: We're able to convert from a pointer to any object
2223 // to a block pointer type.
2224 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2225 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2228 ToPointeeType = ToBlockPtr->getPointeeType();
2230 else if (FromType->getAs<BlockPointerType>() &&
2231 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2232 // Objective C++: We're able to convert from a block pointer type to a
2233 // pointer to any object.
2234 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2240 QualType FromPointeeType;
2241 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2242 FromPointeeType = FromCPtr->getPointeeType();
2243 else if (const BlockPointerType *FromBlockPtr =
2244 FromType->getAs<BlockPointerType>())
2245 FromPointeeType = FromBlockPtr->getPointeeType();
2249 // If we have pointers to pointers, recursively check whether this
2250 // is an Objective-C conversion.
2251 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2252 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2253 IncompatibleObjC)) {
2254 // We always complain about this conversion.
2255 IncompatibleObjC = true;
2256 ConvertedType = Context.getPointerType(ConvertedType);
2257 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2260 // Allow conversion of pointee being objective-c pointer to another one;
2262 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2263 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2264 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2265 IncompatibleObjC)) {
2267 ConvertedType = Context.getPointerType(ConvertedType);
2268 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2272 // If we have pointers to functions or blocks, check whether the only
2273 // differences in the argument and result types are in Objective-C
2274 // pointer conversions. If so, we permit the conversion (but
2275 // complain about it).
2276 const FunctionProtoType *FromFunctionType
2277 = FromPointeeType->getAs<FunctionProtoType>();
2278 const FunctionProtoType *ToFunctionType
2279 = ToPointeeType->getAs<FunctionProtoType>();
2280 if (FromFunctionType && ToFunctionType) {
2281 // If the function types are exactly the same, this isn't an
2282 // Objective-C pointer conversion.
2283 if (Context.getCanonicalType(FromPointeeType)
2284 == Context.getCanonicalType(ToPointeeType))
2287 // Perform the quick checks that will tell us whether these
2288 // function types are obviously different.
2289 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2290 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2291 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2294 bool HasObjCConversion = false;
2295 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2296 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2297 // Okay, the types match exactly. Nothing to do.
2298 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2299 ToFunctionType->getReturnType(),
2300 ConvertedType, IncompatibleObjC)) {
2301 // Okay, we have an Objective-C pointer conversion.
2302 HasObjCConversion = true;
2304 // Function types are too different. Abort.
2308 // Check argument types.
2309 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2310 ArgIdx != NumArgs; ++ArgIdx) {
2311 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2312 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2313 if (Context.getCanonicalType(FromArgType)
2314 == Context.getCanonicalType(ToArgType)) {
2315 // Okay, the types match exactly. Nothing to do.
2316 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2317 ConvertedType, IncompatibleObjC)) {
2318 // Okay, we have an Objective-C pointer conversion.
2319 HasObjCConversion = true;
2321 // Argument types are too different. Abort.
2326 if (HasObjCConversion) {
2327 // We had an Objective-C conversion. Allow this pointer
2328 // conversion, but complain about it.
2329 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2330 IncompatibleObjC = true;
2338 /// \brief Determine whether this is an Objective-C writeback conversion,
2339 /// used for parameter passing when performing automatic reference counting.
2341 /// \param FromType The type we're converting form.
2343 /// \param ToType The type we're converting to.
2345 /// \param ConvertedType The type that will be produced after applying
2346 /// this conversion.
2347 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2348 QualType &ConvertedType) {
2349 if (!getLangOpts().ObjCAutoRefCount ||
2350 Context.hasSameUnqualifiedType(FromType, ToType))
2353 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2355 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2356 ToPointee = ToPointer->getPointeeType();
2360 Qualifiers ToQuals = ToPointee.getQualifiers();
2361 if (!ToPointee->isObjCLifetimeType() ||
2362 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2363 !ToQuals.withoutObjCLifetime().empty())
2366 // Argument must be a pointer to __strong to __weak.
2367 QualType FromPointee;
2368 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2369 FromPointee = FromPointer->getPointeeType();
2373 Qualifiers FromQuals = FromPointee.getQualifiers();
2374 if (!FromPointee->isObjCLifetimeType() ||
2375 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2376 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2379 // Make sure that we have compatible qualifiers.
2380 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2381 if (!ToQuals.compatiblyIncludes(FromQuals))
2384 // Remove qualifiers from the pointee type we're converting from; they
2385 // aren't used in the compatibility check belong, and we'll be adding back
2386 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2387 FromPointee = FromPointee.getUnqualifiedType();
2389 // The unqualified form of the pointee types must be compatible.
2390 ToPointee = ToPointee.getUnqualifiedType();
2391 bool IncompatibleObjC;
2392 if (Context.typesAreCompatible(FromPointee, ToPointee))
2393 FromPointee = ToPointee;
2394 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2398 /// \brief Construct the type we're converting to, which is a pointer to
2399 /// __autoreleasing pointee.
2400 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2401 ConvertedType = Context.getPointerType(FromPointee);
2405 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2406 QualType& ConvertedType) {
2407 QualType ToPointeeType;
2408 if (const BlockPointerType *ToBlockPtr =
2409 ToType->getAs<BlockPointerType>())
2410 ToPointeeType = ToBlockPtr->getPointeeType();
2414 QualType FromPointeeType;
2415 if (const BlockPointerType *FromBlockPtr =
2416 FromType->getAs<BlockPointerType>())
2417 FromPointeeType = FromBlockPtr->getPointeeType();
2420 // We have pointer to blocks, check whether the only
2421 // differences in the argument and result types are in Objective-C
2422 // pointer conversions. If so, we permit the conversion.
2424 const FunctionProtoType *FromFunctionType
2425 = FromPointeeType->getAs<FunctionProtoType>();
2426 const FunctionProtoType *ToFunctionType
2427 = ToPointeeType->getAs<FunctionProtoType>();
2429 if (!FromFunctionType || !ToFunctionType)
2432 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2435 // Perform the quick checks that will tell us whether these
2436 // function types are obviously different.
2437 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2438 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2441 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2442 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2443 if (FromEInfo != ToEInfo)
2446 bool IncompatibleObjC = false;
2447 if (Context.hasSameType(FromFunctionType->getReturnType(),
2448 ToFunctionType->getReturnType())) {
2449 // Okay, the types match exactly. Nothing to do.
2451 QualType RHS = FromFunctionType->getReturnType();
2452 QualType LHS = ToFunctionType->getReturnType();
2453 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2454 !RHS.hasQualifiers() && LHS.hasQualifiers())
2455 LHS = LHS.getUnqualifiedType();
2457 if (Context.hasSameType(RHS,LHS)) {
2459 } else if (isObjCPointerConversion(RHS, LHS,
2460 ConvertedType, IncompatibleObjC)) {
2461 if (IncompatibleObjC)
2463 // Okay, we have an Objective-C pointer conversion.
2469 // Check argument types.
2470 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2471 ArgIdx != NumArgs; ++ArgIdx) {
2472 IncompatibleObjC = false;
2473 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2474 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2475 if (Context.hasSameType(FromArgType, ToArgType)) {
2476 // Okay, the types match exactly. Nothing to do.
2477 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2478 ConvertedType, IncompatibleObjC)) {
2479 if (IncompatibleObjC)
2481 // Okay, we have an Objective-C pointer conversion.
2483 // Argument types are too different. Abort.
2486 if (LangOpts.ObjCAutoRefCount &&
2487 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2491 ConvertedType = ToType;
2499 ft_parameter_mismatch,
2501 ft_qualifer_mismatch
2504 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2505 /// function types. Catches different number of parameter, mismatch in
2506 /// parameter types, and different return types.
2507 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2508 QualType FromType, QualType ToType) {
2509 // If either type is not valid, include no extra info.
2510 if (FromType.isNull() || ToType.isNull()) {
2511 PDiag << ft_default;
2515 // Get the function type from the pointers.
2516 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2517 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2518 *ToMember = ToType->getAs<MemberPointerType>();
2519 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2520 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2521 << QualType(FromMember->getClass(), 0);
2524 FromType = FromMember->getPointeeType();
2525 ToType = ToMember->getPointeeType();
2528 if (FromType->isPointerType())
2529 FromType = FromType->getPointeeType();
2530 if (ToType->isPointerType())
2531 ToType = ToType->getPointeeType();
2533 // Remove references.
2534 FromType = FromType.getNonReferenceType();
2535 ToType = ToType.getNonReferenceType();
2537 // Don't print extra info for non-specialized template functions.
2538 if (FromType->isInstantiationDependentType() &&
2539 !FromType->getAs<TemplateSpecializationType>()) {
2540 PDiag << ft_default;
2544 // No extra info for same types.
2545 if (Context.hasSameType(FromType, ToType)) {
2546 PDiag << ft_default;
2550 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2551 *ToFunction = ToType->getAs<FunctionProtoType>();
2553 // Both types need to be function types.
2554 if (!FromFunction || !ToFunction) {
2555 PDiag << ft_default;
2559 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2560 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2561 << FromFunction->getNumParams();
2565 // Handle different parameter types.
2567 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2568 PDiag << ft_parameter_mismatch << ArgPos + 1
2569 << ToFunction->getParamType(ArgPos)
2570 << FromFunction->getParamType(ArgPos);
2574 // Handle different return type.
2575 if (!Context.hasSameType(FromFunction->getReturnType(),
2576 ToFunction->getReturnType())) {
2577 PDiag << ft_return_type << ToFunction->getReturnType()
2578 << FromFunction->getReturnType();
2582 unsigned FromQuals = FromFunction->getTypeQuals(),
2583 ToQuals = ToFunction->getTypeQuals();
2584 if (FromQuals != ToQuals) {
2585 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2589 // Unable to find a difference, so add no extra info.
2590 PDiag << ft_default;
2593 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2594 /// for equality of their argument types. Caller has already checked that
2595 /// they have same number of arguments. If the parameters are different,
2596 /// ArgPos will have the parameter index of the first different parameter.
2597 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2598 const FunctionProtoType *NewType,
2600 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2601 N = NewType->param_type_begin(),
2602 E = OldType->param_type_end();
2603 O && (O != E); ++O, ++N) {
2604 if (!Context.hasSameType(O->getUnqualifiedType(),
2605 N->getUnqualifiedType())) {
2607 *ArgPos = O - OldType->param_type_begin();
2614 /// CheckPointerConversion - Check the pointer conversion from the
2615 /// expression From to the type ToType. This routine checks for
2616 /// ambiguous or inaccessible derived-to-base pointer
2617 /// conversions for which IsPointerConversion has already returned
2618 /// true. It returns true and produces a diagnostic if there was an
2619 /// error, or returns false otherwise.
2620 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2622 CXXCastPath& BasePath,
2623 bool IgnoreBaseAccess) {
2624 QualType FromType = From->getType();
2625 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2629 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2630 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2631 Expr::NPCK_ZeroExpression) {
2632 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2633 DiagRuntimeBehavior(From->getExprLoc(), From,
2634 PDiag(diag::warn_impcast_bool_to_null_pointer)
2635 << ToType << From->getSourceRange());
2636 else if (!isUnevaluatedContext())
2637 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2638 << ToType << From->getSourceRange();
2640 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2641 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2642 QualType FromPointeeType = FromPtrType->getPointeeType(),
2643 ToPointeeType = ToPtrType->getPointeeType();
2645 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2646 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2647 // We must have a derived-to-base conversion. Check an
2648 // ambiguous or inaccessible conversion.
2649 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2651 From->getSourceRange(), &BasePath,
2655 // The conversion was successful.
2656 Kind = CK_DerivedToBase;
2659 } else if (const ObjCObjectPointerType *ToPtrType =
2660 ToType->getAs<ObjCObjectPointerType>()) {
2661 if (const ObjCObjectPointerType *FromPtrType =
2662 FromType->getAs<ObjCObjectPointerType>()) {
2663 // Objective-C++ conversions are always okay.
2664 // FIXME: We should have a different class of conversions for the
2665 // Objective-C++ implicit conversions.
2666 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2668 } else if (FromType->isBlockPointerType()) {
2669 Kind = CK_BlockPointerToObjCPointerCast;
2671 Kind = CK_CPointerToObjCPointerCast;
2673 } else if (ToType->isBlockPointerType()) {
2674 if (!FromType->isBlockPointerType())
2675 Kind = CK_AnyPointerToBlockPointerCast;
2678 // We shouldn't fall into this case unless it's valid for other
2680 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2681 Kind = CK_NullToPointer;
2686 /// IsMemberPointerConversion - Determines whether the conversion of the
2687 /// expression From, which has the (possibly adjusted) type FromType, can be
2688 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
2689 /// If so, returns true and places the converted type (that might differ from
2690 /// ToType in its cv-qualifiers at some level) into ConvertedType.
2691 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2693 bool InOverloadResolution,
2694 QualType &ConvertedType) {
2695 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2699 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
2700 if (From->isNullPointerConstant(Context,
2701 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2702 : Expr::NPC_ValueDependentIsNull)) {
2703 ConvertedType = ToType;
2707 // Otherwise, both types have to be member pointers.
2708 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
2712 // A pointer to member of B can be converted to a pointer to member of D,
2713 // where D is derived from B (C++ 4.11p2).
2714 QualType FromClass(FromTypePtr->getClass(), 0);
2715 QualType ToClass(ToTypePtr->getClass(), 0);
2717 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2718 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
2719 IsDerivedFrom(ToClass, FromClass)) {
2720 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2721 ToClass.getTypePtr());
2728 /// CheckMemberPointerConversion - Check the member pointer conversion from the
2729 /// expression From to the type ToType. This routine checks for ambiguous or
2730 /// virtual or inaccessible base-to-derived member pointer conversions
2731 /// for which IsMemberPointerConversion has already returned true. It returns
2732 /// true and produces a diagnostic if there was an error, or returns false
2734 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
2736 CXXCastPath &BasePath,
2737 bool IgnoreBaseAccess) {
2738 QualType FromType = From->getType();
2739 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
2741 // This must be a null pointer to member pointer conversion
2742 assert(From->isNullPointerConstant(Context,
2743 Expr::NPC_ValueDependentIsNull) &&
2744 "Expr must be null pointer constant!");
2745 Kind = CK_NullToMemberPointer;
2749 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
2750 assert(ToPtrType && "No member pointer cast has a target type "
2751 "that is not a member pointer.");
2753 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2754 QualType ToClass = QualType(ToPtrType->getClass(), 0);
2756 // FIXME: What about dependent types?
2757 assert(FromClass->isRecordType() && "Pointer into non-class.");
2758 assert(ToClass->isRecordType() && "Pointer into non-class.");
2760 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2761 /*DetectVirtual=*/true);
2762 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2763 assert(DerivationOkay &&
2764 "Should not have been called if derivation isn't OK.");
2765 (void)DerivationOkay;
2767 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2768 getUnqualifiedType())) {
2769 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2770 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2771 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2775 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
2776 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2777 << FromClass << ToClass << QualType(VBase, 0)
2778 << From->getSourceRange();
2782 if (!IgnoreBaseAccess)
2783 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2785 diag::err_downcast_from_inaccessible_base);
2787 // Must be a base to derived member conversion.
2788 BuildBasePathArray(Paths, BasePath);
2789 Kind = CK_BaseToDerivedMemberPointer;
2793 /// Determine whether the lifetime conversion between the two given
2794 /// qualifiers sets is nontrivial.
2795 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2796 Qualifiers ToQuals) {
2797 // Converting anything to const __unsafe_unretained is trivial.
2798 if (ToQuals.hasConst() &&
2799 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2805 /// IsQualificationConversion - Determines whether the conversion from
2806 /// an rvalue of type FromType to ToType is a qualification conversion
2809 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2810 /// when the qualification conversion involves a change in the Objective-C
2811 /// object lifetime.
2813 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
2814 bool CStyle, bool &ObjCLifetimeConversion) {
2815 FromType = Context.getCanonicalType(FromType);
2816 ToType = Context.getCanonicalType(ToType);
2817 ObjCLifetimeConversion = false;
2819 // If FromType and ToType are the same type, this is not a
2820 // qualification conversion.
2821 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
2825 // A conversion can add cv-qualifiers at levels other than the first
2826 // in multi-level pointers, subject to the following rules: [...]
2827 bool PreviousToQualsIncludeConst = true;
2828 bool UnwrappedAnyPointer = false;
2829 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
2830 // Within each iteration of the loop, we check the qualifiers to
2831 // determine if this still looks like a qualification
2832 // conversion. Then, if all is well, we unwrap one more level of
2833 // pointers or pointers-to-members and do it all again
2834 // until there are no more pointers or pointers-to-members left to
2836 UnwrappedAnyPointer = true;
2838 Qualifiers FromQuals = FromType.getQualifiers();
2839 Qualifiers ToQuals = ToType.getQualifiers();
2842 // Check Objective-C lifetime conversions.
2843 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2844 UnwrappedAnyPointer) {
2845 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2846 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2847 ObjCLifetimeConversion = true;
2848 FromQuals.removeObjCLifetime();
2849 ToQuals.removeObjCLifetime();
2851 // Qualification conversions cannot cast between different
2852 // Objective-C lifetime qualifiers.
2857 // Allow addition/removal of GC attributes but not changing GC attributes.
2858 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2859 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2860 FromQuals.removeObjCGCAttr();
2861 ToQuals.removeObjCGCAttr();
2864 // -- for every j > 0, if const is in cv 1,j then const is in cv
2865 // 2,j, and similarly for volatile.
2866 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
2869 // -- if the cv 1,j and cv 2,j are different, then const is in
2870 // every cv for 0 < k < j.
2871 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
2872 && !PreviousToQualsIncludeConst)
2875 // Keep track of whether all prior cv-qualifiers in the "to" type
2877 PreviousToQualsIncludeConst
2878 = PreviousToQualsIncludeConst && ToQuals.hasConst();
2881 // We are left with FromType and ToType being the pointee types
2882 // after unwrapping the original FromType and ToType the same number
2883 // of types. If we unwrapped any pointers, and if FromType and
2884 // ToType have the same unqualified type (since we checked
2885 // qualifiers above), then this is a qualification conversion.
2886 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
2889 /// \brief - Determine whether this is a conversion from a scalar type to an
2892 /// If successful, updates \c SCS's second and third steps in the conversion
2893 /// sequence to finish the conversion.
2894 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2895 bool InOverloadResolution,
2896 StandardConversionSequence &SCS,
2898 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2902 StandardConversionSequence InnerSCS;
2903 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2904 InOverloadResolution, InnerSCS,
2905 CStyle, /*AllowObjCWritebackConversion=*/false))
2908 SCS.Second = InnerSCS.Second;
2909 SCS.setToType(1, InnerSCS.getToType(1));
2910 SCS.Third = InnerSCS.Third;
2911 SCS.QualificationIncludesObjCLifetime
2912 = InnerSCS.QualificationIncludesObjCLifetime;
2913 SCS.setToType(2, InnerSCS.getToType(2));
2917 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2918 CXXConstructorDecl *Constructor,
2920 const FunctionProtoType *CtorType =
2921 Constructor->getType()->getAs<FunctionProtoType>();
2922 if (CtorType->getNumParams() > 0) {
2923 QualType FirstArg = CtorType->getParamType(0);
2924 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2930 static OverloadingResult
2931 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2933 UserDefinedConversionSequence &User,
2934 OverloadCandidateSet &CandidateSet,
2935 bool AllowExplicit) {
2936 DeclContext::lookup_result R = S.LookupConstructors(To);
2937 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
2938 Con != ConEnd; ++Con) {
2939 NamedDecl *D = *Con;
2940 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2942 // Find the constructor (which may be a template).
2943 CXXConstructorDecl *Constructor = nullptr;
2944 FunctionTemplateDecl *ConstructorTmpl
2945 = dyn_cast<FunctionTemplateDecl>(D);
2946 if (ConstructorTmpl)
2948 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2950 Constructor = cast<CXXConstructorDecl>(D);
2952 bool Usable = !Constructor->isInvalidDecl() &&
2953 S.isInitListConstructor(Constructor) &&
2954 (AllowExplicit || !Constructor->isExplicit());
2956 // If the first argument is (a reference to) the target type,
2957 // suppress conversions.
2958 bool SuppressUserConversions =
2959 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
2960 if (ConstructorTmpl)
2961 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2962 /*ExplicitArgs*/ nullptr,
2964 SuppressUserConversions);
2966 S.AddOverloadCandidate(Constructor, FoundDecl,
2968 SuppressUserConversions);
2972 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2974 OverloadCandidateSet::iterator Best;
2975 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2977 // Record the standard conversion we used and the conversion function.
2978 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2979 QualType ThisType = Constructor->getThisType(S.Context);
2980 // Initializer lists don't have conversions as such.
2981 User.Before.setAsIdentityConversion();
2982 User.HadMultipleCandidates = HadMultipleCandidates;
2983 User.ConversionFunction = Constructor;
2984 User.FoundConversionFunction = Best->FoundDecl;
2985 User.After.setAsIdentityConversion();
2986 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2987 User.After.setAllToTypes(ToType);
2991 case OR_No_Viable_Function:
2992 return OR_No_Viable_Function;
2996 return OR_Ambiguous;
2999 llvm_unreachable("Invalid OverloadResult!");
3002 /// Determines whether there is a user-defined conversion sequence
3003 /// (C++ [over.ics.user]) that converts expression From to the type
3004 /// ToType. If such a conversion exists, User will contain the
3005 /// user-defined conversion sequence that performs such a conversion
3006 /// and this routine will return true. Otherwise, this routine returns
3007 /// false and User is unspecified.
3009 /// \param AllowExplicit true if the conversion should consider C++0x
3010 /// "explicit" conversion functions as well as non-explicit conversion
3011 /// functions (C++0x [class.conv.fct]p2).
3013 /// \param AllowObjCConversionOnExplicit true if the conversion should
3014 /// allow an extra Objective-C pointer conversion on uses of explicit
3015 /// constructors. Requires \c AllowExplicit to also be set.
3016 static OverloadingResult
3017 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3018 UserDefinedConversionSequence &User,
3019 OverloadCandidateSet &CandidateSet,
3021 bool AllowObjCConversionOnExplicit) {
3022 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3024 // Whether we will only visit constructors.
3025 bool ConstructorsOnly = false;
3027 // If the type we are conversion to is a class type, enumerate its
3029 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3030 // C++ [over.match.ctor]p1:
3031 // When objects of class type are direct-initialized (8.5), or
3032 // copy-initialized from an expression of the same or a
3033 // derived class type (8.5), overload resolution selects the
3034 // constructor. [...] For copy-initialization, the candidate
3035 // functions are all the converting constructors (12.3.1) of
3036 // that class. The argument list is the expression-list within
3037 // the parentheses of the initializer.
3038 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3039 (From->getType()->getAs<RecordType>() &&
3040 S.IsDerivedFrom(From->getType(), ToType)))
3041 ConstructorsOnly = true;
3043 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
3044 // RequireCompleteType may have returned true due to some invalid decl
3045 // during template instantiation, but ToType may be complete enough now
3046 // to try to recover.
3047 if (ToType->isIncompleteType()) {
3048 // We're not going to find any constructors.
3049 } else if (CXXRecordDecl *ToRecordDecl
3050 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3052 Expr **Args = &From;
3053 unsigned NumArgs = 1;
3054 bool ListInitializing = false;
3055 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3056 // But first, see if there is an init-list-constructor that will work.
3057 OverloadingResult Result = IsInitializerListConstructorConversion(
3058 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3059 if (Result != OR_No_Viable_Function)
3062 CandidateSet.clear();
3064 // If we're list-initializing, we pass the individual elements as
3065 // arguments, not the entire list.
3066 Args = InitList->getInits();
3067 NumArgs = InitList->getNumInits();
3068 ListInitializing = true;
3071 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3072 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
3073 Con != ConEnd; ++Con) {
3074 NamedDecl *D = *Con;
3075 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3077 // Find the constructor (which may be a template).
3078 CXXConstructorDecl *Constructor = nullptr;
3079 FunctionTemplateDecl *ConstructorTmpl
3080 = dyn_cast<FunctionTemplateDecl>(D);
3081 if (ConstructorTmpl)
3083 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3085 Constructor = cast<CXXConstructorDecl>(D);
3087 bool Usable = !Constructor->isInvalidDecl();
3088 if (ListInitializing)
3089 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3091 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3093 bool SuppressUserConversions = !ConstructorsOnly;
3094 if (SuppressUserConversions && ListInitializing) {
3095 SuppressUserConversions = false;
3097 // If the first argument is (a reference to) the target type,
3098 // suppress conversions.
3099 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3100 S.Context, Constructor, ToType);
3103 if (ConstructorTmpl)
3104 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3105 /*ExplicitArgs*/ nullptr,
3106 llvm::makeArrayRef(Args, NumArgs),
3107 CandidateSet, SuppressUserConversions);
3109 // Allow one user-defined conversion when user specifies a
3110 // From->ToType conversion via an static cast (c-style, etc).
3111 S.AddOverloadCandidate(Constructor, FoundDecl,
3112 llvm::makeArrayRef(Args, NumArgs),
3113 CandidateSet, SuppressUserConversions);
3119 // Enumerate conversion functions, if we're allowed to.
3120 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3121 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
3122 // No conversion functions from incomplete types.
3123 } else if (const RecordType *FromRecordType
3124 = From->getType()->getAs<RecordType>()) {
3125 if (CXXRecordDecl *FromRecordDecl
3126 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3127 // Add all of the conversion functions as candidates.
3128 std::pair<CXXRecordDecl::conversion_iterator,
3129 CXXRecordDecl::conversion_iterator>
3130 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3131 for (CXXRecordDecl::conversion_iterator
3132 I = Conversions.first, E = Conversions.second; I != E; ++I) {
3133 DeclAccessPair FoundDecl = I.getPair();
3134 NamedDecl *D = FoundDecl.getDecl();
3135 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3136 if (isa<UsingShadowDecl>(D))
3137 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3139 CXXConversionDecl *Conv;
3140 FunctionTemplateDecl *ConvTemplate;
3141 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3142 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3144 Conv = cast<CXXConversionDecl>(D);
3146 if (AllowExplicit || !Conv->isExplicit()) {
3148 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3149 ActingContext, From, ToType,
3151 AllowObjCConversionOnExplicit);
3153 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3154 From, ToType, CandidateSet,
3155 AllowObjCConversionOnExplicit);
3161 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3163 OverloadCandidateSet::iterator Best;
3164 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
3166 // Record the standard conversion we used and the conversion function.
3167 if (CXXConstructorDecl *Constructor
3168 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3169 // C++ [over.ics.user]p1:
3170 // If the user-defined conversion is specified by a
3171 // constructor (12.3.1), the initial standard conversion
3172 // sequence converts the source type to the type required by
3173 // the argument of the constructor.
3175 QualType ThisType = Constructor->getThisType(S.Context);
3176 if (isa<InitListExpr>(From)) {
3177 // Initializer lists don't have conversions as such.
3178 User.Before.setAsIdentityConversion();
3180 if (Best->Conversions[0].isEllipsis())
3181 User.EllipsisConversion = true;
3183 User.Before = Best->Conversions[0].Standard;
3184 User.EllipsisConversion = false;
3187 User.HadMultipleCandidates = HadMultipleCandidates;
3188 User.ConversionFunction = Constructor;
3189 User.FoundConversionFunction = Best->FoundDecl;
3190 User.After.setAsIdentityConversion();
3191 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3192 User.After.setAllToTypes(ToType);
3195 if (CXXConversionDecl *Conversion
3196 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3197 // C++ [over.ics.user]p1:
3199 // [...] If the user-defined conversion is specified by a
3200 // conversion function (12.3.2), the initial standard
3201 // conversion sequence converts the source type to the
3202 // implicit object parameter of the conversion function.
3203 User.Before = Best->Conversions[0].Standard;
3204 User.HadMultipleCandidates = HadMultipleCandidates;
3205 User.ConversionFunction = Conversion;
3206 User.FoundConversionFunction = Best->FoundDecl;
3207 User.EllipsisConversion = false;
3209 // C++ [over.ics.user]p2:
3210 // The second standard conversion sequence converts the
3211 // result of the user-defined conversion to the target type
3212 // for the sequence. Since an implicit conversion sequence
3213 // is an initialization, the special rules for
3214 // initialization by user-defined conversion apply when
3215 // selecting the best user-defined conversion for a
3216 // user-defined conversion sequence (see 13.3.3 and
3218 User.After = Best->FinalConversion;
3221 llvm_unreachable("Not a constructor or conversion function?");
3223 case OR_No_Viable_Function:
3224 return OR_No_Viable_Function;
3226 // No conversion here! We're done.
3230 return OR_Ambiguous;
3233 llvm_unreachable("Invalid OverloadResult!");
3237 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3238 ImplicitConversionSequence ICS;
3239 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3240 OverloadCandidateSet::CSK_Normal);
3241 OverloadingResult OvResult =
3242 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3243 CandidateSet, false, false);
3244 if (OvResult == OR_Ambiguous)
3245 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3246 << From->getType() << ToType << From->getSourceRange();
3247 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
3248 if (!RequireCompleteType(From->getLocStart(), ToType,
3249 diag::err_typecheck_nonviable_condition_incomplete,
3250 From->getType(), From->getSourceRange()))
3251 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3252 << From->getType() << From->getSourceRange() << ToType;
3255 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
3259 /// \brief Compare the user-defined conversion functions or constructors
3260 /// of two user-defined conversion sequences to determine whether any ordering
3262 static ImplicitConversionSequence::CompareKind
3263 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3264 FunctionDecl *Function2) {
3265 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
3266 return ImplicitConversionSequence::Indistinguishable;
3269 // If both conversion functions are implicitly-declared conversions from
3270 // a lambda closure type to a function pointer and a block pointer,
3271 // respectively, always prefer the conversion to a function pointer,
3272 // because the function pointer is more lightweight and is more likely
3273 // to keep code working.
3274 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3276 return ImplicitConversionSequence::Indistinguishable;
3278 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3280 return ImplicitConversionSequence::Indistinguishable;
3282 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3283 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3284 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3285 if (Block1 != Block2)
3286 return Block1 ? ImplicitConversionSequence::Worse
3287 : ImplicitConversionSequence::Better;
3290 return ImplicitConversionSequence::Indistinguishable;
3293 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3294 const ImplicitConversionSequence &ICS) {
3295 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3296 (ICS.isUserDefined() &&
3297 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3300 /// CompareImplicitConversionSequences - Compare two implicit
3301 /// conversion sequences to determine whether one is better than the
3302 /// other or if they are indistinguishable (C++ 13.3.3.2).
3303 static ImplicitConversionSequence::CompareKind
3304 CompareImplicitConversionSequences(Sema &S,
3305 const ImplicitConversionSequence& ICS1,
3306 const ImplicitConversionSequence& ICS2)
3308 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3309 // conversion sequences (as defined in 13.3.3.1)
3310 // -- a standard conversion sequence (13.3.3.1.1) is a better
3311 // conversion sequence than a user-defined conversion sequence or
3312 // an ellipsis conversion sequence, and
3313 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3314 // conversion sequence than an ellipsis conversion sequence
3317 // C++0x [over.best.ics]p10:
3318 // For the purpose of ranking implicit conversion sequences as
3319 // described in 13.3.3.2, the ambiguous conversion sequence is
3320 // treated as a user-defined sequence that is indistinguishable
3321 // from any other user-defined conversion sequence.
3323 // String literal to 'char *' conversion has been deprecated in C++03. It has
3324 // been removed from C++11. We still accept this conversion, if it happens at
3325 // the best viable function. Otherwise, this conversion is considered worse
3326 // than ellipsis conversion. Consider this as an extension; this is not in the
3327 // standard. For example:
3329 // int &f(...); // #1
3330 // void f(char*); // #2
3331 // void g() { int &r = f("foo"); }
3333 // In C++03, we pick #2 as the best viable function.
3334 // In C++11, we pick #1 as the best viable function, because ellipsis
3335 // conversion is better than string-literal to char* conversion (since there
3336 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3337 // convert arguments, #2 would be the best viable function in C++11.
3338 // If the best viable function has this conversion, a warning will be issued
3339 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3341 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3342 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3343 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3344 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3345 ? ImplicitConversionSequence::Worse
3346 : ImplicitConversionSequence::Better;
3348 if (ICS1.getKindRank() < ICS2.getKindRank())
3349 return ImplicitConversionSequence::Better;
3350 if (ICS2.getKindRank() < ICS1.getKindRank())
3351 return ImplicitConversionSequence::Worse;
3353 // The following checks require both conversion sequences to be of
3355 if (ICS1.getKind() != ICS2.getKind())
3356 return ImplicitConversionSequence::Indistinguishable;
3358 ImplicitConversionSequence::CompareKind Result =
3359 ImplicitConversionSequence::Indistinguishable;
3361 // Two implicit conversion sequences of the same form are
3362 // indistinguishable conversion sequences unless one of the
3363 // following rules apply: (C++ 13.3.3.2p3):
3364 if (ICS1.isStandard())
3365 Result = CompareStandardConversionSequences(S,
3366 ICS1.Standard, ICS2.Standard);
3367 else if (ICS1.isUserDefined()) {
3368 // User-defined conversion sequence U1 is a better conversion
3369 // sequence than another user-defined conversion sequence U2 if
3370 // they contain the same user-defined conversion function or
3371 // constructor and if the second standard conversion sequence of
3372 // U1 is better than the second standard conversion sequence of
3373 // U2 (C++ 13.3.3.2p3).
3374 if (ICS1.UserDefined.ConversionFunction ==
3375 ICS2.UserDefined.ConversionFunction)
3376 Result = CompareStandardConversionSequences(S,
3377 ICS1.UserDefined.After,
3378 ICS2.UserDefined.After);
3380 Result = compareConversionFunctions(S,
3381 ICS1.UserDefined.ConversionFunction,
3382 ICS2.UserDefined.ConversionFunction);
3385 // List-initialization sequence L1 is a better conversion sequence than
3386 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3387 // for some X and L2 does not.
3388 if (Result == ImplicitConversionSequence::Indistinguishable &&
3390 if (ICS1.isStdInitializerListElement() &&
3391 !ICS2.isStdInitializerListElement())
3392 return ImplicitConversionSequence::Better;
3393 if (!ICS1.isStdInitializerListElement() &&
3394 ICS2.isStdInitializerListElement())
3395 return ImplicitConversionSequence::Worse;
3401 static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3402 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3404 T1 = Context.getUnqualifiedArrayType(T1, Quals);
3405 T2 = Context.getUnqualifiedArrayType(T2, Quals);
3408 return Context.hasSameUnqualifiedType(T1, T2);
3411 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3412 // determine if one is a proper subset of the other.
3413 static ImplicitConversionSequence::CompareKind
3414 compareStandardConversionSubsets(ASTContext &Context,
3415 const StandardConversionSequence& SCS1,
3416 const StandardConversionSequence& SCS2) {
3417 ImplicitConversionSequence::CompareKind Result
3418 = ImplicitConversionSequence::Indistinguishable;
3420 // the identity conversion sequence is considered to be a subsequence of
3421 // any non-identity conversion sequence
3422 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3423 return ImplicitConversionSequence::Better;
3424 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3425 return ImplicitConversionSequence::Worse;
3427 if (SCS1.Second != SCS2.Second) {
3428 if (SCS1.Second == ICK_Identity)
3429 Result = ImplicitConversionSequence::Better;
3430 else if (SCS2.Second == ICK_Identity)
3431 Result = ImplicitConversionSequence::Worse;
3433 return ImplicitConversionSequence::Indistinguishable;
3434 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
3435 return ImplicitConversionSequence::Indistinguishable;
3437 if (SCS1.Third == SCS2.Third) {
3438 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3439 : ImplicitConversionSequence::Indistinguishable;
3442 if (SCS1.Third == ICK_Identity)
3443 return Result == ImplicitConversionSequence::Worse
3444 ? ImplicitConversionSequence::Indistinguishable
3445 : ImplicitConversionSequence::Better;
3447 if (SCS2.Third == ICK_Identity)
3448 return Result == ImplicitConversionSequence::Better
3449 ? ImplicitConversionSequence::Indistinguishable
3450 : ImplicitConversionSequence::Worse;
3452 return ImplicitConversionSequence::Indistinguishable;
3455 /// \brief Determine whether one of the given reference bindings is better
3456 /// than the other based on what kind of bindings they are.
3458 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3459 const StandardConversionSequence &SCS2) {
3460 // C++0x [over.ics.rank]p3b4:
3461 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3462 // implicit object parameter of a non-static member function declared
3463 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3464 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3465 // lvalue reference to a function lvalue and S2 binds an rvalue
3468 // FIXME: Rvalue references. We're going rogue with the above edits,
3469 // because the semantics in the current C++0x working paper (N3225 at the
3470 // time of this writing) break the standard definition of std::forward
3471 // and std::reference_wrapper when dealing with references to functions.
3472 // Proposed wording changes submitted to CWG for consideration.
3473 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3474 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3477 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3478 SCS2.IsLvalueReference) ||
3479 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3480 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3483 /// CompareStandardConversionSequences - Compare two standard
3484 /// conversion sequences to determine whether one is better than the
3485 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3486 static ImplicitConversionSequence::CompareKind
3487 CompareStandardConversionSequences(Sema &S,
3488 const StandardConversionSequence& SCS1,
3489 const StandardConversionSequence& SCS2)
3491 // Standard conversion sequence S1 is a better conversion sequence
3492 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3494 // -- S1 is a proper subsequence of S2 (comparing the conversion
3495 // sequences in the canonical form defined by 13.3.3.1.1,
3496 // excluding any Lvalue Transformation; the identity conversion
3497 // sequence is considered to be a subsequence of any
3498 // non-identity conversion sequence) or, if not that,
3499 if (ImplicitConversionSequence::CompareKind CK
3500 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3503 // -- the rank of S1 is better than the rank of S2 (by the rules
3504 // defined below), or, if not that,
3505 ImplicitConversionRank Rank1 = SCS1.getRank();
3506 ImplicitConversionRank Rank2 = SCS2.getRank();
3508 return ImplicitConversionSequence::Better;
3509 else if (Rank2 < Rank1)
3510 return ImplicitConversionSequence::Worse;
3512 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3513 // are indistinguishable unless one of the following rules
3516 // A conversion that is not a conversion of a pointer, or
3517 // pointer to member, to bool is better than another conversion
3518 // that is such a conversion.
3519 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3520 return SCS2.isPointerConversionToBool()
3521 ? ImplicitConversionSequence::Better
3522 : ImplicitConversionSequence::Worse;
3524 // C++ [over.ics.rank]p4b2:
3526 // If class B is derived directly or indirectly from class A,
3527 // conversion of B* to A* is better than conversion of B* to
3528 // void*, and conversion of A* to void* is better than conversion
3530 bool SCS1ConvertsToVoid
3531 = SCS1.isPointerConversionToVoidPointer(S.Context);
3532 bool SCS2ConvertsToVoid
3533 = SCS2.isPointerConversionToVoidPointer(S.Context);
3534 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3535 // Exactly one of the conversion sequences is a conversion to
3536 // a void pointer; it's the worse conversion.
3537 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3538 : ImplicitConversionSequence::Worse;
3539 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3540 // Neither conversion sequence converts to a void pointer; compare
3541 // their derived-to-base conversions.
3542 if (ImplicitConversionSequence::CompareKind DerivedCK
3543 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
3545 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3546 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3547 // Both conversion sequences are conversions to void
3548 // pointers. Compare the source types to determine if there's an
3549 // inheritance relationship in their sources.
3550 QualType FromType1 = SCS1.getFromType();
3551 QualType FromType2 = SCS2.getFromType();
3553 // Adjust the types we're converting from via the array-to-pointer
3554 // conversion, if we need to.
3555 if (SCS1.First == ICK_Array_To_Pointer)
3556 FromType1 = S.Context.getArrayDecayedType(FromType1);
3557 if (SCS2.First == ICK_Array_To_Pointer)
3558 FromType2 = S.Context.getArrayDecayedType(FromType2);
3560 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3561 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3563 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3564 return ImplicitConversionSequence::Better;
3565 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3566 return ImplicitConversionSequence::Worse;
3568 // Objective-C++: If one interface is more specific than the
3569 // other, it is the better one.
3570 const ObjCObjectPointerType* FromObjCPtr1
3571 = FromType1->getAs<ObjCObjectPointerType>();
3572 const ObjCObjectPointerType* FromObjCPtr2
3573 = FromType2->getAs<ObjCObjectPointerType>();
3574 if (FromObjCPtr1 && FromObjCPtr2) {
3575 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3577 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3579 if (AssignLeft != AssignRight) {
3580 return AssignLeft? ImplicitConversionSequence::Better
3581 : ImplicitConversionSequence::Worse;
3586 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3588 if (ImplicitConversionSequence::CompareKind QualCK
3589 = CompareQualificationConversions(S, SCS1, SCS2))
3592 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3593 // Check for a better reference binding based on the kind of bindings.
3594 if (isBetterReferenceBindingKind(SCS1, SCS2))
3595 return ImplicitConversionSequence::Better;
3596 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3597 return ImplicitConversionSequence::Worse;
3599 // C++ [over.ics.rank]p3b4:
3600 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3601 // which the references refer are the same type except for
3602 // top-level cv-qualifiers, and the type to which the reference
3603 // initialized by S2 refers is more cv-qualified than the type
3604 // to which the reference initialized by S1 refers.
3605 QualType T1 = SCS1.getToType(2);
3606 QualType T2 = SCS2.getToType(2);
3607 T1 = S.Context.getCanonicalType(T1);
3608 T2 = S.Context.getCanonicalType(T2);
3609 Qualifiers T1Quals, T2Quals;
3610 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3611 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3612 if (UnqualT1 == UnqualT2) {
3613 // Objective-C++ ARC: If the references refer to objects with different
3614 // lifetimes, prefer bindings that don't change lifetime.
3615 if (SCS1.ObjCLifetimeConversionBinding !=
3616 SCS2.ObjCLifetimeConversionBinding) {
3617 return SCS1.ObjCLifetimeConversionBinding
3618 ? ImplicitConversionSequence::Worse
3619 : ImplicitConversionSequence::Better;
3622 // If the type is an array type, promote the element qualifiers to the
3623 // type for comparison.
3624 if (isa<ArrayType>(T1) && T1Quals)
3625 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3626 if (isa<ArrayType>(T2) && T2Quals)
3627 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3628 if (T2.isMoreQualifiedThan(T1))
3629 return ImplicitConversionSequence::Better;
3630 else if (T1.isMoreQualifiedThan(T2))
3631 return ImplicitConversionSequence::Worse;
3635 // In Microsoft mode, prefer an integral conversion to a
3636 // floating-to-integral conversion if the integral conversion
3637 // is between types of the same size.
3645 // Here, MSVC will call f(int) instead of generating a compile error
3646 // as clang will do in standard mode.
3647 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3648 SCS2.Second == ICK_Floating_Integral &&
3649 S.Context.getTypeSize(SCS1.getFromType()) ==
3650 S.Context.getTypeSize(SCS1.getToType(2)))
3651 return ImplicitConversionSequence::Better;
3653 return ImplicitConversionSequence::Indistinguishable;
3656 /// CompareQualificationConversions - Compares two standard conversion
3657 /// sequences to determine whether they can be ranked based on their
3658 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3659 ImplicitConversionSequence::CompareKind
3660 CompareQualificationConversions(Sema &S,
3661 const StandardConversionSequence& SCS1,
3662 const StandardConversionSequence& SCS2) {
3664 // -- S1 and S2 differ only in their qualification conversion and
3665 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3666 // cv-qualification signature of type T1 is a proper subset of
3667 // the cv-qualification signature of type T2, and S1 is not the
3668 // deprecated string literal array-to-pointer conversion (4.2).
3669 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3670 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3671 return ImplicitConversionSequence::Indistinguishable;
3673 // FIXME: the example in the standard doesn't use a qualification
3675 QualType T1 = SCS1.getToType(2);
3676 QualType T2 = SCS2.getToType(2);
3677 T1 = S.Context.getCanonicalType(T1);
3678 T2 = S.Context.getCanonicalType(T2);
3679 Qualifiers T1Quals, T2Quals;
3680 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3681 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3683 // If the types are the same, we won't learn anything by unwrapped
3685 if (UnqualT1 == UnqualT2)
3686 return ImplicitConversionSequence::Indistinguishable;
3688 // If the type is an array type, promote the element qualifiers to the type
3690 if (isa<ArrayType>(T1) && T1Quals)
3691 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3692 if (isa<ArrayType>(T2) && T2Quals)
3693 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3695 ImplicitConversionSequence::CompareKind Result
3696 = ImplicitConversionSequence::Indistinguishable;
3698 // Objective-C++ ARC:
3699 // Prefer qualification conversions not involving a change in lifetime
3700 // to qualification conversions that do not change lifetime.
3701 if (SCS1.QualificationIncludesObjCLifetime !=
3702 SCS2.QualificationIncludesObjCLifetime) {
3703 Result = SCS1.QualificationIncludesObjCLifetime
3704 ? ImplicitConversionSequence::Worse
3705 : ImplicitConversionSequence::Better;
3708 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
3709 // Within each iteration of the loop, we check the qualifiers to
3710 // determine if this still looks like a qualification
3711 // conversion. Then, if all is well, we unwrap one more level of
3712 // pointers or pointers-to-members and do it all again
3713 // until there are no more pointers or pointers-to-members left
3714 // to unwrap. This essentially mimics what
3715 // IsQualificationConversion does, but here we're checking for a
3716 // strict subset of qualifiers.
3717 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3718 // The qualifiers are the same, so this doesn't tell us anything
3719 // about how the sequences rank.
3721 else if (T2.isMoreQualifiedThan(T1)) {
3722 // T1 has fewer qualifiers, so it could be the better sequence.
3723 if (Result == ImplicitConversionSequence::Worse)
3724 // Neither has qualifiers that are a subset of the other's
3726 return ImplicitConversionSequence::Indistinguishable;
3728 Result = ImplicitConversionSequence::Better;
3729 } else if (T1.isMoreQualifiedThan(T2)) {
3730 // T2 has fewer qualifiers, so it could be the better sequence.
3731 if (Result == ImplicitConversionSequence::Better)
3732 // Neither has qualifiers that are a subset of the other's
3734 return ImplicitConversionSequence::Indistinguishable;
3736 Result = ImplicitConversionSequence::Worse;
3738 // Qualifiers are disjoint.
3739 return ImplicitConversionSequence::Indistinguishable;
3742 // If the types after this point are equivalent, we're done.
3743 if (S.Context.hasSameUnqualifiedType(T1, T2))
3747 // Check that the winning standard conversion sequence isn't using
3748 // the deprecated string literal array to pointer conversion.
3750 case ImplicitConversionSequence::Better:
3751 if (SCS1.DeprecatedStringLiteralToCharPtr)
3752 Result = ImplicitConversionSequence::Indistinguishable;
3755 case ImplicitConversionSequence::Indistinguishable:
3758 case ImplicitConversionSequence::Worse:
3759 if (SCS2.DeprecatedStringLiteralToCharPtr)
3760 Result = ImplicitConversionSequence::Indistinguishable;
3767 /// CompareDerivedToBaseConversions - Compares two standard conversion
3768 /// sequences to determine whether they can be ranked based on their
3769 /// various kinds of derived-to-base conversions (C++
3770 /// [over.ics.rank]p4b3). As part of these checks, we also look at
3771 /// conversions between Objective-C interface types.
3772 ImplicitConversionSequence::CompareKind
3773 CompareDerivedToBaseConversions(Sema &S,
3774 const StandardConversionSequence& SCS1,
3775 const StandardConversionSequence& SCS2) {
3776 QualType FromType1 = SCS1.getFromType();
3777 QualType ToType1 = SCS1.getToType(1);
3778 QualType FromType2 = SCS2.getFromType();
3779 QualType ToType2 = SCS2.getToType(1);
3781 // Adjust the types we're converting from via the array-to-pointer
3782 // conversion, if we need to.
3783 if (SCS1.First == ICK_Array_To_Pointer)
3784 FromType1 = S.Context.getArrayDecayedType(FromType1);
3785 if (SCS2.First == ICK_Array_To_Pointer)
3786 FromType2 = S.Context.getArrayDecayedType(FromType2);
3788 // Canonicalize all of the types.
3789 FromType1 = S.Context.getCanonicalType(FromType1);
3790 ToType1 = S.Context.getCanonicalType(ToType1);
3791 FromType2 = S.Context.getCanonicalType(FromType2);
3792 ToType2 = S.Context.getCanonicalType(ToType2);
3794 // C++ [over.ics.rank]p4b3:
3796 // If class B is derived directly or indirectly from class A and
3797 // class C is derived directly or indirectly from B,
3799 // Compare based on pointer conversions.
3800 if (SCS1.Second == ICK_Pointer_Conversion &&
3801 SCS2.Second == ICK_Pointer_Conversion &&
3802 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3803 FromType1->isPointerType() && FromType2->isPointerType() &&
3804 ToType1->isPointerType() && ToType2->isPointerType()) {
3805 QualType FromPointee1
3806 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3808 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3809 QualType FromPointee2
3810 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3812 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
3814 // -- conversion of C* to B* is better than conversion of C* to A*,
3815 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3816 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3817 return ImplicitConversionSequence::Better;
3818 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3819 return ImplicitConversionSequence::Worse;
3822 // -- conversion of B* to A* is better than conversion of C* to A*,
3823 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
3824 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3825 return ImplicitConversionSequence::Better;
3826 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3827 return ImplicitConversionSequence::Worse;
3829 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3830 SCS2.Second == ICK_Pointer_Conversion) {
3831 const ObjCObjectPointerType *FromPtr1
3832 = FromType1->getAs<ObjCObjectPointerType>();
3833 const ObjCObjectPointerType *FromPtr2
3834 = FromType2->getAs<ObjCObjectPointerType>();
3835 const ObjCObjectPointerType *ToPtr1
3836 = ToType1->getAs<ObjCObjectPointerType>();
3837 const ObjCObjectPointerType *ToPtr2
3838 = ToType2->getAs<ObjCObjectPointerType>();
3840 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3841 // Apply the same conversion ranking rules for Objective-C pointer types
3842 // that we do for C++ pointers to class types. However, we employ the
3843 // Objective-C pseudo-subtyping relationship used for assignment of
3844 // Objective-C pointer types.
3846 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3847 bool FromAssignRight
3848 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3850 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3852 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3854 // A conversion to an a non-id object pointer type or qualified 'id'
3855 // type is better than a conversion to 'id'.
3856 if (ToPtr1->isObjCIdType() &&
3857 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3858 return ImplicitConversionSequence::Worse;
3859 if (ToPtr2->isObjCIdType() &&
3860 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3861 return ImplicitConversionSequence::Better;
3863 // A conversion to a non-id object pointer type is better than a
3864 // conversion to a qualified 'id' type
3865 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3866 return ImplicitConversionSequence::Worse;
3867 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3868 return ImplicitConversionSequence::Better;
3870 // A conversion to an a non-Class object pointer type or qualified 'Class'
3871 // type is better than a conversion to 'Class'.
3872 if (ToPtr1->isObjCClassType() &&
3873 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3874 return ImplicitConversionSequence::Worse;
3875 if (ToPtr2->isObjCClassType() &&
3876 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3877 return ImplicitConversionSequence::Better;
3879 // A conversion to a non-Class object pointer type is better than a
3880 // conversion to a qualified 'Class' type.
3881 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3882 return ImplicitConversionSequence::Worse;
3883 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3884 return ImplicitConversionSequence::Better;
3886 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3887 if (S.Context.hasSameType(FromType1, FromType2) &&
3888 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3889 (ToAssignLeft != ToAssignRight))
3890 return ToAssignLeft? ImplicitConversionSequence::Worse
3891 : ImplicitConversionSequence::Better;
3893 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3894 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3895 (FromAssignLeft != FromAssignRight))
3896 return FromAssignLeft? ImplicitConversionSequence::Better
3897 : ImplicitConversionSequence::Worse;
3901 // Ranking of member-pointer types.
3902 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3903 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3904 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
3905 const MemberPointerType * FromMemPointer1 =
3906 FromType1->getAs<MemberPointerType>();
3907 const MemberPointerType * ToMemPointer1 =
3908 ToType1->getAs<MemberPointerType>();
3909 const MemberPointerType * FromMemPointer2 =
3910 FromType2->getAs<MemberPointerType>();
3911 const MemberPointerType * ToMemPointer2 =
3912 ToType2->getAs<MemberPointerType>();
3913 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3914 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3915 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3916 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3917 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3918 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3919 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3920 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
3921 // conversion of A::* to B::* is better than conversion of A::* to C::*,
3922 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
3923 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
3924 return ImplicitConversionSequence::Worse;
3925 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
3926 return ImplicitConversionSequence::Better;
3928 // conversion of B::* to C::* is better than conversion of A::* to C::*
3929 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
3930 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
3931 return ImplicitConversionSequence::Better;
3932 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
3933 return ImplicitConversionSequence::Worse;
3937 if (SCS1.Second == ICK_Derived_To_Base) {
3938 // -- conversion of C to B is better than conversion of C to A,
3939 // -- binding of an expression of type C to a reference of type
3940 // B& is better than binding an expression of type C to a
3941 // reference of type A&,
3942 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3943 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3944 if (S.IsDerivedFrom(ToType1, ToType2))
3945 return ImplicitConversionSequence::Better;
3946 else if (S.IsDerivedFrom(ToType2, ToType1))
3947 return ImplicitConversionSequence::Worse;
3950 // -- conversion of B to A is better than conversion of C to A.
3951 // -- binding of an expression of type B to a reference of type
3952 // A& is better than binding an expression of type C to a
3953 // reference of type A&,
3954 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3955 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3956 if (S.IsDerivedFrom(FromType2, FromType1))
3957 return ImplicitConversionSequence::Better;
3958 else if (S.IsDerivedFrom(FromType1, FromType2))
3959 return ImplicitConversionSequence::Worse;
3963 return ImplicitConversionSequence::Indistinguishable;
3966 /// \brief Determine whether the given type is valid, e.g., it is not an invalid
3968 static bool isTypeValid(QualType T) {
3969 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3970 return !Record->isInvalidDecl();
3975 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
3976 /// determine whether they are reference-related,
3977 /// reference-compatible, reference-compatible with added
3978 /// qualification, or incompatible, for use in C++ initialization by
3979 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3980 /// type, and the first type (T1) is the pointee type of the reference
3981 /// type being initialized.
3982 Sema::ReferenceCompareResult
3983 Sema::CompareReferenceRelationship(SourceLocation Loc,
3984 QualType OrigT1, QualType OrigT2,
3985 bool &DerivedToBase,
3986 bool &ObjCConversion,
3987 bool &ObjCLifetimeConversion) {
3988 assert(!OrigT1->isReferenceType() &&
3989 "T1 must be the pointee type of the reference type");
3990 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3992 QualType T1 = Context.getCanonicalType(OrigT1);
3993 QualType T2 = Context.getCanonicalType(OrigT2);
3994 Qualifiers T1Quals, T2Quals;
3995 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3996 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3998 // C++ [dcl.init.ref]p4:
3999 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4000 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4001 // T1 is a base class of T2.
4002 DerivedToBase = false;
4003 ObjCConversion = false;
4004 ObjCLifetimeConversion = false;
4005 if (UnqualT1 == UnqualT2) {
4007 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
4008 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4009 IsDerivedFrom(UnqualT2, UnqualT1))
4010 DerivedToBase = true;
4011 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4012 UnqualT2->isObjCObjectOrInterfaceType() &&
4013 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4014 ObjCConversion = true;
4016 return Ref_Incompatible;
4018 // At this point, we know that T1 and T2 are reference-related (at
4021 // If the type is an array type, promote the element qualifiers to the type
4023 if (isa<ArrayType>(T1) && T1Quals)
4024 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4025 if (isa<ArrayType>(T2) && T2Quals)
4026 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4028 // C++ [dcl.init.ref]p4:
4029 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4030 // reference-related to T2 and cv1 is the same cv-qualification
4031 // as, or greater cv-qualification than, cv2. For purposes of
4032 // overload resolution, cases for which cv1 is greater
4033 // cv-qualification than cv2 are identified as
4034 // reference-compatible with added qualification (see 13.3.3.2).
4036 // Note that we also require equivalence of Objective-C GC and address-space
4037 // qualifiers when performing these computations, so that e.g., an int in
4038 // address space 1 is not reference-compatible with an int in address
4040 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4041 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4042 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4043 ObjCLifetimeConversion = true;
4045 T1Quals.removeObjCLifetime();
4046 T2Quals.removeObjCLifetime();
4049 if (T1Quals == T2Quals)
4050 return Ref_Compatible;
4051 else if (T1Quals.compatiblyIncludes(T2Quals))
4052 return Ref_Compatible_With_Added_Qualification;
4057 /// \brief Look for a user-defined conversion to an value reference-compatible
4058 /// with DeclType. Return true if something definite is found.
4060 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4061 QualType DeclType, SourceLocation DeclLoc,
4062 Expr *Init, QualType T2, bool AllowRvalues,
4063 bool AllowExplicit) {
4064 assert(T2->isRecordType() && "Can only find conversions of record types.");
4065 CXXRecordDecl *T2RecordDecl
4066 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4068 OverloadCandidateSet CandidateSet(DeclLoc, OverloadCandidateSet::CSK_Normal);
4069 std::pair<CXXRecordDecl::conversion_iterator,
4070 CXXRecordDecl::conversion_iterator>
4071 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4072 for (CXXRecordDecl::conversion_iterator
4073 I = Conversions.first, E = Conversions.second; I != E; ++I) {
4075 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4076 if (isa<UsingShadowDecl>(D))
4077 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4079 FunctionTemplateDecl *ConvTemplate
4080 = dyn_cast<FunctionTemplateDecl>(D);
4081 CXXConversionDecl *Conv;
4083 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4085 Conv = cast<CXXConversionDecl>(D);
4087 // If this is an explicit conversion, and we're not allowed to consider
4088 // explicit conversions, skip it.
4089 if (!AllowExplicit && Conv->isExplicit())
4093 bool DerivedToBase = false;
4094 bool ObjCConversion = false;
4095 bool ObjCLifetimeConversion = false;
4097 // If we are initializing an rvalue reference, don't permit conversion
4098 // functions that return lvalues.
4099 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4100 const ReferenceType *RefType
4101 = Conv->getConversionType()->getAs<LValueReferenceType>();
4102 if (RefType && !RefType->getPointeeType()->isFunctionType())
4106 if (!ConvTemplate &&
4107 S.CompareReferenceRelationship(
4109 Conv->getConversionType().getNonReferenceType()
4110 .getUnqualifiedType(),
4111 DeclType.getNonReferenceType().getUnqualifiedType(),
4112 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4113 Sema::Ref_Incompatible)
4116 // If the conversion function doesn't return a reference type,
4117 // it can't be considered for this conversion. An rvalue reference
4118 // is only acceptable if its referencee is a function type.
4120 const ReferenceType *RefType =
4121 Conv->getConversionType()->getAs<ReferenceType>();
4123 (!RefType->isLValueReferenceType() &&
4124 !RefType->getPointeeType()->isFunctionType()))
4129 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
4130 Init, DeclType, CandidateSet,
4131 /*AllowObjCConversionOnExplicit=*/false);
4133 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
4134 DeclType, CandidateSet,
4135 /*AllowObjCConversionOnExplicit=*/false);
4138 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4140 OverloadCandidateSet::iterator Best;
4141 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
4143 // C++ [over.ics.ref]p1:
4145 // [...] If the parameter binds directly to the result of
4146 // applying a conversion function to the argument
4147 // expression, the implicit conversion sequence is a
4148 // user-defined conversion sequence (13.3.3.1.2), with the
4149 // second standard conversion sequence either an identity
4150 // conversion or, if the conversion function returns an
4151 // entity of a type that is a derived class of the parameter
4152 // type, a derived-to-base Conversion.
4153 if (!Best->FinalConversion.DirectBinding)
4156 ICS.setUserDefined();
4157 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4158 ICS.UserDefined.After = Best->FinalConversion;
4159 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4160 ICS.UserDefined.ConversionFunction = Best->Function;
4161 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4162 ICS.UserDefined.EllipsisConversion = false;
4163 assert(ICS.UserDefined.After.ReferenceBinding &&
4164 ICS.UserDefined.After.DirectBinding &&
4165 "Expected a direct reference binding!");
4170 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4171 Cand != CandidateSet.end(); ++Cand)
4173 ICS.Ambiguous.addConversion(Cand->Function);
4176 case OR_No_Viable_Function:
4178 // There was no suitable conversion, or we found a deleted
4179 // conversion; continue with other checks.
4183 llvm_unreachable("Invalid OverloadResult!");
4186 /// \brief Compute an implicit conversion sequence for reference
4188 static ImplicitConversionSequence
4189 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4190 SourceLocation DeclLoc,
4191 bool SuppressUserConversions,
4192 bool AllowExplicit) {
4193 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4195 // Most paths end in a failed conversion.
4196 ImplicitConversionSequence ICS;
4197 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4199 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4200 QualType T2 = Init->getType();
4202 // If the initializer is the address of an overloaded function, try
4203 // to resolve the overloaded function. If all goes well, T2 is the
4204 // type of the resulting function.
4205 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4206 DeclAccessPair Found;
4207 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4212 // Compute some basic properties of the types and the initializer.
4213 bool isRValRef = DeclType->isRValueReferenceType();
4214 bool DerivedToBase = false;
4215 bool ObjCConversion = false;
4216 bool ObjCLifetimeConversion = false;
4217 Expr::Classification InitCategory = Init->Classify(S.Context);
4218 Sema::ReferenceCompareResult RefRelationship
4219 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4220 ObjCConversion, ObjCLifetimeConversion);
4223 // C++0x [dcl.init.ref]p5:
4224 // A reference to type "cv1 T1" is initialized by an expression
4225 // of type "cv2 T2" as follows:
4227 // -- If reference is an lvalue reference and the initializer expression
4229 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4230 // reference-compatible with "cv2 T2," or
4232 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4233 if (InitCategory.isLValue() &&
4234 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
4235 // C++ [over.ics.ref]p1:
4236 // When a parameter of reference type binds directly (8.5.3)
4237 // to an argument expression, the implicit conversion sequence
4238 // is the identity conversion, unless the argument expression
4239 // has a type that is a derived class of the parameter type,
4240 // in which case the implicit conversion sequence is a
4241 // derived-to-base Conversion (13.3.3.1).
4243 ICS.Standard.First = ICK_Identity;
4244 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4245 : ObjCConversion? ICK_Compatible_Conversion
4247 ICS.Standard.Third = ICK_Identity;
4248 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4249 ICS.Standard.setToType(0, T2);
4250 ICS.Standard.setToType(1, T1);
4251 ICS.Standard.setToType(2, T1);
4252 ICS.Standard.ReferenceBinding = true;
4253 ICS.Standard.DirectBinding = true;
4254 ICS.Standard.IsLvalueReference = !isRValRef;
4255 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4256 ICS.Standard.BindsToRvalue = false;
4257 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4258 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4259 ICS.Standard.CopyConstructor = nullptr;
4260 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4262 // Nothing more to do: the inaccessibility/ambiguity check for
4263 // derived-to-base conversions is suppressed when we're
4264 // computing the implicit conversion sequence (C++
4265 // [over.best.ics]p2).
4269 // -- has a class type (i.e., T2 is a class type), where T1 is
4270 // not reference-related to T2, and can be implicitly
4271 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4272 // is reference-compatible with "cv3 T3" 92) (this
4273 // conversion is selected by enumerating the applicable
4274 // conversion functions (13.3.1.6) and choosing the best
4275 // one through overload resolution (13.3)),
4276 if (!SuppressUserConversions && T2->isRecordType() &&
4277 !S.RequireCompleteType(DeclLoc, T2, 0) &&
4278 RefRelationship == Sema::Ref_Incompatible) {
4279 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4280 Init, T2, /*AllowRvalues=*/false,
4286 // -- Otherwise, the reference shall be an lvalue reference to a
4287 // non-volatile const type (i.e., cv1 shall be const), or the reference
4288 // shall be an rvalue reference.
4290 // We actually handle one oddity of C++ [over.ics.ref] at this
4291 // point, which is that, due to p2 (which short-circuits reference
4292 // binding by only attempting a simple conversion for non-direct
4293 // bindings) and p3's strange wording, we allow a const volatile
4294 // reference to bind to an rvalue. Hence the check for the presence
4295 // of "const" rather than checking for "const" being the only
4297 // This is also the point where rvalue references and lvalue inits no longer
4299 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4302 // -- If the initializer expression
4304 // -- is an xvalue, class prvalue, array prvalue or function
4305 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4306 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4307 (InitCategory.isXValue() ||
4308 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4309 (InitCategory.isLValue() && T2->isFunctionType()))) {
4311 ICS.Standard.First = ICK_Identity;
4312 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4313 : ObjCConversion? ICK_Compatible_Conversion
4315 ICS.Standard.Third = ICK_Identity;
4316 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4317 ICS.Standard.setToType(0, T2);
4318 ICS.Standard.setToType(1, T1);
4319 ICS.Standard.setToType(2, T1);
4320 ICS.Standard.ReferenceBinding = true;
4321 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4322 // binding unless we're binding to a class prvalue.
4323 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4324 // allow the use of rvalue references in C++98/03 for the benefit of
4325 // standard library implementors; therefore, we need the xvalue check here.
4326 ICS.Standard.DirectBinding =
4327 S.getLangOpts().CPlusPlus11 ||
4328 !(InitCategory.isPRValue() || T2->isRecordType());
4329 ICS.Standard.IsLvalueReference = !isRValRef;
4330 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4331 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4332 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4333 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4334 ICS.Standard.CopyConstructor = nullptr;
4335 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4339 // -- has a class type (i.e., T2 is a class type), where T1 is not
4340 // reference-related to T2, and can be implicitly converted to
4341 // an xvalue, class prvalue, or function lvalue of type
4342 // "cv3 T3", where "cv1 T1" is reference-compatible with
4345 // then the reference is bound to the value of the initializer
4346 // expression in the first case and to the result of the conversion
4347 // in the second case (or, in either case, to an appropriate base
4348 // class subobject).
4349 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4350 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
4351 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4352 Init, T2, /*AllowRvalues=*/true,
4354 // In the second case, if the reference is an rvalue reference
4355 // and the second standard conversion sequence of the
4356 // user-defined conversion sequence includes an lvalue-to-rvalue
4357 // conversion, the program is ill-formed.
4358 if (ICS.isUserDefined() && isRValRef &&
4359 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4360 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4365 // A temporary of function type cannot be created; don't even try.
4366 if (T1->isFunctionType())
4369 // -- Otherwise, a temporary of type "cv1 T1" is created and
4370 // initialized from the initializer expression using the
4371 // rules for a non-reference copy initialization (8.5). The
4372 // reference is then bound to the temporary. If T1 is
4373 // reference-related to T2, cv1 must be the same
4374 // cv-qualification as, or greater cv-qualification than,
4375 // cv2; otherwise, the program is ill-formed.
4376 if (RefRelationship == Sema::Ref_Related) {
4377 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4378 // we would be reference-compatible or reference-compatible with
4379 // added qualification. But that wasn't the case, so the reference
4380 // initialization fails.
4382 // Note that we only want to check address spaces and cvr-qualifiers here.
4383 // ObjC GC and lifetime qualifiers aren't important.
4384 Qualifiers T1Quals = T1.getQualifiers();
4385 Qualifiers T2Quals = T2.getQualifiers();
4386 T1Quals.removeObjCGCAttr();
4387 T1Quals.removeObjCLifetime();
4388 T2Quals.removeObjCGCAttr();
4389 T2Quals.removeObjCLifetime();
4390 if (!T1Quals.compatiblyIncludes(T2Quals))
4394 // If at least one of the types is a class type, the types are not
4395 // related, and we aren't allowed any user conversions, the
4396 // reference binding fails. This case is important for breaking
4397 // recursion, since TryImplicitConversion below will attempt to
4398 // create a temporary through the use of a copy constructor.
4399 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4400 (T1->isRecordType() || T2->isRecordType()))
4403 // If T1 is reference-related to T2 and the reference is an rvalue
4404 // reference, the initializer expression shall not be an lvalue.
4405 if (RefRelationship >= Sema::Ref_Related &&
4406 isRValRef && Init->Classify(S.Context).isLValue())
4409 // C++ [over.ics.ref]p2:
4410 // When a parameter of reference type is not bound directly to
4411 // an argument expression, the conversion sequence is the one
4412 // required to convert the argument expression to the
4413 // underlying type of the reference according to
4414 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4415 // to copy-initializing a temporary of the underlying type with
4416 // the argument expression. Any difference in top-level
4417 // cv-qualification is subsumed by the initialization itself
4418 // and does not constitute a conversion.
4419 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4420 /*AllowExplicit=*/false,
4421 /*InOverloadResolution=*/false,
4423 /*AllowObjCWritebackConversion=*/false,
4424 /*AllowObjCConversionOnExplicit=*/false);
4426 // Of course, that's still a reference binding.
4427 if (ICS.isStandard()) {
4428 ICS.Standard.ReferenceBinding = true;
4429 ICS.Standard.IsLvalueReference = !isRValRef;
4430 ICS.Standard.BindsToFunctionLvalue = false;
4431 ICS.Standard.BindsToRvalue = true;
4432 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4433 ICS.Standard.ObjCLifetimeConversionBinding = false;
4434 } else if (ICS.isUserDefined()) {
4435 const ReferenceType *LValRefType =
4436 ICS.UserDefined.ConversionFunction->getReturnType()
4437 ->getAs<LValueReferenceType>();
4439 // C++ [over.ics.ref]p3:
4440 // Except for an implicit object parameter, for which see 13.3.1, a
4441 // standard conversion sequence cannot be formed if it requires [...]
4442 // binding an rvalue reference to an lvalue other than a function
4444 // Note that the function case is not possible here.
4445 if (DeclType->isRValueReferenceType() && LValRefType) {
4446 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4447 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4448 // reference to an rvalue!
4449 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4453 ICS.UserDefined.Before.setAsIdentityConversion();
4454 ICS.UserDefined.After.ReferenceBinding = true;
4455 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4456 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4457 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4458 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4459 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4465 static ImplicitConversionSequence
4466 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4467 bool SuppressUserConversions,
4468 bool InOverloadResolution,
4469 bool AllowObjCWritebackConversion,
4470 bool AllowExplicit = false);
4472 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4473 /// initializer list From.
4474 static ImplicitConversionSequence
4475 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4476 bool SuppressUserConversions,
4477 bool InOverloadResolution,
4478 bool AllowObjCWritebackConversion) {
4479 // C++11 [over.ics.list]p1:
4480 // When an argument is an initializer list, it is not an expression and
4481 // special rules apply for converting it to a parameter type.
4483 ImplicitConversionSequence Result;
4484 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4486 // We need a complete type for what follows. Incomplete types can never be
4487 // initialized from init lists.
4488 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
4491 // C++11 [over.ics.list]p2:
4492 // If the parameter type is std::initializer_list<X> or "array of X" and
4493 // all the elements can be implicitly converted to X, the implicit
4494 // conversion sequence is the worst conversion necessary to convert an
4495 // element of the list to X.
4496 bool toStdInitializerList = false;
4498 if (ToType->isArrayType())
4499 X = S.Context.getAsArrayType(ToType)->getElementType();
4501 toStdInitializerList = S.isStdInitializerList(ToType, &X);
4503 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4504 Expr *Init = From->getInit(i);
4505 ImplicitConversionSequence ICS =
4506 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4507 InOverloadResolution,
4508 AllowObjCWritebackConversion);
4509 // If a single element isn't convertible, fail.
4514 // Otherwise, look for the worst conversion.
4515 if (Result.isBad() ||
4516 CompareImplicitConversionSequences(S, ICS, Result) ==
4517 ImplicitConversionSequence::Worse)
4521 // For an empty list, we won't have computed any conversion sequence.
4522 // Introduce the identity conversion sequence.
4523 if (From->getNumInits() == 0) {
4524 Result.setStandard();
4525 Result.Standard.setAsIdentityConversion();
4526 Result.Standard.setFromType(ToType);
4527 Result.Standard.setAllToTypes(ToType);
4530 Result.setStdInitializerListElement(toStdInitializerList);
4534 // C++11 [over.ics.list]p3:
4535 // Otherwise, if the parameter is a non-aggregate class X and overload
4536 // resolution chooses a single best constructor [...] the implicit
4537 // conversion sequence is a user-defined conversion sequence. If multiple
4538 // constructors are viable but none is better than the others, the
4539 // implicit conversion sequence is a user-defined conversion sequence.
4540 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4541 // This function can deal with initializer lists.
4542 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4543 /*AllowExplicit=*/false,
4544 InOverloadResolution, /*CStyle=*/false,
4545 AllowObjCWritebackConversion,
4546 /*AllowObjCConversionOnExplicit=*/false);
4549 // C++11 [over.ics.list]p4:
4550 // Otherwise, if the parameter has an aggregate type which can be
4551 // initialized from the initializer list [...] the implicit conversion
4552 // sequence is a user-defined conversion sequence.
4553 if (ToType->isAggregateType()) {
4554 // Type is an aggregate, argument is an init list. At this point it comes
4555 // down to checking whether the initialization works.
4556 // FIXME: Find out whether this parameter is consumed or not.
4557 InitializedEntity Entity =
4558 InitializedEntity::InitializeParameter(S.Context, ToType,
4559 /*Consumed=*/false);
4560 if (S.CanPerformCopyInitialization(Entity, From)) {
4561 Result.setUserDefined();
4562 Result.UserDefined.Before.setAsIdentityConversion();
4563 // Initializer lists don't have a type.
4564 Result.UserDefined.Before.setFromType(QualType());
4565 Result.UserDefined.Before.setAllToTypes(QualType());
4567 Result.UserDefined.After.setAsIdentityConversion();
4568 Result.UserDefined.After.setFromType(ToType);
4569 Result.UserDefined.After.setAllToTypes(ToType);
4570 Result.UserDefined.ConversionFunction = nullptr;
4575 // C++11 [over.ics.list]p5:
4576 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4577 if (ToType->isReferenceType()) {
4578 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4579 // mention initializer lists in any way. So we go by what list-
4580 // initialization would do and try to extrapolate from that.
4582 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4584 // If the initializer list has a single element that is reference-related
4585 // to the parameter type, we initialize the reference from that.
4586 if (From->getNumInits() == 1) {
4587 Expr *Init = From->getInit(0);
4589 QualType T2 = Init->getType();
4591 // If the initializer is the address of an overloaded function, try
4592 // to resolve the overloaded function. If all goes well, T2 is the
4593 // type of the resulting function.
4594 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4595 DeclAccessPair Found;
4596 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4597 Init, ToType, false, Found))
4601 // Compute some basic properties of the types and the initializer.
4602 bool dummy1 = false;
4603 bool dummy2 = false;
4604 bool dummy3 = false;
4605 Sema::ReferenceCompareResult RefRelationship
4606 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4609 if (RefRelationship >= Sema::Ref_Related) {
4610 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4611 SuppressUserConversions,
4612 /*AllowExplicit=*/false);
4616 // Otherwise, we bind the reference to a temporary created from the
4617 // initializer list.
4618 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4619 InOverloadResolution,
4620 AllowObjCWritebackConversion);
4621 if (Result.isFailure())
4623 assert(!Result.isEllipsis() &&
4624 "Sub-initialization cannot result in ellipsis conversion.");
4626 // Can we even bind to a temporary?
4627 if (ToType->isRValueReferenceType() ||
4628 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4629 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4630 Result.UserDefined.After;
4631 SCS.ReferenceBinding = true;
4632 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4633 SCS.BindsToRvalue = true;
4634 SCS.BindsToFunctionLvalue = false;
4635 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4636 SCS.ObjCLifetimeConversionBinding = false;
4638 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4643 // C++11 [over.ics.list]p6:
4644 // Otherwise, if the parameter type is not a class:
4645 if (!ToType->isRecordType()) {
4646 // - if the initializer list has one element, the implicit conversion
4647 // sequence is the one required to convert the element to the
4649 unsigned NumInits = From->getNumInits();
4651 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4652 SuppressUserConversions,
4653 InOverloadResolution,
4654 AllowObjCWritebackConversion);
4655 // - if the initializer list has no elements, the implicit conversion
4656 // sequence is the identity conversion.
4657 else if (NumInits == 0) {
4658 Result.setStandard();
4659 Result.Standard.setAsIdentityConversion();
4660 Result.Standard.setFromType(ToType);
4661 Result.Standard.setAllToTypes(ToType);
4666 // C++11 [over.ics.list]p7:
4667 // In all cases other than those enumerated above, no conversion is possible
4671 /// TryCopyInitialization - Try to copy-initialize a value of type
4672 /// ToType from the expression From. Return the implicit conversion
4673 /// sequence required to pass this argument, which may be a bad
4674 /// conversion sequence (meaning that the argument cannot be passed to
4675 /// a parameter of this type). If @p SuppressUserConversions, then we
4676 /// do not permit any user-defined conversion sequences.
4677 static ImplicitConversionSequence
4678 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4679 bool SuppressUserConversions,
4680 bool InOverloadResolution,
4681 bool AllowObjCWritebackConversion,
4682 bool AllowExplicit) {
4683 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4684 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4685 InOverloadResolution,AllowObjCWritebackConversion);
4687 if (ToType->isReferenceType())
4688 return TryReferenceInit(S, From, ToType,
4689 /*FIXME:*/From->getLocStart(),
4690 SuppressUserConversions,
4693 return TryImplicitConversion(S, From, ToType,
4694 SuppressUserConversions,
4695 /*AllowExplicit=*/false,
4696 InOverloadResolution,
4698 AllowObjCWritebackConversion,
4699 /*AllowObjCConversionOnExplicit=*/false);
4702 static bool TryCopyInitialization(const CanQualType FromQTy,
4703 const CanQualType ToQTy,
4706 ExprValueKind FromVK) {
4707 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4708 ImplicitConversionSequence ICS =
4709 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4711 return !ICS.isBad();
4714 /// TryObjectArgumentInitialization - Try to initialize the object
4715 /// parameter of the given member function (@c Method) from the
4716 /// expression @p From.
4717 static ImplicitConversionSequence
4718 TryObjectArgumentInitialization(Sema &S, QualType FromType,
4719 Expr::Classification FromClassification,
4720 CXXMethodDecl *Method,
4721 CXXRecordDecl *ActingContext) {
4722 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
4723 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4724 // const volatile object.
4725 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4726 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
4727 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
4729 // Set up the conversion sequence as a "bad" conversion, to allow us
4731 ImplicitConversionSequence ICS;
4733 // We need to have an object of class type.
4734 if (const PointerType *PT = FromType->getAs<PointerType>()) {
4735 FromType = PT->getPointeeType();
4737 // When we had a pointer, it's implicitly dereferenced, so we
4738 // better have an lvalue.
4739 assert(FromClassification.isLValue());
4742 assert(FromType->isRecordType());
4744 // C++0x [over.match.funcs]p4:
4745 // For non-static member functions, the type of the implicit object
4748 // - "lvalue reference to cv X" for functions declared without a
4749 // ref-qualifier or with the & ref-qualifier
4750 // - "rvalue reference to cv X" for functions declared with the &&
4753 // where X is the class of which the function is a member and cv is the
4754 // cv-qualification on the member function declaration.
4756 // However, when finding an implicit conversion sequence for the argument, we
4757 // are not allowed to create temporaries or perform user-defined conversions
4758 // (C++ [over.match.funcs]p5). We perform a simplified version of
4759 // reference binding here, that allows class rvalues to bind to
4760 // non-constant references.
4762 // First check the qualifiers.
4763 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
4764 if (ImplicitParamType.getCVRQualifiers()
4765 != FromTypeCanon.getLocalCVRQualifiers() &&
4766 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
4767 ICS.setBad(BadConversionSequence::bad_qualifiers,
4768 FromType, ImplicitParamType);
4772 // Check that we have either the same type or a derived type. It
4773 // affects the conversion rank.
4774 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
4775 ImplicitConversionKind SecondKind;
4776 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4777 SecondKind = ICK_Identity;
4778 } else if (S.IsDerivedFrom(FromType, ClassType))
4779 SecondKind = ICK_Derived_To_Base;
4781 ICS.setBad(BadConversionSequence::unrelated_class,
4782 FromType, ImplicitParamType);
4786 // Check the ref-qualifier.
4787 switch (Method->getRefQualifier()) {
4789 // Do nothing; we don't care about lvalueness or rvalueness.
4793 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4794 // non-const lvalue reference cannot bind to an rvalue
4795 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
4802 if (!FromClassification.isRValue()) {
4803 // rvalue reference cannot bind to an lvalue
4804 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
4811 // Success. Mark this as a reference binding.
4813 ICS.Standard.setAsIdentityConversion();
4814 ICS.Standard.Second = SecondKind;
4815 ICS.Standard.setFromType(FromType);
4816 ICS.Standard.setAllToTypes(ImplicitParamType);
4817 ICS.Standard.ReferenceBinding = true;
4818 ICS.Standard.DirectBinding = true;
4819 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
4820 ICS.Standard.BindsToFunctionLvalue = false;
4821 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4822 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4823 = (Method->getRefQualifier() == RQ_None);
4827 /// PerformObjectArgumentInitialization - Perform initialization of
4828 /// the implicit object parameter for the given Method with the given
4831 Sema::PerformObjectArgumentInitialization(Expr *From,
4832 NestedNameSpecifier *Qualifier,
4833 NamedDecl *FoundDecl,
4834 CXXMethodDecl *Method) {
4835 QualType FromRecordType, DestType;
4836 QualType ImplicitParamRecordType =
4837 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
4839 Expr::Classification FromClassification;
4840 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
4841 FromRecordType = PT->getPointeeType();
4842 DestType = Method->getThisType(Context);
4843 FromClassification = Expr::Classification::makeSimpleLValue();
4845 FromRecordType = From->getType();
4846 DestType = ImplicitParamRecordType;
4847 FromClassification = From->Classify(Context);
4850 // Note that we always use the true parent context when performing
4851 // the actual argument initialization.
4852 ImplicitConversionSequence ICS
4853 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4854 Method, Method->getParent());
4856 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4857 Qualifiers FromQs = FromRecordType.getQualifiers();
4858 Qualifiers ToQs = DestType.getQualifiers();
4859 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4861 Diag(From->getLocStart(),
4862 diag::err_member_function_call_bad_cvr)
4863 << Method->getDeclName() << FromRecordType << (CVR - 1)
4864 << From->getSourceRange();
4865 Diag(Method->getLocation(), diag::note_previous_decl)
4866 << Method->getDeclName();
4871 return Diag(From->getLocStart(),
4872 diag::err_implicit_object_parameter_init)
4873 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
4876 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4877 ExprResult FromRes =
4878 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4879 if (FromRes.isInvalid())
4881 From = FromRes.get();
4884 if (!Context.hasSameType(From->getType(), DestType))
4885 From = ImpCastExprToType(From, DestType, CK_NoOp,
4886 From->getValueKind()).get();
4890 /// TryContextuallyConvertToBool - Attempt to contextually convert the
4891 /// expression From to bool (C++0x [conv]p3).
4892 static ImplicitConversionSequence
4893 TryContextuallyConvertToBool(Sema &S, Expr *From) {
4894 return TryImplicitConversion(S, From, S.Context.BoolTy,
4895 /*SuppressUserConversions=*/false,
4896 /*AllowExplicit=*/true,
4897 /*InOverloadResolution=*/false,
4899 /*AllowObjCWritebackConversion=*/false,
4900 /*AllowObjCConversionOnExplicit=*/false);
4903 /// PerformContextuallyConvertToBool - Perform a contextual conversion
4904 /// of the expression From to bool (C++0x [conv]p3).
4905 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
4906 if (checkPlaceholderForOverload(*this, From))
4909 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
4911 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
4913 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
4914 return Diag(From->getLocStart(),
4915 diag::err_typecheck_bool_condition)
4916 << From->getType() << From->getSourceRange();
4920 /// Check that the specified conversion is permitted in a converted constant
4921 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
4923 static bool CheckConvertedConstantConversions(Sema &S,
4924 StandardConversionSequence &SCS) {
4925 // Since we know that the target type is an integral or unscoped enumeration
4926 // type, most conversion kinds are impossible. All possible First and Third
4927 // conversions are fine.
4928 switch (SCS.Second) {
4930 case ICK_Integral_Promotion:
4931 case ICK_Integral_Conversion:
4932 case ICK_Zero_Event_Conversion:
4935 case ICK_Boolean_Conversion:
4936 // Conversion from an integral or unscoped enumeration type to bool is
4937 // classified as ICK_Boolean_Conversion, but it's also an integral
4938 // conversion, so it's permitted in a converted constant expression.
4939 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4940 SCS.getToType(2)->isBooleanType();
4942 case ICK_Floating_Integral:
4943 case ICK_Complex_Real:
4946 case ICK_Lvalue_To_Rvalue:
4947 case ICK_Array_To_Pointer:
4948 case ICK_Function_To_Pointer:
4949 case ICK_NoReturn_Adjustment:
4950 case ICK_Qualification:
4951 case ICK_Compatible_Conversion:
4952 case ICK_Vector_Conversion:
4953 case ICK_Vector_Splat:
4954 case ICK_Derived_To_Base:
4955 case ICK_Pointer_Conversion:
4956 case ICK_Pointer_Member:
4957 case ICK_Block_Pointer_Conversion:
4958 case ICK_Writeback_Conversion:
4959 case ICK_Floating_Promotion:
4960 case ICK_Complex_Promotion:
4961 case ICK_Complex_Conversion:
4962 case ICK_Floating_Conversion:
4963 case ICK_TransparentUnionConversion:
4964 llvm_unreachable("unexpected second conversion kind");
4966 case ICK_Num_Conversion_Kinds:
4970 llvm_unreachable("unknown conversion kind");
4973 /// CheckConvertedConstantExpression - Check that the expression From is a
4974 /// converted constant expression of type T, perform the conversion and produce
4975 /// the converted expression, per C++11 [expr.const]p3.
4976 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4977 llvm::APSInt &Value,
4979 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
4980 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4982 if (checkPlaceholderForOverload(*this, From))
4985 // C++11 [expr.const]p3 with proposed wording fixes:
4986 // A converted constant expression of type T is a core constant expression,
4987 // implicitly converted to a prvalue of type T, where the converted
4988 // expression is a literal constant expression and the implicit conversion
4989 // sequence contains only user-defined conversions, lvalue-to-rvalue
4990 // conversions, integral promotions, and integral conversions other than
4991 // narrowing conversions.
4992 ImplicitConversionSequence ICS =
4993 TryImplicitConversion(From, T,
4994 /*SuppressUserConversions=*/false,
4995 /*AllowExplicit=*/false,
4996 /*InOverloadResolution=*/false,
4998 /*AllowObjcWritebackConversion=*/false);
4999 StandardConversionSequence *SCS = nullptr;
5000 switch (ICS.getKind()) {
5001 case ImplicitConversionSequence::StandardConversion:
5002 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
5003 return Diag(From->getLocStart(),
5004 diag::err_typecheck_converted_constant_expression_disallowed)
5005 << From->getType() << From->getSourceRange() << T;
5006 SCS = &ICS.Standard;
5008 case ImplicitConversionSequence::UserDefinedConversion:
5009 // We are converting from class type to an integral or enumeration type, so
5010 // the Before sequence must be trivial.
5011 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
5012 return Diag(From->getLocStart(),
5013 diag::err_typecheck_converted_constant_expression_disallowed)
5014 << From->getType() << From->getSourceRange() << T;
5015 SCS = &ICS.UserDefined.After;
5017 case ImplicitConversionSequence::AmbiguousConversion:
5018 case ImplicitConversionSequence::BadConversion:
5019 if (!DiagnoseMultipleUserDefinedConversion(From, T))
5020 return Diag(From->getLocStart(),
5021 diag::err_typecheck_converted_constant_expression)
5022 << From->getType() << From->getSourceRange() << T;
5025 case ImplicitConversionSequence::EllipsisConversion:
5026 llvm_unreachable("ellipsis conversion in converted constant expression");
5029 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
5030 if (Result.isInvalid())
5033 // Check for a narrowing implicit conversion.
5034 APValue PreNarrowingValue;
5035 QualType PreNarrowingType;
5036 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
5037 PreNarrowingType)) {
5038 case NK_Variable_Narrowing:
5039 // Implicit conversion to a narrower type, and the value is not a constant
5040 // expression. We'll diagnose this in a moment.
5041 case NK_Not_Narrowing:
5044 case NK_Constant_Narrowing:
5045 Diag(From->getLocStart(), diag::ext_cce_narrowing)
5046 << CCE << /*Constant*/1
5047 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
5050 case NK_Type_Narrowing:
5051 Diag(From->getLocStart(), diag::ext_cce_narrowing)
5052 << CCE << /*Constant*/0 << From->getType() << T;
5056 // Check the expression is a constant expression.
5057 SmallVector<PartialDiagnosticAt, 8> Notes;
5058 Expr::EvalResult Eval;
5061 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
5062 // The expression can't be folded, so we can't keep it at this position in
5064 Result = ExprError();
5066 Value = Eval.Val.getInt();
5068 if (Notes.empty()) {
5069 // It's a constant expression.
5074 // It's not a constant expression. Produce an appropriate diagnostic.
5075 if (Notes.size() == 1 &&
5076 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5077 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5079 Diag(From->getLocStart(), diag::err_expr_not_cce)
5080 << CCE << From->getSourceRange();
5081 for (unsigned I = 0; I < Notes.size(); ++I)
5082 Diag(Notes[I].first, Notes[I].second);
5087 /// dropPointerConversions - If the given standard conversion sequence
5088 /// involves any pointer conversions, remove them. This may change
5089 /// the result type of the conversion sequence.
5090 static void dropPointerConversion(StandardConversionSequence &SCS) {
5091 if (SCS.Second == ICK_Pointer_Conversion) {
5092 SCS.Second = ICK_Identity;
5093 SCS.Third = ICK_Identity;
5094 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5098 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5099 /// convert the expression From to an Objective-C pointer type.
5100 static ImplicitConversionSequence
5101 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5102 // Do an implicit conversion to 'id'.
5103 QualType Ty = S.Context.getObjCIdType();
5104 ImplicitConversionSequence ICS
5105 = TryImplicitConversion(S, From, Ty,
5106 // FIXME: Are these flags correct?
5107 /*SuppressUserConversions=*/false,
5108 /*AllowExplicit=*/true,
5109 /*InOverloadResolution=*/false,
5111 /*AllowObjCWritebackConversion=*/false,
5112 /*AllowObjCConversionOnExplicit=*/true);
5114 // Strip off any final conversions to 'id'.
5115 switch (ICS.getKind()) {
5116 case ImplicitConversionSequence::BadConversion:
5117 case ImplicitConversionSequence::AmbiguousConversion:
5118 case ImplicitConversionSequence::EllipsisConversion:
5121 case ImplicitConversionSequence::UserDefinedConversion:
5122 dropPointerConversion(ICS.UserDefined.After);
5125 case ImplicitConversionSequence::StandardConversion:
5126 dropPointerConversion(ICS.Standard);
5133 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5134 /// conversion of the expression From to an Objective-C pointer type.
5135 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5136 if (checkPlaceholderForOverload(*this, From))
5139 QualType Ty = Context.getObjCIdType();
5140 ImplicitConversionSequence ICS =
5141 TryContextuallyConvertToObjCPointer(*this, From);
5143 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5147 /// Determine whether the provided type is an integral type, or an enumeration
5148 /// type of a permitted flavor.
5149 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5150 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5151 : T->isIntegralOrUnscopedEnumerationType();
5155 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5156 Sema::ContextualImplicitConverter &Converter,
5157 QualType T, UnresolvedSetImpl &ViableConversions) {
5159 if (Converter.Suppress)
5162 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5163 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5164 CXXConversionDecl *Conv =
5165 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5166 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5167 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5173 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5174 Sema::ContextualImplicitConverter &Converter,
5175 QualType T, bool HadMultipleCandidates,
5176 UnresolvedSetImpl &ExplicitConversions) {
5177 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5178 DeclAccessPair Found = ExplicitConversions[0];
5179 CXXConversionDecl *Conversion =
5180 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5182 // The user probably meant to invoke the given explicit
5183 // conversion; use it.
5184 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5185 std::string TypeStr;
5186 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5188 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5189 << FixItHint::CreateInsertion(From->getLocStart(),
5190 "static_cast<" + TypeStr + ">(")
5191 << FixItHint::CreateInsertion(
5192 SemaRef.getLocForEndOfToken(From->getLocEnd()), ")");
5193 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5195 // If we aren't in a SFINAE context, build a call to the
5196 // explicit conversion function.
5197 if (SemaRef.isSFINAEContext())
5200 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5201 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5202 HadMultipleCandidates);
5203 if (Result.isInvalid())
5205 // Record usage of conversion in an implicit cast.
5206 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5207 CK_UserDefinedConversion, Result.get(),
5208 nullptr, Result.get()->getValueKind());
5213 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5214 Sema::ContextualImplicitConverter &Converter,
5215 QualType T, bool HadMultipleCandidates,
5216 DeclAccessPair &Found) {
5217 CXXConversionDecl *Conversion =
5218 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5219 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5221 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5222 if (!Converter.SuppressConversion) {
5223 if (SemaRef.isSFINAEContext())
5226 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5227 << From->getSourceRange();
5230 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5231 HadMultipleCandidates);
5232 if (Result.isInvalid())
5234 // Record usage of conversion in an implicit cast.
5235 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5236 CK_UserDefinedConversion, Result.get(),
5237 nullptr, Result.get()->getValueKind());
5241 static ExprResult finishContextualImplicitConversion(
5242 Sema &SemaRef, SourceLocation Loc, Expr *From,
5243 Sema::ContextualImplicitConverter &Converter) {
5244 if (!Converter.match(From->getType()) && !Converter.Suppress)
5245 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5246 << From->getSourceRange();
5248 return SemaRef.DefaultLvalueConversion(From);
5252 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5253 UnresolvedSetImpl &ViableConversions,
5254 OverloadCandidateSet &CandidateSet) {
5255 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5256 DeclAccessPair FoundDecl = ViableConversions[I];
5257 NamedDecl *D = FoundDecl.getDecl();
5258 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5259 if (isa<UsingShadowDecl>(D))
5260 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5262 CXXConversionDecl *Conv;
5263 FunctionTemplateDecl *ConvTemplate;
5264 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5265 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5267 Conv = cast<CXXConversionDecl>(D);
5270 SemaRef.AddTemplateConversionCandidate(
5271 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5272 /*AllowObjCConversionOnExplicit=*/false);
5274 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5275 ToType, CandidateSet,
5276 /*AllowObjCConversionOnExplicit=*/false);
5280 /// \brief Attempt to convert the given expression to a type which is accepted
5281 /// by the given converter.
5283 /// This routine will attempt to convert an expression of class type to a
5284 /// type accepted by the specified converter. In C++11 and before, the class
5285 /// must have a single non-explicit conversion function converting to a matching
5286 /// type. In C++1y, there can be multiple such conversion functions, but only
5287 /// one target type.
5289 /// \param Loc The source location of the construct that requires the
5292 /// \param From The expression we're converting from.
5294 /// \param Converter Used to control and diagnose the conversion process.
5296 /// \returns The expression, converted to an integral or enumeration type if
5298 ExprResult Sema::PerformContextualImplicitConversion(
5299 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5300 // We can't perform any more checking for type-dependent expressions.
5301 if (From->isTypeDependent())
5304 // Process placeholders immediately.
5305 if (From->hasPlaceholderType()) {
5306 ExprResult result = CheckPlaceholderExpr(From);
5307 if (result.isInvalid())
5309 From = result.get();
5312 // If the expression already has a matching type, we're golden.
5313 QualType T = From->getType();
5314 if (Converter.match(T))
5315 return DefaultLvalueConversion(From);
5317 // FIXME: Check for missing '()' if T is a function type?
5319 // We can only perform contextual implicit conversions on objects of class
5321 const RecordType *RecordTy = T->getAs<RecordType>();
5322 if (!RecordTy || !getLangOpts().CPlusPlus) {
5323 if (!Converter.Suppress)
5324 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5328 // We must have a complete class type.
5329 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5330 ContextualImplicitConverter &Converter;
5333 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5334 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5336 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5337 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5339 } IncompleteDiagnoser(Converter, From);
5341 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
5344 // Look for a conversion to an integral or enumeration type.
5346 ViableConversions; // These are *potentially* viable in C++1y.
5347 UnresolvedSet<4> ExplicitConversions;
5348 std::pair<CXXRecordDecl::conversion_iterator,
5349 CXXRecordDecl::conversion_iterator> Conversions =
5350 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5352 bool HadMultipleCandidates =
5353 (std::distance(Conversions.first, Conversions.second) > 1);
5355 // To check that there is only one target type, in C++1y:
5357 bool HasUniqueTargetType = true;
5359 // Collect explicit or viable (potentially in C++1y) conversions.
5360 for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5361 E = Conversions.second;
5363 NamedDecl *D = (*I)->getUnderlyingDecl();
5364 CXXConversionDecl *Conversion;
5365 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5367 if (getLangOpts().CPlusPlus1y)
5368 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5370 continue; // C++11 does not consider conversion operator templates(?).
5372 Conversion = cast<CXXConversionDecl>(D);
5374 assert((!ConvTemplate || getLangOpts().CPlusPlus1y) &&
5375 "Conversion operator templates are considered potentially "
5378 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5379 if (Converter.match(CurToType) || ConvTemplate) {
5381 if (Conversion->isExplicit()) {
5382 // FIXME: For C++1y, do we need this restriction?
5383 // cf. diagnoseNoViableConversion()
5385 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5387 if (!ConvTemplate && getLangOpts().CPlusPlus1y) {
5388 if (ToType.isNull())
5389 ToType = CurToType.getUnqualifiedType();
5390 else if (HasUniqueTargetType &&
5391 (CurToType.getUnqualifiedType() != ToType))
5392 HasUniqueTargetType = false;
5394 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5399 if (getLangOpts().CPlusPlus1y) {
5401 // ... An expression e of class type E appearing in such a context
5402 // is said to be contextually implicitly converted to a specified
5403 // type T and is well-formed if and only if e can be implicitly
5404 // converted to a type T that is determined as follows: E is searched
5405 // for conversion functions whose return type is cv T or reference to
5406 // cv T such that T is allowed by the context. There shall be
5407 // exactly one such T.
5409 // If no unique T is found:
5410 if (ToType.isNull()) {
5411 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5412 HadMultipleCandidates,
5413 ExplicitConversions))
5415 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5418 // If more than one unique Ts are found:
5419 if (!HasUniqueTargetType)
5420 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5423 // If one unique T is found:
5424 // First, build a candidate set from the previously recorded
5425 // potentially viable conversions.
5426 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5427 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5430 // Then, perform overload resolution over the candidate set.
5431 OverloadCandidateSet::iterator Best;
5432 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5434 // Apply this conversion.
5435 DeclAccessPair Found =
5436 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5437 if (recordConversion(*this, Loc, From, Converter, T,
5438 HadMultipleCandidates, Found))
5443 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5445 case OR_No_Viable_Function:
5446 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5447 HadMultipleCandidates,
5448 ExplicitConversions))
5450 // fall through 'OR_Deleted' case.
5452 // We'll complain below about a non-integral condition type.
5456 switch (ViableConversions.size()) {
5458 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5459 HadMultipleCandidates,
5460 ExplicitConversions))
5463 // We'll complain below about a non-integral condition type.
5467 // Apply this conversion.
5468 DeclAccessPair Found = ViableConversions[0];
5469 if (recordConversion(*this, Loc, From, Converter, T,
5470 HadMultipleCandidates, Found))
5475 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5480 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5483 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5484 /// an acceptable non-member overloaded operator for a call whose
5485 /// arguments have types T1 (and, if non-empty, T2). This routine
5486 /// implements the check in C++ [over.match.oper]p3b2 concerning
5487 /// enumeration types.
5488 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5490 ArrayRef<Expr *> Args) {
5491 QualType T1 = Args[0]->getType();
5492 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5494 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5497 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5500 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5501 if (Proto->getNumParams() < 1)
5504 if (T1->isEnumeralType()) {
5505 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5506 if (Context.hasSameUnqualifiedType(T1, ArgType))
5510 if (Proto->getNumParams() < 2)
5513 if (!T2.isNull() && T2->isEnumeralType()) {
5514 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5515 if (Context.hasSameUnqualifiedType(T2, ArgType))
5522 /// AddOverloadCandidate - Adds the given function to the set of
5523 /// candidate functions, using the given function call arguments. If
5524 /// @p SuppressUserConversions, then don't allow user-defined
5525 /// conversions via constructors or conversion operators.
5527 /// \param PartialOverloading true if we are performing "partial" overloading
5528 /// based on an incomplete set of function arguments. This feature is used by
5529 /// code completion.
5531 Sema::AddOverloadCandidate(FunctionDecl *Function,
5532 DeclAccessPair FoundDecl,
5533 ArrayRef<Expr *> Args,
5534 OverloadCandidateSet &CandidateSet,
5535 bool SuppressUserConversions,
5536 bool PartialOverloading,
5537 bool AllowExplicit) {
5538 const FunctionProtoType *Proto
5539 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
5540 assert(Proto && "Functions without a prototype cannot be overloaded");
5541 assert(!Function->getDescribedFunctionTemplate() &&
5542 "Use AddTemplateOverloadCandidate for function templates");
5544 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
5545 if (!isa<CXXConstructorDecl>(Method)) {
5546 // If we get here, it's because we're calling a member function
5547 // that is named without a member access expression (e.g.,
5548 // "this->f") that was either written explicitly or created
5549 // implicitly. This can happen with a qualified call to a member
5550 // function, e.g., X::f(). We use an empty type for the implied
5551 // object argument (C++ [over.call.func]p3), and the acting context
5553 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
5554 QualType(), Expr::Classification::makeSimpleLValue(),
5555 Args, CandidateSet, SuppressUserConversions);
5558 // We treat a constructor like a non-member function, since its object
5559 // argument doesn't participate in overload resolution.
5562 if (!CandidateSet.isNewCandidate(Function))
5565 // C++ [over.match.oper]p3:
5566 // if no operand has a class type, only those non-member functions in the
5567 // lookup set that have a first parameter of type T1 or "reference to
5568 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
5569 // is a right operand) a second parameter of type T2 or "reference to
5570 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
5571 // candidate functions.
5572 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
5573 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
5576 // C++11 [class.copy]p11: [DR1402]
5577 // A defaulted move constructor that is defined as deleted is ignored by
5578 // overload resolution.
5579 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5580 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5581 Constructor->isMoveConstructor())
5584 // Overload resolution is always an unevaluated context.
5585 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5588 // C++ [class.copy]p3:
5589 // A member function template is never instantiated to perform the copy
5590 // of a class object to an object of its class type.
5591 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
5592 if (Args.size() == 1 &&
5593 Constructor->isSpecializationCopyingObject() &&
5594 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5595 IsDerivedFrom(Args[0]->getType(), ClassType)))
5599 // Add this candidate
5600 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
5601 Candidate.FoundDecl = FoundDecl;
5602 Candidate.Function = Function;
5603 Candidate.Viable = true;
5604 Candidate.IsSurrogate = false;
5605 Candidate.IgnoreObjectArgument = false;
5606 Candidate.ExplicitCallArguments = Args.size();
5608 unsigned NumParams = Proto->getNumParams();
5610 // (C++ 13.3.2p2): A candidate function having fewer than m
5611 // parameters is viable only if it has an ellipsis in its parameter
5613 if ((Args.size() + (PartialOverloading && Args.size())) > NumParams &&
5614 !Proto->isVariadic()) {
5615 Candidate.Viable = false;
5616 Candidate.FailureKind = ovl_fail_too_many_arguments;
5620 // (C++ 13.3.2p2): A candidate function having more than m parameters
5621 // is viable only if the (m+1)st parameter has a default argument
5622 // (8.3.6). For the purposes of overload resolution, the
5623 // parameter list is truncated on the right, so that there are
5624 // exactly m parameters.
5625 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
5626 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
5627 // Not enough arguments.
5628 Candidate.Viable = false;
5629 Candidate.FailureKind = ovl_fail_too_few_arguments;
5633 // (CUDA B.1): Check for invalid calls between targets.
5634 if (getLangOpts().CUDA)
5635 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5636 if (CheckCUDATarget(Caller, Function)) {
5637 Candidate.Viable = false;
5638 Candidate.FailureKind = ovl_fail_bad_target;
5642 // Determine the implicit conversion sequences for each of the
5644 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5645 if (ArgIdx < NumParams) {
5646 // (C++ 13.3.2p3): for F to be a viable function, there shall
5647 // exist for each argument an implicit conversion sequence
5648 // (13.3.3.1) that converts that argument to the corresponding
5650 QualType ParamType = Proto->getParamType(ArgIdx);
5651 Candidate.Conversions[ArgIdx]
5652 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5653 SuppressUserConversions,
5654 /*InOverloadResolution=*/true,
5655 /*AllowObjCWritebackConversion=*/
5656 getLangOpts().ObjCAutoRefCount,
5658 if (Candidate.Conversions[ArgIdx].isBad()) {
5659 Candidate.Viable = false;
5660 Candidate.FailureKind = ovl_fail_bad_conversion;
5664 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5665 // argument for which there is no corresponding parameter is
5666 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
5667 Candidate.Conversions[ArgIdx].setEllipsis();
5671 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5672 Candidate.Viable = false;
5673 Candidate.FailureKind = ovl_fail_enable_if;
5674 Candidate.DeductionFailure.Data = FailedAttr;
5679 static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5681 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5682 bool MissingImplicitThis) {
5683 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5684 // we need to find the first failing one.
5685 if (!Function->hasAttrs())
5687 AttrVec Attrs = Function->getAttrs();
5688 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5690 if (Attrs.begin() == E)
5692 std::reverse(Attrs.begin(), E);
5694 SFINAETrap Trap(*this);
5696 // Convert the arguments.
5697 SmallVector<Expr *, 16> ConvertedArgs;
5698 bool InitializationFailed = false;
5699 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5700 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
5701 !cast<CXXMethodDecl>(Function)->isStatic() &&
5702 !isa<CXXConstructorDecl>(Function)) {
5703 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5705 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
5707 if (R.isInvalid()) {
5708 InitializationFailed = true;
5711 ConvertedArgs.push_back(R.get());
5714 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5716 Function->getParamDecl(i)),
5719 if (R.isInvalid()) {
5720 InitializationFailed = true;
5723 ConvertedArgs.push_back(R.get());
5727 if (InitializationFailed || Trap.hasErrorOccurred())
5728 return cast<EnableIfAttr>(Attrs[0]);
5730 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5732 EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
5733 if (!EIA->getCond()->EvaluateWithSubstitution(
5734 Result, Context, Function,
5735 ArrayRef<const Expr*>(ConvertedArgs.data(),
5736 ConvertedArgs.size())) ||
5737 !Result.isInt() || !Result.getInt().getBoolValue()) {
5744 /// \brief Add all of the function declarations in the given function set to
5745 /// the overload candidate set.
5746 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
5747 ArrayRef<Expr *> Args,
5748 OverloadCandidateSet& CandidateSet,
5749 bool SuppressUserConversions,
5750 TemplateArgumentListInfo *ExplicitTemplateArgs) {
5751 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
5752 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5753 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5754 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
5755 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
5756 cast<CXXMethodDecl>(FD)->getParent(),
5757 Args[0]->getType(), Args[0]->Classify(Context),
5758 Args.slice(1), CandidateSet,
5759 SuppressUserConversions);
5761 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
5762 SuppressUserConversions);
5764 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
5765 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5766 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
5767 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
5768 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
5769 ExplicitTemplateArgs,
5771 Args[0]->Classify(Context), Args.slice(1),
5772 CandidateSet, SuppressUserConversions);
5774 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
5775 ExplicitTemplateArgs, Args,
5776 CandidateSet, SuppressUserConversions);
5781 /// AddMethodCandidate - Adds a named decl (which is some kind of
5782 /// method) as a method candidate to the given overload set.
5783 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
5784 QualType ObjectType,
5785 Expr::Classification ObjectClassification,
5786 ArrayRef<Expr *> Args,
5787 OverloadCandidateSet& CandidateSet,
5788 bool SuppressUserConversions) {
5789 NamedDecl *Decl = FoundDecl.getDecl();
5790 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
5792 if (isa<UsingShadowDecl>(Decl))
5793 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
5795 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5796 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5797 "Expected a member function template");
5798 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5799 /*ExplicitArgs*/ nullptr,
5800 ObjectType, ObjectClassification,
5802 SuppressUserConversions);
5804 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
5805 ObjectType, ObjectClassification,
5807 CandidateSet, SuppressUserConversions);
5811 /// AddMethodCandidate - Adds the given C++ member function to the set
5812 /// of candidate functions, using the given function call arguments
5813 /// and the object argument (@c Object). For example, in a call
5814 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5815 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5816 /// allow user-defined conversions via constructors or conversion
5819 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
5820 CXXRecordDecl *ActingContext, QualType ObjectType,
5821 Expr::Classification ObjectClassification,
5822 ArrayRef<Expr *> Args,
5823 OverloadCandidateSet &CandidateSet,
5824 bool SuppressUserConversions) {
5825 const FunctionProtoType *Proto
5826 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
5827 assert(Proto && "Methods without a prototype cannot be overloaded");
5828 assert(!isa<CXXConstructorDecl>(Method) &&
5829 "Use AddOverloadCandidate for constructors");
5831 if (!CandidateSet.isNewCandidate(Method))
5834 // C++11 [class.copy]p23: [DR1402]
5835 // A defaulted move assignment operator that is defined as deleted is
5836 // ignored by overload resolution.
5837 if (Method->isDefaulted() && Method->isDeleted() &&
5838 Method->isMoveAssignmentOperator())
5841 // Overload resolution is always an unevaluated context.
5842 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
5844 // Add this candidate
5845 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
5846 Candidate.FoundDecl = FoundDecl;
5847 Candidate.Function = Method;
5848 Candidate.IsSurrogate = false;
5849 Candidate.IgnoreObjectArgument = false;
5850 Candidate.ExplicitCallArguments = Args.size();
5852 unsigned NumParams = Proto->getNumParams();
5854 // (C++ 13.3.2p2): A candidate function having fewer than m
5855 // parameters is viable only if it has an ellipsis in its parameter
5857 if (Args.size() > NumParams && !Proto->isVariadic()) {
5858 Candidate.Viable = false;
5859 Candidate.FailureKind = ovl_fail_too_many_arguments;
5863 // (C++ 13.3.2p2): A candidate function having more than m parameters
5864 // is viable only if the (m+1)st parameter has a default argument
5865 // (8.3.6). For the purposes of overload resolution, the
5866 // parameter list is truncated on the right, so that there are
5867 // exactly m parameters.
5868 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
5869 if (Args.size() < MinRequiredArgs) {
5870 // Not enough arguments.
5871 Candidate.Viable = false;
5872 Candidate.FailureKind = ovl_fail_too_few_arguments;
5876 Candidate.Viable = true;
5878 if (Method->isStatic() || ObjectType.isNull())
5879 // The implicit object argument is ignored.
5880 Candidate.IgnoreObjectArgument = true;
5882 // Determine the implicit conversion sequence for the object
5884 Candidate.Conversions[0]
5885 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5886 Method, ActingContext);
5887 if (Candidate.Conversions[0].isBad()) {
5888 Candidate.Viable = false;
5889 Candidate.FailureKind = ovl_fail_bad_conversion;
5894 // Determine the implicit conversion sequences for each of the
5896 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
5897 if (ArgIdx < NumParams) {
5898 // (C++ 13.3.2p3): for F to be a viable function, there shall
5899 // exist for each argument an implicit conversion sequence
5900 // (13.3.3.1) that converts that argument to the corresponding
5902 QualType ParamType = Proto->getParamType(ArgIdx);
5903 Candidate.Conversions[ArgIdx + 1]
5904 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
5905 SuppressUserConversions,
5906 /*InOverloadResolution=*/true,
5907 /*AllowObjCWritebackConversion=*/
5908 getLangOpts().ObjCAutoRefCount);
5909 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
5910 Candidate.Viable = false;
5911 Candidate.FailureKind = ovl_fail_bad_conversion;
5915 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5916 // argument for which there is no corresponding parameter is
5917 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
5918 Candidate.Conversions[ArgIdx + 1].setEllipsis();
5922 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
5923 Candidate.Viable = false;
5924 Candidate.FailureKind = ovl_fail_enable_if;
5925 Candidate.DeductionFailure.Data = FailedAttr;
5930 /// \brief Add a C++ member function template as a candidate to the candidate
5931 /// set, using template argument deduction to produce an appropriate member
5932 /// function template specialization.
5934 Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
5935 DeclAccessPair FoundDecl,
5936 CXXRecordDecl *ActingContext,
5937 TemplateArgumentListInfo *ExplicitTemplateArgs,
5938 QualType ObjectType,
5939 Expr::Classification ObjectClassification,
5940 ArrayRef<Expr *> Args,
5941 OverloadCandidateSet& CandidateSet,
5942 bool SuppressUserConversions) {
5943 if (!CandidateSet.isNewCandidate(MethodTmpl))
5946 // C++ [over.match.funcs]p7:
5947 // In each case where a candidate is a function template, candidate
5948 // function template specializations are generated using template argument
5949 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
5950 // candidate functions in the usual way.113) A given name can refer to one
5951 // or more function templates and also to a set of overloaded non-template
5952 // functions. In such a case, the candidate functions generated from each
5953 // function template are combined with the set of non-template candidate
5955 TemplateDeductionInfo Info(CandidateSet.getLocation());
5956 FunctionDecl *Specialization = nullptr;
5957 if (TemplateDeductionResult Result
5958 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5959 Specialization, Info)) {
5960 OverloadCandidate &Candidate = CandidateSet.addCandidate();
5961 Candidate.FoundDecl = FoundDecl;
5962 Candidate.Function = MethodTmpl->getTemplatedDecl();
5963 Candidate.Viable = false;
5964 Candidate.FailureKind = ovl_fail_bad_deduction;
5965 Candidate.IsSurrogate = false;
5966 Candidate.IgnoreObjectArgument = false;
5967 Candidate.ExplicitCallArguments = Args.size();
5968 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
5973 // Add the function template specialization produced by template argument
5974 // deduction as a candidate.
5975 assert(Specialization && "Missing member function template specialization?");
5976 assert(isa<CXXMethodDecl>(Specialization) &&
5977 "Specialization is not a member function?");
5978 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
5979 ActingContext, ObjectType, ObjectClassification, Args,
5980 CandidateSet, SuppressUserConversions);
5983 /// \brief Add a C++ function template specialization as a candidate
5984 /// in the candidate set, using template argument deduction to produce
5985 /// an appropriate function template specialization.
5987 Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
5988 DeclAccessPair FoundDecl,
5989 TemplateArgumentListInfo *ExplicitTemplateArgs,
5990 ArrayRef<Expr *> Args,
5991 OverloadCandidateSet& CandidateSet,
5992 bool SuppressUserConversions) {
5993 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5996 // C++ [over.match.funcs]p7:
5997 // In each case where a candidate is a function template, candidate
5998 // function template specializations are generated using template argument
5999 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6000 // candidate functions in the usual way.113) A given name can refer to one
6001 // or more function templates and also to a set of overloaded non-template
6002 // functions. In such a case, the candidate functions generated from each
6003 // function template are combined with the set of non-template candidate
6005 TemplateDeductionInfo Info(CandidateSet.getLocation());
6006 FunctionDecl *Specialization = nullptr;
6007 if (TemplateDeductionResult Result
6008 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
6009 Specialization, Info)) {
6010 OverloadCandidate &Candidate = CandidateSet.addCandidate();
6011 Candidate.FoundDecl = FoundDecl;
6012 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6013 Candidate.Viable = false;
6014 Candidate.FailureKind = ovl_fail_bad_deduction;
6015 Candidate.IsSurrogate = false;
6016 Candidate.IgnoreObjectArgument = false;
6017 Candidate.ExplicitCallArguments = Args.size();
6018 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6023 // Add the function template specialization produced by template argument
6024 // deduction as a candidate.
6025 assert(Specialization && "Missing function template specialization?");
6026 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
6027 SuppressUserConversions);
6030 /// Determine whether this is an allowable conversion from the result
6031 /// of an explicit conversion operator to the expected type, per C++
6032 /// [over.match.conv]p1 and [over.match.ref]p1.
6034 /// \param ConvType The return type of the conversion function.
6036 /// \param ToType The type we are converting to.
6038 /// \param AllowObjCPointerConversion Allow a conversion from one
6039 /// Objective-C pointer to another.
6041 /// \returns true if the conversion is allowable, false otherwise.
6042 static bool isAllowableExplicitConversion(Sema &S,
6043 QualType ConvType, QualType ToType,
6044 bool AllowObjCPointerConversion) {
6045 QualType ToNonRefType = ToType.getNonReferenceType();
6047 // Easy case: the types are the same.
6048 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6051 // Allow qualification conversions.
6052 bool ObjCLifetimeConversion;
6053 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6054 ObjCLifetimeConversion))
6057 // If we're not allowed to consider Objective-C pointer conversions,
6059 if (!AllowObjCPointerConversion)
6062 // Is this an Objective-C pointer conversion?
6063 bool IncompatibleObjC = false;
6064 QualType ConvertedType;
6065 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6069 /// AddConversionCandidate - Add a C++ conversion function as a
6070 /// candidate in the candidate set (C++ [over.match.conv],
6071 /// C++ [over.match.copy]). From is the expression we're converting from,
6072 /// and ToType is the type that we're eventually trying to convert to
6073 /// (which may or may not be the same type as the type that the
6074 /// conversion function produces).
6076 Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
6077 DeclAccessPair FoundDecl,
6078 CXXRecordDecl *ActingContext,
6079 Expr *From, QualType ToType,
6080 OverloadCandidateSet& CandidateSet,
6081 bool AllowObjCConversionOnExplicit) {
6082 assert(!Conversion->getDescribedFunctionTemplate() &&
6083 "Conversion function templates use AddTemplateConversionCandidate");
6084 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6085 if (!CandidateSet.isNewCandidate(Conversion))
6088 // If the conversion function has an undeduced return type, trigger its
6090 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
6091 if (DeduceReturnType(Conversion, From->getExprLoc()))
6093 ConvType = Conversion->getConversionType().getNonReferenceType();
6096 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6097 // operator is only a candidate if its return type is the target type or
6098 // can be converted to the target type with a qualification conversion.
6099 if (Conversion->isExplicit() &&
6100 !isAllowableExplicitConversion(*this, ConvType, ToType,
6101 AllowObjCConversionOnExplicit))
6104 // Overload resolution is always an unevaluated context.
6105 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6107 // Add this candidate
6108 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6109 Candidate.FoundDecl = FoundDecl;
6110 Candidate.Function = Conversion;
6111 Candidate.IsSurrogate = false;
6112 Candidate.IgnoreObjectArgument = false;
6113 Candidate.FinalConversion.setAsIdentityConversion();
6114 Candidate.FinalConversion.setFromType(ConvType);
6115 Candidate.FinalConversion.setAllToTypes(ToType);
6116 Candidate.Viable = true;
6117 Candidate.ExplicitCallArguments = 1;
6119 // C++ [over.match.funcs]p4:
6120 // For conversion functions, the function is considered to be a member of
6121 // the class of the implicit implied object argument for the purpose of
6122 // defining the type of the implicit object parameter.
6124 // Determine the implicit conversion sequence for the implicit
6125 // object parameter.
6126 QualType ImplicitParamType = From->getType();
6127 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6128 ImplicitParamType = FromPtrType->getPointeeType();
6129 CXXRecordDecl *ConversionContext
6130 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
6132 Candidate.Conversions[0]
6133 = TryObjectArgumentInitialization(*this, From->getType(),
6134 From->Classify(Context),
6135 Conversion, ConversionContext);
6137 if (Candidate.Conversions[0].isBad()) {
6138 Candidate.Viable = false;
6139 Candidate.FailureKind = ovl_fail_bad_conversion;
6143 // We won't go through a user-defined type conversion function to convert a
6144 // derived to base as such conversions are given Conversion Rank. They only
6145 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6147 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6148 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6149 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6150 Candidate.Viable = false;
6151 Candidate.FailureKind = ovl_fail_trivial_conversion;
6155 // To determine what the conversion from the result of calling the
6156 // conversion function to the type we're eventually trying to
6157 // convert to (ToType), we need to synthesize a call to the
6158 // conversion function and attempt copy initialization from it. This
6159 // makes sure that we get the right semantics with respect to
6160 // lvalues/rvalues and the type. Fortunately, we can allocate this
6161 // call on the stack and we don't need its arguments to be
6163 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
6164 VK_LValue, From->getLocStart());
6165 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6166 Context.getPointerType(Conversion->getType()),
6167 CK_FunctionToPointerDecay,
6168 &ConversionRef, VK_RValue);
6170 QualType ConversionType = Conversion->getConversionType();
6171 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
6172 Candidate.Viable = false;
6173 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6177 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
6179 // Note that it is safe to allocate CallExpr on the stack here because
6180 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6182 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
6183 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
6184 From->getLocStart());
6185 ImplicitConversionSequence ICS =
6186 TryCopyInitialization(*this, &Call, ToType,
6187 /*SuppressUserConversions=*/true,
6188 /*InOverloadResolution=*/false,
6189 /*AllowObjCWritebackConversion=*/false);
6191 switch (ICS.getKind()) {
6192 case ImplicitConversionSequence::StandardConversion:
6193 Candidate.FinalConversion = ICS.Standard;
6195 // C++ [over.ics.user]p3:
6196 // If the user-defined conversion is specified by a specialization of a
6197 // conversion function template, the second standard conversion sequence
6198 // shall have exact match rank.
6199 if (Conversion->getPrimaryTemplate() &&
6200 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6201 Candidate.Viable = false;
6202 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
6206 // C++0x [dcl.init.ref]p5:
6207 // In the second case, if the reference is an rvalue reference and
6208 // the second standard conversion sequence of the user-defined
6209 // conversion sequence includes an lvalue-to-rvalue conversion, the
6210 // program is ill-formed.
6211 if (ToType->isRValueReferenceType() &&
6212 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6213 Candidate.Viable = false;
6214 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6219 case ImplicitConversionSequence::BadConversion:
6220 Candidate.Viable = false;
6221 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6226 "Can only end up with a standard conversion sequence or failure");
6229 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) {
6230 Candidate.Viable = false;
6231 Candidate.FailureKind = ovl_fail_enable_if;
6232 Candidate.DeductionFailure.Data = FailedAttr;
6237 /// \brief Adds a conversion function template specialization
6238 /// candidate to the overload set, using template argument deduction
6239 /// to deduce the template arguments of the conversion function
6240 /// template from the type that we are converting to (C++
6241 /// [temp.deduct.conv]).
6243 Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
6244 DeclAccessPair FoundDecl,
6245 CXXRecordDecl *ActingDC,
6246 Expr *From, QualType ToType,
6247 OverloadCandidateSet &CandidateSet,
6248 bool AllowObjCConversionOnExplicit) {
6249 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6250 "Only conversion function templates permitted here");
6252 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6255 TemplateDeductionInfo Info(CandidateSet.getLocation());
6256 CXXConversionDecl *Specialization = nullptr;
6257 if (TemplateDeductionResult Result
6258 = DeduceTemplateArguments(FunctionTemplate, ToType,
6259 Specialization, Info)) {
6260 OverloadCandidate &Candidate = CandidateSet.addCandidate();
6261 Candidate.FoundDecl = FoundDecl;
6262 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6263 Candidate.Viable = false;
6264 Candidate.FailureKind = ovl_fail_bad_deduction;
6265 Candidate.IsSurrogate = false;
6266 Candidate.IgnoreObjectArgument = false;
6267 Candidate.ExplicitCallArguments = 1;
6268 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6273 // Add the conversion function template specialization produced by
6274 // template argument deduction as a candidate.
6275 assert(Specialization && "Missing function template specialization?");
6276 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
6277 CandidateSet, AllowObjCConversionOnExplicit);
6280 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6281 /// converts the given @c Object to a function pointer via the
6282 /// conversion function @c Conversion, and then attempts to call it
6283 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
6284 /// the type of function that we'll eventually be calling.
6285 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
6286 DeclAccessPair FoundDecl,
6287 CXXRecordDecl *ActingContext,
6288 const FunctionProtoType *Proto,
6290 ArrayRef<Expr *> Args,
6291 OverloadCandidateSet& CandidateSet) {
6292 if (!CandidateSet.isNewCandidate(Conversion))
6295 // Overload resolution is always an unevaluated context.
6296 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6298 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
6299 Candidate.FoundDecl = FoundDecl;
6300 Candidate.Function = nullptr;
6301 Candidate.Surrogate = Conversion;
6302 Candidate.Viable = true;
6303 Candidate.IsSurrogate = true;
6304 Candidate.IgnoreObjectArgument = false;
6305 Candidate.ExplicitCallArguments = Args.size();
6307 // Determine the implicit conversion sequence for the implicit
6308 // object parameter.
6309 ImplicitConversionSequence ObjectInit
6310 = TryObjectArgumentInitialization(*this, Object->getType(),
6311 Object->Classify(Context),
6312 Conversion, ActingContext);
6313 if (ObjectInit.isBad()) {
6314 Candidate.Viable = false;
6315 Candidate.FailureKind = ovl_fail_bad_conversion;
6316 Candidate.Conversions[0] = ObjectInit;
6320 // The first conversion is actually a user-defined conversion whose
6321 // first conversion is ObjectInit's standard conversion (which is
6322 // effectively a reference binding). Record it as such.
6323 Candidate.Conversions[0].setUserDefined();
6324 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
6325 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
6326 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
6327 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
6328 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
6329 Candidate.Conversions[0].UserDefined.After
6330 = Candidate.Conversions[0].UserDefined.Before;
6331 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6334 unsigned NumParams = Proto->getNumParams();
6336 // (C++ 13.3.2p2): A candidate function having fewer than m
6337 // parameters is viable only if it has an ellipsis in its parameter
6339 if (Args.size() > NumParams && !Proto->isVariadic()) {
6340 Candidate.Viable = false;
6341 Candidate.FailureKind = ovl_fail_too_many_arguments;
6345 // Function types don't have any default arguments, so just check if
6346 // we have enough arguments.
6347 if (Args.size() < NumParams) {
6348 // Not enough arguments.
6349 Candidate.Viable = false;
6350 Candidate.FailureKind = ovl_fail_too_few_arguments;
6354 // Determine the implicit conversion sequences for each of the
6356 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6357 if (ArgIdx < NumParams) {
6358 // (C++ 13.3.2p3): for F to be a viable function, there shall
6359 // exist for each argument an implicit conversion sequence
6360 // (13.3.3.1) that converts that argument to the corresponding
6362 QualType ParamType = Proto->getParamType(ArgIdx);
6363 Candidate.Conversions[ArgIdx + 1]
6364 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6365 /*SuppressUserConversions=*/false,
6366 /*InOverloadResolution=*/false,
6367 /*AllowObjCWritebackConversion=*/
6368 getLangOpts().ObjCAutoRefCount);
6369 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6370 Candidate.Viable = false;
6371 Candidate.FailureKind = ovl_fail_bad_conversion;
6375 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6376 // argument for which there is no corresponding parameter is
6377 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6378 Candidate.Conversions[ArgIdx + 1].setEllipsis();
6382 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) {
6383 Candidate.Viable = false;
6384 Candidate.FailureKind = ovl_fail_enable_if;
6385 Candidate.DeductionFailure.Data = FailedAttr;
6390 /// \brief Add overload candidates for overloaded operators that are
6391 /// member functions.
6393 /// Add the overloaded operator candidates that are member functions
6394 /// for the operator Op that was used in an operator expression such
6395 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
6396 /// CandidateSet will store the added overload candidates. (C++
6397 /// [over.match.oper]).
6398 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6399 SourceLocation OpLoc,
6400 ArrayRef<Expr *> Args,
6401 OverloadCandidateSet& CandidateSet,
6402 SourceRange OpRange) {
6403 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6405 // C++ [over.match.oper]p3:
6406 // For a unary operator @ with an operand of a type whose
6407 // cv-unqualified version is T1, and for a binary operator @ with
6408 // a left operand of a type whose cv-unqualified version is T1 and
6409 // a right operand of a type whose cv-unqualified version is T2,
6410 // three sets of candidate functions, designated member
6411 // candidates, non-member candidates and built-in candidates, are
6412 // constructed as follows:
6413 QualType T1 = Args[0]->getType();
6415 // -- If T1 is a complete class type or a class currently being
6416 // defined, the set of member candidates is the result of the
6417 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6418 // the set of member candidates is empty.
6419 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
6420 // Complete the type if it can be completed.
6421 RequireCompleteType(OpLoc, T1, 0);
6422 // If the type is neither complete nor being defined, bail out now.
6423 if (!T1Rec->getDecl()->getDefinition())
6426 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6427 LookupQualifiedName(Operators, T1Rec->getDecl());
6428 Operators.suppressDiagnostics();
6430 for (LookupResult::iterator Oper = Operators.begin(),
6431 OperEnd = Operators.end();
6434 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
6435 Args[0]->Classify(Context),
6438 /* SuppressUserConversions = */ false);
6442 /// AddBuiltinCandidate - Add a candidate for a built-in
6443 /// operator. ResultTy and ParamTys are the result and parameter types
6444 /// of the built-in candidate, respectively. Args and NumArgs are the
6445 /// arguments being passed to the candidate. IsAssignmentOperator
6446 /// should be true when this built-in candidate is an assignment
6447 /// operator. NumContextualBoolArguments is the number of arguments
6448 /// (at the beginning of the argument list) that will be contextually
6449 /// converted to bool.
6450 void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
6451 ArrayRef<Expr *> Args,
6452 OverloadCandidateSet& CandidateSet,
6453 bool IsAssignmentOperator,
6454 unsigned NumContextualBoolArguments) {
6455 // Overload resolution is always an unevaluated context.
6456 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
6458 // Add this candidate
6459 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
6460 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
6461 Candidate.Function = nullptr;
6462 Candidate.IsSurrogate = false;
6463 Candidate.IgnoreObjectArgument = false;
6464 Candidate.BuiltinTypes.ResultTy = ResultTy;
6465 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
6466 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6468 // Determine the implicit conversion sequences for each of the
6470 Candidate.Viable = true;
6471 Candidate.ExplicitCallArguments = Args.size();
6472 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
6473 // C++ [over.match.oper]p4:
6474 // For the built-in assignment operators, conversions of the
6475 // left operand are restricted as follows:
6476 // -- no temporaries are introduced to hold the left operand, and
6477 // -- no user-defined conversions are applied to the left
6478 // operand to achieve a type match with the left-most
6479 // parameter of a built-in candidate.
6481 // We block these conversions by turning off user-defined
6482 // conversions, since that is the only way that initialization of
6483 // a reference to a non-class type can occur from something that
6484 // is not of the same type.
6485 if (ArgIdx < NumContextualBoolArguments) {
6486 assert(ParamTys[ArgIdx] == Context.BoolTy &&
6487 "Contextual conversion to bool requires bool type");
6488 Candidate.Conversions[ArgIdx]
6489 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
6491 Candidate.Conversions[ArgIdx]
6492 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
6493 ArgIdx == 0 && IsAssignmentOperator,
6494 /*InOverloadResolution=*/false,
6495 /*AllowObjCWritebackConversion=*/
6496 getLangOpts().ObjCAutoRefCount);
6498 if (Candidate.Conversions[ArgIdx].isBad()) {
6499 Candidate.Viable = false;
6500 Candidate.FailureKind = ovl_fail_bad_conversion;
6508 /// BuiltinCandidateTypeSet - A set of types that will be used for the
6509 /// candidate operator functions for built-in operators (C++
6510 /// [over.built]). The types are separated into pointer types and
6511 /// enumeration types.
6512 class BuiltinCandidateTypeSet {
6513 /// TypeSet - A set of types.
6514 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
6516 /// PointerTypes - The set of pointer types that will be used in the
6517 /// built-in candidates.
6518 TypeSet PointerTypes;
6520 /// MemberPointerTypes - The set of member pointer types that will be
6521 /// used in the built-in candidates.
6522 TypeSet MemberPointerTypes;
6524 /// EnumerationTypes - The set of enumeration types that will be
6525 /// used in the built-in candidates.
6526 TypeSet EnumerationTypes;
6528 /// \brief The set of vector types that will be used in the built-in
6530 TypeSet VectorTypes;
6532 /// \brief A flag indicating non-record types are viable candidates
6533 bool HasNonRecordTypes;
6535 /// \brief A flag indicating whether either arithmetic or enumeration types
6536 /// were present in the candidate set.
6537 bool HasArithmeticOrEnumeralTypes;
6539 /// \brief A flag indicating whether the nullptr type was present in the
6541 bool HasNullPtrType;
6543 /// Sema - The semantic analysis instance where we are building the
6544 /// candidate type set.
6547 /// Context - The AST context in which we will build the type sets.
6548 ASTContext &Context;
6550 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6551 const Qualifiers &VisibleQuals);
6552 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
6555 /// iterator - Iterates through the types that are part of the set.
6556 typedef TypeSet::iterator iterator;
6558 BuiltinCandidateTypeSet(Sema &SemaRef)
6559 : HasNonRecordTypes(false),
6560 HasArithmeticOrEnumeralTypes(false),
6561 HasNullPtrType(false),
6563 Context(SemaRef.Context) { }
6565 void AddTypesConvertedFrom(QualType Ty,
6567 bool AllowUserConversions,
6568 bool AllowExplicitConversions,
6569 const Qualifiers &VisibleTypeConversionsQuals);
6571 /// pointer_begin - First pointer type found;
6572 iterator pointer_begin() { return PointerTypes.begin(); }
6574 /// pointer_end - Past the last pointer type found;
6575 iterator pointer_end() { return PointerTypes.end(); }
6577 /// member_pointer_begin - First member pointer type found;
6578 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6580 /// member_pointer_end - Past the last member pointer type found;
6581 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6583 /// enumeration_begin - First enumeration type found;
6584 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6586 /// enumeration_end - Past the last enumeration type found;
6587 iterator enumeration_end() { return EnumerationTypes.end(); }
6589 iterator vector_begin() { return VectorTypes.begin(); }
6590 iterator vector_end() { return VectorTypes.end(); }
6592 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6593 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
6594 bool hasNullPtrType() const { return HasNullPtrType; }
6597 } // end anonymous namespace
6599 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
6600 /// the set of pointer types along with any more-qualified variants of
6601 /// that type. For example, if @p Ty is "int const *", this routine
6602 /// will add "int const *", "int const volatile *", "int const
6603 /// restrict *", and "int const volatile restrict *" to the set of
6604 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6605 /// false otherwise.
6607 /// FIXME: what to do about extended qualifiers?
6609 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6610 const Qualifiers &VisibleQuals) {
6612 // Insert this type.
6613 if (!PointerTypes.insert(Ty))
6617 const PointerType *PointerTy = Ty->getAs<PointerType>();
6618 bool buildObjCPtr = false;
6620 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6621 PointeeTy = PTy->getPointeeType();
6622 buildObjCPtr = true;
6624 PointeeTy = PointerTy->getPointeeType();
6627 // Don't add qualified variants of arrays. For one, they're not allowed
6628 // (the qualifier would sink to the element type), and for another, the
6629 // only overload situation where it matters is subscript or pointer +- int,
6630 // and those shouldn't have qualifier variants anyway.
6631 if (PointeeTy->isArrayType())
6634 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6635 bool hasVolatile = VisibleQuals.hasVolatile();
6636 bool hasRestrict = VisibleQuals.hasRestrict();
6638 // Iterate through all strict supersets of BaseCVR.
6639 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6640 if ((CVR | BaseCVR) != CVR) continue;
6641 // Skip over volatile if no volatile found anywhere in the types.
6642 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6644 // Skip over restrict if no restrict found anywhere in the types, or if
6645 // the type cannot be restrict-qualified.
6646 if ((CVR & Qualifiers::Restrict) &&
6648 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6651 // Build qualified pointee type.
6652 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6654 // Build qualified pointer type.
6655 QualType QPointerTy;
6657 QPointerTy = Context.getPointerType(QPointeeTy);
6659 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6661 // Insert qualified pointer type.
6662 PointerTypes.insert(QPointerTy);
6668 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6669 /// to the set of pointer types along with any more-qualified variants of
6670 /// that type. For example, if @p Ty is "int const *", this routine
6671 /// will add "int const *", "int const volatile *", "int const
6672 /// restrict *", and "int const volatile restrict *" to the set of
6673 /// pointer types. Returns true if the add of @p Ty itself succeeded,
6674 /// false otherwise.
6676 /// FIXME: what to do about extended qualifiers?
6678 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6680 // Insert this type.
6681 if (!MemberPointerTypes.insert(Ty))
6684 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6685 assert(PointerTy && "type was not a member pointer type!");
6687 QualType PointeeTy = PointerTy->getPointeeType();
6688 // Don't add qualified variants of arrays. For one, they're not allowed
6689 // (the qualifier would sink to the element type), and for another, the
6690 // only overload situation where it matters is subscript or pointer +- int,
6691 // and those shouldn't have qualifier variants anyway.
6692 if (PointeeTy->isArrayType())
6694 const Type *ClassTy = PointerTy->getClass();
6696 // Iterate through all strict supersets of the pointee type's CVR
6698 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6699 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6700 if ((CVR | BaseCVR) != CVR) continue;
6702 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
6703 MemberPointerTypes.insert(
6704 Context.getMemberPointerType(QPointeeTy, ClassTy));
6710 /// AddTypesConvertedFrom - Add each of the types to which the type @p
6711 /// Ty can be implicit converted to the given set of @p Types. We're
6712 /// primarily interested in pointer types and enumeration types. We also
6713 /// take member pointer types, for the conditional operator.
6714 /// AllowUserConversions is true if we should look at the conversion
6715 /// functions of a class type, and AllowExplicitConversions if we
6716 /// should also include the explicit conversion functions of a class
6719 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
6721 bool AllowUserConversions,
6722 bool AllowExplicitConversions,
6723 const Qualifiers &VisibleQuals) {
6724 // Only deal with canonical types.
6725 Ty = Context.getCanonicalType(Ty);
6727 // Look through reference types; they aren't part of the type of an
6728 // expression for the purposes of conversions.
6729 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
6730 Ty = RefTy->getPointeeType();
6732 // If we're dealing with an array type, decay to the pointer.
6733 if (Ty->isArrayType())
6734 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6736 // Otherwise, we don't care about qualifiers on the type.
6737 Ty = Ty.getLocalUnqualifiedType();
6739 // Flag if we ever add a non-record type.
6740 const RecordType *TyRec = Ty->getAs<RecordType>();
6741 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6743 // Flag if we encounter an arithmetic type.
6744 HasArithmeticOrEnumeralTypes =
6745 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6747 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6748 PointerTypes.insert(Ty);
6749 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
6750 // Insert our type, and its more-qualified variants, into the set
6752 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
6754 } else if (Ty->isMemberPointerType()) {
6755 // Member pointers are far easier, since the pointee can't be converted.
6756 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6758 } else if (Ty->isEnumeralType()) {
6759 HasArithmeticOrEnumeralTypes = true;
6760 EnumerationTypes.insert(Ty);
6761 } else if (Ty->isVectorType()) {
6762 // We treat vector types as arithmetic types in many contexts as an
6764 HasArithmeticOrEnumeralTypes = true;
6765 VectorTypes.insert(Ty);
6766 } else if (Ty->isNullPtrType()) {
6767 HasNullPtrType = true;
6768 } else if (AllowUserConversions && TyRec) {
6769 // No conversion functions in incomplete types.
6770 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6773 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6774 std::pair<CXXRecordDecl::conversion_iterator,
6775 CXXRecordDecl::conversion_iterator>
6776 Conversions = ClassDecl->getVisibleConversionFunctions();
6777 for (CXXRecordDecl::conversion_iterator
6778 I = Conversions.first, E = Conversions.second; I != E; ++I) {
6779 NamedDecl *D = I.getDecl();
6780 if (isa<UsingShadowDecl>(D))
6781 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6783 // Skip conversion function templates; they don't tell us anything
6784 // about which builtin types we can convert to.
6785 if (isa<FunctionTemplateDecl>(D))
6788 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6789 if (AllowExplicitConversions || !Conv->isExplicit()) {
6790 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6797 /// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6798 /// the volatile- and non-volatile-qualified assignment operators for the
6799 /// given type to the candidate set.
6800 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6802 ArrayRef<Expr *> Args,
6803 OverloadCandidateSet &CandidateSet) {
6804 QualType ParamTypes[2];
6806 // T& operator=(T&, T)
6807 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6809 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6810 /*IsAssignmentOperator=*/true);
6812 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6813 // volatile T& operator=(volatile T&, T)
6815 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
6817 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
6818 /*IsAssignmentOperator=*/true);
6822 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6823 /// if any, found in visible type conversion functions found in ArgExpr's type.
6824 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6826 const RecordType *TyRec;
6827 if (const MemberPointerType *RHSMPType =
6828 ArgExpr->getType()->getAs<MemberPointerType>())
6829 TyRec = RHSMPType->getClass()->getAs<RecordType>();
6831 TyRec = ArgExpr->getType()->getAs<RecordType>();
6833 // Just to be safe, assume the worst case.
6834 VRQuals.addVolatile();
6835 VRQuals.addRestrict();
6839 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6840 if (!ClassDecl->hasDefinition())
6843 std::pair<CXXRecordDecl::conversion_iterator,
6844 CXXRecordDecl::conversion_iterator>
6845 Conversions = ClassDecl->getVisibleConversionFunctions();
6847 for (CXXRecordDecl::conversion_iterator
6848 I = Conversions.first, E = Conversions.second; I != E; ++I) {
6849 NamedDecl *D = I.getDecl();
6850 if (isa<UsingShadowDecl>(D))
6851 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6852 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
6853 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6854 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6855 CanTy = ResTypeRef->getPointeeType();
6856 // Need to go down the pointer/mempointer chain and add qualifiers
6860 if (CanTy.isRestrictQualified())
6861 VRQuals.addRestrict();
6862 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6863 CanTy = ResTypePtr->getPointeeType();
6864 else if (const MemberPointerType *ResTypeMPtr =
6865 CanTy->getAs<MemberPointerType>())
6866 CanTy = ResTypeMPtr->getPointeeType();
6869 if (CanTy.isVolatileQualified())
6870 VRQuals.addVolatile();
6871 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6881 /// \brief Helper class to manage the addition of builtin operator overload
6882 /// candidates. It provides shared state and utility methods used throughout
6883 /// the process, as well as a helper method to add each group of builtin
6884 /// operator overloads from the standard to a candidate set.
6885 class BuiltinOperatorOverloadBuilder {
6886 // Common instance state available to all overload candidate addition methods.
6888 ArrayRef<Expr *> Args;
6889 Qualifiers VisibleTypeConversionsQuals;
6890 bool HasArithmeticOrEnumeralCandidateType;
6891 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
6892 OverloadCandidateSet &CandidateSet;
6894 // Define some constants used to index and iterate over the arithemetic types
6895 // provided via the getArithmeticType() method below.
6896 // The "promoted arithmetic types" are the arithmetic
6897 // types are that preserved by promotion (C++ [over.built]p2).
6898 static const unsigned FirstIntegralType = 3;
6899 static const unsigned LastIntegralType = 20;
6900 static const unsigned FirstPromotedIntegralType = 3,
6901 LastPromotedIntegralType = 11;
6902 static const unsigned FirstPromotedArithmeticType = 0,
6903 LastPromotedArithmeticType = 11;
6904 static const unsigned NumArithmeticTypes = 20;
6906 /// \brief Get the canonical type for a given arithmetic type index.
6907 CanQualType getArithmeticType(unsigned index) {
6908 assert(index < NumArithmeticTypes);
6909 static CanQualType ASTContext::* const
6910 ArithmeticTypes[NumArithmeticTypes] = {
6911 // Start of promoted types.
6912 &ASTContext::FloatTy,
6913 &ASTContext::DoubleTy,
6914 &ASTContext::LongDoubleTy,
6916 // Start of integral types.
6918 &ASTContext::LongTy,
6919 &ASTContext::LongLongTy,
6920 &ASTContext::Int128Ty,
6921 &ASTContext::UnsignedIntTy,
6922 &ASTContext::UnsignedLongTy,
6923 &ASTContext::UnsignedLongLongTy,
6924 &ASTContext::UnsignedInt128Ty,
6925 // End of promoted types.
6927 &ASTContext::BoolTy,
6928 &ASTContext::CharTy,
6929 &ASTContext::WCharTy,
6930 &ASTContext::Char16Ty,
6931 &ASTContext::Char32Ty,
6932 &ASTContext::SignedCharTy,
6933 &ASTContext::ShortTy,
6934 &ASTContext::UnsignedCharTy,
6935 &ASTContext::UnsignedShortTy,
6936 // End of integral types.
6937 // FIXME: What about complex? What about half?
6939 return S.Context.*ArithmeticTypes[index];
6942 /// \brief Gets the canonical type resulting from the usual arithemetic
6943 /// converions for the given arithmetic types.
6944 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6945 // Accelerator table for performing the usual arithmetic conversions.
6946 // The rules are basically:
6947 // - if either is floating-point, use the wider floating-point
6948 // - if same signedness, use the higher rank
6949 // - if same size, use unsigned of the higher rank
6950 // - use the larger type
6951 // These rules, together with the axiom that higher ranks are
6952 // never smaller, are sufficient to precompute all of these results
6953 // *except* when dealing with signed types of higher rank.
6954 // (we could precompute SLL x UI for all known platforms, but it's
6955 // better not to make any assumptions).
6956 // We assume that int128 has a higher rank than long long on all platforms.
6959 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
6961 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
6962 [LastPromotedArithmeticType] = {
6963 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6964 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6965 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6966 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6967 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6968 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6969 /*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6970 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6971 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6972 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6973 /*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
6976 assert(L < LastPromotedArithmeticType);
6977 assert(R < LastPromotedArithmeticType);
6978 int Idx = ConversionsTable[L][R];
6980 // Fast path: the table gives us a concrete answer.
6981 if (Idx != Dep) return getArithmeticType(Idx);
6983 // Slow path: we need to compare widths.
6984 // An invariant is that the signed type has higher rank.
6985 CanQualType LT = getArithmeticType(L),
6986 RT = getArithmeticType(R);
6987 unsigned LW = S.Context.getIntWidth(LT),
6988 RW = S.Context.getIntWidth(RT);
6990 // If they're different widths, use the signed type.
6991 if (LW > RW) return LT;
6992 else if (LW < RW) return RT;
6994 // Otherwise, use the unsigned type of the signed type's rank.
6995 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6996 assert(L == SLL || R == SLL);
6997 return S.Context.UnsignedLongLongTy;
7000 /// \brief Helper method to factor out the common pattern of adding overloads
7001 /// for '++' and '--' builtin operators.
7002 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7005 QualType ParamTypes[2] = {
7006 S.Context.getLValueReferenceType(CandidateTy),
7010 // Non-volatile version.
7011 if (Args.size() == 1)
7012 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7014 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7016 // Use a heuristic to reduce number of builtin candidates in the set:
7017 // add volatile version only if there are conversions to a volatile type.
7020 S.Context.getLValueReferenceType(
7021 S.Context.getVolatileType(CandidateTy));
7022 if (Args.size() == 1)
7023 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7025 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7028 // Add restrict version only if there are conversions to a restrict type
7029 // and our candidate type is a non-restrict-qualified pointer.
7030 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7031 !CandidateTy.isRestrictQualified()) {
7033 = S.Context.getLValueReferenceType(
7034 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7035 if (Args.size() == 1)
7036 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7038 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7042 = S.Context.getLValueReferenceType(
7043 S.Context.getCVRQualifiedType(CandidateTy,
7044 (Qualifiers::Volatile |
7045 Qualifiers::Restrict)));
7046 if (Args.size() == 1)
7047 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7049 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
7056 BuiltinOperatorOverloadBuilder(
7057 Sema &S, ArrayRef<Expr *> Args,
7058 Qualifiers VisibleTypeConversionsQuals,
7059 bool HasArithmeticOrEnumeralCandidateType,
7060 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7061 OverloadCandidateSet &CandidateSet)
7063 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7064 HasArithmeticOrEnumeralCandidateType(
7065 HasArithmeticOrEnumeralCandidateType),
7066 CandidateTypes(CandidateTypes),
7067 CandidateSet(CandidateSet) {
7068 // Validate some of our static helper constants in debug builds.
7069 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
7070 "Invalid first promoted integral type");
7071 assert(getArithmeticType(LastPromotedIntegralType - 1)
7072 == S.Context.UnsignedInt128Ty &&
7073 "Invalid last promoted integral type");
7074 assert(getArithmeticType(FirstPromotedArithmeticType)
7075 == S.Context.FloatTy &&
7076 "Invalid first promoted arithmetic type");
7077 assert(getArithmeticType(LastPromotedArithmeticType - 1)
7078 == S.Context.UnsignedInt128Ty &&
7079 "Invalid last promoted arithmetic type");
7082 // C++ [over.built]p3:
7084 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7085 // is either volatile or empty, there exist candidate operator
7086 // functions of the form
7088 // VQ T& operator++(VQ T&);
7089 // T operator++(VQ T&, int);
7091 // C++ [over.built]p4:
7093 // For every pair (T, VQ), where T is an arithmetic type other
7094 // than bool, and VQ is either volatile or empty, there exist
7095 // candidate operator functions of the form
7097 // VQ T& operator--(VQ T&);
7098 // T operator--(VQ T&, int);
7099 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7100 if (!HasArithmeticOrEnumeralCandidateType)
7103 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7104 Arith < NumArithmeticTypes; ++Arith) {
7105 addPlusPlusMinusMinusStyleOverloads(
7106 getArithmeticType(Arith),
7107 VisibleTypeConversionsQuals.hasVolatile(),
7108 VisibleTypeConversionsQuals.hasRestrict());
7112 // C++ [over.built]p5:
7114 // For every pair (T, VQ), where T is a cv-qualified or
7115 // cv-unqualified object type, and VQ is either volatile or
7116 // empty, there exist candidate operator functions of the form
7118 // T*VQ& operator++(T*VQ&);
7119 // T*VQ& operator--(T*VQ&);
7120 // T* operator++(T*VQ&, int);
7121 // T* operator--(T*VQ&, int);
7122 void addPlusPlusMinusMinusPointerOverloads() {
7123 for (BuiltinCandidateTypeSet::iterator
7124 Ptr = CandidateTypes[0].pointer_begin(),
7125 PtrEnd = CandidateTypes[0].pointer_end();
7126 Ptr != PtrEnd; ++Ptr) {
7127 // Skip pointer types that aren't pointers to object types.
7128 if (!(*Ptr)->getPointeeType()->isObjectType())
7131 addPlusPlusMinusMinusStyleOverloads(*Ptr,
7132 (!(*Ptr).isVolatileQualified() &&
7133 VisibleTypeConversionsQuals.hasVolatile()),
7134 (!(*Ptr).isRestrictQualified() &&
7135 VisibleTypeConversionsQuals.hasRestrict()));
7139 // C++ [over.built]p6:
7140 // For every cv-qualified or cv-unqualified object type T, there
7141 // exist candidate operator functions of the form
7143 // T& operator*(T*);
7145 // C++ [over.built]p7:
7146 // For every function type T that does not have cv-qualifiers or a
7147 // ref-qualifier, there exist candidate operator functions of the form
7148 // T& operator*(T*);
7149 void addUnaryStarPointerOverloads() {
7150 for (BuiltinCandidateTypeSet::iterator
7151 Ptr = CandidateTypes[0].pointer_begin(),
7152 PtrEnd = CandidateTypes[0].pointer_end();
7153 Ptr != PtrEnd; ++Ptr) {
7154 QualType ParamTy = *Ptr;
7155 QualType PointeeTy = ParamTy->getPointeeType();
7156 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7159 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7160 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7163 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
7164 &ParamTy, Args, CandidateSet);
7168 // C++ [over.built]p9:
7169 // For every promoted arithmetic type T, there exist candidate
7170 // operator functions of the form
7174 void addUnaryPlusOrMinusArithmeticOverloads() {
7175 if (!HasArithmeticOrEnumeralCandidateType)
7178 for (unsigned Arith = FirstPromotedArithmeticType;
7179 Arith < LastPromotedArithmeticType; ++Arith) {
7180 QualType ArithTy = getArithmeticType(Arith);
7181 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
7184 // Extension: We also add these operators for vector types.
7185 for (BuiltinCandidateTypeSet::iterator
7186 Vec = CandidateTypes[0].vector_begin(),
7187 VecEnd = CandidateTypes[0].vector_end();
7188 Vec != VecEnd; ++Vec) {
7189 QualType VecTy = *Vec;
7190 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7194 // C++ [over.built]p8:
7195 // For every type T, there exist candidate operator functions of
7198 // T* operator+(T*);
7199 void addUnaryPlusPointerOverloads() {
7200 for (BuiltinCandidateTypeSet::iterator
7201 Ptr = CandidateTypes[0].pointer_begin(),
7202 PtrEnd = CandidateTypes[0].pointer_end();
7203 Ptr != PtrEnd; ++Ptr) {
7204 QualType ParamTy = *Ptr;
7205 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
7209 // C++ [over.built]p10:
7210 // For every promoted integral type T, there exist candidate
7211 // operator functions of the form
7214 void addUnaryTildePromotedIntegralOverloads() {
7215 if (!HasArithmeticOrEnumeralCandidateType)
7218 for (unsigned Int = FirstPromotedIntegralType;
7219 Int < LastPromotedIntegralType; ++Int) {
7220 QualType IntTy = getArithmeticType(Int);
7221 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
7224 // Extension: We also add this operator for vector types.
7225 for (BuiltinCandidateTypeSet::iterator
7226 Vec = CandidateTypes[0].vector_begin(),
7227 VecEnd = CandidateTypes[0].vector_end();
7228 Vec != VecEnd; ++Vec) {
7229 QualType VecTy = *Vec;
7230 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
7234 // C++ [over.match.oper]p16:
7235 // For every pointer to member type T, there exist candidate operator
7236 // functions of the form
7238 // bool operator==(T,T);
7239 // bool operator!=(T,T);
7240 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7241 /// Set of (canonical) types that we've already handled.
7242 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7244 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7245 for (BuiltinCandidateTypeSet::iterator
7246 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7247 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7248 MemPtr != MemPtrEnd;
7250 // Don't add the same builtin candidate twice.
7251 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7254 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7255 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7260 // C++ [over.built]p15:
7262 // For every T, where T is an enumeration type, a pointer type, or
7263 // std::nullptr_t, there exist candidate operator functions of the form
7265 // bool operator<(T, T);
7266 // bool operator>(T, T);
7267 // bool operator<=(T, T);
7268 // bool operator>=(T, T);
7269 // bool operator==(T, T);
7270 // bool operator!=(T, T);
7271 void addRelationalPointerOrEnumeralOverloads() {
7272 // C++ [over.match.oper]p3:
7273 // [...]the built-in candidates include all of the candidate operator
7274 // functions defined in 13.6 that, compared to the given operator, [...]
7275 // do not have the same parameter-type-list as any non-template non-member
7278 // Note that in practice, this only affects enumeration types because there
7279 // aren't any built-in candidates of record type, and a user-defined operator
7280 // must have an operand of record or enumeration type. Also, the only other
7281 // overloaded operator with enumeration arguments, operator=,
7282 // cannot be overloaded for enumeration types, so this is the only place
7283 // where we must suppress candidates like this.
7284 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7285 UserDefinedBinaryOperators;
7287 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7288 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7289 CandidateTypes[ArgIdx].enumeration_end()) {
7290 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7291 CEnd = CandidateSet.end();
7293 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7296 if (C->Function->isFunctionTemplateSpecialization())
7299 QualType FirstParamType =
7300 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7301 QualType SecondParamType =
7302 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7304 // Skip if either parameter isn't of enumeral type.
7305 if (!FirstParamType->isEnumeralType() ||
7306 !SecondParamType->isEnumeralType())
7309 // Add this operator to the set of known user-defined operators.
7310 UserDefinedBinaryOperators.insert(
7311 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7312 S.Context.getCanonicalType(SecondParamType)));
7317 /// Set of (canonical) types that we've already handled.
7318 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7320 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7321 for (BuiltinCandidateTypeSet::iterator
7322 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7323 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7324 Ptr != PtrEnd; ++Ptr) {
7325 // Don't add the same builtin candidate twice.
7326 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7329 QualType ParamTypes[2] = { *Ptr, *Ptr };
7330 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7332 for (BuiltinCandidateTypeSet::iterator
7333 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7334 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7335 Enum != EnumEnd; ++Enum) {
7336 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7338 // Don't add the same builtin candidate twice, or if a user defined
7339 // candidate exists.
7340 if (!AddedTypes.insert(CanonType) ||
7341 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7345 QualType ParamTypes[2] = { *Enum, *Enum };
7346 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
7349 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7350 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7351 if (AddedTypes.insert(NullPtrTy) &&
7352 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
7354 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
7355 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
7362 // C++ [over.built]p13:
7364 // For every cv-qualified or cv-unqualified object type T
7365 // there exist candidate operator functions of the form
7367 // T* operator+(T*, ptrdiff_t);
7368 // T& operator[](T*, ptrdiff_t); [BELOW]
7369 // T* operator-(T*, ptrdiff_t);
7370 // T* operator+(ptrdiff_t, T*);
7371 // T& operator[](ptrdiff_t, T*); [BELOW]
7373 // C++ [over.built]p14:
7375 // For every T, where T is a pointer to object type, there
7376 // exist candidate operator functions of the form
7378 // ptrdiff_t operator-(T, T);
7379 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7380 /// Set of (canonical) types that we've already handled.
7381 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7383 for (int Arg = 0; Arg < 2; ++Arg) {
7384 QualType AsymetricParamTypes[2] = {
7385 S.Context.getPointerDiffType(),
7386 S.Context.getPointerDiffType(),
7388 for (BuiltinCandidateTypeSet::iterator
7389 Ptr = CandidateTypes[Arg].pointer_begin(),
7390 PtrEnd = CandidateTypes[Arg].pointer_end();
7391 Ptr != PtrEnd; ++Ptr) {
7392 QualType PointeeTy = (*Ptr)->getPointeeType();
7393 if (!PointeeTy->isObjectType())
7396 AsymetricParamTypes[Arg] = *Ptr;
7397 if (Arg == 0 || Op == OO_Plus) {
7398 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7399 // T* operator+(ptrdiff_t, T*);
7400 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
7402 if (Op == OO_Minus) {
7403 // ptrdiff_t operator-(T, T);
7404 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7407 QualType ParamTypes[2] = { *Ptr, *Ptr };
7408 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
7409 Args, CandidateSet);
7415 // C++ [over.built]p12:
7417 // For every pair of promoted arithmetic types L and R, there
7418 // exist candidate operator functions of the form
7420 // LR operator*(L, R);
7421 // LR operator/(L, R);
7422 // LR operator+(L, R);
7423 // LR operator-(L, R);
7424 // bool operator<(L, R);
7425 // bool operator>(L, R);
7426 // bool operator<=(L, R);
7427 // bool operator>=(L, R);
7428 // bool operator==(L, R);
7429 // bool operator!=(L, R);
7431 // where LR is the result of the usual arithmetic conversions
7432 // between types L and R.
7434 // C++ [over.built]p24:
7436 // For every pair of promoted arithmetic types L and R, there exist
7437 // candidate operator functions of the form
7439 // LR operator?(bool, L, R);
7441 // where LR is the result of the usual arithmetic conversions
7442 // between types L and R.
7443 // Our candidates ignore the first parameter.
7444 void addGenericBinaryArithmeticOverloads(bool isComparison) {
7445 if (!HasArithmeticOrEnumeralCandidateType)
7448 for (unsigned Left = FirstPromotedArithmeticType;
7449 Left < LastPromotedArithmeticType; ++Left) {
7450 for (unsigned Right = FirstPromotedArithmeticType;
7451 Right < LastPromotedArithmeticType; ++Right) {
7452 QualType LandR[2] = { getArithmeticType(Left),
7453 getArithmeticType(Right) };
7455 isComparison ? S.Context.BoolTy
7456 : getUsualArithmeticConversions(Left, Right);
7457 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7461 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7462 // conditional operator for vector types.
7463 for (BuiltinCandidateTypeSet::iterator
7464 Vec1 = CandidateTypes[0].vector_begin(),
7465 Vec1End = CandidateTypes[0].vector_end();
7466 Vec1 != Vec1End; ++Vec1) {
7467 for (BuiltinCandidateTypeSet::iterator
7468 Vec2 = CandidateTypes[1].vector_begin(),
7469 Vec2End = CandidateTypes[1].vector_end();
7470 Vec2 != Vec2End; ++Vec2) {
7471 QualType LandR[2] = { *Vec1, *Vec2 };
7472 QualType Result = S.Context.BoolTy;
7473 if (!isComparison) {
7474 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7480 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7485 // C++ [over.built]p17:
7487 // For every pair of promoted integral types L and R, there
7488 // exist candidate operator functions of the form
7490 // LR operator%(L, R);
7491 // LR operator&(L, R);
7492 // LR operator^(L, R);
7493 // LR operator|(L, R);
7494 // L operator<<(L, R);
7495 // L operator>>(L, R);
7497 // where LR is the result of the usual arithmetic conversions
7498 // between types L and R.
7499 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
7500 if (!HasArithmeticOrEnumeralCandidateType)
7503 for (unsigned Left = FirstPromotedIntegralType;
7504 Left < LastPromotedIntegralType; ++Left) {
7505 for (unsigned Right = FirstPromotedIntegralType;
7506 Right < LastPromotedIntegralType; ++Right) {
7507 QualType LandR[2] = { getArithmeticType(Left),
7508 getArithmeticType(Right) };
7509 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7511 : getUsualArithmeticConversions(Left, Right);
7512 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
7517 // C++ [over.built]p20:
7519 // For every pair (T, VQ), where T is an enumeration or
7520 // pointer to member type and VQ is either volatile or
7521 // empty, there exist candidate operator functions of the form
7523 // VQ T& operator=(VQ T&, T);
7524 void addAssignmentMemberPointerOrEnumeralOverloads() {
7525 /// Set of (canonical) types that we've already handled.
7526 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7528 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7529 for (BuiltinCandidateTypeSet::iterator
7530 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7531 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7532 Enum != EnumEnd; ++Enum) {
7533 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7536 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
7539 for (BuiltinCandidateTypeSet::iterator
7540 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7541 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7542 MemPtr != MemPtrEnd; ++MemPtr) {
7543 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7546 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
7551 // C++ [over.built]p19:
7553 // For every pair (T, VQ), where T is any type and VQ is either
7554 // volatile or empty, there exist candidate operator functions
7557 // T*VQ& operator=(T*VQ&, T*);
7559 // C++ [over.built]p21:
7561 // For every pair (T, VQ), where T is a cv-qualified or
7562 // cv-unqualified object type and VQ is either volatile or
7563 // empty, there exist candidate operator functions of the form
7565 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7566 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7567 void addAssignmentPointerOverloads(bool isEqualOp) {
7568 /// Set of (canonical) types that we've already handled.
7569 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7571 for (BuiltinCandidateTypeSet::iterator
7572 Ptr = CandidateTypes[0].pointer_begin(),
7573 PtrEnd = CandidateTypes[0].pointer_end();
7574 Ptr != PtrEnd; ++Ptr) {
7575 // If this is operator=, keep track of the builtin candidates we added.
7577 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
7578 else if (!(*Ptr)->getPointeeType()->isObjectType())
7581 // non-volatile version
7582 QualType ParamTypes[2] = {
7583 S.Context.getLValueReferenceType(*Ptr),
7584 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7586 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7587 /*IsAssigmentOperator=*/ isEqualOp);
7589 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7590 VisibleTypeConversionsQuals.hasVolatile();
7594 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7595 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7596 /*IsAssigmentOperator=*/isEqualOp);
7599 if (!(*Ptr).isRestrictQualified() &&
7600 VisibleTypeConversionsQuals.hasRestrict()) {
7603 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7604 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7605 /*IsAssigmentOperator=*/isEqualOp);
7608 // volatile restrict version
7610 = S.Context.getLValueReferenceType(
7611 S.Context.getCVRQualifiedType(*Ptr,
7612 (Qualifiers::Volatile |
7613 Qualifiers::Restrict)));
7614 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7615 /*IsAssigmentOperator=*/isEqualOp);
7621 for (BuiltinCandidateTypeSet::iterator
7622 Ptr = CandidateTypes[1].pointer_begin(),
7623 PtrEnd = CandidateTypes[1].pointer_end();
7624 Ptr != PtrEnd; ++Ptr) {
7625 // Make sure we don't add the same candidate twice.
7626 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7629 QualType ParamTypes[2] = {
7630 S.Context.getLValueReferenceType(*Ptr),
7634 // non-volatile version
7635 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7636 /*IsAssigmentOperator=*/true);
7638 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7639 VisibleTypeConversionsQuals.hasVolatile();
7643 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7644 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7645 /*IsAssigmentOperator=*/true);
7648 if (!(*Ptr).isRestrictQualified() &&
7649 VisibleTypeConversionsQuals.hasRestrict()) {
7652 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7653 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7654 /*IsAssigmentOperator=*/true);
7657 // volatile restrict version
7659 = S.Context.getLValueReferenceType(
7660 S.Context.getCVRQualifiedType(*Ptr,
7661 (Qualifiers::Volatile |
7662 Qualifiers::Restrict)));
7663 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7664 /*IsAssigmentOperator=*/true);
7671 // C++ [over.built]p18:
7673 // For every triple (L, VQ, R), where L is an arithmetic type,
7674 // VQ is either volatile or empty, and R is a promoted
7675 // arithmetic type, there exist candidate operator functions of
7678 // VQ L& operator=(VQ L&, R);
7679 // VQ L& operator*=(VQ L&, R);
7680 // VQ L& operator/=(VQ L&, R);
7681 // VQ L& operator+=(VQ L&, R);
7682 // VQ L& operator-=(VQ L&, R);
7683 void addAssignmentArithmeticOverloads(bool isEqualOp) {
7684 if (!HasArithmeticOrEnumeralCandidateType)
7687 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7688 for (unsigned Right = FirstPromotedArithmeticType;
7689 Right < LastPromotedArithmeticType; ++Right) {
7690 QualType ParamTypes[2];
7691 ParamTypes[1] = getArithmeticType(Right);
7693 // Add this built-in operator as a candidate (VQ is empty).
7695 S.Context.getLValueReferenceType(getArithmeticType(Left));
7696 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7697 /*IsAssigmentOperator=*/isEqualOp);
7699 // Add this built-in operator as a candidate (VQ is 'volatile').
7700 if (VisibleTypeConversionsQuals.hasVolatile()) {
7702 S.Context.getVolatileType(getArithmeticType(Left));
7703 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7704 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7705 /*IsAssigmentOperator=*/isEqualOp);
7710 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7711 for (BuiltinCandidateTypeSet::iterator
7712 Vec1 = CandidateTypes[0].vector_begin(),
7713 Vec1End = CandidateTypes[0].vector_end();
7714 Vec1 != Vec1End; ++Vec1) {
7715 for (BuiltinCandidateTypeSet::iterator
7716 Vec2 = CandidateTypes[1].vector_begin(),
7717 Vec2End = CandidateTypes[1].vector_end();
7718 Vec2 != Vec2End; ++Vec2) {
7719 QualType ParamTypes[2];
7720 ParamTypes[1] = *Vec2;
7721 // Add this built-in operator as a candidate (VQ is empty).
7722 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7723 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7724 /*IsAssigmentOperator=*/isEqualOp);
7726 // Add this built-in operator as a candidate (VQ is 'volatile').
7727 if (VisibleTypeConversionsQuals.hasVolatile()) {
7728 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7729 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7730 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7731 /*IsAssigmentOperator=*/isEqualOp);
7737 // C++ [over.built]p22:
7739 // For every triple (L, VQ, R), where L is an integral type, VQ
7740 // is either volatile or empty, and R is a promoted integral
7741 // type, there exist candidate operator functions of the form
7743 // VQ L& operator%=(VQ L&, R);
7744 // VQ L& operator<<=(VQ L&, R);
7745 // VQ L& operator>>=(VQ L&, R);
7746 // VQ L& operator&=(VQ L&, R);
7747 // VQ L& operator^=(VQ L&, R);
7748 // VQ L& operator|=(VQ L&, R);
7749 void addAssignmentIntegralOverloads() {
7750 if (!HasArithmeticOrEnumeralCandidateType)
7753 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7754 for (unsigned Right = FirstPromotedIntegralType;
7755 Right < LastPromotedIntegralType; ++Right) {
7756 QualType ParamTypes[2];
7757 ParamTypes[1] = getArithmeticType(Right);
7759 // Add this built-in operator as a candidate (VQ is empty).
7761 S.Context.getLValueReferenceType(getArithmeticType(Left));
7762 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7763 if (VisibleTypeConversionsQuals.hasVolatile()) {
7764 // Add this built-in operator as a candidate (VQ is 'volatile').
7765 ParamTypes[0] = getArithmeticType(Left);
7766 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7767 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7768 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
7774 // C++ [over.operator]p23:
7776 // There also exist candidate operator functions of the form
7778 // bool operator!(bool);
7779 // bool operator&&(bool, bool);
7780 // bool operator||(bool, bool);
7781 void addExclaimOverload() {
7782 QualType ParamTy = S.Context.BoolTy;
7783 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
7784 /*IsAssignmentOperator=*/false,
7785 /*NumContextualBoolArguments=*/1);
7787 void addAmpAmpOrPipePipeOverload() {
7788 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7789 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
7790 /*IsAssignmentOperator=*/false,
7791 /*NumContextualBoolArguments=*/2);
7794 // C++ [over.built]p13:
7796 // For every cv-qualified or cv-unqualified object type T there
7797 // exist candidate operator functions of the form
7799 // T* operator+(T*, ptrdiff_t); [ABOVE]
7800 // T& operator[](T*, ptrdiff_t);
7801 // T* operator-(T*, ptrdiff_t); [ABOVE]
7802 // T* operator+(ptrdiff_t, T*); [ABOVE]
7803 // T& operator[](ptrdiff_t, T*);
7804 void addSubscriptOverloads() {
7805 for (BuiltinCandidateTypeSet::iterator
7806 Ptr = CandidateTypes[0].pointer_begin(),
7807 PtrEnd = CandidateTypes[0].pointer_end();
7808 Ptr != PtrEnd; ++Ptr) {
7809 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7810 QualType PointeeType = (*Ptr)->getPointeeType();
7811 if (!PointeeType->isObjectType())
7814 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7816 // T& operator[](T*, ptrdiff_t)
7817 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7820 for (BuiltinCandidateTypeSet::iterator
7821 Ptr = CandidateTypes[1].pointer_begin(),
7822 PtrEnd = CandidateTypes[1].pointer_end();
7823 Ptr != PtrEnd; ++Ptr) {
7824 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7825 QualType PointeeType = (*Ptr)->getPointeeType();
7826 if (!PointeeType->isObjectType())
7829 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7831 // T& operator[](ptrdiff_t, T*)
7832 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7836 // C++ [over.built]p11:
7837 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7838 // C1 is the same type as C2 or is a derived class of C2, T is an object
7839 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7840 // there exist candidate operator functions of the form
7842 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7844 // where CV12 is the union of CV1 and CV2.
7845 void addArrowStarOverloads() {
7846 for (BuiltinCandidateTypeSet::iterator
7847 Ptr = CandidateTypes[0].pointer_begin(),
7848 PtrEnd = CandidateTypes[0].pointer_end();
7849 Ptr != PtrEnd; ++Ptr) {
7850 QualType C1Ty = (*Ptr);
7852 QualifierCollector Q1;
7853 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7854 if (!isa<RecordType>(C1))
7856 // heuristic to reduce number of builtin candidates in the set.
7857 // Add volatile/restrict version only if there are conversions to a
7858 // volatile/restrict type.
7859 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7861 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7863 for (BuiltinCandidateTypeSet::iterator
7864 MemPtr = CandidateTypes[1].member_pointer_begin(),
7865 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7866 MemPtr != MemPtrEnd; ++MemPtr) {
7867 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7868 QualType C2 = QualType(mptr->getClass(), 0);
7869 C2 = C2.getUnqualifiedType();
7870 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7872 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7874 QualType T = mptr->getPointeeType();
7875 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7876 T.isVolatileQualified())
7878 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7879 T.isRestrictQualified())
7881 T = Q1.apply(S.Context, T);
7882 QualType ResultTy = S.Context.getLValueReferenceType(T);
7883 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
7888 // Note that we don't consider the first argument, since it has been
7889 // contextually converted to bool long ago. The candidates below are
7890 // therefore added as binary.
7892 // C++ [over.built]p25:
7893 // For every type T, where T is a pointer, pointer-to-member, or scoped
7894 // enumeration type, there exist candidate operator functions of the form
7896 // T operator?(bool, T, T);
7898 void addConditionalOperatorOverloads() {
7899 /// Set of (canonical) types that we've already handled.
7900 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7902 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7903 for (BuiltinCandidateTypeSet::iterator
7904 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7905 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7906 Ptr != PtrEnd; ++Ptr) {
7907 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7910 QualType ParamTypes[2] = { *Ptr, *Ptr };
7911 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
7914 for (BuiltinCandidateTypeSet::iterator
7915 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7916 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7917 MemPtr != MemPtrEnd; ++MemPtr) {
7918 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7921 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7922 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
7925 if (S.getLangOpts().CPlusPlus11) {
7926 for (BuiltinCandidateTypeSet::iterator
7927 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7928 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7929 Enum != EnumEnd; ++Enum) {
7930 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7933 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7936 QualType ParamTypes[2] = { *Enum, *Enum };
7937 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
7944 } // end anonymous namespace
7946 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
7947 /// operator overloads to the candidate set (C++ [over.built]), based
7948 /// on the operator @p Op and the arguments given. For example, if the
7949 /// operator is a binary '+', this routine might add "int
7950 /// operator+(int, int)" to cover integer addition.
7951 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7952 SourceLocation OpLoc,
7953 ArrayRef<Expr *> Args,
7954 OverloadCandidateSet &CandidateSet) {
7955 // Find all of the types that the arguments can convert to, but only
7956 // if the operator we're looking at has built-in operator candidates
7957 // that make use of these types. Also record whether we encounter non-record
7958 // candidate types or either arithmetic or enumeral candidate types.
7959 Qualifiers VisibleTypeConversionsQuals;
7960 VisibleTypeConversionsQuals.addConst();
7961 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
7962 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
7964 bool HasNonRecordCandidateType = false;
7965 bool HasArithmeticOrEnumeralCandidateType = false;
7966 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
7967 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7968 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7969 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7972 (Op == OO_Exclaim ||
7975 VisibleTypeConversionsQuals);
7976 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7977 CandidateTypes[ArgIdx].hasNonRecordTypes();
7978 HasArithmeticOrEnumeralCandidateType =
7979 HasArithmeticOrEnumeralCandidateType ||
7980 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
7983 // Exit early when no non-record types have been added to the candidate set
7984 // for any of the arguments to the operator.
7986 // We can't exit early for !, ||, or &&, since there we have always have
7987 // 'bool' overloads.
7988 if (!HasNonRecordCandidateType &&
7989 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
7992 // Setup an object to manage the common state for building overloads.
7993 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
7994 VisibleTypeConversionsQuals,
7995 HasArithmeticOrEnumeralCandidateType,
7996 CandidateTypes, CandidateSet);
7998 // Dispatch over the operation to add in only those overloads which apply.
8001 case NUM_OVERLOADED_OPERATORS:
8002 llvm_unreachable("Expected an overloaded operator");
8007 case OO_Array_Delete:
8010 "Special operators don't use AddBuiltinOperatorCandidates");
8014 // C++ [over.match.oper]p3:
8015 // -- For the operator ',', the unary operator '&', or the
8016 // operator '->', the built-in candidates set is empty.
8019 case OO_Plus: // '+' is either unary or binary
8020 if (Args.size() == 1)
8021 OpBuilder.addUnaryPlusPointerOverloads();
8024 case OO_Minus: // '-' is either unary or binary
8025 if (Args.size() == 1) {
8026 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8028 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8029 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8033 case OO_Star: // '*' is either unary or binary
8034 if (Args.size() == 1)
8035 OpBuilder.addUnaryStarPointerOverloads();
8037 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8041 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8046 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8047 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8051 case OO_ExclaimEqual:
8052 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
8058 case OO_GreaterEqual:
8059 OpBuilder.addRelationalPointerOrEnumeralOverloads();
8060 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8067 case OO_GreaterGreater:
8068 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8071 case OO_Amp: // '&' is either unary or binary
8072 if (Args.size() == 1)
8073 // C++ [over.match.oper]p3:
8074 // -- For the operator ',', the unary operator '&', or the
8075 // operator '->', the built-in candidates set is empty.
8078 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8082 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8086 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8091 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8096 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8099 case OO_PercentEqual:
8100 case OO_LessLessEqual:
8101 case OO_GreaterGreaterEqual:
8105 OpBuilder.addAssignmentIntegralOverloads();
8109 OpBuilder.addExclaimOverload();
8114 OpBuilder.addAmpAmpOrPipePipeOverload();
8118 OpBuilder.addSubscriptOverloads();
8122 OpBuilder.addArrowStarOverloads();
8125 case OO_Conditional:
8126 OpBuilder.addConditionalOperatorOverloads();
8127 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8132 /// \brief Add function candidates found via argument-dependent lookup
8133 /// to the set of overloading candidates.
8135 /// This routine performs argument-dependent name lookup based on the
8136 /// given function name (which may also be an operator name) and adds
8137 /// all of the overload candidates found by ADL to the overload
8138 /// candidate set (C++ [basic.lookup.argdep]).
8140 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8142 ArrayRef<Expr *> Args,
8143 TemplateArgumentListInfo *ExplicitTemplateArgs,
8144 OverloadCandidateSet& CandidateSet,
8145 bool PartialOverloading) {
8148 // FIXME: This approach for uniquing ADL results (and removing
8149 // redundant candidates from the set) relies on pointer-equality,
8150 // which means we need to key off the canonical decl. However,
8151 // always going back to the canonical decl might not get us the
8152 // right set of default arguments. What default arguments are
8153 // we supposed to consider on ADL candidates, anyway?
8155 // FIXME: Pass in the explicit template arguments?
8156 ArgumentDependentLookup(Name, Loc, Args, Fns);
8158 // Erase all of the candidates we already knew about.
8159 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8160 CandEnd = CandidateSet.end();
8161 Cand != CandEnd; ++Cand)
8162 if (Cand->Function) {
8163 Fns.erase(Cand->Function);
8164 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
8168 // For each of the ADL candidates we found, add it to the overload
8170 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
8171 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
8172 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
8173 if (ExplicitTemplateArgs)
8176 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8177 PartialOverloading);
8179 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
8180 FoundDecl, ExplicitTemplateArgs,
8181 Args, CandidateSet);
8185 /// isBetterOverloadCandidate - Determines whether the first overload
8186 /// candidate is a better candidate than the second (C++ 13.3.3p1).
8188 isBetterOverloadCandidate(Sema &S,
8189 const OverloadCandidate &Cand1,
8190 const OverloadCandidate &Cand2,
8192 bool UserDefinedConversion) {
8193 // Define viable functions to be better candidates than non-viable
8196 return Cand1.Viable;
8197 else if (!Cand1.Viable)
8200 // C++ [over.match.best]p1:
8202 // -- if F is a static member function, ICS1(F) is defined such
8203 // that ICS1(F) is neither better nor worse than ICS1(G) for
8204 // any function G, and, symmetrically, ICS1(G) is neither
8205 // better nor worse than ICS1(F).
8206 unsigned StartArg = 0;
8207 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8210 // C++ [over.match.best]p1:
8211 // A viable function F1 is defined to be a better function than another
8212 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
8213 // conversion sequence than ICSi(F2), and then...
8214 unsigned NumArgs = Cand1.NumConversions;
8215 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
8216 bool HasBetterConversion = false;
8217 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
8218 switch (CompareImplicitConversionSequences(S,
8219 Cand1.Conversions[ArgIdx],
8220 Cand2.Conversions[ArgIdx])) {
8221 case ImplicitConversionSequence::Better:
8222 // Cand1 has a better conversion sequence.
8223 HasBetterConversion = true;
8226 case ImplicitConversionSequence::Worse:
8227 // Cand1 can't be better than Cand2.
8230 case ImplicitConversionSequence::Indistinguishable:
8236 // -- for some argument j, ICSj(F1) is a better conversion sequence than
8237 // ICSj(F2), or, if not that,
8238 if (HasBetterConversion)
8241 // -- the context is an initialization by user-defined conversion
8242 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8243 // from the return type of F1 to the destination type (i.e.,
8244 // the type of the entity being initialized) is a better
8245 // conversion sequence than the standard conversion sequence
8246 // from the return type of F2 to the destination type.
8247 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
8248 isa<CXXConversionDecl>(Cand1.Function) &&
8249 isa<CXXConversionDecl>(Cand2.Function)) {
8250 // First check whether we prefer one of the conversion functions over the
8251 // other. This only distinguishes the results in non-standard, extension
8252 // cases such as the conversion from a lambda closure type to a function
8253 // pointer or block.
8254 ImplicitConversionSequence::CompareKind Result =
8255 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8256 if (Result == ImplicitConversionSequence::Indistinguishable)
8257 Result = CompareStandardConversionSequences(S,
8258 Cand1.FinalConversion,
8259 Cand2.FinalConversion);
8261 if (Result != ImplicitConversionSequence::Indistinguishable)
8262 return Result == ImplicitConversionSequence::Better;
8264 // FIXME: Compare kind of reference binding if conversion functions
8265 // convert to a reference type used in direct reference binding, per
8266 // C++14 [over.match.best]p1 section 2 bullet 3.
8269 // -- F1 is a non-template function and F2 is a function template
8270 // specialization, or, if not that,
8271 bool Cand1IsSpecialization = Cand1.Function &&
8272 Cand1.Function->getPrimaryTemplate();
8273 bool Cand2IsSpecialization = Cand2.Function &&
8274 Cand2.Function->getPrimaryTemplate();
8275 if (Cand1IsSpecialization != Cand2IsSpecialization)
8276 return Cand2IsSpecialization;
8278 // -- F1 and F2 are function template specializations, and the function
8279 // template for F1 is more specialized than the template for F2
8280 // according to the partial ordering rules described in 14.5.5.2, or,
8282 if (Cand1IsSpecialization && Cand2IsSpecialization) {
8283 if (FunctionTemplateDecl *BetterTemplate
8284 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8285 Cand2.Function->getPrimaryTemplate(),
8287 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
8289 Cand1.ExplicitCallArguments,
8290 Cand2.ExplicitCallArguments))
8291 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
8294 // Check for enable_if value-based overload resolution.
8295 if (Cand1.Function && Cand2.Function &&
8296 (Cand1.Function->hasAttr<EnableIfAttr>() ||
8297 Cand2.Function->hasAttr<EnableIfAttr>())) {
8298 // FIXME: The next several lines are just
8299 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8300 // instead of reverse order which is how they're stored in the AST.
8302 if (Cand1.Function->hasAttrs()) {
8303 Cand1Attrs = Cand1.Function->getAttrs();
8304 Cand1Attrs.erase(std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8307 std::reverse(Cand1Attrs.begin(), Cand1Attrs.end());
8311 if (Cand2.Function->hasAttrs()) {
8312 Cand2Attrs = Cand2.Function->getAttrs();
8313 Cand2Attrs.erase(std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8316 std::reverse(Cand2Attrs.begin(), Cand2Attrs.end());
8319 // Candidate 1 is better if it has strictly more attributes and
8320 // the common sequence is identical.
8321 if (Cand1Attrs.size() <= Cand2Attrs.size())
8324 auto Cand1I = Cand1Attrs.begin();
8325 for (auto &Cand2A : Cand2Attrs) {
8326 auto &Cand1A = *Cand1I++;
8327 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8328 cast<EnableIfAttr>(Cand1A)->getCond()->Profile(Cand1ID,
8329 S.getASTContext(), true);
8330 cast<EnableIfAttr>(Cand2A)->getCond()->Profile(Cand2ID,
8331 S.getASTContext(), true);
8332 if (Cand1ID != Cand2ID)
8342 /// \brief Computes the best viable function (C++ 13.3.3)
8343 /// within an overload candidate set.
8345 /// \param Loc The location of the function name (or operator symbol) for
8346 /// which overload resolution occurs.
8348 /// \param Best If overload resolution was successful or found a deleted
8349 /// function, \p Best points to the candidate function found.
8351 /// \returns The result of overload resolution.
8353 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
8355 bool UserDefinedConversion) {
8356 // Find the best viable function.
8358 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8360 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
8361 UserDefinedConversion))
8365 // If we didn't find any viable functions, abort.
8367 return OR_No_Viable_Function;
8369 // Make sure that this function is better than every other viable
8370 // function. If not, we have an ambiguity.
8371 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8374 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
8375 UserDefinedConversion)) {
8377 return OR_Ambiguous;
8381 // Best is the best viable function.
8382 if (Best->Function &&
8383 (Best->Function->isDeleted() ||
8384 S.isFunctionConsideredUnavailable(Best->Function)))
8392 enum OverloadCandidateKind {
8396 oc_function_template,
8398 oc_constructor_template,
8399 oc_implicit_default_constructor,
8400 oc_implicit_copy_constructor,
8401 oc_implicit_move_constructor,
8402 oc_implicit_copy_assignment,
8403 oc_implicit_move_assignment,
8404 oc_implicit_inherited_constructor
8407 OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8409 std::string &Description) {
8410 bool isTemplate = false;
8412 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8414 Description = S.getTemplateArgumentBindingsText(
8415 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8418 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
8419 if (!Ctor->isImplicit())
8420 return isTemplate ? oc_constructor_template : oc_constructor;
8422 if (Ctor->getInheritedConstructor())
8423 return oc_implicit_inherited_constructor;
8425 if (Ctor->isDefaultConstructor())
8426 return oc_implicit_default_constructor;
8428 if (Ctor->isMoveConstructor())
8429 return oc_implicit_move_constructor;
8431 assert(Ctor->isCopyConstructor() &&
8432 "unexpected sort of implicit constructor");
8433 return oc_implicit_copy_constructor;
8436 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8437 // This actually gets spelled 'candidate function' for now, but
8438 // it doesn't hurt to split it out.
8439 if (!Meth->isImplicit())
8440 return isTemplate ? oc_method_template : oc_method;
8442 if (Meth->isMoveAssignmentOperator())
8443 return oc_implicit_move_assignment;
8445 if (Meth->isCopyAssignmentOperator())
8446 return oc_implicit_copy_assignment;
8448 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8452 return isTemplate ? oc_function_template : oc_function;
8455 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
8456 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8459 Ctor = Ctor->getInheritedConstructor();
8462 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8465 } // end anonymous namespace
8467 // Notes the location of an overload candidate.
8468 void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
8470 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
8471 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8472 << (unsigned) K << FnDesc;
8473 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8474 Diag(Fn->getLocation(), PD);
8475 MaybeEmitInheritedConstructorNote(*this, Fn);
8478 // Notes the location of all overload candidates designated through
8480 void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
8481 assert(OverloadedExpr->getType() == Context.OverloadTy);
8483 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8484 OverloadExpr *OvlExpr = Ovl.Expression;
8486 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8487 IEnd = OvlExpr->decls_end();
8489 if (FunctionTemplateDecl *FunTmpl =
8490 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
8491 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
8492 } else if (FunctionDecl *Fun
8493 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
8494 NoteOverloadCandidate(Fun, DestType);
8499 /// Diagnoses an ambiguous conversion. The partial diagnostic is the
8500 /// "lead" diagnostic; it will be given two arguments, the source and
8501 /// target types of the conversion.
8502 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8504 SourceLocation CaretLoc,
8505 const PartialDiagnostic &PDiag) const {
8506 S.Diag(CaretLoc, PDiag)
8507 << Ambiguous.getFromType() << Ambiguous.getToType();
8508 // FIXME: The note limiting machinery is borrowed from
8509 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8510 // refactoring here.
8511 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8512 unsigned CandsShown = 0;
8513 AmbiguousConversionSequence::const_iterator I, E;
8514 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8515 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8518 S.NoteOverloadCandidate(*I);
8521 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
8526 void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8527 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8528 assert(Conv.isBad());
8529 assert(Cand->Function && "for now, candidate must be a function");
8530 FunctionDecl *Fn = Cand->Function;
8532 // There's a conversion slot for the object argument if this is a
8533 // non-constructor method. Note that 'I' corresponds the
8534 // conversion-slot index.
8535 bool isObjectArgument = false;
8536 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
8538 isObjectArgument = true;
8544 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8546 Expr *FromExpr = Conv.Bad.FromExpr;
8547 QualType FromTy = Conv.Bad.getFromType();
8548 QualType ToTy = Conv.Bad.getToType();
8550 if (FromTy == S.Context.OverloadTy) {
8551 assert(FromExpr && "overload set argument came from implicit argument?");
8552 Expr *E = FromExpr->IgnoreParens();
8553 if (isa<UnaryOperator>(E))
8554 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
8555 DeclarationName Name = cast<OverloadExpr>(E)->getName();
8557 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8558 << (unsigned) FnKind << FnDesc
8559 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8560 << ToTy << Name << I+1;
8561 MaybeEmitInheritedConstructorNote(S, Fn);
8565 // Do some hand-waving analysis to see if the non-viability is due
8566 // to a qualifier mismatch.
8567 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8568 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8569 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8570 CToTy = RT->getPointeeType();
8572 // TODO: detect and diagnose the full richness of const mismatches.
8573 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8574 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8575 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8578 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8579 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
8580 Qualifiers FromQs = CFromTy.getQualifiers();
8581 Qualifiers ToQs = CToTy.getQualifiers();
8583 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8584 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8585 << (unsigned) FnKind << FnDesc
8586 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8588 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8589 << (unsigned) isObjectArgument << I+1;
8590 MaybeEmitInheritedConstructorNote(S, Fn);
8594 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8595 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
8596 << (unsigned) FnKind << FnDesc
8597 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8599 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8600 << (unsigned) isObjectArgument << I+1;
8601 MaybeEmitInheritedConstructorNote(S, Fn);
8605 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8606 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8607 << (unsigned) FnKind << FnDesc
8608 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8610 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8611 << (unsigned) isObjectArgument << I+1;
8612 MaybeEmitInheritedConstructorNote(S, Fn);
8616 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8617 assert(CVR && "unexpected qualifiers mismatch");
8619 if (isObjectArgument) {
8620 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8621 << (unsigned) FnKind << FnDesc
8622 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8623 << FromTy << (CVR - 1);
8625 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8626 << (unsigned) FnKind << FnDesc
8627 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8628 << FromTy << (CVR - 1) << I+1;
8630 MaybeEmitInheritedConstructorNote(S, Fn);
8634 // Special diagnostic for failure to convert an initializer list, since
8635 // telling the user that it has type void is not useful.
8636 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8637 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8638 << (unsigned) FnKind << FnDesc
8639 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8640 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8641 MaybeEmitInheritedConstructorNote(S, Fn);
8645 // Diagnose references or pointers to incomplete types differently,
8646 // since it's far from impossible that the incompleteness triggered
8648 QualType TempFromTy = FromTy.getNonReferenceType();
8649 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8650 TempFromTy = PTy->getPointeeType();
8651 if (TempFromTy->isIncompleteType()) {
8652 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8653 << (unsigned) FnKind << FnDesc
8654 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8655 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8656 MaybeEmitInheritedConstructorNote(S, Fn);
8660 // Diagnose base -> derived pointer conversions.
8661 unsigned BaseToDerivedConversion = 0;
8662 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8663 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8664 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8665 FromPtrTy->getPointeeType()) &&
8666 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8667 !ToPtrTy->getPointeeType()->isIncompleteType() &&
8668 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
8669 FromPtrTy->getPointeeType()))
8670 BaseToDerivedConversion = 1;
8672 } else if (const ObjCObjectPointerType *FromPtrTy
8673 = FromTy->getAs<ObjCObjectPointerType>()) {
8674 if (const ObjCObjectPointerType *ToPtrTy
8675 = ToTy->getAs<ObjCObjectPointerType>())
8676 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8677 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8678 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8679 FromPtrTy->getPointeeType()) &&
8680 FromIface->isSuperClassOf(ToIface))
8681 BaseToDerivedConversion = 2;
8682 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8683 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8684 !FromTy->isIncompleteType() &&
8685 !ToRefTy->getPointeeType()->isIncompleteType() &&
8686 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8687 BaseToDerivedConversion = 3;
8688 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8689 ToTy.getNonReferenceType().getCanonicalType() ==
8690 FromTy.getNonReferenceType().getCanonicalType()) {
8691 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8692 << (unsigned) FnKind << FnDesc
8693 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8694 << (unsigned) isObjectArgument << I + 1;
8695 MaybeEmitInheritedConstructorNote(S, Fn);
8700 if (BaseToDerivedConversion) {
8701 S.Diag(Fn->getLocation(),
8702 diag::note_ovl_candidate_bad_base_to_derived_conv)
8703 << (unsigned) FnKind << FnDesc
8704 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8705 << (BaseToDerivedConversion - 1)
8706 << FromTy << ToTy << I+1;
8707 MaybeEmitInheritedConstructorNote(S, Fn);
8711 if (isa<ObjCObjectPointerType>(CFromTy) &&
8712 isa<PointerType>(CToTy)) {
8713 Qualifiers FromQs = CFromTy.getQualifiers();
8714 Qualifiers ToQs = CToTy.getQualifiers();
8715 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8716 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8717 << (unsigned) FnKind << FnDesc
8718 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8719 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8720 MaybeEmitInheritedConstructorNote(S, Fn);
8725 // Emit the generic diagnostic and, optionally, add the hints to it.
8726 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8727 FDiag << (unsigned) FnKind << FnDesc
8728 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8729 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8730 << (unsigned) (Cand->Fix.Kind);
8732 // If we can fix the conversion, suggest the FixIts.
8733 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8734 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
8736 S.Diag(Fn->getLocation(), FDiag);
8738 MaybeEmitInheritedConstructorNote(S, Fn);
8741 /// Additional arity mismatch diagnosis specific to a function overload
8742 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
8743 /// over a candidate in any candidate set.
8744 bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8746 FunctionDecl *Fn = Cand->Function;
8747 unsigned MinParams = Fn->getMinRequiredArguments();
8749 // With invalid overloaded operators, it's possible that we think we
8750 // have an arity mismatch when in fact it looks like we have the
8751 // right number of arguments, because only overloaded operators have
8752 // the weird behavior of overloading member and non-member functions.
8753 // Just don't report anything.
8754 if (Fn->isInvalidDecl() &&
8755 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8758 if (NumArgs < MinParams) {
8759 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8760 (Cand->FailureKind == ovl_fail_bad_deduction &&
8761 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8763 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8764 (Cand->FailureKind == ovl_fail_bad_deduction &&
8765 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8771 /// General arity mismatch diagnosis over a candidate in a candidate set.
8772 void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8773 assert(isa<FunctionDecl>(D) &&
8774 "The templated declaration should at least be a function"
8775 " when diagnosing bad template argument deduction due to too many"
8776 " or too few arguments");
8778 FunctionDecl *Fn = cast<FunctionDecl>(D);
8780 // TODO: treat calls to a missing default constructor as a special case
8781 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8782 unsigned MinParams = Fn->getMinRequiredArguments();
8784 // at least / at most / exactly
8785 unsigned mode, modeCount;
8786 if (NumFormalArgs < MinParams) {
8787 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
8788 FnTy->isTemplateVariadic())
8789 mode = 0; // "at least"
8791 mode = 2; // "exactly"
8792 modeCount = MinParams;
8794 if (MinParams != FnTy->getNumParams())
8795 mode = 1; // "at most"
8797 mode = 2; // "exactly"
8798 modeCount = FnTy->getNumParams();
8801 std::string Description;
8802 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8804 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8805 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8806 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8807 << mode << Fn->getParamDecl(0) << NumFormalArgs;
8809 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8810 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != nullptr)
8811 << mode << modeCount << NumFormalArgs;
8812 MaybeEmitInheritedConstructorNote(S, Fn);
8815 /// Arity mismatch diagnosis specific to a function overload candidate.
8816 void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8817 unsigned NumFormalArgs) {
8818 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8819 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8822 TemplateDecl *getDescribedTemplate(Decl *Templated) {
8823 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8824 return FD->getDescribedFunctionTemplate();
8825 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8826 return RD->getDescribedClassTemplate();
8828 llvm_unreachable("Unsupported: Getting the described template declaration"
8829 " for bad deduction diagnosis");
8832 /// Diagnose a failed template-argument deduction.
8833 void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8834 DeductionFailureInfo &DeductionFailure,
8836 TemplateParameter Param = DeductionFailure.getTemplateParameter();
8838 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8839 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8840 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
8841 switch (DeductionFailure.Result) {
8842 case Sema::TDK_Success:
8843 llvm_unreachable("TDK_success while diagnosing bad deduction");
8845 case Sema::TDK_Incomplete: {
8846 assert(ParamD && "no parameter found for incomplete deduction result");
8847 S.Diag(Templated->getLocation(),
8848 diag::note_ovl_candidate_incomplete_deduction)
8849 << ParamD->getDeclName();
8850 MaybeEmitInheritedConstructorNote(S, Templated);
8854 case Sema::TDK_Underqualified: {
8855 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8856 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8858 QualType Param = DeductionFailure.getFirstArg()->getAsType();
8860 // Param will have been canonicalized, but it should just be a
8861 // qualified version of ParamD, so move the qualifiers to that.
8862 QualifierCollector Qs;
8864 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
8865 assert(S.Context.hasSameType(Param, NonCanonParam));
8867 // Arg has also been canonicalized, but there's nothing we can do
8868 // about that. It also doesn't matter as much, because it won't
8869 // have any template parameters in it (because deduction isn't
8870 // done on dependent types).
8871 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
8873 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
8874 << ParamD->getDeclName() << Arg << NonCanonParam;
8875 MaybeEmitInheritedConstructorNote(S, Templated);
8879 case Sema::TDK_Inconsistent: {
8880 assert(ParamD && "no parameter found for inconsistent deduction result");
8882 if (isa<TemplateTypeParmDecl>(ParamD))
8884 else if (isa<NonTypeTemplateParmDecl>(ParamD))
8890 S.Diag(Templated->getLocation(),
8891 diag::note_ovl_candidate_inconsistent_deduction)
8892 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
8893 << *DeductionFailure.getSecondArg();
8894 MaybeEmitInheritedConstructorNote(S, Templated);
8898 case Sema::TDK_InvalidExplicitArguments:
8899 assert(ParamD && "no parameter found for invalid explicit arguments");
8900 if (ParamD->getDeclName())
8901 S.Diag(Templated->getLocation(),
8902 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8903 << ParamD->getDeclName();
8906 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8907 index = TTP->getIndex();
8908 else if (NonTypeTemplateParmDecl *NTTP
8909 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8910 index = NTTP->getIndex();
8912 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
8913 S.Diag(Templated->getLocation(),
8914 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8917 MaybeEmitInheritedConstructorNote(S, Templated);
8920 case Sema::TDK_TooManyArguments:
8921 case Sema::TDK_TooFewArguments:
8922 DiagnoseArityMismatch(S, Templated, NumArgs);
8925 case Sema::TDK_InstantiationDepth:
8926 S.Diag(Templated->getLocation(),
8927 diag::note_ovl_candidate_instantiation_depth);
8928 MaybeEmitInheritedConstructorNote(S, Templated);
8931 case Sema::TDK_SubstitutionFailure: {
8932 // Format the template argument list into the argument string.
8933 SmallString<128> TemplateArgString;
8934 if (TemplateArgumentList *Args =
8935 DeductionFailure.getTemplateArgumentList()) {
8936 TemplateArgString = " ";
8937 TemplateArgString += S.getTemplateArgumentBindingsText(
8938 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
8941 // If this candidate was disabled by enable_if, say so.
8942 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
8943 if (PDiag && PDiag->second.getDiagID() ==
8944 diag::err_typename_nested_not_found_enable_if) {
8945 // FIXME: Use the source range of the condition, and the fully-qualified
8946 // name of the enable_if template. These are both present in PDiag.
8947 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8948 << "'enable_if'" << TemplateArgString;
8952 // Format the SFINAE diagnostic into the argument string.
8953 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8954 // formatted message in another diagnostic.
8955 SmallString<128> SFINAEArgString;
8958 SFINAEArgString = ": ";
8959 R = SourceRange(PDiag->first, PDiag->first);
8960 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8963 S.Diag(Templated->getLocation(),
8964 diag::note_ovl_candidate_substitution_failure)
8965 << TemplateArgString << SFINAEArgString << R;
8966 MaybeEmitInheritedConstructorNote(S, Templated);
8970 case Sema::TDK_FailedOverloadResolution: {
8971 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
8972 S.Diag(Templated->getLocation(),
8973 diag::note_ovl_candidate_failed_overload_resolution)
8974 << R.Expression->getName();
8978 case Sema::TDK_NonDeducedMismatch: {
8979 // FIXME: Provide a source location to indicate what we couldn't match.
8980 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
8981 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
8982 if (FirstTA.getKind() == TemplateArgument::Template &&
8983 SecondTA.getKind() == TemplateArgument::Template) {
8984 TemplateName FirstTN = FirstTA.getAsTemplate();
8985 TemplateName SecondTN = SecondTA.getAsTemplate();
8986 if (FirstTN.getKind() == TemplateName::Template &&
8987 SecondTN.getKind() == TemplateName::Template) {
8988 if (FirstTN.getAsTemplateDecl()->getName() ==
8989 SecondTN.getAsTemplateDecl()->getName()) {
8990 // FIXME: This fixes a bad diagnostic where both templates are named
8991 // the same. This particular case is a bit difficult since:
8992 // 1) It is passed as a string to the diagnostic printer.
8993 // 2) The diagnostic printer only attempts to find a better
8994 // name for types, not decls.
8995 // Ideally, this should folded into the diagnostic printer.
8996 S.Diag(Templated->getLocation(),
8997 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8998 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
9003 // FIXME: For generic lambda parameters, check if the function is a lambda
9004 // call operator, and if so, emit a prettier and more informative
9005 // diagnostic that mentions 'auto' and lambda in addition to
9006 // (or instead of?) the canonical template type parameters.
9007 S.Diag(Templated->getLocation(),
9008 diag::note_ovl_candidate_non_deduced_mismatch)
9009 << FirstTA << SecondTA;
9012 // TODO: diagnose these individually, then kill off
9013 // note_ovl_candidate_bad_deduction, which is uselessly vague.
9014 case Sema::TDK_MiscellaneousDeductionFailure:
9015 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
9016 MaybeEmitInheritedConstructorNote(S, Templated);
9021 /// Diagnose a failed template-argument deduction, for function calls.
9022 void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) {
9023 unsigned TDK = Cand->DeductionFailure.Result;
9024 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
9025 if (CheckArityMismatch(S, Cand, NumArgs))
9028 DiagnoseBadDeduction(S, Cand->Function, // pattern
9029 Cand->DeductionFailure, NumArgs);
9032 /// CUDA: diagnose an invalid call across targets.
9033 void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
9034 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
9035 FunctionDecl *Callee = Cand->Function;
9037 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
9038 CalleeTarget = S.IdentifyCUDATarget(Callee);
9041 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
9043 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9044 << (unsigned) FnKind << CalleeTarget << CallerTarget;
9047 void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9048 FunctionDecl *Callee = Cand->Function;
9049 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9051 S.Diag(Callee->getLocation(),
9052 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9053 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9056 /// Generates a 'note' diagnostic for an overload candidate. We've
9057 /// already generated a primary error at the call site.
9059 /// It really does need to be a single diagnostic with its caret
9060 /// pointed at the candidate declaration. Yes, this creates some
9061 /// major challenges of technical writing. Yes, this makes pointing
9062 /// out problems with specific arguments quite awkward. It's still
9063 /// better than generating twenty screens of text for every failed
9066 /// It would be great to be able to express per-candidate problems
9067 /// more richly for those diagnostic clients that cared, but we'd
9068 /// still have to be just as careful with the default diagnostics.
9069 void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
9071 FunctionDecl *Fn = Cand->Function;
9073 // Note deleted candidates, but only if they're viable.
9074 if (Cand->Viable && (Fn->isDeleted() ||
9075 S.isFunctionConsideredUnavailable(Fn))) {
9077 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
9079 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
9081 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
9082 MaybeEmitInheritedConstructorNote(S, Fn);
9086 // We don't really have anything else to say about viable candidates.
9088 S.NoteOverloadCandidate(Fn);
9092 switch (Cand->FailureKind) {
9093 case ovl_fail_too_many_arguments:
9094 case ovl_fail_too_few_arguments:
9095 return DiagnoseArityMismatch(S, Cand, NumArgs);
9097 case ovl_fail_bad_deduction:
9098 return DiagnoseBadDeduction(S, Cand, NumArgs);
9100 case ovl_fail_trivial_conversion:
9101 case ovl_fail_bad_final_conversion:
9102 case ovl_fail_final_conversion_not_exact:
9103 return S.NoteOverloadCandidate(Fn);
9105 case ovl_fail_bad_conversion: {
9106 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
9107 for (unsigned N = Cand->NumConversions; I != N; ++I)
9108 if (Cand->Conversions[I].isBad())
9109 return DiagnoseBadConversion(S, Cand, I);
9111 // FIXME: this currently happens when we're called from SemaInit
9112 // when user-conversion overload fails. Figure out how to handle
9113 // those conditions and diagnose them well.
9114 return S.NoteOverloadCandidate(Fn);
9117 case ovl_fail_bad_target:
9118 return DiagnoseBadTarget(S, Cand);
9120 case ovl_fail_enable_if:
9121 return DiagnoseFailedEnableIfAttr(S, Cand);
9125 void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9126 // Desugar the type of the surrogate down to a function type,
9127 // retaining as many typedefs as possible while still showing
9128 // the function type (and, therefore, its parameter types).
9129 QualType FnType = Cand->Surrogate->getConversionType();
9130 bool isLValueReference = false;
9131 bool isRValueReference = false;
9132 bool isPointer = false;
9133 if (const LValueReferenceType *FnTypeRef =
9134 FnType->getAs<LValueReferenceType>()) {
9135 FnType = FnTypeRef->getPointeeType();
9136 isLValueReference = true;
9137 } else if (const RValueReferenceType *FnTypeRef =
9138 FnType->getAs<RValueReferenceType>()) {
9139 FnType = FnTypeRef->getPointeeType();
9140 isRValueReference = true;
9142 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9143 FnType = FnTypePtr->getPointeeType();
9146 // Desugar down to a function type.
9147 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9148 // Reconstruct the pointer/reference as appropriate.
9149 if (isPointer) FnType = S.Context.getPointerType(FnType);
9150 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9151 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9153 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9155 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
9158 void NoteBuiltinOperatorCandidate(Sema &S,
9160 SourceLocation OpLoc,
9161 OverloadCandidate *Cand) {
9162 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
9163 std::string TypeStr("operator");
9166 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
9167 if (Cand->NumConversions == 1) {
9169 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9172 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9174 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9178 void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9179 OverloadCandidate *Cand) {
9180 unsigned NoOperands = Cand->NumConversions;
9181 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9182 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
9183 if (ICS.isBad()) break; // all meaningless after first invalid
9184 if (!ICS.isAmbiguous()) continue;
9186 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
9187 S.PDiag(diag::note_ambiguous_type_conversion));
9191 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
9193 return Cand->Function->getLocation();
9194 if (Cand->IsSurrogate)
9195 return Cand->Surrogate->getLocation();
9196 return SourceLocation();
9199 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
9200 switch ((Sema::TemplateDeductionResult)DFI.Result) {
9201 case Sema::TDK_Success:
9202 llvm_unreachable("TDK_success while diagnosing bad deduction");
9204 case Sema::TDK_Invalid:
9205 case Sema::TDK_Incomplete:
9208 case Sema::TDK_Underqualified:
9209 case Sema::TDK_Inconsistent:
9212 case Sema::TDK_SubstitutionFailure:
9213 case Sema::TDK_NonDeducedMismatch:
9214 case Sema::TDK_MiscellaneousDeductionFailure:
9217 case Sema::TDK_InstantiationDepth:
9218 case Sema::TDK_FailedOverloadResolution:
9221 case Sema::TDK_InvalidExplicitArguments:
9224 case Sema::TDK_TooManyArguments:
9225 case Sema::TDK_TooFewArguments:
9228 llvm_unreachable("Unhandled deduction result");
9231 struct CompareOverloadCandidatesForDisplay {
9235 CompareOverloadCandidatesForDisplay(Sema &S, size_t nArgs)
9236 : S(S), NumArgs(nArgs) {}
9238 bool operator()(const OverloadCandidate *L,
9239 const OverloadCandidate *R) {
9240 // Fast-path this check.
9241 if (L == R) return false;
9243 // Order first by viability.
9245 if (!R->Viable) return true;
9247 // TODO: introduce a tri-valued comparison for overload
9248 // candidates. Would be more worthwhile if we had a sort
9249 // that could exploit it.
9250 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9251 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
9252 } else if (R->Viable)
9255 assert(L->Viable == R->Viable);
9257 // Criteria by which we can sort non-viable candidates:
9259 // 1. Arity mismatches come after other candidates.
9260 if (L->FailureKind == ovl_fail_too_many_arguments ||
9261 L->FailureKind == ovl_fail_too_few_arguments) {
9262 if (R->FailureKind == ovl_fail_too_many_arguments ||
9263 R->FailureKind == ovl_fail_too_few_arguments) {
9264 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
9265 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
9266 if (LDist == RDist) {
9267 if (L->FailureKind == R->FailureKind)
9268 // Sort non-surrogates before surrogates.
9269 return !L->IsSurrogate && R->IsSurrogate;
9270 // Sort candidates requiring fewer parameters than there were
9271 // arguments given after candidates requiring more parameters
9272 // than there were arguments given.
9273 return L->FailureKind == ovl_fail_too_many_arguments;
9275 return LDist < RDist;
9279 if (R->FailureKind == ovl_fail_too_many_arguments ||
9280 R->FailureKind == ovl_fail_too_few_arguments)
9283 // 2. Bad conversions come first and are ordered by the number
9284 // of bad conversions and quality of good conversions.
9285 if (L->FailureKind == ovl_fail_bad_conversion) {
9286 if (R->FailureKind != ovl_fail_bad_conversion)
9289 // The conversion that can be fixed with a smaller number of changes,
9291 unsigned numLFixes = L->Fix.NumConversionsFixed;
9292 unsigned numRFixes = R->Fix.NumConversionsFixed;
9293 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9294 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
9295 if (numLFixes != numRFixes) {
9296 if (numLFixes < numRFixes)
9302 // If there's any ordering between the defined conversions...
9303 // FIXME: this might not be transitive.
9304 assert(L->NumConversions == R->NumConversions);
9307 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
9308 for (unsigned E = L->NumConversions; I != E; ++I) {
9309 switch (CompareImplicitConversionSequences(S,
9311 R->Conversions[I])) {
9312 case ImplicitConversionSequence::Better:
9316 case ImplicitConversionSequence::Worse:
9320 case ImplicitConversionSequence::Indistinguishable:
9324 if (leftBetter > 0) return true;
9325 if (leftBetter < 0) return false;
9327 } else if (R->FailureKind == ovl_fail_bad_conversion)
9330 if (L->FailureKind == ovl_fail_bad_deduction) {
9331 if (R->FailureKind != ovl_fail_bad_deduction)
9334 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9335 return RankDeductionFailure(L->DeductionFailure)
9336 < RankDeductionFailure(R->DeductionFailure);
9337 } else if (R->FailureKind == ovl_fail_bad_deduction)
9343 // Sort everything else by location.
9344 SourceLocation LLoc = GetLocationForCandidate(L);
9345 SourceLocation RLoc = GetLocationForCandidate(R);
9347 // Put candidates without locations (e.g. builtins) at the end.
9348 if (LLoc.isInvalid()) return false;
9349 if (RLoc.isInvalid()) return true;
9351 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9355 /// CompleteNonViableCandidate - Normally, overload resolution only
9356 /// computes up to the first. Produces the FixIt set if possible.
9357 void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
9358 ArrayRef<Expr *> Args) {
9359 assert(!Cand->Viable);
9361 // Don't do anything on failures other than bad conversion.
9362 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9364 // We only want the FixIts if all the arguments can be corrected.
9365 bool Unfixable = false;
9366 // Use a implicit copy initialization to check conversion fixes.
9367 Cand->Fix.setConversionChecker(TryCopyInitialization);
9369 // Skip forward to the first bad conversion.
9370 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
9371 unsigned ConvCount = Cand->NumConversions;
9373 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9375 if (Cand->Conversions[ConvIdx - 1].isBad()) {
9376 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
9381 if (ConvIdx == ConvCount)
9384 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9385 "remaining conversion is initialized?");
9387 // FIXME: this should probably be preserved from the overload
9388 // operation somehow.
9389 bool SuppressUserConversions = false;
9391 const FunctionProtoType* Proto;
9392 unsigned ArgIdx = ConvIdx;
9394 if (Cand->IsSurrogate) {
9396 = Cand->Surrogate->getConversionType().getNonReferenceType();
9397 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9398 ConvType = ConvPtrType->getPointeeType();
9399 Proto = ConvType->getAs<FunctionProtoType>();
9401 } else if (Cand->Function) {
9402 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9403 if (isa<CXXMethodDecl>(Cand->Function) &&
9404 !isa<CXXConstructorDecl>(Cand->Function))
9407 // Builtin binary operator with a bad first conversion.
9408 assert(ConvCount <= 3);
9409 for (; ConvIdx != ConvCount; ++ConvIdx)
9410 Cand->Conversions[ConvIdx]
9411 = TryCopyInitialization(S, Args[ConvIdx],
9412 Cand->BuiltinTypes.ParamTypes[ConvIdx],
9413 SuppressUserConversions,
9414 /*InOverloadResolution*/ true,
9415 /*AllowObjCWritebackConversion=*/
9416 S.getLangOpts().ObjCAutoRefCount);
9420 // Fill in the rest of the conversions.
9421 unsigned NumParams = Proto->getNumParams();
9422 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
9423 if (ArgIdx < NumParams) {
9424 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9425 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9426 /*InOverloadResolution=*/true,
9427 /*AllowObjCWritebackConversion=*/
9428 S.getLangOpts().ObjCAutoRefCount);
9429 // Store the FixIt in the candidate if it exists.
9430 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
9431 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
9434 Cand->Conversions[ConvIdx].setEllipsis();
9438 } // end anonymous namespace
9440 /// PrintOverloadCandidates - When overload resolution fails, prints
9441 /// diagnostic messages containing the candidates in the candidate
9443 void OverloadCandidateSet::NoteCandidates(Sema &S,
9444 OverloadCandidateDisplayKind OCD,
9445 ArrayRef<Expr *> Args,
9447 SourceLocation OpLoc) {
9448 // Sort the candidates by viability and position. Sorting directly would
9449 // be prohibitive, so we make a set of pointers and sort those.
9450 SmallVector<OverloadCandidate*, 32> Cands;
9451 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9452 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9454 Cands.push_back(Cand);
9455 else if (OCD == OCD_AllCandidates) {
9456 CompleteNonViableCandidate(S, Cand, Args);
9457 if (Cand->Function || Cand->IsSurrogate)
9458 Cands.push_back(Cand);
9459 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9460 // want to list every possible builtin candidate.
9464 std::sort(Cands.begin(), Cands.end(),
9465 CompareOverloadCandidatesForDisplay(S, Args.size()));
9467 bool ReportedAmbiguousConversions = false;
9469 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
9470 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9471 unsigned CandsShown = 0;
9472 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9473 OverloadCandidate *Cand = *I;
9475 // Set an arbitrary limit on the number of candidate functions we'll spam
9476 // the user with. FIXME: This limit should depend on details of the
9478 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
9484 NoteFunctionCandidate(S, Cand, Args.size());
9485 else if (Cand->IsSurrogate)
9486 NoteSurrogateCandidate(S, Cand);
9488 assert(Cand->Viable &&
9489 "Non-viable built-in candidates are not added to Cands.");
9490 // Generally we only see ambiguities including viable builtin
9491 // operators if overload resolution got screwed up by an
9492 // ambiguous user-defined conversion.
9494 // FIXME: It's quite possible for different conversions to see
9495 // different ambiguities, though.
9496 if (!ReportedAmbiguousConversions) {
9497 NoteAmbiguousUserConversions(S, OpLoc, Cand);
9498 ReportedAmbiguousConversions = true;
9501 // If this is a viable builtin, print it.
9502 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
9507 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
9510 static SourceLocation
9511 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9512 return Cand->Specialization ? Cand->Specialization->getLocation()
9516 struct CompareTemplateSpecCandidatesForDisplay {
9518 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9520 bool operator()(const TemplateSpecCandidate *L,
9521 const TemplateSpecCandidate *R) {
9522 // Fast-path this check.
9526 // Assuming that both candidates are not matches...
9528 // Sort by the ranking of deduction failures.
9529 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9530 return RankDeductionFailure(L->DeductionFailure) <
9531 RankDeductionFailure(R->DeductionFailure);
9533 // Sort everything else by location.
9534 SourceLocation LLoc = GetLocationForCandidate(L);
9535 SourceLocation RLoc = GetLocationForCandidate(R);
9537 // Put candidates without locations (e.g. builtins) at the end.
9538 if (LLoc.isInvalid())
9540 if (RLoc.isInvalid())
9543 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9547 /// Diagnose a template argument deduction failure.
9548 /// We are treating these failures as overload failures due to bad
9550 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9551 DiagnoseBadDeduction(S, Specialization, // pattern
9552 DeductionFailure, /*NumArgs=*/0);
9555 void TemplateSpecCandidateSet::destroyCandidates() {
9556 for (iterator i = begin(), e = end(); i != e; ++i) {
9557 i->DeductionFailure.Destroy();
9561 void TemplateSpecCandidateSet::clear() {
9562 destroyCandidates();
9566 /// NoteCandidates - When no template specialization match is found, prints
9567 /// diagnostic messages containing the non-matching specializations that form
9568 /// the candidate set.
9569 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9570 /// OCD == OCD_AllCandidates and Cand->Viable == false.
9571 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9572 // Sort the candidates by position (assuming no candidate is a match).
9573 // Sorting directly would be prohibitive, so we make a set of pointers
9575 SmallVector<TemplateSpecCandidate *, 32> Cands;
9576 Cands.reserve(size());
9577 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9578 if (Cand->Specialization)
9579 Cands.push_back(Cand);
9580 // Otherwise, this is a non-matching builtin candidate. We do not,
9581 // in general, want to list every possible builtin candidate.
9584 std::sort(Cands.begin(), Cands.end(),
9585 CompareTemplateSpecCandidatesForDisplay(S));
9587 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9588 // for generalization purposes (?).
9589 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9591 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9592 unsigned CandsShown = 0;
9593 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9594 TemplateSpecCandidate *Cand = *I;
9596 // Set an arbitrary limit on the number of candidates we'll spam
9597 // the user with. FIXME: This limit should depend on details of the
9599 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9603 assert(Cand->Specialization &&
9604 "Non-matching built-in candidates are not added to Cands.");
9605 Cand->NoteDeductionFailure(S);
9609 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9612 // [PossiblyAFunctionType] --> [Return]
9613 // NonFunctionType --> NonFunctionType
9615 // R (*)(A) --> R (A)
9616 // R (&)(A) --> R (A)
9617 // R (S::*)(A) --> R (A)
9618 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9619 QualType Ret = PossiblyAFunctionType;
9620 if (const PointerType *ToTypePtr =
9621 PossiblyAFunctionType->getAs<PointerType>())
9622 Ret = ToTypePtr->getPointeeType();
9623 else if (const ReferenceType *ToTypeRef =
9624 PossiblyAFunctionType->getAs<ReferenceType>())
9625 Ret = ToTypeRef->getPointeeType();
9626 else if (const MemberPointerType *MemTypePtr =
9627 PossiblyAFunctionType->getAs<MemberPointerType>())
9628 Ret = MemTypePtr->getPointeeType();
9630 Context.getCanonicalType(Ret).getUnqualifiedType();
9634 // A helper class to help with address of function resolution
9635 // - allows us to avoid passing around all those ugly parameters
9636 class AddressOfFunctionResolver
9640 const QualType& TargetType;
9641 QualType TargetFunctionType; // Extracted function type from target type
9644 //DeclAccessPair& ResultFunctionAccessPair;
9645 ASTContext& Context;
9647 bool TargetTypeIsNonStaticMemberFunction;
9648 bool FoundNonTemplateFunction;
9649 bool StaticMemberFunctionFromBoundPointer;
9651 OverloadExpr::FindResult OvlExprInfo;
9652 OverloadExpr *OvlExpr;
9653 TemplateArgumentListInfo OvlExplicitTemplateArgs;
9654 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
9655 TemplateSpecCandidateSet FailedCandidates;
9658 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9659 const QualType &TargetType, bool Complain)
9660 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9661 Complain(Complain), Context(S.getASTContext()),
9662 TargetTypeIsNonStaticMemberFunction(
9663 !!TargetType->getAs<MemberPointerType>()),
9664 FoundNonTemplateFunction(false),
9665 StaticMemberFunctionFromBoundPointer(false),
9666 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9667 OvlExpr(OvlExprInfo.Expression),
9668 FailedCandidates(OvlExpr->getNameLoc()) {
9669 ExtractUnqualifiedFunctionTypeFromTargetType();
9671 if (TargetFunctionType->isFunctionType()) {
9672 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9673 if (!UME->isImplicitAccess() &&
9674 !S.ResolveSingleFunctionTemplateSpecialization(UME))
9675 StaticMemberFunctionFromBoundPointer = true;
9676 } else if (OvlExpr->hasExplicitTemplateArgs()) {
9678 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9679 OvlExpr, false, &dap)) {
9680 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9681 if (!Method->isStatic()) {
9682 // If the target type is a non-function type and the function found
9683 // is a non-static member function, pretend as if that was the
9684 // target, it's the only possible type to end up with.
9685 TargetTypeIsNonStaticMemberFunction = true;
9687 // And skip adding the function if its not in the proper form.
9688 // We'll diagnose this due to an empty set of functions.
9689 if (!OvlExprInfo.HasFormOfMemberPointer)
9693 Matches.push_back(std::make_pair(dap, Fn));
9698 if (OvlExpr->hasExplicitTemplateArgs())
9699 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
9701 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9702 // C++ [over.over]p4:
9703 // If more than one function is selected, [...]
9704 if (Matches.size() > 1) {
9705 if (FoundNonTemplateFunction)
9706 EliminateAllTemplateMatches();
9708 EliminateAllExceptMostSpecializedTemplate();
9714 bool isTargetTypeAFunction() const {
9715 return TargetFunctionType->isFunctionType();
9718 // [ToType] [Return]
9720 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9721 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9722 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9723 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9724 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9727 // return true if any matching specializations were found
9728 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9729 const DeclAccessPair& CurAccessFunPair) {
9730 if (CXXMethodDecl *Method
9731 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9732 // Skip non-static function templates when converting to pointer, and
9733 // static when converting to member pointer.
9734 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9737 else if (TargetTypeIsNonStaticMemberFunction)
9740 // C++ [over.over]p2:
9741 // If the name is a function template, template argument deduction is
9742 // done (14.8.2.2), and if the argument deduction succeeds, the
9743 // resulting template argument list is used to generate a single
9744 // function template specialization, which is added to the set of
9745 // overloaded functions considered.
9746 FunctionDecl *Specialization = nullptr;
9747 TemplateDeductionInfo Info(FailedCandidates.getLocation());
9748 if (Sema::TemplateDeductionResult Result
9749 = S.DeduceTemplateArguments(FunctionTemplate,
9750 &OvlExplicitTemplateArgs,
9751 TargetFunctionType, Specialization,
9752 Info, /*InOverloadResolution=*/true)) {
9753 // Make a note of the failed deduction for diagnostics.
9754 FailedCandidates.addCandidate()
9755 .set(FunctionTemplate->getTemplatedDecl(),
9756 MakeDeductionFailureInfo(Context, Result, Info));
9760 // Template argument deduction ensures that we have an exact match or
9761 // compatible pointer-to-function arguments that would be adjusted by ICS.
9762 // This function template specicalization works.
9763 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9764 assert(S.isSameOrCompatibleFunctionType(
9765 Context.getCanonicalType(Specialization->getType()),
9766 Context.getCanonicalType(TargetFunctionType)));
9767 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9771 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9772 const DeclAccessPair& CurAccessFunPair) {
9773 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9774 // Skip non-static functions when converting to pointer, and static
9775 // when converting to member pointer.
9776 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9779 else if (TargetTypeIsNonStaticMemberFunction)
9782 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
9783 if (S.getLangOpts().CUDA)
9784 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9785 if (S.CheckCUDATarget(Caller, FunDecl))
9788 // If any candidate has a placeholder return type, trigger its deduction
9790 if (S.getLangOpts().CPlusPlus1y &&
9791 FunDecl->getReturnType()->isUndeducedType() &&
9792 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9796 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9797 FunDecl->getType()) ||
9798 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9800 Matches.push_back(std::make_pair(CurAccessFunPair,
9801 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
9802 FoundNonTemplateFunction = true;
9810 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9813 // If the overload expression doesn't have the form of a pointer to
9814 // member, don't try to convert it to a pointer-to-member type.
9815 if (IsInvalidFormOfPointerToMemberFunction())
9818 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9819 E = OvlExpr->decls_end();
9821 // Look through any using declarations to find the underlying function.
9822 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9824 // C++ [over.over]p3:
9825 // Non-member functions and static member functions match
9826 // targets of type "pointer-to-function" or "reference-to-function."
9827 // Nonstatic member functions match targets of
9828 // type "pointer-to-member-function."
9829 // Note that according to DR 247, the containing class does not matter.
9830 if (FunctionTemplateDecl *FunctionTemplate
9831 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9832 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9835 // If we have explicit template arguments supplied, skip non-templates.
9836 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9837 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9840 assert(Ret || Matches.empty());
9844 void EliminateAllExceptMostSpecializedTemplate() {
9845 // [...] and any given function template specialization F1 is
9846 // eliminated if the set contains a second function template
9847 // specialization whose function template is more specialized
9848 // than the function template of F1 according to the partial
9849 // ordering rules of 14.5.5.2.
9851 // The algorithm specified above is quadratic. We instead use a
9852 // two-pass algorithm (similar to the one used to identify the
9853 // best viable function in an overload set) that identifies the
9854 // best function template (if it exists).
9856 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9857 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9858 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
9860 // TODO: It looks like FailedCandidates does not serve much purpose
9861 // here, since the no_viable diagnostic has index 0.
9862 UnresolvedSetIterator Result = S.getMostSpecialized(
9863 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
9864 SourceExpr->getLocStart(), S.PDiag(),
9865 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
9866 .second->getDeclName(),
9867 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
9868 Complain, TargetFunctionType);
9870 if (Result != MatchesCopy.end()) {
9871 // Make it the first and only element
9872 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9873 Matches[0].second = cast<FunctionDecl>(*Result);
9878 void EliminateAllTemplateMatches() {
9879 // [...] any function template specializations in the set are
9880 // eliminated if the set also contains a non-template function, [...]
9881 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9882 if (Matches[I].second->getPrimaryTemplate() == nullptr)
9885 Matches[I] = Matches[--N];
9886 Matches.set_size(N);
9892 void ComplainNoMatchesFound() const {
9893 assert(Matches.empty());
9894 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9895 << OvlExpr->getName() << TargetFunctionType
9896 << OvlExpr->getSourceRange();
9897 if (FailedCandidates.empty())
9898 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9900 // We have some deduction failure messages. Use them to diagnose
9901 // the function templates, and diagnose the non-template candidates
9903 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9904 IEnd = OvlExpr->decls_end();
9906 if (FunctionDecl *Fun =
9907 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
9908 S.NoteOverloadCandidate(Fun, TargetFunctionType);
9909 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
9913 bool IsInvalidFormOfPointerToMemberFunction() const {
9914 return TargetTypeIsNonStaticMemberFunction &&
9915 !OvlExprInfo.HasFormOfMemberPointer;
9918 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9919 // TODO: Should we condition this on whether any functions might
9920 // have matched, or is it more appropriate to do that in callers?
9921 // TODO: a fixit wouldn't hurt.
9922 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9923 << TargetType << OvlExpr->getSourceRange();
9926 bool IsStaticMemberFunctionFromBoundPointer() const {
9927 return StaticMemberFunctionFromBoundPointer;
9930 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
9931 S.Diag(OvlExpr->getLocStart(),
9932 diag::err_invalid_form_pointer_member_function)
9933 << OvlExpr->getSourceRange();
9936 void ComplainOfInvalidConversion() const {
9937 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9938 << OvlExpr->getName() << TargetType;
9941 void ComplainMultipleMatchesFound() const {
9942 assert(Matches.size() > 1);
9943 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9944 << OvlExpr->getName()
9945 << OvlExpr->getSourceRange();
9946 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9949 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9951 int getNumMatches() const { return Matches.size(); }
9953 FunctionDecl* getMatchingFunctionDecl() const {
9954 if (Matches.size() != 1) return nullptr;
9955 return Matches[0].second;
9958 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9959 if (Matches.size() != 1) return nullptr;
9960 return &Matches[0].first;
9964 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9965 /// an overloaded function (C++ [over.over]), where @p From is an
9966 /// expression with overloaded function type and @p ToType is the type
9967 /// we're trying to resolve to. For example:
9973 /// int (*pfd)(double) = f; // selects f(double)
9976 /// This routine returns the resulting FunctionDecl if it could be
9977 /// resolved, and NULL otherwise. When @p Complain is true, this
9978 /// routine will emit diagnostics if there is an error.
9980 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9981 QualType TargetType,
9983 DeclAccessPair &FoundResult,
9984 bool *pHadMultipleCandidates) {
9985 assert(AddressOfExpr->getType() == Context.OverloadTy);
9987 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9989 int NumMatches = Resolver.getNumMatches();
9990 FunctionDecl *Fn = nullptr;
9991 if (NumMatches == 0 && Complain) {
9992 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9993 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9995 Resolver.ComplainNoMatchesFound();
9997 else if (NumMatches > 1 && Complain)
9998 Resolver.ComplainMultipleMatchesFound();
9999 else if (NumMatches == 1) {
10000 Fn = Resolver.getMatchingFunctionDecl();
10002 FoundResult = *Resolver.getMatchingFunctionAccessPair();
10004 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
10005 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
10007 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
10011 if (pHadMultipleCandidates)
10012 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
10016 /// \brief Given an expression that refers to an overloaded function, try to
10017 /// resolve that overloaded function expression down to a single function.
10019 /// This routine can only resolve template-ids that refer to a single function
10020 /// template, where that template-id refers to a single template whose template
10021 /// arguments are either provided by the template-id or have defaults,
10022 /// as described in C++0x [temp.arg.explicit]p3.
10024 /// If no template-ids are found, no diagnostics are emitted and NULL is
10027 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
10029 DeclAccessPair *FoundResult) {
10030 // C++ [over.over]p1:
10031 // [...] [Note: any redundant set of parentheses surrounding the
10032 // overloaded function name is ignored (5.1). ]
10033 // C++ [over.over]p1:
10034 // [...] The overloaded function name can be preceded by the &
10037 // If we didn't actually find any template-ids, we're done.
10038 if (!ovl->hasExplicitTemplateArgs())
10041 TemplateArgumentListInfo ExplicitTemplateArgs;
10042 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
10043 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
10045 // Look through all of the overloaded functions, searching for one
10046 // whose type matches exactly.
10047 FunctionDecl *Matched = nullptr;
10048 for (UnresolvedSetIterator I = ovl->decls_begin(),
10049 E = ovl->decls_end(); I != E; ++I) {
10050 // C++0x [temp.arg.explicit]p3:
10051 // [...] In contexts where deduction is done and fails, or in contexts
10052 // where deduction is not done, if a template argument list is
10053 // specified and it, along with any default template arguments,
10054 // identifies a single function template specialization, then the
10055 // template-id is an lvalue for the function template specialization.
10056 FunctionTemplateDecl *FunctionTemplate
10057 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
10059 // C++ [over.over]p2:
10060 // If the name is a function template, template argument deduction is
10061 // done (14.8.2.2), and if the argument deduction succeeds, the
10062 // resulting template argument list is used to generate a single
10063 // function template specialization, which is added to the set of
10064 // overloaded functions considered.
10065 FunctionDecl *Specialization = nullptr;
10066 TemplateDeductionInfo Info(FailedCandidates.getLocation());
10067 if (TemplateDeductionResult Result
10068 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
10069 Specialization, Info,
10070 /*InOverloadResolution=*/true)) {
10071 // Make a note of the failed deduction for diagnostics.
10072 // TODO: Actually use the failed-deduction info?
10073 FailedCandidates.addCandidate()
10074 .set(FunctionTemplate->getTemplatedDecl(),
10075 MakeDeductionFailureInfo(Context, Result, Info));
10079 assert(Specialization && "no specialization and no error?");
10081 // Multiple matches; we can't resolve to a single declaration.
10084 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10086 NoteAllOverloadCandidates(ovl);
10091 Matched = Specialization;
10092 if (FoundResult) *FoundResult = I.getPair();
10095 if (Matched && getLangOpts().CPlusPlus1y &&
10096 Matched->getReturnType()->isUndeducedType() &&
10097 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10106 // Resolve and fix an overloaded expression that can be resolved
10107 // because it identifies a single function template specialization.
10109 // Last three arguments should only be supplied if Complain = true
10111 // Return true if it was logically possible to so resolve the
10112 // expression, regardless of whether or not it succeeded. Always
10113 // returns true if 'complain' is set.
10114 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10115 ExprResult &SrcExpr, bool doFunctionPointerConverion,
10116 bool complain, const SourceRange& OpRangeForComplaining,
10117 QualType DestTypeForComplaining,
10118 unsigned DiagIDForComplaining) {
10119 assert(SrcExpr.get()->getType() == Context.OverloadTy);
10121 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
10123 DeclAccessPair found;
10124 ExprResult SingleFunctionExpression;
10125 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10126 ovl.Expression, /*complain*/ false, &found)) {
10127 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
10128 SrcExpr = ExprError();
10132 // It is only correct to resolve to an instance method if we're
10133 // resolving a form that's permitted to be a pointer to member.
10134 // Otherwise we'll end up making a bound member expression, which
10135 // is illegal in all the contexts we resolve like this.
10136 if (!ovl.HasFormOfMemberPointer &&
10137 isa<CXXMethodDecl>(fn) &&
10138 cast<CXXMethodDecl>(fn)->isInstance()) {
10139 if (!complain) return false;
10141 Diag(ovl.Expression->getExprLoc(),
10142 diag::err_bound_member_function)
10143 << 0 << ovl.Expression->getSourceRange();
10145 // TODO: I believe we only end up here if there's a mix of
10146 // static and non-static candidates (otherwise the expression
10147 // would have 'bound member' type, not 'overload' type).
10148 // Ideally we would note which candidate was chosen and why
10149 // the static candidates were rejected.
10150 SrcExpr = ExprError();
10154 // Fix the expression to refer to 'fn'.
10155 SingleFunctionExpression =
10156 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
10158 // If desired, do function-to-pointer decay.
10159 if (doFunctionPointerConverion) {
10160 SingleFunctionExpression =
10161 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
10162 if (SingleFunctionExpression.isInvalid()) {
10163 SrcExpr = ExprError();
10169 if (!SingleFunctionExpression.isUsable()) {
10171 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10172 << ovl.Expression->getName()
10173 << DestTypeForComplaining
10174 << OpRangeForComplaining
10175 << ovl.Expression->getQualifierLoc().getSourceRange();
10176 NoteAllOverloadCandidates(SrcExpr.get());
10178 SrcExpr = ExprError();
10185 SrcExpr = SingleFunctionExpression;
10189 /// \brief Add a single candidate to the overload set.
10190 static void AddOverloadedCallCandidate(Sema &S,
10191 DeclAccessPair FoundDecl,
10192 TemplateArgumentListInfo *ExplicitTemplateArgs,
10193 ArrayRef<Expr *> Args,
10194 OverloadCandidateSet &CandidateSet,
10195 bool PartialOverloading,
10197 NamedDecl *Callee = FoundDecl.getDecl();
10198 if (isa<UsingShadowDecl>(Callee))
10199 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10201 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
10202 if (ExplicitTemplateArgs) {
10203 assert(!KnownValid && "Explicit template arguments?");
10206 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
10207 PartialOverloading);
10211 if (FunctionTemplateDecl *FuncTemplate
10212 = dyn_cast<FunctionTemplateDecl>(Callee)) {
10213 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
10214 ExplicitTemplateArgs, Args, CandidateSet);
10218 assert(!KnownValid && "unhandled case in overloaded call candidate");
10221 /// \brief Add the overload candidates named by callee and/or found by argument
10222 /// dependent lookup to the given overload set.
10223 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
10224 ArrayRef<Expr *> Args,
10225 OverloadCandidateSet &CandidateSet,
10226 bool PartialOverloading) {
10229 // Verify that ArgumentDependentLookup is consistent with the rules
10230 // in C++0x [basic.lookup.argdep]p3:
10232 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10233 // and let Y be the lookup set produced by argument dependent
10234 // lookup (defined as follows). If X contains
10236 // -- a declaration of a class member, or
10238 // -- a block-scope function declaration that is not a
10239 // using-declaration, or
10241 // -- a declaration that is neither a function or a function
10244 // then Y is empty.
10246 if (ULE->requiresADL()) {
10247 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10248 E = ULE->decls_end(); I != E; ++I) {
10249 assert(!(*I)->getDeclContext()->isRecord());
10250 assert(isa<UsingShadowDecl>(*I) ||
10251 !(*I)->getDeclContext()->isFunctionOrMethod());
10252 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
10257 // It would be nice to avoid this copy.
10258 TemplateArgumentListInfo TABuffer;
10259 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10260 if (ULE->hasExplicitTemplateArgs()) {
10261 ULE->copyTemplateArgumentsInto(TABuffer);
10262 ExplicitTemplateArgs = &TABuffer;
10265 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10266 E = ULE->decls_end(); I != E; ++I)
10267 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10268 CandidateSet, PartialOverloading,
10269 /*KnownValid*/ true);
10271 if (ULE->requiresADL())
10272 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
10273 Args, ExplicitTemplateArgs,
10274 CandidateSet, PartialOverloading);
10277 /// Determine whether a declaration with the specified name could be moved into
10278 /// a different namespace.
10279 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10280 switch (Name.getCXXOverloadedOperator()) {
10281 case OO_New: case OO_Array_New:
10282 case OO_Delete: case OO_Array_Delete:
10290 /// Attempt to recover from an ill-formed use of a non-dependent name in a
10291 /// template, where the non-dependent name was declared after the template
10292 /// was defined. This is common in code written for a compilers which do not
10293 /// correctly implement two-stage name lookup.
10295 /// Returns true if a viable candidate was found and a diagnostic was issued.
10297 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10298 const CXXScopeSpec &SS, LookupResult &R,
10299 OverloadCandidateSet::CandidateSetKind CSK,
10300 TemplateArgumentListInfo *ExplicitTemplateArgs,
10301 ArrayRef<Expr *> Args) {
10302 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10305 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
10306 if (DC->isTransparentContext())
10309 SemaRef.LookupQualifiedName(R, DC);
10312 R.suppressDiagnostics();
10314 if (isa<CXXRecordDecl>(DC)) {
10315 // Don't diagnose names we find in classes; we get much better
10316 // diagnostics for these from DiagnoseEmptyLookup.
10321 OverloadCandidateSet Candidates(FnLoc, CSK);
10322 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10323 AddOverloadedCallCandidate(SemaRef, I.getPair(),
10324 ExplicitTemplateArgs, Args,
10325 Candidates, false, /*KnownValid*/ false);
10327 OverloadCandidateSet::iterator Best;
10328 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
10329 // No viable functions. Don't bother the user with notes for functions
10330 // which don't work and shouldn't be found anyway.
10335 // Find the namespaces where ADL would have looked, and suggest
10336 // declaring the function there instead.
10337 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10338 Sema::AssociatedClassSet AssociatedClasses;
10339 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
10340 AssociatedNamespaces,
10341 AssociatedClasses);
10342 Sema::AssociatedNamespaceSet SuggestedNamespaces;
10343 if (canBeDeclaredInNamespace(R.getLookupName())) {
10344 DeclContext *Std = SemaRef.getStdNamespace();
10345 for (Sema::AssociatedNamespaceSet::iterator
10346 it = AssociatedNamespaces.begin(),
10347 end = AssociatedNamespaces.end(); it != end; ++it) {
10348 // Never suggest declaring a function within namespace 'std'.
10349 if (Std && Std->Encloses(*it))
10352 // Never suggest declaring a function within a namespace with a
10353 // reserved name, like __gnu_cxx.
10354 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10356 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10359 SuggestedNamespaces.insert(*it);
10363 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10364 << R.getLookupName();
10365 if (SuggestedNamespaces.empty()) {
10366 SemaRef.Diag(Best->Function->getLocation(),
10367 diag::note_not_found_by_two_phase_lookup)
10368 << R.getLookupName() << 0;
10369 } else if (SuggestedNamespaces.size() == 1) {
10370 SemaRef.Diag(Best->Function->getLocation(),
10371 diag::note_not_found_by_two_phase_lookup)
10372 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
10374 // FIXME: It would be useful to list the associated namespaces here,
10375 // but the diagnostics infrastructure doesn't provide a way to produce
10376 // a localized representation of a list of items.
10377 SemaRef.Diag(Best->Function->getLocation(),
10378 diag::note_not_found_by_two_phase_lookup)
10379 << R.getLookupName() << 2;
10382 // Try to recover by calling this function.
10392 /// Attempt to recover from ill-formed use of a non-dependent operator in a
10393 /// template, where the non-dependent operator was declared after the template
10396 /// Returns true if a viable candidate was found and a diagnostic was issued.
10398 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10399 SourceLocation OpLoc,
10400 ArrayRef<Expr *> Args) {
10401 DeclarationName OpName =
10402 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10403 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10404 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
10405 OverloadCandidateSet::CSK_Operator,
10406 /*ExplicitTemplateArgs=*/nullptr, Args);
10410 class BuildRecoveryCallExprRAII {
10413 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10414 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10415 SemaRef.IsBuildingRecoveryCallExpr = true;
10418 ~BuildRecoveryCallExprRAII() {
10419 SemaRef.IsBuildingRecoveryCallExpr = false;
10425 /// Attempts to recover from a call where no functions were found.
10427 /// Returns true if new candidates were found.
10429 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10430 UnresolvedLookupExpr *ULE,
10431 SourceLocation LParenLoc,
10432 MutableArrayRef<Expr *> Args,
10433 SourceLocation RParenLoc,
10434 bool EmptyLookup, bool AllowTypoCorrection) {
10435 // Do not try to recover if it is already building a recovery call.
10436 // This stops infinite loops for template instantiations like
10438 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10439 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10441 if (SemaRef.IsBuildingRecoveryCallExpr)
10442 return ExprError();
10443 BuildRecoveryCallExprRAII RCE(SemaRef);
10446 SS.Adopt(ULE->getQualifierLoc());
10447 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
10449 TemplateArgumentListInfo TABuffer;
10450 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
10451 if (ULE->hasExplicitTemplateArgs()) {
10452 ULE->copyTemplateArgumentsInto(TABuffer);
10453 ExplicitTemplateArgs = &TABuffer;
10456 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10457 Sema::LookupOrdinaryName);
10458 FunctionCallFilterCCC Validator(SemaRef, Args.size(),
10459 ExplicitTemplateArgs != nullptr,
10460 dyn_cast<MemberExpr>(Fn));
10461 NoTypoCorrectionCCC RejectAll;
10462 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
10463 (CorrectionCandidateCallback*)&Validator :
10464 (CorrectionCandidateCallback*)&RejectAll;
10465 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
10466 OverloadCandidateSet::CSK_Normal,
10467 ExplicitTemplateArgs, Args) &&
10469 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
10470 ExplicitTemplateArgs, Args)))
10471 return ExprError();
10473 assert(!R.empty() && "lookup results empty despite recovery");
10475 // Build an implicit member call if appropriate. Just drop the
10476 // casts and such from the call, we don't really care.
10477 ExprResult NewFn = ExprError();
10478 if ((*R.begin())->isCXXClassMember())
10479 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10480 R, ExplicitTemplateArgs);
10481 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
10482 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
10483 ExplicitTemplateArgs);
10485 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10487 if (NewFn.isInvalid())
10488 return ExprError();
10490 // This shouldn't cause an infinite loop because we're giving it
10491 // an expression with viable lookup results, which should never
10493 return SemaRef.ActOnCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
10494 MultiExprArg(Args.data(), Args.size()),
10498 /// \brief Constructs and populates an OverloadedCandidateSet from
10499 /// the given function.
10500 /// \returns true when an the ExprResult output parameter has been set.
10501 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10502 UnresolvedLookupExpr *ULE,
10504 SourceLocation RParenLoc,
10505 OverloadCandidateSet *CandidateSet,
10506 ExprResult *Result) {
10508 if (ULE->requiresADL()) {
10509 // To do ADL, we must have found an unqualified name.
10510 assert(!ULE->getQualifier() && "qualified name with ADL");
10512 // We don't perform ADL for implicit declarations of builtins.
10513 // Verify that this was correctly set up.
10515 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10516 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10517 F->getBuiltinID() && F->isImplicit())
10518 llvm_unreachable("performing ADL for builtin");
10520 // We don't perform ADL in C.
10521 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
10525 UnbridgedCastsSet UnbridgedCasts;
10526 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
10527 *Result = ExprError();
10531 // Add the functions denoted by the callee to the set of candidate
10532 // functions, including those from argument-dependent lookup.
10533 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
10535 // If we found nothing, try to recover.
10536 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10537 // out if it fails.
10538 if (CandidateSet->empty()) {
10539 // In Microsoft mode, if we are inside a template class member function then
10540 // create a type dependent CallExpr. The goal is to postpone name lookup
10541 // to instantiation time to be able to search into type dependent base
10543 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
10544 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
10545 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
10546 Context.DependentTy, VK_RValue,
10548 CE->setTypeDependent(true);
10555 UnbridgedCasts.restore();
10559 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10560 /// the completed call expression. If overload resolution fails, emits
10561 /// diagnostics and returns ExprError()
10562 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10563 UnresolvedLookupExpr *ULE,
10564 SourceLocation LParenLoc,
10566 SourceLocation RParenLoc,
10568 OverloadCandidateSet *CandidateSet,
10569 OverloadCandidateSet::iterator *Best,
10570 OverloadingResult OverloadResult,
10571 bool AllowTypoCorrection) {
10572 if (CandidateSet->empty())
10573 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
10574 RParenLoc, /*EmptyLookup=*/true,
10575 AllowTypoCorrection);
10577 switch (OverloadResult) {
10579 FunctionDecl *FDecl = (*Best)->Function;
10580 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
10581 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10582 return ExprError();
10583 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10584 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10588 case OR_No_Viable_Function: {
10589 // Try to recover by looking for viable functions which the user might
10590 // have meant to call.
10591 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
10593 /*EmptyLookup=*/false,
10594 AllowTypoCorrection);
10595 if (!Recovery.isInvalid())
10598 SemaRef.Diag(Fn->getLocStart(),
10599 diag::err_ovl_no_viable_function_in_call)
10600 << ULE->getName() << Fn->getSourceRange();
10601 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10606 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
10607 << ULE->getName() << Fn->getSourceRange();
10608 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
10612 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10613 << (*Best)->Function->isDeleted()
10615 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10616 << Fn->getSourceRange();
10617 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
10619 // We emitted an error for the unvailable/deleted function call but keep
10620 // the call in the AST.
10621 FunctionDecl *FDecl = (*Best)->Function;
10622 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
10623 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10628 // Overload resolution failed.
10629 return ExprError();
10632 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
10633 /// (which eventually refers to the declaration Func) and the call
10634 /// arguments Args/NumArgs, attempt to resolve the function call down
10635 /// to a specific function. If overload resolution succeeds, returns
10636 /// the call expression produced by overload resolution.
10637 /// Otherwise, emits diagnostics and returns ExprError.
10638 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10639 UnresolvedLookupExpr *ULE,
10640 SourceLocation LParenLoc,
10642 SourceLocation RParenLoc,
10644 bool AllowTypoCorrection) {
10645 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
10646 OverloadCandidateSet::CSK_Normal);
10649 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10653 OverloadCandidateSet::iterator Best;
10654 OverloadingResult OverloadResult =
10655 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10657 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
10658 RParenLoc, ExecConfig, &CandidateSet,
10659 &Best, OverloadResult,
10660 AllowTypoCorrection);
10663 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
10664 return Functions.size() > 1 ||
10665 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10668 /// \brief Create a unary operation that may resolve to an overloaded
10671 /// \param OpLoc The location of the operator itself (e.g., '*').
10673 /// \param OpcIn The UnaryOperator::Opcode that describes this
10676 /// \param Fns The set of non-member functions that will be
10677 /// considered by overload resolution. The caller needs to build this
10678 /// set based on the context using, e.g.,
10679 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10680 /// set should not contain any member functions; those will be added
10681 /// by CreateOverloadedUnaryOp().
10683 /// \param Input The input argument.
10685 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10686 const UnresolvedSetImpl &Fns,
10688 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
10690 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10691 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10692 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10693 // TODO: provide better source location info.
10694 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10696 if (checkPlaceholderForOverload(*this, Input))
10697 return ExprError();
10699 Expr *Args[2] = { Input, nullptr };
10700 unsigned NumArgs = 1;
10702 // For post-increment and post-decrement, add the implicit '0' as
10703 // the second argument, so that we know this is a post-increment or
10705 if (Opc == UO_PostInc || Opc == UO_PostDec) {
10706 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
10707 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10712 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10714 if (Input->isTypeDependent()) {
10716 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
10717 VK_RValue, OK_Ordinary, OpLoc);
10719 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
10720 UnresolvedLookupExpr *Fn
10721 = UnresolvedLookupExpr::Create(Context, NamingClass,
10722 NestedNameSpecifierLoc(), OpNameInfo,
10723 /*ADL*/ true, IsOverloaded(Fns),
10724 Fns.begin(), Fns.end());
10725 return new (Context)
10726 CXXOperatorCallExpr(Context, Op, Fn, ArgsArray, Context.DependentTy,
10727 VK_RValue, OpLoc, false);
10730 // Build an empty overload set.
10731 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
10733 // Add the candidates from the given function set.
10734 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
10736 // Add operator candidates that are member functions.
10737 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10739 // Add candidates from ADL.
10740 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
10741 /*ExplicitTemplateArgs*/nullptr,
10744 // Add builtin operator candidates.
10745 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
10747 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10749 // Perform overload resolution.
10750 OverloadCandidateSet::iterator Best;
10751 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10753 // We found a built-in operator or an overloaded operator.
10754 FunctionDecl *FnDecl = Best->Function;
10757 // We matched an overloaded operator. Build a call to that
10760 // Convert the arguments.
10761 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10762 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
10764 ExprResult InputRes =
10765 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
10766 Best->FoundDecl, Method);
10767 if (InputRes.isInvalid())
10768 return ExprError();
10769 Input = InputRes.get();
10771 // Convert the arguments.
10772 ExprResult InputInit
10773 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
10775 FnDecl->getParamDecl(0)),
10778 if (InputInit.isInvalid())
10779 return ExprError();
10780 Input = InputInit.get();
10783 // Build the actual expression node.
10784 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
10785 HadMultipleCandidates, OpLoc);
10786 if (FnExpr.isInvalid())
10787 return ExprError();
10789 // Determine the result type.
10790 QualType ResultTy = FnDecl->getReturnType();
10791 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10792 ResultTy = ResultTy.getNonLValueExprType(Context);
10795 CallExpr *TheCall =
10796 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(), ArgsArray,
10797 ResultTy, VK, OpLoc, false);
10799 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
10800 return ExprError();
10802 return MaybeBindToTemporary(TheCall);
10804 // We matched a built-in operator. Convert the arguments, then
10805 // break out so that we will build the appropriate built-in
10807 ExprResult InputRes =
10808 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10809 Best->Conversions[0], AA_Passing);
10810 if (InputRes.isInvalid())
10811 return ExprError();
10812 Input = InputRes.get();
10817 case OR_No_Viable_Function:
10818 // This is an erroneous use of an operator which can be overloaded by
10819 // a non-member function. Check for non-member operators which were
10820 // defined too late to be candidates.
10821 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
10822 // FIXME: Recover by calling the found function.
10823 return ExprError();
10825 // No viable function; fall through to handling this as a
10826 // built-in operator, which will produce an error message for us.
10830 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10831 << UnaryOperator::getOpcodeStr(Opc)
10832 << Input->getType()
10833 << Input->getSourceRange();
10834 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
10835 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10836 return ExprError();
10839 Diag(OpLoc, diag::err_ovl_deleted_oper)
10840 << Best->Function->isDeleted()
10841 << UnaryOperator::getOpcodeStr(Opc)
10842 << getDeletedOrUnavailableSuffix(Best->Function)
10843 << Input->getSourceRange();
10844 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
10845 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10846 return ExprError();
10849 // Either we found no viable overloaded operator or we matched a
10850 // built-in operator. In either case, fall through to trying to
10851 // build a built-in operation.
10852 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
10855 /// \brief Create a binary operation that may resolve to an overloaded
10858 /// \param OpLoc The location of the operator itself (e.g., '+').
10860 /// \param OpcIn The BinaryOperator::Opcode that describes this
10863 /// \param Fns The set of non-member functions that will be
10864 /// considered by overload resolution. The caller needs to build this
10865 /// set based on the context using, e.g.,
10866 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10867 /// set should not contain any member functions; those will be added
10868 /// by CreateOverloadedBinOp().
10870 /// \param LHS Left-hand argument.
10871 /// \param RHS Right-hand argument.
10873 Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
10875 const UnresolvedSetImpl &Fns,
10876 Expr *LHS, Expr *RHS) {
10877 Expr *Args[2] = { LHS, RHS };
10878 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
10880 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10881 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10882 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10884 // If either side is type-dependent, create an appropriate dependent
10886 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10888 // If there are no functions to store, just build a dependent
10889 // BinaryOperator or CompoundAssignment.
10890 if (Opc <= BO_Assign || Opc > BO_OrAssign)
10891 return new (Context) BinaryOperator(
10892 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
10893 OpLoc, FPFeatures.fp_contract);
10895 return new (Context) CompoundAssignOperator(
10896 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
10897 Context.DependentTy, Context.DependentTy, OpLoc,
10898 FPFeatures.fp_contract);
10901 // FIXME: save results of ADL from here?
10902 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
10903 // TODO: provide better source location info in DNLoc component.
10904 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
10905 UnresolvedLookupExpr *Fn
10906 = UnresolvedLookupExpr::Create(Context, NamingClass,
10907 NestedNameSpecifierLoc(), OpNameInfo,
10908 /*ADL*/ true, IsOverloaded(Fns),
10909 Fns.begin(), Fns.end());
10910 return new (Context)
10911 CXXOperatorCallExpr(Context, Op, Fn, Args, Context.DependentTy,
10912 VK_RValue, OpLoc, FPFeatures.fp_contract);
10915 // Always do placeholder-like conversions on the RHS.
10916 if (checkPlaceholderForOverload(*this, Args[1]))
10917 return ExprError();
10919 // Do placeholder-like conversion on the LHS; note that we should
10920 // not get here with a PseudoObject LHS.
10921 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
10922 if (checkPlaceholderForOverload(*this, Args[0]))
10923 return ExprError();
10925 // If this is the assignment operator, we only perform overload resolution
10926 // if the left-hand side is a class or enumeration type. This is actually
10927 // a hack. The standard requires that we do overload resolution between the
10928 // various built-in candidates, but as DR507 points out, this can lead to
10929 // problems. So we do it this way, which pretty much follows what GCC does.
10930 // Note that we go the traditional code path for compound assignment forms.
10931 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
10932 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10934 // If this is the .* operator, which is not overloadable, just
10935 // create a built-in binary operator.
10936 if (Opc == BO_PtrMemD)
10937 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10939 // Build an empty overload set.
10940 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
10942 // Add the candidates from the given function set.
10943 AddFunctionCandidates(Fns, Args, CandidateSet, false);
10945 // Add operator candidates that are member functions.
10946 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
10948 // Add candidates from ADL.
10949 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
10950 /*ExplicitTemplateArgs*/ nullptr,
10953 // Add builtin operator candidates.
10954 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
10956 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10958 // Perform overload resolution.
10959 OverloadCandidateSet::iterator Best;
10960 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
10962 // We found a built-in operator or an overloaded operator.
10963 FunctionDecl *FnDecl = Best->Function;
10966 // We matched an overloaded operator. Build a call to that
10969 // Convert the arguments.
10970 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
10971 // Best->Access is only meaningful for class members.
10972 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
10975 PerformCopyInitialization(
10976 InitializedEntity::InitializeParameter(Context,
10977 FnDecl->getParamDecl(0)),
10978 SourceLocation(), Args[1]);
10979 if (Arg1.isInvalid())
10980 return ExprError();
10983 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
10984 Best->FoundDecl, Method);
10985 if (Arg0.isInvalid())
10986 return ExprError();
10987 Args[0] = Arg0.getAs<Expr>();
10988 Args[1] = RHS = Arg1.getAs<Expr>();
10990 // Convert the arguments.
10991 ExprResult Arg0 = PerformCopyInitialization(
10992 InitializedEntity::InitializeParameter(Context,
10993 FnDecl->getParamDecl(0)),
10994 SourceLocation(), Args[0]);
10995 if (Arg0.isInvalid())
10996 return ExprError();
10999 PerformCopyInitialization(
11000 InitializedEntity::InitializeParameter(Context,
11001 FnDecl->getParamDecl(1)),
11002 SourceLocation(), Args[1]);
11003 if (Arg1.isInvalid())
11004 return ExprError();
11005 Args[0] = LHS = Arg0.getAs<Expr>();
11006 Args[1] = RHS = Arg1.getAs<Expr>();
11009 // Build the actual expression node.
11010 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11012 HadMultipleCandidates, OpLoc);
11013 if (FnExpr.isInvalid())
11014 return ExprError();
11016 // Determine the result type.
11017 QualType ResultTy = FnDecl->getReturnType();
11018 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11019 ResultTy = ResultTy.getNonLValueExprType(Context);
11021 CXXOperatorCallExpr *TheCall =
11022 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.get(),
11023 Args, ResultTy, VK, OpLoc,
11024 FPFeatures.fp_contract);
11026 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
11028 return ExprError();
11030 ArrayRef<const Expr *> ArgsArray(Args, 2);
11031 // Cut off the implicit 'this'.
11032 if (isa<CXXMethodDecl>(FnDecl))
11033 ArgsArray = ArgsArray.slice(1);
11034 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
11035 TheCall->getSourceRange(), VariadicDoesNotApply);
11037 return MaybeBindToTemporary(TheCall);
11039 // We matched a built-in operator. Convert the arguments, then
11040 // break out so that we will build the appropriate built-in
11042 ExprResult ArgsRes0 =
11043 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11044 Best->Conversions[0], AA_Passing);
11045 if (ArgsRes0.isInvalid())
11046 return ExprError();
11047 Args[0] = ArgsRes0.get();
11049 ExprResult ArgsRes1 =
11050 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11051 Best->Conversions[1], AA_Passing);
11052 if (ArgsRes1.isInvalid())
11053 return ExprError();
11054 Args[1] = ArgsRes1.get();
11059 case OR_No_Viable_Function: {
11060 // C++ [over.match.oper]p9:
11061 // If the operator is the operator , [...] and there are no
11062 // viable functions, then the operator is assumed to be the
11063 // built-in operator and interpreted according to clause 5.
11064 if (Opc == BO_Comma)
11067 // For class as left operand for assignment or compound assigment
11068 // operator do not fall through to handling in built-in, but report that
11069 // no overloaded assignment operator found
11070 ExprResult Result = ExprError();
11071 if (Args[0]->getType()->isRecordType() &&
11072 Opc >= BO_Assign && Opc <= BO_OrAssign) {
11073 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11074 << BinaryOperator::getOpcodeStr(Opc)
11075 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11076 if (Args[0]->getType()->isIncompleteType()) {
11077 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11078 << Args[0]->getType()
11079 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11082 // This is an erroneous use of an operator which can be overloaded by
11083 // a non-member function. Check for non-member operators which were
11084 // defined too late to be candidates.
11085 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
11086 // FIXME: Recover by calling the found function.
11087 return ExprError();
11089 // No viable function; try to create a built-in operation, which will
11090 // produce an error. Then, show the non-viable candidates.
11091 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11093 assert(Result.isInvalid() &&
11094 "C++ binary operator overloading is missing candidates!");
11095 if (Result.isInvalid())
11096 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11097 BinaryOperator::getOpcodeStr(Opc), OpLoc);
11102 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
11103 << BinaryOperator::getOpcodeStr(Opc)
11104 << Args[0]->getType() << Args[1]->getType()
11105 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11106 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11107 BinaryOperator::getOpcodeStr(Opc), OpLoc);
11108 return ExprError();
11111 if (isImplicitlyDeleted(Best->Function)) {
11112 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11113 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
11114 << Context.getRecordType(Method->getParent())
11115 << getSpecialMember(Method);
11117 // The user probably meant to call this special member. Just
11118 // explain why it's deleted.
11119 NoteDeletedFunction(Method);
11120 return ExprError();
11122 Diag(OpLoc, diag::err_ovl_deleted_oper)
11123 << Best->Function->isDeleted()
11124 << BinaryOperator::getOpcodeStr(Opc)
11125 << getDeletedOrUnavailableSuffix(Best->Function)
11126 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11128 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11129 BinaryOperator::getOpcodeStr(Opc), OpLoc);
11130 return ExprError();
11133 // We matched a built-in operator; build it.
11134 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
11138 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11139 SourceLocation RLoc,
11140 Expr *Base, Expr *Idx) {
11141 Expr *Args[2] = { Base, Idx };
11142 DeclarationName OpName =
11143 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11145 // If either side is type-dependent, create an appropriate dependent
11147 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11149 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
11150 // CHECKME: no 'operator' keyword?
11151 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11152 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11153 UnresolvedLookupExpr *Fn
11154 = UnresolvedLookupExpr::Create(Context, NamingClass,
11155 NestedNameSpecifierLoc(), OpNameInfo,
11156 /*ADL*/ true, /*Overloaded*/ false,
11157 UnresolvedSetIterator(),
11158 UnresolvedSetIterator());
11159 // Can't add any actual overloads yet
11161 return new (Context)
11162 CXXOperatorCallExpr(Context, OO_Subscript, Fn, Args,
11163 Context.DependentTy, VK_RValue, RLoc, false);
11166 // Handle placeholders on both operands.
11167 if (checkPlaceholderForOverload(*this, Args[0]))
11168 return ExprError();
11169 if (checkPlaceholderForOverload(*this, Args[1]))
11170 return ExprError();
11172 // Build an empty overload set.
11173 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
11175 // Subscript can only be overloaded as a member function.
11177 // Add operator candidates that are member functions.
11178 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11180 // Add builtin operator candidates.
11181 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
11183 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11185 // Perform overload resolution.
11186 OverloadCandidateSet::iterator Best;
11187 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
11189 // We found a built-in operator or an overloaded operator.
11190 FunctionDecl *FnDecl = Best->Function;
11193 // We matched an overloaded operator. Build a call to that
11196 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
11198 // Convert the arguments.
11199 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
11201 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
11202 Best->FoundDecl, Method);
11203 if (Arg0.isInvalid())
11204 return ExprError();
11205 Args[0] = Arg0.get();
11207 // Convert the arguments.
11208 ExprResult InputInit
11209 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11211 FnDecl->getParamDecl(0)),
11214 if (InputInit.isInvalid())
11215 return ExprError();
11217 Args[1] = InputInit.getAs<Expr>();
11219 // Build the actual expression node.
11220 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11221 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
11222 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
11224 HadMultipleCandidates,
11225 OpLocInfo.getLoc(),
11226 OpLocInfo.getInfo());
11227 if (FnExpr.isInvalid())
11228 return ExprError();
11230 // Determine the result type
11231 QualType ResultTy = FnDecl->getReturnType();
11232 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11233 ResultTy = ResultTy.getNonLValueExprType(Context);
11235 CXXOperatorCallExpr *TheCall =
11236 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
11237 FnExpr.get(), Args,
11238 ResultTy, VK, RLoc,
11241 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
11242 return ExprError();
11244 return MaybeBindToTemporary(TheCall);
11246 // We matched a built-in operator. Convert the arguments, then
11247 // break out so that we will build the appropriate built-in
11249 ExprResult ArgsRes0 =
11250 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11251 Best->Conversions[0], AA_Passing);
11252 if (ArgsRes0.isInvalid())
11253 return ExprError();
11254 Args[0] = ArgsRes0.get();
11256 ExprResult ArgsRes1 =
11257 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11258 Best->Conversions[1], AA_Passing);
11259 if (ArgsRes1.isInvalid())
11260 return ExprError();
11261 Args[1] = ArgsRes1.get();
11267 case OR_No_Viable_Function: {
11268 if (CandidateSet.empty())
11269 Diag(LLoc, diag::err_ovl_no_oper)
11270 << Args[0]->getType() << /*subscript*/ 0
11271 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11273 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11274 << Args[0]->getType()
11275 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11276 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11278 return ExprError();
11282 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
11284 << Args[0]->getType() << Args[1]->getType()
11285 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11286 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
11288 return ExprError();
11291 Diag(LLoc, diag::err_ovl_deleted_oper)
11292 << Best->Function->isDeleted() << "[]"
11293 << getDeletedOrUnavailableSuffix(Best->Function)
11294 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11295 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
11297 return ExprError();
11300 // We matched a built-in operator; build it.
11301 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
11304 /// BuildCallToMemberFunction - Build a call to a member
11305 /// function. MemExpr is the expression that refers to the member
11306 /// function (and includes the object parameter), Args/NumArgs are the
11307 /// arguments to the function call (not including the object
11308 /// parameter). The caller needs to validate that the member
11309 /// expression refers to a non-static member function or an overloaded
11310 /// member function.
11312 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
11313 SourceLocation LParenLoc,
11315 SourceLocation RParenLoc) {
11316 assert(MemExprE->getType() == Context.BoundMemberTy ||
11317 MemExprE->getType() == Context.OverloadTy);
11319 // Dig out the member expression. This holds both the object
11320 // argument and the member function we're referring to.
11321 Expr *NakedMemExpr = MemExprE->IgnoreParens();
11323 // Determine whether this is a call to a pointer-to-member function.
11324 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11325 assert(op->getType() == Context.BoundMemberTy);
11326 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11329 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11331 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11332 QualType resultType = proto->getCallResultType(Context);
11333 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
11335 // Check that the object type isn't more qualified than the
11336 // member function we're calling.
11337 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11339 QualType objectType = op->getLHS()->getType();
11340 if (op->getOpcode() == BO_PtrMemI)
11341 objectType = objectType->castAs<PointerType>()->getPointeeType();
11342 Qualifiers objectQuals = objectType.getQualifiers();
11344 Qualifiers difference = objectQuals - funcQuals;
11345 difference.removeObjCGCAttr();
11346 difference.removeAddressSpace();
11348 std::string qualsString = difference.getAsString();
11349 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11350 << fnType.getUnqualifiedType()
11352 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11355 CXXMemberCallExpr *call
11356 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11357 resultType, valueKind, RParenLoc);
11359 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
11361 return ExprError();
11363 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
11364 return ExprError();
11366 if (CheckOtherCall(call, proto))
11367 return ExprError();
11369 return MaybeBindToTemporary(call);
11372 UnbridgedCastsSet UnbridgedCasts;
11373 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11374 return ExprError();
11376 MemberExpr *MemExpr;
11377 CXXMethodDecl *Method = nullptr;
11378 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
11379 NestedNameSpecifier *Qualifier = nullptr;
11380 if (isa<MemberExpr>(NakedMemExpr)) {
11381 MemExpr = cast<MemberExpr>(NakedMemExpr);
11382 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
11383 FoundDecl = MemExpr->getFoundDecl();
11384 Qualifier = MemExpr->getQualifier();
11385 UnbridgedCasts.restore();
11387 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
11388 Qualifier = UnresExpr->getQualifier();
11390 QualType ObjectType = UnresExpr->getBaseType();
11391 Expr::Classification ObjectClassification
11392 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11393 : UnresExpr->getBase()->Classify(Context);
11395 // Add overload candidates
11396 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
11397 OverloadCandidateSet::CSK_Normal);
11399 // FIXME: avoid copy.
11400 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
11401 if (UnresExpr->hasExplicitTemplateArgs()) {
11402 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11403 TemplateArgs = &TemplateArgsBuffer;
11406 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11407 E = UnresExpr->decls_end(); I != E; ++I) {
11409 NamedDecl *Func = *I;
11410 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11411 if (isa<UsingShadowDecl>(Func))
11412 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11415 // Microsoft supports direct constructor calls.
11416 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
11417 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
11418 Args, CandidateSet);
11419 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
11420 // If explicit template arguments were provided, we can't call a
11421 // non-template member function.
11425 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
11426 ObjectClassification, Args, CandidateSet,
11427 /*SuppressUserConversions=*/false);
11429 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
11430 I.getPair(), ActingDC, TemplateArgs,
11431 ObjectType, ObjectClassification,
11432 Args, CandidateSet,
11433 /*SuppressUsedConversions=*/false);
11437 DeclarationName DeclName = UnresExpr->getMemberName();
11439 UnbridgedCasts.restore();
11441 OverloadCandidateSet::iterator Best;
11442 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
11445 Method = cast<CXXMethodDecl>(Best->Function);
11446 FoundDecl = Best->FoundDecl;
11447 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
11448 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11449 return ExprError();
11450 // If FoundDecl is different from Method (such as if one is a template
11451 // and the other a specialization), make sure DiagnoseUseOfDecl is
11453 // FIXME: This would be more comprehensively addressed by modifying
11454 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11456 if (Method != FoundDecl.getDecl() &&
11457 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11458 return ExprError();
11461 case OR_No_Viable_Function:
11462 Diag(UnresExpr->getMemberLoc(),
11463 diag::err_ovl_no_viable_member_function_in_call)
11464 << DeclName << MemExprE->getSourceRange();
11465 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11466 // FIXME: Leaking incoming expressions!
11467 return ExprError();
11470 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
11471 << DeclName << MemExprE->getSourceRange();
11472 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11473 // FIXME: Leaking incoming expressions!
11474 return ExprError();
11477 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
11478 << Best->Function->isDeleted()
11480 << getDeletedOrUnavailableSuffix(Best->Function)
11481 << MemExprE->getSourceRange();
11482 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11483 // FIXME: Leaking incoming expressions!
11484 return ExprError();
11487 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
11489 // If overload resolution picked a static member, build a
11490 // non-member call based on that function.
11491 if (Method->isStatic()) {
11492 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11496 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
11499 QualType ResultType = Method->getReturnType();
11500 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11501 ResultType = ResultType.getNonLValueExprType(Context);
11503 assert(Method && "Member call to something that isn't a method?");
11504 CXXMemberCallExpr *TheCall =
11505 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
11506 ResultType, VK, RParenLoc);
11508 // Check for a valid return type.
11509 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
11511 return ExprError();
11513 // Convert the object argument (for a non-static member function call).
11514 // We only need to do this if there was actually an overload; otherwise
11515 // it was done at lookup.
11516 if (!Method->isStatic()) {
11517 ExprResult ObjectArg =
11518 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11519 FoundDecl, Method);
11520 if (ObjectArg.isInvalid())
11521 return ExprError();
11522 MemExpr->setBase(ObjectArg.get());
11525 // Convert the rest of the arguments
11526 const FunctionProtoType *Proto =
11527 Method->getType()->getAs<FunctionProtoType>();
11528 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
11530 return ExprError();
11532 DiagnoseSentinelCalls(Method, LParenLoc, Args);
11534 if (CheckFunctionCall(Method, TheCall, Proto))
11535 return ExprError();
11537 if ((isa<CXXConstructorDecl>(CurContext) ||
11538 isa<CXXDestructorDecl>(CurContext)) &&
11539 TheCall->getMethodDecl()->isPure()) {
11540 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11542 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
11543 Diag(MemExpr->getLocStart(),
11544 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11545 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11546 << MD->getParent()->getDeclName();
11548 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
11551 return MaybeBindToTemporary(TheCall);
11554 /// BuildCallToObjectOfClassType - Build a call to an object of class
11555 /// type (C++ [over.call.object]), which can end up invoking an
11556 /// overloaded function call operator (@c operator()) or performing a
11557 /// user-defined conversion on the object argument.
11559 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
11560 SourceLocation LParenLoc,
11562 SourceLocation RParenLoc) {
11563 if (checkPlaceholderForOverload(*this, Obj))
11564 return ExprError();
11565 ExprResult Object = Obj;
11567 UnbridgedCastsSet UnbridgedCasts;
11568 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
11569 return ExprError();
11571 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11572 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
11574 // C++ [over.call.object]p1:
11575 // If the primary-expression E in the function call syntax
11576 // evaluates to a class object of type "cv T", then the set of
11577 // candidate functions includes at least the function call
11578 // operators of T. The function call operators of T are obtained by
11579 // ordinary lookup of the name operator() in the context of
11581 OverloadCandidateSet CandidateSet(LParenLoc,
11582 OverloadCandidateSet::CSK_Operator);
11583 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
11585 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
11586 diag::err_incomplete_object_call, Object.get()))
11589 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11590 LookupQualifiedName(R, Record->getDecl());
11591 R.suppressDiagnostics();
11593 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11594 Oper != OperEnd; ++Oper) {
11595 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
11596 Object.get()->Classify(Context),
11597 Args, CandidateSet,
11598 /*SuppressUserConversions=*/ false);
11601 // C++ [over.call.object]p2:
11602 // In addition, for each (non-explicit in C++0x) conversion function
11603 // declared in T of the form
11605 // operator conversion-type-id () cv-qualifier;
11607 // where cv-qualifier is the same cv-qualification as, or a
11608 // greater cv-qualification than, cv, and where conversion-type-id
11609 // denotes the type "pointer to function of (P1,...,Pn) returning
11610 // R", or the type "reference to pointer to function of
11611 // (P1,...,Pn) returning R", or the type "reference to function
11612 // of (P1,...,Pn) returning R", a surrogate call function [...]
11613 // is also considered as a candidate function. Similarly,
11614 // surrogate call functions are added to the set of candidate
11615 // functions for each conversion function declared in an
11616 // accessible base class provided the function is not hidden
11617 // within T by another intervening declaration.
11618 std::pair<CXXRecordDecl::conversion_iterator,
11619 CXXRecordDecl::conversion_iterator> Conversions
11620 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
11621 for (CXXRecordDecl::conversion_iterator
11622 I = Conversions.first, E = Conversions.second; I != E; ++I) {
11624 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11625 if (isa<UsingShadowDecl>(D))
11626 D = cast<UsingShadowDecl>(D)->getTargetDecl();
11628 // Skip over templated conversion functions; they aren't
11630 if (isa<FunctionTemplateDecl>(D))
11633 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
11634 if (!Conv->isExplicit()) {
11635 // Strip the reference type (if any) and then the pointer type (if
11636 // any) to get down to what might be a function type.
11637 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11638 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11639 ConvType = ConvPtrType->getPointeeType();
11641 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11643 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
11644 Object.get(), Args, CandidateSet);
11649 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11651 // Perform overload resolution.
11652 OverloadCandidateSet::iterator Best;
11653 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
11656 // Overload resolution succeeded; we'll build the appropriate call
11660 case OR_No_Viable_Function:
11661 if (CandidateSet.empty())
11662 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
11663 << Object.get()->getType() << /*call*/ 1
11664 << Object.get()->getSourceRange();
11666 Diag(Object.get()->getLocStart(),
11667 diag::err_ovl_no_viable_object_call)
11668 << Object.get()->getType() << Object.get()->getSourceRange();
11669 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11673 Diag(Object.get()->getLocStart(),
11674 diag::err_ovl_ambiguous_object_call)
11675 << Object.get()->getType() << Object.get()->getSourceRange();
11676 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11680 Diag(Object.get()->getLocStart(),
11681 diag::err_ovl_deleted_object_call)
11682 << Best->Function->isDeleted()
11683 << Object.get()->getType()
11684 << getDeletedOrUnavailableSuffix(Best->Function)
11685 << Object.get()->getSourceRange();
11686 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11690 if (Best == CandidateSet.end())
11693 UnbridgedCasts.restore();
11695 if (Best->Function == nullptr) {
11696 // Since there is no function declaration, this is one of the
11697 // surrogate candidates. Dig out the conversion function.
11698 CXXConversionDecl *Conv
11699 = cast<CXXConversionDecl>(
11700 Best->Conversions[0].UserDefined.ConversionFunction);
11702 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
11704 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11705 return ExprError();
11706 assert(Conv == Best->FoundDecl.getDecl() &&
11707 "Found Decl & conversion-to-functionptr should be same, right?!");
11708 // We selected one of the surrogate functions that converts the
11709 // object parameter to a function pointer. Perform the conversion
11710 // on the object argument, then let ActOnCallExpr finish the job.
11712 // Create an implicit member expr to refer to the conversion operator.
11713 // and then call it.
11714 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11715 Conv, HadMultipleCandidates);
11716 if (Call.isInvalid())
11717 return ExprError();
11718 // Record usage of conversion in an implicit cast.
11719 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
11720 CK_UserDefinedConversion, Call.get(),
11721 nullptr, VK_RValue);
11723 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
11726 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
11728 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11729 // that calls this method, using Object for the implicit object
11730 // parameter and passing along the remaining arguments.
11731 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11733 // An error diagnostic has already been printed when parsing the declaration.
11734 if (Method->isInvalidDecl())
11735 return ExprError();
11737 const FunctionProtoType *Proto =
11738 Method->getType()->getAs<FunctionProtoType>();
11740 unsigned NumParams = Proto->getNumParams();
11742 DeclarationNameInfo OpLocInfo(
11743 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11744 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
11745 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11746 HadMultipleCandidates,
11747 OpLocInfo.getLoc(),
11748 OpLocInfo.getInfo());
11749 if (NewFn.isInvalid())
11752 // Build the full argument list for the method call (the implicit object
11753 // parameter is placed at the beginning of the list).
11754 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
11755 MethodArgs[0] = Object.get();
11756 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11758 // Once we've built TheCall, all of the expressions are properly
11760 QualType ResultTy = Method->getReturnType();
11761 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11762 ResultTy = ResultTy.getNonLValueExprType(Context);
11764 CXXOperatorCallExpr *TheCall = new (Context)
11765 CXXOperatorCallExpr(Context, OO_Call, NewFn.get(),
11766 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
11767 ResultTy, VK, RParenLoc, false);
11768 MethodArgs.reset();
11770 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
11773 // We may have default arguments. If so, we need to allocate more
11774 // slots in the call for them.
11775 if (Args.size() < NumParams)
11776 TheCall->setNumArgs(Context, NumParams + 1);
11778 bool IsError = false;
11780 // Initialize the implicit object parameter.
11781 ExprResult ObjRes =
11782 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
11783 Best->FoundDecl, Method);
11784 if (ObjRes.isInvalid())
11788 TheCall->setArg(0, Object.get());
11790 // Check the argument types.
11791 for (unsigned i = 0; i != NumParams; i++) {
11793 if (i < Args.size()) {
11796 // Pass the argument.
11798 ExprResult InputInit
11799 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
11801 Method->getParamDecl(i)),
11802 SourceLocation(), Arg);
11804 IsError |= InputInit.isInvalid();
11805 Arg = InputInit.getAs<Expr>();
11808 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11809 if (DefArg.isInvalid()) {
11814 Arg = DefArg.getAs<Expr>();
11817 TheCall->setArg(i + 1, Arg);
11820 // If this is a variadic call, handle args passed through "...".
11821 if (Proto->isVariadic()) {
11822 // Promote the arguments (C99 6.5.2.2p7).
11823 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
11824 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
11826 IsError |= Arg.isInvalid();
11827 TheCall->setArg(i + 1, Arg.get());
11831 if (IsError) return true;
11833 DiagnoseSentinelCalls(Method, LParenLoc, Args);
11835 if (CheckFunctionCall(Method, TheCall, Proto))
11838 return MaybeBindToTemporary(TheCall);
11841 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
11842 /// (if one exists), where @c Base is an expression of class type and
11843 /// @c Member is the name of the member we're trying to find.
11845 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
11846 bool *NoArrowOperatorFound) {
11847 assert(Base->getType()->isRecordType() &&
11848 "left-hand side must have class type");
11850 if (checkPlaceholderForOverload(*this, Base))
11851 return ExprError();
11853 SourceLocation Loc = Base->getExprLoc();
11855 // C++ [over.ref]p1:
11857 // [...] An expression x->m is interpreted as (x.operator->())->m
11858 // for a class object x of type T if T::operator->() exists and if
11859 // the operator is selected as the best match function by the
11860 // overload resolution mechanism (13.3).
11861 DeclarationName OpName =
11862 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
11863 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
11864 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
11866 if (RequireCompleteType(Loc, Base->getType(),
11867 diag::err_typecheck_incomplete_tag, Base))
11868 return ExprError();
11870 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11871 LookupQualifiedName(R, BaseRecord->getDecl());
11872 R.suppressDiagnostics();
11874 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
11875 Oper != OperEnd; ++Oper) {
11876 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11877 None, CandidateSet, /*SuppressUserConversions=*/false);
11880 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11882 // Perform overload resolution.
11883 OverloadCandidateSet::iterator Best;
11884 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
11886 // Overload resolution succeeded; we'll build the call below.
11889 case OR_No_Viable_Function:
11890 if (CandidateSet.empty()) {
11891 QualType BaseType = Base->getType();
11892 if (NoArrowOperatorFound) {
11893 // Report this specific error to the caller instead of emitting a
11894 // diagnostic, as requested.
11895 *NoArrowOperatorFound = true;
11896 return ExprError();
11898 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11899 << BaseType << Base->getSourceRange();
11900 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
11901 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
11902 << FixItHint::CreateReplacement(OpLoc, ".");
11905 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11906 << "operator->" << Base->getSourceRange();
11907 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11908 return ExprError();
11911 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11912 << "->" << Base->getType() << Base->getSourceRange();
11913 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
11914 return ExprError();
11917 Diag(OpLoc, diag::err_ovl_deleted_oper)
11918 << Best->Function->isDeleted()
11920 << getDeletedOrUnavailableSuffix(Best->Function)
11921 << Base->getSourceRange();
11922 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
11923 return ExprError();
11926 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
11928 // Convert the object parameter.
11929 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11930 ExprResult BaseResult =
11931 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
11932 Best->FoundDecl, Method);
11933 if (BaseResult.isInvalid())
11934 return ExprError();
11935 Base = BaseResult.get();
11937 // Build the operator call.
11938 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
11939 HadMultipleCandidates, OpLoc);
11940 if (FnExpr.isInvalid())
11941 return ExprError();
11943 QualType ResultTy = Method->getReturnType();
11944 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11945 ResultTy = ResultTy.getNonLValueExprType(Context);
11946 CXXOperatorCallExpr *TheCall =
11947 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.get(),
11948 Base, ResultTy, VK, OpLoc, false);
11950 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
11951 return ExprError();
11953 return MaybeBindToTemporary(TheCall);
11956 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11957 /// a literal operator described by the provided lookup results.
11958 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11959 DeclarationNameInfo &SuffixInfo,
11960 ArrayRef<Expr*> Args,
11961 SourceLocation LitEndLoc,
11962 TemplateArgumentListInfo *TemplateArgs) {
11963 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
11965 OverloadCandidateSet CandidateSet(UDSuffixLoc,
11966 OverloadCandidateSet::CSK_Normal);
11967 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11970 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11972 // Perform overload resolution. This will usually be trivial, but might need
11973 // to perform substitutions for a literal operator template.
11974 OverloadCandidateSet::iterator Best;
11975 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11980 case OR_No_Viable_Function:
11981 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11982 << R.getLookupName();
11983 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11984 return ExprError();
11987 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11988 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11989 return ExprError();
11992 FunctionDecl *FD = Best->Function;
11993 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11994 HadMultipleCandidates,
11995 SuffixInfo.getLoc(),
11996 SuffixInfo.getInfo());
11997 if (Fn.isInvalid())
12000 // Check the argument types. This should almost always be a no-op, except
12001 // that array-to-pointer decay is applied to string literals.
12003 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
12004 ExprResult InputInit = PerformCopyInitialization(
12005 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
12006 SourceLocation(), Args[ArgIdx]);
12007 if (InputInit.isInvalid())
12009 ConvArgs[ArgIdx] = InputInit.get();
12012 QualType ResultTy = FD->getReturnType();
12013 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12014 ResultTy = ResultTy.getNonLValueExprType(Context);
12016 UserDefinedLiteral *UDL =
12017 new (Context) UserDefinedLiteral(Context, Fn.get(),
12018 llvm::makeArrayRef(ConvArgs, Args.size()),
12019 ResultTy, VK, LitEndLoc, UDSuffixLoc);
12021 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
12022 return ExprError();
12024 if (CheckFunctionCall(FD, UDL, nullptr))
12025 return ExprError();
12027 return MaybeBindToTemporary(UDL);
12030 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
12031 /// given LookupResult is non-empty, it is assumed to describe a member which
12032 /// will be invoked. Otherwise, the function will be found via argument
12033 /// dependent lookup.
12034 /// CallExpr is set to a valid expression and FRS_Success returned on success,
12035 /// otherwise CallExpr is set to ExprError() and some non-success value
12037 Sema::ForRangeStatus
12038 Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
12039 SourceLocation RangeLoc, VarDecl *Decl,
12040 BeginEndFunction BEF,
12041 const DeclarationNameInfo &NameInfo,
12042 LookupResult &MemberLookup,
12043 OverloadCandidateSet *CandidateSet,
12044 Expr *Range, ExprResult *CallExpr) {
12045 CandidateSet->clear();
12046 if (!MemberLookup.empty()) {
12047 ExprResult MemberRef =
12048 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
12049 /*IsPtr=*/false, CXXScopeSpec(),
12050 /*TemplateKWLoc=*/SourceLocation(),
12051 /*FirstQualifierInScope=*/nullptr,
12053 /*TemplateArgs=*/nullptr);
12054 if (MemberRef.isInvalid()) {
12055 *CallExpr = ExprError();
12056 Diag(Range->getLocStart(), diag::note_in_for_range)
12057 << RangeLoc << BEF << Range->getType();
12058 return FRS_DiagnosticIssued;
12060 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
12061 if (CallExpr->isInvalid()) {
12062 *CallExpr = ExprError();
12063 Diag(Range->getLocStart(), diag::note_in_for_range)
12064 << RangeLoc << BEF << Range->getType();
12065 return FRS_DiagnosticIssued;
12068 UnresolvedSet<0> FoundNames;
12069 UnresolvedLookupExpr *Fn =
12070 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
12071 NestedNameSpecifierLoc(), NameInfo,
12072 /*NeedsADL=*/true, /*Overloaded=*/false,
12073 FoundNames.begin(), FoundNames.end());
12075 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
12076 CandidateSet, CallExpr);
12077 if (CandidateSet->empty() || CandidateSetError) {
12078 *CallExpr = ExprError();
12079 return FRS_NoViableFunction;
12081 OverloadCandidateSet::iterator Best;
12082 OverloadingResult OverloadResult =
12083 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12085 if (OverloadResult == OR_No_Viable_Function) {
12086 *CallExpr = ExprError();
12087 return FRS_NoViableFunction;
12089 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
12090 Loc, nullptr, CandidateSet, &Best,
12092 /*AllowTypoCorrection=*/false);
12093 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12094 *CallExpr = ExprError();
12095 Diag(Range->getLocStart(), diag::note_in_for_range)
12096 << RangeLoc << BEF << Range->getType();
12097 return FRS_DiagnosticIssued;
12100 return FRS_Success;
12104 /// FixOverloadedFunctionReference - E is an expression that refers to
12105 /// a C++ overloaded function (possibly with some parentheses and
12106 /// perhaps a '&' around it). We have resolved the overloaded function
12107 /// to the function declaration Fn, so patch up the expression E to
12108 /// refer (possibly indirectly) to Fn. Returns the new expr.
12109 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
12110 FunctionDecl *Fn) {
12111 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
12112 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12114 if (SubExpr == PE->getSubExpr())
12117 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
12120 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12121 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12123 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
12124 SubExpr->getType()) &&
12125 "Implicit cast type cannot be determined from overload");
12126 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
12127 if (SubExpr == ICE->getSubExpr())
12130 return ImplicitCastExpr::Create(Context, ICE->getType(),
12131 ICE->getCastKind(),
12133 ICE->getValueKind());
12136 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
12137 assert(UnOp->getOpcode() == UO_AddrOf &&
12138 "Can only take the address of an overloaded function");
12139 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12140 if (Method->isStatic()) {
12141 // Do nothing: static member functions aren't any different
12142 // from non-member functions.
12144 // Fix the subexpression, which really has to be an
12145 // UnresolvedLookupExpr holding an overloaded member function
12147 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12149 if (SubExpr == UnOp->getSubExpr())
12152 assert(isa<DeclRefExpr>(SubExpr)
12153 && "fixed to something other than a decl ref");
12154 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12155 && "fixed to a member ref with no nested name qualifier");
12157 // We have taken the address of a pointer to member
12158 // function. Perform the computation here so that we get the
12159 // appropriate pointer to member type.
12161 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12162 QualType MemPtrType
12163 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12165 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12166 VK_RValue, OK_Ordinary,
12167 UnOp->getOperatorLoc());
12170 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12172 if (SubExpr == UnOp->getSubExpr())
12175 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
12176 Context.getPointerType(SubExpr->getType()),
12177 VK_RValue, OK_Ordinary,
12178 UnOp->getOperatorLoc());
12181 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
12182 // FIXME: avoid copy.
12183 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12184 if (ULE->hasExplicitTemplateArgs()) {
12185 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12186 TemplateArgs = &TemplateArgsBuffer;
12189 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12190 ULE->getQualifierLoc(),
12191 ULE->getTemplateKeywordLoc(),
12193 /*enclosing*/ false, // FIXME?
12199 MarkDeclRefReferenced(DRE);
12200 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12204 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
12205 // FIXME: avoid copy.
12206 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
12207 if (MemExpr->hasExplicitTemplateArgs()) {
12208 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12209 TemplateArgs = &TemplateArgsBuffer;
12214 // If we're filling in a static method where we used to have an
12215 // implicit member access, rewrite to a simple decl ref.
12216 if (MemExpr->isImplicitAccess()) {
12217 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12218 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12219 MemExpr->getQualifierLoc(),
12220 MemExpr->getTemplateKeywordLoc(),
12222 /*enclosing*/ false,
12223 MemExpr->getMemberLoc(),
12228 MarkDeclRefReferenced(DRE);
12229 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12232 SourceLocation Loc = MemExpr->getMemberLoc();
12233 if (MemExpr->getQualifier())
12234 Loc = MemExpr->getQualifierLoc().getBeginLoc();
12235 CheckCXXThisCapture(Loc);
12236 Base = new (Context) CXXThisExpr(Loc,
12237 MemExpr->getBaseType(),
12238 /*isImplicit=*/true);
12241 Base = MemExpr->getBase();
12243 ExprValueKind valueKind;
12245 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12246 valueKind = VK_LValue;
12247 type = Fn->getType();
12249 valueKind = VK_RValue;
12250 type = Context.BoundMemberTy;
12253 MemberExpr *ME = MemberExpr::Create(Context, Base,
12254 MemExpr->isArrow(),
12255 MemExpr->getQualifierLoc(),
12256 MemExpr->getTemplateKeywordLoc(),
12259 MemExpr->getMemberNameInfo(),
12261 type, valueKind, OK_Ordinary);
12262 ME->setHadMultipleCandidates(true);
12263 MarkMemberReferenced(ME);
12267 llvm_unreachable("Invalid reference to overloaded function");
12270 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
12271 DeclAccessPair Found,
12272 FunctionDecl *Fn) {
12273 return FixOverloadedFunctionReference(E.get(), Found, Fn);
12276 } // end namespace clang