1 //===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file provides Sema routines for C++ overloading.
11 //===----------------------------------------------------------------------===//
13 #include "clang/Sema/Overload.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/AST/TypeOrdering.h"
21 #include "clang/Basic/Diagnostic.h"
22 #include "clang/Basic/DiagnosticOptions.h"
23 #include "clang/Basic/PartialDiagnostic.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "clang/Sema/Initialization.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/SemaInternal.h"
28 #include "clang/Sema/Template.h"
29 #include "clang/Sema/TemplateDeduction.h"
30 #include "llvm/ADT/DenseSet.h"
31 #include "llvm/ADT/Optional.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
38 using namespace clang;
41 static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
42 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
43 return P->hasAttr<PassObjectSizeAttr>();
47 /// A convenience routine for creating a decayed reference to a function.
49 CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
50 const Expr *Base, bool HadMultipleCandidates,
51 SourceLocation Loc = SourceLocation(),
52 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
53 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
55 // If FoundDecl is different from Fn (such as if one is a template
56 // and the other a specialization), make sure DiagnoseUseOfDecl is
58 // FIXME: This would be more comprehensively addressed by modifying
59 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
61 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
63 DeclRefExpr *DRE = new (S.Context)
64 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
65 if (HadMultipleCandidates)
66 DRE->setHadMultipleCandidates(true);
68 S.MarkDeclRefReferenced(DRE, Base);
69 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
70 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
71 S.ResolveExceptionSpec(Loc, FPT);
72 DRE->setType(Fn->getType());
75 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
76 CK_FunctionToPointerDecay);
79 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
80 bool InOverloadResolution,
81 StandardConversionSequence &SCS,
83 bool AllowObjCWritebackConversion);
85 static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
87 bool InOverloadResolution,
88 StandardConversionSequence &SCS,
90 static OverloadingResult
91 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
92 UserDefinedConversionSequence& User,
93 OverloadCandidateSet& Conversions,
95 bool AllowObjCConversionOnExplicit);
98 static ImplicitConversionSequence::CompareKind
99 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
100 const StandardConversionSequence& SCS1,
101 const StandardConversionSequence& SCS2);
103 static ImplicitConversionSequence::CompareKind
104 CompareQualificationConversions(Sema &S,
105 const StandardConversionSequence& SCS1,
106 const StandardConversionSequence& SCS2);
108 static ImplicitConversionSequence::CompareKind
109 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
110 const StandardConversionSequence& SCS1,
111 const StandardConversionSequence& SCS2);
113 /// GetConversionRank - Retrieve the implicit conversion rank
114 /// corresponding to the given implicit conversion kind.
115 ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
116 static const ImplicitConversionRank
117 Rank[(int)ICK_Num_Conversion_Kinds] = {
137 ICR_OCL_Scalar_Widening,
138 ICR_Complex_Real_Conversion,
141 ICR_Writeback_Conversion,
142 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
143 // it was omitted by the patch that added
144 // ICK_Zero_Event_Conversion
146 ICR_C_Conversion_Extension
148 return Rank[(int)Kind];
151 /// GetImplicitConversionName - Return the name of this kind of
152 /// implicit conversion.
153 static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
154 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
158 "Function-to-pointer",
159 "Function pointer conversion",
161 "Integral promotion",
162 "Floating point promotion",
164 "Integral conversion",
165 "Floating conversion",
166 "Complex conversion",
167 "Floating-integral conversion",
168 "Pointer conversion",
169 "Pointer-to-member conversion",
170 "Boolean conversion",
171 "Compatible-types conversion",
172 "Derived-to-base conversion",
175 "Complex-real conversion",
176 "Block Pointer conversion",
177 "Transparent Union Conversion",
178 "Writeback conversion",
179 "OpenCL Zero Event Conversion",
180 "C specific type conversion",
181 "Incompatible pointer conversion"
186 /// StandardConversionSequence - Set the standard conversion
187 /// sequence to the identity conversion.
188 void StandardConversionSequence::setAsIdentityConversion() {
189 First = ICK_Identity;
190 Second = ICK_Identity;
191 Third = ICK_Identity;
192 DeprecatedStringLiteralToCharPtr = false;
193 QualificationIncludesObjCLifetime = false;
194 ReferenceBinding = false;
195 DirectBinding = false;
196 IsLvalueReference = true;
197 BindsToFunctionLvalue = false;
198 BindsToRvalue = false;
199 BindsImplicitObjectArgumentWithoutRefQualifier = false;
200 ObjCLifetimeConversionBinding = false;
201 CopyConstructor = nullptr;
204 /// getRank - Retrieve the rank of this standard conversion sequence
205 /// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
206 /// implicit conversions.
207 ImplicitConversionRank StandardConversionSequence::getRank() const {
208 ImplicitConversionRank Rank = ICR_Exact_Match;
209 if (GetConversionRank(First) > Rank)
210 Rank = GetConversionRank(First);
211 if (GetConversionRank(Second) > Rank)
212 Rank = GetConversionRank(Second);
213 if (GetConversionRank(Third) > Rank)
214 Rank = GetConversionRank(Third);
218 /// isPointerConversionToBool - Determines whether this conversion is
219 /// a conversion of a pointer or pointer-to-member to bool. This is
220 /// used as part of the ranking of standard conversion sequences
221 /// (C++ 13.3.3.2p4).
222 bool StandardConversionSequence::isPointerConversionToBool() const {
223 // Note that FromType has not necessarily been transformed by the
224 // array-to-pointer or function-to-pointer implicit conversions, so
225 // check for their presence as well as checking whether FromType is
227 if (getToType(1)->isBooleanType() &&
228 (getFromType()->isPointerType() ||
229 getFromType()->isMemberPointerType() ||
230 getFromType()->isObjCObjectPointerType() ||
231 getFromType()->isBlockPointerType() ||
232 getFromType()->isNullPtrType() ||
233 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
239 /// isPointerConversionToVoidPointer - Determines whether this
240 /// conversion is a conversion of a pointer to a void pointer. This is
241 /// used as part of the ranking of standard conversion sequences (C++
244 StandardConversionSequence::
245 isPointerConversionToVoidPointer(ASTContext& Context) const {
246 QualType FromType = getFromType();
247 QualType ToType = getToType(1);
249 // Note that FromType has not necessarily been transformed by the
250 // array-to-pointer implicit conversion, so check for its presence
251 // and redo the conversion to get a pointer.
252 if (First == ICK_Array_To_Pointer)
253 FromType = Context.getArrayDecayedType(FromType);
255 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
256 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
257 return ToPtrType->getPointeeType()->isVoidType();
262 /// Skip any implicit casts which could be either part of a narrowing conversion
263 /// or after one in an implicit conversion.
264 static const Expr *IgnoreNarrowingConversion(ASTContext &Ctx,
265 const Expr *Converted) {
266 // We can have cleanups wrapping the converted expression; these need to be
267 // preserved so that destructors run if necessary.
268 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
270 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
271 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
275 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
276 switch (ICE->getCastKind()) {
278 case CK_IntegralCast:
279 case CK_IntegralToBoolean:
280 case CK_IntegralToFloating:
281 case CK_BooleanToSignedIntegral:
282 case CK_FloatingToIntegral:
283 case CK_FloatingToBoolean:
284 case CK_FloatingCast:
285 Converted = ICE->getSubExpr();
296 /// Check if this standard conversion sequence represents a narrowing
297 /// conversion, according to C++11 [dcl.init.list]p7.
299 /// \param Ctx The AST context.
300 /// \param Converted The result of applying this standard conversion sequence.
301 /// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
302 /// value of the expression prior to the narrowing conversion.
303 /// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
304 /// type of the expression prior to the narrowing conversion.
305 /// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
306 /// from floating point types to integral types should be ignored.
307 NarrowingKind StandardConversionSequence::getNarrowingKind(
308 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
309 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
310 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
312 // C++11 [dcl.init.list]p7:
313 // A narrowing conversion is an implicit conversion ...
314 QualType FromType = getToType(0);
315 QualType ToType = getToType(1);
317 // A conversion to an enumeration type is narrowing if the conversion to
318 // the underlying type is narrowing. This only arises for expressions of
319 // the form 'Enum{init}'.
320 if (auto *ET = ToType->getAs<EnumType>())
321 ToType = ET->getDecl()->getIntegerType();
324 // 'bool' is an integral type; dispatch to the right place to handle it.
325 case ICK_Boolean_Conversion:
326 if (FromType->isRealFloatingType())
327 goto FloatingIntegralConversion;
328 if (FromType->isIntegralOrUnscopedEnumerationType())
329 goto IntegralConversion;
330 // Boolean conversions can be from pointers and pointers to members
331 // [conv.bool], and those aren't considered narrowing conversions.
332 return NK_Not_Narrowing;
334 // -- from a floating-point type to an integer type, or
336 // -- from an integer type or unscoped enumeration type to a floating-point
337 // type, except where the source is a constant expression and the actual
338 // value after conversion will fit into the target type and will produce
339 // the original value when converted back to the original type, or
340 case ICK_Floating_Integral:
341 FloatingIntegralConversion:
342 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
343 return NK_Type_Narrowing;
344 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
345 ToType->isRealFloatingType()) {
346 if (IgnoreFloatToIntegralConversion)
347 return NK_Not_Narrowing;
348 llvm::APSInt IntConstantValue;
349 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
350 assert(Initializer && "Unknown conversion expression");
352 // If it's value-dependent, we can't tell whether it's narrowing.
353 if (Initializer->isValueDependent())
354 return NK_Dependent_Narrowing;
356 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
357 // Convert the integer to the floating type.
358 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
359 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
360 llvm::APFloat::rmNearestTiesToEven);
362 llvm::APSInt ConvertedValue = IntConstantValue;
364 Result.convertToInteger(ConvertedValue,
365 llvm::APFloat::rmTowardZero, &ignored);
366 // If the resulting value is different, this was a narrowing conversion.
367 if (IntConstantValue != ConvertedValue) {
368 ConstantValue = APValue(IntConstantValue);
369 ConstantType = Initializer->getType();
370 return NK_Constant_Narrowing;
373 // Variables are always narrowings.
374 return NK_Variable_Narrowing;
377 return NK_Not_Narrowing;
379 // -- from long double to double or float, or from double to float, except
380 // where the source is a constant expression and the actual value after
381 // conversion is within the range of values that can be represented (even
382 // if it cannot be represented exactly), or
383 case ICK_Floating_Conversion:
384 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
385 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
386 // FromType is larger than ToType.
387 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
389 // If it's value-dependent, we can't tell whether it's narrowing.
390 if (Initializer->isValueDependent())
391 return NK_Dependent_Narrowing;
393 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
395 assert(ConstantValue.isFloat());
396 llvm::APFloat FloatVal = ConstantValue.getFloat();
397 // Convert the source value into the target type.
399 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
400 Ctx.getFloatTypeSemantics(ToType),
401 llvm::APFloat::rmNearestTiesToEven, &ignored);
402 // If there was no overflow, the source value is within the range of
403 // values that can be represented.
404 if (ConvertStatus & llvm::APFloat::opOverflow) {
405 ConstantType = Initializer->getType();
406 return NK_Constant_Narrowing;
409 return NK_Variable_Narrowing;
412 return NK_Not_Narrowing;
414 // -- from an integer type or unscoped enumeration type to an integer type
415 // that cannot represent all the values of the original type, except where
416 // the source is a constant expression and the actual value after
417 // conversion will fit into the target type and will produce the original
418 // value when converted back to the original type.
419 case ICK_Integral_Conversion:
420 IntegralConversion: {
421 assert(FromType->isIntegralOrUnscopedEnumerationType());
422 assert(ToType->isIntegralOrUnscopedEnumerationType());
423 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
424 const unsigned FromWidth = Ctx.getIntWidth(FromType);
425 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
426 const unsigned ToWidth = Ctx.getIntWidth(ToType);
428 if (FromWidth > ToWidth ||
429 (FromWidth == ToWidth && FromSigned != ToSigned) ||
430 (FromSigned && !ToSigned)) {
431 // Not all values of FromType can be represented in ToType.
432 llvm::APSInt InitializerValue;
433 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
435 // If it's value-dependent, we can't tell whether it's narrowing.
436 if (Initializer->isValueDependent())
437 return NK_Dependent_Narrowing;
439 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
440 // Such conversions on variables are always narrowing.
441 return NK_Variable_Narrowing;
443 bool Narrowing = false;
444 if (FromWidth < ToWidth) {
445 // Negative -> unsigned is narrowing. Otherwise, more bits is never
447 if (InitializerValue.isSigned() && InitializerValue.isNegative())
450 // Add a bit to the InitializerValue so we don't have to worry about
451 // signed vs. unsigned comparisons.
452 InitializerValue = InitializerValue.extend(
453 InitializerValue.getBitWidth() + 1);
454 // Convert the initializer to and from the target width and signed-ness.
455 llvm::APSInt ConvertedValue = InitializerValue;
456 ConvertedValue = ConvertedValue.trunc(ToWidth);
457 ConvertedValue.setIsSigned(ToSigned);
458 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
459 ConvertedValue.setIsSigned(InitializerValue.isSigned());
460 // If the result is different, this was a narrowing conversion.
461 if (ConvertedValue != InitializerValue)
465 ConstantType = Initializer->getType();
466 ConstantValue = APValue(InitializerValue);
467 return NK_Constant_Narrowing;
470 return NK_Not_Narrowing;
474 // Other kinds of conversions are not narrowings.
475 return NK_Not_Narrowing;
479 /// dump - Print this standard conversion sequence to standard
480 /// error. Useful for debugging overloading issues.
481 LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
482 raw_ostream &OS = llvm::errs();
483 bool PrintedSomething = false;
484 if (First != ICK_Identity) {
485 OS << GetImplicitConversionName(First);
486 PrintedSomething = true;
489 if (Second != ICK_Identity) {
490 if (PrintedSomething) {
493 OS << GetImplicitConversionName(Second);
495 if (CopyConstructor) {
496 OS << " (by copy constructor)";
497 } else if (DirectBinding) {
498 OS << " (direct reference binding)";
499 } else if (ReferenceBinding) {
500 OS << " (reference binding)";
502 PrintedSomething = true;
505 if (Third != ICK_Identity) {
506 if (PrintedSomething) {
509 OS << GetImplicitConversionName(Third);
510 PrintedSomething = true;
513 if (!PrintedSomething) {
514 OS << "No conversions required";
518 /// dump - Print this user-defined conversion sequence to standard
519 /// error. Useful for debugging overloading issues.
520 void UserDefinedConversionSequence::dump() const {
521 raw_ostream &OS = llvm::errs();
522 if (Before.First || Before.Second || Before.Third) {
526 if (ConversionFunction)
527 OS << '\'' << *ConversionFunction << '\'';
529 OS << "aggregate initialization";
530 if (After.First || After.Second || After.Third) {
536 /// dump - Print this implicit conversion sequence to standard
537 /// error. Useful for debugging overloading issues.
538 void ImplicitConversionSequence::dump() const {
539 raw_ostream &OS = llvm::errs();
540 if (isStdInitializerListElement())
541 OS << "Worst std::initializer_list element conversion: ";
542 switch (ConversionKind) {
543 case StandardConversion:
544 OS << "Standard conversion: ";
547 case UserDefinedConversion:
548 OS << "User-defined conversion: ";
551 case EllipsisConversion:
552 OS << "Ellipsis conversion";
554 case AmbiguousConversion:
555 OS << "Ambiguous conversion";
558 OS << "Bad conversion";
565 void AmbiguousConversionSequence::construct() {
566 new (&conversions()) ConversionSet();
569 void AmbiguousConversionSequence::destruct() {
570 conversions().~ConversionSet();
574 AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
575 FromTypePtr = O.FromTypePtr;
576 ToTypePtr = O.ToTypePtr;
577 new (&conversions()) ConversionSet(O.conversions());
581 // Structure used by DeductionFailureInfo to store
582 // template argument information.
583 struct DFIArguments {
584 TemplateArgument FirstArg;
585 TemplateArgument SecondArg;
587 // Structure used by DeductionFailureInfo to store
588 // template parameter and template argument information.
589 struct DFIParamWithArguments : DFIArguments {
590 TemplateParameter Param;
592 // Structure used by DeductionFailureInfo to store template argument
593 // information and the index of the problematic call argument.
594 struct DFIDeducedMismatchArgs : DFIArguments {
595 TemplateArgumentList *TemplateArgs;
596 unsigned CallArgIndex;
598 // Structure used by DeductionFailureInfo to store information about
599 // unsatisfied constraints.
601 TemplateArgumentList *TemplateArgs;
602 ConstraintSatisfaction Satisfaction;
606 /// Convert from Sema's representation of template deduction information
607 /// to the form used in overload-candidate information.
609 clang::MakeDeductionFailureInfo(ASTContext &Context,
610 Sema::TemplateDeductionResult TDK,
611 TemplateDeductionInfo &Info) {
612 DeductionFailureInfo Result;
613 Result.Result = static_cast<unsigned>(TDK);
614 Result.HasDiagnostic = false;
616 case Sema::TDK_Invalid:
617 case Sema::TDK_InstantiationDepth:
618 case Sema::TDK_TooManyArguments:
619 case Sema::TDK_TooFewArguments:
620 case Sema::TDK_MiscellaneousDeductionFailure:
621 case Sema::TDK_CUDATargetMismatch:
622 Result.Data = nullptr;
625 case Sema::TDK_Incomplete:
626 case Sema::TDK_InvalidExplicitArguments:
627 Result.Data = Info.Param.getOpaqueValue();
630 case Sema::TDK_DeducedMismatch:
631 case Sema::TDK_DeducedMismatchNested: {
632 // FIXME: Should allocate from normal heap so that we can free this later.
633 auto *Saved = new (Context) DFIDeducedMismatchArgs;
634 Saved->FirstArg = Info.FirstArg;
635 Saved->SecondArg = Info.SecondArg;
636 Saved->TemplateArgs = Info.take();
637 Saved->CallArgIndex = Info.CallArgIndex;
642 case Sema::TDK_NonDeducedMismatch: {
643 // FIXME: Should allocate from normal heap so that we can free this later.
644 DFIArguments *Saved = new (Context) DFIArguments;
645 Saved->FirstArg = Info.FirstArg;
646 Saved->SecondArg = Info.SecondArg;
651 case Sema::TDK_IncompletePack:
652 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
653 case Sema::TDK_Inconsistent:
654 case Sema::TDK_Underqualified: {
655 // FIXME: Should allocate from normal heap so that we can free this later.
656 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
657 Saved->Param = Info.Param;
658 Saved->FirstArg = Info.FirstArg;
659 Saved->SecondArg = Info.SecondArg;
664 case Sema::TDK_SubstitutionFailure:
665 Result.Data = Info.take();
666 if (Info.hasSFINAEDiagnostic()) {
667 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
668 SourceLocation(), PartialDiagnostic::NullDiagnostic());
669 Info.takeSFINAEDiagnostic(*Diag);
670 Result.HasDiagnostic = true;
674 case Sema::TDK_ConstraintsNotSatisfied: {
675 CNSInfo *Saved = new (Context) CNSInfo;
676 Saved->TemplateArgs = Info.take();
677 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
682 case Sema::TDK_Success:
683 case Sema::TDK_NonDependentConversionFailure:
684 llvm_unreachable("not a deduction failure");
690 void DeductionFailureInfo::Destroy() {
691 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
692 case Sema::TDK_Success:
693 case Sema::TDK_Invalid:
694 case Sema::TDK_InstantiationDepth:
695 case Sema::TDK_Incomplete:
696 case Sema::TDK_TooManyArguments:
697 case Sema::TDK_TooFewArguments:
698 case Sema::TDK_InvalidExplicitArguments:
699 case Sema::TDK_CUDATargetMismatch:
700 case Sema::TDK_NonDependentConversionFailure:
703 case Sema::TDK_IncompletePack:
704 case Sema::TDK_Inconsistent:
705 case Sema::TDK_Underqualified:
706 case Sema::TDK_DeducedMismatch:
707 case Sema::TDK_DeducedMismatchNested:
708 case Sema::TDK_NonDeducedMismatch:
709 // FIXME: Destroy the data?
713 case Sema::TDK_SubstitutionFailure:
714 // FIXME: Destroy the template argument list?
716 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
717 Diag->~PartialDiagnosticAt();
718 HasDiagnostic = false;
722 case Sema::TDK_ConstraintsNotSatisfied:
723 // FIXME: Destroy the template argument list?
725 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
726 Diag->~PartialDiagnosticAt();
727 HasDiagnostic = false;
732 case Sema::TDK_MiscellaneousDeductionFailure:
737 PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
739 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
743 TemplateParameter DeductionFailureInfo::getTemplateParameter() {
744 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
745 case Sema::TDK_Success:
746 case Sema::TDK_Invalid:
747 case Sema::TDK_InstantiationDepth:
748 case Sema::TDK_TooManyArguments:
749 case Sema::TDK_TooFewArguments:
750 case Sema::TDK_SubstitutionFailure:
751 case Sema::TDK_DeducedMismatch:
752 case Sema::TDK_DeducedMismatchNested:
753 case Sema::TDK_NonDeducedMismatch:
754 case Sema::TDK_CUDATargetMismatch:
755 case Sema::TDK_NonDependentConversionFailure:
756 case Sema::TDK_ConstraintsNotSatisfied:
757 return TemplateParameter();
759 case Sema::TDK_Incomplete:
760 case Sema::TDK_InvalidExplicitArguments:
761 return TemplateParameter::getFromOpaqueValue(Data);
763 case Sema::TDK_IncompletePack:
764 case Sema::TDK_Inconsistent:
765 case Sema::TDK_Underqualified:
766 return static_cast<DFIParamWithArguments*>(Data)->Param;
769 case Sema::TDK_MiscellaneousDeductionFailure:
773 return TemplateParameter();
776 TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
777 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
778 case Sema::TDK_Success:
779 case Sema::TDK_Invalid:
780 case Sema::TDK_InstantiationDepth:
781 case Sema::TDK_TooManyArguments:
782 case Sema::TDK_TooFewArguments:
783 case Sema::TDK_Incomplete:
784 case Sema::TDK_IncompletePack:
785 case Sema::TDK_InvalidExplicitArguments:
786 case Sema::TDK_Inconsistent:
787 case Sema::TDK_Underqualified:
788 case Sema::TDK_NonDeducedMismatch:
789 case Sema::TDK_CUDATargetMismatch:
790 case Sema::TDK_NonDependentConversionFailure:
793 case Sema::TDK_DeducedMismatch:
794 case Sema::TDK_DeducedMismatchNested:
795 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
797 case Sema::TDK_SubstitutionFailure:
798 return static_cast<TemplateArgumentList*>(Data);
800 case Sema::TDK_ConstraintsNotSatisfied:
801 return static_cast<CNSInfo*>(Data)->TemplateArgs;
804 case Sema::TDK_MiscellaneousDeductionFailure:
811 const TemplateArgument *DeductionFailureInfo::getFirstArg() {
812 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
813 case Sema::TDK_Success:
814 case Sema::TDK_Invalid:
815 case Sema::TDK_InstantiationDepth:
816 case Sema::TDK_Incomplete:
817 case Sema::TDK_TooManyArguments:
818 case Sema::TDK_TooFewArguments:
819 case Sema::TDK_InvalidExplicitArguments:
820 case Sema::TDK_SubstitutionFailure:
821 case Sema::TDK_CUDATargetMismatch:
822 case Sema::TDK_NonDependentConversionFailure:
823 case Sema::TDK_ConstraintsNotSatisfied:
826 case Sema::TDK_IncompletePack:
827 case Sema::TDK_Inconsistent:
828 case Sema::TDK_Underqualified:
829 case Sema::TDK_DeducedMismatch:
830 case Sema::TDK_DeducedMismatchNested:
831 case Sema::TDK_NonDeducedMismatch:
832 return &static_cast<DFIArguments*>(Data)->FirstArg;
835 case Sema::TDK_MiscellaneousDeductionFailure:
842 const TemplateArgument *DeductionFailureInfo::getSecondArg() {
843 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
844 case Sema::TDK_Success:
845 case Sema::TDK_Invalid:
846 case Sema::TDK_InstantiationDepth:
847 case Sema::TDK_Incomplete:
848 case Sema::TDK_IncompletePack:
849 case Sema::TDK_TooManyArguments:
850 case Sema::TDK_TooFewArguments:
851 case Sema::TDK_InvalidExplicitArguments:
852 case Sema::TDK_SubstitutionFailure:
853 case Sema::TDK_CUDATargetMismatch:
854 case Sema::TDK_NonDependentConversionFailure:
855 case Sema::TDK_ConstraintsNotSatisfied:
858 case Sema::TDK_Inconsistent:
859 case Sema::TDK_Underqualified:
860 case Sema::TDK_DeducedMismatch:
861 case Sema::TDK_DeducedMismatchNested:
862 case Sema::TDK_NonDeducedMismatch:
863 return &static_cast<DFIArguments*>(Data)->SecondArg;
866 case Sema::TDK_MiscellaneousDeductionFailure:
873 llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
874 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
875 case Sema::TDK_DeducedMismatch:
876 case Sema::TDK_DeducedMismatchNested:
877 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
884 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
885 OverloadedOperatorKind Op) {
886 if (!AllowRewrittenCandidates)
888 return Op == OO_EqualEqual || Op == OO_Spaceship;
891 bool OverloadCandidateSet::OperatorRewriteInfo::shouldAddReversed(
892 ASTContext &Ctx, const FunctionDecl *FD) {
893 if (!shouldAddReversed(FD->getDeclName().getCXXOverloadedOperator()))
895 // Don't bother adding a reversed candidate that can never be a better
896 // match than the non-reversed version.
897 return FD->getNumParams() != 2 ||
898 !Ctx.hasSameUnqualifiedType(FD->getParamDecl(0)->getType(),
899 FD->getParamDecl(1)->getType()) ||
900 FD->hasAttr<EnableIfAttr>();
903 void OverloadCandidateSet::destroyCandidates() {
904 for (iterator i = begin(), e = end(); i != e; ++i) {
905 for (auto &C : i->Conversions)
906 C.~ImplicitConversionSequence();
907 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
908 i->DeductionFailure.Destroy();
912 void OverloadCandidateSet::clear(CandidateSetKind CSK) {
914 SlabAllocator.Reset();
915 NumInlineBytesUsed = 0;
922 class UnbridgedCastsSet {
927 SmallVector<Entry, 2> Entries;
930 void save(Sema &S, Expr *&E) {
931 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
932 Entry entry = { &E, E };
933 Entries.push_back(entry);
934 E = S.stripARCUnbridgedCast(E);
938 for (SmallVectorImpl<Entry>::iterator
939 i = Entries.begin(), e = Entries.end(); i != e; ++i)
945 /// checkPlaceholderForOverload - Do any interesting placeholder-like
946 /// preprocessing on the given expression.
948 /// \param unbridgedCasts a collection to which to add unbridged casts;
949 /// without this, they will be immediately diagnosed as errors
951 /// Return true on unrecoverable error.
953 checkPlaceholderForOverload(Sema &S, Expr *&E,
954 UnbridgedCastsSet *unbridgedCasts = nullptr) {
955 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
956 // We can't handle overloaded expressions here because overload
957 // resolution might reasonably tweak them.
958 if (placeholder->getKind() == BuiltinType::Overload) return false;
960 // If the context potentially accepts unbridged ARC casts, strip
961 // the unbridged cast and add it to the collection for later restoration.
962 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
964 unbridgedCasts->save(S, E);
968 // Go ahead and check everything else.
969 ExprResult result = S.CheckPlaceholderExpr(E);
970 if (result.isInvalid())
981 /// checkArgPlaceholdersForOverload - Check a set of call operands for
983 static bool checkArgPlaceholdersForOverload(Sema &S,
985 UnbridgedCastsSet &unbridged) {
986 for (unsigned i = 0, e = Args.size(); i != e; ++i)
987 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
993 /// Determine whether the given New declaration is an overload of the
994 /// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
995 /// New and Old cannot be overloaded, e.g., if New has the same signature as
996 /// some function in Old (C++ 1.3.10) or if the Old declarations aren't
997 /// functions (or function templates) at all. When it does return Ovl_Match or
998 /// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
999 /// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
1002 /// Example: Given the following input:
1004 /// void f(int, float); // #1
1005 /// void f(int, int); // #2
1006 /// int f(int, int); // #3
1008 /// When we process #1, there is no previous declaration of "f", so IsOverload
1009 /// will not be used.
1011 /// When we process #2, Old contains only the FunctionDecl for #1. By comparing
1012 /// the parameter types, we see that #1 and #2 are overloaded (since they have
1013 /// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
1016 /// When we process #3, Old is an overload set containing #1 and #2. We compare
1017 /// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
1018 /// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
1019 /// functions are not part of the signature), IsOverload returns Ovl_Match and
1020 /// MatchedDecl will be set to point to the FunctionDecl for #2.
1022 /// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
1023 /// by a using declaration. The rules for whether to hide shadow declarations
1024 /// ignore some properties which otherwise figure into a function template's
1027 Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
1028 NamedDecl *&Match, bool NewIsUsingDecl) {
1029 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1031 NamedDecl *OldD = *I;
1033 bool OldIsUsingDecl = false;
1034 if (isa<UsingShadowDecl>(OldD)) {
1035 OldIsUsingDecl = true;
1037 // We can always introduce two using declarations into the same
1038 // context, even if they have identical signatures.
1039 if (NewIsUsingDecl) continue;
1041 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1044 // A using-declaration does not conflict with another declaration
1045 // if one of them is hidden.
1046 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1049 // If either declaration was introduced by a using declaration,
1050 // we'll need to use slightly different rules for matching.
1051 // Essentially, these rules are the normal rules, except that
1052 // function templates hide function templates with different
1053 // return types or template parameter lists.
1054 bool UseMemberUsingDeclRules =
1055 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1056 !New->getFriendObjectKind();
1058 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1059 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1060 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1061 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1065 if (!isa<FunctionTemplateDecl>(OldD) &&
1066 !shouldLinkPossiblyHiddenDecl(*I, New))
1073 // Builtins that have custom typechecking or have a reference should
1074 // not be overloadable or redeclarable.
1075 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1077 return Ovl_NonFunction;
1079 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1080 // We can overload with these, which can show up when doing
1081 // redeclaration checks for UsingDecls.
1082 assert(Old.getLookupKind() == LookupUsingDeclName);
1083 } else if (isa<TagDecl>(OldD)) {
1084 // We can always overload with tags by hiding them.
1085 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1086 // Optimistically assume that an unresolved using decl will
1087 // overload; if it doesn't, we'll have to diagnose during
1088 // template instantiation.
1090 // Exception: if the scope is dependent and this is not a class
1091 // member, the using declaration can only introduce an enumerator.
1092 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1094 return Ovl_NonFunction;
1098 // Only function declarations can be overloaded; object and type
1099 // declarations cannot be overloaded.
1101 return Ovl_NonFunction;
1105 // C++ [temp.friend]p1:
1106 // For a friend function declaration that is not a template declaration:
1107 // -- if the name of the friend is a qualified or unqualified template-id,
1109 // -- if the name of the friend is a qualified-id and a matching
1110 // non-template function is found in the specified class or namespace,
1111 // the friend declaration refers to that function, otherwise,
1112 // -- if the name of the friend is a qualified-id and a matching function
1113 // template is found in the specified class or namespace, the friend
1114 // declaration refers to the deduced specialization of that function
1115 // template, otherwise
1116 // -- the name shall be an unqualified-id [...]
1117 // If we get here for a qualified friend declaration, we've just reached the
1118 // third bullet. If the type of the friend is dependent, skip this lookup
1119 // until instantiation.
1120 if (New->getFriendObjectKind() && New->getQualifier() &&
1121 !New->getDescribedFunctionTemplate() &&
1122 !New->getDependentSpecializationInfo() &&
1123 !New->getType()->isDependentType()) {
1124 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1125 TemplateSpecResult.addAllDecls(Old);
1126 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1127 /*QualifiedFriend*/true)) {
1128 New->setInvalidDecl();
1129 return Ovl_Overload;
1132 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1136 return Ovl_Overload;
1139 bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1140 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs,
1141 bool ConsiderRequiresClauses) {
1142 // C++ [basic.start.main]p2: This function shall not be overloaded.
1146 // MSVCRT user defined entry points cannot be overloaded.
1147 if (New->isMSVCRTEntryPoint())
1150 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1151 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1153 // C++ [temp.fct]p2:
1154 // A function template can be overloaded with other function templates
1155 // and with normal (non-template) functions.
1156 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1159 // Is the function New an overload of the function Old?
1160 QualType OldQType = Context.getCanonicalType(Old->getType());
1161 QualType NewQType = Context.getCanonicalType(New->getType());
1163 // Compare the signatures (C++ 1.3.10) of the two functions to
1164 // determine whether they are overloads. If we find any mismatch
1165 // in the signature, they are overloads.
1167 // If either of these functions is a K&R-style function (no
1168 // prototype), then we consider them to have matching signatures.
1169 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1170 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1173 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1174 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1176 // The signature of a function includes the types of its
1177 // parameters (C++ 1.3.10), which includes the presence or absence
1178 // of the ellipsis; see C++ DR 357).
1179 if (OldQType != NewQType &&
1180 (OldType->getNumParams() != NewType->getNumParams() ||
1181 OldType->isVariadic() != NewType->isVariadic() ||
1182 !FunctionParamTypesAreEqual(OldType, NewType)))
1185 // C++ [temp.over.link]p4:
1186 // The signature of a function template consists of its function
1187 // signature, its return type and its template parameter list. The names
1188 // of the template parameters are significant only for establishing the
1189 // relationship between the template parameters and the rest of the
1192 // We check the return type and template parameter lists for function
1193 // templates first; the remaining checks follow.
1195 // However, we don't consider either of these when deciding whether
1196 // a member introduced by a shadow declaration is hidden.
1197 if (!UseMemberUsingDeclRules && NewTemplate &&
1198 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1199 OldTemplate->getTemplateParameters(),
1200 false, TPL_TemplateMatch) ||
1201 !Context.hasSameType(Old->getDeclaredReturnType(),
1202 New->getDeclaredReturnType())))
1205 // If the function is a class member, its signature includes the
1206 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1208 // As part of this, also check whether one of the member functions
1209 // is static, in which case they are not overloads (C++
1210 // 13.1p2). While not part of the definition of the signature,
1211 // this check is important to determine whether these functions
1212 // can be overloaded.
1213 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1214 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1215 if (OldMethod && NewMethod &&
1216 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1217 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1218 if (!UseMemberUsingDeclRules &&
1219 (OldMethod->getRefQualifier() == RQ_None ||
1220 NewMethod->getRefQualifier() == RQ_None)) {
1221 // C++0x [over.load]p2:
1222 // - Member function declarations with the same name and the same
1223 // parameter-type-list as well as member function template
1224 // declarations with the same name, the same parameter-type-list, and
1225 // the same template parameter lists cannot be overloaded if any of
1226 // them, but not all, have a ref-qualifier (8.3.5).
1227 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1228 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1229 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1234 // We may not have applied the implicit const for a constexpr member
1235 // function yet (because we haven't yet resolved whether this is a static
1236 // or non-static member function). Add it now, on the assumption that this
1237 // is a redeclaration of OldMethod.
1238 auto OldQuals = OldMethod->getMethodQualifiers();
1239 auto NewQuals = NewMethod->getMethodQualifiers();
1240 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1241 !isa<CXXConstructorDecl>(NewMethod))
1242 NewQuals.addConst();
1243 // We do not allow overloading based off of '__restrict'.
1244 OldQuals.removeRestrict();
1245 NewQuals.removeRestrict();
1246 if (OldQuals != NewQuals)
1250 // Though pass_object_size is placed on parameters and takes an argument, we
1251 // consider it to be a function-level modifier for the sake of function
1252 // identity. Either the function has one or more parameters with
1253 // pass_object_size or it doesn't.
1254 if (functionHasPassObjectSizeParams(New) !=
1255 functionHasPassObjectSizeParams(Old))
1258 // enable_if attributes are an order-sensitive part of the signature.
1259 for (specific_attr_iterator<EnableIfAttr>
1260 NewI = New->specific_attr_begin<EnableIfAttr>(),
1261 NewE = New->specific_attr_end<EnableIfAttr>(),
1262 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1263 OldE = Old->specific_attr_end<EnableIfAttr>();
1264 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1265 if (NewI == NewE || OldI == OldE)
1267 llvm::FoldingSetNodeID NewID, OldID;
1268 NewI->getCond()->Profile(NewID, Context, true);
1269 OldI->getCond()->Profile(OldID, Context, true);
1274 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1275 // Don't allow overloading of destructors. (In theory we could, but it
1276 // would be a giant change to clang.)
1277 if (!isa<CXXDestructorDecl>(New)) {
1278 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1279 OldTarget = IdentifyCUDATarget(Old);
1280 if (NewTarget != CFT_InvalidTarget) {
1281 assert((OldTarget != CFT_InvalidTarget) &&
1282 "Unexpected invalid target.");
1284 // Allow overloading of functions with same signature and different CUDA
1285 // target attributes.
1286 if (NewTarget != OldTarget)
1292 if (ConsiderRequiresClauses) {
1293 Expr *NewRC = New->getTrailingRequiresClause(),
1294 *OldRC = Old->getTrailingRequiresClause();
1295 if ((NewRC != nullptr) != (OldRC != nullptr))
1296 // RC are most certainly different - these are overloads.
1300 llvm::FoldingSetNodeID NewID, OldID;
1301 NewRC->Profile(NewID, Context, /*Canonical=*/true);
1302 OldRC->Profile(OldID, Context, /*Canonical=*/true);
1304 // RCs are not equivalent - these are overloads.
1309 // The signatures match; this is not an overload.
1313 /// Tries a user-defined conversion from From to ToType.
1315 /// Produces an implicit conversion sequence for when a standard conversion
1316 /// is not an option. See TryImplicitConversion for more information.
1317 static ImplicitConversionSequence
1318 TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1319 bool SuppressUserConversions,
1321 bool InOverloadResolution,
1323 bool AllowObjCWritebackConversion,
1324 bool AllowObjCConversionOnExplicit) {
1325 ImplicitConversionSequence ICS;
1327 if (SuppressUserConversions) {
1328 // We're not in the case above, so there is no conversion that
1330 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1334 // Attempt user-defined conversion.
1335 OverloadCandidateSet Conversions(From->getExprLoc(),
1336 OverloadCandidateSet::CSK_Normal);
1337 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1338 Conversions, AllowExplicit,
1339 AllowObjCConversionOnExplicit)) {
1342 ICS.setUserDefined();
1343 // C++ [over.ics.user]p4:
1344 // A conversion of an expression of class type to the same class
1345 // type is given Exact Match rank, and a conversion of an
1346 // expression of class type to a base class of that type is
1347 // given Conversion rank, in spite of the fact that a copy
1348 // constructor (i.e., a user-defined conversion function) is
1349 // called for those cases.
1350 if (CXXConstructorDecl *Constructor
1351 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1353 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1355 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1356 if (Constructor->isCopyConstructor() &&
1357 (FromCanon == ToCanon ||
1358 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1359 // Turn this into a "standard" conversion sequence, so that it
1360 // gets ranked with standard conversion sequences.
1361 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1363 ICS.Standard.setAsIdentityConversion();
1364 ICS.Standard.setFromType(From->getType());
1365 ICS.Standard.setAllToTypes(ToType);
1366 ICS.Standard.CopyConstructor = Constructor;
1367 ICS.Standard.FoundCopyConstructor = Found;
1368 if (ToCanon != FromCanon)
1369 ICS.Standard.Second = ICK_Derived_To_Base;
1376 ICS.Ambiguous.setFromType(From->getType());
1377 ICS.Ambiguous.setToType(ToType);
1378 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1379 Cand != Conversions.end(); ++Cand)
1381 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1385 case OR_No_Viable_Function:
1386 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1393 /// TryImplicitConversion - Attempt to perform an implicit conversion
1394 /// from the given expression (Expr) to the given type (ToType). This
1395 /// function returns an implicit conversion sequence that can be used
1396 /// to perform the initialization. Given
1398 /// void f(float f);
1399 /// void g(int i) { f(i); }
1401 /// this routine would produce an implicit conversion sequence to
1402 /// describe the initialization of f from i, which will be a standard
1403 /// conversion sequence containing an lvalue-to-rvalue conversion (C++
1404 /// 4.1) followed by a floating-integral conversion (C++ 4.9).
1406 /// Note that this routine only determines how the conversion can be
1407 /// performed; it does not actually perform the conversion. As such,
1408 /// it will not produce any diagnostics if no conversion is available,
1409 /// but will instead return an implicit conversion sequence of kind
1410 /// "BadConversion".
1412 /// If @p SuppressUserConversions, then user-defined conversions are
1414 /// If @p AllowExplicit, then explicit user-defined conversions are
1417 /// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1418 /// writeback conversion, which allows __autoreleasing id* parameters to
1419 /// be initialized with __strong id* or __weak id* arguments.
1420 static ImplicitConversionSequence
1421 TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1422 bool SuppressUserConversions,
1424 bool InOverloadResolution,
1426 bool AllowObjCWritebackConversion,
1427 bool AllowObjCConversionOnExplicit) {
1428 ImplicitConversionSequence ICS;
1429 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1430 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1435 if (!S.getLangOpts().CPlusPlus) {
1436 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1440 // C++ [over.ics.user]p4:
1441 // A conversion of an expression of class type to the same class
1442 // type is given Exact Match rank, and a conversion of an
1443 // expression of class type to a base class of that type is
1444 // given Conversion rank, in spite of the fact that a copy/move
1445 // constructor (i.e., a user-defined conversion function) is
1446 // called for those cases.
1447 QualType FromType = From->getType();
1448 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1449 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1450 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1452 ICS.Standard.setAsIdentityConversion();
1453 ICS.Standard.setFromType(FromType);
1454 ICS.Standard.setAllToTypes(ToType);
1456 // We don't actually check at this point whether there is a valid
1457 // copy/move constructor, since overloading just assumes that it
1458 // exists. When we actually perform initialization, we'll find the
1459 // appropriate constructor to copy the returned object, if needed.
1460 ICS.Standard.CopyConstructor = nullptr;
1462 // Determine whether this is considered a derived-to-base conversion.
1463 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1464 ICS.Standard.Second = ICK_Derived_To_Base;
1469 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1470 AllowExplicit, InOverloadResolution, CStyle,
1471 AllowObjCWritebackConversion,
1472 AllowObjCConversionOnExplicit);
1475 ImplicitConversionSequence
1476 Sema::TryImplicitConversion(Expr *From, QualType ToType,
1477 bool SuppressUserConversions,
1479 bool InOverloadResolution,
1481 bool AllowObjCWritebackConversion) {
1482 return ::TryImplicitConversion(*this, From, ToType,
1483 SuppressUserConversions, AllowExplicit,
1484 InOverloadResolution, CStyle,
1485 AllowObjCWritebackConversion,
1486 /*AllowObjCConversionOnExplicit=*/false);
1489 /// PerformImplicitConversion - Perform an implicit conversion of the
1490 /// expression From to the type ToType. Returns the
1491 /// converted expression. Flavor is the kind of conversion we're
1492 /// performing, used in the error message. If @p AllowExplicit,
1493 /// explicit user-defined conversions are permitted.
1495 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1496 AssignmentAction Action, bool AllowExplicit) {
1497 ImplicitConversionSequence ICS;
1498 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1502 Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1503 AssignmentAction Action, bool AllowExplicit,
1504 ImplicitConversionSequence& ICS) {
1505 if (checkPlaceholderForOverload(*this, From))
1508 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1509 bool AllowObjCWritebackConversion
1510 = getLangOpts().ObjCAutoRefCount &&
1511 (Action == AA_Passing || Action == AA_Sending);
1512 if (getLangOpts().ObjC)
1513 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1514 From->getType(), From);
1515 ICS = ::TryImplicitConversion(*this, From, ToType,
1516 /*SuppressUserConversions=*/false,
1518 /*InOverloadResolution=*/false,
1520 AllowObjCWritebackConversion,
1521 /*AllowObjCConversionOnExplicit=*/false);
1522 return PerformImplicitConversion(From, ToType, ICS, Action);
1525 /// Determine whether the conversion from FromType to ToType is a valid
1526 /// conversion that strips "noexcept" or "noreturn" off the nested function
1528 bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1529 QualType &ResultTy) {
1530 if (Context.hasSameUnqualifiedType(FromType, ToType))
1533 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1534 // or F(t noexcept) -> F(t)
1535 // where F adds one of the following at most once:
1537 // - a member pointer
1538 // - a block pointer
1539 // Changes here need matching changes in FindCompositePointerType.
1540 CanQualType CanTo = Context.getCanonicalType(ToType);
1541 CanQualType CanFrom = Context.getCanonicalType(FromType);
1542 Type::TypeClass TyClass = CanTo->getTypeClass();
1543 if (TyClass != CanFrom->getTypeClass()) return false;
1544 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1545 if (TyClass == Type::Pointer) {
1546 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1547 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1548 } else if (TyClass == Type::BlockPointer) {
1549 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1550 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1551 } else if (TyClass == Type::MemberPointer) {
1552 auto ToMPT = CanTo.castAs<MemberPointerType>();
1553 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1554 // A function pointer conversion cannot change the class of the function.
1555 if (ToMPT->getClass() != FromMPT->getClass())
1557 CanTo = ToMPT->getPointeeType();
1558 CanFrom = FromMPT->getPointeeType();
1563 TyClass = CanTo->getTypeClass();
1564 if (TyClass != CanFrom->getTypeClass()) return false;
1565 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1569 const auto *FromFn = cast<FunctionType>(CanFrom);
1570 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1572 const auto *ToFn = cast<FunctionType>(CanTo);
1573 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1575 bool Changed = false;
1577 // Drop 'noreturn' if not present in target type.
1578 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1579 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1583 // Drop 'noexcept' if not present in target type.
1584 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1585 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1586 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1587 FromFn = cast<FunctionType>(
1588 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1594 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1595 // only if the ExtParameterInfo lists of the two function prototypes can be
1596 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1597 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1598 bool CanUseToFPT, CanUseFromFPT;
1599 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1600 CanUseFromFPT, NewParamInfos) &&
1601 CanUseToFPT && !CanUseFromFPT) {
1602 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1603 ExtInfo.ExtParameterInfos =
1604 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1605 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1606 FromFPT->getParamTypes(), ExtInfo);
1607 FromFn = QT->getAs<FunctionType>();
1615 assert(QualType(FromFn, 0).isCanonical());
1616 if (QualType(FromFn, 0) != CanTo) return false;
1622 /// Determine whether the conversion from FromType to ToType is a valid
1623 /// vector conversion.
1625 /// \param ICK Will be set to the vector conversion kind, if this is a vector
1627 static bool IsVectorConversion(Sema &S, QualType FromType,
1628 QualType ToType, ImplicitConversionKind &ICK) {
1629 // We need at least one of these types to be a vector type to have a vector
1631 if (!ToType->isVectorType() && !FromType->isVectorType())
1634 // Identical types require no conversions.
1635 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1638 // There are no conversions between extended vector types, only identity.
1639 if (ToType->isExtVectorType()) {
1640 // There are no conversions between extended vector types other than the
1641 // identity conversion.
1642 if (FromType->isExtVectorType())
1645 // Vector splat from any arithmetic type to a vector.
1646 if (FromType->isArithmeticType()) {
1647 ICK = ICK_Vector_Splat;
1652 // We can perform the conversion between vector types in the following cases:
1653 // 1)vector types are equivalent AltiVec and GCC vector types
1654 // 2)lax vector conversions are permitted and the vector types are of the
1656 if (ToType->isVectorType() && FromType->isVectorType()) {
1657 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1658 S.isLaxVectorConversion(FromType, ToType)) {
1659 ICK = ICK_Vector_Conversion;
1667 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1668 bool InOverloadResolution,
1669 StandardConversionSequence &SCS,
1672 /// IsStandardConversion - Determines whether there is a standard
1673 /// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1674 /// expression From to the type ToType. Standard conversion sequences
1675 /// only consider non-class types; for conversions that involve class
1676 /// types, use TryImplicitConversion. If a conversion exists, SCS will
1677 /// contain the standard conversion sequence required to perform this
1678 /// conversion and this routine will return true. Otherwise, this
1679 /// routine will return false and the value of SCS is unspecified.
1680 static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1681 bool InOverloadResolution,
1682 StandardConversionSequence &SCS,
1684 bool AllowObjCWritebackConversion) {
1685 QualType FromType = From->getType();
1687 // Standard conversions (C++ [conv])
1688 SCS.setAsIdentityConversion();
1689 SCS.IncompatibleObjC = false;
1690 SCS.setFromType(FromType);
1691 SCS.CopyConstructor = nullptr;
1693 // There are no standard conversions for class types in C++, so
1694 // abort early. When overloading in C, however, we do permit them.
1695 if (S.getLangOpts().CPlusPlus &&
1696 (FromType->isRecordType() || ToType->isRecordType()))
1699 // The first conversion can be an lvalue-to-rvalue conversion,
1700 // array-to-pointer conversion, or function-to-pointer conversion
1703 if (FromType == S.Context.OverloadTy) {
1704 DeclAccessPair AccessPair;
1705 if (FunctionDecl *Fn
1706 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1708 // We were able to resolve the address of the overloaded function,
1709 // so we can convert to the type of that function.
1710 FromType = Fn->getType();
1711 SCS.setFromType(FromType);
1713 // we can sometimes resolve &foo<int> regardless of ToType, so check
1714 // if the type matches (identity) or we are converting to bool
1715 if (!S.Context.hasSameUnqualifiedType(
1716 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1718 // if the function type matches except for [[noreturn]], it's ok
1719 if (!S.IsFunctionConversion(FromType,
1720 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1721 // otherwise, only a boolean conversion is standard
1722 if (!ToType->isBooleanType())
1726 // Check if the "from" expression is taking the address of an overloaded
1727 // function and recompute the FromType accordingly. Take advantage of the
1728 // fact that non-static member functions *must* have such an address-of
1730 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1731 if (Method && !Method->isStatic()) {
1732 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1733 "Non-unary operator on non-static member address");
1734 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1736 "Non-address-of operator on non-static member address");
1737 const Type *ClassType
1738 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1739 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1740 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1741 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1743 "Non-address-of operator for overloaded function expression");
1744 FromType = S.Context.getPointerType(FromType);
1747 // Check that we've computed the proper type after overload resolution.
1748 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1749 // be calling it from within an NDEBUG block.
1750 assert(S.Context.hasSameType(
1752 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1757 // Lvalue-to-rvalue conversion (C++11 4.1):
1758 // A glvalue (3.10) of a non-function, non-array type T can
1759 // be converted to a prvalue.
1760 bool argIsLValue = From->isGLValue();
1762 !FromType->isFunctionType() && !FromType->isArrayType() &&
1763 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1764 SCS.First = ICK_Lvalue_To_Rvalue;
1767 // ... if the lvalue has atomic type, the value has the non-atomic version
1768 // of the type of the lvalue ...
1769 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1770 FromType = Atomic->getValueType();
1772 // If T is a non-class type, the type of the rvalue is the
1773 // cv-unqualified version of T. Otherwise, the type of the rvalue
1774 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1775 // just strip the qualifiers because they don't matter.
1776 FromType = FromType.getUnqualifiedType();
1777 } else if (FromType->isArrayType()) {
1778 // Array-to-pointer conversion (C++ 4.2)
1779 SCS.First = ICK_Array_To_Pointer;
1781 // An lvalue or rvalue of type "array of N T" or "array of unknown
1782 // bound of T" can be converted to an rvalue of type "pointer to
1784 FromType = S.Context.getArrayDecayedType(FromType);
1786 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1787 // This conversion is deprecated in C++03 (D.4)
1788 SCS.DeprecatedStringLiteralToCharPtr = true;
1790 // For the purpose of ranking in overload resolution
1791 // (13.3.3.1.1), this conversion is considered an
1792 // array-to-pointer conversion followed by a qualification
1793 // conversion (4.4). (C++ 4.2p2)
1794 SCS.Second = ICK_Identity;
1795 SCS.Third = ICK_Qualification;
1796 SCS.QualificationIncludesObjCLifetime = false;
1797 SCS.setAllToTypes(FromType);
1800 } else if (FromType->isFunctionType() && argIsLValue) {
1801 // Function-to-pointer conversion (C++ 4.3).
1802 SCS.First = ICK_Function_To_Pointer;
1804 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1805 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1806 if (!S.checkAddressOfFunctionIsAvailable(FD))
1809 // An lvalue of function type T can be converted to an rvalue of
1810 // type "pointer to T." The result is a pointer to the
1811 // function. (C++ 4.3p1).
1812 FromType = S.Context.getPointerType(FromType);
1814 // We don't require any conversions for the first step.
1815 SCS.First = ICK_Identity;
1817 SCS.setToType(0, FromType);
1819 // The second conversion can be an integral promotion, floating
1820 // point promotion, integral conversion, floating point conversion,
1821 // floating-integral conversion, pointer conversion,
1822 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1823 // For overloading in C, this can also be a "compatible-type"
1825 bool IncompatibleObjC = false;
1826 ImplicitConversionKind SecondICK = ICK_Identity;
1827 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1828 // The unqualified versions of the types are the same: there's no
1829 // conversion to do.
1830 SCS.Second = ICK_Identity;
1831 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1832 // Integral promotion (C++ 4.5).
1833 SCS.Second = ICK_Integral_Promotion;
1834 FromType = ToType.getUnqualifiedType();
1835 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1836 // Floating point promotion (C++ 4.6).
1837 SCS.Second = ICK_Floating_Promotion;
1838 FromType = ToType.getUnqualifiedType();
1839 } else if (S.IsComplexPromotion(FromType, ToType)) {
1840 // Complex promotion (Clang extension)
1841 SCS.Second = ICK_Complex_Promotion;
1842 FromType = ToType.getUnqualifiedType();
1843 } else if (ToType->isBooleanType() &&
1844 (FromType->isArithmeticType() ||
1845 FromType->isAnyPointerType() ||
1846 FromType->isBlockPointerType() ||
1847 FromType->isMemberPointerType() ||
1848 FromType->isNullPtrType())) {
1849 // Boolean conversions (C++ 4.12).
1850 SCS.Second = ICK_Boolean_Conversion;
1851 FromType = S.Context.BoolTy;
1852 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1853 ToType->isIntegralType(S.Context)) {
1854 // Integral conversions (C++ 4.7).
1855 SCS.Second = ICK_Integral_Conversion;
1856 FromType = ToType.getUnqualifiedType();
1857 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1858 // Complex conversions (C99 6.3.1.6)
1859 SCS.Second = ICK_Complex_Conversion;
1860 FromType = ToType.getUnqualifiedType();
1861 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1862 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1863 // Complex-real conversions (C99 6.3.1.7)
1864 SCS.Second = ICK_Complex_Real;
1865 FromType = ToType.getUnqualifiedType();
1866 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1867 // FIXME: disable conversions between long double and __float128 if
1868 // their representation is different until there is back end support
1869 // We of course allow this conversion if long double is really double.
1870 if (&S.Context.getFloatTypeSemantics(FromType) !=
1871 &S.Context.getFloatTypeSemantics(ToType)) {
1872 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1873 ToType == S.Context.LongDoubleTy) ||
1874 (FromType == S.Context.LongDoubleTy &&
1875 ToType == S.Context.Float128Ty));
1876 if (Float128AndLongDouble &&
1877 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1878 &llvm::APFloat::PPCDoubleDouble()))
1881 // Floating point conversions (C++ 4.8).
1882 SCS.Second = ICK_Floating_Conversion;
1883 FromType = ToType.getUnqualifiedType();
1884 } else if ((FromType->isRealFloatingType() &&
1885 ToType->isIntegralType(S.Context)) ||
1886 (FromType->isIntegralOrUnscopedEnumerationType() &&
1887 ToType->isRealFloatingType())) {
1888 // Floating-integral conversions (C++ 4.9).
1889 SCS.Second = ICK_Floating_Integral;
1890 FromType = ToType.getUnqualifiedType();
1891 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1892 SCS.Second = ICK_Block_Pointer_Conversion;
1893 } else if (AllowObjCWritebackConversion &&
1894 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1895 SCS.Second = ICK_Writeback_Conversion;
1896 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1897 FromType, IncompatibleObjC)) {
1898 // Pointer conversions (C++ 4.10).
1899 SCS.Second = ICK_Pointer_Conversion;
1900 SCS.IncompatibleObjC = IncompatibleObjC;
1901 FromType = FromType.getUnqualifiedType();
1902 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1903 InOverloadResolution, FromType)) {
1904 // Pointer to member conversions (4.11).
1905 SCS.Second = ICK_Pointer_Member;
1906 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1907 SCS.Second = SecondICK;
1908 FromType = ToType.getUnqualifiedType();
1909 } else if (!S.getLangOpts().CPlusPlus &&
1910 S.Context.typesAreCompatible(ToType, FromType)) {
1911 // Compatible conversions (Clang extension for C function overloading)
1912 SCS.Second = ICK_Compatible_Conversion;
1913 FromType = ToType.getUnqualifiedType();
1914 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1915 InOverloadResolution,
1917 SCS.Second = ICK_TransparentUnionConversion;
1919 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1921 // tryAtomicConversion has updated the standard conversion sequence
1924 } else if (ToType->isEventT() &&
1925 From->isIntegerConstantExpr(S.getASTContext()) &&
1926 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1927 SCS.Second = ICK_Zero_Event_Conversion;
1929 } else if (ToType->isQueueT() &&
1930 From->isIntegerConstantExpr(S.getASTContext()) &&
1931 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1932 SCS.Second = ICK_Zero_Queue_Conversion;
1934 } else if (ToType->isSamplerT() &&
1935 From->isIntegerConstantExpr(S.getASTContext())) {
1936 SCS.Second = ICK_Compatible_Conversion;
1939 // No second conversion required.
1940 SCS.Second = ICK_Identity;
1942 SCS.setToType(1, FromType);
1944 // The third conversion can be a function pointer conversion or a
1945 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1946 bool ObjCLifetimeConversion;
1947 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1948 // Function pointer conversions (removing 'noexcept') including removal of
1949 // 'noreturn' (Clang extension).
1950 SCS.Third = ICK_Function_Conversion;
1951 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1952 ObjCLifetimeConversion)) {
1953 SCS.Third = ICK_Qualification;
1954 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1957 // No conversion required
1958 SCS.Third = ICK_Identity;
1961 // C++ [over.best.ics]p6:
1962 // [...] Any difference in top-level cv-qualification is
1963 // subsumed by the initialization itself and does not constitute
1964 // a conversion. [...]
1965 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1966 QualType CanonTo = S.Context.getCanonicalType(ToType);
1967 if (CanonFrom.getLocalUnqualifiedType()
1968 == CanonTo.getLocalUnqualifiedType() &&
1969 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1971 CanonFrom = CanonTo;
1974 SCS.setToType(2, FromType);
1976 if (CanonFrom == CanonTo)
1979 // If we have not converted the argument type to the parameter type,
1980 // this is a bad conversion sequence, unless we're resolving an overload in C.
1981 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1984 ExprResult ER = ExprResult{From};
1985 Sema::AssignConvertType Conv =
1986 S.CheckSingleAssignmentConstraints(ToType, ER,
1988 /*DiagnoseCFAudited=*/false,
1989 /*ConvertRHS=*/false);
1990 ImplicitConversionKind SecondConv;
1992 case Sema::Compatible:
1993 SecondConv = ICK_C_Only_Conversion;
1995 // For our purposes, discarding qualifiers is just as bad as using an
1996 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1997 // qualifiers, as well.
1998 case Sema::CompatiblePointerDiscardsQualifiers:
1999 case Sema::IncompatiblePointer:
2000 case Sema::IncompatiblePointerSign:
2001 SecondConv = ICK_Incompatible_Pointer_Conversion;
2007 // First can only be an lvalue conversion, so we pretend that this was the
2008 // second conversion. First should already be valid from earlier in the
2010 SCS.Second = SecondConv;
2011 SCS.setToType(1, ToType);
2013 // Third is Identity, because Second should rank us worse than any other
2014 // conversion. This could also be ICK_Qualification, but it's simpler to just
2015 // lump everything in with the second conversion, and we don't gain anything
2016 // from making this ICK_Qualification.
2017 SCS.Third = ICK_Identity;
2018 SCS.setToType(2, ToType);
2023 IsTransparentUnionStandardConversion(Sema &S, Expr* From,
2025 bool InOverloadResolution,
2026 StandardConversionSequence &SCS,
2029 const RecordType *UT = ToType->getAsUnionType();
2030 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
2032 // The field to initialize within the transparent union.
2033 RecordDecl *UD = UT->getDecl();
2034 // It's compatible if the expression matches any of the fields.
2035 for (const auto *it : UD->fields()) {
2036 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2037 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2038 ToType = it->getType();
2045 /// IsIntegralPromotion - Determines whether the conversion from the
2046 /// expression From (whose potentially-adjusted type is FromType) to
2047 /// ToType is an integral promotion (C++ 4.5). If so, returns true and
2048 /// sets PromotedType to the promoted type.
2049 bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2050 const BuiltinType *To = ToType->getAs<BuiltinType>();
2051 // All integers are built-in.
2056 // An rvalue of type char, signed char, unsigned char, short int, or
2057 // unsigned short int can be converted to an rvalue of type int if
2058 // int can represent all the values of the source type; otherwise,
2059 // the source rvalue can be converted to an rvalue of type unsigned
2061 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
2062 !FromType->isEnumeralType()) {
2063 if (// We can promote any signed, promotable integer type to an int
2064 (FromType->isSignedIntegerType() ||
2065 // We can promote any unsigned integer type whose size is
2066 // less than int to an int.
2067 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2068 return To->getKind() == BuiltinType::Int;
2071 return To->getKind() == BuiltinType::UInt;
2074 // C++11 [conv.prom]p3:
2075 // A prvalue of an unscoped enumeration type whose underlying type is not
2076 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2077 // following types that can represent all the values of the enumeration
2078 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2079 // unsigned int, long int, unsigned long int, long long int, or unsigned
2080 // long long int. If none of the types in that list can represent all the
2081 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2082 // type can be converted to an rvalue a prvalue of the extended integer type
2083 // with lowest integer conversion rank (4.13) greater than the rank of long
2084 // long in which all the values of the enumeration can be represented. If
2085 // there are two such extended types, the signed one is chosen.
2086 // C++11 [conv.prom]p4:
2087 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2088 // can be converted to a prvalue of its underlying type. Moreover, if
2089 // integral promotion can be applied to its underlying type, a prvalue of an
2090 // unscoped enumeration type whose underlying type is fixed can also be
2091 // converted to a prvalue of the promoted underlying type.
2092 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2093 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2094 // provided for a scoped enumeration.
2095 if (FromEnumType->getDecl()->isScoped())
2098 // We can perform an integral promotion to the underlying type of the enum,
2099 // even if that's not the promoted type. Note that the check for promoting
2100 // the underlying type is based on the type alone, and does not consider
2101 // the bitfield-ness of the actual source expression.
2102 if (FromEnumType->getDecl()->isFixed()) {
2103 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2104 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2105 IsIntegralPromotion(nullptr, Underlying, ToType);
2108 // We have already pre-calculated the promotion type, so this is trivial.
2109 if (ToType->isIntegerType() &&
2110 isCompleteType(From->getBeginLoc(), FromType))
2111 return Context.hasSameUnqualifiedType(
2112 ToType, FromEnumType->getDecl()->getPromotionType());
2114 // C++ [conv.prom]p5:
2115 // If the bit-field has an enumerated type, it is treated as any other
2116 // value of that type for promotion purposes.
2118 // ... so do not fall through into the bit-field checks below in C++.
2119 if (getLangOpts().CPlusPlus)
2123 // C++0x [conv.prom]p2:
2124 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2125 // to an rvalue a prvalue of the first of the following types that can
2126 // represent all the values of its underlying type: int, unsigned int,
2127 // long int, unsigned long int, long long int, or unsigned long long int.
2128 // If none of the types in that list can represent all the values of its
2129 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2130 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2132 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2133 ToType->isIntegerType()) {
2134 // Determine whether the type we're converting from is signed or
2136 bool FromIsSigned = FromType->isSignedIntegerType();
2137 uint64_t FromSize = Context.getTypeSize(FromType);
2139 // The types we'll try to promote to, in the appropriate
2140 // order. Try each of these types.
2141 QualType PromoteTypes[6] = {
2142 Context.IntTy, Context.UnsignedIntTy,
2143 Context.LongTy, Context.UnsignedLongTy ,
2144 Context.LongLongTy, Context.UnsignedLongLongTy
2146 for (int Idx = 0; Idx < 6; ++Idx) {
2147 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2148 if (FromSize < ToSize ||
2149 (FromSize == ToSize &&
2150 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2151 // We found the type that we can promote to. If this is the
2152 // type we wanted, we have a promotion. Otherwise, no
2154 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2159 // An rvalue for an integral bit-field (9.6) can be converted to an
2160 // rvalue of type int if int can represent all the values of the
2161 // bit-field; otherwise, it can be converted to unsigned int if
2162 // unsigned int can represent all the values of the bit-field. If
2163 // the bit-field is larger yet, no integral promotion applies to
2164 // it. If the bit-field has an enumerated type, it is treated as any
2165 // other value of that type for promotion purposes (C++ 4.5p3).
2166 // FIXME: We should delay checking of bit-fields until we actually perform the
2169 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2170 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2171 // bit-fields and those whose underlying type is larger than int) for GCC
2174 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2175 llvm::APSInt BitWidth;
2176 if (FromType->isIntegralType(Context) &&
2177 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2178 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2179 ToSize = Context.getTypeSize(ToType);
2181 // Are we promoting to an int from a bitfield that fits in an int?
2182 if (BitWidth < ToSize ||
2183 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2184 return To->getKind() == BuiltinType::Int;
2187 // Are we promoting to an unsigned int from an unsigned bitfield
2188 // that fits into an unsigned int?
2189 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2190 return To->getKind() == BuiltinType::UInt;
2198 // An rvalue of type bool can be converted to an rvalue of type int,
2199 // with false becoming zero and true becoming one (C++ 4.5p4).
2200 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2207 /// IsFloatingPointPromotion - Determines whether the conversion from
2208 /// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2209 /// returns true and sets PromotedType to the promoted type.
2210 bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2211 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2212 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2213 /// An rvalue of type float can be converted to an rvalue of type
2214 /// double. (C++ 4.6p1).
2215 if (FromBuiltin->getKind() == BuiltinType::Float &&
2216 ToBuiltin->getKind() == BuiltinType::Double)
2220 // When a float is promoted to double or long double, or a
2221 // double is promoted to long double [...].
2222 if (!getLangOpts().CPlusPlus &&
2223 (FromBuiltin->getKind() == BuiltinType::Float ||
2224 FromBuiltin->getKind() == BuiltinType::Double) &&
2225 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2226 ToBuiltin->getKind() == BuiltinType::Float128))
2229 // Half can be promoted to float.
2230 if (!getLangOpts().NativeHalfType &&
2231 FromBuiltin->getKind() == BuiltinType::Half &&
2232 ToBuiltin->getKind() == BuiltinType::Float)
2239 /// Determine if a conversion is a complex promotion.
2241 /// A complex promotion is defined as a complex -> complex conversion
2242 /// where the conversion between the underlying real types is a
2243 /// floating-point or integral promotion.
2244 bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2245 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2249 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2253 return IsFloatingPointPromotion(FromComplex->getElementType(),
2254 ToComplex->getElementType()) ||
2255 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2256 ToComplex->getElementType());
2259 /// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2260 /// the pointer type FromPtr to a pointer to type ToPointee, with the
2261 /// same type qualifiers as FromPtr has on its pointee type. ToType,
2262 /// if non-empty, will be a pointer to ToType that may or may not have
2263 /// the right set of qualifiers on its pointee.
2266 BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2267 QualType ToPointee, QualType ToType,
2268 ASTContext &Context,
2269 bool StripObjCLifetime = false) {
2270 assert((FromPtr->getTypeClass() == Type::Pointer ||
2271 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2272 "Invalid similarly-qualified pointer type");
2274 /// Conversions to 'id' subsume cv-qualifier conversions.
2275 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2276 return ToType.getUnqualifiedType();
2278 QualType CanonFromPointee
2279 = Context.getCanonicalType(FromPtr->getPointeeType());
2280 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2281 Qualifiers Quals = CanonFromPointee.getQualifiers();
2283 if (StripObjCLifetime)
2284 Quals.removeObjCLifetime();
2286 // Exact qualifier match -> return the pointer type we're converting to.
2287 if (CanonToPointee.getLocalQualifiers() == Quals) {
2288 // ToType is exactly what we need. Return it.
2289 if (!ToType.isNull())
2290 return ToType.getUnqualifiedType();
2292 // Build a pointer to ToPointee. It has the right qualifiers
2294 if (isa<ObjCObjectPointerType>(ToType))
2295 return Context.getObjCObjectPointerType(ToPointee);
2296 return Context.getPointerType(ToPointee);
2299 // Just build a canonical type that has the right qualifiers.
2300 QualType QualifiedCanonToPointee
2301 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2303 if (isa<ObjCObjectPointerType>(ToType))
2304 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2305 return Context.getPointerType(QualifiedCanonToPointee);
2308 static bool isNullPointerConstantForConversion(Expr *Expr,
2309 bool InOverloadResolution,
2310 ASTContext &Context) {
2311 // Handle value-dependent integral null pointer constants correctly.
2312 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2313 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2314 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2315 return !InOverloadResolution;
2317 return Expr->isNullPointerConstant(Context,
2318 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2319 : Expr::NPC_ValueDependentIsNull);
2322 /// IsPointerConversion - Determines whether the conversion of the
2323 /// expression From, which has the (possibly adjusted) type FromType,
2324 /// can be converted to the type ToType via a pointer conversion (C++
2325 /// 4.10). If so, returns true and places the converted type (that
2326 /// might differ from ToType in its cv-qualifiers at some level) into
2329 /// This routine also supports conversions to and from block pointers
2330 /// and conversions with Objective-C's 'id', 'id<protocols...>', and
2331 /// pointers to interfaces. FIXME: Once we've determined the
2332 /// appropriate overloading rules for Objective-C, we may want to
2333 /// split the Objective-C checks into a different routine; however,
2334 /// GCC seems to consider all of these conversions to be pointer
2335 /// conversions, so for now they live here. IncompatibleObjC will be
2336 /// set if the conversion is an allowed Objective-C conversion that
2337 /// should result in a warning.
2338 bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2339 bool InOverloadResolution,
2340 QualType& ConvertedType,
2341 bool &IncompatibleObjC) {
2342 IncompatibleObjC = false;
2343 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2347 // Conversion from a null pointer constant to any Objective-C pointer type.
2348 if (ToType->isObjCObjectPointerType() &&
2349 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2350 ConvertedType = ToType;
2354 // Blocks: Block pointers can be converted to void*.
2355 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2356 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2357 ConvertedType = ToType;
2360 // Blocks: A null pointer constant can be converted to a block
2362 if (ToType->isBlockPointerType() &&
2363 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2364 ConvertedType = ToType;
2368 // If the left-hand-side is nullptr_t, the right side can be a null
2369 // pointer constant.
2370 if (ToType->isNullPtrType() &&
2371 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2372 ConvertedType = ToType;
2376 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2380 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2381 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2382 ConvertedType = ToType;
2386 // Beyond this point, both types need to be pointers
2387 // , including objective-c pointers.
2388 QualType ToPointeeType = ToTypePtr->getPointeeType();
2389 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2390 !getLangOpts().ObjCAutoRefCount) {
2391 ConvertedType = BuildSimilarlyQualifiedPointerType(
2392 FromType->getAs<ObjCObjectPointerType>(),
2397 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2401 QualType FromPointeeType = FromTypePtr->getPointeeType();
2403 // If the unqualified pointee types are the same, this can't be a
2404 // pointer conversion, so don't do all of the work below.
2405 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2408 // An rvalue of type "pointer to cv T," where T is an object type,
2409 // can be converted to an rvalue of type "pointer to cv void" (C++
2411 if (FromPointeeType->isIncompleteOrObjectType() &&
2412 ToPointeeType->isVoidType()) {
2413 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2416 /*StripObjCLifetime=*/true);
2420 // MSVC allows implicit function to void* type conversion.
2421 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2422 ToPointeeType->isVoidType()) {
2423 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2429 // When we're overloading in C, we allow a special kind of pointer
2430 // conversion for compatible-but-not-identical pointee types.
2431 if (!getLangOpts().CPlusPlus &&
2432 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2433 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2439 // C++ [conv.ptr]p3:
2441 // An rvalue of type "pointer to cv D," where D is a class type,
2442 // can be converted to an rvalue of type "pointer to cv B," where
2443 // B is a base class (clause 10) of D. If B is an inaccessible
2444 // (clause 11) or ambiguous (10.2) base class of D, a program that
2445 // necessitates this conversion is ill-formed. The result of the
2446 // conversion is a pointer to the base class sub-object of the
2447 // derived class object. The null pointer value is converted to
2448 // the null pointer value of the destination type.
2450 // Note that we do not check for ambiguity or inaccessibility
2451 // here. That is handled by CheckPointerConversion.
2452 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2453 ToPointeeType->isRecordType() &&
2454 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2455 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2456 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2462 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2463 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2464 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2473 /// Adopt the given qualifiers for the given type.
2474 static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2475 Qualifiers TQs = T.getQualifiers();
2477 // Check whether qualifiers already match.
2481 if (Qs.compatiblyIncludes(TQs))
2482 return Context.getQualifiedType(T, Qs);
2484 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2487 /// isObjCPointerConversion - Determines whether this is an
2488 /// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2489 /// with the same arguments and return values.
2490 bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2491 QualType& ConvertedType,
2492 bool &IncompatibleObjC) {
2493 if (!getLangOpts().ObjC)
2496 // The set of qualifiers on the type we're converting from.
2497 Qualifiers FromQualifiers = FromType.getQualifiers();
2499 // First, we handle all conversions on ObjC object pointer types.
2500 const ObjCObjectPointerType* ToObjCPtr =
2501 ToType->getAs<ObjCObjectPointerType>();
2502 const ObjCObjectPointerType *FromObjCPtr =
2503 FromType->getAs<ObjCObjectPointerType>();
2505 if (ToObjCPtr && FromObjCPtr) {
2506 // If the pointee types are the same (ignoring qualifications),
2507 // then this is not a pointer conversion.
2508 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2509 FromObjCPtr->getPointeeType()))
2512 // Conversion between Objective-C pointers.
2513 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2514 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2515 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2516 if (getLangOpts().CPlusPlus && LHS && RHS &&
2517 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2518 FromObjCPtr->getPointeeType()))
2520 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2521 ToObjCPtr->getPointeeType(),
2523 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2527 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2528 // Okay: this is some kind of implicit downcast of Objective-C
2529 // interfaces, which is permitted. However, we're going to
2530 // complain about it.
2531 IncompatibleObjC = true;
2532 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2533 ToObjCPtr->getPointeeType(),
2535 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2539 // Beyond this point, both types need to be C pointers or block pointers.
2540 QualType ToPointeeType;
2541 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2542 ToPointeeType = ToCPtr->getPointeeType();
2543 else if (const BlockPointerType *ToBlockPtr =
2544 ToType->getAs<BlockPointerType>()) {
2545 // Objective C++: We're able to convert from a pointer to any object
2546 // to a block pointer type.
2547 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2548 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2551 ToPointeeType = ToBlockPtr->getPointeeType();
2553 else if (FromType->getAs<BlockPointerType>() &&
2554 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2555 // Objective C++: We're able to convert from a block pointer type to a
2556 // pointer to any object.
2557 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2563 QualType FromPointeeType;
2564 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2565 FromPointeeType = FromCPtr->getPointeeType();
2566 else if (const BlockPointerType *FromBlockPtr =
2567 FromType->getAs<BlockPointerType>())
2568 FromPointeeType = FromBlockPtr->getPointeeType();
2572 // If we have pointers to pointers, recursively check whether this
2573 // is an Objective-C conversion.
2574 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2575 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2576 IncompatibleObjC)) {
2577 // We always complain about this conversion.
2578 IncompatibleObjC = true;
2579 ConvertedType = Context.getPointerType(ConvertedType);
2580 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2583 // Allow conversion of pointee being objective-c pointer to another one;
2585 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2586 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2587 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2588 IncompatibleObjC)) {
2590 ConvertedType = Context.getPointerType(ConvertedType);
2591 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2595 // If we have pointers to functions or blocks, check whether the only
2596 // differences in the argument and result types are in Objective-C
2597 // pointer conversions. If so, we permit the conversion (but
2598 // complain about it).
2599 const FunctionProtoType *FromFunctionType
2600 = FromPointeeType->getAs<FunctionProtoType>();
2601 const FunctionProtoType *ToFunctionType
2602 = ToPointeeType->getAs<FunctionProtoType>();
2603 if (FromFunctionType && ToFunctionType) {
2604 // If the function types are exactly the same, this isn't an
2605 // Objective-C pointer conversion.
2606 if (Context.getCanonicalType(FromPointeeType)
2607 == Context.getCanonicalType(ToPointeeType))
2610 // Perform the quick checks that will tell us whether these
2611 // function types are obviously different.
2612 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2613 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2614 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2617 bool HasObjCConversion = false;
2618 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2619 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2620 // Okay, the types match exactly. Nothing to do.
2621 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2622 ToFunctionType->getReturnType(),
2623 ConvertedType, IncompatibleObjC)) {
2624 // Okay, we have an Objective-C pointer conversion.
2625 HasObjCConversion = true;
2627 // Function types are too different. Abort.
2631 // Check argument types.
2632 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2633 ArgIdx != NumArgs; ++ArgIdx) {
2634 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2635 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2636 if (Context.getCanonicalType(FromArgType)
2637 == Context.getCanonicalType(ToArgType)) {
2638 // Okay, the types match exactly. Nothing to do.
2639 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2640 ConvertedType, IncompatibleObjC)) {
2641 // Okay, we have an Objective-C pointer conversion.
2642 HasObjCConversion = true;
2644 // Argument types are too different. Abort.
2649 if (HasObjCConversion) {
2650 // We had an Objective-C conversion. Allow this pointer
2651 // conversion, but complain about it.
2652 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2653 IncompatibleObjC = true;
2661 /// Determine whether this is an Objective-C writeback conversion,
2662 /// used for parameter passing when performing automatic reference counting.
2664 /// \param FromType The type we're converting form.
2666 /// \param ToType The type we're converting to.
2668 /// \param ConvertedType The type that will be produced after applying
2669 /// this conversion.
2670 bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2671 QualType &ConvertedType) {
2672 if (!getLangOpts().ObjCAutoRefCount ||
2673 Context.hasSameUnqualifiedType(FromType, ToType))
2676 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2678 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2679 ToPointee = ToPointer->getPointeeType();
2683 Qualifiers ToQuals = ToPointee.getQualifiers();
2684 if (!ToPointee->isObjCLifetimeType() ||
2685 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2686 !ToQuals.withoutObjCLifetime().empty())
2689 // Argument must be a pointer to __strong to __weak.
2690 QualType FromPointee;
2691 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2692 FromPointee = FromPointer->getPointeeType();
2696 Qualifiers FromQuals = FromPointee.getQualifiers();
2697 if (!FromPointee->isObjCLifetimeType() ||
2698 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2699 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2702 // Make sure that we have compatible qualifiers.
2703 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2704 if (!ToQuals.compatiblyIncludes(FromQuals))
2707 // Remove qualifiers from the pointee type we're converting from; they
2708 // aren't used in the compatibility check belong, and we'll be adding back
2709 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2710 FromPointee = FromPointee.getUnqualifiedType();
2712 // The unqualified form of the pointee types must be compatible.
2713 ToPointee = ToPointee.getUnqualifiedType();
2714 bool IncompatibleObjC;
2715 if (Context.typesAreCompatible(FromPointee, ToPointee))
2716 FromPointee = ToPointee;
2717 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2721 /// Construct the type we're converting to, which is a pointer to
2722 /// __autoreleasing pointee.
2723 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2724 ConvertedType = Context.getPointerType(FromPointee);
2728 bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2729 QualType& ConvertedType) {
2730 QualType ToPointeeType;
2731 if (const BlockPointerType *ToBlockPtr =
2732 ToType->getAs<BlockPointerType>())
2733 ToPointeeType = ToBlockPtr->getPointeeType();
2737 QualType FromPointeeType;
2738 if (const BlockPointerType *FromBlockPtr =
2739 FromType->getAs<BlockPointerType>())
2740 FromPointeeType = FromBlockPtr->getPointeeType();
2743 // We have pointer to blocks, check whether the only
2744 // differences in the argument and result types are in Objective-C
2745 // pointer conversions. If so, we permit the conversion.
2747 const FunctionProtoType *FromFunctionType
2748 = FromPointeeType->getAs<FunctionProtoType>();
2749 const FunctionProtoType *ToFunctionType
2750 = ToPointeeType->getAs<FunctionProtoType>();
2752 if (!FromFunctionType || !ToFunctionType)
2755 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2758 // Perform the quick checks that will tell us whether these
2759 // function types are obviously different.
2760 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2761 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2764 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2765 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2766 if (FromEInfo != ToEInfo)
2769 bool IncompatibleObjC = false;
2770 if (Context.hasSameType(FromFunctionType->getReturnType(),
2771 ToFunctionType->getReturnType())) {
2772 // Okay, the types match exactly. Nothing to do.
2774 QualType RHS = FromFunctionType->getReturnType();
2775 QualType LHS = ToFunctionType->getReturnType();
2776 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2777 !RHS.hasQualifiers() && LHS.hasQualifiers())
2778 LHS = LHS.getUnqualifiedType();
2780 if (Context.hasSameType(RHS,LHS)) {
2782 } else if (isObjCPointerConversion(RHS, LHS,
2783 ConvertedType, IncompatibleObjC)) {
2784 if (IncompatibleObjC)
2786 // Okay, we have an Objective-C pointer conversion.
2792 // Check argument types.
2793 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2794 ArgIdx != NumArgs; ++ArgIdx) {
2795 IncompatibleObjC = false;
2796 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2797 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2798 if (Context.hasSameType(FromArgType, ToArgType)) {
2799 // Okay, the types match exactly. Nothing to do.
2800 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2801 ConvertedType, IncompatibleObjC)) {
2802 if (IncompatibleObjC)
2804 // Okay, we have an Objective-C pointer conversion.
2806 // Argument types are too different. Abort.
2810 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2811 bool CanUseToFPT, CanUseFromFPT;
2812 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2813 CanUseToFPT, CanUseFromFPT,
2817 ConvertedType = ToType;
2825 ft_parameter_mismatch,
2827 ft_qualifer_mismatch,
2831 /// Attempts to get the FunctionProtoType from a Type. Handles
2832 /// MemberFunctionPointers properly.
2833 static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2834 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2837 if (auto *MPT = FromType->getAs<MemberPointerType>())
2838 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2843 /// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2844 /// function types. Catches different number of parameter, mismatch in
2845 /// parameter types, and different return types.
2846 void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2847 QualType FromType, QualType ToType) {
2848 // If either type is not valid, include no extra info.
2849 if (FromType.isNull() || ToType.isNull()) {
2850 PDiag << ft_default;
2854 // Get the function type from the pointers.
2855 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2856 const auto *FromMember = FromType->castAs<MemberPointerType>(),
2857 *ToMember = ToType->castAs<MemberPointerType>();
2858 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2859 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2860 << QualType(FromMember->getClass(), 0);
2863 FromType = FromMember->getPointeeType();
2864 ToType = ToMember->getPointeeType();
2867 if (FromType->isPointerType())
2868 FromType = FromType->getPointeeType();
2869 if (ToType->isPointerType())
2870 ToType = ToType->getPointeeType();
2872 // Remove references.
2873 FromType = FromType.getNonReferenceType();
2874 ToType = ToType.getNonReferenceType();
2876 // Don't print extra info for non-specialized template functions.
2877 if (FromType->isInstantiationDependentType() &&
2878 !FromType->getAs<TemplateSpecializationType>()) {
2879 PDiag << ft_default;
2883 // No extra info for same types.
2884 if (Context.hasSameType(FromType, ToType)) {
2885 PDiag << ft_default;
2889 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2890 *ToFunction = tryGetFunctionProtoType(ToType);
2892 // Both types need to be function types.
2893 if (!FromFunction || !ToFunction) {
2894 PDiag << ft_default;
2898 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2899 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2900 << FromFunction->getNumParams();
2904 // Handle different parameter types.
2906 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2907 PDiag << ft_parameter_mismatch << ArgPos + 1
2908 << ToFunction->getParamType(ArgPos)
2909 << FromFunction->getParamType(ArgPos);
2913 // Handle different return type.
2914 if (!Context.hasSameType(FromFunction->getReturnType(),
2915 ToFunction->getReturnType())) {
2916 PDiag << ft_return_type << ToFunction->getReturnType()
2917 << FromFunction->getReturnType();
2921 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2922 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2923 << FromFunction->getMethodQuals();
2927 // Handle exception specification differences on canonical type (in C++17
2929 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2931 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2933 PDiag << ft_noexcept;
2937 // Unable to find a difference, so add no extra info.
2938 PDiag << ft_default;
2941 /// FunctionParamTypesAreEqual - This routine checks two function proto types
2942 /// for equality of their argument types. Caller has already checked that
2943 /// they have same number of arguments. If the parameters are different,
2944 /// ArgPos will have the parameter index of the first different parameter.
2945 bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2946 const FunctionProtoType *NewType,
2948 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2949 N = NewType->param_type_begin(),
2950 E = OldType->param_type_end();
2951 O && (O != E); ++O, ++N) {
2952 // Ignore address spaces in pointee type. This is to disallow overloading
2953 // on __ptr32/__ptr64 address spaces.
2954 QualType Old = Context.removePtrSizeAddrSpace(O->getUnqualifiedType());
2955 QualType New = Context.removePtrSizeAddrSpace(N->getUnqualifiedType());
2957 if (!Context.hasSameType(Old, New)) {
2959 *ArgPos = O - OldType->param_type_begin();
2966 /// CheckPointerConversion - Check the pointer conversion from the
2967 /// expression From to the type ToType. This routine checks for
2968 /// ambiguous or inaccessible derived-to-base pointer
2969 /// conversions for which IsPointerConversion has already returned
2970 /// true. It returns true and produces a diagnostic if there was an
2971 /// error, or returns false otherwise.
2972 bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2974 CXXCastPath& BasePath,
2975 bool IgnoreBaseAccess,
2977 QualType FromType = From->getType();
2978 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2982 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2983 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2984 Expr::NPCK_ZeroExpression) {
2985 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2986 DiagRuntimeBehavior(From->getExprLoc(), From,
2987 PDiag(diag::warn_impcast_bool_to_null_pointer)
2988 << ToType << From->getSourceRange());
2989 else if (!isUnevaluatedContext())
2990 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2991 << ToType << From->getSourceRange();
2993 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2994 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2995 QualType FromPointeeType = FromPtrType->getPointeeType(),
2996 ToPointeeType = ToPtrType->getPointeeType();
2998 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2999 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3000 // We must have a derived-to-base conversion. Check an
3001 // ambiguous or inaccessible conversion.
3002 unsigned InaccessibleID = 0;
3003 unsigned AmbigiousID = 0;
3005 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3006 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
3008 if (CheckDerivedToBaseConversion(
3009 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
3010 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3011 &BasePath, IgnoreBaseAccess))
3014 // The conversion was successful.
3015 Kind = CK_DerivedToBase;
3018 if (Diagnose && !IsCStyleOrFunctionalCast &&
3019 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3020 assert(getLangOpts().MSVCCompat &&
3021 "this should only be possible with MSVCCompat!");
3022 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3023 << From->getSourceRange();
3026 } else if (const ObjCObjectPointerType *ToPtrType =
3027 ToType->getAs<ObjCObjectPointerType>()) {
3028 if (const ObjCObjectPointerType *FromPtrType =
3029 FromType->getAs<ObjCObjectPointerType>()) {
3030 // Objective-C++ conversions are always okay.
3031 // FIXME: We should have a different class of conversions for the
3032 // Objective-C++ implicit conversions.
3033 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3035 } else if (FromType->isBlockPointerType()) {
3036 Kind = CK_BlockPointerToObjCPointerCast;
3038 Kind = CK_CPointerToObjCPointerCast;
3040 } else if (ToType->isBlockPointerType()) {
3041 if (!FromType->isBlockPointerType())
3042 Kind = CK_AnyPointerToBlockPointerCast;
3045 // We shouldn't fall into this case unless it's valid for other
3047 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
3048 Kind = CK_NullToPointer;
3053 /// IsMemberPointerConversion - Determines whether the conversion of the
3054 /// expression From, which has the (possibly adjusted) type FromType, can be
3055 /// converted to the type ToType via a member pointer conversion (C++ 4.11).
3056 /// If so, returns true and places the converted type (that might differ from
3057 /// ToType in its cv-qualifiers at some level) into ConvertedType.
3058 bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
3060 bool InOverloadResolution,
3061 QualType &ConvertedType) {
3062 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3066 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3067 if (From->isNullPointerConstant(Context,
3068 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3069 : Expr::NPC_ValueDependentIsNull)) {
3070 ConvertedType = ToType;
3074 // Otherwise, both types have to be member pointers.
3075 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3079 // A pointer to member of B can be converted to a pointer to member of D,
3080 // where D is derived from B (C++ 4.11p2).
3081 QualType FromClass(FromTypePtr->getClass(), 0);
3082 QualType ToClass(ToTypePtr->getClass(), 0);
3084 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3085 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3086 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3087 ToClass.getTypePtr());
3094 /// CheckMemberPointerConversion - Check the member pointer conversion from the
3095 /// expression From to the type ToType. This routine checks for ambiguous or
3096 /// virtual or inaccessible base-to-derived member pointer conversions
3097 /// for which IsMemberPointerConversion has already returned true. It returns
3098 /// true and produces a diagnostic if there was an error, or returns false
3100 bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3102 CXXCastPath &BasePath,
3103 bool IgnoreBaseAccess) {
3104 QualType FromType = From->getType();
3105 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3107 // This must be a null pointer to member pointer conversion
3108 assert(From->isNullPointerConstant(Context,
3109 Expr::NPC_ValueDependentIsNull) &&
3110 "Expr must be null pointer constant!");
3111 Kind = CK_NullToMemberPointer;
3115 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3116 assert(ToPtrType && "No member pointer cast has a target type "
3117 "that is not a member pointer.");
3119 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3120 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3122 // FIXME: What about dependent types?
3123 assert(FromClass->isRecordType() && "Pointer into non-class.");
3124 assert(ToClass->isRecordType() && "Pointer into non-class.");
3126 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3127 /*DetectVirtual=*/true);
3128 bool DerivationOkay =
3129 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3130 assert(DerivationOkay &&
3131 "Should not have been called if derivation isn't OK.");
3132 (void)DerivationOkay;
3134 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3135 getUnqualifiedType())) {
3136 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3137 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3138 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3142 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3143 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3144 << FromClass << ToClass << QualType(VBase, 0)
3145 << From->getSourceRange();
3149 if (!IgnoreBaseAccess)
3150 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3152 diag::err_downcast_from_inaccessible_base);
3154 // Must be a base to derived member conversion.
3155 BuildBasePathArray(Paths, BasePath);
3156 Kind = CK_BaseToDerivedMemberPointer;
3160 /// Determine whether the lifetime conversion between the two given
3161 /// qualifiers sets is nontrivial.
3162 static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3163 Qualifiers ToQuals) {
3164 // Converting anything to const __unsafe_unretained is trivial.
3165 if (ToQuals.hasConst() &&
3166 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3172 /// Perform a single iteration of the loop for checking if a qualification
3173 /// conversion is valid.
3175 /// Specifically, check whether any change between the qualifiers of \p
3176 /// FromType and \p ToType is permissible, given knowledge about whether every
3177 /// outer layer is const-qualified.
3178 static bool isQualificationConversionStep(QualType FromType, QualType ToType,
3179 bool CStyle, bool IsTopLevel,
3180 bool &PreviousToQualsIncludeConst,
3181 bool &ObjCLifetimeConversion) {
3182 Qualifiers FromQuals = FromType.getQualifiers();
3183 Qualifiers ToQuals = ToType.getQualifiers();
3185 // Ignore __unaligned qualifier if this type is void.
3186 if (ToType.getUnqualifiedType()->isVoidType())
3187 FromQuals.removeUnaligned();
3190 // Check Objective-C lifetime conversions.
3191 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3192 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3193 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3194 ObjCLifetimeConversion = true;
3195 FromQuals.removeObjCLifetime();
3196 ToQuals.removeObjCLifetime();
3198 // Qualification conversions cannot cast between different
3199 // Objective-C lifetime qualifiers.
3204 // Allow addition/removal of GC attributes but not changing GC attributes.
3205 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3206 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3207 FromQuals.removeObjCGCAttr();
3208 ToQuals.removeObjCGCAttr();
3211 // -- for every j > 0, if const is in cv 1,j then const is in cv
3212 // 2,j, and similarly for volatile.
3213 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3216 // If address spaces mismatch:
3217 // - in top level it is only valid to convert to addr space that is a
3218 // superset in all cases apart from C-style casts where we allow
3219 // conversions between overlapping address spaces.
3220 // - in non-top levels it is not a valid conversion.
3221 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3223 !(ToQuals.isAddressSpaceSupersetOf(FromQuals) ||
3224 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals)))))
3227 // -- if the cv 1,j and cv 2,j are different, then const is in
3228 // every cv for 0 < k < j.
3229 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3230 !PreviousToQualsIncludeConst)
3233 // Keep track of whether all prior cv-qualifiers in the "to" type
3235 PreviousToQualsIncludeConst =
3236 PreviousToQualsIncludeConst && ToQuals.hasConst();
3240 /// IsQualificationConversion - Determines whether the conversion from
3241 /// an rvalue of type FromType to ToType is a qualification conversion
3244 /// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3245 /// when the qualification conversion involves a change in the Objective-C
3246 /// object lifetime.
3248 Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3249 bool CStyle, bool &ObjCLifetimeConversion) {
3250 FromType = Context.getCanonicalType(FromType);
3251 ToType = Context.getCanonicalType(ToType);
3252 ObjCLifetimeConversion = false;
3254 // If FromType and ToType are the same type, this is not a
3255 // qualification conversion.
3256 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3260 // A conversion can add cv-qualifiers at levels other than the first
3261 // in multi-level pointers, subject to the following rules: [...]
3262 bool PreviousToQualsIncludeConst = true;
3263 bool UnwrappedAnyPointer = false;
3264 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3265 if (!isQualificationConversionStep(
3266 FromType, ToType, CStyle, !UnwrappedAnyPointer,
3267 PreviousToQualsIncludeConst, ObjCLifetimeConversion))
3269 UnwrappedAnyPointer = true;
3272 // We are left with FromType and ToType being the pointee types
3273 // after unwrapping the original FromType and ToType the same number
3274 // of times. If we unwrapped any pointers, and if FromType and
3275 // ToType have the same unqualified type (since we checked
3276 // qualifiers above), then this is a qualification conversion.
3277 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3280 /// - Determine whether this is a conversion from a scalar type to an
3283 /// If successful, updates \c SCS's second and third steps in the conversion
3284 /// sequence to finish the conversion.
3285 static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3286 bool InOverloadResolution,
3287 StandardConversionSequence &SCS,
3289 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3293 StandardConversionSequence InnerSCS;
3294 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3295 InOverloadResolution, InnerSCS,
3296 CStyle, /*AllowObjCWritebackConversion=*/false))
3299 SCS.Second = InnerSCS.Second;
3300 SCS.setToType(1, InnerSCS.getToType(1));
3301 SCS.Third = InnerSCS.Third;
3302 SCS.QualificationIncludesObjCLifetime
3303 = InnerSCS.QualificationIncludesObjCLifetime;
3304 SCS.setToType(2, InnerSCS.getToType(2));
3308 static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3309 CXXConstructorDecl *Constructor,
3311 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3312 if (CtorType->getNumParams() > 0) {
3313 QualType FirstArg = CtorType->getParamType(0);
3314 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3320 static OverloadingResult
3321 IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3323 UserDefinedConversionSequence &User,
3324 OverloadCandidateSet &CandidateSet,
3325 bool AllowExplicit) {
3326 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3327 for (auto *D : S.LookupConstructors(To)) {
3328 auto Info = getConstructorInfo(D);
3332 bool Usable = !Info.Constructor->isInvalidDecl() &&
3333 S.isInitListConstructor(Info.Constructor);
3335 // If the first argument is (a reference to) the target type,
3336 // suppress conversions.
3337 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3338 S.Context, Info.Constructor, ToType);
3339 if (Info.ConstructorTmpl)
3340 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3341 /*ExplicitArgs*/ nullptr, From,
3342 CandidateSet, SuppressUserConversions,
3343 /*PartialOverloading*/ false,
3346 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3347 CandidateSet, SuppressUserConversions,
3348 /*PartialOverloading*/ false, AllowExplicit);
3352 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3354 OverloadCandidateSet::iterator Best;
3355 switch (auto Result =
3356 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3359 // Record the standard conversion we used and the conversion function.
3360 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3361 QualType ThisType = Constructor->getThisType();
3362 // Initializer lists don't have conversions as such.
3363 User.Before.setAsIdentityConversion();
3364 User.HadMultipleCandidates = HadMultipleCandidates;
3365 User.ConversionFunction = Constructor;
3366 User.FoundConversionFunction = Best->FoundDecl;
3367 User.After.setAsIdentityConversion();
3368 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3369 User.After.setAllToTypes(ToType);
3373 case OR_No_Viable_Function:
3374 return OR_No_Viable_Function;
3376 return OR_Ambiguous;
3379 llvm_unreachable("Invalid OverloadResult!");
3382 /// Determines whether there is a user-defined conversion sequence
3383 /// (C++ [over.ics.user]) that converts expression From to the type
3384 /// ToType. If such a conversion exists, User will contain the
3385 /// user-defined conversion sequence that performs such a conversion
3386 /// and this routine will return true. Otherwise, this routine returns
3387 /// false and User is unspecified.
3389 /// \param AllowExplicit true if the conversion should consider C++0x
3390 /// "explicit" conversion functions as well as non-explicit conversion
3391 /// functions (C++0x [class.conv.fct]p2).
3393 /// \param AllowObjCConversionOnExplicit true if the conversion should
3394 /// allow an extra Objective-C pointer conversion on uses of explicit
3395 /// constructors. Requires \c AllowExplicit to also be set.
3396 static OverloadingResult
3397 IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3398 UserDefinedConversionSequence &User,
3399 OverloadCandidateSet &CandidateSet,
3401 bool AllowObjCConversionOnExplicit) {
3402 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3403 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3405 // Whether we will only visit constructors.
3406 bool ConstructorsOnly = false;
3408 // If the type we are conversion to is a class type, enumerate its
3410 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3411 // C++ [over.match.ctor]p1:
3412 // When objects of class type are direct-initialized (8.5), or
3413 // copy-initialized from an expression of the same or a
3414 // derived class type (8.5), overload resolution selects the
3415 // constructor. [...] For copy-initialization, the candidate
3416 // functions are all the converting constructors (12.3.1) of
3417 // that class. The argument list is the expression-list within
3418 // the parentheses of the initializer.
3419 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3420 (From->getType()->getAs<RecordType>() &&
3421 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3422 ConstructorsOnly = true;
3424 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3425 // We're not going to find any constructors.
3426 } else if (CXXRecordDecl *ToRecordDecl
3427 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3429 Expr **Args = &From;
3430 unsigned NumArgs = 1;
3431 bool ListInitializing = false;
3432 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3433 // But first, see if there is an init-list-constructor that will work.
3434 OverloadingResult Result = IsInitializerListConstructorConversion(
3435 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3436 if (Result != OR_No_Viable_Function)
3440 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3442 // If we're list-initializing, we pass the individual elements as
3443 // arguments, not the entire list.
3444 Args = InitList->getInits();
3445 NumArgs = InitList->getNumInits();
3446 ListInitializing = true;
3449 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3450 auto Info = getConstructorInfo(D);
3454 bool Usable = !Info.Constructor->isInvalidDecl();
3455 if (!ListInitializing)
3456 Usable = Usable && Info.Constructor->isConvertingConstructor(
3457 /*AllowExplicit*/ true);
3459 bool SuppressUserConversions = !ConstructorsOnly;
3460 if (SuppressUserConversions && ListInitializing) {
3461 SuppressUserConversions = false;
3463 // If the first argument is (a reference to) the target type,
3464 // suppress conversions.
3465 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3466 S.Context, Info.Constructor, ToType);
3469 if (Info.ConstructorTmpl)
3470 S.AddTemplateOverloadCandidate(
3471 Info.ConstructorTmpl, Info.FoundDecl,
3472 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3473 CandidateSet, SuppressUserConversions,
3474 /*PartialOverloading*/ false, AllowExplicit);
3476 // Allow one user-defined conversion when user specifies a
3477 // From->ToType conversion via an static cast (c-style, etc).
3478 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3479 llvm::makeArrayRef(Args, NumArgs),
3480 CandidateSet, SuppressUserConversions,
3481 /*PartialOverloading*/ false, AllowExplicit);
3487 // Enumerate conversion functions, if we're allowed to.
3488 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3489 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3490 // No conversion functions from incomplete types.
3491 } else if (const RecordType *FromRecordType =
3492 From->getType()->getAs<RecordType>()) {
3493 if (CXXRecordDecl *FromRecordDecl
3494 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3495 // Add all of the conversion functions as candidates.
3496 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3497 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3498 DeclAccessPair FoundDecl = I.getPair();
3499 NamedDecl *D = FoundDecl.getDecl();
3500 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3501 if (isa<UsingShadowDecl>(D))
3502 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3504 CXXConversionDecl *Conv;
3505 FunctionTemplateDecl *ConvTemplate;
3506 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3507 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3509 Conv = cast<CXXConversionDecl>(D);
3512 S.AddTemplateConversionCandidate(
3513 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3514 CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit);
3516 S.AddConversionCandidate(
3517 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
3518 AllowObjCConversionOnExplicit, AllowExplicit);
3523 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3525 OverloadCandidateSet::iterator Best;
3526 switch (auto Result =
3527 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3530 // Record the standard conversion we used and the conversion function.
3531 if (CXXConstructorDecl *Constructor
3532 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3533 // C++ [over.ics.user]p1:
3534 // If the user-defined conversion is specified by a
3535 // constructor (12.3.1), the initial standard conversion
3536 // sequence converts the source type to the type required by
3537 // the argument of the constructor.
3539 QualType ThisType = Constructor->getThisType();
3540 if (isa<InitListExpr>(From)) {
3541 // Initializer lists don't have conversions as such.
3542 User.Before.setAsIdentityConversion();
3544 if (Best->Conversions[0].isEllipsis())
3545 User.EllipsisConversion = true;
3547 User.Before = Best->Conversions[0].Standard;
3548 User.EllipsisConversion = false;
3551 User.HadMultipleCandidates = HadMultipleCandidates;
3552 User.ConversionFunction = Constructor;
3553 User.FoundConversionFunction = Best->FoundDecl;
3554 User.After.setAsIdentityConversion();
3555 User.After.setFromType(ThisType->castAs<PointerType>()->getPointeeType());
3556 User.After.setAllToTypes(ToType);
3559 if (CXXConversionDecl *Conversion
3560 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3561 // C++ [over.ics.user]p1:
3563 // [...] If the user-defined conversion is specified by a
3564 // conversion function (12.3.2), the initial standard
3565 // conversion sequence converts the source type to the
3566 // implicit object parameter of the conversion function.
3567 User.Before = Best->Conversions[0].Standard;
3568 User.HadMultipleCandidates = HadMultipleCandidates;
3569 User.ConversionFunction = Conversion;
3570 User.FoundConversionFunction = Best->FoundDecl;
3571 User.EllipsisConversion = false;
3573 // C++ [over.ics.user]p2:
3574 // The second standard conversion sequence converts the
3575 // result of the user-defined conversion to the target type
3576 // for the sequence. Since an implicit conversion sequence
3577 // is an initialization, the special rules for
3578 // initialization by user-defined conversion apply when
3579 // selecting the best user-defined conversion for a
3580 // user-defined conversion sequence (see 13.3.3 and
3582 User.After = Best->FinalConversion;
3585 llvm_unreachable("Not a constructor or conversion function?");
3587 case OR_No_Viable_Function:
3588 return OR_No_Viable_Function;
3591 return OR_Ambiguous;
3594 llvm_unreachable("Invalid OverloadResult!");
3598 Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3599 ImplicitConversionSequence ICS;
3600 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3601 OverloadCandidateSet::CSK_Normal);
3602 OverloadingResult OvResult =
3603 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3604 CandidateSet, false, false);
3606 if (!(OvResult == OR_Ambiguous ||
3607 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3610 auto Cands = CandidateSet.CompleteCandidates(
3612 OvResult == OR_Ambiguous ? OCD_AmbiguousCandidates : OCD_AllCandidates,
3614 if (OvResult == OR_Ambiguous)
3615 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3616 << From->getType() << ToType << From->getSourceRange();
3617 else { // OR_No_Viable_Function && !CandidateSet.empty()
3618 if (!RequireCompleteType(From->getBeginLoc(), ToType,
3619 diag::err_typecheck_nonviable_condition_incomplete,
3620 From->getType(), From->getSourceRange()))
3621 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3622 << false << From->getType() << From->getSourceRange() << ToType;
3625 CandidateSet.NoteCandidates(
3626 *this, From, Cands);
3630 /// Compare the user-defined conversion functions or constructors
3631 /// of two user-defined conversion sequences to determine whether any ordering
3633 static ImplicitConversionSequence::CompareKind
3634 compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3635 FunctionDecl *Function2) {
3636 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3637 return ImplicitConversionSequence::Indistinguishable;
3640 // If both conversion functions are implicitly-declared conversions from
3641 // a lambda closure type to a function pointer and a block pointer,
3642 // respectively, always prefer the conversion to a function pointer,
3643 // because the function pointer is more lightweight and is more likely
3644 // to keep code working.
3645 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3647 return ImplicitConversionSequence::Indistinguishable;
3649 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3651 return ImplicitConversionSequence::Indistinguishable;
3653 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3654 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3655 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3656 if (Block1 != Block2)
3657 return Block1 ? ImplicitConversionSequence::Worse
3658 : ImplicitConversionSequence::Better;
3661 return ImplicitConversionSequence::Indistinguishable;
3664 static bool hasDeprecatedStringLiteralToCharPtrConversion(
3665 const ImplicitConversionSequence &ICS) {
3666 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3667 (ICS.isUserDefined() &&
3668 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3671 /// CompareImplicitConversionSequences - Compare two implicit
3672 /// conversion sequences to determine whether one is better than the
3673 /// other or if they are indistinguishable (C++ 13.3.3.2).
3674 static ImplicitConversionSequence::CompareKind
3675 CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3676 const ImplicitConversionSequence& ICS1,
3677 const ImplicitConversionSequence& ICS2)
3679 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3680 // conversion sequences (as defined in 13.3.3.1)
3681 // -- a standard conversion sequence (13.3.3.1.1) is a better
3682 // conversion sequence than a user-defined conversion sequence or
3683 // an ellipsis conversion sequence, and
3684 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3685 // conversion sequence than an ellipsis conversion sequence
3688 // C++0x [over.best.ics]p10:
3689 // For the purpose of ranking implicit conversion sequences as
3690 // described in 13.3.3.2, the ambiguous conversion sequence is
3691 // treated as a user-defined sequence that is indistinguishable
3692 // from any other user-defined conversion sequence.
3694 // String literal to 'char *' conversion has been deprecated in C++03. It has
3695 // been removed from C++11. We still accept this conversion, if it happens at
3696 // the best viable function. Otherwise, this conversion is considered worse
3697 // than ellipsis conversion. Consider this as an extension; this is not in the
3698 // standard. For example:
3700 // int &f(...); // #1
3701 // void f(char*); // #2
3702 // void g() { int &r = f("foo"); }
3704 // In C++03, we pick #2 as the best viable function.
3705 // In C++11, we pick #1 as the best viable function, because ellipsis
3706 // conversion is better than string-literal to char* conversion (since there
3707 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3708 // convert arguments, #2 would be the best viable function in C++11.
3709 // If the best viable function has this conversion, a warning will be issued
3710 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3712 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3713 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3714 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3715 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3716 ? ImplicitConversionSequence::Worse
3717 : ImplicitConversionSequence::Better;
3719 if (ICS1.getKindRank() < ICS2.getKindRank())
3720 return ImplicitConversionSequence::Better;
3721 if (ICS2.getKindRank() < ICS1.getKindRank())
3722 return ImplicitConversionSequence::Worse;
3724 // The following checks require both conversion sequences to be of
3726 if (ICS1.getKind() != ICS2.getKind())
3727 return ImplicitConversionSequence::Indistinguishable;
3729 ImplicitConversionSequence::CompareKind Result =
3730 ImplicitConversionSequence::Indistinguishable;
3732 // Two implicit conversion sequences of the same form are
3733 // indistinguishable conversion sequences unless one of the
3734 // following rules apply: (C++ 13.3.3.2p3):
3736 // List-initialization sequence L1 is a better conversion sequence than
3737 // list-initialization sequence L2 if:
3738 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3740 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3741 // and N1 is smaller than N2.,
3742 // even if one of the other rules in this paragraph would otherwise apply.
3743 if (!ICS1.isBad()) {
3744 if (ICS1.isStdInitializerListElement() &&
3745 !ICS2.isStdInitializerListElement())
3746 return ImplicitConversionSequence::Better;
3747 if (!ICS1.isStdInitializerListElement() &&
3748 ICS2.isStdInitializerListElement())
3749 return ImplicitConversionSequence::Worse;
3752 if (ICS1.isStandard())
3753 // Standard conversion sequence S1 is a better conversion sequence than
3754 // standard conversion sequence S2 if [...]
3755 Result = CompareStandardConversionSequences(S, Loc,
3756 ICS1.Standard, ICS2.Standard);
3757 else if (ICS1.isUserDefined()) {
3758 // User-defined conversion sequence U1 is a better conversion
3759 // sequence than another user-defined conversion sequence U2 if
3760 // they contain the same user-defined conversion function or
3761 // constructor and if the second standard conversion sequence of
3762 // U1 is better than the second standard conversion sequence of
3763 // U2 (C++ 13.3.3.2p3).
3764 if (ICS1.UserDefined.ConversionFunction ==
3765 ICS2.UserDefined.ConversionFunction)
3766 Result = CompareStandardConversionSequences(S, Loc,
3767 ICS1.UserDefined.After,
3768 ICS2.UserDefined.After);
3770 Result = compareConversionFunctions(S,
3771 ICS1.UserDefined.ConversionFunction,
3772 ICS2.UserDefined.ConversionFunction);
3778 // Per 13.3.3.2p3, compare the given standard conversion sequences to
3779 // determine if one is a proper subset of the other.
3780 static ImplicitConversionSequence::CompareKind
3781 compareStandardConversionSubsets(ASTContext &Context,
3782 const StandardConversionSequence& SCS1,
3783 const StandardConversionSequence& SCS2) {
3784 ImplicitConversionSequence::CompareKind Result
3785 = ImplicitConversionSequence::Indistinguishable;
3787 // the identity conversion sequence is considered to be a subsequence of
3788 // any non-identity conversion sequence
3789 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3790 return ImplicitConversionSequence::Better;
3791 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3792 return ImplicitConversionSequence::Worse;
3794 if (SCS1.Second != SCS2.Second) {
3795 if (SCS1.Second == ICK_Identity)
3796 Result = ImplicitConversionSequence::Better;
3797 else if (SCS2.Second == ICK_Identity)
3798 Result = ImplicitConversionSequence::Worse;
3800 return ImplicitConversionSequence::Indistinguishable;
3801 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3802 return ImplicitConversionSequence::Indistinguishable;
3804 if (SCS1.Third == SCS2.Third) {
3805 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3806 : ImplicitConversionSequence::Indistinguishable;
3809 if (SCS1.Third == ICK_Identity)
3810 return Result == ImplicitConversionSequence::Worse
3811 ? ImplicitConversionSequence::Indistinguishable
3812 : ImplicitConversionSequence::Better;
3814 if (SCS2.Third == ICK_Identity)
3815 return Result == ImplicitConversionSequence::Better
3816 ? ImplicitConversionSequence::Indistinguishable
3817 : ImplicitConversionSequence::Worse;
3819 return ImplicitConversionSequence::Indistinguishable;
3822 /// Determine whether one of the given reference bindings is better
3823 /// than the other based on what kind of bindings they are.
3825 isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3826 const StandardConversionSequence &SCS2) {
3827 // C++0x [over.ics.rank]p3b4:
3828 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3829 // implicit object parameter of a non-static member function declared
3830 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3831 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3832 // lvalue reference to a function lvalue and S2 binds an rvalue
3835 // FIXME: Rvalue references. We're going rogue with the above edits,
3836 // because the semantics in the current C++0x working paper (N3225 at the
3837 // time of this writing) break the standard definition of std::forward
3838 // and std::reference_wrapper when dealing with references to functions.
3839 // Proposed wording changes submitted to CWG for consideration.
3840 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3841 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3844 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3845 SCS2.IsLvalueReference) ||
3846 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3847 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3850 enum class FixedEnumPromotion {
3853 ToPromotedUnderlyingType
3856 /// Returns kind of fixed enum promotion the \a SCS uses.
3857 static FixedEnumPromotion
3858 getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS) {
3860 if (SCS.Second != ICK_Integral_Promotion)
3861 return FixedEnumPromotion::None;
3863 QualType FromType = SCS.getFromType();
3864 if (!FromType->isEnumeralType())
3865 return FixedEnumPromotion::None;
3867 EnumDecl *Enum = FromType->getAs<EnumType>()->getDecl();
3868 if (!Enum->isFixed())
3869 return FixedEnumPromotion::None;
3871 QualType UnderlyingType = Enum->getIntegerType();
3872 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
3873 return FixedEnumPromotion::ToUnderlyingType;
3875 return FixedEnumPromotion::ToPromotedUnderlyingType;
3878 /// CompareStandardConversionSequences - Compare two standard
3879 /// conversion sequences to determine whether one is better than the
3880 /// other or if they are indistinguishable (C++ 13.3.3.2p3).
3881 static ImplicitConversionSequence::CompareKind
3882 CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3883 const StandardConversionSequence& SCS1,
3884 const StandardConversionSequence& SCS2)
3886 // Standard conversion sequence S1 is a better conversion sequence
3887 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3889 // -- S1 is a proper subsequence of S2 (comparing the conversion
3890 // sequences in the canonical form defined by 13.3.3.1.1,
3891 // excluding any Lvalue Transformation; the identity conversion
3892 // sequence is considered to be a subsequence of any
3893 // non-identity conversion sequence) or, if not that,
3894 if (ImplicitConversionSequence::CompareKind CK
3895 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3898 // -- the rank of S1 is better than the rank of S2 (by the rules
3899 // defined below), or, if not that,
3900 ImplicitConversionRank Rank1 = SCS1.getRank();
3901 ImplicitConversionRank Rank2 = SCS2.getRank();
3903 return ImplicitConversionSequence::Better;
3904 else if (Rank2 < Rank1)
3905 return ImplicitConversionSequence::Worse;
3907 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3908 // are indistinguishable unless one of the following rules
3911 // A conversion that is not a conversion of a pointer, or
3912 // pointer to member, to bool is better than another conversion
3913 // that is such a conversion.
3914 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3915 return SCS2.isPointerConversionToBool()
3916 ? ImplicitConversionSequence::Better
3917 : ImplicitConversionSequence::Worse;
3919 // C++14 [over.ics.rank]p4b2:
3920 // This is retroactively applied to C++11 by CWG 1601.
3922 // A conversion that promotes an enumeration whose underlying type is fixed
3923 // to its underlying type is better than one that promotes to the promoted
3924 // underlying type, if the two are different.
3925 FixedEnumPromotion FEP1 = getFixedEnumPromtion(S, SCS1);
3926 FixedEnumPromotion FEP2 = getFixedEnumPromtion(S, SCS2);
3927 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
3929 return FEP1 == FixedEnumPromotion::ToUnderlyingType
3930 ? ImplicitConversionSequence::Better
3931 : ImplicitConversionSequence::Worse;
3933 // C++ [over.ics.rank]p4b2:
3935 // If class B is derived directly or indirectly from class A,
3936 // conversion of B* to A* is better than conversion of B* to
3937 // void*, and conversion of A* to void* is better than conversion
3939 bool SCS1ConvertsToVoid
3940 = SCS1.isPointerConversionToVoidPointer(S.Context);
3941 bool SCS2ConvertsToVoid
3942 = SCS2.isPointerConversionToVoidPointer(S.Context);
3943 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3944 // Exactly one of the conversion sequences is a conversion to
3945 // a void pointer; it's the worse conversion.
3946 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3947 : ImplicitConversionSequence::Worse;
3948 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3949 // Neither conversion sequence converts to a void pointer; compare
3950 // their derived-to-base conversions.
3951 if (ImplicitConversionSequence::CompareKind DerivedCK
3952 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3954 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3955 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3956 // Both conversion sequences are conversions to void
3957 // pointers. Compare the source types to determine if there's an
3958 // inheritance relationship in their sources.
3959 QualType FromType1 = SCS1.getFromType();
3960 QualType FromType2 = SCS2.getFromType();
3962 // Adjust the types we're converting from via the array-to-pointer
3963 // conversion, if we need to.
3964 if (SCS1.First == ICK_Array_To_Pointer)
3965 FromType1 = S.Context.getArrayDecayedType(FromType1);
3966 if (SCS2.First == ICK_Array_To_Pointer)
3967 FromType2 = S.Context.getArrayDecayedType(FromType2);
3969 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3970 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3972 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3973 return ImplicitConversionSequence::Better;
3974 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3975 return ImplicitConversionSequence::Worse;
3977 // Objective-C++: If one interface is more specific than the
3978 // other, it is the better one.
3979 const ObjCObjectPointerType* FromObjCPtr1
3980 = FromType1->getAs<ObjCObjectPointerType>();
3981 const ObjCObjectPointerType* FromObjCPtr2
3982 = FromType2->getAs<ObjCObjectPointerType>();
3983 if (FromObjCPtr1 && FromObjCPtr2) {
3984 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3986 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3988 if (AssignLeft != AssignRight) {
3989 return AssignLeft? ImplicitConversionSequence::Better
3990 : ImplicitConversionSequence::Worse;
3995 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3996 // Check for a better reference binding based on the kind of bindings.
3997 if (isBetterReferenceBindingKind(SCS1, SCS2))
3998 return ImplicitConversionSequence::Better;
3999 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4000 return ImplicitConversionSequence::Worse;
4003 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4005 if (ImplicitConversionSequence::CompareKind QualCK
4006 = CompareQualificationConversions(S, SCS1, SCS2))
4009 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4010 // C++ [over.ics.rank]p3b4:
4011 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4012 // which the references refer are the same type except for
4013 // top-level cv-qualifiers, and the type to which the reference
4014 // initialized by S2 refers is more cv-qualified than the type
4015 // to which the reference initialized by S1 refers.
4016 QualType T1 = SCS1.getToType(2);
4017 QualType T2 = SCS2.getToType(2);
4018 T1 = S.Context.getCanonicalType(T1);
4019 T2 = S.Context.getCanonicalType(T2);
4020 Qualifiers T1Quals, T2Quals;
4021 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4022 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4023 if (UnqualT1 == UnqualT2) {
4024 // Objective-C++ ARC: If the references refer to objects with different
4025 // lifetimes, prefer bindings that don't change lifetime.
4026 if (SCS1.ObjCLifetimeConversionBinding !=
4027 SCS2.ObjCLifetimeConversionBinding) {
4028 return SCS1.ObjCLifetimeConversionBinding
4029 ? ImplicitConversionSequence::Worse
4030 : ImplicitConversionSequence::Better;
4033 // If the type is an array type, promote the element qualifiers to the
4034 // type for comparison.
4035 if (isa<ArrayType>(T1) && T1Quals)
4036 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4037 if (isa<ArrayType>(T2) && T2Quals)
4038 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4039 if (T2.isMoreQualifiedThan(T1))
4040 return ImplicitConversionSequence::Better;
4041 if (T1.isMoreQualifiedThan(T2))
4042 return ImplicitConversionSequence::Worse;
4046 // In Microsoft mode, prefer an integral conversion to a
4047 // floating-to-integral conversion if the integral conversion
4048 // is between types of the same size.
4056 // Here, MSVC will call f(int) instead of generating a compile error
4057 // as clang will do in standard mode.
4058 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
4059 SCS2.Second == ICK_Floating_Integral &&
4060 S.Context.getTypeSize(SCS1.getFromType()) ==
4061 S.Context.getTypeSize(SCS1.getToType(2)))
4062 return ImplicitConversionSequence::Better;
4064 // Prefer a compatible vector conversion over a lax vector conversion
4067 // typedef float __v4sf __attribute__((__vector_size__(16)));
4068 // void f(vector float);
4069 // void f(vector signed int);
4074 // Here, we'd like to choose f(vector float) and not
4075 // report an ambiguous call error
4076 if (SCS1.Second == ICK_Vector_Conversion &&
4077 SCS2.Second == ICK_Vector_Conversion) {
4078 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4079 SCS1.getFromType(), SCS1.getToType(2));
4080 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4081 SCS2.getFromType(), SCS2.getToType(2));
4083 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4084 return SCS1IsCompatibleVectorConversion
4085 ? ImplicitConversionSequence::Better
4086 : ImplicitConversionSequence::Worse;
4089 return ImplicitConversionSequence::Indistinguishable;
4092 /// CompareQualificationConversions - Compares two standard conversion
4093 /// sequences to determine whether they can be ranked based on their
4094 /// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4095 static ImplicitConversionSequence::CompareKind
4096 CompareQualificationConversions(Sema &S,
4097 const StandardConversionSequence& SCS1,
4098 const StandardConversionSequence& SCS2) {
4100 // -- S1 and S2 differ only in their qualification conversion and
4101 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
4102 // cv-qualification signature of type T1 is a proper subset of
4103 // the cv-qualification signature of type T2, and S1 is not the
4104 // deprecated string literal array-to-pointer conversion (4.2).
4105 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4106 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4107 return ImplicitConversionSequence::Indistinguishable;
4109 // FIXME: the example in the standard doesn't use a qualification
4111 QualType T1 = SCS1.getToType(2);
4112 QualType T2 = SCS2.getToType(2);
4113 T1 = S.Context.getCanonicalType(T1);
4114 T2 = S.Context.getCanonicalType(T2);
4115 assert(!T1->isReferenceType() && !T2->isReferenceType());
4116 Qualifiers T1Quals, T2Quals;
4117 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4118 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4120 // If the types are the same, we won't learn anything by unwrapping
4122 if (UnqualT1 == UnqualT2)
4123 return ImplicitConversionSequence::Indistinguishable;
4125 ImplicitConversionSequence::CompareKind Result
4126 = ImplicitConversionSequence::Indistinguishable;
4128 // Objective-C++ ARC:
4129 // Prefer qualification conversions not involving a change in lifetime
4130 // to qualification conversions that do not change lifetime.
4131 if (SCS1.QualificationIncludesObjCLifetime !=
4132 SCS2.QualificationIncludesObjCLifetime) {
4133 Result = SCS1.QualificationIncludesObjCLifetime
4134 ? ImplicitConversionSequence::Worse
4135 : ImplicitConversionSequence::Better;
4138 while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4139 // Within each iteration of the loop, we check the qualifiers to
4140 // determine if this still looks like a qualification
4141 // conversion. Then, if all is well, we unwrap one more level of
4142 // pointers or pointers-to-members and do it all again
4143 // until there are no more pointers or pointers-to-members left
4144 // to unwrap. This essentially mimics what
4145 // IsQualificationConversion does, but here we're checking for a
4146 // strict subset of qualifiers.
4147 if (T1.getQualifiers().withoutObjCLifetime() ==
4148 T2.getQualifiers().withoutObjCLifetime())
4149 // The qualifiers are the same, so this doesn't tell us anything
4150 // about how the sequences rank.
4151 // ObjC ownership quals are omitted above as they interfere with
4152 // the ARC overload rule.
4154 else if (T2.isMoreQualifiedThan(T1)) {
4155 // T1 has fewer qualifiers, so it could be the better sequence.
4156 if (Result == ImplicitConversionSequence::Worse)
4157 // Neither has qualifiers that are a subset of the other's
4159 return ImplicitConversionSequence::Indistinguishable;
4161 Result = ImplicitConversionSequence::Better;
4162 } else if (T1.isMoreQualifiedThan(T2)) {
4163 // T2 has fewer qualifiers, so it could be the better sequence.
4164 if (Result == ImplicitConversionSequence::Better)
4165 // Neither has qualifiers that are a subset of the other's
4167 return ImplicitConversionSequence::Indistinguishable;
4169 Result = ImplicitConversionSequence::Worse;
4171 // Qualifiers are disjoint.
4172 return ImplicitConversionSequence::Indistinguishable;
4175 // If the types after this point are equivalent, we're done.
4176 if (S.Context.hasSameUnqualifiedType(T1, T2))
4180 // Check that the winning standard conversion sequence isn't using
4181 // the deprecated string literal array to pointer conversion.
4183 case ImplicitConversionSequence::Better:
4184 if (SCS1.DeprecatedStringLiteralToCharPtr)
4185 Result = ImplicitConversionSequence::Indistinguishable;
4188 case ImplicitConversionSequence::Indistinguishable:
4191 case ImplicitConversionSequence::Worse:
4192 if (SCS2.DeprecatedStringLiteralToCharPtr)
4193 Result = ImplicitConversionSequence::Indistinguishable;
4200 /// CompareDerivedToBaseConversions - Compares two standard conversion
4201 /// sequences to determine whether they can be ranked based on their
4202 /// various kinds of derived-to-base conversions (C++
4203 /// [over.ics.rank]p4b3). As part of these checks, we also look at
4204 /// conversions between Objective-C interface types.
4205 static ImplicitConversionSequence::CompareKind
4206 CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4207 const StandardConversionSequence& SCS1,
4208 const StandardConversionSequence& SCS2) {
4209 QualType FromType1 = SCS1.getFromType();
4210 QualType ToType1 = SCS1.getToType(1);
4211 QualType FromType2 = SCS2.getFromType();
4212 QualType ToType2 = SCS2.getToType(1);
4214 // Adjust the types we're converting from via the array-to-pointer
4215 // conversion, if we need to.
4216 if (SCS1.First == ICK_Array_To_Pointer)
4217 FromType1 = S.Context.getArrayDecayedType(FromType1);
4218 if (SCS2.First == ICK_Array_To_Pointer)
4219 FromType2 = S.Context.getArrayDecayedType(FromType2);
4221 // Canonicalize all of the types.
4222 FromType1 = S.Context.getCanonicalType(FromType1);
4223 ToType1 = S.Context.getCanonicalType(ToType1);
4224 FromType2 = S.Context.getCanonicalType(FromType2);
4225 ToType2 = S.Context.getCanonicalType(ToType2);
4227 // C++ [over.ics.rank]p4b3:
4229 // If class B is derived directly or indirectly from class A and
4230 // class C is derived directly or indirectly from B,
4232 // Compare based on pointer conversions.
4233 if (SCS1.Second == ICK_Pointer_Conversion &&
4234 SCS2.Second == ICK_Pointer_Conversion &&
4235 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4236 FromType1->isPointerType() && FromType2->isPointerType() &&
4237 ToType1->isPointerType() && ToType2->isPointerType()) {
4238 QualType FromPointee1 =
4239 FromType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4240 QualType ToPointee1 =
4241 ToType1->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4242 QualType FromPointee2 =
4243 FromType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4244 QualType ToPointee2 =
4245 ToType2->castAs<PointerType>()->getPointeeType().getUnqualifiedType();
4247 // -- conversion of C* to B* is better than conversion of C* to A*,
4248 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4249 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4250 return ImplicitConversionSequence::Better;
4251 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4252 return ImplicitConversionSequence::Worse;
4255 // -- conversion of B* to A* is better than conversion of C* to A*,
4256 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4257 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4258 return ImplicitConversionSequence::Better;
4259 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4260 return ImplicitConversionSequence::Worse;
4262 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4263 SCS2.Second == ICK_Pointer_Conversion) {
4264 const ObjCObjectPointerType *FromPtr1
4265 = FromType1->getAs<ObjCObjectPointerType>();
4266 const ObjCObjectPointerType *FromPtr2
4267 = FromType2->getAs<ObjCObjectPointerType>();
4268 const ObjCObjectPointerType *ToPtr1
4269 = ToType1->getAs<ObjCObjectPointerType>();
4270 const ObjCObjectPointerType *ToPtr2
4271 = ToType2->getAs<ObjCObjectPointerType>();
4273 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4274 // Apply the same conversion ranking rules for Objective-C pointer types
4275 // that we do for C++ pointers to class types. However, we employ the
4276 // Objective-C pseudo-subtyping relationship used for assignment of
4277 // Objective-C pointer types.
4279 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4280 bool FromAssignRight
4281 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4283 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4285 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4287 // A conversion to an a non-id object pointer type or qualified 'id'
4288 // type is better than a conversion to 'id'.
4289 if (ToPtr1->isObjCIdType() &&
4290 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4291 return ImplicitConversionSequence::Worse;
4292 if (ToPtr2->isObjCIdType() &&
4293 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4294 return ImplicitConversionSequence::Better;
4296 // A conversion to a non-id object pointer type is better than a
4297 // conversion to a qualified 'id' type
4298 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4299 return ImplicitConversionSequence::Worse;
4300 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4301 return ImplicitConversionSequence::Better;
4303 // A conversion to an a non-Class object pointer type or qualified 'Class'
4304 // type is better than a conversion to 'Class'.
4305 if (ToPtr1->isObjCClassType() &&
4306 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4307 return ImplicitConversionSequence::Worse;
4308 if (ToPtr2->isObjCClassType() &&
4309 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4310 return ImplicitConversionSequence::Better;
4312 // A conversion to a non-Class object pointer type is better than a
4313 // conversion to a qualified 'Class' type.
4314 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4315 return ImplicitConversionSequence::Worse;
4316 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4317 return ImplicitConversionSequence::Better;
4319 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4320 if (S.Context.hasSameType(FromType1, FromType2) &&
4321 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4322 (ToAssignLeft != ToAssignRight)) {
4323 if (FromPtr1->isSpecialized()) {
4324 // "conversion of B<A> * to B * is better than conversion of B * to
4327 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4329 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4332 return ImplicitConversionSequence::Better;
4333 } else if (IsSecondSame)
4334 return ImplicitConversionSequence::Worse;
4336 return ToAssignLeft? ImplicitConversionSequence::Worse
4337 : ImplicitConversionSequence::Better;
4340 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4341 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4342 (FromAssignLeft != FromAssignRight))
4343 return FromAssignLeft? ImplicitConversionSequence::Better
4344 : ImplicitConversionSequence::Worse;
4348 // Ranking of member-pointer types.
4349 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4350 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4351 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4352 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4353 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4354 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4355 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4356 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4357 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4358 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4359 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4360 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4361 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4362 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4363 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4364 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4365 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4366 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4367 return ImplicitConversionSequence::Worse;
4368 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4369 return ImplicitConversionSequence::Better;
4371 // conversion of B::* to C::* is better than conversion of A::* to C::*
4372 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4373 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4374 return ImplicitConversionSequence::Better;
4375 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4376 return ImplicitConversionSequence::Worse;
4380 if (SCS1.Second == ICK_Derived_To_Base) {
4381 // -- conversion of C to B is better than conversion of C to A,
4382 // -- binding of an expression of type C to a reference of type
4383 // B& is better than binding an expression of type C to a
4384 // reference of type A&,
4385 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4386 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4387 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4388 return ImplicitConversionSequence::Better;
4389 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4390 return ImplicitConversionSequence::Worse;
4393 // -- conversion of B to A is better than conversion of C to A.
4394 // -- binding of an expression of type B to a reference of type
4395 // A& is better than binding an expression of type C to a
4396 // reference of type A&,
4397 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4398 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4399 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4400 return ImplicitConversionSequence::Better;
4401 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4402 return ImplicitConversionSequence::Worse;
4406 return ImplicitConversionSequence::Indistinguishable;
4409 /// Determine whether the given type is valid, e.g., it is not an invalid
4411 static bool isTypeValid(QualType T) {
4412 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4413 return !Record->isInvalidDecl();
4418 static QualType withoutUnaligned(ASTContext &Ctx, QualType T) {
4419 if (!T.getQualifiers().hasUnaligned())
4423 T = Ctx.getUnqualifiedArrayType(T, Q);
4424 Q.removeUnaligned();
4425 return Ctx.getQualifiedType(T, Q);
4428 /// CompareReferenceRelationship - Compare the two types T1 and T2 to
4429 /// determine whether they are reference-compatible,
4430 /// reference-related, or incompatible, for use in C++ initialization by
4431 /// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4432 /// type, and the first type (T1) is the pointee type of the reference
4433 /// type being initialized.
4434 Sema::ReferenceCompareResult
4435 Sema::CompareReferenceRelationship(SourceLocation Loc,
4436 QualType OrigT1, QualType OrigT2,
4437 ReferenceConversions *ConvOut) {
4438 assert(!OrigT1->isReferenceType() &&
4439 "T1 must be the pointee type of the reference type");
4440 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4442 QualType T1 = Context.getCanonicalType(OrigT1);
4443 QualType T2 = Context.getCanonicalType(OrigT2);
4444 Qualifiers T1Quals, T2Quals;
4445 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4446 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4448 ReferenceConversions ConvTmp;
4449 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
4450 Conv = ReferenceConversions();
4452 // C++2a [dcl.init.ref]p4:
4453 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4454 // reference-related to "cv2 T2" if T1 is similar to T2, or
4455 // T1 is a base class of T2.
4456 // "cv1 T1" is reference-compatible with "cv2 T2" if
4457 // a prvalue of type "pointer to cv2 T2" can be converted to the type
4458 // "pointer to cv1 T1" via a standard conversion sequence.
4460 // Check for standard conversions we can apply to pointers: derived-to-base
4461 // conversions, ObjC pointer conversions, and function pointer conversions.
4462 // (Qualification conversions are checked last.)
4463 QualType ConvertedT2;
4464 if (UnqualT1 == UnqualT2) {
4466 } else if (isCompleteType(Loc, OrigT2) &&
4467 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4468 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4469 Conv |= ReferenceConversions::DerivedToBase;
4470 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4471 UnqualT2->isObjCObjectOrInterfaceType() &&
4472 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4473 Conv |= ReferenceConversions::ObjC;
4474 else if (UnqualT2->isFunctionType() &&
4475 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2)) {
4476 Conv |= ReferenceConversions::Function;
4477 // No need to check qualifiers; function types don't have them.
4478 return Ref_Compatible;
4480 bool ConvertedReferent = Conv != 0;
4482 // We can have a qualification conversion. Compute whether the types are
4483 // similar at the same time.
4484 bool PreviousToQualsIncludeConst = true;
4485 bool TopLevel = true;
4490 // We will need a qualification conversion.
4491 Conv |= ReferenceConversions::Qualification;
4493 // Track whether we performed a qualification conversion anywhere other
4494 // than the top level. This matters for ranking reference bindings in
4495 // overload resolution.
4497 Conv |= ReferenceConversions::NestedQualification;
4499 // MS compiler ignores __unaligned qualifier for references; do the same.
4500 T1 = withoutUnaligned(Context, T1);
4501 T2 = withoutUnaligned(Context, T2);
4503 // If we find a qualifier mismatch, the types are not reference-compatible,
4504 // but are still be reference-related if they're similar.
4505 bool ObjCLifetimeConversion = false;
4506 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
4507 PreviousToQualsIncludeConst,
4508 ObjCLifetimeConversion))
4509 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
4513 // FIXME: Should we track this for any level other than the first?
4514 if (ObjCLifetimeConversion)
4515 Conv |= ReferenceConversions::ObjCLifetime;
4518 } while (Context.UnwrapSimilarTypes(T1, T2));
4520 // At this point, if the types are reference-related, we must either have the
4521 // same inner type (ignoring qualifiers), or must have already worked out how
4522 // to convert the referent.
4523 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
4528 /// Look for a user-defined conversion to a value reference-compatible
4529 /// with DeclType. Return true if something definite is found.
4531 FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4532 QualType DeclType, SourceLocation DeclLoc,
4533 Expr *Init, QualType T2, bool AllowRvalues,
4534 bool AllowExplicit) {
4535 assert(T2->isRecordType() && "Can only find conversions of record types.");
4536 auto *T2RecordDecl = cast<CXXRecordDecl>(T2->castAs<RecordType>()->getDecl());
4538 OverloadCandidateSet CandidateSet(
4539 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4540 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4541 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4543 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4544 if (isa<UsingShadowDecl>(D))
4545 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4547 FunctionTemplateDecl *ConvTemplate
4548 = dyn_cast<FunctionTemplateDecl>(D);
4549 CXXConversionDecl *Conv;
4551 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4553 Conv = cast<CXXConversionDecl>(D);
4556 // If we are initializing an rvalue reference, don't permit conversion
4557 // functions that return lvalues.
4558 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4559 const ReferenceType *RefType
4560 = Conv->getConversionType()->getAs<LValueReferenceType>();
4561 if (RefType && !RefType->getPointeeType()->isFunctionType())
4565 if (!ConvTemplate &&
4566 S.CompareReferenceRelationship(
4568 Conv->getConversionType()
4569 .getNonReferenceType()
4570 .getUnqualifiedType(),
4571 DeclType.getNonReferenceType().getUnqualifiedType()) ==
4572 Sema::Ref_Incompatible)
4575 // If the conversion function doesn't return a reference type,
4576 // it can't be considered for this conversion. An rvalue reference
4577 // is only acceptable if its referencee is a function type.
4579 const ReferenceType *RefType =
4580 Conv->getConversionType()->getAs<ReferenceType>();
4582 (!RefType->isLValueReferenceType() &&
4583 !RefType->getPointeeType()->isFunctionType()))
4588 S.AddTemplateConversionCandidate(
4589 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4590 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4592 S.AddConversionCandidate(
4593 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4594 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4597 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4599 OverloadCandidateSet::iterator Best;
4600 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4602 // C++ [over.ics.ref]p1:
4604 // [...] If the parameter binds directly to the result of
4605 // applying a conversion function to the argument
4606 // expression, the implicit conversion sequence is a
4607 // user-defined conversion sequence (13.3.3.1.2), with the
4608 // second standard conversion sequence either an identity
4609 // conversion or, if the conversion function returns an
4610 // entity of a type that is a derived class of the parameter
4611 // type, a derived-to-base Conversion.
4612 if (!Best->FinalConversion.DirectBinding)
4615 ICS.setUserDefined();
4616 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4617 ICS.UserDefined.After = Best->FinalConversion;
4618 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4619 ICS.UserDefined.ConversionFunction = Best->Function;
4620 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4621 ICS.UserDefined.EllipsisConversion = false;
4622 assert(ICS.UserDefined.After.ReferenceBinding &&
4623 ICS.UserDefined.After.DirectBinding &&
4624 "Expected a direct reference binding!");
4629 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4630 Cand != CandidateSet.end(); ++Cand)
4632 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4635 case OR_No_Viable_Function:
4637 // There was no suitable conversion, or we found a deleted
4638 // conversion; continue with other checks.
4642 llvm_unreachable("Invalid OverloadResult!");
4645 /// Compute an implicit conversion sequence for reference
4647 static ImplicitConversionSequence
4648 TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4649 SourceLocation DeclLoc,
4650 bool SuppressUserConversions,
4651 bool AllowExplicit) {
4652 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4654 // Most paths end in a failed conversion.
4655 ImplicitConversionSequence ICS;
4656 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4658 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
4659 QualType T2 = Init->getType();
4661 // If the initializer is the address of an overloaded function, try
4662 // to resolve the overloaded function. If all goes well, T2 is the
4663 // type of the resulting function.
4664 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4665 DeclAccessPair Found;
4666 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4671 // Compute some basic properties of the types and the initializer.
4672 bool isRValRef = DeclType->isRValueReferenceType();
4673 Expr::Classification InitCategory = Init->Classify(S.Context);
4675 Sema::ReferenceConversions RefConv;
4676 Sema::ReferenceCompareResult RefRelationship =
4677 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
4679 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
4681 ICS.Standard.First = ICK_Identity;
4682 // FIXME: A reference binding can be a function conversion too. We should
4683 // consider that when ordering reference-to-function bindings.
4684 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
4685 ? ICK_Derived_To_Base
4686 : (RefConv & Sema::ReferenceConversions::ObjC)
4687 ? ICK_Compatible_Conversion
4689 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
4690 // a reference binding that performs a non-top-level qualification
4691 // conversion as a qualification conversion, not as an identity conversion.
4692 ICS.Standard.Third = (RefConv &
4693 Sema::ReferenceConversions::NestedQualification)
4696 ICS.Standard.setFromType(T2);
4697 ICS.Standard.setToType(0, T2);
4698 ICS.Standard.setToType(1, T1);
4699 ICS.Standard.setToType(2, T1);
4700 ICS.Standard.ReferenceBinding = true;
4701 ICS.Standard.DirectBinding = BindsDirectly;
4702 ICS.Standard.IsLvalueReference = !isRValRef;
4703 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4704 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4705 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4706 ICS.Standard.ObjCLifetimeConversionBinding =
4707 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
4708 ICS.Standard.CopyConstructor = nullptr;
4709 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4712 // C++0x [dcl.init.ref]p5:
4713 // A reference to type "cv1 T1" is initialized by an expression
4714 // of type "cv2 T2" as follows:
4716 // -- If reference is an lvalue reference and the initializer expression
4718 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4719 // reference-compatible with "cv2 T2," or
4721 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4722 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4723 // C++ [over.ics.ref]p1:
4724 // When a parameter of reference type binds directly (8.5.3)
4725 // to an argument expression, the implicit conversion sequence
4726 // is the identity conversion, unless the argument expression
4727 // has a type that is a derived class of the parameter type,
4728 // in which case the implicit conversion sequence is a
4729 // derived-to-base Conversion (13.3.3.1).
4730 SetAsReferenceBinding(/*BindsDirectly=*/true);
4732 // Nothing more to do: the inaccessibility/ambiguity check for
4733 // derived-to-base conversions is suppressed when we're
4734 // computing the implicit conversion sequence (C++
4735 // [over.best.ics]p2).
4739 // -- has a class type (i.e., T2 is a class type), where T1 is
4740 // not reference-related to T2, and can be implicitly
4741 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4742 // is reference-compatible with "cv3 T3" 92) (this
4743 // conversion is selected by enumerating the applicable
4744 // conversion functions (13.3.1.6) and choosing the best
4745 // one through overload resolution (13.3)),
4746 if (!SuppressUserConversions && T2->isRecordType() &&
4747 S.isCompleteType(DeclLoc, T2) &&
4748 RefRelationship == Sema::Ref_Incompatible) {
4749 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4750 Init, T2, /*AllowRvalues=*/false,
4756 // -- Otherwise, the reference shall be an lvalue reference to a
4757 // non-volatile const type (i.e., cv1 shall be const), or the reference
4758 // shall be an rvalue reference.
4759 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4762 // -- If the initializer expression
4764 // -- is an xvalue, class prvalue, array prvalue or function
4765 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4766 if (RefRelationship == Sema::Ref_Compatible &&
4767 (InitCategory.isXValue() ||
4768 (InitCategory.isPRValue() &&
4769 (T2->isRecordType() || T2->isArrayType())) ||
4770 (InitCategory.isLValue() && T2->isFunctionType()))) {
4771 // In C++11, this is always a direct binding. In C++98/03, it's a direct
4772 // binding unless we're binding to a class prvalue.
4773 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4774 // allow the use of rvalue references in C++98/03 for the benefit of
4775 // standard library implementors; therefore, we need the xvalue check here.
4776 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
4777 !(InitCategory.isPRValue() || T2->isRecordType()));
4781 // -- has a class type (i.e., T2 is a class type), where T1 is not
4782 // reference-related to T2, and can be implicitly converted to
4783 // an xvalue, class prvalue, or function lvalue of type
4784 // "cv3 T3", where "cv1 T1" is reference-compatible with
4787 // then the reference is bound to the value of the initializer
4788 // expression in the first case and to the result of the conversion
4789 // in the second case (or, in either case, to an appropriate base
4790 // class subobject).
4791 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4792 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4793 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4794 Init, T2, /*AllowRvalues=*/true,
4796 // In the second case, if the reference is an rvalue reference
4797 // and the second standard conversion sequence of the
4798 // user-defined conversion sequence includes an lvalue-to-rvalue
4799 // conversion, the program is ill-formed.
4800 if (ICS.isUserDefined() && isRValRef &&
4801 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4802 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4807 // A temporary of function type cannot be created; don't even try.
4808 if (T1->isFunctionType())
4811 // -- Otherwise, a temporary of type "cv1 T1" is created and
4812 // initialized from the initializer expression using the
4813 // rules for a non-reference copy initialization (8.5). The
4814 // reference is then bound to the temporary. If T1 is
4815 // reference-related to T2, cv1 must be the same
4816 // cv-qualification as, or greater cv-qualification than,
4817 // cv2; otherwise, the program is ill-formed.
4818 if (RefRelationship == Sema::Ref_Related) {
4819 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4820 // we would be reference-compatible or reference-compatible with
4821 // added qualification. But that wasn't the case, so the reference
4822 // initialization fails.
4824 // Note that we only want to check address spaces and cvr-qualifiers here.
4825 // ObjC GC, lifetime and unaligned qualifiers aren't important.
4826 Qualifiers T1Quals = T1.getQualifiers();
4827 Qualifiers T2Quals = T2.getQualifiers();
4828 T1Quals.removeObjCGCAttr();
4829 T1Quals.removeObjCLifetime();
4830 T2Quals.removeObjCGCAttr();
4831 T2Quals.removeObjCLifetime();
4832 // MS compiler ignores __unaligned qualifier for references; do the same.
4833 T1Quals.removeUnaligned();
4834 T2Quals.removeUnaligned();
4835 if (!T1Quals.compatiblyIncludes(T2Quals))
4839 // If at least one of the types is a class type, the types are not
4840 // related, and we aren't allowed any user conversions, the
4841 // reference binding fails. This case is important for breaking
4842 // recursion, since TryImplicitConversion below will attempt to
4843 // create a temporary through the use of a copy constructor.
4844 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4845 (T1->isRecordType() || T2->isRecordType()))
4848 // If T1 is reference-related to T2 and the reference is an rvalue
4849 // reference, the initializer expression shall not be an lvalue.
4850 if (RefRelationship >= Sema::Ref_Related &&
4851 isRValRef && Init->Classify(S.Context).isLValue())
4854 // C++ [over.ics.ref]p2:
4855 // When a parameter of reference type is not bound directly to
4856 // an argument expression, the conversion sequence is the one
4857 // required to convert the argument expression to the
4858 // underlying type of the reference according to
4859 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4860 // to copy-initializing a temporary of the underlying type with
4861 // the argument expression. Any difference in top-level
4862 // cv-qualification is subsumed by the initialization itself
4863 // and does not constitute a conversion.
4864 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4865 /*AllowExplicit=*/false,
4866 /*InOverloadResolution=*/false,
4868 /*AllowObjCWritebackConversion=*/false,
4869 /*AllowObjCConversionOnExplicit=*/false);
4871 // Of course, that's still a reference binding.
4872 if (ICS.isStandard()) {
4873 ICS.Standard.ReferenceBinding = true;
4874 ICS.Standard.IsLvalueReference = !isRValRef;
4875 ICS.Standard.BindsToFunctionLvalue = false;
4876 ICS.Standard.BindsToRvalue = true;
4877 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4878 ICS.Standard.ObjCLifetimeConversionBinding = false;
4879 } else if (ICS.isUserDefined()) {
4880 const ReferenceType *LValRefType =
4881 ICS.UserDefined.ConversionFunction->getReturnType()
4882 ->getAs<LValueReferenceType>();
4884 // C++ [over.ics.ref]p3:
4885 // Except for an implicit object parameter, for which see 13.3.1, a
4886 // standard conversion sequence cannot be formed if it requires [...]
4887 // binding an rvalue reference to an lvalue other than a function
4889 // Note that the function case is not possible here.
4890 if (DeclType->isRValueReferenceType() && LValRefType) {
4891 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4892 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4893 // reference to an rvalue!
4894 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4898 ICS.UserDefined.After.ReferenceBinding = true;
4899 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4900 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4901 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4902 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4903 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4909 static ImplicitConversionSequence
4910 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4911 bool SuppressUserConversions,
4912 bool InOverloadResolution,
4913 bool AllowObjCWritebackConversion,
4914 bool AllowExplicit = false);
4916 /// TryListConversion - Try to copy-initialize a value of type ToType from the
4917 /// initializer list From.
4918 static ImplicitConversionSequence
4919 TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4920 bool SuppressUserConversions,
4921 bool InOverloadResolution,
4922 bool AllowObjCWritebackConversion) {
4923 // C++11 [over.ics.list]p1:
4924 // When an argument is an initializer list, it is not an expression and
4925 // special rules apply for converting it to a parameter type.
4927 ImplicitConversionSequence Result;
4928 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4930 // We need a complete type for what follows. Incomplete types can never be
4931 // initialized from init lists.
4932 if (!S.isCompleteType(From->getBeginLoc(), ToType))
4936 // If the parameter type is a class X and the initializer list has a single
4937 // element of type cv U, where U is X or a class derived from X, the
4938 // implicit conversion sequence is the one required to convert the element
4939 // to the parameter type.
4941 // Otherwise, if the parameter type is a character array [... ]
4942 // and the initializer list has a single element that is an
4943 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4944 // implicit conversion sequence is the identity conversion.
4945 if (From->getNumInits() == 1) {
4946 if (ToType->isRecordType()) {
4947 QualType InitType = From->getInit(0)->getType();
4948 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4949 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4950 return TryCopyInitialization(S, From->getInit(0), ToType,
4951 SuppressUserConversions,
4952 InOverloadResolution,
4953 AllowObjCWritebackConversion);
4955 // FIXME: Check the other conditions here: array of character type,
4956 // initializer is a string literal.
4957 if (ToType->isArrayType()) {
4958 InitializedEntity Entity =
4959 InitializedEntity::InitializeParameter(S.Context, ToType,
4960 /*Consumed=*/false);
4961 if (S.CanPerformCopyInitialization(Entity, From)) {
4962 Result.setStandard();
4963 Result.Standard.setAsIdentityConversion();
4964 Result.Standard.setFromType(ToType);
4965 Result.Standard.setAllToTypes(ToType);
4971 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4972 // C++11 [over.ics.list]p2:
4973 // If the parameter type is std::initializer_list<X> or "array of X" and
4974 // all the elements can be implicitly converted to X, the implicit
4975 // conversion sequence is the worst conversion necessary to convert an
4976 // element of the list to X.
4978 // C++14 [over.ics.list]p3:
4979 // Otherwise, if the parameter type is "array of N X", if the initializer
4980 // list has exactly N elements or if it has fewer than N elements and X is
4981 // default-constructible, and if all the elements of the initializer list
4982 // can be implicitly converted to X, the implicit conversion sequence is
4983 // the worst conversion necessary to convert an element of the list to X.
4985 // FIXME: We're missing a lot of these checks.
4986 bool toStdInitializerList = false;
4988 if (ToType->isArrayType())
4989 X = S.Context.getAsArrayType(ToType)->getElementType();
4991 toStdInitializerList = S.isStdInitializerList(ToType, &X);
4993 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4994 Expr *Init = From->getInit(i);
4995 ImplicitConversionSequence ICS =
4996 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4997 InOverloadResolution,
4998 AllowObjCWritebackConversion);
4999 // If a single element isn't convertible, fail.
5004 // Otherwise, look for the worst conversion.
5005 if (Result.isBad() || CompareImplicitConversionSequences(
5006 S, From->getBeginLoc(), ICS, Result) ==
5007 ImplicitConversionSequence::Worse)
5011 // For an empty list, we won't have computed any conversion sequence.
5012 // Introduce the identity conversion sequence.
5013 if (From->getNumInits() == 0) {
5014 Result.setStandard();
5015 Result.Standard.setAsIdentityConversion();
5016 Result.Standard.setFromType(ToType);
5017 Result.Standard.setAllToTypes(ToType);
5020 Result.setStdInitializerListElement(toStdInitializerList);
5024 // C++14 [over.ics.list]p4:
5025 // C++11 [over.ics.list]p3:
5026 // Otherwise, if the parameter is a non-aggregate class X and overload
5027 // resolution chooses a single best constructor [...] the implicit
5028 // conversion sequence is a user-defined conversion sequence. If multiple
5029 // constructors are viable but none is better than the others, the
5030 // implicit conversion sequence is a user-defined conversion sequence.
5031 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5032 // This function can deal with initializer lists.
5033 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5034 /*AllowExplicit=*/false,
5035 InOverloadResolution, /*CStyle=*/false,
5036 AllowObjCWritebackConversion,
5037 /*AllowObjCConversionOnExplicit=*/false);
5040 // C++14 [over.ics.list]p5:
5041 // C++11 [over.ics.list]p4:
5042 // Otherwise, if the parameter has an aggregate type which can be
5043 // initialized from the initializer list [...] the implicit conversion
5044 // sequence is a user-defined conversion sequence.
5045 if (ToType->isAggregateType()) {
5046 // Type is an aggregate, argument is an init list. At this point it comes
5047 // down to checking whether the initialization works.
5048 // FIXME: Find out whether this parameter is consumed or not.
5049 InitializedEntity Entity =
5050 InitializedEntity::InitializeParameter(S.Context, ToType,
5051 /*Consumed=*/false);
5052 if (S.CanPerformAggregateInitializationForOverloadResolution(Entity,
5054 Result.setUserDefined();
5055 Result.UserDefined.Before.setAsIdentityConversion();
5056 // Initializer lists don't have a type.
5057 Result.UserDefined.Before.setFromType(QualType());
5058 Result.UserDefined.Before.setAllToTypes(QualType());
5060 Result.UserDefined.After.setAsIdentityConversion();
5061 Result.UserDefined.After.setFromType(ToType);
5062 Result.UserDefined.After.setAllToTypes(ToType);
5063 Result.UserDefined.ConversionFunction = nullptr;
5068 // C++14 [over.ics.list]p6:
5069 // C++11 [over.ics.list]p5:
5070 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5071 if (ToType->isReferenceType()) {
5072 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5073 // mention initializer lists in any way. So we go by what list-
5074 // initialization would do and try to extrapolate from that.
5076 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5078 // If the initializer list has a single element that is reference-related
5079 // to the parameter type, we initialize the reference from that.
5080 if (From->getNumInits() == 1) {
5081 Expr *Init = From->getInit(0);
5083 QualType T2 = Init->getType();
5085 // If the initializer is the address of an overloaded function, try
5086 // to resolve the overloaded function. If all goes well, T2 is the
5087 // type of the resulting function.
5088 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5089 DeclAccessPair Found;
5090 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
5091 Init, ToType, false, Found))
5095 // Compute some basic properties of the types and the initializer.
5096 Sema::ReferenceCompareResult RefRelationship =
5097 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5099 if (RefRelationship >= Sema::Ref_Related) {
5100 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5101 SuppressUserConversions,
5102 /*AllowExplicit=*/false);
5106 // Otherwise, we bind the reference to a temporary created from the
5107 // initializer list.
5108 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5109 InOverloadResolution,
5110 AllowObjCWritebackConversion);
5111 if (Result.isFailure())
5113 assert(!Result.isEllipsis() &&
5114 "Sub-initialization cannot result in ellipsis conversion.");
5116 // Can we even bind to a temporary?
5117 if (ToType->isRValueReferenceType() ||
5118 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5119 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5120 Result.UserDefined.After;
5121 SCS.ReferenceBinding = true;
5122 SCS.IsLvalueReference = ToType->isLValueReferenceType();
5123 SCS.BindsToRvalue = true;
5124 SCS.BindsToFunctionLvalue = false;
5125 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5126 SCS.ObjCLifetimeConversionBinding = false;
5128 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5133 // C++14 [over.ics.list]p7:
5134 // C++11 [over.ics.list]p6:
5135 // Otherwise, if the parameter type is not a class:
5136 if (!ToType->isRecordType()) {
5137 // - if the initializer list has one element that is not itself an
5138 // initializer list, the implicit conversion sequence is the one
5139 // required to convert the element to the parameter type.
5140 unsigned NumInits = From->getNumInits();
5141 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5142 Result = TryCopyInitialization(S, From->getInit(0), ToType,
5143 SuppressUserConversions,
5144 InOverloadResolution,
5145 AllowObjCWritebackConversion);
5146 // - if the initializer list has no elements, the implicit conversion
5147 // sequence is the identity conversion.
5148 else if (NumInits == 0) {
5149 Result.setStandard();
5150 Result.Standard.setAsIdentityConversion();
5151 Result.Standard.setFromType(ToType);
5152 Result.Standard.setAllToTypes(ToType);
5157 // C++14 [over.ics.list]p8:
5158 // C++11 [over.ics.list]p7:
5159 // In all cases other than those enumerated above, no conversion is possible
5163 /// TryCopyInitialization - Try to copy-initialize a value of type
5164 /// ToType from the expression From. Return the implicit conversion
5165 /// sequence required to pass this argument, which may be a bad
5166 /// conversion sequence (meaning that the argument cannot be passed to
5167 /// a parameter of this type). If @p SuppressUserConversions, then we
5168 /// do not permit any user-defined conversion sequences.
5169 static ImplicitConversionSequence
5170 TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5171 bool SuppressUserConversions,
5172 bool InOverloadResolution,
5173 bool AllowObjCWritebackConversion,
5174 bool AllowExplicit) {
5175 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5176 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5177 InOverloadResolution,AllowObjCWritebackConversion);
5179 if (ToType->isReferenceType())
5180 return TryReferenceInit(S, From, ToType,
5181 /*FIXME:*/ From->getBeginLoc(),
5182 SuppressUserConversions, AllowExplicit);
5184 return TryImplicitConversion(S, From, ToType,
5185 SuppressUserConversions,
5186 /*AllowExplicit=*/false,
5187 InOverloadResolution,
5189 AllowObjCWritebackConversion,
5190 /*AllowObjCConversionOnExplicit=*/false);
5193 static bool TryCopyInitialization(const CanQualType FromQTy,
5194 const CanQualType ToQTy,
5197 ExprValueKind FromVK) {
5198 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5199 ImplicitConversionSequence ICS =
5200 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5202 return !ICS.isBad();
5205 /// TryObjectArgumentInitialization - Try to initialize the object
5206 /// parameter of the given member function (@c Method) from the
5207 /// expression @p From.
5208 static ImplicitConversionSequence
5209 TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5210 Expr::Classification FromClassification,
5211 CXXMethodDecl *Method,
5212 CXXRecordDecl *ActingContext) {
5213 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5214 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5215 // const volatile object.
5216 Qualifiers Quals = Method->getMethodQualifiers();
5217 if (isa<CXXDestructorDecl>(Method)) {
5219 Quals.addVolatile();
5222 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5224 // Set up the conversion sequence as a "bad" conversion, to allow us
5226 ImplicitConversionSequence ICS;
5228 // We need to have an object of class type.
5229 if (const PointerType *PT = FromType->getAs<PointerType>()) {
5230 FromType = PT->getPointeeType();
5232 // When we had a pointer, it's implicitly dereferenced, so we
5233 // better have an lvalue.
5234 assert(FromClassification.isLValue());
5237 assert(FromType->isRecordType());
5239 // C++0x [over.match.funcs]p4:
5240 // For non-static member functions, the type of the implicit object
5243 // - "lvalue reference to cv X" for functions declared without a
5244 // ref-qualifier or with the & ref-qualifier
5245 // - "rvalue reference to cv X" for functions declared with the &&
5248 // where X is the class of which the function is a member and cv is the
5249 // cv-qualification on the member function declaration.
5251 // However, when finding an implicit conversion sequence for the argument, we
5252 // are not allowed to perform user-defined conversions
5253 // (C++ [over.match.funcs]p5). We perform a simplified version of
5254 // reference binding here, that allows class rvalues to bind to
5255 // non-constant references.
5257 // First check the qualifiers.
5258 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5259 if (ImplicitParamType.getCVRQualifiers()
5260 != FromTypeCanon.getLocalCVRQualifiers() &&
5261 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5262 ICS.setBad(BadConversionSequence::bad_qualifiers,
5263 FromType, ImplicitParamType);
5267 if (FromTypeCanon.hasAddressSpace()) {
5268 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5269 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5270 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5271 ICS.setBad(BadConversionSequence::bad_qualifiers,
5272 FromType, ImplicitParamType);
5277 // Check that we have either the same type or a derived type. It
5278 // affects the conversion rank.
5279 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5280 ImplicitConversionKind SecondKind;
5281 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5282 SecondKind = ICK_Identity;
5283 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5284 SecondKind = ICK_Derived_To_Base;
5286 ICS.setBad(BadConversionSequence::unrelated_class,
5287 FromType, ImplicitParamType);
5291 // Check the ref-qualifier.
5292 switch (Method->getRefQualifier()) {
5294 // Do nothing; we don't care about lvalueness or rvalueness.
5298 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5299 // non-const lvalue reference cannot bind to an rvalue
5300 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5307 if (!FromClassification.isRValue()) {
5308 // rvalue reference cannot bind to an lvalue
5309 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5316 // Success. Mark this as a reference binding.
5318 ICS.Standard.setAsIdentityConversion();
5319 ICS.Standard.Second = SecondKind;
5320 ICS.Standard.setFromType(FromType);
5321 ICS.Standard.setAllToTypes(ImplicitParamType);
5322 ICS.Standard.ReferenceBinding = true;
5323 ICS.Standard.DirectBinding = true;
5324 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5325 ICS.Standard.BindsToFunctionLvalue = false;
5326 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5327 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5328 = (Method->getRefQualifier() == RQ_None);
5332 /// PerformObjectArgumentInitialization - Perform initialization of
5333 /// the implicit object parameter for the given Method with the given
5336 Sema::PerformObjectArgumentInitialization(Expr *From,
5337 NestedNameSpecifier *Qualifier,
5338 NamedDecl *FoundDecl,
5339 CXXMethodDecl *Method) {
5340 QualType FromRecordType, DestType;
5341 QualType ImplicitParamRecordType =
5342 Method->getThisType()->castAs<PointerType>()->getPointeeType();
5344 Expr::Classification FromClassification;
5345 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5346 FromRecordType = PT->getPointeeType();
5347 DestType = Method->getThisType();
5348 FromClassification = Expr::Classification::makeSimpleLValue();
5350 FromRecordType = From->getType();
5351 DestType = ImplicitParamRecordType;
5352 FromClassification = From->Classify(Context);
5354 // When performing member access on an rvalue, materialize a temporary.
5355 if (From->isRValue()) {
5356 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5357 Method->getRefQualifier() !=
5358 RefQualifierKind::RQ_RValue);
5362 // Note that we always use the true parent context when performing
5363 // the actual argument initialization.
5364 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5365 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5366 Method->getParent());
5368 switch (ICS.Bad.Kind) {
5369 case BadConversionSequence::bad_qualifiers: {
5370 Qualifiers FromQs = FromRecordType.getQualifiers();
5371 Qualifiers ToQs = DestType.getQualifiers();
5372 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5374 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5375 << Method->getDeclName() << FromRecordType << (CVR - 1)
5376 << From->getSourceRange();
5377 Diag(Method->getLocation(), diag::note_previous_decl)
5378 << Method->getDeclName();
5384 case BadConversionSequence::lvalue_ref_to_rvalue:
5385 case BadConversionSequence::rvalue_ref_to_lvalue: {
5386 bool IsRValueQualified =
5387 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5388 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5389 << Method->getDeclName() << FromClassification.isRValue()
5390 << IsRValueQualified;
5391 Diag(Method->getLocation(), diag::note_previous_decl)
5392 << Method->getDeclName();
5396 case BadConversionSequence::no_conversion:
5397 case BadConversionSequence::unrelated_class:
5401 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5402 << ImplicitParamRecordType << FromRecordType
5403 << From->getSourceRange();
5406 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5407 ExprResult FromRes =
5408 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5409 if (FromRes.isInvalid())
5411 From = FromRes.get();
5414 if (!Context.hasSameType(From->getType(), DestType)) {
5416 QualType PteeTy = DestType->getPointeeType();
5418 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
5419 if (FromRecordType.getAddressSpace() != DestAS)
5420 CK = CK_AddressSpaceConversion;
5423 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5428 /// TryContextuallyConvertToBool - Attempt to contextually convert the
5429 /// expression From to bool (C++0x [conv]p3).
5430 static ImplicitConversionSequence
5431 TryContextuallyConvertToBool(Sema &S, Expr *From) {
5432 return TryImplicitConversion(S, From, S.Context.BoolTy,
5433 /*SuppressUserConversions=*/false,
5434 /*AllowExplicit=*/true,
5435 /*InOverloadResolution=*/false,
5437 /*AllowObjCWritebackConversion=*/false,
5438 /*AllowObjCConversionOnExplicit=*/false);
5441 /// PerformContextuallyConvertToBool - Perform a contextual conversion
5442 /// of the expression From to bool (C++0x [conv]p3).
5443 ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5444 if (checkPlaceholderForOverload(*this, From))
5447 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5449 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5451 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5452 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5453 << From->getType() << From->getSourceRange();
5457 /// Check that the specified conversion is permitted in a converted constant
5458 /// expression, according to C++11 [expr.const]p3. Return true if the conversion
5460 static bool CheckConvertedConstantConversions(Sema &S,
5461 StandardConversionSequence &SCS) {
5462 // Since we know that the target type is an integral or unscoped enumeration
5463 // type, most conversion kinds are impossible. All possible First and Third
5464 // conversions are fine.
5465 switch (SCS.Second) {
5467 case ICK_Function_Conversion:
5468 case ICK_Integral_Promotion:
5469 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5470 case ICK_Zero_Queue_Conversion:
5473 case ICK_Boolean_Conversion:
5474 // Conversion from an integral or unscoped enumeration type to bool is
5475 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5476 // conversion, so we allow it in a converted constant expression.
5478 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5479 // a lot of popular code. We should at least add a warning for this
5480 // (non-conforming) extension.
5481 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5482 SCS.getToType(2)->isBooleanType();
5484 case ICK_Pointer_Conversion:
5485 case ICK_Pointer_Member:
5486 // C++1z: null pointer conversions and null member pointer conversions are
5487 // only permitted if the source type is std::nullptr_t.
5488 return SCS.getFromType()->isNullPtrType();
5490 case ICK_Floating_Promotion:
5491 case ICK_Complex_Promotion:
5492 case ICK_Floating_Conversion:
5493 case ICK_Complex_Conversion:
5494 case ICK_Floating_Integral:
5495 case ICK_Compatible_Conversion:
5496 case ICK_Derived_To_Base:
5497 case ICK_Vector_Conversion:
5498 case ICK_Vector_Splat:
5499 case ICK_Complex_Real:
5500 case ICK_Block_Pointer_Conversion:
5501 case ICK_TransparentUnionConversion:
5502 case ICK_Writeback_Conversion:
5503 case ICK_Zero_Event_Conversion:
5504 case ICK_C_Only_Conversion:
5505 case ICK_Incompatible_Pointer_Conversion:
5508 case ICK_Lvalue_To_Rvalue:
5509 case ICK_Array_To_Pointer:
5510 case ICK_Function_To_Pointer:
5511 llvm_unreachable("found a first conversion kind in Second");
5513 case ICK_Qualification:
5514 llvm_unreachable("found a third conversion kind in Second");
5516 case ICK_Num_Conversion_Kinds:
5520 llvm_unreachable("unknown conversion kind");
5523 /// CheckConvertedConstantExpression - Check that the expression From is a
5524 /// converted constant expression of type T, perform the conversion and produce
5525 /// the converted expression, per C++11 [expr.const]p3.
5526 static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5527 QualType T, APValue &Value,
5530 assert(S.getLangOpts().CPlusPlus11 &&
5531 "converted constant expression outside C++11");
5533 if (checkPlaceholderForOverload(S, From))
5536 // C++1z [expr.const]p3:
5537 // A converted constant expression of type T is an expression,
5538 // implicitly converted to type T, where the converted
5539 // expression is a constant expression and the implicit conversion
5540 // sequence contains only [... list of conversions ...].
5541 // C++1z [stmt.if]p2:
5542 // If the if statement is of the form if constexpr, the value of the
5543 // condition shall be a contextually converted constant expression of type
5545 ImplicitConversionSequence ICS =
5546 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
5547 ? TryContextuallyConvertToBool(S, From)
5548 : TryCopyInitialization(S, From, T,
5549 /*SuppressUserConversions=*/false,
5550 /*InOverloadResolution=*/false,
5551 /*AllowObjCWritebackConversion=*/false,
5552 /*AllowExplicit=*/false);
5553 StandardConversionSequence *SCS = nullptr;
5554 switch (ICS.getKind()) {
5555 case ImplicitConversionSequence::StandardConversion:
5556 SCS = &ICS.Standard;
5558 case ImplicitConversionSequence::UserDefinedConversion:
5559 // We are converting to a non-class type, so the Before sequence
5561 SCS = &ICS.UserDefined.After;
5563 case ImplicitConversionSequence::AmbiguousConversion:
5564 case ImplicitConversionSequence::BadConversion:
5565 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5566 return S.Diag(From->getBeginLoc(),
5567 diag::err_typecheck_converted_constant_expression)
5568 << From->getType() << From->getSourceRange() << T;
5571 case ImplicitConversionSequence::EllipsisConversion:
5572 llvm_unreachable("ellipsis conversion in converted constant expression");
5575 // Check that we would only use permitted conversions.
5576 if (!CheckConvertedConstantConversions(S, *SCS)) {
5577 return S.Diag(From->getBeginLoc(),
5578 diag::err_typecheck_converted_constant_expression_disallowed)
5579 << From->getType() << From->getSourceRange() << T;
5581 // [...] and where the reference binding (if any) binds directly.
5582 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5583 return S.Diag(From->getBeginLoc(),
5584 diag::err_typecheck_converted_constant_expression_indirect)
5585 << From->getType() << From->getSourceRange() << T;
5589 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5590 if (Result.isInvalid())
5593 // C++2a [intro.execution]p5:
5594 // A full-expression is [...] a constant-expression [...]
5596 S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
5597 /*DiscardedValue=*/false, /*IsConstexpr=*/true);
5598 if (Result.isInvalid())
5601 // Check for a narrowing implicit conversion.
5602 APValue PreNarrowingValue;
5603 QualType PreNarrowingType;
5604 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5605 PreNarrowingType)) {
5606 case NK_Dependent_Narrowing:
5607 // Implicit conversion to a narrower type, but the expression is
5608 // value-dependent so we can't tell whether it's actually narrowing.
5609 case NK_Variable_Narrowing:
5610 // Implicit conversion to a narrower type, and the value is not a constant
5611 // expression. We'll diagnose this in a moment.
5612 case NK_Not_Narrowing:
5615 case NK_Constant_Narrowing:
5616 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5617 << CCE << /*Constant*/ 1
5618 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5621 case NK_Type_Narrowing:
5622 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5623 << CCE << /*Constant*/ 0 << From->getType() << T;
5627 if (Result.get()->isValueDependent()) {
5632 // Check the expression is a constant expression.
5633 SmallVector<PartialDiagnosticAt, 8> Notes;
5634 Expr::EvalResult Eval;
5636 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5637 ? Expr::EvaluateForMangling
5638 : Expr::EvaluateForCodeGen;
5640 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5641 (RequireInt && !Eval.Val.isInt())) {
5642 // The expression can't be folded, so we can't keep it at this position in
5644 Result = ExprError();
5648 if (Notes.empty()) {
5649 // It's a constant expression.
5650 return ConstantExpr::Create(S.Context, Result.get(), Value);
5654 // It's not a constant expression. Produce an appropriate diagnostic.
5655 if (Notes.size() == 1 &&
5656 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5657 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5659 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5660 << CCE << From->getSourceRange();
5661 for (unsigned I = 0; I < Notes.size(); ++I)
5662 S.Diag(Notes[I].first, Notes[I].second);
5667 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5668 APValue &Value, CCEKind CCE) {
5669 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5672 ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5673 llvm::APSInt &Value,
5675 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5678 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5679 if (!R.isInvalid() && !R.get()->isValueDependent())
5685 /// dropPointerConversions - If the given standard conversion sequence
5686 /// involves any pointer conversions, remove them. This may change
5687 /// the result type of the conversion sequence.
5688 static void dropPointerConversion(StandardConversionSequence &SCS) {
5689 if (SCS.Second == ICK_Pointer_Conversion) {
5690 SCS.Second = ICK_Identity;
5691 SCS.Third = ICK_Identity;
5692 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5696 /// TryContextuallyConvertToObjCPointer - Attempt to contextually
5697 /// convert the expression From to an Objective-C pointer type.
5698 static ImplicitConversionSequence
5699 TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5700 // Do an implicit conversion to 'id'.
5701 QualType Ty = S.Context.getObjCIdType();
5702 ImplicitConversionSequence ICS
5703 = TryImplicitConversion(S, From, Ty,
5704 // FIXME: Are these flags correct?
5705 /*SuppressUserConversions=*/false,
5706 /*AllowExplicit=*/true,
5707 /*InOverloadResolution=*/false,
5709 /*AllowObjCWritebackConversion=*/false,
5710 /*AllowObjCConversionOnExplicit=*/true);
5712 // Strip off any final conversions to 'id'.
5713 switch (ICS.getKind()) {
5714 case ImplicitConversionSequence::BadConversion:
5715 case ImplicitConversionSequence::AmbiguousConversion:
5716 case ImplicitConversionSequence::EllipsisConversion:
5719 case ImplicitConversionSequence::UserDefinedConversion:
5720 dropPointerConversion(ICS.UserDefined.After);
5723 case ImplicitConversionSequence::StandardConversion:
5724 dropPointerConversion(ICS.Standard);
5731 /// PerformContextuallyConvertToObjCPointer - Perform a contextual
5732 /// conversion of the expression From to an Objective-C pointer type.
5733 /// Returns a valid but null ExprResult if no conversion sequence exists.
5734 ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5735 if (checkPlaceholderForOverload(*this, From))
5738 QualType Ty = Context.getObjCIdType();
5739 ImplicitConversionSequence ICS =
5740 TryContextuallyConvertToObjCPointer(*this, From);
5742 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5743 return ExprResult();
5746 /// Determine whether the provided type is an integral type, or an enumeration
5747 /// type of a permitted flavor.
5748 bool Sema::ICEConvertDiagnoser::match(QualType T) {
5749 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5750 : T->isIntegralOrUnscopedEnumerationType();
5754 diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5755 Sema::ContextualImplicitConverter &Converter,
5756 QualType T, UnresolvedSetImpl &ViableConversions) {
5758 if (Converter.Suppress)
5761 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5762 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5763 CXXConversionDecl *Conv =
5764 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5765 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5766 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5772 diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5773 Sema::ContextualImplicitConverter &Converter,
5774 QualType T, bool HadMultipleCandidates,
5775 UnresolvedSetImpl &ExplicitConversions) {
5776 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5777 DeclAccessPair Found = ExplicitConversions[0];
5778 CXXConversionDecl *Conversion =
5779 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5781 // The user probably meant to invoke the given explicit
5782 // conversion; use it.
5783 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5784 std::string TypeStr;
5785 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5787 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5788 << FixItHint::CreateInsertion(From->getBeginLoc(),
5789 "static_cast<" + TypeStr + ">(")
5790 << FixItHint::CreateInsertion(
5791 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5792 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5794 // If we aren't in a SFINAE context, build a call to the
5795 // explicit conversion function.
5796 if (SemaRef.isSFINAEContext())
5799 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5800 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5801 HadMultipleCandidates);
5802 if (Result.isInvalid())
5804 // Record usage of conversion in an implicit cast.
5805 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5806 CK_UserDefinedConversion, Result.get(),
5807 nullptr, Result.get()->getValueKind());
5812 static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5813 Sema::ContextualImplicitConverter &Converter,
5814 QualType T, bool HadMultipleCandidates,
5815 DeclAccessPair &Found) {
5816 CXXConversionDecl *Conversion =
5817 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5818 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5820 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5821 if (!Converter.SuppressConversion) {
5822 if (SemaRef.isSFINAEContext())
5825 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5826 << From->getSourceRange();
5829 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5830 HadMultipleCandidates);
5831 if (Result.isInvalid())
5833 // Record usage of conversion in an implicit cast.
5834 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5835 CK_UserDefinedConversion, Result.get(),
5836 nullptr, Result.get()->getValueKind());
5840 static ExprResult finishContextualImplicitConversion(
5841 Sema &SemaRef, SourceLocation Loc, Expr *From,
5842 Sema::ContextualImplicitConverter &Converter) {
5843 if (!Converter.match(From->getType()) && !Converter.Suppress)
5844 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5845 << From->getSourceRange();
5847 return SemaRef.DefaultLvalueConversion(From);
5851 collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5852 UnresolvedSetImpl &ViableConversions,
5853 OverloadCandidateSet &CandidateSet) {
5854 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5855 DeclAccessPair FoundDecl = ViableConversions[I];
5856 NamedDecl *D = FoundDecl.getDecl();
5857 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5858 if (isa<UsingShadowDecl>(D))
5859 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5861 CXXConversionDecl *Conv;
5862 FunctionTemplateDecl *ConvTemplate;
5863 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5864 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5866 Conv = cast<CXXConversionDecl>(D);
5869 SemaRef.AddTemplateConversionCandidate(
5870 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5871 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
5873 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5874 ToType, CandidateSet,
5875 /*AllowObjCConversionOnExplicit=*/false,
5876 /*AllowExplicit*/ true);
5880 /// Attempt to convert the given expression to a type which is accepted
5881 /// by the given converter.
5883 /// This routine will attempt to convert an expression of class type to a
5884 /// type accepted by the specified converter. In C++11 and before, the class
5885 /// must have a single non-explicit conversion function converting to a matching
5886 /// type. In C++1y, there can be multiple such conversion functions, but only
5887 /// one target type.
5889 /// \param Loc The source location of the construct that requires the
5892 /// \param From The expression we're converting from.
5894 /// \param Converter Used to control and diagnose the conversion process.
5896 /// \returns The expression, converted to an integral or enumeration type if
5898 ExprResult Sema::PerformContextualImplicitConversion(
5899 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5900 // We can't perform any more checking for type-dependent expressions.
5901 if (From->isTypeDependent())
5904 // Process placeholders immediately.
5905 if (From->hasPlaceholderType()) {
5906 ExprResult result = CheckPlaceholderExpr(From);
5907 if (result.isInvalid())
5909 From = result.get();
5912 // If the expression already has a matching type, we're golden.
5913 QualType T = From->getType();
5914 if (Converter.match(T))
5915 return DefaultLvalueConversion(From);
5917 // FIXME: Check for missing '()' if T is a function type?
5919 // We can only perform contextual implicit conversions on objects of class
5921 const RecordType *RecordTy = T->getAs<RecordType>();
5922 if (!RecordTy || !getLangOpts().CPlusPlus) {
5923 if (!Converter.Suppress)
5924 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5928 // We must have a complete class type.
5929 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5930 ContextualImplicitConverter &Converter;
5933 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5934 : Converter(Converter), From(From) {}
5936 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5937 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5939 } IncompleteDiagnoser(Converter, From);
5941 if (Converter.Suppress ? !isCompleteType(Loc, T)
5942 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5945 // Look for a conversion to an integral or enumeration type.
5947 ViableConversions; // These are *potentially* viable in C++1y.
5948 UnresolvedSet<4> ExplicitConversions;
5949 const auto &Conversions =
5950 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5952 bool HadMultipleCandidates =
5953 (std::distance(Conversions.begin(), Conversions.end()) > 1);
5955 // To check that there is only one target type, in C++1y:
5957 bool HasUniqueTargetType = true;
5959 // Collect explicit or viable (potentially in C++1y) conversions.
5960 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5961 NamedDecl *D = (*I)->getUnderlyingDecl();
5962 CXXConversionDecl *Conversion;
5963 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5965 if (getLangOpts().CPlusPlus14)
5966 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5968 continue; // C++11 does not consider conversion operator templates(?).
5970 Conversion = cast<CXXConversionDecl>(D);
5972 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5973 "Conversion operator templates are considered potentially "
5976 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5977 if (Converter.match(CurToType) || ConvTemplate) {
5979 if (Conversion->isExplicit()) {
5980 // FIXME: For C++1y, do we need this restriction?
5981 // cf. diagnoseNoViableConversion()
5983 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5985 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5986 if (ToType.isNull())
5987 ToType = CurToType.getUnqualifiedType();
5988 else if (HasUniqueTargetType &&
5989 (CurToType.getUnqualifiedType() != ToType))
5990 HasUniqueTargetType = false;
5992 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5997 if (getLangOpts().CPlusPlus14) {
5999 // ... An expression e of class type E appearing in such a context
6000 // is said to be contextually implicitly converted to a specified
6001 // type T and is well-formed if and only if e can be implicitly
6002 // converted to a type T that is determined as follows: E is searched
6003 // for conversion functions whose return type is cv T or reference to
6004 // cv T such that T is allowed by the context. There shall be
6005 // exactly one such T.
6007 // If no unique T is found:
6008 if (ToType.isNull()) {
6009 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6010 HadMultipleCandidates,
6011 ExplicitConversions))
6013 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6016 // If more than one unique Ts are found:
6017 if (!HasUniqueTargetType)
6018 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6021 // If one unique T is found:
6022 // First, build a candidate set from the previously recorded
6023 // potentially viable conversions.
6024 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
6025 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6028 // Then, perform overload resolution over the candidate set.
6029 OverloadCandidateSet::iterator Best;
6030 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6032 // Apply this conversion.
6033 DeclAccessPair Found =
6034 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6035 if (recordConversion(*this, Loc, From, Converter, T,
6036 HadMultipleCandidates, Found))
6041 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6043 case OR_No_Viable_Function:
6044 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6045 HadMultipleCandidates,
6046 ExplicitConversions))
6050 // We'll complain below about a non-integral condition type.
6054 switch (ViableConversions.size()) {
6056 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6057 HadMultipleCandidates,
6058 ExplicitConversions))
6061 // We'll complain below about a non-integral condition type.
6065 // Apply this conversion.
6066 DeclAccessPair Found = ViableConversions[0];
6067 if (recordConversion(*this, Loc, From, Converter, T,
6068 HadMultipleCandidates, Found))
6073 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6078 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6081 /// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6082 /// an acceptable non-member overloaded operator for a call whose
6083 /// arguments have types T1 (and, if non-empty, T2). This routine
6084 /// implements the check in C++ [over.match.oper]p3b2 concerning
6085 /// enumeration types.
6086 static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
6088 ArrayRef<Expr *> Args) {
6089 QualType T1 = Args[0]->getType();
6090 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6092 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6095 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6098 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6099 if (Proto->getNumParams() < 1)
6102 if (T1->isEnumeralType()) {
6103 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
6104 if (Context.hasSameUnqualifiedType(T1, ArgType))
6108 if (Proto->getNumParams() < 2)
6111 if (!T2.isNull() && T2->isEnumeralType()) {
6112 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
6113 if (Context.hasSameUnqualifiedType(T2, ArgType))
6120 /// AddOverloadCandidate - Adds the given function to the set of
6121 /// candidate functions, using the given function call arguments. If
6122 /// @p SuppressUserConversions, then don't allow user-defined
6123 /// conversions via constructors or conversion operators.
6125 /// \param PartialOverloading true if we are performing "partial" overloading
6126 /// based on an incomplete set of function arguments. This feature is used by
6127 /// code completion.
6128 void Sema::AddOverloadCandidate(
6129 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6130 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6131 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6132 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
6133 OverloadCandidateParamOrder PO) {
6134 const FunctionProtoType *Proto
6135 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6136 assert(Proto && "Functions without a prototype cannot be overloaded");
6137 assert(!Function->getDescribedFunctionTemplate() &&
6138 "Use AddTemplateOverloadCandidate for function templates");
6140 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6141 if (!isa<CXXConstructorDecl>(Method)) {
6142 // If we get here, it's because we're calling a member function
6143 // that is named without a member access expression (e.g.,
6144 // "this->f") that was either written explicitly or created
6145 // implicitly. This can happen with a qualified call to a member
6146 // function, e.g., X::f(). We use an empty type for the implied
6147 // object argument (C++ [over.call.func]p3), and the acting context
6149 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6150 Expr::Classification::makeSimpleLValue(), Args,
6151 CandidateSet, SuppressUserConversions,
6152 PartialOverloading, EarlyConversions, PO);
6155 // We treat a constructor like a non-member function, since its object
6156 // argument doesn't participate in overload resolution.
6159 if (!CandidateSet.isNewCandidate(Function, PO))
6162 // C++11 [class.copy]p11: [DR1402]
6163 // A defaulted move constructor that is defined as deleted is ignored by
6164 // overload resolution.
6165 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6166 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6167 Constructor->isMoveConstructor())
6170 // Overload resolution is always an unevaluated context.
6171 EnterExpressionEvaluationContext Unevaluated(
6172 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6174 // C++ [over.match.oper]p3:
6175 // if no operand has a class type, only those non-member functions in the
6176 // lookup set that have a first parameter of type T1 or "reference to
6177 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6178 // is a right operand) a second parameter of type T2 or "reference to
6179 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6180 // candidate functions.
6181 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6182 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6185 // Add this candidate
6186 OverloadCandidate &Candidate =
6187 CandidateSet.addCandidate(Args.size(), EarlyConversions);
6188 Candidate.FoundDecl = FoundDecl;
6189 Candidate.Function = Function;
6190 Candidate.Viable = true;
6191 Candidate.RewriteKind =
6192 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
6193 Candidate.IsSurrogate = false;
6194 Candidate.IsADLCandidate = IsADLCandidate;
6195 Candidate.IgnoreObjectArgument = false;
6196 Candidate.ExplicitCallArguments = Args.size();
6198 // Explicit functions are not actually candidates at all if we're not
6199 // allowing them in this context, but keep them around so we can point
6200 // to them in diagnostics.
6201 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
6202 Candidate.Viable = false;
6203 Candidate.FailureKind = ovl_fail_explicit;
6207 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6208 !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6209 Candidate.Viable = false;
6210 Candidate.FailureKind = ovl_non_default_multiversion_function;
6215 // C++ [class.copy]p3:
6216 // A member function template is never instantiated to perform the copy
6217 // of a class object to an object of its class type.
6218 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6219 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6220 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6221 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6223 Candidate.Viable = false;
6224 Candidate.FailureKind = ovl_fail_illegal_constructor;
6228 // C++ [over.match.funcs]p8: (proposed DR resolution)
6229 // A constructor inherited from class type C that has a first parameter
6230 // of type "reference to P" (including such a constructor instantiated
6231 // from a template) is excluded from the set of candidate functions when
6232 // constructing an object of type cv D if the argument list has exactly
6233 // one argument and D is reference-related to P and P is reference-related
6235 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6236 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6237 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6238 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6239 QualType C = Context.getRecordType(Constructor->getParent());
6240 QualType D = Context.getRecordType(Shadow->getParent());
6241 SourceLocation Loc = Args.front()->getExprLoc();
6242 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6243 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6244 Candidate.Viable = false;
6245 Candidate.FailureKind = ovl_fail_inhctor_slice;
6250 // Check that the constructor is capable of constructing an object in the
6251 // destination address space.
6252 if (!Qualifiers::isAddressSpaceSupersetOf(
6253 Constructor->getMethodQualifiers().getAddressSpace(),
6254 CandidateSet.getDestAS())) {
6255 Candidate.Viable = false;
6256 Candidate.FailureKind = ovl_fail_object_addrspace_mismatch;
6260 unsigned NumParams = Proto->getNumParams();
6262 // (C++ 13.3.2p2): A candidate function having fewer than m
6263 // parameters is viable only if it has an ellipsis in its parameter
6265 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6266 !Proto->isVariadic()) {
6267 Candidate.Viable = false;
6268 Candidate.FailureKind = ovl_fail_too_many_arguments;
6272 // (C++ 13.3.2p2): A candidate function having more than m parameters
6273 // is viable only if the (m+1)st parameter has a default argument
6274 // (8.3.6). For the purposes of overload resolution, the
6275 // parameter list is truncated on the right, so that there are
6276 // exactly m parameters.
6277 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6278 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6279 // Not enough arguments.
6280 Candidate.Viable = false;
6281 Candidate.FailureKind = ovl_fail_too_few_arguments;
6285 // (CUDA B.1): Check for invalid calls between targets.
6286 if (getLangOpts().CUDA)
6287 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6288 // Skip the check for callers that are implicit members, because in this
6289 // case we may not yet know what the member's target is; the target is
6290 // inferred for the member automatically, based on the bases and fields of
6292 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6293 Candidate.Viable = false;
6294 Candidate.FailureKind = ovl_fail_bad_target;
6298 if (Function->getTrailingRequiresClause()) {
6299 ConstraintSatisfaction Satisfaction;
6300 if (CheckFunctionConstraints(Function, Satisfaction) ||
6301 !Satisfaction.IsSatisfied) {
6302 Candidate.Viable = false;
6303 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6308 // Determine the implicit conversion sequences for each of the
6310 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6312 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
6313 if (Candidate.Conversions[ConvIdx].isInitialized()) {
6314 // We already formed a conversion sequence for this parameter during
6315 // template argument deduction.
6316 } else if (ArgIdx < NumParams) {
6317 // (C++ 13.3.2p3): for F to be a viable function, there shall
6318 // exist for each argument an implicit conversion sequence
6319 // (13.3.3.1) that converts that argument to the corresponding
6321 QualType ParamType = Proto->getParamType(ArgIdx);
6322 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
6323 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6324 /*InOverloadResolution=*/true,
6325 /*AllowObjCWritebackConversion=*/
6326 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6327 if (Candidate.Conversions[ConvIdx].isBad()) {
6328 Candidate.Viable = false;
6329 Candidate.FailureKind = ovl_fail_bad_conversion;
6333 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6334 // argument for which there is no corresponding parameter is
6335 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6336 Candidate.Conversions[ConvIdx].setEllipsis();
6340 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6341 Candidate.Viable = false;
6342 Candidate.FailureKind = ovl_fail_enable_if;
6343 Candidate.DeductionFailure.Data = FailedAttr;
6347 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6348 Candidate.Viable = false;
6349 Candidate.FailureKind = ovl_fail_ext_disabled;
6355 Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6356 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6357 if (Methods.size() <= 1)
6360 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6362 ObjCMethodDecl *Method = Methods[b];
6363 unsigned NumNamedArgs = Sel.getNumArgs();
6364 // Method might have more arguments than selector indicates. This is due
6365 // to addition of c-style arguments in method.
6366 if (Method->param_size() > NumNamedArgs)
6367 NumNamedArgs = Method->param_size();
6368 if (Args.size() < NumNamedArgs)
6371 for (unsigned i = 0; i < NumNamedArgs; i++) {
6372 // We can't do any type-checking on a type-dependent argument.
6373 if (Args[i]->isTypeDependent()) {
6378 ParmVarDecl *param = Method->parameters()[i];
6379 Expr *argExpr = Args[i];
6380 assert(argExpr && "SelectBestMethod(): missing expression");
6382 // Strip the unbridged-cast placeholder expression off unless it's
6383 // a consumed argument.
6384 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6385 !param->hasAttr<CFConsumedAttr>())
6386 argExpr = stripARCUnbridgedCast(argExpr);
6388 // If the parameter is __unknown_anytype, move on to the next method.
6389 if (param->getType() == Context.UnknownAnyTy) {
6394 ImplicitConversionSequence ConversionState
6395 = TryCopyInitialization(*this, argExpr, param->getType(),
6396 /*SuppressUserConversions*/false,
6397 /*InOverloadResolution=*/true,
6398 /*AllowObjCWritebackConversion=*/
6399 getLangOpts().ObjCAutoRefCount,
6400 /*AllowExplicit*/false);
6401 // This function looks for a reasonably-exact match, so we consider
6402 // incompatible pointer conversions to be a failure here.
6403 if (ConversionState.isBad() ||
6404 (ConversionState.isStandard() &&
6405 ConversionState.Standard.Second ==
6406 ICK_Incompatible_Pointer_Conversion)) {
6411 // Promote additional arguments to variadic methods.
6412 if (Match && Method->isVariadic()) {
6413 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6414 if (Args[i]->isTypeDependent()) {
6418 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6420 if (Arg.isInvalid()) {
6426 // Check for extra arguments to non-variadic methods.
6427 if (Args.size() != NumNamedArgs)
6429 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6430 // Special case when selectors have no argument. In this case, select
6431 // one with the most general result type of 'id'.
6432 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6433 QualType ReturnT = Methods[b]->getReturnType();
6434 if (ReturnT->isObjCIdType())
6447 convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6448 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6449 bool MissingImplicitThis, Expr *&ConvertedThis,
6450 SmallVectorImpl<Expr *> &ConvertedArgs) {
6452 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6453 assert(!isa<CXXConstructorDecl>(Method) &&
6454 "Shouldn't have `this` for ctors!");
6455 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6456 ExprResult R = S.PerformObjectArgumentInitialization(
6457 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6460 ConvertedThis = R.get();
6462 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6464 assert((MissingImplicitThis || MD->isStatic() ||
6465 isa<CXXConstructorDecl>(MD)) &&
6466 "Expected `this` for non-ctor instance methods");
6468 ConvertedThis = nullptr;
6471 // Ignore any variadic arguments. Converting them is pointless, since the
6472 // user can't refer to them in the function condition.
6473 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6475 // Convert the arguments.
6476 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6478 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6479 S.Context, Function->getParamDecl(I)),
6480 SourceLocation(), Args[I]);
6485 ConvertedArgs.push_back(R.get());
6488 if (Trap.hasErrorOccurred())
6491 // Push default arguments if needed.
6492 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6493 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6494 ParmVarDecl *P = Function->getParamDecl(i);
6495 Expr *DefArg = P->hasUninstantiatedDefaultArg()
6496 ? P->getUninstantiatedDefaultArg()
6497 : P->getDefaultArg();
6498 // This can only happen in code completion, i.e. when PartialOverloading
6503 S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6504 S.Context, Function->getParamDecl(i)),
6505 SourceLocation(), DefArg);
6508 ConvertedArgs.push_back(R.get());
6511 if (Trap.hasErrorOccurred())
6517 EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6518 bool MissingImplicitThis) {
6519 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6520 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6523 SFINAETrap Trap(*this);
6524 SmallVector<Expr *, 16> ConvertedArgs;
6525 // FIXME: We should look into making enable_if late-parsed.
6526 Expr *DiscardedThis;
6527 if (!convertArgsForAvailabilityChecks(
6528 *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6529 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6530 return *EnableIfAttrs.begin();
6532 for (auto *EIA : EnableIfAttrs) {
6534 // FIXME: This doesn't consider value-dependent cases, because doing so is
6535 // very difficult. Ideally, we should handle them more gracefully.
6536 if (EIA->getCond()->isValueDependent() ||
6537 !EIA->getCond()->EvaluateWithSubstitution(
6538 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6541 if (!Result.isInt() || !Result.getInt().getBoolValue())
6547 template <typename CheckFn>
6548 static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6549 bool ArgDependent, SourceLocation Loc,
6550 CheckFn &&IsSuccessful) {
6551 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6552 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6553 if (ArgDependent == DIA->getArgDependent())
6554 Attrs.push_back(DIA);
6557 // Common case: No diagnose_if attributes, so we can quit early.
6561 auto WarningBegin = std::stable_partition(
6562 Attrs.begin(), Attrs.end(),
6563 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6565 // Note that diagnose_if attributes are late-parsed, so they appear in the
6566 // correct order (unlike enable_if attributes).
6567 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6569 if (ErrAttr != WarningBegin) {
6570 const DiagnoseIfAttr *DIA = *ErrAttr;
6571 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6572 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6573 << DIA->getParent() << DIA->getCond()->getSourceRange();
6577 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6578 if (IsSuccessful(DIA)) {
6579 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6580 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6581 << DIA->getParent() << DIA->getCond()->getSourceRange();
6587 bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6588 const Expr *ThisArg,
6589 ArrayRef<const Expr *> Args,
6590 SourceLocation Loc) {
6591 return diagnoseDiagnoseIfAttrsWith(
6592 *this, Function, /*ArgDependent=*/true, Loc,
6593 [&](const DiagnoseIfAttr *DIA) {
6595 // It's sane to use the same Args for any redecl of this function, since
6596 // EvaluateWithSubstitution only cares about the position of each
6597 // argument in the arg list, not the ParmVarDecl* it maps to.
6598 if (!DIA->getCond()->EvaluateWithSubstitution(
6599 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6601 return Result.isInt() && Result.getInt().getBoolValue();
6605 bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6606 SourceLocation Loc) {
6607 return diagnoseDiagnoseIfAttrsWith(
6608 *this, ND, /*ArgDependent=*/false, Loc,
6609 [&](const DiagnoseIfAttr *DIA) {
6611 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6616 /// Add all of the function declarations in the given function set to
6617 /// the overload candidate set.
6618 void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6619 ArrayRef<Expr *> Args,
6620 OverloadCandidateSet &CandidateSet,
6621 TemplateArgumentListInfo *ExplicitTemplateArgs,
6622 bool SuppressUserConversions,
6623 bool PartialOverloading,
6624 bool FirstArgumentIsBase) {
6625 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6626 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6627 ArrayRef<Expr *> FunctionArgs = Args;
6629 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6631 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6633 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6634 QualType ObjectType;
6635 Expr::Classification ObjectClassification;
6636 if (Args.size() > 0) {
6637 if (Expr *E = Args[0]) {
6638 // Use the explicit base to restrict the lookup:
6639 ObjectType = E->getType();
6640 // Pointers in the object arguments are implicitly dereferenced, so we
6641 // always classify them as l-values.
6642 if (!ObjectType.isNull() && ObjectType->isPointerType())
6643 ObjectClassification = Expr::Classification::makeSimpleLValue();
6645 ObjectClassification = E->Classify(Context);
6646 } // .. else there is an implicit base.
6647 FunctionArgs = Args.slice(1);
6650 AddMethodTemplateCandidate(
6651 FunTmpl, F.getPair(),
6652 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6653 ExplicitTemplateArgs, ObjectType, ObjectClassification,
6654 FunctionArgs, CandidateSet, SuppressUserConversions,
6655 PartialOverloading);
6657 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6658 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6659 ObjectClassification, FunctionArgs, CandidateSet,
6660 SuppressUserConversions, PartialOverloading);
6663 // This branch handles both standalone functions and static methods.
6665 // Slice the first argument (which is the base) when we access
6666 // static method as non-static.
6667 if (Args.size() > 0 &&
6668 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6669 !isa<CXXConstructorDecl>(FD)))) {
6670 assert(cast<CXXMethodDecl>(FD)->isStatic());
6671 FunctionArgs = Args.slice(1);
6674 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
6675 ExplicitTemplateArgs, FunctionArgs,
6676 CandidateSet, SuppressUserConversions,
6677 PartialOverloading);
6679 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6680 SuppressUserConversions, PartialOverloading);
6686 /// AddMethodCandidate - Adds a named decl (which is some kind of
6687 /// method) as a method candidate to the given overload set.
6688 void Sema::AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType,
6689 Expr::Classification ObjectClassification,
6690 ArrayRef<Expr *> Args,
6691 OverloadCandidateSet &CandidateSet,
6692 bool SuppressUserConversions,
6693 OverloadCandidateParamOrder PO) {
6694 NamedDecl *Decl = FoundDecl.getDecl();
6695 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6697 if (isa<UsingShadowDecl>(Decl))
6698 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6700 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6701 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6702 "Expected a member function template");
6703 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6704 /*ExplicitArgs*/ nullptr, ObjectType,
6705 ObjectClassification, Args, CandidateSet,
6706 SuppressUserConversions, false, PO);
6708 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6709 ObjectType, ObjectClassification, Args, CandidateSet,
6710 SuppressUserConversions, false, None, PO);
6714 /// AddMethodCandidate - Adds the given C++ member function to the set
6715 /// of candidate functions, using the given function call arguments
6716 /// and the object argument (@c Object). For example, in a call
6717 /// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6718 /// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6719 /// allow user-defined conversions via constructors or conversion
6722 Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6723 CXXRecordDecl *ActingContext, QualType ObjectType,
6724 Expr::Classification ObjectClassification,
6725 ArrayRef<Expr *> Args,
6726 OverloadCandidateSet &CandidateSet,
6727 bool SuppressUserConversions,
6728 bool PartialOverloading,
6729 ConversionSequenceList EarlyConversions,
6730 OverloadCandidateParamOrder PO) {
6731 const FunctionProtoType *Proto
6732 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6733 assert(Proto && "Methods without a prototype cannot be overloaded");
6734 assert(!isa<CXXConstructorDecl>(Method) &&
6735 "Use AddOverloadCandidate for constructors");
6737 if (!CandidateSet.isNewCandidate(Method, PO))
6740 // C++11 [class.copy]p23: [DR1402]
6741 // A defaulted move assignment operator that is defined as deleted is
6742 // ignored by overload resolution.
6743 if (Method->isDefaulted() && Method->isDeleted() &&
6744 Method->isMoveAssignmentOperator())
6747 // Overload resolution is always an unevaluated context.
6748 EnterExpressionEvaluationContext Unevaluated(
6749 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6751 // Add this candidate
6752 OverloadCandidate &Candidate =
6753 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6754 Candidate.FoundDecl = FoundDecl;
6755 Candidate.Function = Method;
6756 Candidate.RewriteKind =
6757 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
6758 Candidate.IsSurrogate = false;
6759 Candidate.IgnoreObjectArgument = false;
6760 Candidate.ExplicitCallArguments = Args.size();
6762 unsigned NumParams = Proto->getNumParams();
6764 // (C++ 13.3.2p2): A candidate function having fewer than m
6765 // parameters is viable only if it has an ellipsis in its parameter
6767 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6768 !Proto->isVariadic()) {
6769 Candidate.Viable = false;
6770 Candidate.FailureKind = ovl_fail_too_many_arguments;
6774 // (C++ 13.3.2p2): A candidate function having more than m parameters
6775 // is viable only if the (m+1)st parameter has a default argument
6776 // (8.3.6). For the purposes of overload resolution, the
6777 // parameter list is truncated on the right, so that there are
6778 // exactly m parameters.
6779 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6780 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6781 // Not enough arguments.
6782 Candidate.Viable = false;
6783 Candidate.FailureKind = ovl_fail_too_few_arguments;
6787 Candidate.Viable = true;
6789 if (Method->isStatic() || ObjectType.isNull())
6790 // The implicit object argument is ignored.
6791 Candidate.IgnoreObjectArgument = true;
6793 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
6794 // Determine the implicit conversion sequence for the object
6796 Candidate.Conversions[ConvIdx] = TryObjectArgumentInitialization(
6797 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6798 Method, ActingContext);
6799 if (Candidate.Conversions[ConvIdx].isBad()) {
6800 Candidate.Viable = false;
6801 Candidate.FailureKind = ovl_fail_bad_conversion;
6806 // (CUDA B.1): Check for invalid calls between targets.
6807 if (getLangOpts().CUDA)
6808 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6809 if (!IsAllowedCUDACall(Caller, Method)) {
6810 Candidate.Viable = false;
6811 Candidate.FailureKind = ovl_fail_bad_target;
6815 if (Method->getTrailingRequiresClause()) {
6816 ConstraintSatisfaction Satisfaction;
6817 if (CheckFunctionConstraints(Method, Satisfaction) ||
6818 !Satisfaction.IsSatisfied) {
6819 Candidate.Viable = false;
6820 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
6825 // Determine the implicit conversion sequences for each of the
6827 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6829 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + 1);
6830 if (Candidate.Conversions[ConvIdx].isInitialized()) {
6831 // We already formed a conversion sequence for this parameter during
6832 // template argument deduction.
6833 } else if (ArgIdx < NumParams) {
6834 // (C++ 13.3.2p3): for F to be a viable function, there shall
6835 // exist for each argument an implicit conversion sequence
6836 // (13.3.3.1) that converts that argument to the corresponding
6838 QualType ParamType = Proto->getParamType(ArgIdx);
6839 Candidate.Conversions[ConvIdx]
6840 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6841 SuppressUserConversions,
6842 /*InOverloadResolution=*/true,
6843 /*AllowObjCWritebackConversion=*/
6844 getLangOpts().ObjCAutoRefCount);
6845 if (Candidate.Conversions[ConvIdx].isBad()) {
6846 Candidate.Viable = false;
6847 Candidate.FailureKind = ovl_fail_bad_conversion;
6851 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6852 // argument for which there is no corresponding parameter is
6853 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6854 Candidate.Conversions[ConvIdx].setEllipsis();
6858 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6859 Candidate.Viable = false;
6860 Candidate.FailureKind = ovl_fail_enable_if;
6861 Candidate.DeductionFailure.Data = FailedAttr;
6865 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6866 !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6867 Candidate.Viable = false;
6868 Candidate.FailureKind = ovl_non_default_multiversion_function;
6872 /// Add a C++ member function template as a candidate to the candidate
6873 /// set, using template argument deduction to produce an appropriate member
6874 /// function template specialization.
6875 void Sema::AddMethodTemplateCandidate(
6876 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
6877 CXXRecordDecl *ActingContext,
6878 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
6879 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
6880 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6881 bool PartialOverloading, OverloadCandidateParamOrder PO) {
6882 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
6885 // C++ [over.match.funcs]p7:
6886 // In each case where a candidate is a function template, candidate
6887 // function template specializations are generated using template argument
6888 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6889 // candidate functions in the usual way.113) A given name can refer to one
6890 // or more function templates and also to a set of overloaded non-template
6891 // functions. In such a case, the candidate functions generated from each
6892 // function template are combined with the set of non-template candidate
6894 TemplateDeductionInfo Info(CandidateSet.getLocation());
6895 FunctionDecl *Specialization = nullptr;
6896 ConversionSequenceList Conversions;
6897 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6898 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6899 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6900 return CheckNonDependentConversions(
6901 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6902 SuppressUserConversions, ActingContext, ObjectType,
6903 ObjectClassification, PO);
6905 OverloadCandidate &Candidate =
6906 CandidateSet.addCandidate(Conversions.size(), Conversions);
6907 Candidate.FoundDecl = FoundDecl;
6908 Candidate.Function = MethodTmpl->getTemplatedDecl();
6909 Candidate.Viable = false;
6910 Candidate.RewriteKind =
6911 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
6912 Candidate.IsSurrogate = false;
6913 Candidate.IgnoreObjectArgument =
6914 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6915 ObjectType.isNull();
6916 Candidate.ExplicitCallArguments = Args.size();
6917 if (Result == TDK_NonDependentConversionFailure)
6918 Candidate.FailureKind = ovl_fail_bad_conversion;
6920 Candidate.FailureKind = ovl_fail_bad_deduction;
6921 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6927 // Add the function template specialization produced by template argument
6928 // deduction as a candidate.
6929 assert(Specialization && "Missing member function template specialization?");
6930 assert(isa<CXXMethodDecl>(Specialization) &&
6931 "Specialization is not a member function?");
6932 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6933 ActingContext, ObjectType, ObjectClassification, Args,
6934 CandidateSet, SuppressUserConversions, PartialOverloading,
6938 /// Determine whether a given function template has a simple explicit specifier
6939 /// or a non-value-dependent explicit-specification that evaluates to true.
6940 static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD) {
6941 return ExplicitSpecifier::getFromDecl(FTD->getTemplatedDecl()).isExplicit();
6944 /// Add a C++ function template specialization as a candidate
6945 /// in the candidate set, using template argument deduction to produce
6946 /// an appropriate function template specialization.
6947 void Sema::AddTemplateOverloadCandidate(
6948 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
6949 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6950 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6951 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
6952 OverloadCandidateParamOrder PO) {
6953 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
6956 // If the function template has a non-dependent explicit specification,
6957 // exclude it now if appropriate; we are not permitted to perform deduction
6958 // and substitution in this case.
6959 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
6960 OverloadCandidate &Candidate = CandidateSet.addCandidate();
6961 Candidate.FoundDecl = FoundDecl;
6962 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6963 Candidate.Viable = false;
6964 Candidate.FailureKind = ovl_fail_explicit;
6968 // C++ [over.match.funcs]p7:
6969 // In each case where a candidate is a function template, candidate
6970 // function template specializations are generated using template argument
6971 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6972 // candidate functions in the usual way.113) A given name can refer to one
6973 // or more function templates and also to a set of overloaded non-template
6974 // functions. In such a case, the candidate functions generated from each
6975 // function template are combined with the set of non-template candidate
6977 TemplateDeductionInfo Info(CandidateSet.getLocation());
6978 FunctionDecl *Specialization = nullptr;
6979 ConversionSequenceList Conversions;
6980 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6981 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6982 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6983 return CheckNonDependentConversions(
6984 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
6985 SuppressUserConversions, nullptr, QualType(), {}, PO);
6987 OverloadCandidate &Candidate =
6988 CandidateSet.addCandidate(Conversions.size(), Conversions);
6989 Candidate.FoundDecl = FoundDecl;
6990 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6991 Candidate.Viable = false;
6992 Candidate.RewriteKind =
6993 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
6994 Candidate.IsSurrogate = false;
6995 Candidate.IsADLCandidate = IsADLCandidate;
6996 // Ignore the object argument if there is one, since we don't have an object
6998 Candidate.IgnoreObjectArgument =
6999 isa<CXXMethodDecl>(Candidate.Function) &&
7000 !isa<CXXConstructorDecl>(Candidate.Function);
7001 Candidate.ExplicitCallArguments = Args.size();
7002 if (Result == TDK_NonDependentConversionFailure)
7003 Candidate.FailureKind = ovl_fail_bad_conversion;
7005 Candidate.FailureKind = ovl_fail_bad_deduction;
7006 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7012 // Add the function template specialization produced by template argument
7013 // deduction as a candidate.
7014 assert(Specialization && "Missing function template specialization?");
7015 AddOverloadCandidate(
7016 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
7017 PartialOverloading, AllowExplicit,
7018 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions, PO);
7021 /// Check that implicit conversion sequences can be formed for each argument
7022 /// whose corresponding parameter has a non-dependent type, per DR1391's
7023 /// [temp.deduct.call]p10.
7024 bool Sema::CheckNonDependentConversions(
7025 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
7026 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
7027 ConversionSequenceList &Conversions, bool SuppressUserConversions,
7028 CXXRecordDecl *ActingContext, QualType ObjectType,
7029 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
7030 // FIXME: The cases in which we allow explicit conversions for constructor
7031 // arguments never consider calling a constructor template. It's not clear
7033 const bool AllowExplicit = false;
7035 auto *FD = FunctionTemplate->getTemplatedDecl();
7036 auto *Method = dyn_cast<CXXMethodDecl>(FD);
7037 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
7038 unsigned ThisConversions = HasThisConversion ? 1 : 0;
7041 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
7043 // Overload resolution is always an unevaluated context.
7044 EnterExpressionEvaluationContext Unevaluated(
7045 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7047 // For a method call, check the 'this' conversion here too. DR1391 doesn't
7048 // require that, but this check should never result in a hard error, and
7049 // overload resolution is permitted to sidestep instantiations.
7050 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
7051 !ObjectType.isNull()) {
7052 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7053 Conversions[ConvIdx] = TryObjectArgumentInitialization(
7054 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7055 Method, ActingContext);
7056 if (Conversions[ConvIdx].isBad())
7060 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
7062 QualType ParamType = ParamTypes[I];
7063 if (!ParamType->isDependentType()) {
7064 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
7066 : (ThisConversions + I);
7067 Conversions[ConvIdx]
7068 = TryCopyInitialization(*this, Args[I], ParamType,
7069 SuppressUserConversions,
7070 /*InOverloadResolution=*/true,
7071 /*AllowObjCWritebackConversion=*/
7072 getLangOpts().ObjCAutoRefCount,
7074 if (Conversions[ConvIdx].isBad())
7082 /// Determine whether this is an allowable conversion from the result
7083 /// of an explicit conversion operator to the expected type, per C++
7084 /// [over.match.conv]p1 and [over.match.ref]p1.
7086 /// \param ConvType The return type of the conversion function.
7088 /// \param ToType The type we are converting to.
7090 /// \param AllowObjCPointerConversion Allow a conversion from one
7091 /// Objective-C pointer to another.
7093 /// \returns true if the conversion is allowable, false otherwise.
7094 static bool isAllowableExplicitConversion(Sema &S,
7095 QualType ConvType, QualType ToType,
7096 bool AllowObjCPointerConversion) {
7097 QualType ToNonRefType = ToType.getNonReferenceType();
7099 // Easy case: the types are the same.
7100 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
7103 // Allow qualification conversions.
7104 bool ObjCLifetimeConversion;
7105 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
7106 ObjCLifetimeConversion))
7109 // If we're not allowed to consider Objective-C pointer conversions,
7111 if (!AllowObjCPointerConversion)
7114 // Is this an Objective-C pointer conversion?
7115 bool IncompatibleObjC = false;
7116 QualType ConvertedType;
7117 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
7121 /// AddConversionCandidate - Add a C++ conversion function as a
7122 /// candidate in the candidate set (C++ [over.match.conv],
7123 /// C++ [over.match.copy]). From is the expression we're converting from,
7124 /// and ToType is the type that we're eventually trying to convert to
7125 /// (which may or may not be the same type as the type that the
7126 /// conversion function produces).
7127 void Sema::AddConversionCandidate(
7128 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
7129 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
7130 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7131 bool AllowExplicit, bool AllowResultConversion) {
7132 assert(!Conversion->getDescribedFunctionTemplate() &&
7133 "Conversion function templates use AddTemplateConversionCandidate");
7134 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
7135 if (!CandidateSet.isNewCandidate(Conversion))
7138 // If the conversion function has an undeduced return type, trigger its
7140 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
7141 if (DeduceReturnType(Conversion, From->getExprLoc()))
7143 ConvType = Conversion->getConversionType().getNonReferenceType();
7146 // If we don't allow any conversion of the result type, ignore conversion
7147 // functions that don't convert to exactly (possibly cv-qualified) T.
7148 if (!AllowResultConversion &&
7149 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
7152 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
7153 // operator is only a candidate if its return type is the target type or
7154 // can be converted to the target type with a qualification conversion.
7156 // FIXME: Include such functions in the candidate list and explain why we
7157 // can't select them.
7158 if (Conversion->isExplicit() &&
7159 !isAllowableExplicitConversion(*this, ConvType, ToType,
7160 AllowObjCConversionOnExplicit))
7163 // Overload resolution is always an unevaluated context.
7164 EnterExpressionEvaluationContext Unevaluated(
7165 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7167 // Add this candidate
7168 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
7169 Candidate.FoundDecl = FoundDecl;
7170 Candidate.Function = Conversion;
7171 Candidate.IsSurrogate = false;
7172 Candidate.IgnoreObjectArgument = false;
7173 Candidate.FinalConversion.setAsIdentityConversion();
7174 Candidate.FinalConversion.setFromType(ConvType);
7175 Candidate.FinalConversion.setAllToTypes(ToType);
7176 Candidate.Viable = true;
7177 Candidate.ExplicitCallArguments = 1;
7179 // Explicit functions are not actually candidates at all if we're not
7180 // allowing them in this context, but keep them around so we can point
7181 // to them in diagnostics.
7182 if (!AllowExplicit && Conversion->isExplicit()) {
7183 Candidate.Viable = false;
7184 Candidate.FailureKind = ovl_fail_explicit;
7188 // C++ [over.match.funcs]p4:
7189 // For conversion functions, the function is considered to be a member of
7190 // the class of the implicit implied object argument for the purpose of
7191 // defining the type of the implicit object parameter.
7193 // Determine the implicit conversion sequence for the implicit
7194 // object parameter.
7195 QualType ImplicitParamType = From->getType();
7196 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7197 ImplicitParamType = FromPtrType->getPointeeType();
7198 CXXRecordDecl *ConversionContext
7199 = cast<CXXRecordDecl>(ImplicitParamType->castAs<RecordType>()->getDecl());
7201 Candidate.Conversions[0] = TryObjectArgumentInitialization(
7202 *this, CandidateSet.getLocation(), From->getType(),
7203 From->Classify(Context), Conversion, ConversionContext);
7205 if (Candidate.Conversions[0].isBad()) {
7206 Candidate.Viable = false;
7207 Candidate.FailureKind = ovl_fail_bad_conversion;
7211 if (Conversion->getTrailingRequiresClause()) {
7212 ConstraintSatisfaction Satisfaction;
7213 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
7214 !Satisfaction.IsSatisfied) {
7215 Candidate.Viable = false;
7216 Candidate.FailureKind = ovl_fail_constraints_not_satisfied;
7221 // We won't go through a user-defined type conversion function to convert a
7222 // derived to base as such conversions are given Conversion Rank. They only
7223 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7225 = Context.getCanonicalType(From->getType().getUnqualifiedType());
7226 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7227 if (FromCanon == ToCanon ||
7228 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7229 Candidate.Viable = false;
7230 Candidate.FailureKind = ovl_fail_trivial_conversion;
7234 // To determine what the conversion from the result of calling the
7235 // conversion function to the type we're eventually trying to
7236 // convert to (ToType), we need to synthesize a call to the
7237 // conversion function and attempt copy initialization from it. This
7238 // makes sure that we get the right semantics with respect to
7239 // lvalues/rvalues and the type. Fortunately, we can allocate this
7240 // call on the stack and we don't need its arguments to be
7242 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7243 VK_LValue, From->getBeginLoc());
7244 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7245 Context.getPointerType(Conversion->getType()),
7246 CK_FunctionToPointerDecay,
7247 &ConversionRef, VK_RValue);
7249 QualType ConversionType = Conversion->getConversionType();
7250 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7251 Candidate.Viable = false;
7252 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7256 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7258 // Note that it is safe to allocate CallExpr on the stack here because
7259 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7261 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7263 alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
7264 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7265 Buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7267 ImplicitConversionSequence ICS =
7268 TryCopyInitialization(*this, TheTemporaryCall, ToType,
7269 /*SuppressUserConversions=*/true,
7270 /*InOverloadResolution=*/false,
7271 /*AllowObjCWritebackConversion=*/false);
7273 switch (ICS.getKind()) {
7274 case ImplicitConversionSequence::StandardConversion:
7275 Candidate.FinalConversion = ICS.Standard;
7277 // C++ [over.ics.user]p3:
7278 // If the user-defined conversion is specified by a specialization of a
7279 // conversion function template, the second standard conversion sequence
7280 // shall have exact match rank.
7281 if (Conversion->getPrimaryTemplate() &&
7282 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7283 Candidate.Viable = false;
7284 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7288 // C++0x [dcl.init.ref]p5:
7289 // In the second case, if the reference is an rvalue reference and
7290 // the second standard conversion sequence of the user-defined
7291 // conversion sequence includes an lvalue-to-rvalue conversion, the
7292 // program is ill-formed.
7293 if (ToType->isRValueReferenceType() &&
7294 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7295 Candidate.Viable = false;
7296 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7301 case ImplicitConversionSequence::BadConversion:
7302 Candidate.Viable = false;
7303 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7308 "Can only end up with a standard conversion sequence or failure");
7311 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7312 Candidate.Viable = false;
7313 Candidate.FailureKind = ovl_fail_enable_if;
7314 Candidate.DeductionFailure.Data = FailedAttr;
7318 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7319 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7320 Candidate.Viable = false;
7321 Candidate.FailureKind = ovl_non_default_multiversion_function;
7325 /// Adds a conversion function template specialization
7326 /// candidate to the overload set, using template argument deduction
7327 /// to deduce the template arguments of the conversion function
7328 /// template from the type that we are converting to (C++
7329 /// [temp.deduct.conv]).
7330 void Sema::AddTemplateConversionCandidate(
7331 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7332 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7333 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7334 bool AllowExplicit, bool AllowResultConversion) {
7335 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7336 "Only conversion function templates permitted here");
7338 if (!CandidateSet.isNewCandidate(FunctionTemplate))
7341 // If the function template has a non-dependent explicit specification,
7342 // exclude it now if appropriate; we are not permitted to perform deduction
7343 // and substitution in this case.
7344 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7345 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7346 Candidate.FoundDecl = FoundDecl;
7347 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7348 Candidate.Viable = false;
7349 Candidate.FailureKind = ovl_fail_explicit;
7353 TemplateDeductionInfo Info(CandidateSet.getLocation());
7354 CXXConversionDecl *Specialization = nullptr;
7355 if (TemplateDeductionResult Result
7356 = DeduceTemplateArguments(FunctionTemplate, ToType,
7357 Specialization, Info)) {
7358 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7359 Candidate.FoundDecl = FoundDecl;
7360 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7361 Candidate.Viable = false;
7362 Candidate.FailureKind = ovl_fail_bad_deduction;
7363 Candidate.IsSurrogate = false;
7364 Candidate.IgnoreObjectArgument = false;
7365 Candidate.ExplicitCallArguments = 1;
7366 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7371 // Add the conversion function template specialization produced by
7372 // template argument deduction as a candidate.
7373 assert(Specialization && "Missing function template specialization?");
7374 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7375 CandidateSet, AllowObjCConversionOnExplicit,
7376 AllowExplicit, AllowResultConversion);
7379 /// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7380 /// converts the given @c Object to a function pointer via the
7381 /// conversion function @c Conversion, and then attempts to call it
7382 /// with the given arguments (C++ [over.call.object]p2-4). Proto is
7383 /// the type of function that we'll eventually be calling.
7384 void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7385 DeclAccessPair FoundDecl,
7386 CXXRecordDecl *ActingContext,
7387 const FunctionProtoType *Proto,
7389 ArrayRef<Expr *> Args,
7390 OverloadCandidateSet& CandidateSet) {
7391 if (!CandidateSet.isNewCandidate(Conversion))
7394 // Overload resolution is always an unevaluated context.
7395 EnterExpressionEvaluationContext Unevaluated(
7396 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7398 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7399 Candidate.FoundDecl = FoundDecl;
7400 Candidate.Function = nullptr;
7401 Candidate.Surrogate = Conversion;
7402 Candidate.Viable = true;
7403 Candidate.IsSurrogate = true;
7404 Candidate.IgnoreObjectArgument = false;
7405 Candidate.ExplicitCallArguments = Args.size();
7407 // Determine the implicit conversion sequence for the implicit
7408 // object parameter.
7409 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7410 *this, CandidateSet.getLocation(), Object->getType(),
7411 Object->Classify(Context), Conversion, ActingContext);
7412 if (ObjectInit.isBad()) {
7413 Candidate.Viable = false;
7414 Candidate.FailureKind = ovl_fail_bad_conversion;
7415 Candidate.Conversions[0] = ObjectInit;
7419 // The first conversion is actually a user-defined conversion whose
7420 // first conversion is ObjectInit's standard conversion (which is
7421 // effectively a reference binding). Record it as such.
7422 Candidate.Conversions[0].setUserDefined();
7423 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7424 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7425 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7426 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7427 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7428 Candidate.Conversions[0].UserDefined.After
7429 = Candidate.Conversions[0].UserDefined.Before;
7430 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7433 unsigned NumParams = Proto->getNumParams();
7435 // (C++ 13.3.2p2): A candidate function having fewer than m
7436 // parameters is viable only if it has an ellipsis in its parameter
7438 if (Args.size() > NumParams && !Proto->isVariadic()) {
7439 Candidate.Viable = false;
7440 Candidate.FailureKind = ovl_fail_too_many_arguments;
7444 // Function types don't have any default arguments, so just check if
7445 // we have enough arguments.
7446 if (Args.size() < NumParams) {
7447 // Not enough arguments.
7448 Candidate.Viable = false;
7449 Candidate.FailureKind = ovl_fail_too_few_arguments;
7453 // Determine the implicit conversion sequences for each of the
7455 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7456 if (ArgIdx < NumParams) {
7457 // (C++ 13.3.2p3): for F to be a viable function, there shall
7458 // exist for each argument an implicit conversion sequence
7459 // (13.3.3.1) that converts that argument to the corresponding
7461 QualType ParamType = Proto->getParamType(ArgIdx);
7462 Candidate.Conversions[ArgIdx + 1]
7463 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7464 /*SuppressUserConversions=*/false,
7465 /*InOverloadResolution=*/false,
7466 /*AllowObjCWritebackConversion=*/
7467 getLangOpts().ObjCAutoRefCount);
7468 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7469 Candidate.Viable = false;
7470 Candidate.FailureKind = ovl_fail_bad_conversion;
7474 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7475 // argument for which there is no corresponding parameter is
7476 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7477 Candidate.Conversions[ArgIdx + 1].setEllipsis();
7481 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7482 Candidate.Viable = false;
7483 Candidate.FailureKind = ovl_fail_enable_if;
7484 Candidate.DeductionFailure.Data = FailedAttr;
7489 /// Add all of the non-member operator function declarations in the given
7490 /// function set to the overload candidate set.
7491 void Sema::AddNonMemberOperatorCandidates(
7492 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
7493 OverloadCandidateSet &CandidateSet,
7494 TemplateArgumentListInfo *ExplicitTemplateArgs) {
7495 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7496 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7497 ArrayRef<Expr *> FunctionArgs = Args;
7499 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7501 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7503 // Don't consider rewritten functions if we're not rewriting.
7504 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
7507 assert(!isa<CXXMethodDecl>(FD) &&
7508 "unqualified operator lookup found a member function");
7511 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
7512 FunctionArgs, CandidateSet);
7513 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7514 AddTemplateOverloadCandidate(
7515 FunTmpl, F.getPair(), ExplicitTemplateArgs,
7516 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet, false, false,
7517 true, ADLCallKind::NotADL, OverloadCandidateParamOrder::Reversed);
7519 if (ExplicitTemplateArgs)
7521 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
7522 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD))
7523 AddOverloadCandidate(FD, F.getPair(),
7524 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
7525 false, false, true, false, ADLCallKind::NotADL,
7526 None, OverloadCandidateParamOrder::Reversed);
7531 /// Add overload candidates for overloaded operators that are
7532 /// member functions.
7534 /// Add the overloaded operator candidates that are member functions
7535 /// for the operator Op that was used in an operator expression such
7536 /// as "x Op y". , Args/NumArgs provides the operator arguments, and
7537 /// CandidateSet will store the added overload candidates. (C++
7538 /// [over.match.oper]).
7539 void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7540 SourceLocation OpLoc,
7541 ArrayRef<Expr *> Args,
7542 OverloadCandidateSet &CandidateSet,
7543 OverloadCandidateParamOrder PO) {
7544 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7546 // C++ [over.match.oper]p3:
7547 // For a unary operator @ with an operand of a type whose
7548 // cv-unqualified version is T1, and for a binary operator @ with
7549 // a left operand of a type whose cv-unqualified version is T1 and
7550 // a right operand of a type whose cv-unqualified version is T2,
7551 // three sets of candidate functions, designated member
7552 // candidates, non-member candidates and built-in candidates, are
7553 // constructed as follows:
7554 QualType T1 = Args[0]->getType();
7556 // -- If T1 is a complete class type or a class currently being
7557 // defined, the set of member candidates is the result of the
7558 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7559 // the set of member candidates is empty.
7560 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7561 // Complete the type if it can be completed.
7562 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7564 // If the type is neither complete nor being defined, bail out now.
7565 if (!T1Rec->getDecl()->getDefinition())
7568 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7569 LookupQualifiedName(Operators, T1Rec->getDecl());
7570 Operators.suppressDiagnostics();
7572 for (LookupResult::iterator Oper = Operators.begin(),
7573 OperEnd = Operators.end();
7576 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7577 Args[0]->Classify(Context), Args.slice(1),
7578 CandidateSet, /*SuppressUserConversion=*/false, PO);
7582 /// AddBuiltinCandidate - Add a candidate for a built-in
7583 /// operator. ResultTy and ParamTys are the result and parameter types
7584 /// of the built-in candidate, respectively. Args and NumArgs are the
7585 /// arguments being passed to the candidate. IsAssignmentOperator
7586 /// should be true when this built-in candidate is an assignment
7587 /// operator. NumContextualBoolArguments is the number of arguments
7588 /// (at the beginning of the argument list) that will be contextually
7589 /// converted to bool.
7590 void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7591 OverloadCandidateSet& CandidateSet,
7592 bool IsAssignmentOperator,
7593 unsigned NumContextualBoolArguments) {
7594 // Overload resolution is always an unevaluated context.
7595 EnterExpressionEvaluationContext Unevaluated(
7596 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7598 // Add this candidate
7599 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7600 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7601 Candidate.Function = nullptr;
7602 Candidate.IsSurrogate = false;
7603 Candidate.IgnoreObjectArgument = false;
7604 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7606 // Determine the implicit conversion sequences for each of the
7608 Candidate.Viable = true;
7609 Candidate.ExplicitCallArguments = Args.size();
7610 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7611 // C++ [over.match.oper]p4:
7612 // For the built-in assignment operators, conversions of the
7613 // left operand are restricted as follows:
7614 // -- no temporaries are introduced to hold the left operand, and
7615 // -- no user-defined conversions are applied to the left
7616 // operand to achieve a type match with the left-most
7617 // parameter of a built-in candidate.
7619 // We block these conversions by turning off user-defined
7620 // conversions, since that is the only way that initialization of
7621 // a reference to a non-class type can occur from something that
7622 // is not of the same type.
7623 if (ArgIdx < NumContextualBoolArguments) {
7624 assert(ParamTys[ArgIdx] == Context.BoolTy &&
7625 "Contextual conversion to bool requires bool type");
7626 Candidate.Conversions[ArgIdx]
7627 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7629 Candidate.Conversions[ArgIdx]
7630 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7631 ArgIdx == 0 && IsAssignmentOperator,
7632 /*InOverloadResolution=*/false,
7633 /*AllowObjCWritebackConversion=*/
7634 getLangOpts().ObjCAutoRefCount);
7636 if (Candidate.Conversions[ArgIdx].isBad()) {
7637 Candidate.Viable = false;
7638 Candidate.FailureKind = ovl_fail_bad_conversion;
7646 /// BuiltinCandidateTypeSet - A set of types that will be used for the
7647 /// candidate operator functions for built-in operators (C++
7648 /// [over.built]). The types are separated into pointer types and
7649 /// enumeration types.
7650 class BuiltinCandidateTypeSet {
7651 /// TypeSet - A set of types.
7652 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7653 llvm::SmallPtrSet<QualType, 8>> TypeSet;
7655 /// PointerTypes - The set of pointer types that will be used in the
7656 /// built-in candidates.
7657 TypeSet PointerTypes;
7659 /// MemberPointerTypes - The set of member pointer types that will be
7660 /// used in the built-in candidates.
7661 TypeSet MemberPointerTypes;
7663 /// EnumerationTypes - The set of enumeration types that will be
7664 /// used in the built-in candidates.
7665 TypeSet EnumerationTypes;
7667 /// The set of vector types that will be used in the built-in
7669 TypeSet VectorTypes;
7671 /// A flag indicating non-record types are viable candidates
7672 bool HasNonRecordTypes;
7674 /// A flag indicating whether either arithmetic or enumeration types
7675 /// were present in the candidate set.
7676 bool HasArithmeticOrEnumeralTypes;
7678 /// A flag indicating whether the nullptr type was present in the
7680 bool HasNullPtrType;
7682 /// Sema - The semantic analysis instance where we are building the
7683 /// candidate type set.
7686 /// Context - The AST context in which we will build the type sets.
7687 ASTContext &Context;
7689 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7690 const Qualifiers &VisibleQuals);
7691 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7694 /// iterator - Iterates through the types that are part of the set.
7695 typedef TypeSet::iterator iterator;
7697 BuiltinCandidateTypeSet(Sema &SemaRef)
7698 : HasNonRecordTypes(false),
7699 HasArithmeticOrEnumeralTypes(false),
7700 HasNullPtrType(false),
7702 Context(SemaRef.Context) { }
7704 void AddTypesConvertedFrom(QualType Ty,
7706 bool AllowUserConversions,
7707 bool AllowExplicitConversions,
7708 const Qualifiers &VisibleTypeConversionsQuals);
7710 /// pointer_begin - First pointer type found;
7711 iterator pointer_begin() { return PointerTypes.begin(); }
7713 /// pointer_end - Past the last pointer type found;
7714 iterator pointer_end() { return PointerTypes.end(); }
7716 /// member_pointer_begin - First member pointer type found;
7717 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7719 /// member_pointer_end - Past the last member pointer type found;
7720 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7722 /// enumeration_begin - First enumeration type found;
7723 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7725 /// enumeration_end - Past the last enumeration type found;
7726 iterator enumeration_end() { return EnumerationTypes.end(); }
7728 iterator vector_begin() { return VectorTypes.begin(); }
7729 iterator vector_end() { return VectorTypes.end(); }
7731 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7732 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7733 bool hasNullPtrType() const { return HasNullPtrType; }
7736 } // end anonymous namespace
7738 /// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7739 /// the set of pointer types along with any more-qualified variants of
7740 /// that type. For example, if @p Ty is "int const *", this routine
7741 /// will add "int const *", "int const volatile *", "int const
7742 /// restrict *", and "int const volatile restrict *" to the set of
7743 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7744 /// false otherwise.
7746 /// FIXME: what to do about extended qualifiers?
7748 BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7749 const Qualifiers &VisibleQuals) {
7751 // Insert this type.
7752 if (!PointerTypes.insert(Ty))
7756 const PointerType *PointerTy = Ty->getAs<PointerType>();
7757 bool buildObjCPtr = false;
7759 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7760 PointeeTy = PTy->getPointeeType();
7761 buildObjCPtr = true;
7763 PointeeTy = PointerTy->getPointeeType();
7766 // Don't add qualified variants of arrays. For one, they're not allowed
7767 // (the qualifier would sink to the element type), and for another, the
7768 // only overload situation where it matters is subscript or pointer +- int,
7769 // and those shouldn't have qualifier variants anyway.
7770 if (PointeeTy->isArrayType())
7773 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7774 bool hasVolatile = VisibleQuals.hasVolatile();
7775 bool hasRestrict = VisibleQuals.hasRestrict();
7777 // Iterate through all strict supersets of BaseCVR.
7778 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7779 if ((CVR | BaseCVR) != CVR) continue;
7780 // Skip over volatile if no volatile found anywhere in the types.
7781 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7783 // Skip over restrict if no restrict found anywhere in the types, or if
7784 // the type cannot be restrict-qualified.
7785 if ((CVR & Qualifiers::Restrict) &&
7787 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7790 // Build qualified pointee type.
7791 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7793 // Build qualified pointer type.
7794 QualType QPointerTy;
7796 QPointerTy = Context.getPointerType(QPointeeTy);
7798 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7800 // Insert qualified pointer type.
7801 PointerTypes.insert(QPointerTy);
7807 /// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7808 /// to the set of pointer types along with any more-qualified variants of
7809 /// that type. For example, if @p Ty is "int const *", this routine
7810 /// will add "int const *", "int const volatile *", "int const
7811 /// restrict *", and "int const volatile restrict *" to the set of
7812 /// pointer types. Returns true if the add of @p Ty itself succeeded,
7813 /// false otherwise.
7815 /// FIXME: what to do about extended qualifiers?
7817 BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7819 // Insert this type.
7820 if (!MemberPointerTypes.insert(Ty))
7823 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7824 assert(PointerTy && "type was not a member pointer type!");
7826 QualType PointeeTy = PointerTy->getPointeeType();
7827 // Don't add qualified variants of arrays. For one, they're not allowed
7828 // (the qualifier would sink to the element type), and for another, the
7829 // only overload situation where it matters is subscript or pointer +- int,
7830 // and those shouldn't have qualifier variants anyway.
7831 if (PointeeTy->isArrayType())
7833 const Type *ClassTy = PointerTy->getClass();
7835 // Iterate through all strict supersets of the pointee type's CVR
7837 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7838 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7839 if ((CVR | BaseCVR) != CVR) continue;
7841 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7842 MemberPointerTypes.insert(
7843 Context.getMemberPointerType(QPointeeTy, ClassTy));
7849 /// AddTypesConvertedFrom - Add each of the types to which the type @p
7850 /// Ty can be implicit converted to the given set of @p Types. We're
7851 /// primarily interested in pointer types and enumeration types. We also
7852 /// take member pointer types, for the conditional operator.
7853 /// AllowUserConversions is true if we should look at the conversion
7854 /// functions of a class type, and AllowExplicitConversions if we
7855 /// should also include the explicit conversion functions of a class
7858 BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7860 bool AllowUserConversions,
7861 bool AllowExplicitConversions,
7862 const Qualifiers &VisibleQuals) {
7863 // Only deal with canonical types.
7864 Ty = Context.getCanonicalType(Ty);
7866 // Look through reference types; they aren't part of the type of an
7867 // expression for the purposes of conversions.
7868 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7869 Ty = RefTy->getPointeeType();
7871 // If we're dealing with an array type, decay to the pointer.
7872 if (Ty->isArrayType())
7873 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7875 // Otherwise, we don't care about qualifiers on the type.
7876 Ty = Ty.getLocalUnqualifiedType();
7878 // Flag if we ever add a non-record type.
7879 const RecordType *TyRec = Ty->getAs<RecordType>();
7880 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7882 // Flag if we encounter an arithmetic type.
7883 HasArithmeticOrEnumeralTypes =
7884 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7886 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7887 PointerTypes.insert(Ty);
7888 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7889 // Insert our type, and its more-qualified variants, into the set
7891 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7893 } else if (Ty->isMemberPointerType()) {
7894 // Member pointers are far easier, since the pointee can't be converted.
7895 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7897 } else if (Ty->isEnumeralType()) {
7898 HasArithmeticOrEnumeralTypes = true;
7899 EnumerationTypes.insert(Ty);
7900 } else if (Ty->isVectorType()) {
7901 // We treat vector types as arithmetic types in many contexts as an
7903 HasArithmeticOrEnumeralTypes = true;
7904 VectorTypes.insert(Ty);
7905 } else if (Ty->isNullPtrType()) {
7906 HasNullPtrType = true;
7907 } else if (AllowUserConversions && TyRec) {
7908 // No conversion functions in incomplete types.
7909 if (!SemaRef.isCompleteType(Loc, Ty))
7912 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7913 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7914 if (isa<UsingShadowDecl>(D))
7915 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7917 // Skip conversion function templates; they don't tell us anything
7918 // about which builtin types we can convert to.
7919 if (isa<FunctionTemplateDecl>(D))
7922 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7923 if (AllowExplicitConversions || !Conv->isExplicit()) {
7924 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7930 /// Helper function for adjusting address spaces for the pointer or reference
7931 /// operands of builtin operators depending on the argument.
7932 static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
7934 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
7937 /// Helper function for AddBuiltinOperatorCandidates() that adds
7938 /// the volatile- and non-volatile-qualified assignment operators for the
7939 /// given type to the candidate set.
7940 static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7942 ArrayRef<Expr *> Args,
7943 OverloadCandidateSet &CandidateSet) {
7944 QualType ParamTypes[2];
7946 // T& operator=(T&, T)
7947 ParamTypes[0] = S.Context.getLValueReferenceType(
7948 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
7950 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7951 /*IsAssignmentOperator=*/true);
7953 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7954 // volatile T& operator=(volatile T&, T)
7955 ParamTypes[0] = S.Context.getLValueReferenceType(
7956 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
7959 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7960 /*IsAssignmentOperator=*/true);
7964 /// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7965 /// if any, found in visible type conversion functions found in ArgExpr's type.
7966 static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7968 const RecordType *TyRec;
7969 if (const MemberPointerType *RHSMPType =
7970 ArgExpr->getType()->getAs<MemberPointerType>())
7971 TyRec = RHSMPType->getClass()->getAs<RecordType>();
7973 TyRec = ArgExpr->getType()->getAs<RecordType>();
7975 // Just to be safe, assume the worst case.
7976 VRQuals.addVolatile();
7977 VRQuals.addRestrict();
7981 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7982 if (!ClassDecl->hasDefinition())
7985 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7986 if (isa<UsingShadowDecl>(D))
7987 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7988 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7989 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7990 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7991 CanTy = ResTypeRef->getPointeeType();
7992 // Need to go down the pointer/mempointer chain and add qualifiers
7996 if (CanTy.isRestrictQualified())
7997 VRQuals.addRestrict();
7998 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7999 CanTy = ResTypePtr->getPointeeType();
8000 else if (const MemberPointerType *ResTypeMPtr =
8001 CanTy->getAs<MemberPointerType>())
8002 CanTy = ResTypeMPtr->getPointeeType();
8005 if (CanTy.isVolatileQualified())
8006 VRQuals.addVolatile();
8007 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
8017 /// Helper class to manage the addition of builtin operator overload
8018 /// candidates. It provides shared state and utility methods used throughout
8019 /// the process, as well as a helper method to add each group of builtin
8020 /// operator overloads from the standard to a candidate set.
8021 class BuiltinOperatorOverloadBuilder {
8022 // Common instance state available to all overload candidate addition methods.
8024 ArrayRef<Expr *> Args;
8025 Qualifiers VisibleTypeConversionsQuals;
8026 bool HasArithmeticOrEnumeralCandidateType;
8027 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
8028 OverloadCandidateSet &CandidateSet;
8030 static constexpr int ArithmeticTypesCap = 24;
8031 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
8033 // Define some indices used to iterate over the arithmetic types in
8034 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
8035 // types are that preserved by promotion (C++ [over.built]p2).
8036 unsigned FirstIntegralType,
8038 unsigned FirstPromotedIntegralType,
8039 LastPromotedIntegralType;
8040 unsigned FirstPromotedArithmeticType,
8041 LastPromotedArithmeticType;
8042 unsigned NumArithmeticTypes;
8044 void InitArithmeticTypes() {
8045 // Start of promoted types.
8046 FirstPromotedArithmeticType = 0;
8047 ArithmeticTypes.push_back(S.Context.FloatTy);
8048 ArithmeticTypes.push_back(S.Context.DoubleTy);
8049 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
8050 if (S.Context.getTargetInfo().hasFloat128Type())
8051 ArithmeticTypes.push_back(S.Context.Float128Ty);
8053 // Start of integral types.
8054 FirstIntegralType = ArithmeticTypes.size();
8055 FirstPromotedIntegralType = ArithmeticTypes.size();
8056 ArithmeticTypes.push_back(S.Context.IntTy);
8057 ArithmeticTypes.push_back(S.Context.LongTy);
8058 ArithmeticTypes.push_back(S.Context.LongLongTy);
8059 if (S.Context.getTargetInfo().hasInt128Type())
8060 ArithmeticTypes.push_back(S.Context.Int128Ty);
8061 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
8062 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
8063 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
8064 if (S.Context.getTargetInfo().hasInt128Type())
8065 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
8066 LastPromotedIntegralType = ArithmeticTypes.size();
8067 LastPromotedArithmeticType = ArithmeticTypes.size();
8068 // End of promoted types.
8070 ArithmeticTypes.push_back(S.Context.BoolTy);
8071 ArithmeticTypes.push_back(S.Context.CharTy);
8072 ArithmeticTypes.push_back(S.Context.WCharTy);
8073 if (S.Context.getLangOpts().Char8)
8074 ArithmeticTypes.push_back(S.Context.Char8Ty);
8075 ArithmeticTypes.push_back(S.Context.Char16Ty);
8076 ArithmeticTypes.push_back(S.Context.Char32Ty);
8077 ArithmeticTypes.push_back(S.Context.SignedCharTy);
8078 ArithmeticTypes.push_back(S.Context.ShortTy);
8079 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
8080 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
8081 LastIntegralType = ArithmeticTypes.size();
8082 NumArithmeticTypes = ArithmeticTypes.size();
8083 // End of integral types.
8084 // FIXME: What about complex? What about half?
8086 assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
8087 "Enough inline storage for all arithmetic types.");
8090 /// Helper method to factor out the common pattern of adding overloads
8091 /// for '++' and '--' builtin operators.
8092 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
8095 QualType ParamTypes[2] = {
8096 S.Context.getLValueReferenceType(CandidateTy),
8100 // Non-volatile version.
8101 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8103 // Use a heuristic to reduce number of builtin candidates in the set:
8104 // add volatile version only if there are conversions to a volatile type.
8107 S.Context.getLValueReferenceType(
8108 S.Context.getVolatileType(CandidateTy));
8109 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8112 // Add restrict version only if there are conversions to a restrict type
8113 // and our candidate type is a non-restrict-qualified pointer.
8114 if (HasRestrict && CandidateTy->isAnyPointerType() &&
8115 !CandidateTy.isRestrictQualified()) {
8117 = S.Context.getLValueReferenceType(
8118 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
8119 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8123 = S.Context.getLValueReferenceType(
8124 S.Context.getCVRQualifiedType(CandidateTy,
8125 (Qualifiers::Volatile |
8126 Qualifiers::Restrict)));
8127 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8134 BuiltinOperatorOverloadBuilder(
8135 Sema &S, ArrayRef<Expr *> Args,
8136 Qualifiers VisibleTypeConversionsQuals,
8137 bool HasArithmeticOrEnumeralCandidateType,
8138 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
8139 OverloadCandidateSet &CandidateSet)
8141 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
8142 HasArithmeticOrEnumeralCandidateType(
8143 HasArithmeticOrEnumeralCandidateType),
8144 CandidateTypes(CandidateTypes),
8145 CandidateSet(CandidateSet) {
8147 InitArithmeticTypes();
8150 // Increment is deprecated for bool since C++17.
8152 // C++ [over.built]p3:
8154 // For every pair (T, VQ), where T is an arithmetic type other
8155 // than bool, and VQ is either volatile or empty, there exist
8156 // candidate operator functions of the form
8158 // VQ T& operator++(VQ T&);
8159 // T operator++(VQ T&, int);
8161 // C++ [over.built]p4:
8163 // For every pair (T, VQ), where T is an arithmetic type other
8164 // than bool, and VQ is either volatile or empty, there exist
8165 // candidate operator functions of the form
8167 // VQ T& operator--(VQ T&);
8168 // T operator--(VQ T&, int);
8169 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
8170 if (!HasArithmeticOrEnumeralCandidateType)
8173 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
8174 const auto TypeOfT = ArithmeticTypes[Arith];
8175 if (TypeOfT == S.Context.BoolTy) {
8176 if (Op == OO_MinusMinus)
8178 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
8181 addPlusPlusMinusMinusStyleOverloads(
8183 VisibleTypeConversionsQuals.hasVolatile(),
8184 VisibleTypeConversionsQuals.hasRestrict());
8188 // C++ [over.built]p5:
8190 // For every pair (T, VQ), where T is a cv-qualified or
8191 // cv-unqualified object type, and VQ is either volatile or
8192 // empty, there exist candidate operator functions of the form
8194 // T*VQ& operator++(T*VQ&);
8195 // T*VQ& operator--(T*VQ&);
8196 // T* operator++(T*VQ&, int);
8197 // T* operator--(T*VQ&, int);
8198 void addPlusPlusMinusMinusPointerOverloads() {
8199 for (BuiltinCandidateTypeSet::iterator
8200 Ptr = CandidateTypes[0].pointer_begin(),
8201 PtrEnd = CandidateTypes[0].pointer_end();
8202 Ptr != PtrEnd; ++Ptr) {
8203 // Skip pointer types that aren't pointers to object types.
8204 if (!(*Ptr)->getPointeeType()->isObjectType())
8207 addPlusPlusMinusMinusStyleOverloads(*Ptr,
8208 (!(*Ptr).isVolatileQualified() &&
8209 VisibleTypeConversionsQuals.hasVolatile()),
8210 (!(*Ptr).isRestrictQualified() &&
8211 VisibleTypeConversionsQuals.hasRestrict()));
8215 // C++ [over.built]p6:
8216 // For every cv-qualified or cv-unqualified object type T, there
8217 // exist candidate operator functions of the form
8219 // T& operator*(T*);
8221 // C++ [over.built]p7:
8222 // For every function type T that does not have cv-qualifiers or a
8223 // ref-qualifier, there exist candidate operator functions of the form
8224 // T& operator*(T*);
8225 void addUnaryStarPointerOverloads() {
8226 for (BuiltinCandidateTypeSet::iterator
8227 Ptr = CandidateTypes[0].pointer_begin(),
8228 PtrEnd = CandidateTypes[0].pointer_end();
8229 Ptr != PtrEnd; ++Ptr) {
8230 QualType ParamTy = *Ptr;
8231 QualType PointeeTy = ParamTy->getPointeeType();
8232 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
8235 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
8236 if (Proto->getMethodQuals() || Proto->getRefQualifier())
8239 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8243 // C++ [over.built]p9:
8244 // For every promoted arithmetic type T, there exist candidate
8245 // operator functions of the form
8249 void addUnaryPlusOrMinusArithmeticOverloads() {
8250 if (!HasArithmeticOrEnumeralCandidateType)
8253 for (unsigned Arith = FirstPromotedArithmeticType;
8254 Arith < LastPromotedArithmeticType; ++Arith) {
8255 QualType ArithTy = ArithmeticTypes[Arith];
8256 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8259 // Extension: We also add these operators for vector types.
8260 for (BuiltinCandidateTypeSet::iterator
8261 Vec = CandidateTypes[0].vector_begin(),
8262 VecEnd = CandidateTypes[0].vector_end();
8263 Vec != VecEnd; ++Vec) {
8264 QualType VecTy = *Vec;
8265 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8269 // C++ [over.built]p8:
8270 // For every type T, there exist candidate operator functions of
8273 // T* operator+(T*);
8274 void addUnaryPlusPointerOverloads() {
8275 for (BuiltinCandidateTypeSet::iterator
8276 Ptr = CandidateTypes[0].pointer_begin(),
8277 PtrEnd = CandidateTypes[0].pointer_end();
8278 Ptr != PtrEnd; ++Ptr) {
8279 QualType ParamTy = *Ptr;
8280 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8284 // C++ [over.built]p10:
8285 // For every promoted integral type T, there exist candidate
8286 // operator functions of the form
8289 void addUnaryTildePromotedIntegralOverloads() {
8290 if (!HasArithmeticOrEnumeralCandidateType)
8293 for (unsigned Int = FirstPromotedIntegralType;
8294 Int < LastPromotedIntegralType; ++Int) {
8295 QualType IntTy = ArithmeticTypes[Int];
8296 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8299 // Extension: We also add this operator for vector types.
8300 for (BuiltinCandidateTypeSet::iterator
8301 Vec = CandidateTypes[0].vector_begin(),
8302 VecEnd = CandidateTypes[0].vector_end();
8303 Vec != VecEnd; ++Vec) {
8304 QualType VecTy = *Vec;
8305 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8309 // C++ [over.match.oper]p16:
8310 // For every pointer to member type T or type std::nullptr_t, there
8311 // exist candidate operator functions of the form
8313 // bool operator==(T,T);
8314 // bool operator!=(T,T);
8315 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8316 /// Set of (canonical) types that we've already handled.
8317 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8319 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8320 for (BuiltinCandidateTypeSet::iterator
8321 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8322 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8323 MemPtr != MemPtrEnd;
8325 // Don't add the same builtin candidate twice.
8326 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8329 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8330 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8333 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8334 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8335 if (AddedTypes.insert(NullPtrTy).second) {
8336 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8337 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8343 // C++ [over.built]p15:
8345 // For every T, where T is an enumeration type or a pointer type,
8346 // there exist candidate operator functions of the form
8348 // bool operator<(T, T);
8349 // bool operator>(T, T);
8350 // bool operator<=(T, T);
8351 // bool operator>=(T, T);
8352 // bool operator==(T, T);
8353 // bool operator!=(T, T);
8354 // R operator<=>(T, T)
8355 void addGenericBinaryPointerOrEnumeralOverloads() {
8356 // C++ [over.match.oper]p3:
8357 // [...]the built-in candidates include all of the candidate operator
8358 // functions defined in 13.6 that, compared to the given operator, [...]
8359 // do not have the same parameter-type-list as any non-template non-member
8362 // Note that in practice, this only affects enumeration types because there
8363 // aren't any built-in candidates of record type, and a user-defined operator
8364 // must have an operand of record or enumeration type. Also, the only other
8365 // overloaded operator with enumeration arguments, operator=,
8366 // cannot be overloaded for enumeration types, so this is the only place
8367 // where we must suppress candidates like this.
8368 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8369 UserDefinedBinaryOperators;
8371 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8372 if (CandidateTypes[ArgIdx].enumeration_begin() !=
8373 CandidateTypes[ArgIdx].enumeration_end()) {
8374 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8375 CEnd = CandidateSet.end();
8377 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8380 if (C->Function->isFunctionTemplateSpecialization())
8383 // We interpret "same parameter-type-list" as applying to the
8384 // "synthesized candidate, with the order of the two parameters
8385 // reversed", not to the original function.
8386 bool Reversed = C->RewriteKind & CRK_Reversed;
8387 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
8389 .getUnqualifiedType();
8390 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
8392 .getUnqualifiedType();
8394 // Skip if either parameter isn't of enumeral type.
8395 if (!FirstParamType->isEnumeralType() ||
8396 !SecondParamType->isEnumeralType())
8399 // Add this operator to the set of known user-defined operators.
8400 UserDefinedBinaryOperators.insert(
8401 std::make_pair(S.Context.getCanonicalType(FirstParamType),
8402 S.Context.getCanonicalType(SecondParamType)));
8407 /// Set of (canonical) types that we've already handled.
8408 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8410 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8411 for (BuiltinCandidateTypeSet::iterator
8412 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8413 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8414 Ptr != PtrEnd; ++Ptr) {
8415 // Don't add the same builtin candidate twice.
8416 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8419 QualType ParamTypes[2] = { *Ptr, *Ptr };
8420 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8422 for (BuiltinCandidateTypeSet::iterator
8423 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8424 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8425 Enum != EnumEnd; ++Enum) {
8426 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8428 // Don't add the same builtin candidate twice, or if a user defined
8429 // candidate exists.
8430 if (!AddedTypes.insert(CanonType).second ||
8431 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8434 QualType ParamTypes[2] = { *Enum, *Enum };
8435 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8440 // C++ [over.built]p13:
8442 // For every cv-qualified or cv-unqualified object type T
8443 // there exist candidate operator functions of the form
8445 // T* operator+(T*, ptrdiff_t);
8446 // T& operator[](T*, ptrdiff_t); [BELOW]
8447 // T* operator-(T*, ptrdiff_t);
8448 // T* operator+(ptrdiff_t, T*);
8449 // T& operator[](ptrdiff_t, T*); [BELOW]
8451 // C++ [over.built]p14:
8453 // For every T, where T is a pointer to object type, there
8454 // exist candidate operator functions of the form
8456 // ptrdiff_t operator-(T, T);
8457 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8458 /// Set of (canonical) types that we've already handled.
8459 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8461 for (int Arg = 0; Arg < 2; ++Arg) {
8462 QualType AsymmetricParamTypes[2] = {
8463 S.Context.getPointerDiffType(),
8464 S.Context.getPointerDiffType(),
8466 for (BuiltinCandidateTypeSet::iterator
8467 Ptr = CandidateTypes[Arg].pointer_begin(),
8468 PtrEnd = CandidateTypes[Arg].pointer_end();
8469 Ptr != PtrEnd; ++Ptr) {
8470 QualType PointeeTy = (*Ptr)->getPointeeType();
8471 if (!PointeeTy->isObjectType())
8474 AsymmetricParamTypes[Arg] = *Ptr;
8475 if (Arg == 0 || Op == OO_Plus) {
8476 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8477 // T* operator+(ptrdiff_t, T*);
8478 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8480 if (Op == OO_Minus) {
8481 // ptrdiff_t operator-(T, T);
8482 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8485 QualType ParamTypes[2] = { *Ptr, *Ptr };
8486 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8492 // C++ [over.built]p12:
8494 // For every pair of promoted arithmetic types L and R, there
8495 // exist candidate operator functions of the form
8497 // LR operator*(L, R);
8498 // LR operator/(L, R);
8499 // LR operator+(L, R);
8500 // LR operator-(L, R);
8501 // bool operator<(L, R);
8502 // bool operator>(L, R);
8503 // bool operator<=(L, R);
8504 // bool operator>=(L, R);
8505 // bool operator==(L, R);
8506 // bool operator!=(L, R);
8508 // where LR is the result of the usual arithmetic conversions
8509 // between types L and R.
8511 // C++ [over.built]p24:
8513 // For every pair of promoted arithmetic types L and R, there exist
8514 // candidate operator functions of the form
8516 // LR operator?(bool, L, R);
8518 // where LR is the result of the usual arithmetic conversions
8519 // between types L and R.
8520 // Our candidates ignore the first parameter.
8521 void addGenericBinaryArithmeticOverloads() {
8522 if (!HasArithmeticOrEnumeralCandidateType)
8525 for (unsigned Left = FirstPromotedArithmeticType;
8526 Left < LastPromotedArithmeticType; ++Left) {
8527 for (unsigned Right = FirstPromotedArithmeticType;
8528 Right < LastPromotedArithmeticType; ++Right) {
8529 QualType LandR[2] = { ArithmeticTypes[Left],
8530 ArithmeticTypes[Right] };
8531 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8535 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8536 // conditional operator for vector types.
8537 for (BuiltinCandidateTypeSet::iterator
8538 Vec1 = CandidateTypes[0].vector_begin(),
8539 Vec1End = CandidateTypes[0].vector_end();
8540 Vec1 != Vec1End; ++Vec1) {
8541 for (BuiltinCandidateTypeSet::iterator
8542 Vec2 = CandidateTypes[1].vector_begin(),
8543 Vec2End = CandidateTypes[1].vector_end();
8544 Vec2 != Vec2End; ++Vec2) {
8545 QualType LandR[2] = { *Vec1, *Vec2 };
8546 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8551 // C++2a [over.built]p14:
8553 // For every integral type T there exists a candidate operator function
8556 // std::strong_ordering operator<=>(T, T)
8558 // C++2a [over.built]p15:
8560 // For every pair of floating-point types L and R, there exists a candidate
8561 // operator function of the form
8563 // std::partial_ordering operator<=>(L, R);
8565 // FIXME: The current specification for integral types doesn't play nice with
8566 // the direction of p0946r0, which allows mixed integral and unscoped-enum
8567 // comparisons. Under the current spec this can lead to ambiguity during
8568 // overload resolution. For example:
8570 // enum A : int {a};
8571 // auto x = (a <=> (long)42);
8573 // error: call is ambiguous for arguments 'A' and 'long'.
8574 // note: candidate operator<=>(int, int)
8575 // note: candidate operator<=>(long, long)
8577 // To avoid this error, this function deviates from the specification and adds
8578 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8579 // arithmetic types (the same as the generic relational overloads).
8581 // For now this function acts as a placeholder.
8582 void addThreeWayArithmeticOverloads() {
8583 addGenericBinaryArithmeticOverloads();
8586 // C++ [over.built]p17:
8588 // For every pair of promoted integral types L and R, there
8589 // exist candidate operator functions of the form
8591 // LR operator%(L, R);
8592 // LR operator&(L, R);
8593 // LR operator^(L, R);
8594 // LR operator|(L, R);
8595 // L operator<<(L, R);
8596 // L operator>>(L, R);
8598 // where LR is the result of the usual arithmetic conversions
8599 // between types L and R.
8600 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8601 if (!HasArithmeticOrEnumeralCandidateType)
8604 for (unsigned Left = FirstPromotedIntegralType;
8605 Left < LastPromotedIntegralType; ++Left) {
8606 for (unsigned Right = FirstPromotedIntegralType;
8607 Right < LastPromotedIntegralType; ++Right) {
8608 QualType LandR[2] = { ArithmeticTypes[Left],
8609 ArithmeticTypes[Right] };
8610 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8615 // C++ [over.built]p20:
8617 // For every pair (T, VQ), where T is an enumeration or
8618 // pointer to member type and VQ is either volatile or
8619 // empty, there exist candidate operator functions of the form
8621 // VQ T& operator=(VQ T&, T);
8622 void addAssignmentMemberPointerOrEnumeralOverloads() {
8623 /// Set of (canonical) types that we've already handled.
8624 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8626 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8627 for (BuiltinCandidateTypeSet::iterator
8628 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8629 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8630 Enum != EnumEnd; ++Enum) {
8631 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8634 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8637 for (BuiltinCandidateTypeSet::iterator
8638 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8639 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8640 MemPtr != MemPtrEnd; ++MemPtr) {
8641 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8644 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8649 // C++ [over.built]p19:
8651 // For every pair (T, VQ), where T is any type and VQ is either
8652 // volatile or empty, there exist candidate operator functions
8655 // T*VQ& operator=(T*VQ&, T*);
8657 // C++ [over.built]p21:
8659 // For every pair (T, VQ), where T is a cv-qualified or
8660 // cv-unqualified object type and VQ is either volatile or
8661 // empty, there exist candidate operator functions of the form
8663 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8664 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8665 void addAssignmentPointerOverloads(bool isEqualOp) {
8666 /// Set of (canonical) types that we've already handled.
8667 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8669 for (BuiltinCandidateTypeSet::iterator
8670 Ptr = CandidateTypes[0].pointer_begin(),
8671 PtrEnd = CandidateTypes[0].pointer_end();
8672 Ptr != PtrEnd; ++Ptr) {
8673 // If this is operator=, keep track of the builtin candidates we added.
8675 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8676 else if (!(*Ptr)->getPointeeType()->isObjectType())
8679 // non-volatile version
8680 QualType ParamTypes[2] = {
8681 S.Context.getLValueReferenceType(*Ptr),
8682 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8684 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8685 /*IsAssignmentOperator=*/ isEqualOp);
8687 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8688 VisibleTypeConversionsQuals.hasVolatile();
8692 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8693 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8694 /*IsAssignmentOperator=*/isEqualOp);
8697 if (!(*Ptr).isRestrictQualified() &&
8698 VisibleTypeConversionsQuals.hasRestrict()) {
8701 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8702 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8703 /*IsAssignmentOperator=*/isEqualOp);
8706 // volatile restrict version
8708 = S.Context.getLValueReferenceType(
8709 S.Context.getCVRQualifiedType(*Ptr,
8710 (Qualifiers::Volatile |
8711 Qualifiers::Restrict)));
8712 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8713 /*IsAssignmentOperator=*/isEqualOp);
8719 for (BuiltinCandidateTypeSet::iterator
8720 Ptr = CandidateTypes[1].pointer_begin(),
8721 PtrEnd = CandidateTypes[1].pointer_end();
8722 Ptr != PtrEnd; ++Ptr) {
8723 // Make sure we don't add the same candidate twice.
8724 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8727 QualType ParamTypes[2] = {
8728 S.Context.getLValueReferenceType(*Ptr),
8732 // non-volatile version
8733 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8734 /*IsAssignmentOperator=*/true);
8736 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8737 VisibleTypeConversionsQuals.hasVolatile();
8741 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8742 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8743 /*IsAssignmentOperator=*/true);
8746 if (!(*Ptr).isRestrictQualified() &&
8747 VisibleTypeConversionsQuals.hasRestrict()) {
8750 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8751 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8752 /*IsAssignmentOperator=*/true);
8755 // volatile restrict version
8757 = S.Context.getLValueReferenceType(
8758 S.Context.getCVRQualifiedType(*Ptr,
8759 (Qualifiers::Volatile |
8760 Qualifiers::Restrict)));
8761 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8762 /*IsAssignmentOperator=*/true);
8769 // C++ [over.built]p18:
8771 // For every triple (L, VQ, R), where L is an arithmetic type,
8772 // VQ is either volatile or empty, and R is a promoted
8773 // arithmetic type, there exist candidate operator functions of
8776 // VQ L& operator=(VQ L&, R);
8777 // VQ L& operator*=(VQ L&, R);
8778 // VQ L& operator/=(VQ L&, R);
8779 // VQ L& operator+=(VQ L&, R);
8780 // VQ L& operator-=(VQ L&, R);
8781 void addAssignmentArithmeticOverloads(bool isEqualOp) {
8782 if (!HasArithmeticOrEnumeralCandidateType)
8785 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8786 for (unsigned Right = FirstPromotedArithmeticType;
8787 Right < LastPromotedArithmeticType; ++Right) {
8788 QualType ParamTypes[2];
8789 ParamTypes[1] = ArithmeticTypes[Right];
8790 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8791 S, ArithmeticTypes[Left], Args[0]);
8792 // Add this built-in operator as a candidate (VQ is empty).
8793 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8794 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8795 /*IsAssignmentOperator=*/isEqualOp);
8797 // Add this built-in operator as a candidate (VQ is 'volatile').
8798 if (VisibleTypeConversionsQuals.hasVolatile()) {
8799 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8800 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8801 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8802 /*IsAssignmentOperator=*/isEqualOp);
8807 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8808 for (BuiltinCandidateTypeSet::iterator
8809 Vec1 = CandidateTypes[0].vector_begin(),
8810 Vec1End = CandidateTypes[0].vector_end();
8811 Vec1 != Vec1End; ++Vec1) {
8812 for (BuiltinCandidateTypeSet::iterator
8813 Vec2 = CandidateTypes[1].vector_begin(),
8814 Vec2End = CandidateTypes[1].vector_end();
8815 Vec2 != Vec2End; ++Vec2) {
8816 QualType ParamTypes[2];
8817 ParamTypes[1] = *Vec2;
8818 // Add this built-in operator as a candidate (VQ is empty).
8819 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8820 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8821 /*IsAssignmentOperator=*/isEqualOp);
8823 // Add this built-in operator as a candidate (VQ is 'volatile').
8824 if (VisibleTypeConversionsQuals.hasVolatile()) {
8825 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8826 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8827 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8828 /*IsAssignmentOperator=*/isEqualOp);
8834 // C++ [over.built]p22:
8836 // For every triple (L, VQ, R), where L is an integral type, VQ
8837 // is either volatile or empty, and R is a promoted integral
8838 // type, there exist candidate operator functions of the form
8840 // VQ L& operator%=(VQ L&, R);
8841 // VQ L& operator<<=(VQ L&, R);
8842 // VQ L& operator>>=(VQ L&, R);
8843 // VQ L& operator&=(VQ L&, R);
8844 // VQ L& operator^=(VQ L&, R);
8845 // VQ L& operator|=(VQ L&, R);
8846 void addAssignmentIntegralOverloads() {
8847 if (!HasArithmeticOrEnumeralCandidateType)
8850 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8851 for (unsigned Right = FirstPromotedIntegralType;
8852 Right < LastPromotedIntegralType; ++Right) {
8853 QualType ParamTypes[2];
8854 ParamTypes[1] = ArithmeticTypes[Right];
8855 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8856 S, ArithmeticTypes[Left], Args[0]);
8857 // Add this built-in operator as a candidate (VQ is empty).
8858 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8859 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8860 if (VisibleTypeConversionsQuals.hasVolatile()) {
8861 // Add this built-in operator as a candidate (VQ is 'volatile').
8862 ParamTypes[0] = LeftBaseTy;
8863 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8864 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8865 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8871 // C++ [over.operator]p23:
8873 // There also exist candidate operator functions of the form
8875 // bool operator!(bool);
8876 // bool operator&&(bool, bool);
8877 // bool operator||(bool, bool);
8878 void addExclaimOverload() {
8879 QualType ParamTy = S.Context.BoolTy;
8880 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8881 /*IsAssignmentOperator=*/false,
8882 /*NumContextualBoolArguments=*/1);
8884 void addAmpAmpOrPipePipeOverload() {
8885 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8886 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8887 /*IsAssignmentOperator=*/false,
8888 /*NumContextualBoolArguments=*/2);
8891 // C++ [over.built]p13:
8893 // For every cv-qualified or cv-unqualified object type T there
8894 // exist candidate operator functions of the form
8896 // T* operator+(T*, ptrdiff_t); [ABOVE]
8897 // T& operator[](T*, ptrdiff_t);
8898 // T* operator-(T*, ptrdiff_t); [ABOVE]
8899 // T* operator+(ptrdiff_t, T*); [ABOVE]
8900 // T& operator[](ptrdiff_t, T*);
8901 void addSubscriptOverloads() {
8902 for (BuiltinCandidateTypeSet::iterator
8903 Ptr = CandidateTypes[0].pointer_begin(),
8904 PtrEnd = CandidateTypes[0].pointer_end();
8905 Ptr != PtrEnd; ++Ptr) {
8906 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8907 QualType PointeeType = (*Ptr)->getPointeeType();
8908 if (!PointeeType->isObjectType())
8911 // T& operator[](T*, ptrdiff_t)
8912 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8915 for (BuiltinCandidateTypeSet::iterator
8916 Ptr = CandidateTypes[1].pointer_begin(),
8917 PtrEnd = CandidateTypes[1].pointer_end();
8918 Ptr != PtrEnd; ++Ptr) {
8919 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8920 QualType PointeeType = (*Ptr)->getPointeeType();
8921 if (!PointeeType->isObjectType())
8924 // T& operator[](ptrdiff_t, T*)
8925 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8929 // C++ [over.built]p11:
8930 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8931 // C1 is the same type as C2 or is a derived class of C2, T is an object
8932 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8933 // there exist candidate operator functions of the form
8935 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8937 // where CV12 is the union of CV1 and CV2.
8938 void addArrowStarOverloads() {
8939 for (BuiltinCandidateTypeSet::iterator
8940 Ptr = CandidateTypes[0].pointer_begin(),
8941 PtrEnd = CandidateTypes[0].pointer_end();
8942 Ptr != PtrEnd; ++Ptr) {
8943 QualType C1Ty = (*Ptr);
8945 QualifierCollector Q1;
8946 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8947 if (!isa<RecordType>(C1))
8949 // heuristic to reduce number of builtin candidates in the set.
8950 // Add volatile/restrict version only if there are conversions to a
8951 // volatile/restrict type.
8952 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8954 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8956 for (BuiltinCandidateTypeSet::iterator
8957 MemPtr = CandidateTypes[1].member_pointer_begin(),
8958 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8959 MemPtr != MemPtrEnd; ++MemPtr) {
8960 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8961 QualType C2 = QualType(mptr->getClass(), 0);
8962 C2 = C2.getUnqualifiedType();
8963 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8965 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8967 QualType T = mptr->getPointeeType();
8968 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8969 T.isVolatileQualified())
8971 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8972 T.isRestrictQualified())
8974 T = Q1.apply(S.Context, T);
8975 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8980 // Note that we don't consider the first argument, since it has been
8981 // contextually converted to bool long ago. The candidates below are
8982 // therefore added as binary.
8984 // C++ [over.built]p25:
8985 // For every type T, where T is a pointer, pointer-to-member, or scoped
8986 // enumeration type, there exist candidate operator functions of the form
8988 // T operator?(bool, T, T);
8990 void addConditionalOperatorOverloads() {
8991 /// Set of (canonical) types that we've already handled.
8992 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8994 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8995 for (BuiltinCandidateTypeSet::iterator
8996 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8997 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8998 Ptr != PtrEnd; ++Ptr) {
8999 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
9002 QualType ParamTypes[2] = { *Ptr, *Ptr };
9003 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9006 for (BuiltinCandidateTypeSet::iterator
9007 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
9008 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
9009 MemPtr != MemPtrEnd; ++MemPtr) {
9010 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
9013 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
9014 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9017 if (S.getLangOpts().CPlusPlus11) {
9018 for (BuiltinCandidateTypeSet::iterator
9019 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
9020 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
9021 Enum != EnumEnd; ++Enum) {
9022 if (!(*Enum)->castAs<EnumType>()->getDecl()->isScoped())
9025 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
9028 QualType ParamTypes[2] = { *Enum, *Enum };
9029 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9036 } // end anonymous namespace
9038 /// AddBuiltinOperatorCandidates - Add the appropriate built-in
9039 /// operator overloads to the candidate set (C++ [over.built]), based
9040 /// on the operator @p Op and the arguments given. For example, if the
9041 /// operator is a binary '+', this routine might add "int
9042 /// operator+(int, int)" to cover integer addition.
9043 void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
9044 SourceLocation OpLoc,
9045 ArrayRef<Expr *> Args,
9046 OverloadCandidateSet &CandidateSet) {
9047 // Find all of the types that the arguments can convert to, but only
9048 // if the operator we're looking at has built-in operator candidates
9049 // that make use of these types. Also record whether we encounter non-record
9050 // candidate types or either arithmetic or enumeral candidate types.
9051 Qualifiers VisibleTypeConversionsQuals;
9052 VisibleTypeConversionsQuals.addConst();
9053 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
9054 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
9056 bool HasNonRecordCandidateType = false;
9057 bool HasArithmeticOrEnumeralCandidateType = false;
9058 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
9059 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9060 CandidateTypes.emplace_back(*this);
9061 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
9064 (Op == OO_Exclaim ||
9067 VisibleTypeConversionsQuals);
9068 HasNonRecordCandidateType = HasNonRecordCandidateType ||
9069 CandidateTypes[ArgIdx].hasNonRecordTypes();
9070 HasArithmeticOrEnumeralCandidateType =
9071 HasArithmeticOrEnumeralCandidateType ||
9072 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
9075 // Exit early when no non-record types have been added to the candidate set
9076 // for any of the arguments to the operator.
9078 // We can't exit early for !, ||, or &&, since there we have always have
9079 // 'bool' overloads.
9080 if (!HasNonRecordCandidateType &&
9081 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
9084 // Setup an object to manage the common state for building overloads.
9085 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
9086 VisibleTypeConversionsQuals,
9087 HasArithmeticOrEnumeralCandidateType,
9088 CandidateTypes, CandidateSet);
9090 // Dispatch over the operation to add in only those overloads which apply.
9093 case NUM_OVERLOADED_OPERATORS:
9094 llvm_unreachable("Expected an overloaded operator");
9099 case OO_Array_Delete:
9102 "Special operators don't use AddBuiltinOperatorCandidates");
9107 // C++ [over.match.oper]p3:
9108 // -- For the operator ',', the unary operator '&', the
9109 // operator '->', or the operator 'co_await', the
9110 // built-in candidates set is empty.
9113 case OO_Plus: // '+' is either unary or binary
9114 if (Args.size() == 1)
9115 OpBuilder.addUnaryPlusPointerOverloads();
9118 case OO_Minus: // '-' is either unary or binary
9119 if (Args.size() == 1) {
9120 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
9122 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
9123 OpBuilder.addGenericBinaryArithmeticOverloads();
9127 case OO_Star: // '*' is either unary or binary
9128 if (Args.size() == 1)
9129 OpBuilder.addUnaryStarPointerOverloads();
9131 OpBuilder.addGenericBinaryArithmeticOverloads();
9135 OpBuilder.addGenericBinaryArithmeticOverloads();
9140 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
9141 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
9145 case OO_ExclaimEqual:
9146 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
9152 case OO_GreaterEqual:
9153 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9154 OpBuilder.addGenericBinaryArithmeticOverloads();
9158 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
9159 OpBuilder.addThreeWayArithmeticOverloads();
9166 case OO_GreaterGreater:
9167 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9170 case OO_Amp: // '&' is either unary or binary
9171 if (Args.size() == 1)
9172 // C++ [over.match.oper]p3:
9173 // -- For the operator ',', the unary operator '&', or the
9174 // operator '->', the built-in candidates set is empty.
9177 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
9181 OpBuilder.addUnaryTildePromotedIntegralOverloads();
9185 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
9190 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
9195 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
9198 case OO_PercentEqual:
9199 case OO_LessLessEqual:
9200 case OO_GreaterGreaterEqual:
9204 OpBuilder.addAssignmentIntegralOverloads();
9208 OpBuilder.addExclaimOverload();
9213 OpBuilder.addAmpAmpOrPipePipeOverload();
9217 OpBuilder.addSubscriptOverloads();
9221 OpBuilder.addArrowStarOverloads();
9224 case OO_Conditional:
9225 OpBuilder.addConditionalOperatorOverloads();
9226 OpBuilder.addGenericBinaryArithmeticOverloads();
9231 /// Add function candidates found via argument-dependent lookup
9232 /// to the set of overloading candidates.
9234 /// This routine performs argument-dependent name lookup based on the
9235 /// given function name (which may also be an operator name) and adds
9236 /// all of the overload candidates found by ADL to the overload
9237 /// candidate set (C++ [basic.lookup.argdep]).
9239 Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
9241 ArrayRef<Expr *> Args,
9242 TemplateArgumentListInfo *ExplicitTemplateArgs,
9243 OverloadCandidateSet& CandidateSet,
9244 bool PartialOverloading) {
9247 // FIXME: This approach for uniquing ADL results (and removing
9248 // redundant candidates from the set) relies on pointer-equality,
9249 // which means we need to key off the canonical decl. However,
9250 // always going back to the canonical decl might not get us the
9251 // right set of default arguments. What default arguments are
9252 // we supposed to consider on ADL candidates, anyway?
9254 // FIXME: Pass in the explicit template arguments?
9255 ArgumentDependentLookup(Name, Loc, Args, Fns);
9257 // Erase all of the candidates we already knew about.
9258 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9259 CandEnd = CandidateSet.end();
9260 Cand != CandEnd; ++Cand)
9261 if (Cand->Function) {
9262 Fns.erase(Cand->Function);
9263 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9267 // For each of the ADL candidates we found, add it to the overload
9269 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9270 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9272 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9273 if (ExplicitTemplateArgs)
9276 AddOverloadCandidate(
9277 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
9278 PartialOverloading, /*AllowExplicit=*/true,
9279 /*AllowExplicitConversions=*/false, ADLCallKind::UsesADL);
9280 if (CandidateSet.getRewriteInfo().shouldAddReversed(Context, FD)) {
9281 AddOverloadCandidate(
9282 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
9283 /*SuppressUserConversions=*/false, PartialOverloading,
9284 /*AllowExplicit=*/true, /*AllowExplicitConversions=*/false,
9285 ADLCallKind::UsesADL, None, OverloadCandidateParamOrder::Reversed);
9288 auto *FTD = cast<FunctionTemplateDecl>(*I);
9289 AddTemplateOverloadCandidate(
9290 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
9291 /*SuppressUserConversions=*/false, PartialOverloading,
9292 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
9293 if (CandidateSet.getRewriteInfo().shouldAddReversed(
9294 Context, FTD->getTemplatedDecl())) {
9295 AddTemplateOverloadCandidate(
9296 FTD, FoundDecl, ExplicitTemplateArgs, {Args[1], Args[0]},
9297 CandidateSet, /*SuppressUserConversions=*/false, PartialOverloading,
9298 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
9299 OverloadCandidateParamOrder::Reversed);
9306 enum class Comparison { Equal, Better, Worse };
9309 /// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9310 /// overload resolution.
9312 /// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9313 /// Cand1's first N enable_if attributes have precisely the same conditions as
9314 /// Cand2's first N enable_if attributes (where N = the number of enable_if
9315 /// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9317 /// Note that you can have a pair of candidates such that Cand1's enable_if
9318 /// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9319 /// worse than Cand1's.
9320 static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9321 const FunctionDecl *Cand2) {
9322 // Common case: One (or both) decls don't have enable_if attrs.
9323 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9324 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9325 if (!Cand1Attr || !Cand2Attr) {
9326 if (Cand1Attr == Cand2Attr)
9327 return Comparison::Equal;
9328 return Cand1Attr ? Comparison::Better : Comparison::Worse;
9331 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9332 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9334 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9335 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9336 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9337 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9339 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9340 // has fewer enable_if attributes than Cand2, and vice versa.
9342 return Comparison::Worse;
9344 return Comparison::Better;
9349 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9350 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9351 if (Cand1ID != Cand2ID)
9352 return Comparison::Worse;
9355 return Comparison::Equal;
9358 static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9359 const OverloadCandidate &Cand2) {
9360 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9361 !Cand2.Function->isMultiVersion())
9364 // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this
9365 // is obviously better.
9366 if (Cand1.Function->isInvalidDecl()) return false;
9367 if (Cand2.Function->isInvalidDecl()) return true;
9369 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9370 // cpu_dispatch, else arbitrarily based on the identifiers.
9371 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9372 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9373 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9374 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9376 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9379 if (Cand1CPUDisp && !Cand2CPUDisp)
9381 if (Cand2CPUDisp && !Cand1CPUDisp)
9384 if (Cand1CPUSpec && Cand2CPUSpec) {
9385 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9386 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
9388 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9389 FirstDiff = std::mismatch(
9390 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9391 Cand2CPUSpec->cpus_begin(),
9392 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9393 return LHS->getName() == RHS->getName();
9396 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9397 "Two different cpu-specific versions should not have the same "
9398 "identifier list, otherwise they'd be the same decl!");
9399 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9401 llvm_unreachable("No way to get here unless both had cpu_dispatch");
9404 /// isBetterOverloadCandidate - Determines whether the first overload
9405 /// candidate is a better candidate than the second (C++ 13.3.3p1).
9406 bool clang::isBetterOverloadCandidate(
9407 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9408 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9409 // Define viable functions to be better candidates than non-viable
9412 return Cand1.Viable;
9413 else if (!Cand1.Viable)
9416 // C++ [over.match.best]p1:
9418 // -- if F is a static member function, ICS1(F) is defined such
9419 // that ICS1(F) is neither better nor worse than ICS1(G) for
9420 // any function G, and, symmetrically, ICS1(G) is neither
9421 // better nor worse than ICS1(F).
9422 unsigned StartArg = 0;
9423 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9426 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9427 // We don't allow incompatible pointer conversions in C++.
9428 if (!S.getLangOpts().CPlusPlus)
9429 return ICS.isStandard() &&
9430 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9432 // The only ill-formed conversion we allow in C++ is the string literal to
9433 // char* conversion, which is only considered ill-formed after C++11.
9434 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9435 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9438 // Define functions that don't require ill-formed conversions for a given
9439 // argument to be better candidates than functions that do.
9440 unsigned NumArgs = Cand1.Conversions.size();
9441 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9442 bool HasBetterConversion = false;
9443 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9444 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9445 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9446 if (Cand1Bad != Cand2Bad) {
9449 HasBetterConversion = true;
9453 if (HasBetterConversion)
9456 // C++ [over.match.best]p1:
9457 // A viable function F1 is defined to be a better function than another
9458 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
9459 // conversion sequence than ICSi(F2), and then...
9460 bool HasWorseConversion = false;
9461 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9462 switch (CompareImplicitConversionSequences(S, Loc,
9463 Cand1.Conversions[ArgIdx],
9464 Cand2.Conversions[ArgIdx])) {
9465 case ImplicitConversionSequence::Better:
9466 // Cand1 has a better conversion sequence.
9467 HasBetterConversion = true;
9470 case ImplicitConversionSequence::Worse:
9471 if (Cand1.Function && Cand1.Function == Cand2.Function &&
9472 (Cand2.RewriteKind & CRK_Reversed) != 0) {
9473 // Work around large-scale breakage caused by considering reversed
9474 // forms of operator== in C++20:
9476 // When comparing a function against its reversed form, if we have a
9477 // better conversion for one argument and a worse conversion for the
9478 // other, we prefer the non-reversed form.
9480 // This prevents a conversion function from being considered ambiguous
9481 // with its own reversed form in various where it's only incidentally
9484 // We diagnose this as an extension from CreateOverloadedBinOp.
9485 HasWorseConversion = true;
9489 // Cand1 can't be better than Cand2.
9492 case ImplicitConversionSequence::Indistinguishable:
9498 // -- for some argument j, ICSj(F1) is a better conversion sequence than
9499 // ICSj(F2), or, if not that,
9500 if (HasBetterConversion)
9502 if (HasWorseConversion)
9505 // -- the context is an initialization by user-defined conversion
9506 // (see 8.5, 13.3.1.5) and the standard conversion sequence
9507 // from the return type of F1 to the destination type (i.e.,
9508 // the type of the entity being initialized) is a better
9509 // conversion sequence than the standard conversion sequence
9510 // from the return type of F2 to the destination type.
9511 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9512 Cand1.Function && Cand2.Function &&
9513 isa<CXXConversionDecl>(Cand1.Function) &&
9514 isa<CXXConversionDecl>(Cand2.Function)) {
9515 // First check whether we prefer one of the conversion functions over the
9516 // other. This only distinguishes the results in non-standard, extension
9517 // cases such as the conversion from a lambda closure type to a function
9518 // pointer or block.
9519 ImplicitConversionSequence::CompareKind Result =
9520 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9521 if (Result == ImplicitConversionSequence::Indistinguishable)
9522 Result = CompareStandardConversionSequences(S, Loc,
9523 Cand1.FinalConversion,
9524 Cand2.FinalConversion);
9526 if (Result != ImplicitConversionSequence::Indistinguishable)
9527 return Result == ImplicitConversionSequence::Better;
9529 // FIXME: Compare kind of reference binding if conversion functions
9530 // convert to a reference type used in direct reference binding, per
9531 // C++14 [over.match.best]p1 section 2 bullet 3.
9534 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9535 // as combined with the resolution to CWG issue 243.
9537 // When the context is initialization by constructor ([over.match.ctor] or
9538 // either phase of [over.match.list]), a constructor is preferred over
9539 // a conversion function.
9540 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9541 Cand1.Function && Cand2.Function &&
9542 isa<CXXConstructorDecl>(Cand1.Function) !=
9543 isa<CXXConstructorDecl>(Cand2.Function))
9544 return isa<CXXConstructorDecl>(Cand1.Function);
9546 // -- F1 is a non-template function and F2 is a function template
9547 // specialization, or, if not that,
9548 bool Cand1IsSpecialization = Cand1.Function &&
9549 Cand1.Function->getPrimaryTemplate();
9550 bool Cand2IsSpecialization = Cand2.Function &&
9551 Cand2.Function->getPrimaryTemplate();
9552 if (Cand1IsSpecialization != Cand2IsSpecialization)
9553 return Cand2IsSpecialization;
9555 // -- F1 and F2 are function template specializations, and the function
9556 // template for F1 is more specialized than the template for F2
9557 // according to the partial ordering rules described in 14.5.5.2, or,
9559 if (Cand1IsSpecialization && Cand2IsSpecialization) {
9560 if (FunctionTemplateDecl *BetterTemplate
9561 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9562 Cand2.Function->getPrimaryTemplate(),
9564 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9566 Cand1.ExplicitCallArguments,
9567 Cand2.ExplicitCallArguments))
9568 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9571 // -— F1 and F2 are non-template functions with the same
9572 // parameter-type-lists, and F1 is more constrained than F2 [...],
9573 if (Cand1.Function && Cand2.Function && !Cand1IsSpecialization &&
9574 !Cand2IsSpecialization && Cand1.Function->hasPrototype() &&
9575 Cand2.Function->hasPrototype()) {
9576 auto *PT1 = cast<FunctionProtoType>(Cand1.Function->getFunctionType());
9577 auto *PT2 = cast<FunctionProtoType>(Cand2.Function->getFunctionType());
9578 if (PT1->getNumParams() == PT2->getNumParams() &&
9579 PT1->isVariadic() == PT2->isVariadic() &&
9580 S.FunctionParamTypesAreEqual(PT1, PT2)) {
9581 Expr *RC1 = Cand1.Function->getTrailingRequiresClause();
9582 Expr *RC2 = Cand2.Function->getTrailingRequiresClause();
9584 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
9585 if (S.IsAtLeastAsConstrained(Cand1.Function, {RC1}, Cand2.Function,
9586 {RC2}, AtLeastAsConstrained1) ||
9587 S.IsAtLeastAsConstrained(Cand2.Function, {RC2}, Cand1.Function,
9588 {RC1}, AtLeastAsConstrained2))
9590 if (AtLeastAsConstrained1 != AtLeastAsConstrained2)
9591 return AtLeastAsConstrained1;
9592 } else if (RC1 || RC2) {
9593 return RC1 != nullptr;
9598 // -- F1 is a constructor for a class D, F2 is a constructor for a base
9599 // class B of D, and for all arguments the corresponding parameters of
9600 // F1 and F2 have the same type.
9601 // FIXME: Implement the "all parameters have the same type" check.
9602 bool Cand1IsInherited =
9603 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9604 bool Cand2IsInherited =
9605 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9606 if (Cand1IsInherited != Cand2IsInherited)
9607 return Cand2IsInherited;
9608 else if (Cand1IsInherited) {
9609 assert(Cand2IsInherited);
9610 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9611 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9612 if (Cand1Class->isDerivedFrom(Cand2Class))
9614 if (Cand2Class->isDerivedFrom(Cand1Class))
9616 // Inherited from sibling base classes: still ambiguous.
9619 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
9620 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
9621 // with reversed order of parameters and F1 is not
9623 // We rank reversed + different operator as worse than just reversed, but
9624 // that comparison can never happen, because we only consider reversing for
9625 // the maximally-rewritten operator (== or <=>).
9626 if (Cand1.RewriteKind != Cand2.RewriteKind)
9627 return Cand1.RewriteKind < Cand2.RewriteKind;
9629 // Check C++17 tie-breakers for deduction guides.
9631 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9632 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9633 if (Guide1 && Guide2) {
9634 // -- F1 is generated from a deduction-guide and F2 is not
9635 if (Guide1->isImplicit() != Guide2->isImplicit())
9636 return Guide2->isImplicit();
9638 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9639 if (Guide1->isCopyDeductionCandidate())
9644 // Check for enable_if value-based overload resolution.
9645 if (Cand1.Function && Cand2.Function) {
9646 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9647 if (Cmp != Comparison::Equal)
9648 return Cmp == Comparison::Better;
9651 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9652 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9653 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9654 S.IdentifyCUDAPreference(Caller, Cand2.Function);
9657 bool HasPS1 = Cand1.Function != nullptr &&
9658 functionHasPassObjectSizeParams(Cand1.Function);
9659 bool HasPS2 = Cand2.Function != nullptr &&
9660 functionHasPassObjectSizeParams(Cand2.Function);
9661 if (HasPS1 != HasPS2 && HasPS1)
9664 return isBetterMultiversionCandidate(Cand1, Cand2);
9667 /// Determine whether two declarations are "equivalent" for the purposes of
9668 /// name lookup and overload resolution. This applies when the same internal/no
9669 /// linkage entity is defined by two modules (probably by textually including
9670 /// the same header). In such a case, we don't consider the declarations to
9671 /// declare the same entity, but we also don't want lookups with both
9672 /// declarations visible to be ambiguous in some cases (this happens when using
9673 /// a modularized libstdc++).
9674 bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9675 const NamedDecl *B) {
9676 auto *VA = dyn_cast_or_null<ValueDecl>(A);
9677 auto *VB = dyn_cast_or_null<ValueDecl>(B);
9681 // The declarations must be declaring the same name as an internal linkage
9682 // entity in different modules.
9683 if (!VA->getDeclContext()->getRedeclContext()->Equals(
9684 VB->getDeclContext()->getRedeclContext()) ||
9685 getOwningModule(VA) == getOwningModule(VB) ||
9686 VA->isExternallyVisible() || VB->isExternallyVisible())
9689 // Check that the declarations appear to be equivalent.
9691 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9692 // For constants and functions, we should check the initializer or body is
9693 // the same. For non-constant variables, we shouldn't allow it at all.
9694 if (Context.hasSameType(VA->getType(), VB->getType()))
9697 // Enum constants within unnamed enumerations will have different types, but
9698 // may still be similar enough to be interchangeable for our purposes.
9699 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9700 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9701 // Only handle anonymous enums. If the enumerations were named and
9702 // equivalent, they would have been merged to the same type.
9703 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9704 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9705 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9706 !Context.hasSameType(EnumA->getIntegerType(),
9707 EnumB->getIntegerType()))
9709 // Allow this only if the value is the same for both enumerators.
9710 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9714 // Nothing else is sufficiently similar.
9718 void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9719 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9720 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9722 Module *M = getOwningModule(D);
9723 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9724 << !M << (M ? M->getFullModuleName() : "");
9726 for (auto *E : Equiv) {
9727 Module *M = getOwningModule(E);
9728 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9729 << !M << (M ? M->getFullModuleName() : "");
9733 /// Computes the best viable function (C++ 13.3.3)
9734 /// within an overload candidate set.
9736 /// \param Loc The location of the function name (or operator symbol) for
9737 /// which overload resolution occurs.
9739 /// \param Best If overload resolution was successful or found a deleted
9740 /// function, \p Best points to the candidate function found.
9742 /// \returns The result of overload resolution.
9744 OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9746 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9747 std::transform(begin(), end(), std::back_inserter(Candidates),
9748 [](OverloadCandidate &Cand) { return &Cand; });
9750 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9751 // are accepted by both clang and NVCC. However, during a particular
9752 // compilation mode only one call variant is viable. We need to
9753 // exclude non-viable overload candidates from consideration based
9754 // only on their host/device attributes. Specifically, if one
9755 // candidate call is WrongSide and the other is SameSide, we ignore
9756 // the WrongSide candidate.
9757 if (S.getLangOpts().CUDA) {
9758 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9759 bool ContainsSameSideCandidate =
9760 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9761 // Check viable function only.
9762 return Cand->Viable && Cand->Function &&
9763 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9766 if (ContainsSameSideCandidate) {
9767 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9768 // Check viable function only to avoid unnecessary data copying/moving.
9769 return Cand->Viable && Cand->Function &&
9770 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9771 Sema::CFP_WrongSide;
9773 llvm::erase_if(Candidates, IsWrongSideCandidate);
9777 // Find the best viable function.
9779 for (auto *Cand : Candidates) {
9782 if (Best == end() ||
9783 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9787 // If we didn't find any viable functions, abort.
9789 return OR_No_Viable_Function;
9791 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9793 llvm::SmallVector<OverloadCandidate*, 4> PendingBest;
9794 PendingBest.push_back(&*Best);
9797 // Make sure that this function is better than every other viable
9798 // function. If not, we have an ambiguity.
9799 while (!PendingBest.empty()) {
9800 auto *Curr = PendingBest.pop_back_val();
9801 for (auto *Cand : Candidates) {
9802 if (Cand->Viable && !Cand->Best &&
9803 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
9804 PendingBest.push_back(Cand);
9807 if (S.isEquivalentInternalLinkageDeclaration(Cand->Function,
9809 EquivalentCands.push_back(Cand->Function);
9816 // If we found more than one best candidate, this is ambiguous.
9818 return OR_Ambiguous;
9820 // Best is the best viable function.
9821 if (Best->Function && Best->Function->isDeleted())
9824 if (!EquivalentCands.empty())
9825 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9833 enum OverloadCandidateKind {
9836 oc_reversed_binary_operator,
9838 oc_implicit_default_constructor,
9839 oc_implicit_copy_constructor,
9840 oc_implicit_move_constructor,
9841 oc_implicit_copy_assignment,
9842 oc_implicit_move_assignment,
9843 oc_implicit_equality_comparison,
9844 oc_inherited_constructor
9847 enum OverloadCandidateSelect {
9850 ocs_described_template,
9853 static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9854 ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9855 OverloadCandidateRewriteKind CRK,
9856 std::string &Description) {
9858 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9859 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9861 Description = S.getTemplateArgumentBindingsText(
9862 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9865 OverloadCandidateSelect Select = [&]() {
9866 if (!Description.empty())
9867 return ocs_described_template;
9868 return isTemplate ? ocs_template : ocs_non_template;
9871 OverloadCandidateKind Kind = [&]() {
9872 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
9873 return oc_implicit_equality_comparison;
9875 if (CRK & CRK_Reversed)
9876 return oc_reversed_binary_operator;
9878 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9879 if (!Ctor->isImplicit()) {
9880 if (isa<ConstructorUsingShadowDecl>(Found))
9881 return oc_inherited_constructor;
9883 return oc_constructor;
9886 if (Ctor->isDefaultConstructor())
9887 return oc_implicit_default_constructor;
9889 if (Ctor->isMoveConstructor())
9890 return oc_implicit_move_constructor;
9892 assert(Ctor->isCopyConstructor() &&
9893 "unexpected sort of implicit constructor");
9894 return oc_implicit_copy_constructor;
9897 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9898 // This actually gets spelled 'candidate function' for now, but
9899 // it doesn't hurt to split it out.
9900 if (!Meth->isImplicit())
9903 if (Meth->isMoveAssignmentOperator())
9904 return oc_implicit_move_assignment;
9906 if (Meth->isCopyAssignmentOperator())
9907 return oc_implicit_copy_assignment;
9909 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9916 return std::make_pair(Kind, Select);
9919 void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9920 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9922 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9923 S.Diag(FoundDecl->getLocation(),
9924 diag::note_ovl_candidate_inherited_constructor)
9925 << Shadow->getNominatedBaseClass();
9928 } // end anonymous namespace
9930 static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9931 const FunctionDecl *FD) {
9932 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9934 if (EnableIf->getCond()->isValueDependent() ||
9935 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9943 /// Returns true if we can take the address of the function.
9945 /// \param Complain - If true, we'll emit a diagnostic
9946 /// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9947 /// we in overload resolution?
9948 /// \param Loc - The location of the statement we're complaining about. Ignored
9949 /// if we're not complaining, or if we're in overload resolution.
9950 static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9952 bool InOverloadResolution,
9953 SourceLocation Loc) {
9954 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9956 if (InOverloadResolution)
9957 S.Diag(FD->getBeginLoc(),
9958 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9960 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9965 if (FD->getTrailingRequiresClause()) {
9966 ConstraintSatisfaction Satisfaction;
9967 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
9969 if (!Satisfaction.IsSatisfied) {
9971 if (InOverloadResolution)
9972 S.Diag(FD->getBeginLoc(),
9973 diag::note_ovl_candidate_unsatisfied_constraints);
9975 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
9977 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
9983 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9984 return P->hasAttr<PassObjectSizeAttr>();
9986 if (I == FD->param_end())
9990 // Add one to ParamNo because it's user-facing
9991 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9992 if (InOverloadResolution)
9993 S.Diag(FD->getLocation(),
9994 diag::note_ovl_candidate_has_pass_object_size_params)
9997 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
10003 static bool checkAddressOfCandidateIsAvailable(Sema &S,
10004 const FunctionDecl *FD) {
10005 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
10006 /*InOverloadResolution=*/true,
10007 /*Loc=*/SourceLocation());
10010 bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
10012 SourceLocation Loc) {
10013 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
10014 /*InOverloadResolution=*/false,
10018 // Notes the location of an overload candidate.
10019 void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
10020 OverloadCandidateRewriteKind RewriteKind,
10021 QualType DestType, bool TakingAddress) {
10022 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
10024 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
10025 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
10028 std::string FnDesc;
10029 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
10030 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
10031 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
10032 << (unsigned)KSPair.first << (unsigned)KSPair.second
10035 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
10036 Diag(Fn->getLocation(), PD);
10037 MaybeEmitInheritedConstructorNote(*this, Found);
10041 MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef<OverloadCandidate> Cands) {
10042 // Perhaps the ambiguity was caused by two atomic constraints that are
10043 // 'identical' but not equivalent:
10045 // void foo() requires (sizeof(T) > 4) { } // #1
10046 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
10048 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
10049 // #2 to subsume #1, but these constraint are not considered equivalent
10050 // according to the subsumption rules because they are not the same
10051 // source-level construct. This behavior is quite confusing and we should try
10052 // to help the user figure out what happened.
10054 SmallVector<const Expr *, 3> FirstAC, SecondAC;
10055 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
10056 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
10059 SmallVector<const Expr *, 3> AC;
10060 if (auto *Template = I->Function->getPrimaryTemplate())
10061 Template->getAssociatedConstraints(AC);
10063 I->Function->getAssociatedConstraints(AC);
10066 if (FirstCand == nullptr) {
10067 FirstCand = I->Function;
10069 } else if (SecondCand == nullptr) {
10070 SecondCand = I->Function;
10073 // We have more than one pair of constrained functions - this check is
10074 // expensive and we'd rather not try to diagnose it.
10080 // The diagnostic can only happen if there are associated constraints on
10081 // both sides (there needs to be some identical atomic constraint).
10082 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
10083 SecondCand, SecondAC))
10084 // Just show the user one diagnostic, they'll probably figure it out
10089 // Notes the location of all overload candidates designated through
10091 void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
10092 bool TakingAddress) {
10093 assert(OverloadedExpr->getType() == Context.OverloadTy);
10095 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
10096 OverloadExpr *OvlExpr = Ovl.Expression;
10098 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
10099 IEnd = OvlExpr->decls_end();
10101 if (FunctionTemplateDecl *FunTmpl =
10102 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
10103 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
10105 } else if (FunctionDecl *Fun
10106 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
10107 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
10112 /// Diagnoses an ambiguous conversion. The partial diagnostic is the
10113 /// "lead" diagnostic; it will be given two arguments, the source and
10114 /// target types of the conversion.
10115 void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
10117 SourceLocation CaretLoc,
10118 const PartialDiagnostic &PDiag) const {
10119 S.Diag(CaretLoc, PDiag)
10120 << Ambiguous.getFromType() << Ambiguous.getToType();
10121 // FIXME: The note limiting machinery is borrowed from
10122 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
10123 // refactoring here.
10124 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10125 unsigned CandsShown = 0;
10126 AmbiguousConversionSequence::const_iterator I, E;
10127 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
10128 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
10131 S.NoteOverloadCandidate(I->first, I->second);
10134 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
10137 static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
10138 unsigned I, bool TakingCandidateAddress) {
10139 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
10140 assert(Conv.isBad());
10141 assert(Cand->Function && "for now, candidate must be a function");
10142 FunctionDecl *Fn = Cand->Function;
10144 // There's a conversion slot for the object argument if this is a
10145 // non-constructor method. Note that 'I' corresponds the
10146 // conversion-slot index.
10147 bool isObjectArgument = false;
10148 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
10150 isObjectArgument = true;
10155 std::string FnDesc;
10156 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10157 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
10160 Expr *FromExpr = Conv.Bad.FromExpr;
10161 QualType FromTy = Conv.Bad.getFromType();
10162 QualType ToTy = Conv.Bad.getToType();
10164 if (FromTy == S.Context.OverloadTy) {
10165 assert(FromExpr && "overload set argument came from implicit argument?");
10166 Expr *E = FromExpr->IgnoreParens();
10167 if (isa<UnaryOperator>(E))
10168 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
10169 DeclarationName Name = cast<OverloadExpr>(E)->getName();
10171 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
10172 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10173 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
10175 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10179 // Do some hand-waving analysis to see if the non-viability is due
10180 // to a qualifier mismatch.
10181 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
10182 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
10183 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
10184 CToTy = RT->getPointeeType();
10186 // TODO: detect and diagnose the full richness of const mismatches.
10187 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
10188 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
10189 CFromTy = FromPT->getPointeeType();
10190 CToTy = ToPT->getPointeeType();
10194 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
10195 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
10196 Qualifiers FromQs = CFromTy.getQualifiers();
10197 Qualifiers ToQs = CToTy.getQualifiers();
10199 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
10200 if (isObjectArgument)
10201 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
10202 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10203 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10204 << FromQs.getAddressSpace() << ToQs.getAddressSpace();
10206 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
10207 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10208 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10209 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
10210 << ToTy->isReferenceType() << I + 1;
10211 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10215 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10216 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
10217 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10218 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10219 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
10220 << (unsigned)isObjectArgument << I + 1;
10221 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10225 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
10226 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
10227 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10228 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10229 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
10230 << (unsigned)isObjectArgument << I + 1;
10231 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10235 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
10236 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
10237 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10238 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10239 << FromQs.hasUnaligned() << I + 1;
10240 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10244 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
10245 assert(CVR && "unexpected qualifiers mismatch");
10247 if (isObjectArgument) {
10248 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
10249 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10250 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10253 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
10254 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10255 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10256 << (CVR - 1) << I + 1;
10258 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10262 // Special diagnostic for failure to convert an initializer list, since
10263 // telling the user that it has type void is not useful.
10264 if (FromExpr && isa<InitListExpr>(FromExpr)) {
10265 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
10266 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10267 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10268 << ToTy << (unsigned)isObjectArgument << I + 1;
10269 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10273 // Diagnose references or pointers to incomplete types differently,
10274 // since it's far from impossible that the incompleteness triggered
10276 QualType TempFromTy = FromTy.getNonReferenceType();
10277 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
10278 TempFromTy = PTy->getPointeeType();
10279 if (TempFromTy->isIncompleteType()) {
10280 // Emit the generic diagnostic and, optionally, add the hints to it.
10281 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
10282 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10283 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10284 << ToTy << (unsigned)isObjectArgument << I + 1
10285 << (unsigned)(Cand->Fix.Kind);
10287 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10291 // Diagnose base -> derived pointer conversions.
10292 unsigned BaseToDerivedConversion = 0;
10293 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
10294 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
10295 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10296 FromPtrTy->getPointeeType()) &&
10297 !FromPtrTy->getPointeeType()->isIncompleteType() &&
10298 !ToPtrTy->getPointeeType()->isIncompleteType() &&
10299 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
10300 FromPtrTy->getPointeeType()))
10301 BaseToDerivedConversion = 1;
10303 } else if (const ObjCObjectPointerType *FromPtrTy
10304 = FromTy->getAs<ObjCObjectPointerType>()) {
10305 if (const ObjCObjectPointerType *ToPtrTy
10306 = ToTy->getAs<ObjCObjectPointerType>())
10307 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
10308 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
10309 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
10310 FromPtrTy->getPointeeType()) &&
10311 FromIface->isSuperClassOf(ToIface))
10312 BaseToDerivedConversion = 2;
10313 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
10314 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
10315 !FromTy->isIncompleteType() &&
10316 !ToRefTy->getPointeeType()->isIncompleteType() &&
10317 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
10318 BaseToDerivedConversion = 3;
10319 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
10320 ToTy.getNonReferenceType().getCanonicalType() ==
10321 FromTy.getNonReferenceType().getCanonicalType()) {
10322 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
10323 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10324 << (unsigned)isObjectArgument << I + 1
10325 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
10326 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10331 if (BaseToDerivedConversion) {
10332 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
10333 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10334 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10335 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
10336 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10340 if (isa<ObjCObjectPointerType>(CFromTy) &&
10341 isa<PointerType>(CToTy)) {
10342 Qualifiers FromQs = CFromTy.getQualifiers();
10343 Qualifiers ToQs = CToTy.getQualifiers();
10344 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
10345 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
10346 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10347 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
10348 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
10349 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10354 if (TakingCandidateAddress &&
10355 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
10358 // Emit the generic diagnostic and, optionally, add the hints to it.
10359 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
10360 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10361 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
10362 << ToTy << (unsigned)isObjectArgument << I + 1
10363 << (unsigned)(Cand->Fix.Kind);
10365 // If we can fix the conversion, suggest the FixIts.
10366 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
10367 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
10369 S.Diag(Fn->getLocation(), FDiag);
10371 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10374 /// Additional arity mismatch diagnosis specific to a function overload
10375 /// candidates. This is not covered by the more general DiagnoseArityMismatch()
10376 /// over a candidate in any candidate set.
10377 static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
10378 unsigned NumArgs) {
10379 FunctionDecl *Fn = Cand->Function;
10380 unsigned MinParams = Fn->getMinRequiredArguments();
10382 // With invalid overloaded operators, it's possible that we think we
10383 // have an arity mismatch when in fact it looks like we have the
10384 // right number of arguments, because only overloaded operators have
10385 // the weird behavior of overloading member and non-member functions.
10386 // Just don't report anything.
10387 if (Fn->isInvalidDecl() &&
10388 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
10391 if (NumArgs < MinParams) {
10392 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
10393 (Cand->FailureKind == ovl_fail_bad_deduction &&
10394 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
10396 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
10397 (Cand->FailureKind == ovl_fail_bad_deduction &&
10398 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
10404 /// General arity mismatch diagnosis over a candidate in a candidate set.
10405 static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
10406 unsigned NumFormalArgs) {
10407 assert(isa<FunctionDecl>(D) &&
10408 "The templated declaration should at least be a function"
10409 " when diagnosing bad template argument deduction due to too many"
10410 " or too few arguments");
10412 FunctionDecl *Fn = cast<FunctionDecl>(D);
10414 // TODO: treat calls to a missing default constructor as a special case
10415 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
10416 unsigned MinParams = Fn->getMinRequiredArguments();
10418 // at least / at most / exactly
10419 unsigned mode, modeCount;
10420 if (NumFormalArgs < MinParams) {
10421 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10422 FnTy->isTemplateVariadic())
10423 mode = 0; // "at least"
10425 mode = 2; // "exactly"
10426 modeCount = MinParams;
10428 if (MinParams != FnTy->getNumParams())
10429 mode = 1; // "at most"
10431 mode = 2; // "exactly"
10432 modeCount = FnTy->getNumParams();
10435 std::string Description;
10436 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10437 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
10439 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10440 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10441 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10442 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10444 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10445 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10446 << Description << mode << modeCount << NumFormalArgs;
10448 MaybeEmitInheritedConstructorNote(S, Found);
10451 /// Arity mismatch diagnosis specific to a function overload candidate.
10452 static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10453 unsigned NumFormalArgs) {
10454 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10455 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10458 static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10459 if (TemplateDecl *TD = Templated->getDescribedTemplate())
10461 llvm_unreachable("Unsupported: Getting the described template declaration"
10462 " for bad deduction diagnosis");
10465 /// Diagnose a failed template-argument deduction.
10466 static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10467 DeductionFailureInfo &DeductionFailure,
10469 bool TakingCandidateAddress) {
10470 TemplateParameter Param = DeductionFailure.getTemplateParameter();
10472 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10473 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10474 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10475 switch (DeductionFailure.Result) {
10476 case Sema::TDK_Success:
10477 llvm_unreachable("TDK_success while diagnosing bad deduction");
10479 case Sema::TDK_Incomplete: {
10480 assert(ParamD && "no parameter found for incomplete deduction result");
10481 S.Diag(Templated->getLocation(),
10482 diag::note_ovl_candidate_incomplete_deduction)
10483 << ParamD->getDeclName();
10484 MaybeEmitInheritedConstructorNote(S, Found);
10488 case Sema::TDK_IncompletePack: {
10489 assert(ParamD && "no parameter found for incomplete deduction result");
10490 S.Diag(Templated->getLocation(),
10491 diag::note_ovl_candidate_incomplete_deduction_pack)
10492 << ParamD->getDeclName()
10493 << (DeductionFailure.getFirstArg()->pack_size() + 1)
10494 << *DeductionFailure.getFirstArg();
10495 MaybeEmitInheritedConstructorNote(S, Found);
10499 case Sema::TDK_Underqualified: {
10500 assert(ParamD && "no parameter found for bad qualifiers deduction result");
10501 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10503 QualType Param = DeductionFailure.getFirstArg()->getAsType();
10505 // Param will have been canonicalized, but it should just be a
10506 // qualified version of ParamD, so move the qualifiers to that.
10507 QualifierCollector Qs;
10509 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10510 assert(S.Context.hasSameType(Param, NonCanonParam));
10512 // Arg has also been canonicalized, but there's nothing we can do
10513 // about that. It also doesn't matter as much, because it won't
10514 // have any template parameters in it (because deduction isn't
10515 // done on dependent types).
10516 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10518 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10519 << ParamD->getDeclName() << Arg << NonCanonParam;
10520 MaybeEmitInheritedConstructorNote(S, Found);
10524 case Sema::TDK_Inconsistent: {
10525 assert(ParamD && "no parameter found for inconsistent deduction result");
10527 if (isa<TemplateTypeParmDecl>(ParamD))
10529 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10530 // Deduction might have failed because we deduced arguments of two
10531 // different types for a non-type template parameter.
10532 // FIXME: Use a different TDK value for this.
10534 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10536 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10537 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10538 S.Diag(Templated->getLocation(),
10539 diag::note_ovl_candidate_inconsistent_deduction_types)
10540 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10541 << *DeductionFailure.getSecondArg() << T2;
10542 MaybeEmitInheritedConstructorNote(S, Found);
10551 // Tweak the diagnostic if the problem is that we deduced packs of
10552 // different arities. We'll print the actual packs anyway in case that
10553 // includes additional useful information.
10554 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
10555 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
10556 DeductionFailure.getFirstArg()->pack_size() !=
10557 DeductionFailure.getSecondArg()->pack_size()) {
10561 S.Diag(Templated->getLocation(),
10562 diag::note_ovl_candidate_inconsistent_deduction)
10563 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10564 << *DeductionFailure.getSecondArg();
10565 MaybeEmitInheritedConstructorNote(S, Found);
10569 case Sema::TDK_InvalidExplicitArguments:
10570 assert(ParamD && "no parameter found for invalid explicit arguments");
10571 if (ParamD->getDeclName())
10572 S.Diag(Templated->getLocation(),
10573 diag::note_ovl_candidate_explicit_arg_mismatch_named)
10574 << ParamD->getDeclName();
10577 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10578 index = TTP->getIndex();
10579 else if (NonTypeTemplateParmDecl *NTTP
10580 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10581 index = NTTP->getIndex();
10583 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10584 S.Diag(Templated->getLocation(),
10585 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10588 MaybeEmitInheritedConstructorNote(S, Found);
10591 case Sema::TDK_ConstraintsNotSatisfied: {
10592 // Format the template argument list into the argument string.
10593 SmallString<128> TemplateArgString;
10594 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
10595 TemplateArgString = " ";
10596 TemplateArgString += S.getTemplateArgumentBindingsText(
10597 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10598 if (TemplateArgString.size() == 1)
10599 TemplateArgString.clear();
10600 S.Diag(Templated->getLocation(),
10601 diag::note_ovl_candidate_unsatisfied_constraints)
10602 << TemplateArgString;
10604 S.DiagnoseUnsatisfiedConstraint(
10605 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
10608 case Sema::TDK_TooManyArguments:
10609 case Sema::TDK_TooFewArguments:
10610 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10613 case Sema::TDK_InstantiationDepth:
10614 S.Diag(Templated->getLocation(),
10615 diag::note_ovl_candidate_instantiation_depth);
10616 MaybeEmitInheritedConstructorNote(S, Found);
10619 case Sema::TDK_SubstitutionFailure: {
10620 // Format the template argument list into the argument string.
10621 SmallString<128> TemplateArgString;
10622 if (TemplateArgumentList *Args =
10623 DeductionFailure.getTemplateArgumentList()) {
10624 TemplateArgString = " ";
10625 TemplateArgString += S.getTemplateArgumentBindingsText(
10626 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10627 if (TemplateArgString.size() == 1)
10628 TemplateArgString.clear();
10631 // If this candidate was disabled by enable_if, say so.
10632 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10633 if (PDiag && PDiag->second.getDiagID() ==
10634 diag::err_typename_nested_not_found_enable_if) {
10635 // FIXME: Use the source range of the condition, and the fully-qualified
10636 // name of the enable_if template. These are both present in PDiag.
10637 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10638 << "'enable_if'" << TemplateArgString;
10642 // We found a specific requirement that disabled the enable_if.
10643 if (PDiag && PDiag->second.getDiagID() ==
10644 diag::err_typename_nested_not_found_requirement) {
10645 S.Diag(Templated->getLocation(),
10646 diag::note_ovl_candidate_disabled_by_requirement)
10647 << PDiag->second.getStringArg(0) << TemplateArgString;
10651 // Format the SFINAE diagnostic into the argument string.
10652 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10653 // formatted message in another diagnostic.
10654 SmallString<128> SFINAEArgString;
10657 SFINAEArgString = ": ";
10658 R = SourceRange(PDiag->first, PDiag->first);
10659 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10662 S.Diag(Templated->getLocation(),
10663 diag::note_ovl_candidate_substitution_failure)
10664 << TemplateArgString << SFINAEArgString << R;
10665 MaybeEmitInheritedConstructorNote(S, Found);
10669 case Sema::TDK_DeducedMismatch:
10670 case Sema::TDK_DeducedMismatchNested: {
10671 // Format the template argument list into the argument string.
10672 SmallString<128> TemplateArgString;
10673 if (TemplateArgumentList *Args =
10674 DeductionFailure.getTemplateArgumentList()) {
10675 TemplateArgString = " ";
10676 TemplateArgString += S.getTemplateArgumentBindingsText(
10677 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10678 if (TemplateArgString.size() == 1)
10679 TemplateArgString.clear();
10682 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10683 << (*DeductionFailure.getCallArgIndex() + 1)
10684 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10685 << TemplateArgString
10686 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10690 case Sema::TDK_NonDeducedMismatch: {
10691 // FIXME: Provide a source location to indicate what we couldn't match.
10692 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10693 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10694 if (FirstTA.getKind() == TemplateArgument::Template &&
10695 SecondTA.getKind() == TemplateArgument::Template) {
10696 TemplateName FirstTN = FirstTA.getAsTemplate();
10697 TemplateName SecondTN = SecondTA.getAsTemplate();
10698 if (FirstTN.getKind() == TemplateName::Template &&
10699 SecondTN.getKind() == TemplateName::Template) {
10700 if (FirstTN.getAsTemplateDecl()->getName() ==
10701 SecondTN.getAsTemplateDecl()->getName()) {
10702 // FIXME: This fixes a bad diagnostic where both templates are named
10703 // the same. This particular case is a bit difficult since:
10704 // 1) It is passed as a string to the diagnostic printer.
10705 // 2) The diagnostic printer only attempts to find a better
10706 // name for types, not decls.
10707 // Ideally, this should folded into the diagnostic printer.
10708 S.Diag(Templated->getLocation(),
10709 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10710 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10716 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10717 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10720 // FIXME: For generic lambda parameters, check if the function is a lambda
10721 // call operator, and if so, emit a prettier and more informative
10722 // diagnostic that mentions 'auto' and lambda in addition to
10723 // (or instead of?) the canonical template type parameters.
10724 S.Diag(Templated->getLocation(),
10725 diag::note_ovl_candidate_non_deduced_mismatch)
10726 << FirstTA << SecondTA;
10729 // TODO: diagnose these individually, then kill off
10730 // note_ovl_candidate_bad_deduction, which is uselessly vague.
10731 case Sema::TDK_MiscellaneousDeductionFailure:
10732 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10733 MaybeEmitInheritedConstructorNote(S, Found);
10735 case Sema::TDK_CUDATargetMismatch:
10736 S.Diag(Templated->getLocation(),
10737 diag::note_cuda_ovl_candidate_target_mismatch);
10742 /// Diagnose a failed template-argument deduction, for function calls.
10743 static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10745 bool TakingCandidateAddress) {
10746 unsigned TDK = Cand->DeductionFailure.Result;
10747 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10748 if (CheckArityMismatch(S, Cand, NumArgs))
10751 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10752 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10755 /// CUDA: diagnose an invalid call across targets.
10756 static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10757 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10758 FunctionDecl *Callee = Cand->Function;
10760 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10761 CalleeTarget = S.IdentifyCUDATarget(Callee);
10763 std::string FnDesc;
10764 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10765 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
10766 Cand->getRewriteKind(), FnDesc);
10768 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10769 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10770 << FnDesc /* Ignored */
10771 << CalleeTarget << CallerTarget;
10773 // This could be an implicit constructor for which we could not infer the
10774 // target due to a collsion. Diagnose that case.
10775 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10776 if (Meth != nullptr && Meth->isImplicit()) {
10777 CXXRecordDecl *ParentClass = Meth->getParent();
10778 Sema::CXXSpecialMember CSM;
10780 switch (FnKindPair.first) {
10783 case oc_implicit_default_constructor:
10784 CSM = Sema::CXXDefaultConstructor;
10786 case oc_implicit_copy_constructor:
10787 CSM = Sema::CXXCopyConstructor;
10789 case oc_implicit_move_constructor:
10790 CSM = Sema::CXXMoveConstructor;
10792 case oc_implicit_copy_assignment:
10793 CSM = Sema::CXXCopyAssignment;
10795 case oc_implicit_move_assignment:
10796 CSM = Sema::CXXMoveAssignment;
10800 bool ConstRHS = false;
10801 if (Meth->getNumParams()) {
10802 if (const ReferenceType *RT =
10803 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10804 ConstRHS = RT->getPointeeType().isConstQualified();
10808 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10809 /* ConstRHS */ ConstRHS,
10810 /* Diagnose */ true);
10814 static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10815 FunctionDecl *Callee = Cand->Function;
10816 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10818 S.Diag(Callee->getLocation(),
10819 diag::note_ovl_candidate_disabled_by_function_cond_attr)
10820 << Attr->getCond()->getSourceRange() << Attr->getMessage();
10823 static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
10824 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Cand->Function);
10825 assert(ES.isExplicit() && "not an explicit candidate");
10828 switch (Cand->Function->getDeclKind()) {
10829 case Decl::Kind::CXXConstructor:
10832 case Decl::Kind::CXXConversion:
10835 case Decl::Kind::CXXDeductionGuide:
10836 Kind = Cand->Function->isImplicit() ? 0 : 2;
10839 llvm_unreachable("invalid Decl");
10842 // Note the location of the first (in-class) declaration; a redeclaration
10843 // (particularly an out-of-class definition) will typically lack the
10844 // 'explicit' specifier.
10845 // FIXME: This is probably a good thing to do for all 'candidate' notes.
10846 FunctionDecl *First = Cand->Function->getFirstDecl();
10847 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
10848 First = Pattern->getFirstDecl();
10850 S.Diag(First->getLocation(),
10851 diag::note_ovl_candidate_explicit)
10852 << Kind << (ES.getExpr() ? 1 : 0)
10853 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
10856 static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10857 FunctionDecl *Callee = Cand->Function;
10859 S.Diag(Callee->getLocation(),
10860 diag::note_ovl_candidate_disabled_by_extension)
10861 << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10864 /// Generates a 'note' diagnostic for an overload candidate. We've
10865 /// already generated a primary error at the call site.
10867 /// It really does need to be a single diagnostic with its caret
10868 /// pointed at the candidate declaration. Yes, this creates some
10869 /// major challenges of technical writing. Yes, this makes pointing
10870 /// out problems with specific arguments quite awkward. It's still
10871 /// better than generating twenty screens of text for every failed
10874 /// It would be great to be able to express per-candidate problems
10875 /// more richly for those diagnostic clients that cared, but we'd
10876 /// still have to be just as careful with the default diagnostics.
10877 /// \param CtorDestAS Addr space of object being constructed (for ctor
10878 /// candidates only).
10879 static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10881 bool TakingCandidateAddress,
10882 LangAS CtorDestAS = LangAS::Default) {
10883 FunctionDecl *Fn = Cand->Function;
10885 // Note deleted candidates, but only if they're viable.
10886 if (Cand->Viable) {
10887 if (Fn->isDeleted()) {
10888 std::string FnDesc;
10889 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10890 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
10891 Cand->getRewriteKind(), FnDesc);
10893 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10894 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10895 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10896 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10900 // We don't really have anything else to say about viable candidates.
10901 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10905 switch (Cand->FailureKind) {
10906 case ovl_fail_too_many_arguments:
10907 case ovl_fail_too_few_arguments:
10908 return DiagnoseArityMismatch(S, Cand, NumArgs);
10910 case ovl_fail_bad_deduction:
10911 return DiagnoseBadDeduction(S, Cand, NumArgs,
10912 TakingCandidateAddress);
10914 case ovl_fail_illegal_constructor: {
10915 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10916 << (Fn->getPrimaryTemplate() ? 1 : 0);
10917 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10921 case ovl_fail_object_addrspace_mismatch: {
10922 Qualifiers QualsForPrinting;
10923 QualsForPrinting.setAddressSpace(CtorDestAS);
10924 S.Diag(Fn->getLocation(),
10925 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
10926 << QualsForPrinting;
10927 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10931 case ovl_fail_trivial_conversion:
10932 case ovl_fail_bad_final_conversion:
10933 case ovl_fail_final_conversion_not_exact:
10934 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10936 case ovl_fail_bad_conversion: {
10937 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10938 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10939 if (Cand->Conversions[I].isBad())
10940 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10942 // FIXME: this currently happens when we're called from SemaInit
10943 // when user-conversion overload fails. Figure out how to handle
10944 // those conditions and diagnose them well.
10945 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
10948 case ovl_fail_bad_target:
10949 return DiagnoseBadTarget(S, Cand);
10951 case ovl_fail_enable_if:
10952 return DiagnoseFailedEnableIfAttr(S, Cand);
10954 case ovl_fail_explicit:
10955 return DiagnoseFailedExplicitSpec(S, Cand);
10957 case ovl_fail_ext_disabled:
10958 return DiagnoseOpenCLExtensionDisabled(S, Cand);
10960 case ovl_fail_inhctor_slice:
10961 // It's generally not interesting to note copy/move constructors here.
10962 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10964 S.Diag(Fn->getLocation(),
10965 diag::note_ovl_candidate_inherited_constructor_slice)
10966 << (Fn->getPrimaryTemplate() ? 1 : 0)
10967 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10968 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10971 case ovl_fail_addr_not_available: {
10972 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10974 assert(!Available);
10977 case ovl_non_default_multiversion_function:
10978 // Do nothing, these should simply be ignored.
10981 case ovl_fail_constraints_not_satisfied: {
10982 std::string FnDesc;
10983 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10984 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
10985 Cand->getRewriteKind(), FnDesc);
10987 S.Diag(Fn->getLocation(),
10988 diag::note_ovl_candidate_constraints_not_satisfied)
10989 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10990 << FnDesc /* Ignored */;
10991 ConstraintSatisfaction Satisfaction;
10992 if (S.CheckFunctionConstraints(Fn, Satisfaction))
10994 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
10999 static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
11000 // Desugar the type of the surrogate down to a function type,
11001 // retaining as many typedefs as possible while still showing
11002 // the function type (and, therefore, its parameter types).
11003 QualType FnType = Cand->Surrogate->getConversionType();
11004 bool isLValueReference = false;
11005 bool isRValueReference = false;
11006 bool isPointer = false;
11007 if (const LValueReferenceType *FnTypeRef =
11008 FnType->getAs<LValueReferenceType>()) {
11009 FnType = FnTypeRef->getPointeeType();
11010 isLValueReference = true;
11011 } else if (const RValueReferenceType *FnTypeRef =
11012 FnType->getAs<RValueReferenceType>()) {
11013 FnType = FnTypeRef->getPointeeType();
11014 isRValueReference = true;
11016 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
11017 FnType = FnTypePtr->getPointeeType();
11020 // Desugar down to a function type.
11021 FnType = QualType(FnType->getAs<FunctionType>(), 0);
11022 // Reconstruct the pointer/reference as appropriate.
11023 if (isPointer) FnType = S.Context.getPointerType(FnType);
11024 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
11025 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
11027 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
11031 static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
11032 SourceLocation OpLoc,
11033 OverloadCandidate *Cand) {
11034 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
11035 std::string TypeStr("operator");
11038 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
11039 if (Cand->Conversions.size() == 1) {
11041 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11044 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
11046 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
11050 static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
11051 OverloadCandidate *Cand) {
11052 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
11053 if (ICS.isBad()) break; // all meaningless after first invalid
11054 if (!ICS.isAmbiguous()) continue;
11056 ICS.DiagnoseAmbiguousConversion(
11057 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
11061 static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
11062 if (Cand->Function)
11063 return Cand->Function->getLocation();
11064 if (Cand->IsSurrogate)
11065 return Cand->Surrogate->getLocation();
11066 return SourceLocation();
11069 static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
11070 switch ((Sema::TemplateDeductionResult)DFI.Result) {
11071 case Sema::TDK_Success:
11072 case Sema::TDK_NonDependentConversionFailure:
11073 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
11075 case Sema::TDK_Invalid:
11076 case Sema::TDK_Incomplete:
11077 case Sema::TDK_IncompletePack:
11080 case Sema::TDK_Underqualified:
11081 case Sema::TDK_Inconsistent:
11084 case Sema::TDK_SubstitutionFailure:
11085 case Sema::TDK_DeducedMismatch:
11086 case Sema::TDK_ConstraintsNotSatisfied:
11087 case Sema::TDK_DeducedMismatchNested:
11088 case Sema::TDK_NonDeducedMismatch:
11089 case Sema::TDK_MiscellaneousDeductionFailure:
11090 case Sema::TDK_CUDATargetMismatch:
11093 case Sema::TDK_InstantiationDepth:
11096 case Sema::TDK_InvalidExplicitArguments:
11099 case Sema::TDK_TooManyArguments:
11100 case Sema::TDK_TooFewArguments:
11103 llvm_unreachable("Unhandled deduction result");
11107 struct CompareOverloadCandidatesForDisplay {
11109 SourceLocation Loc;
11111 OverloadCandidateSet::CandidateSetKind CSK;
11113 CompareOverloadCandidatesForDisplay(
11114 Sema &S, SourceLocation Loc, size_t NArgs,
11115 OverloadCandidateSet::CandidateSetKind CSK)
11116 : S(S), NumArgs(NArgs), CSK(CSK) {}
11118 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
11119 // If there are too many or too few arguments, that's the high-order bit we
11120 // want to sort by, even if the immediate failure kind was something else.
11121 if (C->FailureKind == ovl_fail_too_many_arguments ||
11122 C->FailureKind == ovl_fail_too_few_arguments)
11123 return static_cast<OverloadFailureKind>(C->FailureKind);
11126 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
11127 return ovl_fail_too_many_arguments;
11128 if (NumArgs < C->Function->getMinRequiredArguments())
11129 return ovl_fail_too_few_arguments;
11132 return static_cast<OverloadFailureKind>(C->FailureKind);
11135 bool operator()(const OverloadCandidate *L,
11136 const OverloadCandidate *R) {
11137 // Fast-path this check.
11138 if (L == R) return false;
11140 // Order first by viability.
11142 if (!R->Viable) return true;
11144 // TODO: introduce a tri-valued comparison for overload
11145 // candidates. Would be more worthwhile if we had a sort
11146 // that could exploit it.
11147 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
11149 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
11151 } else if (R->Viable)
11154 assert(L->Viable == R->Viable);
11156 // Criteria by which we can sort non-viable candidates:
11158 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
11159 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
11161 // 1. Arity mismatches come after other candidates.
11162 if (LFailureKind == ovl_fail_too_many_arguments ||
11163 LFailureKind == ovl_fail_too_few_arguments) {
11164 if (RFailureKind == ovl_fail_too_many_arguments ||
11165 RFailureKind == ovl_fail_too_few_arguments) {
11166 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
11167 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
11168 if (LDist == RDist) {
11169 if (LFailureKind == RFailureKind)
11170 // Sort non-surrogates before surrogates.
11171 return !L->IsSurrogate && R->IsSurrogate;
11172 // Sort candidates requiring fewer parameters than there were
11173 // arguments given after candidates requiring more parameters
11174 // than there were arguments given.
11175 return LFailureKind == ovl_fail_too_many_arguments;
11177 return LDist < RDist;
11181 if (RFailureKind == ovl_fail_too_many_arguments ||
11182 RFailureKind == ovl_fail_too_few_arguments)
11185 // 2. Bad conversions come first and are ordered by the number
11186 // of bad conversions and quality of good conversions.
11187 if (LFailureKind == ovl_fail_bad_conversion) {
11188 if (RFailureKind != ovl_fail_bad_conversion)
11191 // The conversion that can be fixed with a smaller number of changes,
11193 unsigned numLFixes = L->Fix.NumConversionsFixed;
11194 unsigned numRFixes = R->Fix.NumConversionsFixed;
11195 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
11196 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
11197 if (numLFixes != numRFixes) {
11198 return numLFixes < numRFixes;
11201 // If there's any ordering between the defined conversions...
11202 // FIXME: this might not be transitive.
11203 assert(L->Conversions.size() == R->Conversions.size());
11205 int leftBetter = 0;
11206 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
11207 for (unsigned E = L->Conversions.size(); I != E; ++I) {
11208 switch (CompareImplicitConversionSequences(S, Loc,
11210 R->Conversions[I])) {
11211 case ImplicitConversionSequence::Better:
11215 case ImplicitConversionSequence::Worse:
11219 case ImplicitConversionSequence::Indistinguishable:
11223 if (leftBetter > 0) return true;
11224 if (leftBetter < 0) return false;
11226 } else if (RFailureKind == ovl_fail_bad_conversion)
11229 if (LFailureKind == ovl_fail_bad_deduction) {
11230 if (RFailureKind != ovl_fail_bad_deduction)
11233 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11234 return RankDeductionFailure(L->DeductionFailure)
11235 < RankDeductionFailure(R->DeductionFailure);
11236 } else if (RFailureKind == ovl_fail_bad_deduction)
11242 // Sort everything else by location.
11243 SourceLocation LLoc = GetLocationForCandidate(L);
11244 SourceLocation RLoc = GetLocationForCandidate(R);
11246 // Put candidates without locations (e.g. builtins) at the end.
11247 if (LLoc.isInvalid()) return false;
11248 if (RLoc.isInvalid()) return true;
11250 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11255 /// CompleteNonViableCandidate - Normally, overload resolution only
11256 /// computes up to the first bad conversion. Produces the FixIt set if
11259 CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
11260 ArrayRef<Expr *> Args,
11261 OverloadCandidateSet::CandidateSetKind CSK) {
11262 assert(!Cand->Viable);
11264 // Don't do anything on failures other than bad conversion.
11265 if (Cand->FailureKind != ovl_fail_bad_conversion)
11268 // We only want the FixIts if all the arguments can be corrected.
11269 bool Unfixable = false;
11270 // Use a implicit copy initialization to check conversion fixes.
11271 Cand->Fix.setConversionChecker(TryCopyInitialization);
11273 // Attempt to fix the bad conversion.
11274 unsigned ConvCount = Cand->Conversions.size();
11275 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
11277 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
11278 if (Cand->Conversions[ConvIdx].isInitialized() &&
11279 Cand->Conversions[ConvIdx].isBad()) {
11280 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11285 // FIXME: this should probably be preserved from the overload
11286 // operation somehow.
11287 bool SuppressUserConversions = false;
11289 unsigned ConvIdx = 0;
11290 unsigned ArgIdx = 0;
11291 ArrayRef<QualType> ParamTypes;
11292 bool Reversed = Cand->RewriteKind & CRK_Reversed;
11294 if (Cand->IsSurrogate) {
11296 = Cand->Surrogate->getConversionType().getNonReferenceType();
11297 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11298 ConvType = ConvPtrType->getPointeeType();
11299 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
11300 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11302 } else if (Cand->Function) {
11304 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
11305 if (isa<CXXMethodDecl>(Cand->Function) &&
11306 !isa<CXXConstructorDecl>(Cand->Function) && !Reversed) {
11307 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
11309 if (CSK == OverloadCandidateSet::CSK_Operator &&
11310 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call)
11311 // Argument 0 is 'this', which doesn't have a corresponding parameter.
11315 // Builtin operator.
11316 assert(ConvCount <= 3);
11317 ParamTypes = Cand->BuiltinParamTypes;
11320 // Fill in the rest of the conversions.
11321 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
11322 ConvIdx != ConvCount;
11323 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
11324 assert(ArgIdx < Args.size() && "no argument for this arg conversion");
11325 if (Cand->Conversions[ConvIdx].isInitialized()) {
11326 // We've already checked this conversion.
11327 } else if (ParamIdx < ParamTypes.size()) {
11328 if (ParamTypes[ParamIdx]->isDependentType())
11329 Cand->Conversions[ConvIdx].setAsIdentityConversion(
11330 Args[ArgIdx]->getType());
11332 Cand->Conversions[ConvIdx] =
11333 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
11334 SuppressUserConversions,
11335 /*InOverloadResolution=*/true,
11336 /*AllowObjCWritebackConversion=*/
11337 S.getLangOpts().ObjCAutoRefCount);
11338 // Store the FixIt in the candidate if it exists.
11339 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
11340 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
11343 Cand->Conversions[ConvIdx].setEllipsis();
11347 SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
11348 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11349 SourceLocation OpLoc,
11350 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11351 // Sort the candidates by viability and position. Sorting directly would
11352 // be prohibitive, so we make a set of pointers and sort those.
11353 SmallVector<OverloadCandidate*, 32> Cands;
11354 if (OCD == OCD_AllCandidates) Cands.reserve(size());
11355 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11356 if (!Filter(*Cand))
11359 case OCD_AllCandidates:
11360 if (!Cand->Viable) {
11361 if (!Cand->Function && !Cand->IsSurrogate) {
11362 // This a non-viable builtin candidate. We do not, in general,
11363 // want to list every possible builtin candidate.
11366 CompleteNonViableCandidate(S, Cand, Args, Kind);
11370 case OCD_ViableCandidates:
11375 case OCD_AmbiguousCandidates:
11381 Cands.push_back(Cand);
11385 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
11390 /// When overload resolution fails, prints diagnostic messages containing the
11391 /// candidates in the candidate set.
11392 void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD,
11393 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
11394 StringRef Opc, SourceLocation OpLoc,
11395 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
11397 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
11399 S.Diag(PD.first, PD.second);
11401 NoteCandidates(S, Args, Cands, Opc, OpLoc);
11403 if (OCD == OCD_AmbiguousCandidates)
11404 MaybeDiagnoseAmbiguousConstraints(S, {begin(), end()});
11407 void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
11408 ArrayRef<OverloadCandidate *> Cands,
11409 StringRef Opc, SourceLocation OpLoc) {
11410 bool ReportedAmbiguousConversions = false;
11412 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11413 unsigned CandsShown = 0;
11414 auto I = Cands.begin(), E = Cands.end();
11415 for (; I != E; ++I) {
11416 OverloadCandidate *Cand = *I;
11418 // Set an arbitrary limit on the number of candidate functions we'll spam
11419 // the user with. FIXME: This limit should depend on details of the
11421 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
11426 if (Cand->Function)
11427 NoteFunctionCandidate(S, Cand, Args.size(),
11428 /*TakingCandidateAddress=*/false, DestAS);
11429 else if (Cand->IsSurrogate)
11430 NoteSurrogateCandidate(S, Cand);
11432 assert(Cand->Viable &&
11433 "Non-viable built-in candidates are not added to Cands.");
11434 // Generally we only see ambiguities including viable builtin
11435 // operators if overload resolution got screwed up by an
11436 // ambiguous user-defined conversion.
11438 // FIXME: It's quite possible for different conversions to see
11439 // different ambiguities, though.
11440 if (!ReportedAmbiguousConversions) {
11441 NoteAmbiguousUserConversions(S, OpLoc, Cand);
11442 ReportedAmbiguousConversions = true;
11445 // If this is a viable builtin, print it.
11446 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
11451 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
11454 static SourceLocation
11455 GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
11456 return Cand->Specialization ? Cand->Specialization->getLocation()
11457 : SourceLocation();
11461 struct CompareTemplateSpecCandidatesForDisplay {
11463 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
11465 bool operator()(const TemplateSpecCandidate *L,
11466 const TemplateSpecCandidate *R) {
11467 // Fast-path this check.
11471 // Assuming that both candidates are not matches...
11473 // Sort by the ranking of deduction failures.
11474 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
11475 return RankDeductionFailure(L->DeductionFailure) <
11476 RankDeductionFailure(R->DeductionFailure);
11478 // Sort everything else by location.
11479 SourceLocation LLoc = GetLocationForCandidate(L);
11480 SourceLocation RLoc = GetLocationForCandidate(R);
11482 // Put candidates without locations (e.g. builtins) at the end.
11483 if (LLoc.isInvalid())
11485 if (RLoc.isInvalid())
11488 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
11493 /// Diagnose a template argument deduction failure.
11494 /// We are treating these failures as overload failures due to bad
11496 void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
11497 bool ForTakingAddress) {
11498 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
11499 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
11502 void TemplateSpecCandidateSet::destroyCandidates() {
11503 for (iterator i = begin(), e = end(); i != e; ++i) {
11504 i->DeductionFailure.Destroy();
11508 void TemplateSpecCandidateSet::clear() {
11509 destroyCandidates();
11510 Candidates.clear();
11513 /// NoteCandidates - When no template specialization match is found, prints
11514 /// diagnostic messages containing the non-matching specializations that form
11515 /// the candidate set.
11516 /// This is analoguous to OverloadCandidateSet::NoteCandidates() with
11517 /// OCD == OCD_AllCandidates and Cand->Viable == false.
11518 void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
11519 // Sort the candidates by position (assuming no candidate is a match).
11520 // Sorting directly would be prohibitive, so we make a set of pointers
11522 SmallVector<TemplateSpecCandidate *, 32> Cands;
11523 Cands.reserve(size());
11524 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
11525 if (Cand->Specialization)
11526 Cands.push_back(Cand);
11527 // Otherwise, this is a non-matching builtin candidate. We do not,
11528 // in general, want to list every possible builtin candidate.
11531 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11533 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11534 // for generalization purposes (?).
11535 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11537 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11538 unsigned CandsShown = 0;
11539 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11540 TemplateSpecCandidate *Cand = *I;
11542 // Set an arbitrary limit on the number of candidates we'll spam
11543 // the user with. FIXME: This limit should depend on details of the
11545 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11549 assert(Cand->Specialization &&
11550 "Non-matching built-in candidates are not added to Cands.");
11551 Cand->NoteDeductionFailure(S, ForTakingAddress);
11555 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11558 // [PossiblyAFunctionType] --> [Return]
11559 // NonFunctionType --> NonFunctionType
11561 // R (*)(A) --> R (A)
11562 // R (&)(A) --> R (A)
11563 // R (S::*)(A) --> R (A)
11564 QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11565 QualType Ret = PossiblyAFunctionType;
11566 if (const PointerType *ToTypePtr =
11567 PossiblyAFunctionType->getAs<PointerType>())
11568 Ret = ToTypePtr->getPointeeType();
11569 else if (const ReferenceType *ToTypeRef =
11570 PossiblyAFunctionType->getAs<ReferenceType>())
11571 Ret = ToTypeRef->getPointeeType();
11572 else if (const MemberPointerType *MemTypePtr =
11573 PossiblyAFunctionType->getAs<MemberPointerType>())
11574 Ret = MemTypePtr->getPointeeType();
11576 Context.getCanonicalType(Ret).getUnqualifiedType();
11580 static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11581 bool Complain = true) {
11582 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11583 S.DeduceReturnType(FD, Loc, Complain))
11586 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11587 if (S.getLangOpts().CPlusPlus17 &&
11588 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11589 !S.ResolveExceptionSpec(Loc, FPT))
11596 // A helper class to help with address of function resolution
11597 // - allows us to avoid passing around all those ugly parameters
11598 class AddressOfFunctionResolver {
11601 const QualType& TargetType;
11602 QualType TargetFunctionType; // Extracted function type from target type
11605 //DeclAccessPair& ResultFunctionAccessPair;
11606 ASTContext& Context;
11608 bool TargetTypeIsNonStaticMemberFunction;
11609 bool FoundNonTemplateFunction;
11610 bool StaticMemberFunctionFromBoundPointer;
11611 bool HasComplained;
11613 OverloadExpr::FindResult OvlExprInfo;
11614 OverloadExpr *OvlExpr;
11615 TemplateArgumentListInfo OvlExplicitTemplateArgs;
11616 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11617 TemplateSpecCandidateSet FailedCandidates;
11620 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11621 const QualType &TargetType, bool Complain)
11622 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11623 Complain(Complain), Context(S.getASTContext()),
11624 TargetTypeIsNonStaticMemberFunction(
11625 !!TargetType->getAs<MemberPointerType>()),
11626 FoundNonTemplateFunction(false),
11627 StaticMemberFunctionFromBoundPointer(false),
11628 HasComplained(false),
11629 OvlExprInfo(OverloadExpr::find(SourceExpr)),
11630 OvlExpr(OvlExprInfo.Expression),
11631 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11632 ExtractUnqualifiedFunctionTypeFromTargetType();
11634 if (TargetFunctionType->isFunctionType()) {
11635 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11636 if (!UME->isImplicitAccess() &&
11637 !S.ResolveSingleFunctionTemplateSpecialization(UME))
11638 StaticMemberFunctionFromBoundPointer = true;
11639 } else if (OvlExpr->hasExplicitTemplateArgs()) {
11640 DeclAccessPair dap;
11641 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11642 OvlExpr, false, &dap)) {
11643 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11644 if (!Method->isStatic()) {
11645 // If the target type is a non-function type and the function found
11646 // is a non-static member function, pretend as if that was the
11647 // target, it's the only possible type to end up with.
11648 TargetTypeIsNonStaticMemberFunction = true;
11650 // And skip adding the function if its not in the proper form.
11651 // We'll diagnose this due to an empty set of functions.
11652 if (!OvlExprInfo.HasFormOfMemberPointer)
11656 Matches.push_back(std::make_pair(dap, Fn));
11661 if (OvlExpr->hasExplicitTemplateArgs())
11662 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11664 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11665 // C++ [over.over]p4:
11666 // If more than one function is selected, [...]
11667 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11668 if (FoundNonTemplateFunction)
11669 EliminateAllTemplateMatches();
11671 EliminateAllExceptMostSpecializedTemplate();
11675 if (S.getLangOpts().CUDA && Matches.size() > 1)
11676 EliminateSuboptimalCudaMatches();
11679 bool hasComplained() const { return HasComplained; }
11682 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11684 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11685 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11688 /// \return true if A is considered a better overload candidate for the
11689 /// desired type than B.
11690 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11691 // If A doesn't have exactly the correct type, we don't want to classify it
11692 // as "better" than anything else. This way, the user is required to
11693 // disambiguate for us if there are multiple candidates and no exact match.
11694 return candidateHasExactlyCorrectType(A) &&
11695 (!candidateHasExactlyCorrectType(B) ||
11696 compareEnableIfAttrs(S, A, B) == Comparison::Better);
11699 /// \return true if we were able to eliminate all but one overload candidate,
11700 /// false otherwise.
11701 bool eliminiateSuboptimalOverloadCandidates() {
11702 // Same algorithm as overload resolution -- one pass to pick the "best",
11703 // another pass to be sure that nothing is better than the best.
11704 auto Best = Matches.begin();
11705 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11706 if (isBetterCandidate(I->second, Best->second))
11709 const FunctionDecl *BestFn = Best->second;
11710 auto IsBestOrInferiorToBest = [this, BestFn](
11711 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11712 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11715 // Note: We explicitly leave Matches unmodified if there isn't a clear best
11716 // option, so we can potentially give the user a better error
11717 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11719 Matches[0] = *Best;
11724 bool isTargetTypeAFunction() const {
11725 return TargetFunctionType->isFunctionType();
11728 // [ToType] [Return]
11730 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11731 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11732 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11733 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11734 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11737 // return true if any matching specializations were found
11738 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11739 const DeclAccessPair& CurAccessFunPair) {
11740 if (CXXMethodDecl *Method
11741 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11742 // Skip non-static function templates when converting to pointer, and
11743 // static when converting to member pointer.
11744 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11747 else if (TargetTypeIsNonStaticMemberFunction)
11750 // C++ [over.over]p2:
11751 // If the name is a function template, template argument deduction is
11752 // done (14.8.2.2), and if the argument deduction succeeds, the
11753 // resulting template argument list is used to generate a single
11754 // function template specialization, which is added to the set of
11755 // overloaded functions considered.
11756 FunctionDecl *Specialization = nullptr;
11757 TemplateDeductionInfo Info(FailedCandidates.getLocation());
11758 if (Sema::TemplateDeductionResult Result
11759 = S.DeduceTemplateArguments(FunctionTemplate,
11760 &OvlExplicitTemplateArgs,
11761 TargetFunctionType, Specialization,
11762 Info, /*IsAddressOfFunction*/true)) {
11763 // Make a note of the failed deduction for diagnostics.
11764 FailedCandidates.addCandidate()
11765 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11766 MakeDeductionFailureInfo(Context, Result, Info));
11770 // Template argument deduction ensures that we have an exact match or
11771 // compatible pointer-to-function arguments that would be adjusted by ICS.
11772 // This function template specicalization works.
11773 assert(S.isSameOrCompatibleFunctionType(
11774 Context.getCanonicalType(Specialization->getType()),
11775 Context.getCanonicalType(TargetFunctionType)));
11777 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11780 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11784 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11785 const DeclAccessPair& CurAccessFunPair) {
11786 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11787 // Skip non-static functions when converting to pointer, and static
11788 // when converting to member pointer.
11789 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11792 else if (TargetTypeIsNonStaticMemberFunction)
11795 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11796 if (S.getLangOpts().CUDA)
11797 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11798 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11800 if (FunDecl->isMultiVersion()) {
11801 const auto *TA = FunDecl->getAttr<TargetAttr>();
11802 if (TA && !TA->isDefaultVersion())
11806 // If any candidate has a placeholder return type, trigger its deduction
11808 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11810 HasComplained |= Complain;
11814 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11817 // If we're in C, we need to support types that aren't exactly identical.
11818 if (!S.getLangOpts().CPlusPlus ||
11819 candidateHasExactlyCorrectType(FunDecl)) {
11820 Matches.push_back(std::make_pair(
11821 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11822 FoundNonTemplateFunction = true;
11830 bool FindAllFunctionsThatMatchTargetTypeExactly() {
11833 // If the overload expression doesn't have the form of a pointer to
11834 // member, don't try to convert it to a pointer-to-member type.
11835 if (IsInvalidFormOfPointerToMemberFunction())
11838 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11839 E = OvlExpr->decls_end();
11841 // Look through any using declarations to find the underlying function.
11842 NamedDecl *Fn = (*I)->getUnderlyingDecl();
11844 // C++ [over.over]p3:
11845 // Non-member functions and static member functions match
11846 // targets of type "pointer-to-function" or "reference-to-function."
11847 // Nonstatic member functions match targets of
11848 // type "pointer-to-member-function."
11849 // Note that according to DR 247, the containing class does not matter.
11850 if (FunctionTemplateDecl *FunctionTemplate
11851 = dyn_cast<FunctionTemplateDecl>(Fn)) {
11852 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11855 // If we have explicit template arguments supplied, skip non-templates.
11856 else if (!OvlExpr->hasExplicitTemplateArgs() &&
11857 AddMatchingNonTemplateFunction(Fn, I.getPair()))
11860 assert(Ret || Matches.empty());
11864 void EliminateAllExceptMostSpecializedTemplate() {
11865 // [...] and any given function template specialization F1 is
11866 // eliminated if the set contains a second function template
11867 // specialization whose function template is more specialized
11868 // than the function template of F1 according to the partial
11869 // ordering rules of 14.5.5.2.
11871 // The algorithm specified above is quadratic. We instead use a
11872 // two-pass algorithm (similar to the one used to identify the
11873 // best viable function in an overload set) that identifies the
11874 // best function template (if it exists).
11876 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11877 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11878 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11880 // TODO: It looks like FailedCandidates does not serve much purpose
11881 // here, since the no_viable diagnostic has index 0.
11882 UnresolvedSetIterator Result = S.getMostSpecialized(
11883 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11884 SourceExpr->getBeginLoc(), S.PDiag(),
11885 S.PDiag(diag::err_addr_ovl_ambiguous)
11886 << Matches[0].second->getDeclName(),
11887 S.PDiag(diag::note_ovl_candidate)
11888 << (unsigned)oc_function << (unsigned)ocs_described_template,
11889 Complain, TargetFunctionType);
11891 if (Result != MatchesCopy.end()) {
11892 // Make it the first and only element
11893 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11894 Matches[0].second = cast<FunctionDecl>(*Result);
11897 HasComplained |= Complain;
11900 void EliminateAllTemplateMatches() {
11901 // [...] any function template specializations in the set are
11902 // eliminated if the set also contains a non-template function, [...]
11903 for (unsigned I = 0, N = Matches.size(); I != N; ) {
11904 if (Matches[I].second->getPrimaryTemplate() == nullptr)
11907 Matches[I] = Matches[--N];
11913 void EliminateSuboptimalCudaMatches() {
11914 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11918 void ComplainNoMatchesFound() const {
11919 assert(Matches.empty());
11920 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
11921 << OvlExpr->getName() << TargetFunctionType
11922 << OvlExpr->getSourceRange();
11923 if (FailedCandidates.empty())
11924 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11925 /*TakingAddress=*/true);
11927 // We have some deduction failure messages. Use them to diagnose
11928 // the function templates, and diagnose the non-template candidates
11930 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11931 IEnd = OvlExpr->decls_end();
11933 if (FunctionDecl *Fun =
11934 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11935 if (!functionHasPassObjectSizeParams(Fun))
11936 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
11937 /*TakingAddress=*/true);
11938 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
11942 bool IsInvalidFormOfPointerToMemberFunction() const {
11943 return TargetTypeIsNonStaticMemberFunction &&
11944 !OvlExprInfo.HasFormOfMemberPointer;
11947 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11948 // TODO: Should we condition this on whether any functions might
11949 // have matched, or is it more appropriate to do that in callers?
11950 // TODO: a fixit wouldn't hurt.
11951 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11952 << TargetType << OvlExpr->getSourceRange();
11955 bool IsStaticMemberFunctionFromBoundPointer() const {
11956 return StaticMemberFunctionFromBoundPointer;
11959 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11960 S.Diag(OvlExpr->getBeginLoc(),
11961 diag::err_invalid_form_pointer_member_function)
11962 << OvlExpr->getSourceRange();
11965 void ComplainOfInvalidConversion() const {
11966 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
11967 << OvlExpr->getName() << TargetType;
11970 void ComplainMultipleMatchesFound() const {
11971 assert(Matches.size() > 1);
11972 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
11973 << OvlExpr->getName() << OvlExpr->getSourceRange();
11974 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11975 /*TakingAddress=*/true);
11978 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11980 int getNumMatches() const { return Matches.size(); }
11982 FunctionDecl* getMatchingFunctionDecl() const {
11983 if (Matches.size() != 1) return nullptr;
11984 return Matches[0].second;
11987 const DeclAccessPair* getMatchingFunctionAccessPair() const {
11988 if (Matches.size() != 1) return nullptr;
11989 return &Matches[0].first;
11994 /// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11995 /// an overloaded function (C++ [over.over]), where @p From is an
11996 /// expression with overloaded function type and @p ToType is the type
11997 /// we're trying to resolve to. For example:
12003 /// int (*pfd)(double) = f; // selects f(double)
12006 /// This routine returns the resulting FunctionDecl if it could be
12007 /// resolved, and NULL otherwise. When @p Complain is true, this
12008 /// routine will emit diagnostics if there is an error.
12010 Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
12011 QualType TargetType,
12013 DeclAccessPair &FoundResult,
12014 bool *pHadMultipleCandidates) {
12015 assert(AddressOfExpr->getType() == Context.OverloadTy);
12017 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
12019 int NumMatches = Resolver.getNumMatches();
12020 FunctionDecl *Fn = nullptr;
12021 bool ShouldComplain = Complain && !Resolver.hasComplained();
12022 if (NumMatches == 0 && ShouldComplain) {
12023 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
12024 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
12026 Resolver.ComplainNoMatchesFound();
12028 else if (NumMatches > 1 && ShouldComplain)
12029 Resolver.ComplainMultipleMatchesFound();
12030 else if (NumMatches == 1) {
12031 Fn = Resolver.getMatchingFunctionDecl();
12033 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
12034 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
12035 FoundResult = *Resolver.getMatchingFunctionAccessPair();
12037 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
12038 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
12040 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
12044 if (pHadMultipleCandidates)
12045 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
12049 /// Given an expression that refers to an overloaded function, try to
12050 /// resolve that function to a single function that can have its address taken.
12051 /// This will modify `Pair` iff it returns non-null.
12053 /// This routine can only succeed if from all of the candidates in the overload
12054 /// set for SrcExpr that can have their addresses taken, there is one candidate
12055 /// that is more constrained than the rest.
12057 Sema::resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &Pair) {
12058 OverloadExpr::FindResult R = OverloadExpr::find(E);
12059 OverloadExpr *Ovl = R.Expression;
12060 bool IsResultAmbiguous = false;
12061 FunctionDecl *Result = nullptr;
12062 DeclAccessPair DAP;
12063 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
12065 auto CheckMoreConstrained =
12066 [&] (FunctionDecl *FD1, FunctionDecl *FD2) -> Optional<bool> {
12067 SmallVector<const Expr *, 1> AC1, AC2;
12068 FD1->getAssociatedConstraints(AC1);
12069 FD2->getAssociatedConstraints(AC2);
12070 bool AtLeastAsConstrained1, AtLeastAsConstrained2;
12071 if (IsAtLeastAsConstrained(FD1, AC1, FD2, AC2, AtLeastAsConstrained1))
12073 if (IsAtLeastAsConstrained(FD2, AC2, FD1, AC1, AtLeastAsConstrained2))
12075 if (AtLeastAsConstrained1 == AtLeastAsConstrained2)
12077 return AtLeastAsConstrained1;
12080 // Don't use the AddressOfResolver because we're specifically looking for
12081 // cases where we have one overload candidate that lacks
12082 // enable_if/pass_object_size/...
12083 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
12084 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
12088 if (!checkAddressOfFunctionIsAvailable(FD))
12091 // We have more than one result - see if it is more constrained than the
12094 Optional<bool> MoreConstrainedThanPrevious = CheckMoreConstrained(FD,
12096 if (!MoreConstrainedThanPrevious) {
12097 IsResultAmbiguous = true;
12098 AmbiguousDecls.push_back(FD);
12101 if (!*MoreConstrainedThanPrevious)
12103 // FD is more constrained - replace Result with it.
12105 IsResultAmbiguous = false;
12110 if (IsResultAmbiguous)
12114 SmallVector<const Expr *, 1> ResultAC;
12115 // We skipped over some ambiguous declarations which might be ambiguous with
12116 // the selected result.
12117 for (FunctionDecl *Skipped : AmbiguousDecls)
12118 if (!CheckMoreConstrained(Skipped, Result).hasValue())
12125 /// Given an overloaded function, tries to turn it into a non-overloaded
12126 /// function reference using resolveAddressOfSingleOverloadCandidate. This
12127 /// will perform access checks, diagnose the use of the resultant decl, and, if
12128 /// requested, potentially perform a function-to-pointer decay.
12130 /// Returns false if resolveAddressOfSingleOverloadCandidate fails.
12131 /// Otherwise, returns true. This may emit diagnostics and return true.
12132 bool Sema::resolveAndFixAddressOfSingleOverloadCandidate(
12133 ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
12134 Expr *E = SrcExpr.get();
12135 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
12137 DeclAccessPair DAP;
12138 FunctionDecl *Found = resolveAddressOfSingleOverloadCandidate(E, DAP);
12139 if (!Found || Found->isCPUDispatchMultiVersion() ||
12140 Found->isCPUSpecificMultiVersion())
12143 // Emitting multiple diagnostics for a function that is both inaccessible and
12144 // unavailable is consistent with our behavior elsewhere. So, always check
12146 DiagnoseUseOfDecl(Found, E->getExprLoc());
12147 CheckAddressOfMemberAccess(E, DAP);
12148 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
12149 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
12150 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
12156 /// Given an expression that refers to an overloaded function, try to
12157 /// resolve that overloaded function expression down to a single function.
12159 /// This routine can only resolve template-ids that refer to a single function
12160 /// template, where that template-id refers to a single template whose template
12161 /// arguments are either provided by the template-id or have defaults,
12162 /// as described in C++0x [temp.arg.explicit]p3.
12164 /// If no template-ids are found, no diagnostics are emitted and NULL is
12167 Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
12169 DeclAccessPair *FoundResult) {
12170 // C++ [over.over]p1:
12171 // [...] [Note: any redundant set of parentheses surrounding the
12172 // overloaded function name is ignored (5.1). ]
12173 // C++ [over.over]p1:
12174 // [...] The overloaded function name can be preceded by the &
12177 // If we didn't actually find any template-ids, we're done.
12178 if (!ovl->hasExplicitTemplateArgs())
12181 TemplateArgumentListInfo ExplicitTemplateArgs;
12182 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
12183 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
12185 // Look through all of the overloaded functions, searching for one
12186 // whose type matches exactly.
12187 FunctionDecl *Matched = nullptr;
12188 for (UnresolvedSetIterator I = ovl->decls_begin(),
12189 E = ovl->decls_end(); I != E; ++I) {
12190 // C++0x [temp.arg.explicit]p3:
12191 // [...] In contexts where deduction is done and fails, or in contexts
12192 // where deduction is not done, if a template argument list is
12193 // specified and it, along with any default template arguments,
12194 // identifies a single function template specialization, then the
12195 // template-id is an lvalue for the function template specialization.
12196 FunctionTemplateDecl *FunctionTemplate
12197 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
12199 // C++ [over.over]p2:
12200 // If the name is a function template, template argument deduction is
12201 // done (14.8.2.2), and if the argument deduction succeeds, the
12202 // resulting template argument list is used to generate a single
12203 // function template specialization, which is added to the set of
12204 // overloaded functions considered.
12205 FunctionDecl *Specialization = nullptr;
12206 TemplateDeductionInfo Info(FailedCandidates.getLocation());
12207 if (TemplateDeductionResult Result
12208 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
12209 Specialization, Info,
12210 /*IsAddressOfFunction*/true)) {
12211 // Make a note of the failed deduction for diagnostics.
12212 // TODO: Actually use the failed-deduction info?
12213 FailedCandidates.addCandidate()
12214 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
12215 MakeDeductionFailureInfo(Context, Result, Info));
12219 assert(Specialization && "no specialization and no error?");
12221 // Multiple matches; we can't resolve to a single declaration.
12224 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
12226 NoteAllOverloadCandidates(ovl);
12231 Matched = Specialization;
12232 if (FoundResult) *FoundResult = I.getPair();
12236 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
12242 // Resolve and fix an overloaded expression that can be resolved
12243 // because it identifies a single function template specialization.
12245 // Last three arguments should only be supplied if Complain = true
12247 // Return true if it was logically possible to so resolve the
12248 // expression, regardless of whether or not it succeeded. Always
12249 // returns true if 'complain' is set.
12250 bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
12251 ExprResult &SrcExpr, bool doFunctionPointerConverion,
12252 bool complain, SourceRange OpRangeForComplaining,
12253 QualType DestTypeForComplaining,
12254 unsigned DiagIDForComplaining) {
12255 assert(SrcExpr.get()->getType() == Context.OverloadTy);
12257 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
12259 DeclAccessPair found;
12260 ExprResult SingleFunctionExpression;
12261 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
12262 ovl.Expression, /*complain*/ false, &found)) {
12263 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
12264 SrcExpr = ExprError();
12268 // It is only correct to resolve to an instance method if we're
12269 // resolving a form that's permitted to be a pointer to member.
12270 // Otherwise we'll end up making a bound member expression, which
12271 // is illegal in all the contexts we resolve like this.
12272 if (!ovl.HasFormOfMemberPointer &&
12273 isa<CXXMethodDecl>(fn) &&
12274 cast<CXXMethodDecl>(fn)->isInstance()) {
12275 if (!complain) return false;
12277 Diag(ovl.Expression->getExprLoc(),
12278 diag::err_bound_member_function)
12279 << 0 << ovl.Expression->getSourceRange();
12281 // TODO: I believe we only end up here if there's a mix of
12282 // static and non-static candidates (otherwise the expression
12283 // would have 'bound member' type, not 'overload' type).
12284 // Ideally we would note which candidate was chosen and why
12285 // the static candidates were rejected.
12286 SrcExpr = ExprError();
12290 // Fix the expression to refer to 'fn'.
12291 SingleFunctionExpression =
12292 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
12294 // If desired, do function-to-pointer decay.
12295 if (doFunctionPointerConverion) {
12296 SingleFunctionExpression =
12297 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
12298 if (SingleFunctionExpression.isInvalid()) {
12299 SrcExpr = ExprError();
12305 if (!SingleFunctionExpression.isUsable()) {
12307 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
12308 << ovl.Expression->getName()
12309 << DestTypeForComplaining
12310 << OpRangeForComplaining
12311 << ovl.Expression->getQualifierLoc().getSourceRange();
12312 NoteAllOverloadCandidates(SrcExpr.get());
12314 SrcExpr = ExprError();
12321 SrcExpr = SingleFunctionExpression;
12325 /// Add a single candidate to the overload set.
12326 static void AddOverloadedCallCandidate(Sema &S,
12327 DeclAccessPair FoundDecl,
12328 TemplateArgumentListInfo *ExplicitTemplateArgs,
12329 ArrayRef<Expr *> Args,
12330 OverloadCandidateSet &CandidateSet,
12331 bool PartialOverloading,
12333 NamedDecl *Callee = FoundDecl.getDecl();
12334 if (isa<UsingShadowDecl>(Callee))
12335 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
12337 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
12338 if (ExplicitTemplateArgs) {
12339 assert(!KnownValid && "Explicit template arguments?");
12342 // Prevent ill-formed function decls to be added as overload candidates.
12343 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
12346 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
12347 /*SuppressUserConversions=*/false,
12348 PartialOverloading);
12352 if (FunctionTemplateDecl *FuncTemplate
12353 = dyn_cast<FunctionTemplateDecl>(Callee)) {
12354 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
12355 ExplicitTemplateArgs, Args, CandidateSet,
12356 /*SuppressUserConversions=*/false,
12357 PartialOverloading);
12361 assert(!KnownValid && "unhandled case in overloaded call candidate");
12364 /// Add the overload candidates named by callee and/or found by argument
12365 /// dependent lookup to the given overload set.
12366 void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
12367 ArrayRef<Expr *> Args,
12368 OverloadCandidateSet &CandidateSet,
12369 bool PartialOverloading) {
12372 // Verify that ArgumentDependentLookup is consistent with the rules
12373 // in C++0x [basic.lookup.argdep]p3:
12375 // Let X be the lookup set produced by unqualified lookup (3.4.1)
12376 // and let Y be the lookup set produced by argument dependent
12377 // lookup (defined as follows). If X contains
12379 // -- a declaration of a class member, or
12381 // -- a block-scope function declaration that is not a
12382 // using-declaration, or
12384 // -- a declaration that is neither a function or a function
12387 // then Y is empty.
12389 if (ULE->requiresADL()) {
12390 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12391 E = ULE->decls_end(); I != E; ++I) {
12392 assert(!(*I)->getDeclContext()->isRecord());
12393 assert(isa<UsingShadowDecl>(*I) ||
12394 !(*I)->getDeclContext()->isFunctionOrMethod());
12395 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
12400 // It would be nice to avoid this copy.
12401 TemplateArgumentListInfo TABuffer;
12402 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12403 if (ULE->hasExplicitTemplateArgs()) {
12404 ULE->copyTemplateArgumentsInto(TABuffer);
12405 ExplicitTemplateArgs = &TABuffer;
12408 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
12409 E = ULE->decls_end(); I != E; ++I)
12410 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
12411 CandidateSet, PartialOverloading,
12412 /*KnownValid*/ true);
12414 if (ULE->requiresADL())
12415 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
12416 Args, ExplicitTemplateArgs,
12417 CandidateSet, PartialOverloading);
12420 /// Determine whether a declaration with the specified name could be moved into
12421 /// a different namespace.
12422 static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
12423 switch (Name.getCXXOverloadedOperator()) {
12424 case OO_New: case OO_Array_New:
12425 case OO_Delete: case OO_Array_Delete:
12433 /// Attempt to recover from an ill-formed use of a non-dependent name in a
12434 /// template, where the non-dependent name was declared after the template
12435 /// was defined. This is common in code written for a compilers which do not
12436 /// correctly implement two-stage name lookup.
12438 /// Returns true if a viable candidate was found and a diagnostic was issued.
12440 DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
12441 const CXXScopeSpec &SS, LookupResult &R,
12442 OverloadCandidateSet::CandidateSetKind CSK,
12443 TemplateArgumentListInfo *ExplicitTemplateArgs,
12444 ArrayRef<Expr *> Args,
12445 bool *DoDiagnoseEmptyLookup = nullptr) {
12446 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
12449 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
12450 if (DC->isTransparentContext())
12453 SemaRef.LookupQualifiedName(R, DC);
12456 R.suppressDiagnostics();
12458 if (isa<CXXRecordDecl>(DC)) {
12459 // Don't diagnose names we find in classes; we get much better
12460 // diagnostics for these from DiagnoseEmptyLookup.
12462 if (DoDiagnoseEmptyLookup)
12463 *DoDiagnoseEmptyLookup = true;
12467 OverloadCandidateSet Candidates(FnLoc, CSK);
12468 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
12469 AddOverloadedCallCandidate(SemaRef, I.getPair(),
12470 ExplicitTemplateArgs, Args,
12471 Candidates, false, /*KnownValid*/ false);
12473 OverloadCandidateSet::iterator Best;
12474 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
12475 // No viable functions. Don't bother the user with notes for functions
12476 // which don't work and shouldn't be found anyway.
12481 // Find the namespaces where ADL would have looked, and suggest
12482 // declaring the function there instead.
12483 Sema::AssociatedNamespaceSet AssociatedNamespaces;
12484 Sema::AssociatedClassSet AssociatedClasses;
12485 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
12486 AssociatedNamespaces,
12487 AssociatedClasses);
12488 Sema::AssociatedNamespaceSet SuggestedNamespaces;
12489 if (canBeDeclaredInNamespace(R.getLookupName())) {
12490 DeclContext *Std = SemaRef.getStdNamespace();
12491 for (Sema::AssociatedNamespaceSet::iterator
12492 it = AssociatedNamespaces.begin(),
12493 end = AssociatedNamespaces.end(); it != end; ++it) {
12494 // Never suggest declaring a function within namespace 'std'.
12495 if (Std && Std->Encloses(*it))
12498 // Never suggest declaring a function within a namespace with a
12499 // reserved name, like __gnu_cxx.
12500 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
12502 NS->getQualifiedNameAsString().find("__") != std::string::npos)
12505 SuggestedNamespaces.insert(*it);
12509 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
12510 << R.getLookupName();
12511 if (SuggestedNamespaces.empty()) {
12512 SemaRef.Diag(Best->Function->getLocation(),
12513 diag::note_not_found_by_two_phase_lookup)
12514 << R.getLookupName() << 0;
12515 } else if (SuggestedNamespaces.size() == 1) {
12516 SemaRef.Diag(Best->Function->getLocation(),
12517 diag::note_not_found_by_two_phase_lookup)
12518 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
12520 // FIXME: It would be useful to list the associated namespaces here,
12521 // but the diagnostics infrastructure doesn't provide a way to produce
12522 // a localized representation of a list of items.
12523 SemaRef.Diag(Best->Function->getLocation(),
12524 diag::note_not_found_by_two_phase_lookup)
12525 << R.getLookupName() << 2;
12528 // Try to recover by calling this function.
12538 /// Attempt to recover from ill-formed use of a non-dependent operator in a
12539 /// template, where the non-dependent operator was declared after the template
12542 /// Returns true if a viable candidate was found and a diagnostic was issued.
12544 DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
12545 SourceLocation OpLoc,
12546 ArrayRef<Expr *> Args) {
12547 DeclarationName OpName =
12548 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
12549 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
12550 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
12551 OverloadCandidateSet::CSK_Operator,
12552 /*ExplicitTemplateArgs=*/nullptr, Args);
12556 class BuildRecoveryCallExprRAII {
12559 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
12560 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
12561 SemaRef.IsBuildingRecoveryCallExpr = true;
12564 ~BuildRecoveryCallExprRAII() {
12565 SemaRef.IsBuildingRecoveryCallExpr = false;
12571 /// Attempts to recover from a call where no functions were found.
12573 /// Returns true if new candidates were found.
12575 BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12576 UnresolvedLookupExpr *ULE,
12577 SourceLocation LParenLoc,
12578 MutableArrayRef<Expr *> Args,
12579 SourceLocation RParenLoc,
12580 bool EmptyLookup, bool AllowTypoCorrection) {
12581 // Do not try to recover if it is already building a recovery call.
12582 // This stops infinite loops for template instantiations like
12584 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12585 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12587 if (SemaRef.IsBuildingRecoveryCallExpr)
12588 return ExprError();
12589 BuildRecoveryCallExprRAII RCE(SemaRef);
12592 SS.Adopt(ULE->getQualifierLoc());
12593 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12595 TemplateArgumentListInfo TABuffer;
12596 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12597 if (ULE->hasExplicitTemplateArgs()) {
12598 ULE->copyTemplateArgumentsInto(TABuffer);
12599 ExplicitTemplateArgs = &TABuffer;
12602 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12603 Sema::LookupOrdinaryName);
12604 bool DoDiagnoseEmptyLookup = EmptyLookup;
12605 if (!DiagnoseTwoPhaseLookup(
12606 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
12607 ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) {
12608 NoTypoCorrectionCCC NoTypoValidator{};
12609 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12610 ExplicitTemplateArgs != nullptr,
12611 dyn_cast<MemberExpr>(Fn));
12612 CorrectionCandidateCallback &Validator =
12613 AllowTypoCorrection
12614 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12615 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12616 if (!DoDiagnoseEmptyLookup ||
12617 SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12619 return ExprError();
12622 assert(!R.empty() && "lookup results empty despite recovery");
12624 // If recovery created an ambiguity, just bail out.
12625 if (R.isAmbiguous()) {
12626 R.suppressDiagnostics();
12627 return ExprError();
12630 // Build an implicit member call if appropriate. Just drop the
12631 // casts and such from the call, we don't really care.
12632 ExprResult NewFn = ExprError();
12633 if ((*R.begin())->isCXXClassMember())
12634 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12635 ExplicitTemplateArgs, S);
12636 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
12637 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
12638 ExplicitTemplateArgs);
12640 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
12642 if (NewFn.isInvalid())
12643 return ExprError();
12645 // This shouldn't cause an infinite loop because we're giving it
12646 // an expression with viable lookup results, which should never
12648 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
12649 MultiExprArg(Args.data(), Args.size()),
12653 /// Constructs and populates an OverloadedCandidateSet from
12654 /// the given function.
12655 /// \returns true when an the ExprResult output parameter has been set.
12656 bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
12657 UnresolvedLookupExpr *ULE,
12659 SourceLocation RParenLoc,
12660 OverloadCandidateSet *CandidateSet,
12661 ExprResult *Result) {
12663 if (ULE->requiresADL()) {
12664 // To do ADL, we must have found an unqualified name.
12665 assert(!ULE->getQualifier() && "qualified name with ADL");
12667 // We don't perform ADL for implicit declarations of builtins.
12668 // Verify that this was correctly set up.
12670 if (ULE->decls_begin() != ULE->decls_end() &&
12671 ULE->decls_begin() + 1 == ULE->decls_end() &&
12672 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
12673 F->getBuiltinID() && F->isImplicit())
12674 llvm_unreachable("performing ADL for builtin");
12676 // We don't perform ADL in C.
12677 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
12681 UnbridgedCastsSet UnbridgedCasts;
12682 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12683 *Result = ExprError();
12687 // Add the functions denoted by the callee to the set of candidate
12688 // functions, including those from argument-dependent lookup.
12689 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12691 if (getLangOpts().MSVCCompat &&
12692 CurContext->isDependentContext() && !isSFINAEContext() &&
12693 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12695 OverloadCandidateSet::iterator Best;
12696 if (CandidateSet->empty() ||
12697 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12698 OR_No_Viable_Function) {
12699 // In Microsoft mode, if we are inside a template class member function
12700 // then create a type dependent CallExpr. The goal is to postpone name
12701 // lookup to instantiation time to be able to search into type dependent
12703 CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy,
12704 VK_RValue, RParenLoc);
12705 CE->setTypeDependent(true);
12706 CE->setValueDependent(true);
12707 CE->setInstantiationDependent(true);
12713 if (CandidateSet->empty())
12716 UnbridgedCasts.restore();
12720 /// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12721 /// the completed call expression. If overload resolution fails, emits
12722 /// diagnostics and returns ExprError()
12723 static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12724 UnresolvedLookupExpr *ULE,
12725 SourceLocation LParenLoc,
12727 SourceLocation RParenLoc,
12729 OverloadCandidateSet *CandidateSet,
12730 OverloadCandidateSet::iterator *Best,
12731 OverloadingResult OverloadResult,
12732 bool AllowTypoCorrection) {
12733 if (CandidateSet->empty())
12734 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12735 RParenLoc, /*EmptyLookup=*/true,
12736 AllowTypoCorrection);
12738 switch (OverloadResult) {
12740 FunctionDecl *FDecl = (*Best)->Function;
12741 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12742 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12743 return ExprError();
12744 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12745 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12746 ExecConfig, /*IsExecConfig=*/false,
12747 (*Best)->IsADLCandidate);
12750 case OR_No_Viable_Function: {
12751 // Try to recover by looking for viable functions which the user might
12752 // have meant to call.
12753 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12755 /*EmptyLookup=*/false,
12756 AllowTypoCorrection);
12757 if (!Recovery.isInvalid())
12760 // If the user passes in a function that we can't take the address of, we
12761 // generally end up emitting really bad error messages. Here, we attempt to
12762 // emit better ones.
12763 for (const Expr *Arg : Args) {
12764 if (!Arg->getType()->isFunctionType())
12766 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12767 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12769 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12770 Arg->getExprLoc()))
12771 return ExprError();
12775 CandidateSet->NoteCandidates(
12776 PartialDiagnosticAt(
12778 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
12779 << ULE->getName() << Fn->getSourceRange()),
12780 SemaRef, OCD_AllCandidates, Args);
12785 CandidateSet->NoteCandidates(
12786 PartialDiagnosticAt(Fn->getBeginLoc(),
12787 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
12788 << ULE->getName() << Fn->getSourceRange()),
12789 SemaRef, OCD_AmbiguousCandidates, Args);
12793 CandidateSet->NoteCandidates(
12794 PartialDiagnosticAt(Fn->getBeginLoc(),
12795 SemaRef.PDiag(diag::err_ovl_deleted_call)
12796 << ULE->getName() << Fn->getSourceRange()),
12797 SemaRef, OCD_AllCandidates, Args);
12799 // We emitted an error for the unavailable/deleted function call but keep
12800 // the call in the AST.
12801 FunctionDecl *FDecl = (*Best)->Function;
12802 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12803 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12804 ExecConfig, /*IsExecConfig=*/false,
12805 (*Best)->IsADLCandidate);
12809 // Overload resolution failed.
12810 return ExprError();
12813 static void markUnaddressableCandidatesUnviable(Sema &S,
12814 OverloadCandidateSet &CS) {
12815 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12817 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12819 I->FailureKind = ovl_fail_addr_not_available;
12824 /// BuildOverloadedCallExpr - Given the call expression that calls Fn
12825 /// (which eventually refers to the declaration Func) and the call
12826 /// arguments Args/NumArgs, attempt to resolve the function call down
12827 /// to a specific function. If overload resolution succeeds, returns
12828 /// the call expression produced by overload resolution.
12829 /// Otherwise, emits diagnostics and returns ExprError.
12830 ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12831 UnresolvedLookupExpr *ULE,
12832 SourceLocation LParenLoc,
12834 SourceLocation RParenLoc,
12836 bool AllowTypoCorrection,
12837 bool CalleesAddressIsTaken) {
12838 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12839 OverloadCandidateSet::CSK_Normal);
12842 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12846 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12847 // functions that aren't addressible are considered unviable.
12848 if (CalleesAddressIsTaken)
12849 markUnaddressableCandidatesUnviable(*this, CandidateSet);
12851 OverloadCandidateSet::iterator Best;
12852 OverloadingResult OverloadResult =
12853 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
12855 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
12856 ExecConfig, &CandidateSet, &Best,
12857 OverloadResult, AllowTypoCorrection);
12860 static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12861 return Functions.size() > 1 ||
12862 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12865 /// Create a unary operation that may resolve to an overloaded
12868 /// \param OpLoc The location of the operator itself (e.g., '*').
12870 /// \param Opc The UnaryOperatorKind that describes this operator.
12872 /// \param Fns The set of non-member functions that will be
12873 /// considered by overload resolution. The caller needs to build this
12874 /// set based on the context using, e.g.,
12875 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12876 /// set should not contain any member functions; those will be added
12877 /// by CreateOverloadedUnaryOp().
12879 /// \param Input The input argument.
12881 Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12882 const UnresolvedSetImpl &Fns,
12883 Expr *Input, bool PerformADL) {
12884 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12885 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12886 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12887 // TODO: provide better source location info.
12888 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12890 if (checkPlaceholderForOverload(*this, Input))
12891 return ExprError();
12893 Expr *Args[2] = { Input, nullptr };
12894 unsigned NumArgs = 1;
12896 // For post-increment and post-decrement, add the implicit '0' as
12897 // the second argument, so that we know this is a post-increment or
12899 if (Opc == UO_PostInc || Opc == UO_PostDec) {
12900 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12901 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12906 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12908 if (Input->isTypeDependent()) {
12910 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12911 VK_RValue, OK_Ordinary, OpLoc, false);
12913 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12914 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12915 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12916 /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end());
12917 return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray,
12918 Context.DependentTy, VK_RValue, OpLoc,
12922 // Build an empty overload set.
12923 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12925 // Add the candidates from the given function set.
12926 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
12928 // Add operator candidates that are member functions.
12929 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12931 // Add candidates from ADL.
12933 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12934 /*ExplicitTemplateArgs*/nullptr,
12938 // Add builtin operator candidates.
12939 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12941 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12943 // Perform overload resolution.
12944 OverloadCandidateSet::iterator Best;
12945 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12947 // We found a built-in operator or an overloaded operator.
12948 FunctionDecl *FnDecl = Best->Function;
12951 Expr *Base = nullptr;
12952 // We matched an overloaded operator. Build a call to that
12955 // Convert the arguments.
12956 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12957 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12959 ExprResult InputRes =
12960 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12961 Best->FoundDecl, Method);
12962 if (InputRes.isInvalid())
12963 return ExprError();
12964 Base = Input = InputRes.get();
12966 // Convert the arguments.
12967 ExprResult InputInit
12968 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12970 FnDecl->getParamDecl(0)),
12973 if (InputInit.isInvalid())
12974 return ExprError();
12975 Input = InputInit.get();
12978 // Build the actual expression node.
12979 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12980 Base, HadMultipleCandidates,
12982 if (FnExpr.isInvalid())
12983 return ExprError();
12985 // Determine the result type.
12986 QualType ResultTy = FnDecl->getReturnType();
12987 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12988 ResultTy = ResultTy.getNonLValueExprType(Context);
12991 CallExpr *TheCall = CXXOperatorCallExpr::Create(
12992 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
12993 FPOptions(), Best->IsADLCandidate);
12995 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12996 return ExprError();
12998 if (CheckFunctionCall(FnDecl, TheCall,
12999 FnDecl->getType()->castAs<FunctionProtoType>()))
13000 return ExprError();
13002 return MaybeBindToTemporary(TheCall);
13004 // We matched a built-in operator. Convert the arguments, then
13005 // break out so that we will build the appropriate built-in
13007 ExprResult InputRes = PerformImplicitConversion(
13008 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
13009 CCK_ForBuiltinOverloadedOp);
13010 if (InputRes.isInvalid())
13011 return ExprError();
13012 Input = InputRes.get();
13017 case OR_No_Viable_Function:
13018 // This is an erroneous use of an operator which can be overloaded by
13019 // a non-member function. Check for non-member operators which were
13020 // defined too late to be candidates.
13021 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
13022 // FIXME: Recover by calling the found function.
13023 return ExprError();
13025 // No viable function; fall through to handling this as a
13026 // built-in operator, which will produce an error message for us.
13030 CandidateSet.NoteCandidates(
13031 PartialDiagnosticAt(OpLoc,
13032 PDiag(diag::err_ovl_ambiguous_oper_unary)
13033 << UnaryOperator::getOpcodeStr(Opc)
13034 << Input->getType() << Input->getSourceRange()),
13035 *this, OCD_AmbiguousCandidates, ArgsArray,
13036 UnaryOperator::getOpcodeStr(Opc), OpLoc);
13037 return ExprError();
13040 CandidateSet.NoteCandidates(
13041 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13042 << UnaryOperator::getOpcodeStr(Opc)
13043 << Input->getSourceRange()),
13044 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
13046 return ExprError();
13049 // Either we found no viable overloaded operator or we matched a
13050 // built-in operator. In either case, fall through to trying to
13051 // build a built-in operation.
13052 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
13055 /// Perform lookup for an overloaded binary operator.
13056 void Sema::LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet,
13057 OverloadedOperatorKind Op,
13058 const UnresolvedSetImpl &Fns,
13059 ArrayRef<Expr *> Args, bool PerformADL) {
13060 SourceLocation OpLoc = CandidateSet.getLocation();
13062 OverloadedOperatorKind ExtraOp =
13063 CandidateSet.getRewriteInfo().AllowRewrittenCandidates
13064 ? getRewrittenOverloadedOperator(Op)
13067 // Add the candidates from the given function set. This also adds the
13068 // rewritten candidates using these functions if necessary.
13069 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
13071 // Add operator candidates that are member functions.
13072 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13073 if (CandidateSet.getRewriteInfo().shouldAddReversed(Op))
13074 AddMemberOperatorCandidates(Op, OpLoc, {Args[1], Args[0]}, CandidateSet,
13075 OverloadCandidateParamOrder::Reversed);
13077 // In C++20, also add any rewritten member candidates.
13079 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
13080 if (CandidateSet.getRewriteInfo().shouldAddReversed(ExtraOp))
13081 AddMemberOperatorCandidates(ExtraOp, OpLoc, {Args[1], Args[0]},
13083 OverloadCandidateParamOrder::Reversed);
13086 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
13087 // performed for an assignment operator (nor for operator[] nor operator->,
13088 // which don't get here).
13089 if (Op != OO_Equal && PerformADL) {
13090 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13091 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
13092 /*ExplicitTemplateArgs*/ nullptr,
13095 DeclarationName ExtraOpName =
13096 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
13097 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
13098 /*ExplicitTemplateArgs*/ nullptr,
13103 // Add builtin operator candidates.
13105 // FIXME: We don't add any rewritten candidates here. This is strictly
13106 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
13107 // resulting in our selecting a rewritten builtin candidate. For example:
13109 // enum class E { e };
13110 // bool operator!=(E, E) requires false;
13111 // bool k = E::e != E::e;
13113 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
13114 // it seems unreasonable to consider rewritten builtin candidates. A core
13115 // issue has been filed proposing to removed this requirement.
13116 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
13119 /// Create a binary operation that may resolve to an overloaded
13122 /// \param OpLoc The location of the operator itself (e.g., '+').
13124 /// \param Opc The BinaryOperatorKind that describes this operator.
13126 /// \param Fns The set of non-member functions that will be
13127 /// considered by overload resolution. The caller needs to build this
13128 /// set based on the context using, e.g.,
13129 /// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
13130 /// set should not contain any member functions; those will be added
13131 /// by CreateOverloadedBinOp().
13133 /// \param LHS Left-hand argument.
13134 /// \param RHS Right-hand argument.
13135 /// \param PerformADL Whether to consider operator candidates found by ADL.
13136 /// \param AllowRewrittenCandidates Whether to consider candidates found by
13137 /// C++20 operator rewrites.
13138 /// \param DefaultedFn If we are synthesizing a defaulted operator function,
13139 /// the function in question. Such a function is never a candidate in
13140 /// our overload resolution. This also enables synthesizing a three-way
13141 /// comparison from < and == as described in C++20 [class.spaceship]p1.
13142 ExprResult Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
13143 BinaryOperatorKind Opc,
13144 const UnresolvedSetImpl &Fns, Expr *LHS,
13145 Expr *RHS, bool PerformADL,
13146 bool AllowRewrittenCandidates,
13147 FunctionDecl *DefaultedFn) {
13148 Expr *Args[2] = { LHS, RHS };
13149 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
13151 if (!getLangOpts().CPlusPlus2a)
13152 AllowRewrittenCandidates = false;
13154 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
13156 // If either side is type-dependent, create an appropriate dependent
13158 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13160 // If there are no functions to store, just build a dependent
13161 // BinaryOperator or CompoundAssignment.
13162 if (Opc <= BO_Assign || Opc > BO_OrAssign)
13163 return new (Context) BinaryOperator(
13164 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
13165 OpLoc, FPFeatures);
13167 return new (Context) CompoundAssignOperator(
13168 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
13169 Context.DependentTy, Context.DependentTy, OpLoc,
13173 // FIXME: save results of ADL from here?
13174 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13175 // TODO: provide better source location info in DNLoc component.
13176 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
13177 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
13178 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
13179 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
13180 /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end());
13181 return CXXOperatorCallExpr::Create(Context, Op, Fn, Args,
13182 Context.DependentTy, VK_RValue, OpLoc,
13186 // Always do placeholder-like conversions on the RHS.
13187 if (checkPlaceholderForOverload(*this, Args[1]))
13188 return ExprError();
13190 // Do placeholder-like conversion on the LHS; note that we should
13191 // not get here with a PseudoObject LHS.
13192 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
13193 if (checkPlaceholderForOverload(*this, Args[0]))
13194 return ExprError();
13196 // If this is the assignment operator, we only perform overload resolution
13197 // if the left-hand side is a class or enumeration type. This is actually
13198 // a hack. The standard requires that we do overload resolution between the
13199 // various built-in candidates, but as DR507 points out, this can lead to
13200 // problems. So we do it this way, which pretty much follows what GCC does.
13201 // Note that we go the traditional code path for compound assignment forms.
13202 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
13203 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13205 // If this is the .* operator, which is not overloadable, just
13206 // create a built-in binary operator.
13207 if (Opc == BO_PtrMemD)
13208 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13210 // Build the overload set.
13211 OverloadCandidateSet CandidateSet(
13212 OpLoc, OverloadCandidateSet::CSK_Operator,
13213 OverloadCandidateSet::OperatorRewriteInfo(Op, AllowRewrittenCandidates));
13215 CandidateSet.exclude(DefaultedFn);
13216 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
13218 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13220 // Perform overload resolution.
13221 OverloadCandidateSet::iterator Best;
13222 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13224 // We found a built-in operator or an overloaded operator.
13225 FunctionDecl *FnDecl = Best->Function;
13227 bool IsReversed = (Best->RewriteKind & CRK_Reversed);
13229 std::swap(Args[0], Args[1]);
13232 Expr *Base = nullptr;
13233 // We matched an overloaded operator. Build a call to that
13236 OverloadedOperatorKind ChosenOp =
13237 FnDecl->getDeclName().getCXXOverloadedOperator();
13239 // C++2a [over.match.oper]p9:
13240 // If a rewritten operator== candidate is selected by overload
13241 // resolution for an operator@, its return type shall be cv bool
13242 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
13243 !FnDecl->getReturnType()->isBooleanType()) {
13244 Diag(OpLoc, diag::err_ovl_rewrite_equalequal_not_bool)
13245 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
13246 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13247 Diag(FnDecl->getLocation(), diag::note_declared_at);
13248 return ExprError();
13251 if (AllowRewrittenCandidates && !IsReversed &&
13252 CandidateSet.getRewriteInfo().shouldAddReversed(ChosenOp)) {
13253 // We could have reversed this operator, but didn't. Check if the
13254 // reversed form was a viable candidate, and if so, if it had a
13255 // better conversion for either parameter. If so, this call is
13256 // formally ambiguous, and allowing it is an extension.
13257 for (OverloadCandidate &Cand : CandidateSet) {
13258 if (Cand.Viable && Cand.Function == FnDecl &&
13259 Cand.RewriteKind & CRK_Reversed) {
13260 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
13261 if (CompareImplicitConversionSequences(
13262 *this, OpLoc, Cand.Conversions[ArgIdx],
13263 Best->Conversions[ArgIdx]) ==
13264 ImplicitConversionSequence::Better) {
13265 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
13266 << BinaryOperator::getOpcodeStr(Opc)
13267 << Args[0]->getType() << Args[1]->getType()
13268 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13269 Diag(FnDecl->getLocation(),
13270 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
13278 // Convert the arguments.
13279 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
13280 // Best->Access is only meaningful for class members.
13281 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
13284 PerformCopyInitialization(
13285 InitializedEntity::InitializeParameter(Context,
13286 FnDecl->getParamDecl(0)),
13287 SourceLocation(), Args[1]);
13288 if (Arg1.isInvalid())
13289 return ExprError();
13292 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13293 Best->FoundDecl, Method);
13294 if (Arg0.isInvalid())
13295 return ExprError();
13296 Base = Args[0] = Arg0.getAs<Expr>();
13297 Args[1] = RHS = Arg1.getAs<Expr>();
13299 // Convert the arguments.
13300 ExprResult Arg0 = PerformCopyInitialization(
13301 InitializedEntity::InitializeParameter(Context,
13302 FnDecl->getParamDecl(0)),
13303 SourceLocation(), Args[0]);
13304 if (Arg0.isInvalid())
13305 return ExprError();
13308 PerformCopyInitialization(
13309 InitializedEntity::InitializeParameter(Context,
13310 FnDecl->getParamDecl(1)),
13311 SourceLocation(), Args[1]);
13312 if (Arg1.isInvalid())
13313 return ExprError();
13314 Args[0] = LHS = Arg0.getAs<Expr>();
13315 Args[1] = RHS = Arg1.getAs<Expr>();
13318 // Build the actual expression node.
13319 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13320 Best->FoundDecl, Base,
13321 HadMultipleCandidates, OpLoc);
13322 if (FnExpr.isInvalid())
13323 return ExprError();
13325 // Determine the result type.
13326 QualType ResultTy = FnDecl->getReturnType();
13327 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13328 ResultTy = ResultTy.getNonLValueExprType(Context);
13330 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13331 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
13332 FPFeatures, Best->IsADLCandidate);
13334 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
13336 return ExprError();
13338 ArrayRef<const Expr *> ArgsArray(Args, 2);
13339 const Expr *ImplicitThis = nullptr;
13340 // Cut off the implicit 'this'.
13341 if (isa<CXXMethodDecl>(FnDecl)) {
13342 ImplicitThis = ArgsArray[0];
13343 ArgsArray = ArgsArray.slice(1);
13346 // Check for a self move.
13347 if (Op == OO_Equal)
13348 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
13350 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
13351 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
13352 VariadicDoesNotApply);
13354 ExprResult R = MaybeBindToTemporary(TheCall);
13356 return ExprError();
13358 // For a rewritten candidate, we've already reversed the arguments
13359 // if needed. Perform the rest of the rewrite now.
13360 if ((Best->RewriteKind & CRK_DifferentOperator) ||
13361 (Op == OO_Spaceship && IsReversed)) {
13362 if (Op == OO_ExclaimEqual) {
13363 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
13364 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
13366 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
13367 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
13368 Expr *ZeroLiteral =
13369 IntegerLiteral::Create(Context, Zero, Context.IntTy, OpLoc);
13371 Sema::CodeSynthesisContext Ctx;
13372 Ctx.Kind = Sema::CodeSynthesisContext::RewritingOperatorAsSpaceship;
13373 Ctx.Entity = FnDecl;
13374 pushCodeSynthesisContext(Ctx);
13376 R = CreateOverloadedBinOp(
13377 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
13378 IsReversed ? R.get() : ZeroLiteral, PerformADL,
13379 /*AllowRewrittenCandidates=*/false);
13381 popCodeSynthesisContext();
13384 return ExprError();
13386 assert(ChosenOp == Op && "unexpected operator name");
13389 // Make a note in the AST if we did any rewriting.
13390 if (Best->RewriteKind != CRK_None)
13391 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
13395 // We matched a built-in operator. Convert the arguments, then
13396 // break out so that we will build the appropriate built-in
13398 ExprResult ArgsRes0 = PerformImplicitConversion(
13399 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13400 AA_Passing, CCK_ForBuiltinOverloadedOp);
13401 if (ArgsRes0.isInvalid())
13402 return ExprError();
13403 Args[0] = ArgsRes0.get();
13405 ExprResult ArgsRes1 = PerformImplicitConversion(
13406 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13407 AA_Passing, CCK_ForBuiltinOverloadedOp);
13408 if (ArgsRes1.isInvalid())
13409 return ExprError();
13410 Args[1] = ArgsRes1.get();
13415 case OR_No_Viable_Function: {
13416 // C++ [over.match.oper]p9:
13417 // If the operator is the operator , [...] and there are no
13418 // viable functions, then the operator is assumed to be the
13419 // built-in operator and interpreted according to clause 5.
13420 if (Opc == BO_Comma)
13423 // When defaulting an 'operator<=>', we can try to synthesize a three-way
13424 // compare result using '==' and '<'.
13425 if (DefaultedFn && Opc == BO_Cmp) {
13426 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
13427 Args[1], DefaultedFn);
13428 if (E.isInvalid() || E.isUsable())
13432 // For class as left operand for assignment or compound assignment
13433 // operator do not fall through to handling in built-in, but report that
13434 // no overloaded assignment operator found
13435 ExprResult Result = ExprError();
13436 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
13437 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
13439 if (Args[0]->getType()->isRecordType() &&
13440 Opc >= BO_Assign && Opc <= BO_OrAssign) {
13441 Diag(OpLoc, diag::err_ovl_no_viable_oper)
13442 << BinaryOperator::getOpcodeStr(Opc)
13443 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13444 if (Args[0]->getType()->isIncompleteType()) {
13445 Diag(OpLoc, diag::note_assign_lhs_incomplete)
13446 << Args[0]->getType()
13447 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
13450 // This is an erroneous use of an operator which can be overloaded by
13451 // a non-member function. Check for non-member operators which were
13452 // defined too late to be candidates.
13453 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
13454 // FIXME: Recover by calling the found function.
13455 return ExprError();
13457 // No viable function; try to create a built-in operation, which will
13458 // produce an error. Then, show the non-viable candidates.
13459 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13461 assert(Result.isInvalid() &&
13462 "C++ binary operator overloading is missing candidates!");
13463 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
13468 CandidateSet.NoteCandidates(
13469 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13470 << BinaryOperator::getOpcodeStr(Opc)
13471 << Args[0]->getType()
13472 << Args[1]->getType()
13473 << Args[0]->getSourceRange()
13474 << Args[1]->getSourceRange()),
13475 *this, OCD_AmbiguousCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13477 return ExprError();
13480 if (isImplicitlyDeleted(Best->Function)) {
13481 FunctionDecl *DeletedFD = Best->Function;
13482 DefaultedFunctionKind DFK = getDefaultedFunctionKind(DeletedFD);
13483 if (DFK.isSpecialMember()) {
13484 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
13485 << Args[0]->getType() << DFK.asSpecialMember();
13487 assert(DFK.isComparison());
13488 Diag(OpLoc, diag::err_ovl_deleted_comparison)
13489 << Args[0]->getType() << DeletedFD;
13492 // The user probably meant to call this special member. Just
13493 // explain why it's deleted.
13494 NoteDeletedFunction(DeletedFD);
13495 return ExprError();
13497 CandidateSet.NoteCandidates(
13498 PartialDiagnosticAt(
13499 OpLoc, PDiag(diag::err_ovl_deleted_oper)
13500 << getOperatorSpelling(Best->Function->getDeclName()
13501 .getCXXOverloadedOperator())
13502 << Args[0]->getSourceRange()
13503 << Args[1]->getSourceRange()),
13504 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
13506 return ExprError();
13509 // We matched a built-in operator; build it.
13510 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
13513 ExprResult Sema::BuildSynthesizedThreeWayComparison(
13514 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
13515 FunctionDecl *DefaultedFn) {
13516 const ComparisonCategoryInfo *Info =
13517 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
13518 // If we're not producing a known comparison category type, we can't
13519 // synthesize a three-way comparison. Let the caller diagnose this.
13521 return ExprResult((Expr*)nullptr);
13523 // If we ever want to perform this synthesis more generally, we will need to
13524 // apply the temporary materialization conversion to the operands.
13525 assert(LHS->isGLValue() && RHS->isGLValue() &&
13526 "cannot use prvalue expressions more than once");
13527 Expr *OrigLHS = LHS;
13528 Expr *OrigRHS = RHS;
13530 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
13531 // each of them multiple times below.
13532 LHS = new (Context)
13533 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
13534 LHS->getObjectKind(), LHS);
13535 RHS = new (Context)
13536 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
13537 RHS->getObjectKind(), RHS);
13539 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
13541 if (Eq.isInvalid())
13542 return ExprError();
13544 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
13545 true, DefaultedFn);
13546 if (Less.isInvalid())
13547 return ExprError();
13549 ExprResult Greater;
13550 if (Info->isPartial()) {
13551 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
13553 if (Greater.isInvalid())
13554 return ExprError();
13557 // Form the list of comparisons we're going to perform.
13558 struct Comparison {
13560 ComparisonCategoryResult Result;
13562 { {Eq, Info->isStrong() ? ComparisonCategoryResult::Equal
13563 : ComparisonCategoryResult::Equivalent},
13564 {Less, ComparisonCategoryResult::Less},
13565 {Greater, ComparisonCategoryResult::Greater},
13566 {ExprResult(), ComparisonCategoryResult::Unordered},
13569 int I = Info->isPartial() ? 3 : 2;
13571 // Combine the comparisons with suitable conditional expressions.
13573 for (; I >= 0; --I) {
13574 // Build a reference to the comparison category constant.
13575 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
13576 // FIXME: Missing a constant for a comparison category. Diagnose this?
13578 return ExprResult((Expr*)nullptr);
13579 ExprResult ThisResult =
13580 BuildDeclarationNameExpr(CXXScopeSpec(), DeclarationNameInfo(), VI->VD);
13581 if (ThisResult.isInvalid())
13582 return ExprError();
13584 // Build a conditional unless this is the final case.
13585 if (Result.get()) {
13586 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
13587 ThisResult.get(), Result.get());
13588 if (Result.isInvalid())
13589 return ExprError();
13591 Result = ThisResult;
13595 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
13596 // bind the OpaqueValueExprs before they're (repeatedly) used.
13597 Expr *SyntacticForm = new (Context)
13598 BinaryOperator(OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
13599 Result.get()->getValueKind(),
13600 Result.get()->getObjectKind(), OpLoc, FPFeatures);
13601 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
13602 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
13606 Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
13607 SourceLocation RLoc,
13608 Expr *Base, Expr *Idx) {
13609 Expr *Args[2] = { Base, Idx };
13610 DeclarationName OpName =
13611 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
13613 // If either side is type-dependent, create an appropriate dependent
13615 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
13617 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
13618 // CHECKME: no 'operator' keyword?
13619 DeclarationNameInfo OpNameInfo(OpName, LLoc);
13620 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13621 UnresolvedLookupExpr *Fn
13622 = UnresolvedLookupExpr::Create(Context, NamingClass,
13623 NestedNameSpecifierLoc(), OpNameInfo,
13624 /*ADL*/ true, /*Overloaded*/ false,
13625 UnresolvedSetIterator(),
13626 UnresolvedSetIterator());
13627 // Can't add any actual overloads yet
13629 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args,
13630 Context.DependentTy, VK_RValue, RLoc,
13634 // Handle placeholders on both operands.
13635 if (checkPlaceholderForOverload(*this, Args[0]))
13636 return ExprError();
13637 if (checkPlaceholderForOverload(*this, Args[1]))
13638 return ExprError();
13640 // Build an empty overload set.
13641 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
13643 // Subscript can only be overloaded as a member function.
13645 // Add operator candidates that are member functions.
13646 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13648 // Add builtin operator candidates.
13649 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
13651 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13653 // Perform overload resolution.
13654 OverloadCandidateSet::iterator Best;
13655 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
13657 // We found a built-in operator or an overloaded operator.
13658 FunctionDecl *FnDecl = Best->Function;
13661 // We matched an overloaded operator. Build a call to that
13664 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
13666 // Convert the arguments.
13667 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
13669 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
13670 Best->FoundDecl, Method);
13671 if (Arg0.isInvalid())
13672 return ExprError();
13673 Args[0] = Arg0.get();
13675 // Convert the arguments.
13676 ExprResult InputInit
13677 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13679 FnDecl->getParamDecl(0)),
13682 if (InputInit.isInvalid())
13683 return ExprError();
13685 Args[1] = InputInit.getAs<Expr>();
13687 // Build the actual expression node.
13688 DeclarationNameInfo OpLocInfo(OpName, LLoc);
13689 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
13690 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
13693 HadMultipleCandidates,
13694 OpLocInfo.getLoc(),
13695 OpLocInfo.getInfo());
13696 if (FnExpr.isInvalid())
13697 return ExprError();
13699 // Determine the result type
13700 QualType ResultTy = FnDecl->getReturnType();
13701 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13702 ResultTy = ResultTy.getNonLValueExprType(Context);
13704 CXXOperatorCallExpr *TheCall =
13705 CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(),
13706 Args, ResultTy, VK, RLoc, FPOptions());
13708 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
13709 return ExprError();
13711 if (CheckFunctionCall(Method, TheCall,
13712 Method->getType()->castAs<FunctionProtoType>()))
13713 return ExprError();
13715 return MaybeBindToTemporary(TheCall);
13717 // We matched a built-in operator. Convert the arguments, then
13718 // break out so that we will build the appropriate built-in
13720 ExprResult ArgsRes0 = PerformImplicitConversion(
13721 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
13722 AA_Passing, CCK_ForBuiltinOverloadedOp);
13723 if (ArgsRes0.isInvalid())
13724 return ExprError();
13725 Args[0] = ArgsRes0.get();
13727 ExprResult ArgsRes1 = PerformImplicitConversion(
13728 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
13729 AA_Passing, CCK_ForBuiltinOverloadedOp);
13730 if (ArgsRes1.isInvalid())
13731 return ExprError();
13732 Args[1] = ArgsRes1.get();
13738 case OR_No_Viable_Function: {
13739 PartialDiagnostic PD = CandidateSet.empty()
13740 ? (PDiag(diag::err_ovl_no_oper)
13741 << Args[0]->getType() << /*subscript*/ 0
13742 << Args[0]->getSourceRange() << Args[1]->getSourceRange())
13743 : (PDiag(diag::err_ovl_no_viable_subscript)
13744 << Args[0]->getType() << Args[0]->getSourceRange()
13745 << Args[1]->getSourceRange());
13746 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
13747 OCD_AllCandidates, Args, "[]", LLoc);
13748 return ExprError();
13752 CandidateSet.NoteCandidates(
13753 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
13754 << "[]" << Args[0]->getType()
13755 << Args[1]->getType()
13756 << Args[0]->getSourceRange()
13757 << Args[1]->getSourceRange()),
13758 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
13759 return ExprError();
13762 CandidateSet.NoteCandidates(
13763 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
13764 << "[]" << Args[0]->getSourceRange()
13765 << Args[1]->getSourceRange()),
13766 *this, OCD_AllCandidates, Args, "[]", LLoc);
13767 return ExprError();
13770 // We matched a built-in operator; build it.
13771 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
13774 /// BuildCallToMemberFunction - Build a call to a member
13775 /// function. MemExpr is the expression that refers to the member
13776 /// function (and includes the object parameter), Args/NumArgs are the
13777 /// arguments to the function call (not including the object
13778 /// parameter). The caller needs to validate that the member
13779 /// expression refers to a non-static member function or an overloaded
13780 /// member function.
13782 Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
13783 SourceLocation LParenLoc,
13785 SourceLocation RParenLoc) {
13786 assert(MemExprE->getType() == Context.BoundMemberTy ||
13787 MemExprE->getType() == Context.OverloadTy);
13789 // Dig out the member expression. This holds both the object
13790 // argument and the member function we're referring to.
13791 Expr *NakedMemExpr = MemExprE->IgnoreParens();
13793 // Determine whether this is a call to a pointer-to-member function.
13794 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
13795 assert(op->getType() == Context.BoundMemberTy);
13796 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
13799 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
13801 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
13802 QualType resultType = proto->getCallResultType(Context);
13803 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
13805 // Check that the object type isn't more qualified than the
13806 // member function we're calling.
13807 Qualifiers funcQuals = proto->getMethodQuals();
13809 QualType objectType = op->getLHS()->getType();
13810 if (op->getOpcode() == BO_PtrMemI)
13811 objectType = objectType->castAs<PointerType>()->getPointeeType();
13812 Qualifiers objectQuals = objectType.getQualifiers();
13814 Qualifiers difference = objectQuals - funcQuals;
13815 difference.removeObjCGCAttr();
13816 difference.removeAddressSpace();
13818 std::string qualsString = difference.getAsString();
13819 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
13820 << fnType.getUnqualifiedType()
13822 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
13825 CXXMemberCallExpr *call =
13826 CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType,
13827 valueKind, RParenLoc, proto->getNumParams());
13829 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
13831 return ExprError();
13833 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
13834 return ExprError();
13836 if (CheckOtherCall(call, proto))
13837 return ExprError();
13839 return MaybeBindToTemporary(call);
13842 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
13843 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
13846 UnbridgedCastsSet UnbridgedCasts;
13847 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13848 return ExprError();
13850 MemberExpr *MemExpr;
13851 CXXMethodDecl *Method = nullptr;
13852 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
13853 NestedNameSpecifier *Qualifier = nullptr;
13854 if (isa<MemberExpr>(NakedMemExpr)) {
13855 MemExpr = cast<MemberExpr>(NakedMemExpr);
13856 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
13857 FoundDecl = MemExpr->getFoundDecl();
13858 Qualifier = MemExpr->getQualifier();
13859 UnbridgedCasts.restore();
13861 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
13862 Qualifier = UnresExpr->getQualifier();
13864 QualType ObjectType = UnresExpr->getBaseType();
13865 Expr::Classification ObjectClassification
13866 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
13867 : UnresExpr->getBase()->Classify(Context);
13869 // Add overload candidates
13870 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
13871 OverloadCandidateSet::CSK_Normal);
13873 // FIXME: avoid copy.
13874 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13875 if (UnresExpr->hasExplicitTemplateArgs()) {
13876 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13877 TemplateArgs = &TemplateArgsBuffer;
13880 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
13881 E = UnresExpr->decls_end(); I != E; ++I) {
13883 NamedDecl *Func = *I;
13884 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
13885 if (isa<UsingShadowDecl>(Func))
13886 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
13889 // Microsoft supports direct constructor calls.
13890 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
13891 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
13893 /*SuppressUserConversions*/ false);
13894 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
13895 // If explicit template arguments were provided, we can't call a
13896 // non-template member function.
13900 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
13901 ObjectClassification, Args, CandidateSet,
13902 /*SuppressUserConversions=*/false);
13904 AddMethodTemplateCandidate(
13905 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
13906 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
13907 /*SuppressUserConversions=*/false);
13911 DeclarationName DeclName = UnresExpr->getMemberName();
13913 UnbridgedCasts.restore();
13915 OverloadCandidateSet::iterator Best;
13916 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
13919 Method = cast<CXXMethodDecl>(Best->Function);
13920 FoundDecl = Best->FoundDecl;
13921 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
13922 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
13923 return ExprError();
13924 // If FoundDecl is different from Method (such as if one is a template
13925 // and the other a specialization), make sure DiagnoseUseOfDecl is
13927 // FIXME: This would be more comprehensively addressed by modifying
13928 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
13930 if (Method != FoundDecl.getDecl() &&
13931 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
13932 return ExprError();
13935 case OR_No_Viable_Function:
13936 CandidateSet.NoteCandidates(
13937 PartialDiagnosticAt(
13938 UnresExpr->getMemberLoc(),
13939 PDiag(diag::err_ovl_no_viable_member_function_in_call)
13940 << DeclName << MemExprE->getSourceRange()),
13941 *this, OCD_AllCandidates, Args);
13942 // FIXME: Leaking incoming expressions!
13943 return ExprError();
13946 CandidateSet.NoteCandidates(
13947 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13948 PDiag(diag::err_ovl_ambiguous_member_call)
13949 << DeclName << MemExprE->getSourceRange()),
13950 *this, OCD_AmbiguousCandidates, Args);
13951 // FIXME: Leaking incoming expressions!
13952 return ExprError();
13955 CandidateSet.NoteCandidates(
13956 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13957 PDiag(diag::err_ovl_deleted_member_call)
13958 << DeclName << MemExprE->getSourceRange()),
13959 *this, OCD_AllCandidates, Args);
13960 // FIXME: Leaking incoming expressions!
13961 return ExprError();
13964 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
13966 // If overload resolution picked a static member, build a
13967 // non-member call based on that function.
13968 if (Method->isStatic()) {
13969 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
13973 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
13976 QualType ResultType = Method->getReturnType();
13977 ExprValueKind VK = Expr::getValueKindForType(ResultType);
13978 ResultType = ResultType.getNonLValueExprType(Context);
13980 assert(Method && "Member call to something that isn't a method?");
13981 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
13982 CXXMemberCallExpr *TheCall =
13983 CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
13984 RParenLoc, Proto->getNumParams());
13986 // Check for a valid return type.
13987 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
13989 return ExprError();
13991 // Convert the object argument (for a non-static member function call).
13992 // We only need to do this if there was actually an overload; otherwise
13993 // it was done at lookup.
13994 if (!Method->isStatic()) {
13995 ExprResult ObjectArg =
13996 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
13997 FoundDecl, Method);
13998 if (ObjectArg.isInvalid())
13999 return ExprError();
14000 MemExpr->setBase(ObjectArg.get());
14003 // Convert the rest of the arguments
14004 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
14006 return ExprError();
14008 DiagnoseSentinelCalls(Method, LParenLoc, Args);
14010 if (CheckFunctionCall(Method, TheCall, Proto))
14011 return ExprError();
14013 // In the case the method to call was not selected by the overloading
14014 // resolution process, we still need to handle the enable_if attribute. Do
14015 // that here, so it will not hide previous -- and more relevant -- errors.
14016 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
14017 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
14018 Diag(MemE->getMemberLoc(),
14019 diag::err_ovl_no_viable_member_function_in_call)
14020 << Method << Method->getSourceRange();
14021 Diag(Method->getLocation(),
14022 diag::note_ovl_candidate_disabled_by_function_cond_attr)
14023 << Attr->getCond()->getSourceRange() << Attr->getMessage();
14024 return ExprError();
14028 if ((isa<CXXConstructorDecl>(CurContext) ||
14029 isa<CXXDestructorDecl>(CurContext)) &&
14030 TheCall->getMethodDecl()->isPure()) {
14031 const CXXMethodDecl *MD = TheCall->getMethodDecl();
14033 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
14034 MemExpr->performsVirtualDispatch(getLangOpts())) {
14035 Diag(MemExpr->getBeginLoc(),
14036 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
14037 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
14038 << MD->getParent()->getDeclName();
14040 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
14041 if (getLangOpts().AppleKext)
14042 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
14043 << MD->getParent()->getDeclName() << MD->getDeclName();
14047 if (CXXDestructorDecl *DD =
14048 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
14049 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
14050 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
14051 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
14052 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
14053 MemExpr->getMemberLoc());
14056 return MaybeBindToTemporary(TheCall);
14059 /// BuildCallToObjectOfClassType - Build a call to an object of class
14060 /// type (C++ [over.call.object]), which can end up invoking an
14061 /// overloaded function call operator (@c operator()) or performing a
14062 /// user-defined conversion on the object argument.
14064 Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
14065 SourceLocation LParenLoc,
14067 SourceLocation RParenLoc) {
14068 if (checkPlaceholderForOverload(*this, Obj))
14069 return ExprError();
14070 ExprResult Object = Obj;
14072 UnbridgedCastsSet UnbridgedCasts;
14073 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
14074 return ExprError();
14076 assert(Object.get()->getType()->isRecordType() &&
14077 "Requires object type argument");
14079 // C++ [over.call.object]p1:
14080 // If the primary-expression E in the function call syntax
14081 // evaluates to a class object of type "cv T", then the set of
14082 // candidate functions includes at least the function call
14083 // operators of T. The function call operators of T are obtained by
14084 // ordinary lookup of the name operator() in the context of
14086 OverloadCandidateSet CandidateSet(LParenLoc,
14087 OverloadCandidateSet::CSK_Operator);
14088 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
14090 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
14091 diag::err_incomplete_object_call, Object.get()))
14094 const auto *Record = Object.get()->getType()->castAs<RecordType>();
14095 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
14096 LookupQualifiedName(R, Record->getDecl());
14097 R.suppressDiagnostics();
14099 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14100 Oper != OperEnd; ++Oper) {
14101 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
14102 Object.get()->Classify(Context), Args, CandidateSet,
14103 /*SuppressUserConversion=*/false);
14106 // C++ [over.call.object]p2:
14107 // In addition, for each (non-explicit in C++0x) conversion function
14108 // declared in T of the form
14110 // operator conversion-type-id () cv-qualifier;
14112 // where cv-qualifier is the same cv-qualification as, or a
14113 // greater cv-qualification than, cv, and where conversion-type-id
14114 // denotes the type "pointer to function of (P1,...,Pn) returning
14115 // R", or the type "reference to pointer to function of
14116 // (P1,...,Pn) returning R", or the type "reference to function
14117 // of (P1,...,Pn) returning R", a surrogate call function [...]
14118 // is also considered as a candidate function. Similarly,
14119 // surrogate call functions are added to the set of candidate
14120 // functions for each conversion function declared in an
14121 // accessible base class provided the function is not hidden
14122 // within T by another intervening declaration.
14123 const auto &Conversions =
14124 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
14125 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
14127 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
14128 if (isa<UsingShadowDecl>(D))
14129 D = cast<UsingShadowDecl>(D)->getTargetDecl();
14131 // Skip over templated conversion functions; they aren't
14133 if (isa<FunctionTemplateDecl>(D))
14136 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
14137 if (!Conv->isExplicit()) {
14138 // Strip the reference type (if any) and then the pointer type (if
14139 // any) to get down to what might be a function type.
14140 QualType ConvType = Conv->getConversionType().getNonReferenceType();
14141 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
14142 ConvType = ConvPtrType->getPointeeType();
14144 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
14146 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
14147 Object.get(), Args, CandidateSet);
14152 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14154 // Perform overload resolution.
14155 OverloadCandidateSet::iterator Best;
14156 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
14159 // Overload resolution succeeded; we'll build the appropriate call
14163 case OR_No_Viable_Function: {
14164 PartialDiagnostic PD =
14165 CandidateSet.empty()
14166 ? (PDiag(diag::err_ovl_no_oper)
14167 << Object.get()->getType() << /*call*/ 1
14168 << Object.get()->getSourceRange())
14169 : (PDiag(diag::err_ovl_no_viable_object_call)
14170 << Object.get()->getType() << Object.get()->getSourceRange());
14171 CandidateSet.NoteCandidates(
14172 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
14173 OCD_AllCandidates, Args);
14177 CandidateSet.NoteCandidates(
14178 PartialDiagnosticAt(Object.get()->getBeginLoc(),
14179 PDiag(diag::err_ovl_ambiguous_object_call)
14180 << Object.get()->getType()
14181 << Object.get()->getSourceRange()),
14182 *this, OCD_AmbiguousCandidates, Args);
14186 CandidateSet.NoteCandidates(
14187 PartialDiagnosticAt(Object.get()->getBeginLoc(),
14188 PDiag(diag::err_ovl_deleted_object_call)
14189 << Object.get()->getType()
14190 << Object.get()->getSourceRange()),
14191 *this, OCD_AllCandidates, Args);
14195 if (Best == CandidateSet.end())
14198 UnbridgedCasts.restore();
14200 if (Best->Function == nullptr) {
14201 // Since there is no function declaration, this is one of the
14202 // surrogate candidates. Dig out the conversion function.
14203 CXXConversionDecl *Conv
14204 = cast<CXXConversionDecl>(
14205 Best->Conversions[0].UserDefined.ConversionFunction);
14207 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
14209 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
14210 return ExprError();
14211 assert(Conv == Best->FoundDecl.getDecl() &&
14212 "Found Decl & conversion-to-functionptr should be same, right?!");
14213 // We selected one of the surrogate functions that converts the
14214 // object parameter to a function pointer. Perform the conversion
14215 // on the object argument, then let BuildCallExpr finish the job.
14217 // Create an implicit member expr to refer to the conversion operator.
14218 // and then call it.
14219 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
14220 Conv, HadMultipleCandidates);
14221 if (Call.isInvalid())
14222 return ExprError();
14223 // Record usage of conversion in an implicit cast.
14224 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
14225 CK_UserDefinedConversion, Call.get(),
14226 nullptr, VK_RValue);
14228 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
14231 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
14233 // We found an overloaded operator(). Build a CXXOperatorCallExpr
14234 // that calls this method, using Object for the implicit object
14235 // parameter and passing along the remaining arguments.
14236 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14238 // An error diagnostic has already been printed when parsing the declaration.
14239 if (Method->isInvalidDecl())
14240 return ExprError();
14242 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
14243 unsigned NumParams = Proto->getNumParams();
14245 DeclarationNameInfo OpLocInfo(
14246 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
14247 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
14248 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14249 Obj, HadMultipleCandidates,
14250 OpLocInfo.getLoc(),
14251 OpLocInfo.getInfo());
14252 if (NewFn.isInvalid())
14255 // The number of argument slots to allocate in the call. If we have default
14256 // arguments we need to allocate space for them as well. We additionally
14257 // need one more slot for the object parameter.
14258 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
14260 // Build the full argument list for the method call (the implicit object
14261 // parameter is placed at the beginning of the list).
14262 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
14264 bool IsError = false;
14266 // Initialize the implicit object parameter.
14267 ExprResult ObjRes =
14268 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
14269 Best->FoundDecl, Method);
14270 if (ObjRes.isInvalid())
14274 MethodArgs[0] = Object.get();
14276 // Check the argument types.
14277 for (unsigned i = 0; i != NumParams; i++) {
14279 if (i < Args.size()) {
14282 // Pass the argument.
14284 ExprResult InputInit
14285 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
14287 Method->getParamDecl(i)),
14288 SourceLocation(), Arg);
14290 IsError |= InputInit.isInvalid();
14291 Arg = InputInit.getAs<Expr>();
14294 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
14295 if (DefArg.isInvalid()) {
14300 Arg = DefArg.getAs<Expr>();
14303 MethodArgs[i + 1] = Arg;
14306 // If this is a variadic call, handle args passed through "...".
14307 if (Proto->isVariadic()) {
14308 // Promote the arguments (C99 6.5.2.2p7).
14309 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
14310 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
14312 IsError |= Arg.isInvalid();
14313 MethodArgs[i + 1] = Arg.get();
14320 DiagnoseSentinelCalls(Method, LParenLoc, Args);
14322 // Once we've built TheCall, all of the expressions are properly owned.
14323 QualType ResultTy = Method->getReturnType();
14324 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14325 ResultTy = ResultTy.getNonLValueExprType(Context);
14327 CXXOperatorCallExpr *TheCall =
14328 CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs,
14329 ResultTy, VK, RParenLoc, FPOptions());
14331 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
14334 if (CheckFunctionCall(Method, TheCall, Proto))
14337 return MaybeBindToTemporary(TheCall);
14340 /// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
14341 /// (if one exists), where @c Base is an expression of class type and
14342 /// @c Member is the name of the member we're trying to find.
14344 Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
14345 bool *NoArrowOperatorFound) {
14346 assert(Base->getType()->isRecordType() &&
14347 "left-hand side must have class type");
14349 if (checkPlaceholderForOverload(*this, Base))
14350 return ExprError();
14352 SourceLocation Loc = Base->getExprLoc();
14354 // C++ [over.ref]p1:
14356 // [...] An expression x->m is interpreted as (x.operator->())->m
14357 // for a class object x of type T if T::operator->() exists and if
14358 // the operator is selected as the best match function by the
14359 // overload resolution mechanism (13.3).
14360 DeclarationName OpName =
14361 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
14362 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
14364 if (RequireCompleteType(Loc, Base->getType(),
14365 diag::err_typecheck_incomplete_tag, Base))
14366 return ExprError();
14368 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
14369 LookupQualifiedName(R, Base->getType()->castAs<RecordType>()->getDecl());
14370 R.suppressDiagnostics();
14372 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
14373 Oper != OperEnd; ++Oper) {
14374 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
14375 None, CandidateSet, /*SuppressUserConversion=*/false);
14378 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14380 // Perform overload resolution.
14381 OverloadCandidateSet::iterator Best;
14382 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
14384 // Overload resolution succeeded; we'll build the call below.
14387 case OR_No_Viable_Function: {
14388 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
14389 if (CandidateSet.empty()) {
14390 QualType BaseType = Base->getType();
14391 if (NoArrowOperatorFound) {
14392 // Report this specific error to the caller instead of emitting a
14393 // diagnostic, as requested.
14394 *NoArrowOperatorFound = true;
14395 return ExprError();
14397 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
14398 << BaseType << Base->getSourceRange();
14399 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
14400 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
14401 << FixItHint::CreateReplacement(OpLoc, ".");
14404 Diag(OpLoc, diag::err_ovl_no_viable_oper)
14405 << "operator->" << Base->getSourceRange();
14406 CandidateSet.NoteCandidates(*this, Base, Cands);
14407 return ExprError();
14410 CandidateSet.NoteCandidates(
14411 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
14412 << "->" << Base->getType()
14413 << Base->getSourceRange()),
14414 *this, OCD_AmbiguousCandidates, Base);
14415 return ExprError();
14418 CandidateSet.NoteCandidates(
14419 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
14420 << "->" << Base->getSourceRange()),
14421 *this, OCD_AllCandidates, Base);
14422 return ExprError();
14425 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
14427 // Convert the object parameter.
14428 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
14429 ExprResult BaseResult =
14430 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
14431 Best->FoundDecl, Method);
14432 if (BaseResult.isInvalid())
14433 return ExprError();
14434 Base = BaseResult.get();
14436 // Build the operator call.
14437 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
14438 Base, HadMultipleCandidates, OpLoc);
14439 if (FnExpr.isInvalid())
14440 return ExprError();
14442 QualType ResultTy = Method->getReturnType();
14443 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14444 ResultTy = ResultTy.getNonLValueExprType(Context);
14445 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
14446 Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions());
14448 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
14449 return ExprError();
14451 if (CheckFunctionCall(Method, TheCall,
14452 Method->getType()->castAs<FunctionProtoType>()))
14453 return ExprError();
14455 return MaybeBindToTemporary(TheCall);
14458 /// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
14459 /// a literal operator described by the provided lookup results.
14460 ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
14461 DeclarationNameInfo &SuffixInfo,
14462 ArrayRef<Expr*> Args,
14463 SourceLocation LitEndLoc,
14464 TemplateArgumentListInfo *TemplateArgs) {
14465 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
14467 OverloadCandidateSet CandidateSet(UDSuffixLoc,
14468 OverloadCandidateSet::CSK_Normal);
14469 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
14472 bool HadMultipleCandidates = (CandidateSet.size() > 1);
14474 // Perform overload resolution. This will usually be trivial, but might need
14475 // to perform substitutions for a literal operator template.
14476 OverloadCandidateSet::iterator Best;
14477 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
14482 case OR_No_Viable_Function:
14483 CandidateSet.NoteCandidates(
14484 PartialDiagnosticAt(UDSuffixLoc,
14485 PDiag(diag::err_ovl_no_viable_function_in_call)
14486 << R.getLookupName()),
14487 *this, OCD_AllCandidates, Args);
14488 return ExprError();
14491 CandidateSet.NoteCandidates(
14492 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
14493 << R.getLookupName()),
14494 *this, OCD_AmbiguousCandidates, Args);
14495 return ExprError();
14498 FunctionDecl *FD = Best->Function;
14499 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
14500 nullptr, HadMultipleCandidates,
14501 SuffixInfo.getLoc(),
14502 SuffixInfo.getInfo());
14503 if (Fn.isInvalid())
14506 // Check the argument types. This should almost always be a no-op, except
14507 // that array-to-pointer decay is applied to string literals.
14509 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
14510 ExprResult InputInit = PerformCopyInitialization(
14511 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
14512 SourceLocation(), Args[ArgIdx]);
14513 if (InputInit.isInvalid())
14515 ConvArgs[ArgIdx] = InputInit.get();
14518 QualType ResultTy = FD->getReturnType();
14519 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
14520 ResultTy = ResultTy.getNonLValueExprType(Context);
14522 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
14523 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
14524 VK, LitEndLoc, UDSuffixLoc);
14526 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
14527 return ExprError();
14529 if (CheckFunctionCall(FD, UDL, nullptr))
14530 return ExprError();
14532 return MaybeBindToTemporary(UDL);
14535 /// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
14536 /// given LookupResult is non-empty, it is assumed to describe a member which
14537 /// will be invoked. Otherwise, the function will be found via argument
14538 /// dependent lookup.
14539 /// CallExpr is set to a valid expression and FRS_Success returned on success,
14540 /// otherwise CallExpr is set to ExprError() and some non-success value
14542 Sema::ForRangeStatus
14543 Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
14544 SourceLocation RangeLoc,
14545 const DeclarationNameInfo &NameInfo,
14546 LookupResult &MemberLookup,
14547 OverloadCandidateSet *CandidateSet,
14548 Expr *Range, ExprResult *CallExpr) {
14549 Scope *S = nullptr;
14551 CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
14552 if (!MemberLookup.empty()) {
14553 ExprResult MemberRef =
14554 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
14555 /*IsPtr=*/false, CXXScopeSpec(),
14556 /*TemplateKWLoc=*/SourceLocation(),
14557 /*FirstQualifierInScope=*/nullptr,
14559 /*TemplateArgs=*/nullptr, S);
14560 if (MemberRef.isInvalid()) {
14561 *CallExpr = ExprError();
14562 return FRS_DiagnosticIssued;
14564 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
14565 if (CallExpr->isInvalid()) {
14566 *CallExpr = ExprError();
14567 return FRS_DiagnosticIssued;
14570 UnresolvedSet<0> FoundNames;
14571 UnresolvedLookupExpr *Fn =
14572 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
14573 NestedNameSpecifierLoc(), NameInfo,
14574 /*NeedsADL=*/true, /*Overloaded=*/false,
14575 FoundNames.begin(), FoundNames.end());
14577 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
14578 CandidateSet, CallExpr);
14579 if (CandidateSet->empty() || CandidateSetError) {
14580 *CallExpr = ExprError();
14581 return FRS_NoViableFunction;
14583 OverloadCandidateSet::iterator Best;
14584 OverloadingResult OverloadResult =
14585 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
14587 if (OverloadResult == OR_No_Viable_Function) {
14588 *CallExpr = ExprError();
14589 return FRS_NoViableFunction;
14591 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
14592 Loc, nullptr, CandidateSet, &Best,
14594 /*AllowTypoCorrection=*/false);
14595 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
14596 *CallExpr = ExprError();
14597 return FRS_DiagnosticIssued;
14600 return FRS_Success;
14604 /// FixOverloadedFunctionReference - E is an expression that refers to
14605 /// a C++ overloaded function (possibly with some parentheses and
14606 /// perhaps a '&' around it). We have resolved the overloaded function
14607 /// to the function declaration Fn, so patch up the expression E to
14608 /// refer (possibly indirectly) to Fn. Returns the new expr.
14609 Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
14610 FunctionDecl *Fn) {
14611 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
14612 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
14614 if (SubExpr == PE->getSubExpr())
14617 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
14620 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
14621 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
14623 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
14624 SubExpr->getType()) &&
14625 "Implicit cast type cannot be determined from overload");
14626 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
14627 if (SubExpr == ICE->getSubExpr())
14630 return ImplicitCastExpr::Create(Context, ICE->getType(),
14631 ICE->getCastKind(),
14633 ICE->getValueKind());
14636 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
14637 if (!GSE->isResultDependent()) {
14639 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
14640 if (SubExpr == GSE->getResultExpr())
14643 // Replace the resulting type information before rebuilding the generic
14644 // selection expression.
14645 ArrayRef<Expr *> A = GSE->getAssocExprs();
14646 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
14647 unsigned ResultIdx = GSE->getResultIndex();
14648 AssocExprs[ResultIdx] = SubExpr;
14650 return GenericSelectionExpr::Create(
14651 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
14652 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
14653 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
14656 // Rather than fall through to the unreachable, return the original generic
14657 // selection expression.
14661 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
14662 assert(UnOp->getOpcode() == UO_AddrOf &&
14663 "Can only take the address of an overloaded function");
14664 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
14665 if (Method->isStatic()) {
14666 // Do nothing: static member functions aren't any different
14667 // from non-member functions.
14669 // Fix the subexpression, which really has to be an
14670 // UnresolvedLookupExpr holding an overloaded member function
14672 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14674 if (SubExpr == UnOp->getSubExpr())
14677 assert(isa<DeclRefExpr>(SubExpr)
14678 && "fixed to something other than a decl ref");
14679 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
14680 && "fixed to a member ref with no nested name qualifier");
14682 // We have taken the address of a pointer to member
14683 // function. Perform the computation here so that we get the
14684 // appropriate pointer to member type.
14686 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
14687 QualType MemPtrType
14688 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
14689 // Under the MS ABI, lock down the inheritance model now.
14690 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
14691 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
14693 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
14694 VK_RValue, OK_Ordinary,
14695 UnOp->getOperatorLoc(), false);
14698 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
14700 if (SubExpr == UnOp->getSubExpr())
14703 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
14704 Context.getPointerType(SubExpr->getType()),
14705 VK_RValue, OK_Ordinary,
14706 UnOp->getOperatorLoc(), false);
14709 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
14710 // FIXME: avoid copy.
14711 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14712 if (ULE->hasExplicitTemplateArgs()) {
14713 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
14714 TemplateArgs = &TemplateArgsBuffer;
14718 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
14719 ULE->getQualifierLoc(), Found.getDecl(),
14720 ULE->getTemplateKeywordLoc(), TemplateArgs);
14721 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
14725 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
14726 // FIXME: avoid copy.
14727 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
14728 if (MemExpr->hasExplicitTemplateArgs()) {
14729 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
14730 TemplateArgs = &TemplateArgsBuffer;
14735 // If we're filling in a static method where we used to have an
14736 // implicit member access, rewrite to a simple decl ref.
14737 if (MemExpr->isImplicitAccess()) {
14738 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14739 DeclRefExpr *DRE = BuildDeclRefExpr(
14740 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
14741 MemExpr->getQualifierLoc(), Found.getDecl(),
14742 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
14743 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
14746 SourceLocation Loc = MemExpr->getMemberLoc();
14747 if (MemExpr->getQualifier())
14748 Loc = MemExpr->getQualifierLoc().getBeginLoc();
14750 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
14753 Base = MemExpr->getBase();
14755 ExprValueKind valueKind;
14757 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
14758 valueKind = VK_LValue;
14759 type = Fn->getType();
14761 valueKind = VK_RValue;
14762 type = Context.BoundMemberTy;
14765 return BuildMemberExpr(
14766 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
14767 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
14768 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
14769 type, valueKind, OK_Ordinary, TemplateArgs);
14772 llvm_unreachable("Invalid reference to overloaded function");
14775 ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
14776 DeclAccessPair Found,
14777 FunctionDecl *Fn) {
14778 return FixOverloadedFunctionReference(E.get(), Found, Fn);