clang 23.0.0git
SemaOverload.cpp
Go to the documentation of this file.
1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ overloading.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CheckExprLifetime.h"
16#include "clang/AST/Decl.h"
17#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/AST/Type.h"
31#include "clang/Sema/Lookup.h"
32#include "clang/Sema/Overload.h"
34#include "clang/Sema/SemaARM.h"
35#include "clang/Sema/SemaCUDA.h"
37#include "clang/Sema/SemaObjC.h"
38#include "clang/Sema/Template.h"
40#include "llvm/ADT/DenseSet.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/STLForwardCompat.h"
43#include "llvm/ADT/ScopeExit.h"
44#include "llvm/ADT/SmallPtrSet.h"
45#include "llvm/ADT/SmallVector.h"
46#include <algorithm>
47#include <cassert>
48#include <cstddef>
49#include <cstdlib>
50#include <optional>
51
52using namespace clang;
53using namespace sema;
54
56
58 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
59 return P->hasAttr<PassObjectSizeAttr>();
60 });
61}
62
63/// A convenience routine for creating a decayed reference to a function.
65 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
66 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
67 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
68 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
69 return ExprError();
70 // If FoundDecl is different from Fn (such as if one is a template
71 // and the other a specialization), make sure DiagnoseUseOfDecl is
72 // called on both.
73 // FIXME: This would be more comprehensively addressed by modifying
74 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
75 // being used.
76 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
77 return ExprError();
78 DeclRefExpr *DRE = new (S.Context)
79 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
80 if (HadMultipleCandidates)
81 DRE->setHadMultipleCandidates(true);
82
84 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
85 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
86 S.ResolveExceptionSpec(Loc, FPT);
87 DRE->setType(Fn->getType());
88 }
89 }
90 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
91 CK_FunctionToPointerDecay);
92}
93
94static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
95 bool InOverloadResolution,
97 bool CStyle,
98 bool AllowObjCWritebackConversion);
99
101 QualType &ToType,
102 bool InOverloadResolution,
104 bool CStyle);
106IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
108 OverloadCandidateSet& Conversions,
109 AllowedExplicit AllowExplicit,
110 bool AllowObjCConversionOnExplicit);
111
114 const StandardConversionSequence& SCS1,
115 const StandardConversionSequence& SCS2);
116
119 const StandardConversionSequence& SCS1,
120 const StandardConversionSequence& SCS2);
121
124 const StandardConversionSequence &SCS1,
125 const StandardConversionSequence &SCS2);
126
129 const StandardConversionSequence& SCS1,
130 const StandardConversionSequence& SCS2);
131
132/// GetConversionRank - Retrieve the implicit conversion rank
133/// corresponding to the given implicit conversion kind.
135 static const ImplicitConversionRank Rank[] = {
162 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
163 // it was omitted by the patch that added
164 // ICK_Zero_Event_Conversion
165 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
166 // it was omitted by the patch that added
167 // ICK_Zero_Queue_Conversion
176 };
177 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
178 return Rank[(int)Kind];
179}
180
199
200/// GetImplicitConversionName - Return the name of this kind of
201/// implicit conversion.
203 static const char *const Name[] = {
204 "No conversion",
205 "Lvalue-to-rvalue",
206 "Array-to-pointer",
207 "Function-to-pointer",
208 "Function pointer conversion",
209 "Qualification",
210 "Integral promotion",
211 "Floating point promotion",
212 "Complex promotion",
213 "Integral conversion",
214 "Floating conversion",
215 "Complex conversion",
216 "Floating-integral conversion",
217 "Pointer conversion",
218 "Pointer-to-member conversion",
219 "Boolean conversion",
220 "Compatible-types conversion",
221 "Derived-to-base conversion",
222 "Vector conversion",
223 "SVE Vector conversion",
224 "RVV Vector conversion",
225 "Vector splat",
226 "Complex-real conversion",
227 "Block Pointer conversion",
228 "Transparent Union Conversion",
229 "Writeback conversion",
230 "OpenCL Zero Event Conversion",
231 "OpenCL Zero Queue Conversion",
232 "C specific type conversion",
233 "Incompatible pointer conversion",
234 "Fixed point conversion",
235 "HLSL vector truncation",
236 "HLSL matrix truncation",
237 "Non-decaying array conversion",
238 "HLSL vector splat",
239 "HLSL matrix splat",
240 };
241 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
242 return Name[Kind];
243}
244
245/// StandardConversionSequence - Set the standard conversion
246/// sequence to the identity conversion.
264
265/// getRank - Retrieve the rank of this standard conversion sequence
266/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
267/// implicit conversions.
280
281/// isPointerConversionToBool - Determines whether this conversion is
282/// a conversion of a pointer or pointer-to-member to bool. This is
283/// used as part of the ranking of standard conversion sequences
284/// (C++ 13.3.3.2p4).
286 // Note that FromType has not necessarily been transformed by the
287 // array-to-pointer or function-to-pointer implicit conversions, so
288 // check for their presence as well as checking whether FromType is
289 // a pointer.
290 if (getToType(1)->isBooleanType() &&
291 (getFromType()->isPointerType() ||
292 getFromType()->isMemberPointerType() ||
293 getFromType()->isObjCObjectPointerType() ||
294 getFromType()->isBlockPointerType() ||
296 return true;
297
298 return false;
299}
300
301/// isPointerConversionToVoidPointer - Determines whether this
302/// conversion is a conversion of a pointer to a void pointer. This is
303/// used as part of the ranking of standard conversion sequences (C++
304/// 13.3.3.2p4).
305bool
308 QualType FromType = getFromType();
309 QualType ToType = getToType(1);
310
311 // Note that FromType has not necessarily been transformed by the
312 // array-to-pointer implicit conversion, so check for its presence
313 // and redo the conversion to get a pointer.
315 FromType = Context.getArrayDecayedType(FromType);
316
317 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
318 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
319 return ToPtrType->getPointeeType()->isVoidType();
320
321 return false;
322}
323
324/// Skip any implicit casts which could be either part of a narrowing conversion
325/// or after one in an implicit conversion.
327 const Expr *Converted) {
328 // We can have cleanups wrapping the converted expression; these need to be
329 // preserved so that destructors run if necessary.
330 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
331 Expr *Inner =
332 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
333 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
334 EWC->getObjects());
335 }
336
337 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
338 switch (ICE->getCastKind()) {
339 case CK_NoOp:
340 case CK_IntegralCast:
341 case CK_IntegralToBoolean:
342 case CK_IntegralToFloating:
343 case CK_BooleanToSignedIntegral:
344 case CK_FloatingToIntegral:
345 case CK_FloatingToBoolean:
346 case CK_FloatingCast:
347 Converted = ICE->getSubExpr();
348 continue;
349
350 default:
351 return Converted;
352 }
353 }
354
355 return Converted;
356}
357
358/// Check if this standard conversion sequence represents a narrowing
359/// conversion, according to C++11 [dcl.init.list]p7.
360///
361/// \param Ctx The AST context.
362/// \param Converted The result of applying this standard conversion sequence.
363/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
364/// value of the expression prior to the narrowing conversion.
365/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
366/// type of the expression prior to the narrowing conversion.
367/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
368/// from floating point types to integral types should be ignored.
370 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
371 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
372 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
373 "narrowing check outside C++");
374
375 // C++11 [dcl.init.list]p7:
376 // A narrowing conversion is an implicit conversion ...
377 QualType FromType = getToType(0);
378 QualType ToType = getToType(1);
379
380 // A conversion to an enumeration type is narrowing if the conversion to
381 // the underlying type is narrowing. This only arises for expressions of
382 // the form 'Enum{init}'.
383 if (const auto *ED = ToType->getAsEnumDecl())
384 ToType = ED->getIntegerType();
385
386 switch (Second) {
387 // 'bool' is an integral type; dispatch to the right place to handle it.
389 if (FromType->isRealFloatingType())
390 goto FloatingIntegralConversion;
392 goto IntegralConversion;
393 // -- from a pointer type or pointer-to-member type to bool, or
394 return NK_Type_Narrowing;
395
396 // -- from a floating-point type to an integer type, or
397 //
398 // -- from an integer type or unscoped enumeration type to a floating-point
399 // type, except where the source is a constant expression and the actual
400 // value after conversion will fit into the target type and will produce
401 // the original value when converted back to the original type, or
403 FloatingIntegralConversion:
404 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
405 return NK_Type_Narrowing;
406 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
407 ToType->isRealFloatingType()) {
408 if (IgnoreFloatToIntegralConversion)
409 return NK_Not_Narrowing;
410 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
411 assert(Initializer && "Unknown conversion expression");
412
413 // If it's value-dependent, we can't tell whether it's narrowing.
414 if (Initializer->isValueDependent())
416
417 if (std::optional<llvm::APSInt> IntConstantValue =
418 Initializer->getIntegerConstantExpr(Ctx)) {
419 // Convert the integer to the floating type.
420 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
421 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
422 llvm::APFloat::rmNearestTiesToEven);
423 // And back.
424 llvm::APSInt ConvertedValue = *IntConstantValue;
425 bool ignored;
426 llvm::APFloat::opStatus Status = Result.convertToInteger(
427 ConvertedValue, llvm::APFloat::rmTowardZero, &ignored);
428 // If the converted-back integer has unspecified value, or if the
429 // resulting value is different, this was a narrowing conversion.
430 if (Status == llvm::APFloat::opInvalidOp ||
431 *IntConstantValue != ConvertedValue) {
432 ConstantValue = APValue(*IntConstantValue);
433 ConstantType = Initializer->getType();
435 }
436 } else {
437 // Variables are always narrowings.
439 }
440 }
441 return NK_Not_Narrowing;
442
443 // -- from long double to double or float, or from double to float, except
444 // where the source is a constant expression and the actual value after
445 // conversion is within the range of values that can be represented (even
446 // if it cannot be represented exactly), or
448 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
449 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
450 // FromType is larger than ToType.
451 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
452
453 // If it's value-dependent, we can't tell whether it's narrowing.
454 if (Initializer->isValueDependent())
456
458 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
459 ((Ctx.getLangOpts().CPlusPlus &&
460 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)))) {
461 // Constant!
462 if (Ctx.getLangOpts().C23)
463 ConstantValue = R.Val;
464 assert(ConstantValue.isFloat());
465 llvm::APFloat FloatVal = ConstantValue.getFloat();
466 // Convert the source value into the target type.
467 bool ignored;
468 llvm::APFloat Converted = FloatVal;
469 llvm::APFloat::opStatus ConvertStatus =
470 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
471 llvm::APFloat::rmNearestTiesToEven, &ignored);
472 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
473 llvm::APFloat::rmNearestTiesToEven, &ignored);
474 if (Ctx.getLangOpts().C23) {
475 if (FloatVal.isNaN() && Converted.isNaN() &&
476 !FloatVal.isSignaling() && !Converted.isSignaling()) {
477 // Quiet NaNs are considered the same value, regardless of
478 // payloads.
479 return NK_Not_Narrowing;
480 }
481 // For normal values, check exact equality.
482 if (!Converted.bitwiseIsEqual(FloatVal)) {
483 ConstantType = Initializer->getType();
485 }
486 } else {
487 // If there was no overflow, the source value is within the range of
488 // values that can be represented.
489 if (ConvertStatus & llvm::APFloat::opOverflow) {
490 ConstantType = Initializer->getType();
492 }
493 }
494 } else {
496 }
497 }
498 return NK_Not_Narrowing;
499
500 // -- from an integer type or unscoped enumeration type to an integer type
501 // that cannot represent all the values of the original type, except where
502 // (CWG2627) -- the source is a bit-field whose width w is less than that
503 // of its type (or, for an enumeration type, its underlying type) and the
504 // target type can represent all the values of a hypothetical extended
505 // integer type with width w and with the same signedness as the original
506 // type or
507 // -- the source is a constant expression and the actual value after
508 // conversion will fit into the target type and will produce the original
509 // value when converted back to the original type.
511 IntegralConversion: {
512 assert(FromType->isIntegralOrUnscopedEnumerationType());
513 assert(ToType->isIntegralOrUnscopedEnumerationType());
514 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
515 unsigned FromWidth = Ctx.getIntWidth(FromType);
516 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
517 const unsigned ToWidth = Ctx.getIntWidth(ToType);
518
519 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
520 bool ToSigned, unsigned ToWidth) {
521 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
522 !(FromSigned && !ToSigned);
523 };
524
525 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
526 return NK_Not_Narrowing;
527
528 // Not all values of FromType can be represented in ToType.
529 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
530
531 bool DependentBitField = false;
532 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
533 if (BitField->getBitWidth()->isValueDependent())
534 DependentBitField = true;
535 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
536 BitFieldWidth < FromWidth) {
537 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
538 return NK_Not_Narrowing;
539
540 // The initializer will be truncated to the bit-field width
541 FromWidth = BitFieldWidth;
542 }
543 }
544
545 // If it's value-dependent, we can't tell whether it's narrowing.
546 if (Initializer->isValueDependent())
548
549 std::optional<llvm::APSInt> OptInitializerValue =
550 Initializer->getIntegerConstantExpr(Ctx);
551 if (!OptInitializerValue) {
552 // If the bit-field width was dependent, it might end up being small
553 // enough to fit in the target type (unless the target type is unsigned
554 // and the source type is signed, in which case it will never fit)
555 if (DependentBitField && !(FromSigned && !ToSigned))
557
558 // Otherwise, such a conversion is always narrowing
560 }
561 llvm::APSInt &InitializerValue = *OptInitializerValue;
562 bool Narrowing = false;
563 if (FromWidth < ToWidth) {
564 // Negative -> unsigned is narrowing. Otherwise, more bits is never
565 // narrowing.
566 if (InitializerValue.isSigned() && InitializerValue.isNegative())
567 Narrowing = true;
568 } else {
569 // Add a bit to the InitializerValue so we don't have to worry about
570 // signed vs. unsigned comparisons.
571 InitializerValue =
572 InitializerValue.extend(InitializerValue.getBitWidth() + 1);
573 // Convert the initializer to and from the target width and signed-ness.
574 llvm::APSInt ConvertedValue = InitializerValue;
575 ConvertedValue = ConvertedValue.trunc(ToWidth);
576 ConvertedValue.setIsSigned(ToSigned);
577 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
578 ConvertedValue.setIsSigned(InitializerValue.isSigned());
579 // If the result is different, this was a narrowing conversion.
580 if (ConvertedValue != InitializerValue)
581 Narrowing = true;
582 }
583 if (Narrowing) {
584 ConstantType = Initializer->getType();
585 ConstantValue = APValue(InitializerValue);
587 }
588
589 return NK_Not_Narrowing;
590 }
591 case ICK_Complex_Real:
592 if (FromType->isComplexType() && !ToType->isComplexType())
593 return NK_Type_Narrowing;
594 return NK_Not_Narrowing;
595
597 if (Ctx.getLangOpts().C23) {
598 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
600 if (Initializer->EvaluateAsRValue(R, Ctx)) {
601 ConstantValue = R.Val;
602 assert(ConstantValue.isFloat());
603 llvm::APFloat FloatVal = ConstantValue.getFloat();
604 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
605 // value, the unqualified versions of the type of the initializer and
606 // the corresponding real type of the object declared shall be
607 // compatible.
608 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
609 ConstantType = Initializer->getType();
611 }
612 }
613 }
614 return NK_Not_Narrowing;
615 default:
616 // Other kinds of conversions are not narrowings.
617 return NK_Not_Narrowing;
618 }
619}
620
621/// dump - Print this standard conversion sequence to standard
622/// error. Useful for debugging overloading issues.
623LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
624 raw_ostream &OS = llvm::errs();
625 bool PrintedSomething = false;
626 if (First != ICK_Identity) {
628 PrintedSomething = true;
629 }
630
631 if (Second != ICK_Identity) {
632 if (PrintedSomething) {
633 OS << " -> ";
634 }
636
637 if (CopyConstructor) {
638 OS << " (by copy constructor)";
639 } else if (DirectBinding) {
640 OS << " (direct reference binding)";
641 } else if (ReferenceBinding) {
642 OS << " (reference binding)";
643 }
644 PrintedSomething = true;
645 }
646
647 if (Third != ICK_Identity) {
648 if (PrintedSomething) {
649 OS << " -> ";
650 }
652 PrintedSomething = true;
653 }
654
655 if (!PrintedSomething) {
656 OS << "No conversions required";
657 }
658}
659
660/// dump - Print this user-defined conversion sequence to standard
661/// error. Useful for debugging overloading issues.
663 raw_ostream &OS = llvm::errs();
664 if (Before.First || Before.Second || Before.Third) {
665 Before.dump();
666 OS << " -> ";
667 }
669 OS << '\'' << *ConversionFunction << '\'';
670 else
671 OS << "aggregate initialization";
672 if (After.First || After.Second || After.Third) {
673 OS << " -> ";
674 After.dump();
675 }
676}
677
678/// dump - Print this implicit conversion sequence to standard
679/// error. Useful for debugging overloading issues.
681 raw_ostream &OS = llvm::errs();
683 OS << "Worst list element conversion: ";
684 switch (ConversionKind) {
686 OS << "Standard conversion: ";
687 Standard.dump();
688 break;
690 OS << "User-defined conversion: ";
691 UserDefined.dump();
692 break;
694 OS << "Ellipsis conversion";
695 break;
697 OS << "Ambiguous conversion";
698 break;
699 case BadConversion:
700 OS << "Bad conversion";
701 break;
702 }
703
704 OS << "\n";
705}
706
710
712 conversions().~ConversionSet();
713}
714
715void
721
722namespace {
723 // Structure used by DeductionFailureInfo to store
724 // template argument information.
725 struct DFIArguments {
726 TemplateArgument FirstArg;
727 TemplateArgument SecondArg;
728 };
729 // Structure used by DeductionFailureInfo to store
730 // template parameter and template argument information.
731 struct DFIParamWithArguments : DFIArguments {
732 TemplateParameter Param;
733 };
734 // Structure used by DeductionFailureInfo to store template argument
735 // information and the index of the problematic call argument.
736 struct DFIDeducedMismatchArgs : DFIArguments {
737 TemplateArgumentList *TemplateArgs;
738 unsigned CallArgIndex;
739 };
740 // Structure used by DeductionFailureInfo to store information about
741 // unsatisfied constraints.
742 struct CNSInfo {
743 TemplateArgumentList *TemplateArgs;
744 ConstraintSatisfaction Satisfaction;
745 };
746}
747
748/// Convert from Sema's representation of template deduction information
749/// to the form used in overload-candidate information.
753 TemplateDeductionInfo &Info) {
755 Result.Result = static_cast<unsigned>(TDK);
756 Result.HasDiagnostic = false;
757 switch (TDK) {
764 Result.Data = nullptr;
765 break;
766
768 Result.Data = Info.Param.getOpaqueValue();
769 break;
771 Result.Data = Info.Param.getOpaqueValue();
772 if (Info.hasSFINAEDiagnostic()) {
776 Result.HasDiagnostic = true;
777 }
778 break;
779
782 // FIXME: Should allocate from normal heap so that we can free this later.
783 auto *Saved = new (Context) DFIDeducedMismatchArgs;
784 Saved->FirstArg = Info.FirstArg;
785 Saved->SecondArg = Info.SecondArg;
786 Saved->TemplateArgs = Info.takeSugared();
787 Saved->CallArgIndex = Info.CallArgIndex;
788 Result.Data = Saved;
789 break;
790 }
791
793 // FIXME: Should allocate from normal heap so that we can free this later.
794 DFIArguments *Saved = new (Context) DFIArguments;
795 Saved->FirstArg = Info.FirstArg;
796 Saved->SecondArg = Info.SecondArg;
797 Result.Data = Saved;
798 break;
799 }
800
802 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
805 // FIXME: Should allocate from normal heap so that we can free this later.
806 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
807 Saved->Param = Info.Param;
808 Saved->FirstArg = Info.FirstArg;
809 Saved->SecondArg = Info.SecondArg;
810 Result.Data = Saved;
811 break;
812 }
813
815 Result.Data = Info.takeSugared();
816 if (Info.hasSFINAEDiagnostic()) {
820 Result.HasDiagnostic = true;
821 }
822 break;
823
825 CNSInfo *Saved = new (Context) CNSInfo;
826 Saved->TemplateArgs = Info.takeSugared();
827 Saved->Satisfaction = std::move(Info.AssociatedConstraintsSatisfaction);
828 Result.Data = Saved;
829 break;
830 }
831
835 llvm_unreachable("not a deduction failure");
836 }
837
838 return Result;
839}
840
842 switch (static_cast<TemplateDeductionResult>(Result)) {
851 break;
852
859 // FIXME: Destroy the data?
860 Data = nullptr;
861 break;
862
865 // FIXME: Destroy the template argument list?
866 Data = nullptr;
868 Diag->~PartialDiagnosticAt();
869 HasDiagnostic = false;
870 }
871 break;
872
874 // FIXME: Destroy the template argument list?
875 static_cast<CNSInfo *>(Data)->Satisfaction.~ConstraintSatisfaction();
876 Data = nullptr;
878 Diag->~PartialDiagnosticAt();
879 HasDiagnostic = false;
880 }
881 break;
882
883 // Unhandled
886 break;
887 }
888}
889
891 if (HasDiagnostic)
892 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
893 return nullptr;
894}
895
929
965
997
1029
1031 switch (static_cast<TemplateDeductionResult>(Result)) {
1034 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1035
1036 default:
1037 return std::nullopt;
1038 }
1039}
1040
1042 const FunctionDecl *Y) {
1043 if (!X || !Y)
1044 return false;
1045 if (X->getNumParams() != Y->getNumParams())
1046 return false;
1047 // FIXME: when do rewritten comparison operators
1048 // with explicit object parameters correspond?
1049 // https://cplusplus.github.io/CWG/issues/2797.html
1050 for (unsigned I = 0; I < X->getNumParams(); ++I)
1051 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1052 Y->getParamDecl(I)->getType()))
1053 return false;
1054 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1055 auto *FTY = Y->getDescribedFunctionTemplate();
1056 if (!FTY)
1057 return false;
1058 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1059 FTY->getTemplateParameters()))
1060 return false;
1061 }
1062 return true;
1063}
1064
1066 Expr *FirstOperand, FunctionDecl *EqFD) {
1067 assert(EqFD->getOverloadedOperator() ==
1068 OverloadedOperatorKind::OO_EqualEqual);
1069 // C++2a [over.match.oper]p4:
1070 // A non-template function or function template F named operator== is a
1071 // rewrite target with first operand o unless a search for the name operator!=
1072 // in the scope S from the instantiation context of the operator expression
1073 // finds a function or function template that would correspond
1074 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1075 // scope of the class type of o if F is a class member, and the namespace
1076 // scope of which F is a member otherwise. A function template specialization
1077 // named operator== is a rewrite target if its function template is a rewrite
1078 // target.
1080 OverloadedOperatorKind::OO_ExclaimEqual);
1081 if (isa<CXXMethodDecl>(EqFD)) {
1082 // If F is a class member, search scope is class type of first operand.
1083 QualType RHS = FirstOperand->getType();
1084 auto *RHSRec = RHS->getAsCXXRecordDecl();
1085 if (!RHSRec)
1086 return true;
1087 LookupResult Members(S, NotEqOp, OpLoc,
1089 S.LookupQualifiedName(Members, RHSRec);
1090 Members.suppressAccessDiagnostics();
1091 for (NamedDecl *Op : Members)
1092 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1093 return false;
1094 return true;
1095 }
1096 // Otherwise the search scope is the namespace scope of which F is a member.
1097 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1098 auto *NotEqFD = Op->getAsFunction();
1099 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1100 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1101 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1103 cast<Decl>(Op->getLexicalDeclContext())))
1104 return false;
1105 }
1106 return true;
1107}
1108
1110 OverloadedOperatorKind Op) const {
1112 return false;
1113 return Op == OO_EqualEqual || Op == OO_Spaceship;
1114}
1115
1117 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) const {
1118 auto Op = FD->getOverloadedOperator();
1119 if (!allowsReversed(Op))
1120 return false;
1121 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1122 assert(OriginalArgs.size() == 2);
1124 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1125 return false;
1126 }
1127 // Don't bother adding a reversed candidate that can never be a better
1128 // match than the non-reversed version.
1129 return FD->getNumNonObjectParams() != 2 ||
1131 FD->getParamDecl(1)->getType()) ||
1132 FD->hasAttr<EnableIfAttr>();
1133}
1134
1135void OverloadCandidateSet::destroyCandidates() {
1136 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1137 for (auto &C : i->Conversions)
1138 C.~ImplicitConversionSequence();
1139 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1140 i->DeductionFailure.Destroy();
1141 }
1142}
1143
1145 destroyCandidates();
1146 SlabAllocator.Reset();
1147 NumInlineBytesUsed = 0;
1148 Candidates.clear();
1149 Functions.clear();
1150 Kind = CSK;
1151 FirstDeferredCandidate = nullptr;
1152 DeferredCandidatesCount = 0;
1153 HasDeferredTemplateConstructors = false;
1154 ResolutionByPerfectCandidateIsDisabled = false;
1155}
1156
1157namespace {
1158 class UnbridgedCastsSet {
1159 struct Entry {
1160 Expr **Addr;
1161 Expr *Saved;
1162 };
1163 SmallVector<Entry, 2> Entries;
1164
1165 public:
1166 void save(Sema &S, Expr *&E) {
1167 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1168 Entry entry = { &E, E };
1169 Entries.push_back(entry);
1170 E = S.ObjC().stripARCUnbridgedCast(E);
1171 }
1172
1173 void restore() {
1174 for (SmallVectorImpl<Entry>::iterator
1175 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1176 *i->Addr = i->Saved;
1177 }
1178 };
1179}
1180
1181/// checkPlaceholderForOverload - Do any interesting placeholder-like
1182/// preprocessing on the given expression.
1183///
1184/// \param unbridgedCasts a collection to which to add unbridged casts;
1185/// without this, they will be immediately diagnosed as errors
1186///
1187/// Return true on unrecoverable error.
1188static bool
1190 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1191 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1192 // We can't handle overloaded expressions here because overload
1193 // resolution might reasonably tweak them.
1194 if (placeholder->getKind() == BuiltinType::Overload) return false;
1195
1196 // If the context potentially accepts unbridged ARC casts, strip
1197 // the unbridged cast and add it to the collection for later restoration.
1198 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1199 unbridgedCasts) {
1200 unbridgedCasts->save(S, E);
1201 return false;
1202 }
1203
1204 // Go ahead and check everything else.
1205 ExprResult result = S.CheckPlaceholderExpr(E);
1206 if (result.isInvalid())
1207 return true;
1208
1209 E = result.get();
1210 return false;
1211 }
1212
1213 // Nothing to do.
1214 return false;
1215}
1216
1217/// checkArgPlaceholdersForOverload - Check a set of call operands for
1218/// placeholders.
1220 UnbridgedCastsSet &unbridged) {
1221 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1222 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1223 return true;
1224
1225 return false;
1226}
1227
1229 const LookupResult &Old, NamedDecl *&Match,
1230 bool NewIsUsingDecl) {
1231 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1232 I != E; ++I) {
1233 NamedDecl *OldD = *I;
1234
1235 bool OldIsUsingDecl = false;
1236 if (isa<UsingShadowDecl>(OldD)) {
1237 OldIsUsingDecl = true;
1238
1239 // We can always introduce two using declarations into the same
1240 // context, even if they have identical signatures.
1241 if (NewIsUsingDecl) continue;
1242
1243 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1244 }
1245
1246 // A using-declaration does not conflict with another declaration
1247 // if one of them is hidden.
1248 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1249 continue;
1250
1251 // If either declaration was introduced by a using declaration,
1252 // we'll need to use slightly different rules for matching.
1253 // Essentially, these rules are the normal rules, except that
1254 // function templates hide function templates with different
1255 // return types or template parameter lists.
1256 bool UseMemberUsingDeclRules =
1257 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1258 !New->getFriendObjectKind();
1259
1260 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1261 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1262 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1264 continue;
1265 }
1266
1267 if (!isa<FunctionTemplateDecl>(OldD) &&
1268 !shouldLinkPossiblyHiddenDecl(*I, New))
1269 continue;
1270
1271 Match = *I;
1272 return OverloadKind::Match;
1273 }
1274
1275 // Builtins that have custom typechecking or have a reference should
1276 // not be overloadable or redeclarable.
1277 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1278 Match = *I;
1280 }
1281 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1282 // We can overload with these, which can show up when doing
1283 // redeclaration checks for UsingDecls.
1284 assert(Old.getLookupKind() == LookupUsingDeclName);
1285 } else if (isa<TagDecl>(OldD)) {
1286 // We can always overload with tags by hiding them.
1287 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1288 // Optimistically assume that an unresolved using decl will
1289 // overload; if it doesn't, we'll have to diagnose during
1290 // template instantiation.
1291 //
1292 // Exception: if the scope is dependent and this is not a class
1293 // member, the using declaration can only introduce an enumerator.
1294 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1295 Match = *I;
1297 }
1298 } else {
1299 // (C++ 13p1):
1300 // Only function declarations can be overloaded; object and type
1301 // declarations cannot be overloaded.
1302 Match = *I;
1304 }
1305 }
1306
1307 // C++ [temp.friend]p1:
1308 // For a friend function declaration that is not a template declaration:
1309 // -- if the name of the friend is a qualified or unqualified template-id,
1310 // [...], otherwise
1311 // -- if the name of the friend is a qualified-id and a matching
1312 // non-template function is found in the specified class or namespace,
1313 // the friend declaration refers to that function, otherwise,
1314 // -- if the name of the friend is a qualified-id and a matching function
1315 // template is found in the specified class or namespace, the friend
1316 // declaration refers to the deduced specialization of that function
1317 // template, otherwise
1318 // -- the name shall be an unqualified-id [...]
1319 // If we get here for a qualified friend declaration, we've just reached the
1320 // third bullet. If the type of the friend is dependent, skip this lookup
1321 // until instantiation.
1322 if (New->getFriendObjectKind() && New->getQualifier() &&
1323 !New->getDescribedFunctionTemplate() &&
1324 !New->getDependentSpecializationInfo() &&
1325 !New->getType()->isDependentType()) {
1326 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1327 TemplateSpecResult.addAllDecls(Old);
1328 if (CheckFunctionTemplateSpecialization(New, /*TemplateParams=*/nullptr,
1329 /*ExplicitTemplateArgs=*/nullptr,
1330 TemplateSpecResult,
1331 /*QualifiedFriend*/ true)) {
1332 New->setInvalidDecl();
1334 }
1335
1336 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1337 return OverloadKind::Match;
1338 }
1339
1341}
1342
1343template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1344 assert(D && "function decl should not be null");
1345 if (auto *A = D->getAttr<AttrT>())
1346 return !A->isImplicit();
1347 return false;
1348}
1349
1351 FunctionDecl *Old,
1352 bool UseMemberUsingDeclRules,
1353 bool ConsiderCudaAttrs,
1354 bool UseOverrideRules = false) {
1355 // C++ [basic.start.main]p2: This function shall not be overloaded.
1356 if (New->isMain())
1357 return false;
1358
1359 // MSVCRT user defined entry points cannot be overloaded.
1360 if (New->isMSVCRTEntryPoint())
1361 return false;
1362
1363 NamedDecl *OldDecl = Old;
1364 NamedDecl *NewDecl = New;
1366 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1367
1368 // C++ [temp.fct]p2:
1369 // A function template can be overloaded with other function templates
1370 // and with normal (non-template) functions.
1371 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1372 return true;
1373
1374 // Is the function New an overload of the function Old?
1375 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1376 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1377
1378 // Compare the signatures (C++ 1.3.10) of the two functions to
1379 // determine whether they are overloads. If we find any mismatch
1380 // in the signature, they are overloads.
1381
1382 // If either of these functions is a K&R-style function (no
1383 // prototype), then we consider them to have matching signatures.
1384 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1386 return false;
1387
1388 const auto *OldType = cast<FunctionProtoType>(OldQType);
1389 const auto *NewType = cast<FunctionProtoType>(NewQType);
1390
1391 // The signature of a function includes the types of its
1392 // parameters (C++ 1.3.10), which includes the presence or absence
1393 // of the ellipsis; see C++ DR 357).
1394 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1395 return true;
1396
1397 // For member-like friends, the enclosing class is part of the signature.
1398 if ((New->isMemberLikeConstrainedFriend() ||
1400 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1401 return true;
1402
1403 // Compare the parameter lists.
1404 // This can only be done once we have establish that friend functions
1405 // inhabit the same context, otherwise we might tried to instantiate
1406 // references to non-instantiated entities during constraint substitution.
1407 // GH78101.
1408 if (NewTemplate) {
1409 OldDecl = OldTemplate;
1410 NewDecl = NewTemplate;
1411 // C++ [temp.over.link]p4:
1412 // The signature of a function template consists of its function
1413 // signature, its return type and its template parameter list. The names
1414 // of the template parameters are significant only for establishing the
1415 // relationship between the template parameters and the rest of the
1416 // signature.
1417 //
1418 // We check the return type and template parameter lists for function
1419 // templates first; the remaining checks follow.
1420 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1421 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1422 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1423 bool SameReturnType = SemaRef.Context.hasSameType(
1424 Old->getDeclaredReturnType(), New->getDeclaredReturnType());
1425 // FIXME(GH58571): Match template parameter list even for non-constrained
1426 // template heads. This currently ensures that the code prior to C++20 is
1427 // not newly broken.
1428 bool ConstraintsInTemplateHead =
1431 // C++ [namespace.udecl]p11:
1432 // The set of declarations named by a using-declarator that inhabits a
1433 // class C does not include member functions and member function
1434 // templates of a base class that "correspond" to (and thus would
1435 // conflict with) a declaration of a function or function template in
1436 // C.
1437 // Comparing return types is not required for the "correspond" check to
1438 // decide whether a member introduced by a shadow declaration is hidden.
1439 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1440 !SameTemplateParameterList)
1441 return true;
1442 if (!UseMemberUsingDeclRules &&
1443 (!SameTemplateParameterList || !SameReturnType))
1444 return true;
1445 }
1446
1447 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1448 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1449
1450 int OldParamsOffset = 0;
1451 int NewParamsOffset = 0;
1452
1453 // When determining if a method is an overload from a base class, act as if
1454 // the implicit object parameter are of the same type.
1455
1456 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1458 auto ThisType = M->getFunctionObjectParameterReferenceType();
1459 if (ThisType.isConstQualified())
1460 Q.removeConst();
1461 return Q;
1462 }
1463
1464 // We do not allow overloading based off of '__restrict'.
1465 Q.removeRestrict();
1466
1467 // We may not have applied the implicit const for a constexpr member
1468 // function yet (because we haven't yet resolved whether this is a static
1469 // or non-static member function). Add it now, on the assumption that this
1470 // is a redeclaration of OldMethod.
1471 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1472 (M->isConstexpr() || M->isConsteval()) &&
1473 !isa<CXXConstructorDecl>(NewMethod))
1474 Q.addConst();
1475 return Q;
1476 };
1477
1478 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1479 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1480 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1481
1482 if (OldMethod->isExplicitObjectMemberFunction()) {
1483 BS.Quals.removeVolatile();
1484 DS.Quals.removeVolatile();
1485 }
1486
1487 return BS.Quals == DS.Quals;
1488 };
1489
1490 auto CompareType = [&](QualType Base, QualType D) {
1491 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1492 auto DS = D.getNonReferenceType().getCanonicalType().split();
1493
1494 if (!AreQualifiersEqual(BS, DS))
1495 return false;
1496
1497 if (OldMethod->isImplicitObjectMemberFunction() &&
1498 OldMethod->getParent() != NewMethod->getParent()) {
1499 CanQualType ParentType =
1500 SemaRef.Context.getCanonicalTagType(OldMethod->getParent());
1501 if (ParentType.getTypePtr() != BS.Ty)
1502 return false;
1503 BS.Ty = DS.Ty;
1504 }
1505
1506 // FIXME: should we ignore some type attributes here?
1507 if (BS.Ty != DS.Ty)
1508 return false;
1509
1510 if (Base->isLValueReferenceType())
1511 return D->isLValueReferenceType();
1512 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1513 };
1514
1515 // If the function is a class member, its signature includes the
1516 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1517 auto DiagnoseInconsistentRefQualifiers = [&]() {
1518 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1519 return false;
1520 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1521 return false;
1522 if (OldMethod->isExplicitObjectMemberFunction() ||
1523 NewMethod->isExplicitObjectMemberFunction())
1524 return false;
1525 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1526 NewMethod->getRefQualifier() == RQ_None)) {
1527 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1528 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1529 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1530 return true;
1531 }
1532 return false;
1533 };
1534
1535 // We look at the parameters first, as it is the common case.
1536 // However we should not emit diagnostic before checking
1537 // the overloads do not differ by constraints or other discriminant.
1538 bool ShouldDiagnoseInconsistentRefQualifiers = false;
1539 bool HaveInconsistentQualifiers = false;
1540
1541 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1542 OldParamsOffset++;
1543 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1544 NewParamsOffset++;
1545
1546 if (OldType->getNumParams() - OldParamsOffset !=
1547 NewType->getNumParams() - NewParamsOffset ||
1549 {OldType->param_type_begin() + OldParamsOffset,
1550 OldType->param_type_end()},
1551 {NewType->param_type_begin() + NewParamsOffset,
1552 NewType->param_type_end()},
1553 nullptr)) {
1554 return true;
1555 }
1556
1557 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1558 !NewMethod->isStatic()) {
1559 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1560 const CXXMethodDecl *New) {
1561 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1562 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1563
1564 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1565 return F->getRefQualifier() == RQ_None &&
1566 !F->isExplicitObjectMemberFunction();
1567 };
1568
1569 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1570 CompareType(OldObjectType.getNonReferenceType(),
1571 NewObjectType.getNonReferenceType()))
1572 return true;
1573 return CompareType(OldObjectType, NewObjectType);
1574 }(OldMethod, NewMethod);
1575
1576 if (!HaveCorrespondingObjectParameters) {
1577 ShouldDiagnoseInconsistentRefQualifiers = true;
1578 // CWG2554
1579 // and, if at least one is an explicit object member function, ignoring
1580 // object parameters
1581 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1582 !OldMethod->isExplicitObjectMemberFunction()))
1583 HaveInconsistentQualifiers = true;
1584 }
1585 }
1586
1587 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1588 NewMethod->isImplicitObjectMemberFunction())
1589 ShouldDiagnoseInconsistentRefQualifiers = true;
1590
1591 if (!UseOverrideRules &&
1592 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1593 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1594 OldRC = Old->getTrailingRequiresClause();
1595 if (!NewRC != !OldRC)
1596 return true;
1597 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1598 return true;
1599 if (NewRC &&
1600 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC.ConstraintExpr,
1601 NewDecl, NewRC.ConstraintExpr))
1602 return true;
1603 }
1604
1605 // Though pass_object_size is placed on parameters and takes an argument, we
1606 // consider it to be a function-level modifier for the sake of function
1607 // identity. Either the function has one or more parameters with
1608 // pass_object_size or it doesn't.
1611 return true;
1612
1613 // enable_if attributes are an order-sensitive part of the signature.
1615 NewI = New->specific_attr_begin<EnableIfAttr>(),
1616 NewE = New->specific_attr_end<EnableIfAttr>(),
1617 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1618 OldE = Old->specific_attr_end<EnableIfAttr>();
1619 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1620 if (NewI == NewE || OldI == OldE)
1621 return true;
1622 llvm::FoldingSetNodeID NewID, OldID;
1623 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1624 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1625 if (NewID != OldID)
1626 return true;
1627 }
1628
1629 if ((ShouldDiagnoseInconsistentRefQualifiers &&
1630 DiagnoseInconsistentRefQualifiers()) ||
1631 HaveInconsistentQualifiers)
1632 return true;
1633
1634 // At this point, it is known that the two functions have the same signature.
1635 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1636 // Don't allow overloading of destructors. (In theory we could, but it
1637 // would be a giant change to clang.)
1639 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1640 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1641 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1642 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1643 "Unexpected invalid target.");
1644
1645 // Allow overloading of functions with same signature and different CUDA
1646 // target attributes.
1647 if (NewTarget != OldTarget) {
1648 // Special case: non-constexpr function is allowed to override
1649 // constexpr virtual function
1650 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1651 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1656 return false;
1657 }
1658 return true;
1659 }
1660 }
1661 }
1662 }
1663
1664 // The signatures match; this is not an overload.
1665 return false;
1666}
1667
1669 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1670 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1671 ConsiderCudaAttrs);
1672}
1673
1675 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1676 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1677 /*UseMemberUsingDeclRules=*/false,
1678 /*ConsiderCudaAttrs=*/true,
1679 /*UseOverrideRules=*/true);
1680}
1681
1682/// Tries a user-defined conversion from From to ToType.
1683///
1684/// Produces an implicit conversion sequence for when a standard conversion
1685/// is not an option. See TryImplicitConversion for more information.
1688 bool SuppressUserConversions,
1689 AllowedExplicit AllowExplicit,
1690 bool InOverloadResolution,
1691 bool CStyle,
1692 bool AllowObjCWritebackConversion,
1693 bool AllowObjCConversionOnExplicit) {
1695
1696 if (SuppressUserConversions) {
1697 // We're not in the case above, so there is no conversion that
1698 // we can perform.
1700 return ICS;
1701 }
1702
1703 // Attempt user-defined conversion.
1704 OverloadCandidateSet Conversions(From->getExprLoc(),
1706 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1707 Conversions, AllowExplicit,
1708 AllowObjCConversionOnExplicit)) {
1709 case OR_Success:
1710 case OR_Deleted:
1711 ICS.setUserDefined();
1712 // C++ [over.ics.user]p4:
1713 // A conversion of an expression of class type to the same class
1714 // type is given Exact Match rank, and a conversion of an
1715 // expression of class type to a base class of that type is
1716 // given Conversion rank, in spite of the fact that a copy
1717 // constructor (i.e., a user-defined conversion function) is
1718 // called for those cases.
1720 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1721 QualType FromType;
1722 SourceLocation FromLoc;
1723 // C++11 [over.ics.list]p6, per DR2137:
1724 // C++17 [over.ics.list]p6:
1725 // If C is not an initializer-list constructor and the initializer list
1726 // has a single element of type cv U, where U is X or a class derived
1727 // from X, the implicit conversion sequence has Exact Match rank if U is
1728 // X, or Conversion rank if U is derived from X.
1729 bool FromListInit = false;
1730 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1731 InitList && InitList->getNumInits() == 1 &&
1733 const Expr *SingleInit = InitList->getInit(0);
1734 FromType = SingleInit->getType();
1735 FromLoc = SingleInit->getBeginLoc();
1736 FromListInit = true;
1737 } else {
1738 FromType = From->getType();
1739 FromLoc = From->getBeginLoc();
1740 }
1741 QualType FromCanon =
1743 QualType ToCanon
1745 if ((FromCanon == ToCanon ||
1746 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1747 // Turn this into a "standard" conversion sequence, so that it
1748 // gets ranked with standard conversion sequences.
1750 ICS.setStandard();
1752 ICS.Standard.setFromType(FromType);
1753 ICS.Standard.setAllToTypes(ToType);
1754 ICS.Standard.FromBracedInitList = FromListInit;
1757 if (ToCanon != FromCanon)
1759 }
1760 }
1761 break;
1762
1763 case OR_Ambiguous:
1764 ICS.setAmbiguous();
1765 ICS.Ambiguous.setFromType(From->getType());
1766 ICS.Ambiguous.setToType(ToType);
1767 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1768 Cand != Conversions.end(); ++Cand)
1769 if (Cand->Best)
1770 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1771 break;
1772
1773 // Fall through.
1776 break;
1777 }
1778
1779 return ICS;
1780}
1781
1782/// TryImplicitConversion - Attempt to perform an implicit conversion
1783/// from the given expression (Expr) to the given type (ToType). This
1784/// function returns an implicit conversion sequence that can be used
1785/// to perform the initialization. Given
1786///
1787/// void f(float f);
1788/// void g(int i) { f(i); }
1789///
1790/// this routine would produce an implicit conversion sequence to
1791/// describe the initialization of f from i, which will be a standard
1792/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1793/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1794//
1795/// Note that this routine only determines how the conversion can be
1796/// performed; it does not actually perform the conversion. As such,
1797/// it will not produce any diagnostics if no conversion is available,
1798/// but will instead return an implicit conversion sequence of kind
1799/// "BadConversion".
1800///
1801/// If @p SuppressUserConversions, then user-defined conversions are
1802/// not permitted.
1803/// If @p AllowExplicit, then explicit user-defined conversions are
1804/// permitted.
1805///
1806/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1807/// writeback conversion, which allows __autoreleasing id* parameters to
1808/// be initialized with __strong id* or __weak id* arguments.
1809static ImplicitConversionSequence
1811 bool SuppressUserConversions,
1812 AllowedExplicit AllowExplicit,
1813 bool InOverloadResolution,
1814 bool CStyle,
1815 bool AllowObjCWritebackConversion,
1816 bool AllowObjCConversionOnExplicit) {
1818 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1819 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1820 ICS.setStandard();
1821 return ICS;
1822 }
1823
1824 if (!S.getLangOpts().CPlusPlus) {
1826 return ICS;
1827 }
1828
1829 // C++ [over.ics.user]p4:
1830 // A conversion of an expression of class type to the same class
1831 // type is given Exact Match rank, and a conversion of an
1832 // expression of class type to a base class of that type is
1833 // given Conversion rank, in spite of the fact that a copy/move
1834 // constructor (i.e., a user-defined conversion function) is
1835 // called for those cases.
1836 QualType FromType = From->getType();
1837 if (ToType->isRecordType() &&
1838 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1839 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1840 ICS.setStandard();
1842 ICS.Standard.setFromType(FromType);
1843 ICS.Standard.setAllToTypes(ToType);
1844
1845 // We don't actually check at this point whether there is a valid
1846 // copy/move constructor, since overloading just assumes that it
1847 // exists. When we actually perform initialization, we'll find the
1848 // appropriate constructor to copy the returned object, if needed.
1849 ICS.Standard.CopyConstructor = nullptr;
1850
1851 // In HLSL, a conversion of an expression of class type to the same class
1852 // type needs implicit LvaluetoRvalue conversion.
1853 if (S.getLangOpts().HLSL)
1855
1856 // Determine whether this is considered a derived-to-base conversion.
1857 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1859
1860 return ICS;
1861 }
1862
1863 if (S.getLangOpts().HLSL) {
1864 // Handle conversion of the HLSL resource types.
1865 const Type *FromTy = FromType->getUnqualifiedDesugaredType();
1866 if (FromTy->isHLSLAttributedResourceType()) {
1867 // Attributed resource types can convert to other attributed
1868 // resource types with the same attributes and contained types,
1869 // or to __hlsl_resource_t without any attributes.
1870 bool CanConvert = false;
1871 const Type *ToTy = ToType->getUnqualifiedDesugaredType();
1872 if (ToTy->isHLSLAttributedResourceType()) {
1873 auto *ToResType = cast<HLSLAttributedResourceType>(ToTy);
1874 auto *FromResType = cast<HLSLAttributedResourceType>(FromTy);
1875 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1876 FromResType->getWrappedType()) &&
1877 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1878 FromResType->getContainedType()) &&
1879 ToResType->getAttrs() == FromResType->getAttrs())
1880 CanConvert = true;
1881 } else if (ToTy->isHLSLResourceType()) {
1882 CanConvert = true;
1883 }
1884 if (CanConvert) {
1885 ICS.setStandard();
1887 ICS.Standard.setFromType(FromType);
1888 ICS.Standard.setAllToTypes(ToType);
1889 return ICS;
1890 }
1891 }
1892 }
1893
1894 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1895 AllowExplicit, InOverloadResolution, CStyle,
1896 AllowObjCWritebackConversion,
1897 AllowObjCConversionOnExplicit);
1898}
1899
1900ImplicitConversionSequence
1902 bool SuppressUserConversions,
1903 AllowedExplicit AllowExplicit,
1904 bool InOverloadResolution,
1905 bool CStyle,
1906 bool AllowObjCWritebackConversion) {
1907 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1908 AllowExplicit, InOverloadResolution, CStyle,
1909 AllowObjCWritebackConversion,
1910 /*AllowObjCConversionOnExplicit=*/false);
1911}
1912
1914 AssignmentAction Action,
1915 bool AllowExplicit) {
1916 if (checkPlaceholderForOverload(*this, From))
1917 return ExprError();
1918
1919 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1920 bool AllowObjCWritebackConversion =
1921 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1922 Action == AssignmentAction::Sending);
1923 if (getLangOpts().ObjC)
1924 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1925 From->getType(), From);
1927 *this, From, ToType,
1928 /*SuppressUserConversions=*/false,
1929 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1930 /*InOverloadResolution=*/false,
1931 /*CStyle=*/false, AllowObjCWritebackConversion,
1932 /*AllowObjCConversionOnExplicit=*/false);
1933 return PerformImplicitConversion(From, ToType, ICS, Action);
1934}
1935
1937 QualType &ResultTy) const {
1938 bool Changed = IsFunctionConversion(FromType, ToType);
1939 if (Changed)
1940 ResultTy = ToType;
1941 return Changed;
1942}
1943
1944bool Sema::IsFunctionConversion(QualType FromType, QualType ToType) const {
1945 if (Context.hasSameUnqualifiedType(FromType, ToType))
1946 return false;
1947
1948 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1949 // or F(t noexcept) -> F(t)
1950 // where F adds one of the following at most once:
1951 // - a pointer
1952 // - a member pointer
1953 // - a block pointer
1954 // Changes here need matching changes in FindCompositePointerType.
1955 CanQualType CanTo = Context.getCanonicalType(ToType);
1956 CanQualType CanFrom = Context.getCanonicalType(FromType);
1957 Type::TypeClass TyClass = CanTo->getTypeClass();
1958 if (TyClass != CanFrom->getTypeClass()) return false;
1959 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1960 if (TyClass == Type::Pointer) {
1961 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1962 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1963 } else if (TyClass == Type::BlockPointer) {
1964 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1965 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1966 } else if (TyClass == Type::MemberPointer) {
1967 auto ToMPT = CanTo.castAs<MemberPointerType>();
1968 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1969 // A function pointer conversion cannot change the class of the function.
1970 if (!declaresSameEntity(ToMPT->getMostRecentCXXRecordDecl(),
1971 FromMPT->getMostRecentCXXRecordDecl()))
1972 return false;
1973 CanTo = ToMPT->getPointeeType();
1974 CanFrom = FromMPT->getPointeeType();
1975 } else {
1976 return false;
1977 }
1978
1979 TyClass = CanTo->getTypeClass();
1980 if (TyClass != CanFrom->getTypeClass()) return false;
1981 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1982 return false;
1983 }
1984
1985 const auto *FromFn = cast<FunctionType>(CanFrom);
1986 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1987
1988 const auto *ToFn = cast<FunctionType>(CanTo);
1989 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1990
1991 bool Changed = false;
1992
1993 // Drop 'noreturn' if not present in target type.
1994 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1995 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1996 Changed = true;
1997 }
1998
1999 const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn);
2000 const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn);
2001
2002 if (FromFPT && ToFPT) {
2003 if (FromFPT->hasCFIUncheckedCallee() != ToFPT->hasCFIUncheckedCallee()) {
2004 QualType NewTy = Context.getFunctionType(
2005 FromFPT->getReturnType(), FromFPT->getParamTypes(),
2006 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(
2007 ToFPT->hasCFIUncheckedCallee()));
2008 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
2009 FromFn = FromFPT;
2010 Changed = true;
2011 }
2012 }
2013
2014 // Drop 'noexcept' if not present in target type.
2015 if (FromFPT && ToFPT) {
2016 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
2017 FromFn = cast<FunctionType>(
2018 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
2019 EST_None)
2020 .getTypePtr());
2021 Changed = true;
2022 }
2023
2024 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
2025 // only if the ExtParameterInfo lists of the two function prototypes can be
2026 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
2028 bool CanUseToFPT, CanUseFromFPT;
2029 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
2030 CanUseFromFPT, NewParamInfos) &&
2031 CanUseToFPT && !CanUseFromFPT) {
2032 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2033 ExtInfo.ExtParameterInfos =
2034 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2035 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
2036 FromFPT->getParamTypes(), ExtInfo);
2037 FromFn = QT->getAs<FunctionType>();
2038 Changed = true;
2039 }
2040
2041 if (Context.hasAnyFunctionEffects()) {
2042 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
2043
2044 // Transparently add/drop effects; here we are concerned with
2045 // language rules/canonicalization. Adding/dropping effects is a warning.
2046 const auto FromFX = FromFPT->getFunctionEffects();
2047 const auto ToFX = ToFPT->getFunctionEffects();
2048 if (FromFX != ToFX) {
2049 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2050 ExtInfo.FunctionEffects = ToFX;
2051 QualType QT = Context.getFunctionType(
2052 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
2053 FromFn = QT->getAs<FunctionType>();
2054 Changed = true;
2055 }
2056 }
2057 }
2058
2059 if (!Changed)
2060 return false;
2061
2062 assert(QualType(FromFn, 0).isCanonical());
2063 if (QualType(FromFn, 0) != CanTo) return false;
2064
2065 return true;
2066}
2067
2068/// Determine whether the conversion from FromType to ToType is a valid
2069/// floating point conversion.
2070///
2071static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2072 QualType ToType) {
2073 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2074 return false;
2075 // FIXME: disable conversions between long double, __ibm128 and __float128
2076 // if their representation is different until there is back end support
2077 // We of course allow this conversion if long double is really double.
2078
2079 // Conversions between bfloat16 and float16 are currently not supported.
2080 if ((FromType->isBFloat16Type() &&
2081 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2082 (ToType->isBFloat16Type() &&
2083 (FromType->isFloat16Type() || FromType->isHalfType())))
2084 return false;
2085
2086 // Conversions between IEEE-quad and IBM-extended semantics are not
2087 // permitted.
2088 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
2089 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2090 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2091 &ToSem == &llvm::APFloat::IEEEquad()) ||
2092 (&FromSem == &llvm::APFloat::IEEEquad() &&
2093 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2094 return false;
2095 return true;
2096}
2097
2099 QualType ToType,
2101 Expr *From) {
2102 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2103 return true;
2104
2105 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2107 return true;
2108 }
2109
2110 if (IsFloatingPointConversion(S, FromType, ToType)) {
2112 return true;
2113 }
2114
2115 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2117 return true;
2118 }
2119
2120 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2122 ToType->isRealFloatingType())) {
2124 return true;
2125 }
2126
2127 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2129 return true;
2130 }
2131
2132 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2133 ToType->isIntegralType(S.Context)) {
2135 return true;
2136 }
2137
2138 return false;
2139}
2140
2141/// Determine whether the conversion from FromType to ToType is a valid
2142/// matrix conversion.
2143///
2144/// \param ICK Will be set to the matrix conversion kind, if this is a matrix
2145/// conversion.
2146static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType,
2148 ImplicitConversionKind &ElConv, Expr *From,
2149 bool InOverloadResolution, bool CStyle) {
2150 // Implicit conversions for matrices are an HLSL feature not present in C/C++.
2151 if (!S.getLangOpts().HLSL)
2152 return false;
2153
2154 auto *ToMatrixType = ToType->getAs<ConstantMatrixType>();
2155 auto *FromMatrixType = FromType->getAs<ConstantMatrixType>();
2156
2157 // If both arguments are matrix, handle possible matrix truncation and
2158 // element conversion.
2159 if (ToMatrixType && FromMatrixType) {
2160 unsigned FromCols = FromMatrixType->getNumColumns();
2161 unsigned ToCols = ToMatrixType->getNumColumns();
2162 if (FromCols < ToCols)
2163 return false;
2164
2165 unsigned FromRows = FromMatrixType->getNumRows();
2166 unsigned ToRows = ToMatrixType->getNumRows();
2167 if (FromRows < ToRows)
2168 return false;
2169
2170 if (FromRows == ToRows && FromCols == ToCols)
2171 ElConv = ICK_Identity;
2172 else
2174
2175 QualType FromElTy = FromMatrixType->getElementType();
2176 QualType ToElTy = ToMatrixType->getElementType();
2177 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2178 return true;
2179 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2180 }
2181
2182 // Matrix splat from any arithmetic type to a matrix.
2183 if (ToMatrixType && FromType->isArithmeticType()) {
2184 ElConv = ICK_HLSL_Matrix_Splat;
2185 QualType ToElTy = ToMatrixType->getElementType();
2186 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK, From);
2187 }
2188 if (FromMatrixType && !ToMatrixType) {
2190 QualType FromElTy = FromMatrixType->getElementType();
2191 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2192 return true;
2193 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2194 }
2195
2196 return false;
2197}
2198
2199/// Determine whether the conversion from FromType to ToType is a valid
2200/// vector conversion.
2201///
2202/// \param ICK Will be set to the vector conversion kind, if this is a vector
2203/// conversion.
2204static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2206 ImplicitConversionKind &ElConv, Expr *From,
2207 bool InOverloadResolution, bool CStyle) {
2208 // We need at least one of these types to be a vector type to have a vector
2209 // conversion.
2210 if (!ToType->isVectorType() && !FromType->isVectorType())
2211 return false;
2212
2213 // Identical types require no conversions.
2214 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2215 return false;
2216
2217 // HLSL allows implicit truncation of vector types.
2218 if (S.getLangOpts().HLSL) {
2219 auto *ToExtType = ToType->getAs<ExtVectorType>();
2220 auto *FromExtType = FromType->getAs<ExtVectorType>();
2221
2222 // If both arguments are vectors, handle possible vector truncation and
2223 // element conversion.
2224 if (ToExtType && FromExtType) {
2225 unsigned FromElts = FromExtType->getNumElements();
2226 unsigned ToElts = ToExtType->getNumElements();
2227 if (FromElts < ToElts)
2228 return false;
2229 if (FromElts == ToElts)
2230 ElConv = ICK_Identity;
2231 else
2233
2234 QualType FromElTy = FromExtType->getElementType();
2235 QualType ToElTy = ToExtType->getElementType();
2236 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2237 return true;
2238 return IsVectorOrMatrixElementConversion(S, FromElTy, ToElTy, ICK, From);
2239 }
2240 if (FromExtType && !ToExtType) {
2242 QualType FromElTy = FromExtType->getElementType();
2243 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2244 return true;
2245 return IsVectorOrMatrixElementConversion(S, FromElTy, ToType, ICK, From);
2246 }
2247 // Fallthrough for the case where ToType is a vector and FromType is not.
2248 }
2249
2250 // There are no conversions between extended vector types, only identity.
2251 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2252 if (auto *FromExtType = FromType->getAs<ExtVectorType>()) {
2253 // Implicit conversions require the same number of elements.
2254 if (ToExtType->getNumElements() != FromExtType->getNumElements())
2255 return false;
2256
2257 // Permit implicit conversions from integral values to boolean vectors.
2258 if (ToType->isExtVectorBoolType() &&
2259 FromExtType->getElementType()->isIntegerType()) {
2261 return true;
2262 }
2263 // There are no other conversions between extended vector types.
2264 return false;
2265 }
2266
2267 // Vector splat from any arithmetic type to a vector.
2268 if (FromType->isArithmeticType()) {
2269 if (S.getLangOpts().HLSL) {
2270 ElConv = ICK_HLSL_Vector_Splat;
2271 QualType ToElTy = ToExtType->getElementType();
2272 return IsVectorOrMatrixElementConversion(S, FromType, ToElTy, ICK,
2273 From);
2274 }
2275 ICK = ICK_Vector_Splat;
2276 return true;
2277 }
2278 }
2279
2280 if (ToType->isSVESizelessBuiltinType() ||
2281 FromType->isSVESizelessBuiltinType())
2282 if (S.ARM().areCompatibleSveTypes(FromType, ToType) ||
2283 S.ARM().areLaxCompatibleSveTypes(FromType, ToType)) {
2285 return true;
2286 }
2287
2288 if (ToType->isRVVSizelessBuiltinType() ||
2289 FromType->isRVVSizelessBuiltinType())
2290 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2291 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2293 return true;
2294 }
2295
2296 // We can perform the conversion between vector types in the following cases:
2297 // 1)vector types are equivalent AltiVec and GCC vector types
2298 // 2)lax vector conversions are permitted and the vector types are of the
2299 // same size
2300 // 3)the destination type does not have the ARM MVE strict-polymorphism
2301 // attribute, which inhibits lax vector conversion for overload resolution
2302 // only
2303 if (ToType->isVectorType() && FromType->isVectorType()) {
2304 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2305 (S.isLaxVectorConversion(FromType, ToType) &&
2306 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2307 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2308 S.isLaxVectorConversion(FromType, ToType) &&
2309 S.anyAltivecTypes(FromType, ToType) &&
2310 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2311 !InOverloadResolution && !CStyle) {
2312 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2313 << FromType << ToType;
2314 }
2316 return true;
2317 }
2318 }
2319
2320 return false;
2321}
2322
2323static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2324 bool InOverloadResolution,
2325 StandardConversionSequence &SCS,
2326 bool CStyle);
2327
2328static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From,
2329 QualType ToType,
2330 bool InOverloadResolution,
2331 StandardConversionSequence &SCS,
2332 bool CStyle);
2333
2334/// IsStandardConversion - Determines whether there is a standard
2335/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2336/// expression From to the type ToType. Standard conversion sequences
2337/// only consider non-class types; for conversions that involve class
2338/// types, use TryImplicitConversion. If a conversion exists, SCS will
2339/// contain the standard conversion sequence required to perform this
2340/// conversion and this routine will return true. Otherwise, this
2341/// routine will return false and the value of SCS is unspecified.
2342static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2343 bool InOverloadResolution,
2345 bool CStyle,
2346 bool AllowObjCWritebackConversion) {
2347 QualType FromType = From->getType();
2348
2349 // Standard conversions (C++ [conv])
2351 SCS.IncompatibleObjC = false;
2352 SCS.setFromType(FromType);
2353 SCS.CopyConstructor = nullptr;
2354
2355 // There are no standard conversions for class types in C++, so
2356 // abort early. When overloading in C, however, we do permit them.
2357 if (S.getLangOpts().CPlusPlus &&
2358 (FromType->isRecordType() || ToType->isRecordType()))
2359 return false;
2360
2361 // The first conversion can be an lvalue-to-rvalue conversion,
2362 // array-to-pointer conversion, or function-to-pointer conversion
2363 // (C++ 4p1).
2364
2365 if (FromType == S.Context.OverloadTy) {
2366 DeclAccessPair AccessPair;
2367 if (FunctionDecl *Fn
2368 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2369 AccessPair)) {
2370 // We were able to resolve the address of the overloaded function,
2371 // so we can convert to the type of that function.
2372 FromType = Fn->getType();
2373 SCS.setFromType(FromType);
2374
2375 // we can sometimes resolve &foo<int> regardless of ToType, so check
2376 // if the type matches (identity) or we are converting to bool
2378 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2379 // if the function type matches except for [[noreturn]], it's ok
2380 if (!S.IsFunctionConversion(FromType,
2382 // otherwise, only a boolean conversion is standard
2383 if (!ToType->isBooleanType())
2384 return false;
2385 }
2386
2387 // Check if the "from" expression is taking the address of an overloaded
2388 // function and recompute the FromType accordingly. Take advantage of the
2389 // fact that non-static member functions *must* have such an address-of
2390 // expression.
2391 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2392 if (Method && !Method->isStatic() &&
2393 !Method->isExplicitObjectMemberFunction()) {
2394 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2395 "Non-unary operator on non-static member address");
2396 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2397 == UO_AddrOf &&
2398 "Non-address-of operator on non-static member address");
2399 FromType = S.Context.getMemberPointerType(
2400 FromType, /*Qualifier=*/std::nullopt, Method->getParent());
2401 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2402 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2403 UO_AddrOf &&
2404 "Non-address-of operator for overloaded function expression");
2405 FromType = S.Context.getPointerType(FromType);
2406 }
2407 } else {
2408 return false;
2409 }
2410 }
2411
2412 bool argIsLValue = From->isGLValue();
2413 // To handle conversion from ArrayParameterType to ConstantArrayType
2414 // this block must be above the one below because Array parameters
2415 // do not decay and when handling HLSLOutArgExprs and
2416 // the From expression is an LValue.
2417 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2418 ToType->isConstantArrayType()) {
2419 // HLSL constant array parameters do not decay, so if the argument is a
2420 // constant array and the parameter is an ArrayParameterType we have special
2421 // handling here.
2422 if (ToType->isArrayParameterType()) {
2423 FromType = S.Context.getArrayParameterType(FromType);
2424 } else if (FromType->isArrayParameterType()) {
2425 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2426 FromType = APT->getConstantArrayType(S.Context);
2427 }
2428
2430
2431 // Don't consider qualifiers, which include things like address spaces
2432 if (FromType.getCanonicalType().getUnqualifiedType() !=
2434 return false;
2435
2436 SCS.setAllToTypes(ToType);
2437 return true;
2438 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2439 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2440 // Lvalue-to-rvalue conversion (C++11 4.1):
2441 // A glvalue (3.10) of a non-function, non-array type T can
2442 // be converted to a prvalue.
2443
2445
2446 // C11 6.3.2.1p2:
2447 // ... if the lvalue has atomic type, the value has the non-atomic version
2448 // of the type of the lvalue ...
2449 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2450 FromType = Atomic->getValueType();
2451
2452 // If T is a non-class type, the type of the rvalue is the
2453 // cv-unqualified version of T. Otherwise, the type of the rvalue
2454 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2455 // just strip the qualifiers because they don't matter.
2456 FromType = FromType.getUnqualifiedType();
2457 } else if (FromType->isArrayType()) {
2458 // Array-to-pointer conversion (C++ 4.2)
2460
2461 // An lvalue or rvalue of type "array of N T" or "array of unknown
2462 // bound of T" can be converted to an rvalue of type "pointer to
2463 // T" (C++ 4.2p1).
2464 FromType = S.Context.getArrayDecayedType(FromType);
2465
2466 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2467 // This conversion is deprecated in C++03 (D.4)
2469
2470 // For the purpose of ranking in overload resolution
2471 // (13.3.3.1.1), this conversion is considered an
2472 // array-to-pointer conversion followed by a qualification
2473 // conversion (4.4). (C++ 4.2p2)
2474 SCS.Second = ICK_Identity;
2477 SCS.setAllToTypes(FromType);
2478 return true;
2479 }
2480 } else if (FromType->isFunctionType() && argIsLValue) {
2481 // Function-to-pointer conversion (C++ 4.3).
2483
2484 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2485 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2487 return false;
2488
2489 // An lvalue of function type T can be converted to an rvalue of
2490 // type "pointer to T." The result is a pointer to the
2491 // function. (C++ 4.3p1).
2492 FromType = S.Context.getPointerType(FromType);
2493 } else {
2494 // We don't require any conversions for the first step.
2495 SCS.First = ICK_Identity;
2496 }
2497 SCS.setToType(0, FromType);
2498
2499 // The second conversion can be an integral promotion, floating
2500 // point promotion, integral conversion, floating point conversion,
2501 // floating-integral conversion, pointer conversion,
2502 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2503 // For overloading in C, this can also be a "compatible-type"
2504 // conversion.
2505 bool IncompatibleObjC = false;
2507 ImplicitConversionKind DimensionICK = ICK_Identity;
2508 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2509 // The unqualified versions of the types are the same: there's no
2510 // conversion to do.
2511 SCS.Second = ICK_Identity;
2512 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2513 // Integral promotion (C++ 4.5).
2515 FromType = ToType.getUnqualifiedType();
2516 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2517 // Floating point promotion (C++ 4.6).
2519 FromType = ToType.getUnqualifiedType();
2520 } else if (S.IsComplexPromotion(FromType, ToType)) {
2521 // Complex promotion (Clang extension)
2523 FromType = ToType.getUnqualifiedType();
2524 } else if (S.IsOverflowBehaviorTypePromotion(FromType, ToType)) {
2525 // OverflowBehaviorType promotions
2527 FromType = ToType.getUnqualifiedType();
2528 } else if (S.IsOverflowBehaviorTypeConversion(FromType, ToType)) {
2529 // OverflowBehaviorType conversions
2531 FromType = ToType.getUnqualifiedType();
2532 } else if (ToType->isBooleanType() &&
2533 (FromType->isArithmeticType() || FromType->isAnyPointerType() ||
2534 FromType->isBlockPointerType() ||
2535 FromType->isMemberPointerType())) {
2536 // Boolean conversions (C++ 4.12).
2538 FromType = S.Context.BoolTy;
2539 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2540 ToType->isIntegralType(S.Context)) {
2541 // Integral conversions (C++ 4.7).
2543 FromType = ToType.getUnqualifiedType();
2544 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2545 // Complex conversions (C99 6.3.1.6)
2547 FromType = ToType.getUnqualifiedType();
2548 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2549 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2550 // Complex-real conversions (C99 6.3.1.7)
2552 FromType = ToType.getUnqualifiedType();
2553 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2554 // Floating point conversions (C++ 4.8).
2556 FromType = ToType.getUnqualifiedType();
2557 } else if ((FromType->isRealFloatingType() &&
2558 ToType->isIntegralType(S.Context)) ||
2560 ToType->isRealFloatingType())) {
2561
2562 // Floating-integral conversions (C++ 4.9).
2564 FromType = ToType.getUnqualifiedType();
2565 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2567 } else if (AllowObjCWritebackConversion &&
2568 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2570 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2571 FromType, IncompatibleObjC)) {
2572 // Pointer conversions (C++ 4.10).
2574 SCS.IncompatibleObjC = IncompatibleObjC;
2575 FromType = FromType.getUnqualifiedType();
2576 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2577 InOverloadResolution, FromType)) {
2578 // Pointer to member conversions (4.11).
2580 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2581 From, InOverloadResolution, CStyle)) {
2582 SCS.Second = SecondICK;
2583 SCS.Dimension = DimensionICK;
2584 FromType = ToType.getUnqualifiedType();
2585 } else if (IsMatrixConversion(S, FromType, ToType, SecondICK, DimensionICK,
2586 From, InOverloadResolution, CStyle)) {
2587 SCS.Second = SecondICK;
2588 SCS.Dimension = DimensionICK;
2589 FromType = ToType.getUnqualifiedType();
2590 } else if (!S.getLangOpts().CPlusPlus &&
2591 S.Context.typesAreCompatible(ToType, FromType)) {
2592 // Compatible conversions (Clang extension for C function overloading)
2594 FromType = ToType.getUnqualifiedType();
2596 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2598 FromType = ToType;
2599 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2600 CStyle)) {
2601 // tryAtomicConversion has updated the standard conversion sequence
2602 // appropriately.
2603 return true;
2605 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2606 return true;
2607 } else if (ToType->isEventT() &&
2609 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2611 FromType = ToType;
2612 } else if (ToType->isQueueT() &&
2614 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2616 FromType = ToType;
2617 } else if (ToType->isSamplerT() &&
2620 FromType = ToType;
2621 } else if ((ToType->isFixedPointType() &&
2622 FromType->isConvertibleToFixedPointType()) ||
2623 (FromType->isFixedPointType() &&
2624 ToType->isConvertibleToFixedPointType())) {
2626 FromType = ToType;
2627 } else {
2628 // No second conversion required.
2629 SCS.Second = ICK_Identity;
2630 }
2631 SCS.setToType(1, FromType);
2632
2633 // The third conversion can be a function pointer conversion or a
2634 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2635 bool ObjCLifetimeConversion;
2636 if (S.TryFunctionConversion(FromType, ToType, FromType)) {
2637 // Function pointer conversions (removing 'noexcept') including removal of
2638 // 'noreturn' (Clang extension).
2640 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2641 ObjCLifetimeConversion)) {
2643 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2644 FromType = ToType;
2645 } else {
2646 // No conversion required
2647 SCS.Third = ICK_Identity;
2648 }
2649
2650 // C++ [over.best.ics]p6:
2651 // [...] Any difference in top-level cv-qualification is
2652 // subsumed by the initialization itself and does not constitute
2653 // a conversion. [...]
2654 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2655 QualType CanonTo = S.Context.getCanonicalType(ToType);
2656 if (CanonFrom.getLocalUnqualifiedType()
2657 == CanonTo.getLocalUnqualifiedType() &&
2658 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2659 FromType = ToType;
2660 CanonFrom = CanonTo;
2661 }
2662
2663 SCS.setToType(2, FromType);
2664
2665 if (CanonFrom == CanonTo)
2666 return true;
2667
2668 // If we have not converted the argument type to the parameter type,
2669 // this is a bad conversion sequence, unless we're resolving an overload in C.
2670 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
2671 return false;
2672
2673 ExprResult ER = ExprResult{From};
2674 AssignConvertType Conv =
2676 /*Diagnose=*/false,
2677 /*DiagnoseCFAudited=*/false,
2678 /*ConvertRHS=*/false);
2679 ImplicitConversionKind SecondConv;
2680 switch (Conv) {
2682 case AssignConvertType::
2683 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2684 SecondConv = ICK_C_Only_Conversion;
2685 break;
2686 // For our purposes, discarding qualifiers is just as bad as using an
2687 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2688 // qualifiers, as well.
2693 break;
2694 default:
2695 return false;
2696 }
2697
2698 // First can only be an lvalue conversion, so we pretend that this was the
2699 // second conversion. First should already be valid from earlier in the
2700 // function.
2701 SCS.Second = SecondConv;
2702 SCS.setToType(1, ToType);
2703
2704 // Third is Identity, because Second should rank us worse than any other
2705 // conversion. This could also be ICK_Qualification, but it's simpler to just
2706 // lump everything in with the second conversion, and we don't gain anything
2707 // from making this ICK_Qualification.
2708 SCS.Third = ICK_Identity;
2709 SCS.setToType(2, ToType);
2710 return true;
2711}
2712
2713static bool
2715 QualType &ToType,
2716 bool InOverloadResolution,
2718 bool CStyle) {
2719
2720 const RecordType *UT = ToType->getAsUnionType();
2721 if (!UT)
2722 return false;
2723 // The field to initialize within the transparent union.
2724 const RecordDecl *UD = UT->getDecl()->getDefinitionOrSelf();
2725 if (!UD->hasAttr<TransparentUnionAttr>())
2726 return false;
2727 // It's compatible if the expression matches any of the fields.
2728 for (const auto *it : UD->fields()) {
2729 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2730 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2731 ToType = it->getType();
2732 return true;
2733 }
2734 }
2735 return false;
2736}
2737
2738bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2739 const BuiltinType *To = ToType->getAs<BuiltinType>();
2740 // All integers are built-in.
2741 if (!To) {
2742 return false;
2743 }
2744
2745 // An rvalue of type char, signed char, unsigned char, short int, or
2746 // unsigned short int can be converted to an rvalue of type int if
2747 // int can represent all the values of the source type; otherwise,
2748 // the source rvalue can be converted to an rvalue of type unsigned
2749 // int (C++ 4.5p1).
2750 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2751 !FromType->isEnumeralType()) {
2752 if ( // We can promote any signed, promotable integer type to an int
2753 (FromType->isSignedIntegerType() ||
2754 // We can promote any unsigned integer type whose size is
2755 // less than int to an int.
2756 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2757 return To->getKind() == BuiltinType::Int;
2758 }
2759
2760 return To->getKind() == BuiltinType::UInt;
2761 }
2762
2763 // C++11 [conv.prom]p3:
2764 // A prvalue of an unscoped enumeration type whose underlying type is not
2765 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2766 // following types that can represent all the values of the enumeration
2767 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2768 // unsigned int, long int, unsigned long int, long long int, or unsigned
2769 // long long int. If none of the types in that list can represent all the
2770 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2771 // type can be converted to an rvalue a prvalue of the extended integer type
2772 // with lowest integer conversion rank (4.13) greater than the rank of long
2773 // long in which all the values of the enumeration can be represented. If
2774 // there are two such extended types, the signed one is chosen.
2775 // C++11 [conv.prom]p4:
2776 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2777 // can be converted to a prvalue of its underlying type. Moreover, if
2778 // integral promotion can be applied to its underlying type, a prvalue of an
2779 // unscoped enumeration type whose underlying type is fixed can also be
2780 // converted to a prvalue of the promoted underlying type.
2781 if (const auto *FromED = FromType->getAsEnumDecl()) {
2782 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2783 // provided for a scoped enumeration.
2784 if (FromED->isScoped())
2785 return false;
2786
2787 // We can perform an integral promotion to the underlying type of the enum,
2788 // even if that's not the promoted type. Note that the check for promoting
2789 // the underlying type is based on the type alone, and does not consider
2790 // the bitfield-ness of the actual source expression.
2791 if (FromED->isFixed()) {
2792 QualType Underlying = FromED->getIntegerType();
2793 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2794 IsIntegralPromotion(nullptr, Underlying, ToType);
2795 }
2796
2797 // We have already pre-calculated the promotion type, so this is trivial.
2798 if (ToType->isIntegerType() &&
2799 isCompleteType(From->getBeginLoc(), FromType))
2800 return Context.hasSameUnqualifiedType(ToType, FromED->getPromotionType());
2801
2802 // C++ [conv.prom]p5:
2803 // If the bit-field has an enumerated type, it is treated as any other
2804 // value of that type for promotion purposes.
2805 //
2806 // ... so do not fall through into the bit-field checks below in C++.
2807 if (getLangOpts().CPlusPlus)
2808 return false;
2809 }
2810
2811 // C++0x [conv.prom]p2:
2812 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2813 // to an rvalue a prvalue of the first of the following types that can
2814 // represent all the values of its underlying type: int, unsigned int,
2815 // long int, unsigned long int, long long int, or unsigned long long int.
2816 // If none of the types in that list can represent all the values of its
2817 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2818 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2819 // type.
2820 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2821 ToType->isIntegerType()) {
2822 // Determine whether the type we're converting from is signed or
2823 // unsigned.
2824 bool FromIsSigned = FromType->isSignedIntegerType();
2825 uint64_t FromSize = Context.getTypeSize(FromType);
2826
2827 // The types we'll try to promote to, in the appropriate
2828 // order. Try each of these types.
2829 QualType PromoteTypes[6] = {
2830 Context.IntTy, Context.UnsignedIntTy,
2831 Context.LongTy, Context.UnsignedLongTy ,
2832 Context.LongLongTy, Context.UnsignedLongLongTy
2833 };
2834 for (int Idx = 0; Idx < 6; ++Idx) {
2835 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2836 if (FromSize < ToSize ||
2837 (FromSize == ToSize &&
2838 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2839 // We found the type that we can promote to. If this is the
2840 // type we wanted, we have a promotion. Otherwise, no
2841 // promotion.
2842 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2843 }
2844 }
2845 }
2846
2847 // An rvalue for an integral bit-field (9.6) can be converted to an
2848 // rvalue of type int if int can represent all the values of the
2849 // bit-field; otherwise, it can be converted to unsigned int if
2850 // unsigned int can represent all the values of the bit-field. If
2851 // the bit-field is larger yet, no integral promotion applies to
2852 // it. If the bit-field has an enumerated type, it is treated as any
2853 // other value of that type for promotion purposes (C++ 4.5p3).
2854 // FIXME: We should delay checking of bit-fields until we actually perform the
2855 // conversion.
2856 //
2857 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2858 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2859 // bit-fields and those whose underlying type is larger than int) for GCC
2860 // compatibility.
2861 if (From) {
2862 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2863 std::optional<llvm::APSInt> BitWidth;
2864 if (FromType->isIntegralType(Context) &&
2865 (BitWidth =
2866 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2867 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2868 ToSize = Context.getTypeSize(ToType);
2869
2870 // Are we promoting to an int from a bitfield that fits in an int?
2871 if (*BitWidth < ToSize ||
2872 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2873 return To->getKind() == BuiltinType::Int;
2874 }
2875
2876 // Are we promoting to an unsigned int from an unsigned bitfield
2877 // that fits into an unsigned int?
2878 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2879 return To->getKind() == BuiltinType::UInt;
2880 }
2881
2882 return false;
2883 }
2884 }
2885 }
2886
2887 // An rvalue of type bool can be converted to an rvalue of type int,
2888 // with false becoming zero and true becoming one (C++ 4.5p4).
2889 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2890 return true;
2891 }
2892
2893 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2894 // integral type.
2895 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2896 ToType->isIntegerType())
2897 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2898
2899 return false;
2900}
2901
2903 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2904 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2905 /// An rvalue of type float can be converted to an rvalue of type
2906 /// double. (C++ 4.6p1).
2907 if (FromBuiltin->getKind() == BuiltinType::Float &&
2908 ToBuiltin->getKind() == BuiltinType::Double)
2909 return true;
2910
2911 // C99 6.3.1.5p1:
2912 // When a float is promoted to double or long double, or a
2913 // double is promoted to long double [...].
2914 if (!getLangOpts().CPlusPlus &&
2915 (FromBuiltin->getKind() == BuiltinType::Float ||
2916 FromBuiltin->getKind() == BuiltinType::Double) &&
2917 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2918 ToBuiltin->getKind() == BuiltinType::Float128 ||
2919 ToBuiltin->getKind() == BuiltinType::Ibm128))
2920 return true;
2921
2922 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2923 // or not native half types are enabled.
2924 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2925 (ToBuiltin->getKind() == BuiltinType::Float ||
2926 ToBuiltin->getKind() == BuiltinType::Double))
2927 return true;
2928
2929 // Half can be promoted to float.
2930 if (!getLangOpts().NativeHalfType &&
2931 FromBuiltin->getKind() == BuiltinType::Half &&
2932 ToBuiltin->getKind() == BuiltinType::Float)
2933 return true;
2934 }
2935
2936 return false;
2937}
2938
2940 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2941 if (!FromComplex)
2942 return false;
2943
2944 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2945 if (!ToComplex)
2946 return false;
2947
2948 return IsFloatingPointPromotion(FromComplex->getElementType(),
2949 ToComplex->getElementType()) ||
2950 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2951 ToComplex->getElementType());
2952}
2953
2955 if (!getLangOpts().OverflowBehaviorTypes)
2956 return false;
2957
2958 if (!FromType->isOverflowBehaviorType() || !ToType->isOverflowBehaviorType())
2959 return false;
2960
2961 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2962}
2963
2965 QualType ToType) {
2966 if (!getLangOpts().OverflowBehaviorTypes)
2967 return false;
2968
2969 if (FromType->isOverflowBehaviorType() && !ToType->isOverflowBehaviorType()) {
2970 if (ToType->isBooleanType())
2971 return false;
2972 // Don't allow implicit conversion from OverflowBehaviorType to scoped enum
2973 if (const EnumType *ToEnumType = ToType->getAs<EnumType>()) {
2974 const EnumDecl *ToED = ToEnumType->getDecl()->getDefinitionOrSelf();
2975 if (ToED->isScoped())
2976 return false;
2977 }
2978 return true;
2979 }
2980
2981 if (!FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2982 return true;
2983
2984 if (FromType->isOverflowBehaviorType() && ToType->isOverflowBehaviorType())
2985 return Context.getTypeSize(FromType) > Context.getTypeSize(ToType);
2986
2987 return false;
2988}
2989
2990/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2991/// the pointer type FromPtr to a pointer to type ToPointee, with the
2992/// same type qualifiers as FromPtr has on its pointee type. ToType,
2993/// if non-empty, will be a pointer to ToType that may or may not have
2994/// the right set of qualifiers on its pointee.
2995///
2996static QualType
2998 QualType ToPointee, QualType ToType,
2999 ASTContext &Context,
3000 bool StripObjCLifetime = false) {
3001 assert((FromPtr->getTypeClass() == Type::Pointer ||
3002 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
3003 "Invalid similarly-qualified pointer type");
3004
3005 /// Conversions to 'id' subsume cv-qualifier conversions.
3006 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
3007 return ToType.getUnqualifiedType();
3008
3009 QualType CanonFromPointee
3010 = Context.getCanonicalType(FromPtr->getPointeeType());
3011 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
3012 Qualifiers Quals = CanonFromPointee.getQualifiers();
3013
3014 if (StripObjCLifetime)
3015 Quals.removeObjCLifetime();
3016
3017 // Exact qualifier match -> return the pointer type we're converting to.
3018 if (CanonToPointee.getLocalQualifiers() == Quals) {
3019 // ToType is exactly what we need. Return it.
3020 if (!ToType.isNull())
3021 return ToType.getUnqualifiedType();
3022
3023 // Build a pointer to ToPointee. It has the right qualifiers
3024 // already.
3025 if (isa<ObjCObjectPointerType>(ToType))
3026 return Context.getObjCObjectPointerType(ToPointee);
3027 return Context.getPointerType(ToPointee);
3028 }
3029
3030 // Just build a canonical type that has the right qualifiers.
3031 QualType QualifiedCanonToPointee
3032 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
3033
3034 if (isa<ObjCObjectPointerType>(ToType))
3035 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
3036 return Context.getPointerType(QualifiedCanonToPointee);
3037}
3038
3040 bool InOverloadResolution,
3041 ASTContext &Context) {
3042 // Handle value-dependent integral null pointer constants correctly.
3043 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
3044 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
3046 return !InOverloadResolution;
3047
3048 return Expr->isNullPointerConstant(Context,
3049 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3051}
3052
3054 bool InOverloadResolution,
3055 QualType& ConvertedType,
3056 bool &IncompatibleObjC) {
3057 IncompatibleObjC = false;
3058 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
3059 IncompatibleObjC))
3060 return true;
3061
3062 // Conversion from a null pointer constant to any Objective-C pointer type.
3063 if (ToType->isObjCObjectPointerType() &&
3064 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3065 ConvertedType = ToType;
3066 return true;
3067 }
3068
3069 // Blocks: Block pointers can be converted to void*.
3070 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
3071 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
3072 ConvertedType = ToType;
3073 return true;
3074 }
3075 // Blocks: A null pointer constant can be converted to a block
3076 // pointer type.
3077 if (ToType->isBlockPointerType() &&
3078 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3079 ConvertedType = ToType;
3080 return true;
3081 }
3082
3083 // If the left-hand-side is nullptr_t, the right side can be a null
3084 // pointer constant.
3085 if (ToType->isNullPtrType() &&
3086 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3087 ConvertedType = ToType;
3088 return true;
3089 }
3090
3091 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
3092 if (!ToTypePtr)
3093 return false;
3094
3095 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
3096 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
3097 ConvertedType = ToType;
3098 return true;
3099 }
3100
3101 // Beyond this point, both types need to be pointers
3102 // , including objective-c pointers.
3103 QualType ToPointeeType = ToTypePtr->getPointeeType();
3104 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
3105 !getLangOpts().ObjCAutoRefCount) {
3106 ConvertedType = BuildSimilarlyQualifiedPointerType(
3107 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
3108 Context);
3109 return true;
3110 }
3111 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
3112 if (!FromTypePtr)
3113 return false;
3114
3115 QualType FromPointeeType = FromTypePtr->getPointeeType();
3116
3117 // If the unqualified pointee types are the same, this can't be a
3118 // pointer conversion, so don't do all of the work below.
3119 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
3120 return false;
3121
3122 // An rvalue of type "pointer to cv T," where T is an object type,
3123 // can be converted to an rvalue of type "pointer to cv void" (C++
3124 // 4.10p2).
3125 if (FromPointeeType->isIncompleteOrObjectType() &&
3126 ToPointeeType->isVoidType()) {
3127 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3128 ToPointeeType,
3129 ToType, Context,
3130 /*StripObjCLifetime=*/true);
3131 return true;
3132 }
3133
3134 // MSVC allows implicit function to void* type conversion.
3135 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
3136 ToPointeeType->isVoidType()) {
3137 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3138 ToPointeeType,
3139 ToType, Context);
3140 return true;
3141 }
3142
3143 // When we're overloading in C, we allow a special kind of pointer
3144 // conversion for compatible-but-not-identical pointee types.
3145 if (!getLangOpts().CPlusPlus &&
3146 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
3147 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3148 ToPointeeType,
3149 ToType, Context);
3150 return true;
3151 }
3152
3153 // C++ [conv.ptr]p3:
3154 //
3155 // An rvalue of type "pointer to cv D," where D is a class type,
3156 // can be converted to an rvalue of type "pointer to cv B," where
3157 // B is a base class (clause 10) of D. If B is an inaccessible
3158 // (clause 11) or ambiguous (10.2) base class of D, a program that
3159 // necessitates this conversion is ill-formed. The result of the
3160 // conversion is a pointer to the base class sub-object of the
3161 // derived class object. The null pointer value is converted to
3162 // the null pointer value of the destination type.
3163 //
3164 // Note that we do not check for ambiguity or inaccessibility
3165 // here. That is handled by CheckPointerConversion.
3166 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3167 ToPointeeType->isRecordType() &&
3168 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
3169 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
3170 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3171 ToPointeeType,
3172 ToType, Context);
3173 return true;
3174 }
3175
3176 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3177 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
3178 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3179 ToPointeeType,
3180 ToType, Context);
3181 return true;
3182 }
3183
3184 return false;
3185}
3186
3187/// Adopt the given qualifiers for the given type.
3189 Qualifiers TQs = T.getQualifiers();
3190
3191 // Check whether qualifiers already match.
3192 if (TQs == Qs)
3193 return T;
3194
3195 if (Qs.compatiblyIncludes(TQs, Context))
3196 return Context.getQualifiedType(T, Qs);
3197
3198 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
3199}
3200
3202 QualType& ConvertedType,
3203 bool &IncompatibleObjC) {
3204 if (!getLangOpts().ObjC)
3205 return false;
3206
3207 // The set of qualifiers on the type we're converting from.
3208 Qualifiers FromQualifiers = FromType.getQualifiers();
3209
3210 // First, we handle all conversions on ObjC object pointer types.
3211 const ObjCObjectPointerType* ToObjCPtr =
3212 ToType->getAs<ObjCObjectPointerType>();
3213 const ObjCObjectPointerType *FromObjCPtr =
3214 FromType->getAs<ObjCObjectPointerType>();
3215
3216 if (ToObjCPtr && FromObjCPtr) {
3217 // If the pointee types are the same (ignoring qualifications),
3218 // then this is not a pointer conversion.
3219 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
3220 FromObjCPtr->getPointeeType()))
3221 return false;
3222
3223 // Conversion between Objective-C pointers.
3224 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3225 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3226 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3227 if (getLangOpts().CPlusPlus && LHS && RHS &&
3229 FromObjCPtr->getPointeeType(), getASTContext()))
3230 return false;
3231 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3232 ToObjCPtr->getPointeeType(),
3233 ToType, Context);
3234 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3235 return true;
3236 }
3237
3238 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3239 // Okay: this is some kind of implicit downcast of Objective-C
3240 // interfaces, which is permitted. However, we're going to
3241 // complain about it.
3242 IncompatibleObjC = true;
3243 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3244 ToObjCPtr->getPointeeType(),
3245 ToType, Context);
3246 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3247 return true;
3248 }
3249 }
3250 // Beyond this point, both types need to be C pointers or block pointers.
3251 QualType ToPointeeType;
3252 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3253 ToPointeeType = ToCPtr->getPointeeType();
3254 else if (const BlockPointerType *ToBlockPtr =
3255 ToType->getAs<BlockPointerType>()) {
3256 // Objective C++: We're able to convert from a pointer to any object
3257 // to a block pointer type.
3258 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3259 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3260 return true;
3261 }
3262 ToPointeeType = ToBlockPtr->getPointeeType();
3263 }
3264 else if (FromType->getAs<BlockPointerType>() &&
3265 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3266 // Objective C++: We're able to convert from a block pointer type to a
3267 // pointer to any object.
3268 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3269 return true;
3270 }
3271 else
3272 return false;
3273
3274 QualType FromPointeeType;
3275 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3276 FromPointeeType = FromCPtr->getPointeeType();
3277 else if (const BlockPointerType *FromBlockPtr =
3278 FromType->getAs<BlockPointerType>())
3279 FromPointeeType = FromBlockPtr->getPointeeType();
3280 else
3281 return false;
3282
3283 // If we have pointers to pointers, recursively check whether this
3284 // is an Objective-C conversion.
3285 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3286 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3287 IncompatibleObjC)) {
3288 // We always complain about this conversion.
3289 IncompatibleObjC = true;
3290 ConvertedType = Context.getPointerType(ConvertedType);
3291 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3292 return true;
3293 }
3294 // Allow conversion of pointee being objective-c pointer to another one;
3295 // as in I* to id.
3296 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3297 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3298 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3299 IncompatibleObjC)) {
3300
3301 ConvertedType = Context.getPointerType(ConvertedType);
3302 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3303 return true;
3304 }
3305
3306 // If we have pointers to functions or blocks, check whether the only
3307 // differences in the argument and result types are in Objective-C
3308 // pointer conversions. If so, we permit the conversion (but
3309 // complain about it).
3310 const FunctionProtoType *FromFunctionType
3311 = FromPointeeType->getAs<FunctionProtoType>();
3312 const FunctionProtoType *ToFunctionType
3313 = ToPointeeType->getAs<FunctionProtoType>();
3314 if (FromFunctionType && ToFunctionType) {
3315 // If the function types are exactly the same, this isn't an
3316 // Objective-C pointer conversion.
3317 if (Context.getCanonicalType(FromPointeeType)
3318 == Context.getCanonicalType(ToPointeeType))
3319 return false;
3320
3321 // Perform the quick checks that will tell us whether these
3322 // function types are obviously different.
3323 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3324 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3325 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3326 return false;
3327
3328 bool HasObjCConversion = false;
3329 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3330 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3331 // Okay, the types match exactly. Nothing to do.
3332 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3333 ToFunctionType->getReturnType(),
3334 ConvertedType, IncompatibleObjC)) {
3335 // Okay, we have an Objective-C pointer conversion.
3336 HasObjCConversion = true;
3337 } else {
3338 // Function types are too different. Abort.
3339 return false;
3340 }
3341
3342 // Check argument types.
3343 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3344 ArgIdx != NumArgs; ++ArgIdx) {
3345 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3346 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3347 if (Context.getCanonicalType(FromArgType)
3348 == Context.getCanonicalType(ToArgType)) {
3349 // Okay, the types match exactly. Nothing to do.
3350 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3351 ConvertedType, IncompatibleObjC)) {
3352 // Okay, we have an Objective-C pointer conversion.
3353 HasObjCConversion = true;
3354 } else {
3355 // Argument types are too different. Abort.
3356 return false;
3357 }
3358 }
3359
3360 if (HasObjCConversion) {
3361 // We had an Objective-C conversion. Allow this pointer
3362 // conversion, but complain about it.
3363 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3364 IncompatibleObjC = true;
3365 return true;
3366 }
3367 }
3368
3369 return false;
3370}
3371
3373 QualType& ConvertedType) {
3374 QualType ToPointeeType;
3375 if (const BlockPointerType *ToBlockPtr =
3376 ToType->getAs<BlockPointerType>())
3377 ToPointeeType = ToBlockPtr->getPointeeType();
3378 else
3379 return false;
3380
3381 QualType FromPointeeType;
3382 if (const BlockPointerType *FromBlockPtr =
3383 FromType->getAs<BlockPointerType>())
3384 FromPointeeType = FromBlockPtr->getPointeeType();
3385 else
3386 return false;
3387 // We have pointer to blocks, check whether the only
3388 // differences in the argument and result types are in Objective-C
3389 // pointer conversions. If so, we permit the conversion.
3390
3391 const FunctionProtoType *FromFunctionType
3392 = FromPointeeType->getAs<FunctionProtoType>();
3393 const FunctionProtoType *ToFunctionType
3394 = ToPointeeType->getAs<FunctionProtoType>();
3395
3396 if (!FromFunctionType || !ToFunctionType)
3397 return false;
3398
3399 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3400 return true;
3401
3402 // Perform the quick checks that will tell us whether these
3403 // function types are obviously different.
3404 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3405 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3406 return false;
3407
3408 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3409 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3410 if (FromEInfo != ToEInfo)
3411 return false;
3412
3413 bool IncompatibleObjC = false;
3414 if (Context.hasSameType(FromFunctionType->getReturnType(),
3415 ToFunctionType->getReturnType())) {
3416 // Okay, the types match exactly. Nothing to do.
3417 } else {
3418 QualType RHS = FromFunctionType->getReturnType();
3419 QualType LHS = ToFunctionType->getReturnType();
3420 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3421 !RHS.hasQualifiers() && LHS.hasQualifiers())
3422 LHS = LHS.getUnqualifiedType();
3423
3424 if (Context.hasSameType(RHS,LHS)) {
3425 // OK exact match.
3426 } else if (isObjCPointerConversion(RHS, LHS,
3427 ConvertedType, IncompatibleObjC)) {
3428 if (IncompatibleObjC)
3429 return false;
3430 // Okay, we have an Objective-C pointer conversion.
3431 }
3432 else
3433 return false;
3434 }
3435
3436 // Check argument types.
3437 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3438 ArgIdx != NumArgs; ++ArgIdx) {
3439 IncompatibleObjC = false;
3440 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3441 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3442 if (Context.hasSameType(FromArgType, ToArgType)) {
3443 // Okay, the types match exactly. Nothing to do.
3444 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3445 ConvertedType, IncompatibleObjC)) {
3446 if (IncompatibleObjC)
3447 return false;
3448 // Okay, we have an Objective-C pointer conversion.
3449 } else
3450 // Argument types are too different. Abort.
3451 return false;
3452 }
3453
3455 bool CanUseToFPT, CanUseFromFPT;
3456 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3457 CanUseToFPT, CanUseFromFPT,
3458 NewParamInfos))
3459 return false;
3460
3461 ConvertedType = ToType;
3462 return true;
3463}
3464
3465enum {
3473};
3474
3475/// Attempts to get the FunctionProtoType from a Type. Handles
3476/// MemberFunctionPointers properly.
3478 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3479 return FPT;
3480
3481 if (auto *MPT = FromType->getAs<MemberPointerType>())
3482 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3483
3484 return nullptr;
3485}
3486
3488 QualType FromType, QualType ToType) {
3489 // If either type is not valid, include no extra info.
3490 if (FromType.isNull() || ToType.isNull()) {
3491 PDiag << ft_default;
3492 return;
3493 }
3494
3495 // Get the function type from the pointers.
3496 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3497 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3498 *ToMember = ToType->castAs<MemberPointerType>();
3499 if (!declaresSameEntity(FromMember->getMostRecentCXXRecordDecl(),
3500 ToMember->getMostRecentCXXRecordDecl())) {
3502 if (ToMember->isSugared())
3503 PDiag << Context.getCanonicalTagType(
3504 ToMember->getMostRecentCXXRecordDecl());
3505 else
3506 PDiag << ToMember->getQualifier();
3507 if (FromMember->isSugared())
3508 PDiag << Context.getCanonicalTagType(
3509 FromMember->getMostRecentCXXRecordDecl());
3510 else
3511 PDiag << FromMember->getQualifier();
3512 return;
3513 }
3514 FromType = FromMember->getPointeeType();
3515 ToType = ToMember->getPointeeType();
3516 }
3517
3518 if (FromType->isPointerType())
3519 FromType = FromType->getPointeeType();
3520 if (ToType->isPointerType())
3521 ToType = ToType->getPointeeType();
3522
3523 // Remove references.
3524 FromType = FromType.getNonReferenceType();
3525 ToType = ToType.getNonReferenceType();
3526
3527 // Don't print extra info for non-specialized template functions.
3528 if (FromType->isInstantiationDependentType() &&
3529 !FromType->getAs<TemplateSpecializationType>()) {
3530 PDiag << ft_default;
3531 return;
3532 }
3533
3534 // No extra info for same types.
3535 if (Context.hasSameType(FromType, ToType)) {
3536 PDiag << ft_default;
3537 return;
3538 }
3539
3540 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3541 *ToFunction = tryGetFunctionProtoType(ToType);
3542
3543 // Both types need to be function types.
3544 if (!FromFunction || !ToFunction) {
3545 PDiag << ft_default;
3546 return;
3547 }
3548
3549 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3550 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3551 << FromFunction->getNumParams();
3552 return;
3553 }
3554
3555 // Handle different parameter types.
3556 unsigned ArgPos;
3557 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3558 PDiag << ft_parameter_mismatch << ArgPos + 1
3559 << ToFunction->getParamType(ArgPos)
3560 << FromFunction->getParamType(ArgPos);
3561 return;
3562 }
3563
3564 // Handle different return type.
3565 if (!Context.hasSameType(FromFunction->getReturnType(),
3566 ToFunction->getReturnType())) {
3567 PDiag << ft_return_type << ToFunction->getReturnType()
3568 << FromFunction->getReturnType();
3569 return;
3570 }
3571
3572 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3573 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3574 << FromFunction->getMethodQuals();
3575 return;
3576 }
3577
3578 // Handle exception specification differences on canonical type (in C++17
3579 // onwards).
3581 ->isNothrow() !=
3582 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3583 ->isNothrow()) {
3584 PDiag << ft_noexcept;
3585 return;
3586 }
3587
3588 // Unable to find a difference, so add no extra info.
3589 PDiag << ft_default;
3590}
3591
3593 ArrayRef<QualType> New, unsigned *ArgPos,
3594 bool Reversed) {
3595 assert(llvm::size(Old) == llvm::size(New) &&
3596 "Can't compare parameters of functions with different number of "
3597 "parameters!");
3598
3599 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3600 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3601 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3602
3603 // Ignore address spaces in pointee type. This is to disallow overloading
3604 // on __ptr32/__ptr64 address spaces.
3605 QualType OldType =
3606 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3607 QualType NewType =
3608 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3609
3610 if (!Context.hasSameType(OldType, NewType)) {
3611 if (ArgPos)
3612 *ArgPos = Idx;
3613 return false;
3614 }
3615 }
3616 return true;
3617}
3618
3620 const FunctionProtoType *NewType,
3621 unsigned *ArgPos, bool Reversed) {
3622 return FunctionParamTypesAreEqual(OldType->param_types(),
3623 NewType->param_types(), ArgPos, Reversed);
3624}
3625
3627 const FunctionDecl *NewFunction,
3628 unsigned *ArgPos,
3629 bool Reversed) {
3630
3631 if (OldFunction->getNumNonObjectParams() !=
3632 NewFunction->getNumNonObjectParams())
3633 return false;
3634
3635 unsigned OldIgnore =
3637 unsigned NewIgnore =
3639
3640 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3641 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3642
3643 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3644 NewPT->param_types().slice(NewIgnore),
3645 ArgPos, Reversed);
3646}
3647
3649 CastKind &Kind,
3650 CXXCastPath& BasePath,
3651 bool IgnoreBaseAccess,
3652 bool Diagnose) {
3653 QualType FromType = From->getType();
3654 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3655
3656 Kind = CK_BitCast;
3657
3658 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3661 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3662 DiagRuntimeBehavior(From->getExprLoc(), From,
3663 PDiag(diag::warn_impcast_bool_to_null_pointer)
3664 << ToType << From->getSourceRange());
3665 else if (!isUnevaluatedContext())
3666 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3667 << ToType << From->getSourceRange();
3668 }
3669 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3670 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3671 QualType FromPointeeType = FromPtrType->getPointeeType(),
3672 ToPointeeType = ToPtrType->getPointeeType();
3673
3674 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3675 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3676 // We must have a derived-to-base conversion. Check an
3677 // ambiguous or inaccessible conversion.
3678 unsigned InaccessibleID = 0;
3679 unsigned AmbiguousID = 0;
3680 if (Diagnose) {
3681 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3682 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3683 }
3685 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3686 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3687 &BasePath, IgnoreBaseAccess))
3688 return true;
3689
3690 // The conversion was successful.
3691 Kind = CK_DerivedToBase;
3692 }
3693
3694 if (Diagnose && !IsCStyleOrFunctionalCast &&
3695 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3696 assert(getLangOpts().MSVCCompat &&
3697 "this should only be possible with MSVCCompat!");
3698 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3699 << From->getSourceRange();
3700 }
3701 }
3702 } else if (const ObjCObjectPointerType *ToPtrType =
3703 ToType->getAs<ObjCObjectPointerType>()) {
3704 if (const ObjCObjectPointerType *FromPtrType =
3705 FromType->getAs<ObjCObjectPointerType>()) {
3706 // Objective-C++ conversions are always okay.
3707 // FIXME: We should have a different class of conversions for the
3708 // Objective-C++ implicit conversions.
3709 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3710 return false;
3711 } else if (FromType->isBlockPointerType()) {
3712 Kind = CK_BlockPointerToObjCPointerCast;
3713 } else {
3714 Kind = CK_CPointerToObjCPointerCast;
3715 }
3716 } else if (ToType->isBlockPointerType()) {
3717 if (!FromType->isBlockPointerType())
3718 Kind = CK_AnyPointerToBlockPointerCast;
3719 }
3720
3721 // We shouldn't fall into this case unless it's valid for other
3722 // reasons.
3724 Kind = CK_NullToPointer;
3725
3726 return false;
3727}
3728
3730 QualType ToType,
3731 bool InOverloadResolution,
3732 QualType &ConvertedType) {
3733 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3734 if (!ToTypePtr)
3735 return false;
3736
3737 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3739 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3741 ConvertedType = ToType;
3742 return true;
3743 }
3744
3745 // Otherwise, both types have to be member pointers.
3746 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3747 if (!FromTypePtr)
3748 return false;
3749
3750 // A pointer to member of B can be converted to a pointer to member of D,
3751 // where D is derived from B (C++ 4.11p2).
3752 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3753 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3754
3755 if (!declaresSameEntity(FromClass, ToClass) &&
3756 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3757 ConvertedType = Context.getMemberPointerType(
3758 FromTypePtr->getPointeeType(), FromTypePtr->getQualifier(), ToClass);
3759 return true;
3760 }
3761
3762 return false;
3763}
3764
3766 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3767 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3768 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3769 // Lock down the inheritance model right now in MS ABI, whether or not the
3770 // pointee types are the same.
3771 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3772 (void)isCompleteType(CheckLoc, FromType);
3773 (void)isCompleteType(CheckLoc, QualType(ToPtrType, 0));
3774 }
3775
3776 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3777 if (!FromPtrType) {
3778 // This must be a null pointer to member pointer conversion
3779 Kind = CK_NullToMemberPointer;
3781 }
3782
3783 // T == T, modulo cv
3785 !Context.hasSameUnqualifiedType(FromPtrType->getPointeeType(),
3786 ToPtrType->getPointeeType()))
3788
3789 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3790 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3791
3792 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3793 const CXXRecordDecl *Cls) {
3794 if (declaresSameEntity(Qual.getAsRecordDecl(), Cls))
3795 PD << Qual;
3796 else
3797 PD << Context.getCanonicalTagType(Cls);
3798 };
3799 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3800 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3801 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3802 return PD;
3803 };
3804
3805 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3807 std::swap(Base, Derived);
3808
3809 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3810 /*DetectVirtual=*/true);
3811 if (!IsDerivedFrom(OpRange.getBegin(), Derived, Base, Paths))
3813
3814 if (Paths.isAmbiguous(Context.getCanonicalTagType(Base))) {
3815 PartialDiagnostic PD = PDiag(diag::err_ambiguous_memptr_conv);
3816 PD << int(Direction);
3817 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3818 Diag(CheckLoc, PD);
3820 }
3821
3822 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3823 PartialDiagnostic PD = PDiag(diag::err_memptr_conv_via_virtual);
3824 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3825 Diag(CheckLoc, PD);
3827 }
3828
3829 // Must be a base to derived member conversion.
3830 BuildBasePathArray(Paths, BasePath);
3832 ? CK_DerivedToBaseMemberPointer
3833 : CK_BaseToDerivedMemberPointer;
3834
3835 if (!IgnoreBaseAccess)
3836 switch (CheckBaseClassAccess(
3837 CheckLoc, Base, Derived, Paths.front(),
3839 ? diag::err_upcast_to_inaccessible_base
3840 : diag::err_downcast_from_inaccessible_base,
3841 [&](PartialDiagnostic &PD) {
3842 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3843 DerivedQual = ToPtrType->getQualifier();
3844 if (Direction == MemberPointerConversionDirection::Upcast)
3845 std::swap(BaseQual, DerivedQual);
3846 DiagCls(PD, DerivedQual, Derived);
3847 DiagCls(PD, BaseQual, Base);
3848 })) {
3850 case Sema::AR_delayed:
3851 case Sema::AR_dependent:
3852 // Optimistically assume that the delayed and dependent cases
3853 // will work out.
3854 break;
3855
3858 }
3859
3861}
3862
3863/// Determine whether the lifetime conversion between the two given
3864/// qualifiers sets is nontrivial.
3866 Qualifiers ToQuals) {
3867 // Converting anything to const __unsafe_unretained is trivial.
3868 if (ToQuals.hasConst() &&
3870 return false;
3871
3872 return true;
3873}
3874
3875/// Perform a single iteration of the loop for checking if a qualification
3876/// conversion is valid.
3877///
3878/// Specifically, check whether any change between the qualifiers of \p
3879/// FromType and \p ToType is permissible, given knowledge about whether every
3880/// outer layer is const-qualified.
3882 bool CStyle, bool IsTopLevel,
3883 bool &PreviousToQualsIncludeConst,
3884 bool &ObjCLifetimeConversion,
3885 const ASTContext &Ctx) {
3886 Qualifiers FromQuals = FromType.getQualifiers();
3887 Qualifiers ToQuals = ToType.getQualifiers();
3888
3889 // Ignore __unaligned qualifier.
3890 FromQuals.removeUnaligned();
3891
3892 // Objective-C ARC:
3893 // Check Objective-C lifetime conversions.
3894 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3895 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3896 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3897 ObjCLifetimeConversion = true;
3898 FromQuals.removeObjCLifetime();
3899 ToQuals.removeObjCLifetime();
3900 } else {
3901 // Qualification conversions cannot cast between different
3902 // Objective-C lifetime qualifiers.
3903 return false;
3904 }
3905 }
3906
3907 // Allow addition/removal of GC attributes but not changing GC attributes.
3908 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3909 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3910 FromQuals.removeObjCGCAttr();
3911 ToQuals.removeObjCGCAttr();
3912 }
3913
3914 // __ptrauth qualifiers must match exactly.
3915 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3916 return false;
3917
3918 // -- for every j > 0, if const is in cv 1,j then const is in cv
3919 // 2,j, and similarly for volatile.
3920 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3921 return false;
3922
3923 // If address spaces mismatch:
3924 // - in top level it is only valid to convert to addr space that is a
3925 // superset in all cases apart from C-style casts where we allow
3926 // conversions between overlapping address spaces.
3927 // - in non-top levels it is not a valid conversion.
3928 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3929 (!IsTopLevel ||
3930 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3931 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3932 return false;
3933
3934 // -- if the cv 1,j and cv 2,j are different, then const is in
3935 // every cv for 0 < k < j.
3936 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3937 !PreviousToQualsIncludeConst)
3938 return false;
3939
3940 // The following wording is from C++20, where the result of the conversion
3941 // is T3, not T2.
3942 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3943 // "array of unknown bound of"
3944 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3945 return false;
3946
3947 // -- if the resulting P3,i is different from P1,i [...], then const is
3948 // added to every cv 3_k for 0 < k < i.
3949 if (!CStyle && FromType->isConstantArrayType() &&
3950 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3951 return false;
3952
3953 // Keep track of whether all prior cv-qualifiers in the "to" type
3954 // include const.
3955 PreviousToQualsIncludeConst =
3956 PreviousToQualsIncludeConst && ToQuals.hasConst();
3957 return true;
3958}
3959
3960bool
3962 bool CStyle, bool &ObjCLifetimeConversion) {
3963 FromType = Context.getCanonicalType(FromType);
3964 ToType = Context.getCanonicalType(ToType);
3965 ObjCLifetimeConversion = false;
3966
3967 // If FromType and ToType are the same type, this is not a
3968 // qualification conversion.
3969 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3970 return false;
3971
3972 // (C++ 4.4p4):
3973 // A conversion can add cv-qualifiers at levels other than the first
3974 // in multi-level pointers, subject to the following rules: [...]
3975 bool PreviousToQualsIncludeConst = true;
3976 bool UnwrappedAnyPointer = false;
3977 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3978 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3979 !UnwrappedAnyPointer,
3980 PreviousToQualsIncludeConst,
3981 ObjCLifetimeConversion, getASTContext()))
3982 return false;
3983 UnwrappedAnyPointer = true;
3984 }
3985
3986 // We are left with FromType and ToType being the pointee types
3987 // after unwrapping the original FromType and ToType the same number
3988 // of times. If we unwrapped any pointers, and if FromType and
3989 // ToType have the same unqualified type (since we checked
3990 // qualifiers above), then this is a qualification conversion.
3991 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3992}
3993
3994/// - Determine whether this is a conversion from a scalar type to an
3995/// atomic type.
3996///
3997/// If successful, updates \c SCS's second and third steps in the conversion
3998/// sequence to finish the conversion.
3999static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
4000 bool InOverloadResolution,
4002 bool CStyle) {
4003 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
4004 if (!ToAtomic)
4005 return false;
4006
4008 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
4009 InOverloadResolution, InnerSCS,
4010 CStyle, /*AllowObjCWritebackConversion=*/false))
4011 return false;
4012
4013 SCS.Second = InnerSCS.Second;
4014 SCS.setToType(1, InnerSCS.getToType(1));
4015 SCS.Third = InnerSCS.Third;
4018 SCS.setToType(2, InnerSCS.getToType(2));
4019 return true;
4020}
4021
4023 QualType ToType,
4024 bool InOverloadResolution,
4026 bool CStyle) {
4027 const OverflowBehaviorType *ToOBT = ToType->getAs<OverflowBehaviorType>();
4028 if (!ToOBT)
4029 return false;
4030
4031 // Check for incompatible OBT kinds (e.g., trap vs wrap)
4032 QualType FromType = From->getType();
4033 if (!S.Context.areCompatibleOverflowBehaviorTypes(FromType, ToType))
4034 return false;
4035
4037 if (!IsStandardConversion(S, From, ToOBT->getUnderlyingType(),
4038 InOverloadResolution, InnerSCS, CStyle,
4039 /*AllowObjCWritebackConversion=*/false))
4040 return false;
4041
4042 SCS.Second = InnerSCS.Second;
4043 SCS.setToType(1, InnerSCS.getToType(1));
4044 SCS.Third = InnerSCS.Third;
4047 SCS.setToType(2, InnerSCS.getToType(2));
4048 return true;
4049}
4050
4053 QualType Type) {
4054 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
4055 if (CtorType->getNumParams() > 0) {
4056 QualType FirstArg = CtorType->getParamType(0);
4057 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
4058 return true;
4059 }
4060 return false;
4061}
4062
4063static OverloadingResult
4065 CXXRecordDecl *To,
4067 OverloadCandidateSet &CandidateSet,
4068 bool AllowExplicit) {
4070 for (auto *D : S.LookupConstructors(To)) {
4071 auto Info = getConstructorInfo(D);
4072 if (!Info)
4073 continue;
4074
4075 bool Usable = !Info.Constructor->isInvalidDecl() &&
4076 S.isInitListConstructor(Info.Constructor);
4077 if (Usable) {
4078 bool SuppressUserConversions = false;
4079 if (Info.ConstructorTmpl)
4080 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
4081 /*ExplicitArgs*/ nullptr, From,
4082 CandidateSet, SuppressUserConversions,
4083 /*PartialOverloading*/ false,
4084 AllowExplicit);
4085 else
4086 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
4087 CandidateSet, SuppressUserConversions,
4088 /*PartialOverloading*/ false, AllowExplicit);
4089 }
4090 }
4091
4092 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4093
4095 switch (auto Result =
4096 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4097 case OR_Deleted:
4098 case OR_Success: {
4099 // Record the standard conversion we used and the conversion function.
4101 QualType ThisType = Constructor->getFunctionObjectParameterType();
4102 // Initializer lists don't have conversions as such.
4104 User.HadMultipleCandidates = HadMultipleCandidates;
4106 User.FoundConversionFunction = Best->FoundDecl;
4108 User.After.setFromType(ThisType);
4109 User.After.setAllToTypes(ToType);
4110 return Result;
4111 }
4112
4114 return OR_No_Viable_Function;
4115 case OR_Ambiguous:
4116 return OR_Ambiguous;
4117 }
4118
4119 llvm_unreachable("Invalid OverloadResult!");
4120}
4121
4122/// Determines whether there is a user-defined conversion sequence
4123/// (C++ [over.ics.user]) that converts expression From to the type
4124/// ToType. If such a conversion exists, User will contain the
4125/// user-defined conversion sequence that performs such a conversion
4126/// and this routine will return true. Otherwise, this routine returns
4127/// false and User is unspecified.
4128///
4129/// \param AllowExplicit true if the conversion should consider C++0x
4130/// "explicit" conversion functions as well as non-explicit conversion
4131/// functions (C++0x [class.conv.fct]p2).
4132///
4133/// \param AllowObjCConversionOnExplicit true if the conversion should
4134/// allow an extra Objective-C pointer conversion on uses of explicit
4135/// constructors. Requires \c AllowExplicit to also be set.
4136static OverloadingResult
4139 OverloadCandidateSet &CandidateSet,
4140 AllowedExplicit AllowExplicit,
4141 bool AllowObjCConversionOnExplicit) {
4142 assert(AllowExplicit != AllowedExplicit::None ||
4143 !AllowObjCConversionOnExplicit);
4145
4146 // Whether we will only visit constructors.
4147 bool ConstructorsOnly = false;
4148
4149 // If the type we are conversion to is a class type, enumerate its
4150 // constructors.
4151 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
4152 // C++ [over.match.ctor]p1:
4153 // When objects of class type are direct-initialized (8.5), or
4154 // copy-initialized from an expression of the same or a
4155 // derived class type (8.5), overload resolution selects the
4156 // constructor. [...] For copy-initialization, the candidate
4157 // functions are all the converting constructors (12.3.1) of
4158 // that class. The argument list is the expression-list within
4159 // the parentheses of the initializer.
4160 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
4161 (From->getType()->isRecordType() &&
4162 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
4163 ConstructorsOnly = true;
4164
4165 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
4166 // We're not going to find any constructors.
4167 } else if (auto *ToRecordDecl =
4168 dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
4169 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
4170
4171 Expr **Args = &From;
4172 unsigned NumArgs = 1;
4173 bool ListInitializing = false;
4174 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
4175 // But first, see if there is an init-list-constructor that will work.
4177 S, From, ToType, ToRecordDecl, User, CandidateSet,
4178 AllowExplicit == AllowedExplicit::All);
4180 return Result;
4181 // Never mind.
4182 CandidateSet.clear(
4184
4185 // If we're list-initializing, we pass the individual elements as
4186 // arguments, not the entire list.
4187 Args = InitList->getInits();
4188 NumArgs = InitList->getNumInits();
4189 ListInitializing = true;
4190 }
4191
4192 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
4193 auto Info = getConstructorInfo(D);
4194 if (!Info)
4195 continue;
4196
4197 bool Usable = !Info.Constructor->isInvalidDecl();
4198 if (!ListInitializing)
4199 Usable = Usable && Info.Constructor->isConvertingConstructor(
4200 /*AllowExplicit*/ true);
4201 if (Usable) {
4202 bool SuppressUserConversions = !ConstructorsOnly;
4203 // C++20 [over.best.ics.general]/4.5:
4204 // if the target is the first parameter of a constructor [of class
4205 // X] and the constructor [...] is a candidate by [...] the second
4206 // phase of [over.match.list] when the initializer list has exactly
4207 // one element that is itself an initializer list, [...] and the
4208 // conversion is to X or reference to cv X, user-defined conversion
4209 // sequences are not considered.
4210 if (SuppressUserConversions && ListInitializing) {
4211 SuppressUserConversions =
4212 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
4213 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
4214 ToType);
4215 }
4216 if (Info.ConstructorTmpl)
4218 Info.ConstructorTmpl, Info.FoundDecl,
4219 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
4220 CandidateSet, SuppressUserConversions,
4221 /*PartialOverloading*/ false,
4222 AllowExplicit == AllowedExplicit::All);
4223 else
4224 // Allow one user-defined conversion when user specifies a
4225 // From->ToType conversion via an static cast (c-style, etc).
4226 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4227 llvm::ArrayRef(Args, NumArgs), CandidateSet,
4228 SuppressUserConversions,
4229 /*PartialOverloading*/ false,
4230 AllowExplicit == AllowedExplicit::All);
4231 }
4232 }
4233 }
4234 }
4235
4236 // Enumerate conversion functions, if we're allowed to.
4237 if (ConstructorsOnly || isa<InitListExpr>(From)) {
4238 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
4239 // No conversion functions from incomplete types.
4240 } else if (const RecordType *FromRecordType =
4241 From->getType()->getAsCanonical<RecordType>()) {
4242 if (auto *FromRecordDecl =
4243 dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
4244 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4245 // Add all of the conversion functions as candidates.
4246 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4247 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4248 DeclAccessPair FoundDecl = I.getPair();
4249 NamedDecl *D = FoundDecl.getDecl();
4250 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
4251 if (isa<UsingShadowDecl>(D))
4252 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4253
4254 CXXConversionDecl *Conv;
4255 FunctionTemplateDecl *ConvTemplate;
4256 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
4257 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4258 else
4259 Conv = cast<CXXConversionDecl>(D);
4260
4261 if (ConvTemplate)
4263 ConvTemplate, FoundDecl, ActingContext, From, ToType,
4264 CandidateSet, AllowObjCConversionOnExplicit,
4265 AllowExplicit != AllowedExplicit::None);
4266 else
4267 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
4268 CandidateSet, AllowObjCConversionOnExplicit,
4269 AllowExplicit != AllowedExplicit::None);
4270 }
4271 }
4272 }
4273
4274 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4275
4277 switch (auto Result =
4278 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4279 case OR_Success:
4280 case OR_Deleted:
4281 // Record the standard conversion we used and the conversion function.
4283 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
4284 // C++ [over.ics.user]p1:
4285 // If the user-defined conversion is specified by a
4286 // constructor (12.3.1), the initial standard conversion
4287 // sequence converts the source type to the type required by
4288 // the argument of the constructor.
4289 //
4290 if (isa<InitListExpr>(From)) {
4291 // Initializer lists don't have conversions as such.
4293 User.Before.FromBracedInitList = true;
4294 } else {
4295 if (Best->Conversions[0].isEllipsis())
4296 User.EllipsisConversion = true;
4297 else {
4298 User.Before = Best->Conversions[0].Standard;
4299 User.EllipsisConversion = false;
4300 }
4301 }
4302 User.HadMultipleCandidates = HadMultipleCandidates;
4304 User.FoundConversionFunction = Best->FoundDecl;
4306 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4307 User.After.setAllToTypes(ToType);
4308 return Result;
4309 }
4310 if (CXXConversionDecl *Conversion
4311 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4312
4313 assert(Best->HasFinalConversion);
4314
4315 // C++ [over.ics.user]p1:
4316 //
4317 // [...] If the user-defined conversion is specified by a
4318 // conversion function (12.3.2), the initial standard
4319 // conversion sequence converts the source type to the
4320 // implicit object parameter of the conversion function.
4321 User.Before = Best->Conversions[0].Standard;
4322 User.HadMultipleCandidates = HadMultipleCandidates;
4323 User.ConversionFunction = Conversion;
4324 User.FoundConversionFunction = Best->FoundDecl;
4325 User.EllipsisConversion = false;
4326
4327 // C++ [over.ics.user]p2:
4328 // The second standard conversion sequence converts the
4329 // result of the user-defined conversion to the target type
4330 // for the sequence. Since an implicit conversion sequence
4331 // is an initialization, the special rules for
4332 // initialization by user-defined conversion apply when
4333 // selecting the best user-defined conversion for a
4334 // user-defined conversion sequence (see 13.3.3 and
4335 // 13.3.3.1).
4336 User.After = Best->FinalConversion;
4337 return Result;
4338 }
4339 llvm_unreachable("Not a constructor or conversion function?");
4340
4342 return OR_No_Viable_Function;
4343
4344 case OR_Ambiguous:
4345 return OR_Ambiguous;
4346 }
4347
4348 llvm_unreachable("Invalid OverloadResult!");
4349}
4350
4351bool
4354 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4356 OverloadingResult OvResult =
4357 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4358 CandidateSet, AllowedExplicit::None, false);
4359
4360 if (!(OvResult == OR_Ambiguous ||
4361 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4362 return false;
4363
4364 auto Cands = CandidateSet.CompleteCandidates(
4365 *this,
4367 From);
4368 if (OvResult == OR_Ambiguous)
4369 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4370 << From->getType() << ToType << From->getSourceRange();
4371 else { // OR_No_Viable_Function && !CandidateSet.empty()
4372 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4373 diag::err_typecheck_nonviable_condition_incomplete,
4374 From->getType(), From->getSourceRange()))
4375 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4376 << false << From->getType() << From->getSourceRange() << ToType;
4377 }
4378
4379 CandidateSet.NoteCandidates(
4380 *this, From, Cands);
4381 return true;
4382}
4383
4384// Helper for compareConversionFunctions that gets the FunctionType that the
4385// conversion-operator return value 'points' to, or nullptr.
4386static const FunctionType *
4388 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4389 const PointerType *RetPtrTy =
4390 ConvFuncTy->getReturnType()->getAs<PointerType>();
4391
4392 if (!RetPtrTy)
4393 return nullptr;
4394
4395 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4396}
4397
4398/// Compare the user-defined conversion functions or constructors
4399/// of two user-defined conversion sequences to determine whether any ordering
4400/// is possible.
4403 FunctionDecl *Function2) {
4404 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4405 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4406 if (!Conv1 || !Conv2)
4408
4409 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4411
4412 // Objective-C++:
4413 // If both conversion functions are implicitly-declared conversions from
4414 // a lambda closure type to a function pointer and a block pointer,
4415 // respectively, always prefer the conversion to a function pointer,
4416 // because the function pointer is more lightweight and is more likely
4417 // to keep code working.
4418 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4419 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4420 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4421 if (Block1 != Block2)
4422 return Block1 ? ImplicitConversionSequence::Worse
4424 }
4425
4426 // In order to support multiple calling conventions for the lambda conversion
4427 // operator (such as when the free and member function calling convention is
4428 // different), prefer the 'free' mechanism, followed by the calling-convention
4429 // of operator(). The latter is in place to support the MSVC-like solution of
4430 // defining ALL of the possible conversions in regards to calling-convention.
4431 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4432 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4433
4434 if (Conv1FuncRet && Conv2FuncRet &&
4435 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4436 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4437 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4438
4439 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4440 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4441
4442 CallingConv CallOpCC =
4443 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4445 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4447 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4448
4449 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4450 for (CallingConv CC : PrefOrder) {
4451 if (Conv1CC == CC)
4453 if (Conv2CC == CC)
4455 }
4456 }
4457
4459}
4460
4467
4468/// CompareImplicitConversionSequences - Compare two implicit
4469/// conversion sequences to determine whether one is better than the
4470/// other or if they are indistinguishable (C++ 13.3.3.2).
4473 const ImplicitConversionSequence& ICS1,
4474 const ImplicitConversionSequence& ICS2)
4475{
4476 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4477 // conversion sequences (as defined in 13.3.3.1)
4478 // -- a standard conversion sequence (13.3.3.1.1) is a better
4479 // conversion sequence than a user-defined conversion sequence or
4480 // an ellipsis conversion sequence, and
4481 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4482 // conversion sequence than an ellipsis conversion sequence
4483 // (13.3.3.1.3).
4484 //
4485 // C++0x [over.best.ics]p10:
4486 // For the purpose of ranking implicit conversion sequences as
4487 // described in 13.3.3.2, the ambiguous conversion sequence is
4488 // treated as a user-defined sequence that is indistinguishable
4489 // from any other user-defined conversion sequence.
4490
4491 // String literal to 'char *' conversion has been deprecated in C++03. It has
4492 // been removed from C++11. We still accept this conversion, if it happens at
4493 // the best viable function. Otherwise, this conversion is considered worse
4494 // than ellipsis conversion. Consider this as an extension; this is not in the
4495 // standard. For example:
4496 //
4497 // int &f(...); // #1
4498 // void f(char*); // #2
4499 // void g() { int &r = f("foo"); }
4500 //
4501 // In C++03, we pick #2 as the best viable function.
4502 // In C++11, we pick #1 as the best viable function, because ellipsis
4503 // conversion is better than string-literal to char* conversion (since there
4504 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4505 // convert arguments, #2 would be the best viable function in C++11.
4506 // If the best viable function has this conversion, a warning will be issued
4507 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4508
4509 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4512 // Ill-formedness must not differ
4513 ICS1.isBad() == ICS2.isBad())
4517
4518 if (ICS1.getKindRank() < ICS2.getKindRank())
4520 if (ICS2.getKindRank() < ICS1.getKindRank())
4522
4523 // The following checks require both conversion sequences to be of
4524 // the same kind.
4525 if (ICS1.getKind() != ICS2.getKind())
4527
4530
4531 // Two implicit conversion sequences of the same form are
4532 // indistinguishable conversion sequences unless one of the
4533 // following rules apply: (C++ 13.3.3.2p3):
4534
4535 // List-initialization sequence L1 is a better conversion sequence than
4536 // list-initialization sequence L2 if:
4537 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4538 // if not that,
4539 // — L1 and L2 convert to arrays of the same element type, and either the
4540 // number of elements n_1 initialized by L1 is less than the number of
4541 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4542 // an array of unknown bound and L1 does not,
4543 // even if one of the other rules in this paragraph would otherwise apply.
4544 if (!ICS1.isBad()) {
4545 bool StdInit1 = false, StdInit2 = false;
4548 nullptr);
4551 nullptr);
4552 if (StdInit1 != StdInit2)
4553 return StdInit1 ? ImplicitConversionSequence::Better
4555
4558 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4560 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4562 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4563 CAT2->getElementType())) {
4564 // Both to arrays of the same element type
4565 if (CAT1->getSize() != CAT2->getSize())
4566 // Different sized, the smaller wins
4567 return CAT1->getSize().ult(CAT2->getSize())
4572 // One is incomplete, it loses
4576 }
4577 }
4578 }
4579
4580 if (ICS1.isStandard())
4581 // Standard conversion sequence S1 is a better conversion sequence than
4582 // standard conversion sequence S2 if [...]
4584 ICS1.Standard, ICS2.Standard);
4585 else if (ICS1.isUserDefined()) {
4586 // With lazy template loading, it is possible to find non-canonical
4587 // FunctionDecls, depending on when redecl chains are completed. Make sure
4588 // to compare the canonical decls of conversion functions. This avoids
4589 // ambiguity problems for templated conversion operators.
4590 const FunctionDecl *ConvFunc1 = ICS1.UserDefined.ConversionFunction;
4591 if (ConvFunc1)
4592 ConvFunc1 = ConvFunc1->getCanonicalDecl();
4593 const FunctionDecl *ConvFunc2 = ICS2.UserDefined.ConversionFunction;
4594 if (ConvFunc2)
4595 ConvFunc2 = ConvFunc2->getCanonicalDecl();
4596 // User-defined conversion sequence U1 is a better conversion
4597 // sequence than another user-defined conversion sequence U2 if
4598 // they contain the same user-defined conversion function or
4599 // constructor and if the second standard conversion sequence of
4600 // U1 is better than the second standard conversion sequence of
4601 // U2 (C++ 13.3.3.2p3).
4602 if (ConvFunc1 == ConvFunc2)
4604 ICS1.UserDefined.After,
4605 ICS2.UserDefined.After);
4606 else
4610 }
4611
4612 return Result;
4613}
4614
4615// Per 13.3.3.2p3, compare the given standard conversion sequences to
4616// determine if one is a proper subset of the other.
4619 const StandardConversionSequence& SCS1,
4620 const StandardConversionSequence& SCS2) {
4623
4624 // the identity conversion sequence is considered to be a subsequence of
4625 // any non-identity conversion sequence
4626 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4628 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4630
4631 if (SCS1.Second != SCS2.Second) {
4632 if (SCS1.Second == ICK_Identity)
4634 else if (SCS2.Second == ICK_Identity)
4636 else
4638 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4640
4641 if (SCS1.Third == SCS2.Third) {
4642 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4644 }
4645
4646 if (SCS1.Third == ICK_Identity)
4650
4651 if (SCS2.Third == ICK_Identity)
4655
4657}
4658
4659/// Determine whether one of the given reference bindings is better
4660/// than the other based on what kind of bindings they are.
4661static bool
4663 const StandardConversionSequence &SCS2) {
4664 // C++0x [over.ics.rank]p3b4:
4665 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4666 // implicit object parameter of a non-static member function declared
4667 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4668 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4669 // lvalue reference to a function lvalue and S2 binds an rvalue
4670 // reference*.
4671 //
4672 // FIXME: Rvalue references. We're going rogue with the above edits,
4673 // because the semantics in the current C++0x working paper (N3225 at the
4674 // time of this writing) break the standard definition of std::forward
4675 // and std::reference_wrapper when dealing with references to functions.
4676 // Proposed wording changes submitted to CWG for consideration.
4679 return false;
4680
4681 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4682 SCS2.IsLvalueReference) ||
4685}
4686
4692
4693/// Returns kind of fixed enum promotion the \a SCS uses.
4694static FixedEnumPromotion
4696
4697 if (SCS.Second != ICK_Integral_Promotion)
4699
4700 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4701 if (!Enum)
4703
4704 if (!Enum->isFixed())
4706
4707 QualType UnderlyingType = Enum->getIntegerType();
4708 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4710
4712}
4713
4714/// CompareStandardConversionSequences - Compare two standard
4715/// conversion sequences to determine whether one is better than the
4716/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4719 const StandardConversionSequence& SCS1,
4720 const StandardConversionSequence& SCS2)
4721{
4722 // Standard conversion sequence S1 is a better conversion sequence
4723 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4724
4725 // -- S1 is a proper subsequence of S2 (comparing the conversion
4726 // sequences in the canonical form defined by 13.3.3.1.1,
4727 // excluding any Lvalue Transformation; the identity conversion
4728 // sequence is considered to be a subsequence of any
4729 // non-identity conversion sequence) or, if not that,
4732 return CK;
4733
4734 // -- the rank of S1 is better than the rank of S2 (by the rules
4735 // defined below), or, if not that,
4736 ImplicitConversionRank Rank1 = SCS1.getRank();
4737 ImplicitConversionRank Rank2 = SCS2.getRank();
4738 if (Rank1 < Rank2)
4740 else if (Rank2 < Rank1)
4742
4743 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4744 // are indistinguishable unless one of the following rules
4745 // applies:
4746
4747 // A conversion that is not a conversion of a pointer, or
4748 // pointer to member, to bool is better than another conversion
4749 // that is such a conversion.
4751 return SCS2.isPointerConversionToBool()
4754
4755 // C++14 [over.ics.rank]p4b2:
4756 // This is retroactively applied to C++11 by CWG 1601.
4757 //
4758 // A conversion that promotes an enumeration whose underlying type is fixed
4759 // to its underlying type is better than one that promotes to the promoted
4760 // underlying type, if the two are different.
4763 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4764 FEP1 != FEP2)
4768
4769 // C++ [over.ics.rank]p4b2:
4770 //
4771 // If class B is derived directly or indirectly from class A,
4772 // conversion of B* to A* is better than conversion of B* to
4773 // void*, and conversion of A* to void* is better than conversion
4774 // of B* to void*.
4775 bool SCS1ConvertsToVoid
4777 bool SCS2ConvertsToVoid
4779 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4780 // Exactly one of the conversion sequences is a conversion to
4781 // a void pointer; it's the worse conversion.
4782 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4784 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4785 // Neither conversion sequence converts to a void pointer; compare
4786 // their derived-to-base conversions.
4788 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4789 return DerivedCK;
4790 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4791 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4792 // Both conversion sequences are conversions to void
4793 // pointers. Compare the source types to determine if there's an
4794 // inheritance relationship in their sources.
4795 QualType FromType1 = SCS1.getFromType();
4796 QualType FromType2 = SCS2.getFromType();
4797
4798 // Adjust the types we're converting from via the array-to-pointer
4799 // conversion, if we need to.
4800 if (SCS1.First == ICK_Array_To_Pointer)
4801 FromType1 = S.Context.getArrayDecayedType(FromType1);
4802 if (SCS2.First == ICK_Array_To_Pointer)
4803 FromType2 = S.Context.getArrayDecayedType(FromType2);
4804
4805 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4806 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4807
4808 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4810 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4812
4813 // Objective-C++: If one interface is more specific than the
4814 // other, it is the better one.
4815 const ObjCObjectPointerType* FromObjCPtr1
4816 = FromType1->getAs<ObjCObjectPointerType>();
4817 const ObjCObjectPointerType* FromObjCPtr2
4818 = FromType2->getAs<ObjCObjectPointerType>();
4819 if (FromObjCPtr1 && FromObjCPtr2) {
4820 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4821 FromObjCPtr2);
4822 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4823 FromObjCPtr1);
4824 if (AssignLeft != AssignRight) {
4825 return AssignLeft? ImplicitConversionSequence::Better
4827 }
4828 }
4829 }
4830
4831 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4832 // Check for a better reference binding based on the kind of bindings.
4833 if (isBetterReferenceBindingKind(SCS1, SCS2))
4835 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4837 }
4838
4839 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4840 // bullet 3).
4842 = CompareQualificationConversions(S, SCS1, SCS2))
4843 return QualCK;
4844
4847 return ObtCK;
4848
4849 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4850 // C++ [over.ics.rank]p3b4:
4851 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4852 // which the references refer are the same type except for
4853 // top-level cv-qualifiers, and the type to which the reference
4854 // initialized by S2 refers is more cv-qualified than the type
4855 // to which the reference initialized by S1 refers.
4856 QualType T1 = SCS1.getToType(2);
4857 QualType T2 = SCS2.getToType(2);
4858 T1 = S.Context.getCanonicalType(T1);
4859 T2 = S.Context.getCanonicalType(T2);
4860 Qualifiers T1Quals, T2Quals;
4861 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4862 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4863 if (UnqualT1 == UnqualT2) {
4864 // Objective-C++ ARC: If the references refer to objects with different
4865 // lifetimes, prefer bindings that don't change lifetime.
4871 }
4872
4873 // If the type is an array type, promote the element qualifiers to the
4874 // type for comparison.
4875 if (isa<ArrayType>(T1) && T1Quals)
4876 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4877 if (isa<ArrayType>(T2) && T2Quals)
4878 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4879 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4881 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4883 }
4884 }
4885
4886 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4887 // floating-to-integral conversion if the integral conversion
4888 // is between types of the same size.
4889 // For example:
4890 // void f(float);
4891 // void f(int);
4892 // int main {
4893 // long a;
4894 // f(a);
4895 // }
4896 // Here, MSVC will call f(int) instead of generating a compile error
4897 // as clang will do in standard mode.
4898 if (S.getLangOpts().MSVCCompat &&
4901 SCS2.Second == ICK_Floating_Integral &&
4902 S.Context.getTypeSize(SCS1.getFromType()) ==
4903 S.Context.getTypeSize(SCS1.getToType(2)))
4905
4906 // Prefer a compatible vector conversion over a lax vector conversion
4907 // For example:
4908 //
4909 // typedef float __v4sf __attribute__((__vector_size__(16)));
4910 // void f(vector float);
4911 // void f(vector signed int);
4912 // int main() {
4913 // __v4sf a;
4914 // f(a);
4915 // }
4916 // Here, we'd like to choose f(vector float) and not
4917 // report an ambiguous call error
4918 if (SCS1.Second == ICK_Vector_Conversion &&
4919 SCS2.Second == ICK_Vector_Conversion) {
4920 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4921 SCS1.getFromType(), SCS1.getToType(2));
4922 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4923 SCS2.getFromType(), SCS2.getToType(2));
4924
4925 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4926 return SCS1IsCompatibleVectorConversion
4929 }
4930
4931 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4933 bool SCS1IsCompatibleSVEVectorConversion =
4934 S.ARM().areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4935 bool SCS2IsCompatibleSVEVectorConversion =
4936 S.ARM().areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4937
4938 if (SCS1IsCompatibleSVEVectorConversion !=
4939 SCS2IsCompatibleSVEVectorConversion)
4940 return SCS1IsCompatibleSVEVectorConversion
4943 }
4944
4945 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4947 bool SCS1IsCompatibleRVVVectorConversion =
4949 bool SCS2IsCompatibleRVVVectorConversion =
4951
4952 if (SCS1IsCompatibleRVVVectorConversion !=
4953 SCS2IsCompatibleRVVVectorConversion)
4954 return SCS1IsCompatibleRVVVectorConversion
4957 }
4959}
4960
4961/// CompareOverflowBehaviorConversions - Compares two standard conversion
4962/// sequences to determine whether they can be ranked based on their
4963/// OverflowBehaviorType's underlying type.
4979
4980/// CompareQualificationConversions - Compares two standard conversion
4981/// sequences to determine whether they can be ranked based on their
4982/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4985 const StandardConversionSequence& SCS1,
4986 const StandardConversionSequence& SCS2) {
4987 // C++ [over.ics.rank]p3:
4988 // -- S1 and S2 differ only in their qualification conversion and
4989 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4990 // [C++98]
4991 // [...] and the cv-qualification signature of type T1 is a proper subset
4992 // of the cv-qualification signature of type T2, and S1 is not the
4993 // deprecated string literal array-to-pointer conversion (4.2).
4994 // [C++2a]
4995 // [...] where T1 can be converted to T2 by a qualification conversion.
4996 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4997 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4999
5000 // FIXME: the example in the standard doesn't use a qualification
5001 // conversion (!)
5002 QualType T1 = SCS1.getToType(2);
5003 QualType T2 = SCS2.getToType(2);
5004 T1 = S.Context.getCanonicalType(T1);
5005 T2 = S.Context.getCanonicalType(T2);
5006 assert(!T1->isReferenceType() && !T2->isReferenceType());
5007 Qualifiers T1Quals, T2Quals;
5008 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
5009 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
5010
5011 // If the types are the same, we won't learn anything by unwrapping
5012 // them.
5013 if (UnqualT1 == UnqualT2)
5015
5016 // Don't ever prefer a standard conversion sequence that uses the deprecated
5017 // string literal array to pointer conversion.
5018 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
5019 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
5020
5021 // Objective-C++ ARC:
5022 // Prefer qualification conversions not involving a change in lifetime
5023 // to qualification conversions that do change lifetime.
5026 CanPick1 = false;
5029 CanPick2 = false;
5030
5031 bool ObjCLifetimeConversion;
5032 if (CanPick1 &&
5033 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
5034 CanPick1 = false;
5035 // FIXME: In Objective-C ARC, we can have qualification conversions in both
5036 // directions, so we can't short-cut this second check in general.
5037 if (CanPick2 &&
5038 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
5039 CanPick2 = false;
5040
5041 if (CanPick1 != CanPick2)
5042 return CanPick1 ? ImplicitConversionSequence::Better
5045}
5046
5047/// CompareDerivedToBaseConversions - Compares two standard conversion
5048/// sequences to determine whether they can be ranked based on their
5049/// various kinds of derived-to-base conversions (C++
5050/// [over.ics.rank]p4b3). As part of these checks, we also look at
5051/// conversions between Objective-C interface types.
5054 const StandardConversionSequence& SCS1,
5055 const StandardConversionSequence& SCS2) {
5056 QualType FromType1 = SCS1.getFromType();
5057 QualType ToType1 = SCS1.getToType(1);
5058 QualType FromType2 = SCS2.getFromType();
5059 QualType ToType2 = SCS2.getToType(1);
5060
5061 // Adjust the types we're converting from via the array-to-pointer
5062 // conversion, if we need to.
5063 if (SCS1.First == ICK_Array_To_Pointer)
5064 FromType1 = S.Context.getArrayDecayedType(FromType1);
5065 if (SCS2.First == ICK_Array_To_Pointer)
5066 FromType2 = S.Context.getArrayDecayedType(FromType2);
5067
5068 // Canonicalize all of the types.
5069 FromType1 = S.Context.getCanonicalType(FromType1);
5070 ToType1 = S.Context.getCanonicalType(ToType1);
5071 FromType2 = S.Context.getCanonicalType(FromType2);
5072 ToType2 = S.Context.getCanonicalType(ToType2);
5073
5074 // C++ [over.ics.rank]p4b3:
5075 //
5076 // If class B is derived directly or indirectly from class A and
5077 // class C is derived directly or indirectly from B,
5078 //
5079 // Compare based on pointer conversions.
5080 if (SCS1.Second == ICK_Pointer_Conversion &&
5082 /*FIXME: Remove if Objective-C id conversions get their own rank*/
5083 FromType1->isPointerType() && FromType2->isPointerType() &&
5084 ToType1->isPointerType() && ToType2->isPointerType()) {
5085 QualType FromPointee1 =
5087 QualType ToPointee1 =
5089 QualType FromPointee2 =
5091 QualType ToPointee2 =
5093
5094 // -- conversion of C* to B* is better than conversion of C* to A*,
5095 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5096 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5098 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5100 }
5101
5102 // -- conversion of B* to A* is better than conversion of C* to A*,
5103 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
5104 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5106 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5108 }
5109 } else if (SCS1.Second == ICK_Pointer_Conversion &&
5111 const ObjCObjectPointerType *FromPtr1
5112 = FromType1->getAs<ObjCObjectPointerType>();
5113 const ObjCObjectPointerType *FromPtr2
5114 = FromType2->getAs<ObjCObjectPointerType>();
5115 const ObjCObjectPointerType *ToPtr1
5116 = ToType1->getAs<ObjCObjectPointerType>();
5117 const ObjCObjectPointerType *ToPtr2
5118 = ToType2->getAs<ObjCObjectPointerType>();
5119
5120 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
5121 // Apply the same conversion ranking rules for Objective-C pointer types
5122 // that we do for C++ pointers to class types. However, we employ the
5123 // Objective-C pseudo-subtyping relationship used for assignment of
5124 // Objective-C pointer types.
5125 bool FromAssignLeft
5126 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
5127 bool FromAssignRight
5128 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
5129 bool ToAssignLeft
5130 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
5131 bool ToAssignRight
5132 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
5133
5134 // A conversion to an a non-id object pointer type or qualified 'id'
5135 // type is better than a conversion to 'id'.
5136 if (ToPtr1->isObjCIdType() &&
5137 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
5139 if (ToPtr2->isObjCIdType() &&
5140 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
5142
5143 // A conversion to a non-id object pointer type is better than a
5144 // conversion to a qualified 'id' type
5145 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
5147 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
5149
5150 // A conversion to an a non-Class object pointer type or qualified 'Class'
5151 // type is better than a conversion to 'Class'.
5152 if (ToPtr1->isObjCClassType() &&
5153 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
5155 if (ToPtr2->isObjCClassType() &&
5156 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
5158
5159 // A conversion to a non-Class object pointer type is better than a
5160 // conversion to a qualified 'Class' type.
5161 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
5163 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
5165
5166 // -- "conversion of C* to B* is better than conversion of C* to A*,"
5167 if (S.Context.hasSameType(FromType1, FromType2) &&
5168 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
5169 (ToAssignLeft != ToAssignRight)) {
5170 if (FromPtr1->isSpecialized()) {
5171 // "conversion of B<A> * to B * is better than conversion of B * to
5172 // C *.
5173 bool IsFirstSame =
5174 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
5175 bool IsSecondSame =
5176 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
5177 if (IsFirstSame) {
5178 if (!IsSecondSame)
5180 } else if (IsSecondSame)
5182 }
5183 return ToAssignLeft? ImplicitConversionSequence::Worse
5185 }
5186
5187 // -- "conversion of B* to A* is better than conversion of C* to A*,"
5188 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
5189 (FromAssignLeft != FromAssignRight))
5190 return FromAssignLeft? ImplicitConversionSequence::Better
5192 }
5193 }
5194
5195 // Ranking of member-pointer types.
5196 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
5197 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
5198 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
5199 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
5200 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
5201 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
5202 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
5203 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
5204 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
5205 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
5206 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
5207 // conversion of A::* to B::* is better than conversion of A::* to C::*,
5208 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
5209 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
5211 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5213 }
5214 // conversion of B::* to C::* is better than conversion of A::* to C::*
5215 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5216 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5218 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5220 }
5221 }
5222
5223 if (SCS1.Second == ICK_Derived_To_Base) {
5224 // -- conversion of C to B is better than conversion of C to A,
5225 // -- binding of an expression of type C to a reference of type
5226 // B& is better than binding an expression of type C to a
5227 // reference of type A&,
5228 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5229 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5230 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
5232 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
5234 }
5235
5236 // -- conversion of B to A is better than conversion of C to A.
5237 // -- binding of an expression of type B to a reference of type
5238 // A& is better than binding an expression of type C to a
5239 // reference of type A&,
5240 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5241 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5242 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
5244 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
5246 }
5247 }
5248
5250}
5251
5253 if (!T.getQualifiers().hasUnaligned())
5254 return T;
5255
5256 Qualifiers Q;
5257 T = Ctx.getUnqualifiedArrayType(T, Q);
5258 Q.removeUnaligned();
5259 return Ctx.getQualifiedType(T, Q);
5260}
5261
5264 QualType OrigT1, QualType OrigT2,
5265 ReferenceConversions *ConvOut) {
5266 assert(!OrigT1->isReferenceType() &&
5267 "T1 must be the pointee type of the reference type");
5268 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5269
5270 QualType T1 = Context.getCanonicalType(OrigT1);
5271 QualType T2 = Context.getCanonicalType(OrigT2);
5272 Qualifiers T1Quals, T2Quals;
5273 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
5274 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
5275
5276 ReferenceConversions ConvTmp;
5277 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5278 Conv = ReferenceConversions();
5279
5280 // C++2a [dcl.init.ref]p4:
5281 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5282 // reference-related to "cv2 T2" if T1 is similar to T2, or
5283 // T1 is a base class of T2.
5284 // "cv1 T1" is reference-compatible with "cv2 T2" if
5285 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5286 // "pointer to cv1 T1" via a standard conversion sequence.
5287
5288 // Check for standard conversions we can apply to pointers: derived-to-base
5289 // conversions, ObjC pointer conversions, and function pointer conversions.
5290 // (Qualification conversions are checked last.)
5291 if (UnqualT1 == UnqualT2) {
5292 // Nothing to do.
5293 } else if (isCompleteType(Loc, OrigT2) &&
5294 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
5295 Conv |= ReferenceConversions::DerivedToBase;
5296 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5297 UnqualT2->isObjCObjectOrInterfaceType() &&
5298 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
5299 Conv |= ReferenceConversions::ObjC;
5300 else if (UnqualT2->isFunctionType() &&
5301 IsFunctionConversion(UnqualT2, UnqualT1)) {
5302 Conv |= ReferenceConversions::Function;
5303 // No need to check qualifiers; function types don't have them.
5304 return Ref_Compatible;
5305 }
5306 bool ConvertedReferent = Conv != 0;
5307
5308 // We can have a qualification conversion. Compute whether the types are
5309 // similar at the same time.
5310 bool PreviousToQualsIncludeConst = true;
5311 bool TopLevel = true;
5312 do {
5313 if (T1 == T2)
5314 break;
5315
5316 // We will need a qualification conversion.
5317 Conv |= ReferenceConversions::Qualification;
5318
5319 // Track whether we performed a qualification conversion anywhere other
5320 // than the top level. This matters for ranking reference bindings in
5321 // overload resolution.
5322 if (!TopLevel)
5323 Conv |= ReferenceConversions::NestedQualification;
5324
5325 // MS compiler ignores __unaligned qualifier for references; do the same.
5326 T1 = withoutUnaligned(Context, T1);
5327 T2 = withoutUnaligned(Context, T2);
5328
5329 // If we find a qualifier mismatch, the types are not reference-compatible,
5330 // but are still be reference-related if they're similar.
5331 bool ObjCLifetimeConversion = false;
5332 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5333 PreviousToQualsIncludeConst,
5334 ObjCLifetimeConversion, getASTContext()))
5335 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5336 ? Ref_Related
5338
5339 // FIXME: Should we track this for any level other than the first?
5340 if (ObjCLifetimeConversion)
5341 Conv |= ReferenceConversions::ObjCLifetime;
5342
5343 TopLevel = false;
5344 } while (Context.UnwrapSimilarTypes(T1, T2));
5345
5346 // At this point, if the types are reference-related, we must either have the
5347 // same inner type (ignoring qualifiers), or must have already worked out how
5348 // to convert the referent.
5349 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5352}
5353
5354/// Look for a user-defined conversion to a value reference-compatible
5355/// with DeclType. Return true if something definite is found.
5356static bool
5358 QualType DeclType, SourceLocation DeclLoc,
5359 Expr *Init, QualType T2, bool AllowRvalues,
5360 bool AllowExplicit) {
5361 assert(T2->isRecordType() && "Can only find conversions of record types.");
5362 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5363 OverloadCandidateSet CandidateSet(
5365 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5366 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5367 NamedDecl *D = *I;
5369 if (isa<UsingShadowDecl>(D))
5370 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5371
5372 FunctionTemplateDecl *ConvTemplate
5373 = dyn_cast<FunctionTemplateDecl>(D);
5374 CXXConversionDecl *Conv;
5375 if (ConvTemplate)
5376 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5377 else
5378 Conv = cast<CXXConversionDecl>(D);
5379
5380 if (AllowRvalues) {
5381 // If we are initializing an rvalue reference, don't permit conversion
5382 // functions that return lvalues.
5383 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5384 const ReferenceType *RefType
5386 if (RefType && !RefType->getPointeeType()->isFunctionType())
5387 continue;
5388 }
5389
5390 if (!ConvTemplate &&
5392 DeclLoc,
5393 Conv->getConversionType()
5398 continue;
5399 } else {
5400 // If the conversion function doesn't return a reference type,
5401 // it can't be considered for this conversion. An rvalue reference
5402 // is only acceptable if its referencee is a function type.
5403
5404 const ReferenceType *RefType =
5406 if (!RefType ||
5407 (!RefType->isLValueReferenceType() &&
5408 !RefType->getPointeeType()->isFunctionType()))
5409 continue;
5410 }
5411
5412 if (ConvTemplate)
5414 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5415 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5416 else
5418 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5419 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5420 }
5421
5422 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5423
5425 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5426 case OR_Success:
5427
5428 assert(Best->HasFinalConversion);
5429
5430 // C++ [over.ics.ref]p1:
5431 //
5432 // [...] If the parameter binds directly to the result of
5433 // applying a conversion function to the argument
5434 // expression, the implicit conversion sequence is a
5435 // user-defined conversion sequence (13.3.3.1.2), with the
5436 // second standard conversion sequence either an identity
5437 // conversion or, if the conversion function returns an
5438 // entity of a type that is a derived class of the parameter
5439 // type, a derived-to-base Conversion.
5440 if (!Best->FinalConversion.DirectBinding)
5441 return false;
5442
5443 ICS.setUserDefined();
5444 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5445 ICS.UserDefined.After = Best->FinalConversion;
5446 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5447 ICS.UserDefined.ConversionFunction = Best->Function;
5448 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5449 ICS.UserDefined.EllipsisConversion = false;
5450 assert(ICS.UserDefined.After.ReferenceBinding &&
5452 "Expected a direct reference binding!");
5453 return true;
5454
5455 case OR_Ambiguous:
5456 ICS.setAmbiguous();
5457 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5458 Cand != CandidateSet.end(); ++Cand)
5459 if (Cand->Best)
5460 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5461 return true;
5462
5464 case OR_Deleted:
5465 // There was no suitable conversion, or we found a deleted
5466 // conversion; continue with other checks.
5467 return false;
5468 }
5469
5470 llvm_unreachable("Invalid OverloadResult!");
5471}
5472
5473/// Compute an implicit conversion sequence for reference
5474/// initialization.
5475static ImplicitConversionSequence
5477 SourceLocation DeclLoc,
5478 bool SuppressUserConversions,
5479 bool AllowExplicit) {
5480 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5481
5482 // Most paths end in a failed conversion.
5485
5486 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5487 QualType T2 = Init->getType();
5488
5489 // If the initializer is the address of an overloaded function, try
5490 // to resolve the overloaded function. If all goes well, T2 is the
5491 // type of the resulting function.
5492 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5495 false, Found))
5496 T2 = Fn->getType();
5497 }
5498
5499 // Compute some basic properties of the types and the initializer.
5500 bool isRValRef = DeclType->isRValueReferenceType();
5501 Expr::Classification InitCategory = Init->Classify(S.Context);
5502
5504 Sema::ReferenceCompareResult RefRelationship =
5505 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5506
5507 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5508 ICS.setStandard();
5510 // FIXME: A reference binding can be a function conversion too. We should
5511 // consider that when ordering reference-to-function bindings.
5512 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5514 : (RefConv & Sema::ReferenceConversions::ObjC)
5516 : ICK_Identity;
5518 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5519 // a reference binding that performs a non-top-level qualification
5520 // conversion as a qualification conversion, not as an identity conversion.
5521 ICS.Standard.Third = (RefConv &
5522 Sema::ReferenceConversions::NestedQualification)
5524 : ICK_Identity;
5525 ICS.Standard.setFromType(T2);
5526 ICS.Standard.setToType(0, T2);
5527 ICS.Standard.setToType(1, T1);
5528 ICS.Standard.setToType(2, T1);
5529 ICS.Standard.ReferenceBinding = true;
5530 ICS.Standard.DirectBinding = BindsDirectly;
5531 ICS.Standard.IsLvalueReference = !isRValRef;
5533 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5536 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5537 ICS.Standard.FromBracedInitList = false;
5538 ICS.Standard.CopyConstructor = nullptr;
5540 };
5541
5542 // C++0x [dcl.init.ref]p5:
5543 // A reference to type "cv1 T1" is initialized by an expression
5544 // of type "cv2 T2" as follows:
5545
5546 // -- If reference is an lvalue reference and the initializer expression
5547 if (!isRValRef) {
5548 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5549 // reference-compatible with "cv2 T2," or
5550 //
5551 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5552 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5553 // C++ [over.ics.ref]p1:
5554 // When a parameter of reference type binds directly (8.5.3)
5555 // to an argument expression, the implicit conversion sequence
5556 // is the identity conversion, unless the argument expression
5557 // has a type that is a derived class of the parameter type,
5558 // in which case the implicit conversion sequence is a
5559 // derived-to-base Conversion (13.3.3.1).
5560 SetAsReferenceBinding(/*BindsDirectly=*/true);
5561
5562 // Nothing more to do: the inaccessibility/ambiguity check for
5563 // derived-to-base conversions is suppressed when we're
5564 // computing the implicit conversion sequence (C++
5565 // [over.best.ics]p2).
5566 return ICS;
5567 }
5568
5569 // -- has a class type (i.e., T2 is a class type), where T1 is
5570 // not reference-related to T2, and can be implicitly
5571 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5572 // is reference-compatible with "cv3 T3" 92) (this
5573 // conversion is selected by enumerating the applicable
5574 // conversion functions (13.3.1.6) and choosing the best
5575 // one through overload resolution (13.3)),
5576 if (!SuppressUserConversions && T2->isRecordType() &&
5577 S.isCompleteType(DeclLoc, T2) &&
5578 RefRelationship == Sema::Ref_Incompatible) {
5579 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5580 Init, T2, /*AllowRvalues=*/false,
5581 AllowExplicit))
5582 return ICS;
5583 }
5584 }
5585
5586 // -- Otherwise, the reference shall be an lvalue reference to a
5587 // non-volatile const type (i.e., cv1 shall be const), or the reference
5588 // shall be an rvalue reference.
5589 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5590 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5592 return ICS;
5593 }
5594
5595 // -- If the initializer expression
5596 //
5597 // -- is an xvalue, class prvalue, array prvalue or function
5598 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5599 if (RefRelationship == Sema::Ref_Compatible &&
5600 (InitCategory.isXValue() ||
5601 (InitCategory.isPRValue() &&
5602 (T2->isRecordType() || T2->isArrayType())) ||
5603 (InitCategory.isLValue() && T2->isFunctionType()))) {
5604 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5605 // binding unless we're binding to a class prvalue.
5606 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5607 // allow the use of rvalue references in C++98/03 for the benefit of
5608 // standard library implementors; therefore, we need the xvalue check here.
5609 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5610 !(InitCategory.isPRValue() || T2->isRecordType()));
5611 return ICS;
5612 }
5613
5614 // -- has a class type (i.e., T2 is a class type), where T1 is not
5615 // reference-related to T2, and can be implicitly converted to
5616 // an xvalue, class prvalue, or function lvalue of type
5617 // "cv3 T3", where "cv1 T1" is reference-compatible with
5618 // "cv3 T3",
5619 //
5620 // then the reference is bound to the value of the initializer
5621 // expression in the first case and to the result of the conversion
5622 // in the second case (or, in either case, to an appropriate base
5623 // class subobject).
5624 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5625 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5626 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5627 Init, T2, /*AllowRvalues=*/true,
5628 AllowExplicit)) {
5629 // In the second case, if the reference is an rvalue reference
5630 // and the second standard conversion sequence of the
5631 // user-defined conversion sequence includes an lvalue-to-rvalue
5632 // conversion, the program is ill-formed.
5633 if (ICS.isUserDefined() && isRValRef &&
5636
5637 return ICS;
5638 }
5639
5640 // A temporary of function type cannot be created; don't even try.
5641 if (T1->isFunctionType())
5642 return ICS;
5643
5644 // -- Otherwise, a temporary of type "cv1 T1" is created and
5645 // initialized from the initializer expression using the
5646 // rules for a non-reference copy initialization (8.5). The
5647 // reference is then bound to the temporary. If T1 is
5648 // reference-related to T2, cv1 must be the same
5649 // cv-qualification as, or greater cv-qualification than,
5650 // cv2; otherwise, the program is ill-formed.
5651 if (RefRelationship == Sema::Ref_Related) {
5652 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5653 // we would be reference-compatible or reference-compatible with
5654 // added qualification. But that wasn't the case, so the reference
5655 // initialization fails.
5656 //
5657 // Note that we only want to check address spaces and cvr-qualifiers here.
5658 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5659 Qualifiers T1Quals = T1.getQualifiers();
5660 Qualifiers T2Quals = T2.getQualifiers();
5661 T1Quals.removeObjCGCAttr();
5662 T1Quals.removeObjCLifetime();
5663 T2Quals.removeObjCGCAttr();
5664 T2Quals.removeObjCLifetime();
5665 // MS compiler ignores __unaligned qualifier for references; do the same.
5666 T1Quals.removeUnaligned();
5667 T2Quals.removeUnaligned();
5668 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5669 return ICS;
5670 }
5671
5672 // If at least one of the types is a class type, the types are not
5673 // related, and we aren't allowed any user conversions, the
5674 // reference binding fails. This case is important for breaking
5675 // recursion, since TryImplicitConversion below will attempt to
5676 // create a temporary through the use of a copy constructor.
5677 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5678 (T1->isRecordType() || T2->isRecordType()))
5679 return ICS;
5680
5681 // If T1 is reference-related to T2 and the reference is an rvalue
5682 // reference, the initializer expression shall not be an lvalue.
5683 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5684 Init->Classify(S.Context).isLValue()) {
5686 return ICS;
5687 }
5688
5689 // C++ [over.ics.ref]p2:
5690 // When a parameter of reference type is not bound directly to
5691 // an argument expression, the conversion sequence is the one
5692 // required to convert the argument expression to the
5693 // underlying type of the reference according to
5694 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5695 // to copy-initializing a temporary of the underlying type with
5696 // the argument expression. Any difference in top-level
5697 // cv-qualification is subsumed by the initialization itself
5698 // and does not constitute a conversion.
5699 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5700 AllowedExplicit::None,
5701 /*InOverloadResolution=*/false,
5702 /*CStyle=*/false,
5703 /*AllowObjCWritebackConversion=*/false,
5704 /*AllowObjCConversionOnExplicit=*/false);
5705
5706 // Of course, that's still a reference binding.
5707 if (ICS.isStandard()) {
5708 ICS.Standard.ReferenceBinding = true;
5709 ICS.Standard.IsLvalueReference = !isRValRef;
5710 ICS.Standard.BindsToFunctionLvalue = false;
5711 ICS.Standard.BindsToRvalue = true;
5714 } else if (ICS.isUserDefined()) {
5715 const ReferenceType *LValRefType =
5718
5719 // C++ [over.ics.ref]p3:
5720 // Except for an implicit object parameter, for which see 13.3.1, a
5721 // standard conversion sequence cannot be formed if it requires [...]
5722 // binding an rvalue reference to an lvalue other than a function
5723 // lvalue.
5724 // Note that the function case is not possible here.
5725 if (isRValRef && LValRefType) {
5727 return ICS;
5728 }
5729
5731 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5733 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5737 }
5738
5739 return ICS;
5740}
5741
5742static ImplicitConversionSequence
5743TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5744 bool SuppressUserConversions,
5745 bool InOverloadResolution,
5746 bool AllowObjCWritebackConversion,
5747 bool AllowExplicit = false);
5748
5749/// TryListConversion - Try to copy-initialize a value of type ToType from the
5750/// initializer list From.
5751static ImplicitConversionSequence
5753 bool SuppressUserConversions,
5754 bool InOverloadResolution,
5755 bool AllowObjCWritebackConversion) {
5756 // C++11 [over.ics.list]p1:
5757 // When an argument is an initializer list, it is not an expression and
5758 // special rules apply for converting it to a parameter type.
5759
5761 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5762
5763 // We need a complete type for what follows. With one C++20 exception,
5764 // incomplete types can never be initialized from init lists.
5765 QualType InitTy = ToType;
5766 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5767 if (AT && S.getLangOpts().CPlusPlus20)
5768 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5769 // C++20 allows list initialization of an incomplete array type.
5770 InitTy = IAT->getElementType();
5771 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5772 return Result;
5773
5774 // C++20 [over.ics.list]/2:
5775 // If the initializer list is a designated-initializer-list, a conversion
5776 // is only possible if the parameter has an aggregate type
5777 //
5778 // FIXME: The exception for reference initialization here is not part of the
5779 // language rules, but follow other compilers in adding it as a tentative DR
5780 // resolution.
5781 bool IsDesignatedInit = From->hasDesignatedInit();
5782 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5783 IsDesignatedInit)
5784 return Result;
5785
5786 // Per DR1467 and DR2137:
5787 // If the parameter type is an aggregate class X and the initializer list
5788 // has a single element of type cv U, where U is X or a class derived from
5789 // X, the implicit conversion sequence is the one required to convert the
5790 // element to the parameter type.
5791 //
5792 // Otherwise, if the parameter type is a character array [... ]
5793 // and the initializer list has a single element that is an
5794 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5795 // implicit conversion sequence is the identity conversion.
5796 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5797 if (ToType->isRecordType() && ToType->isAggregateType()) {
5798 QualType InitType = From->getInit(0)->getType();
5799 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5800 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5801 return TryCopyInitialization(S, From->getInit(0), ToType,
5802 SuppressUserConversions,
5803 InOverloadResolution,
5804 AllowObjCWritebackConversion);
5805 }
5806
5807 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5808 InitializedEntity Entity =
5810 /*Consumed=*/false);
5811 if (S.CanPerformCopyInitialization(Entity, From)) {
5812 Result.setStandard();
5813 Result.Standard.setAsIdentityConversion();
5814 Result.Standard.setFromType(ToType);
5815 Result.Standard.setAllToTypes(ToType);
5816 return Result;
5817 }
5818 }
5819 }
5820
5821 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5822 // C++11 [over.ics.list]p2:
5823 // If the parameter type is std::initializer_list<X> or "array of X" and
5824 // all the elements can be implicitly converted to X, the implicit
5825 // conversion sequence is the worst conversion necessary to convert an
5826 // element of the list to X.
5827 //
5828 // C++14 [over.ics.list]p3:
5829 // Otherwise, if the parameter type is "array of N X", if the initializer
5830 // list has exactly N elements or if it has fewer than N elements and X is
5831 // default-constructible, and if all the elements of the initializer list
5832 // can be implicitly converted to X, the implicit conversion sequence is
5833 // the worst conversion necessary to convert an element of the list to X.
5834 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5835 unsigned e = From->getNumInits();
5838 QualType());
5839 QualType ContTy = ToType;
5840 bool IsUnbounded = false;
5841 if (AT) {
5842 InitTy = AT->getElementType();
5843 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5844 if (CT->getSize().ult(e)) {
5845 // Too many inits, fatally bad
5847 ToType);
5848 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5849 return Result;
5850 }
5851 if (CT->getSize().ugt(e)) {
5852 // Need an init from empty {}, is there one?
5853 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5854 From->getEndLoc(), /*isExplicit=*/false);
5855 EmptyList.setType(S.Context.VoidTy);
5856 DfltElt = TryListConversion(
5857 S, &EmptyList, InitTy, SuppressUserConversions,
5858 InOverloadResolution, AllowObjCWritebackConversion);
5859 if (DfltElt.isBad()) {
5860 // No {} init, fatally bad
5862 ToType);
5863 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5864 return Result;
5865 }
5866 }
5867 } else {
5868 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5869 IsUnbounded = true;
5870 if (!e) {
5871 // Cannot convert to zero-sized.
5873 ToType);
5874 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5875 return Result;
5876 }
5877 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5878 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5880 }
5881 }
5882
5883 Result.setStandard();
5884 Result.Standard.setAsIdentityConversion();
5885 Result.Standard.setFromType(InitTy);
5886 Result.Standard.setAllToTypes(InitTy);
5887 for (unsigned i = 0; i < e; ++i) {
5888 Expr *Init = From->getInit(i);
5890 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5891 AllowObjCWritebackConversion);
5892
5893 // Keep the worse conversion seen so far.
5894 // FIXME: Sequences are not totally ordered, so 'worse' can be
5895 // ambiguous. CWG has been informed.
5897 Result) ==
5899 Result = ICS;
5900 // Bail as soon as we find something unconvertible.
5901 if (Result.isBad()) {
5902 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5903 return Result;
5904 }
5905 }
5906 }
5907
5908 // If we needed any implicit {} initialization, compare that now.
5909 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5910 // has been informed that this might not be the best thing.
5911 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5912 S, From->getEndLoc(), DfltElt, Result) ==
5914 Result = DfltElt;
5915 // Record the type being initialized so that we may compare sequences
5916 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5917 return Result;
5918 }
5919
5920 // C++14 [over.ics.list]p4:
5921 // C++11 [over.ics.list]p3:
5922 // Otherwise, if the parameter is a non-aggregate class X and overload
5923 // resolution chooses a single best constructor [...] the implicit
5924 // conversion sequence is a user-defined conversion sequence. If multiple
5925 // constructors are viable but none is better than the others, the
5926 // implicit conversion sequence is a user-defined conversion sequence.
5927 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5928 // This function can deal with initializer lists.
5929 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5930 AllowedExplicit::None,
5931 InOverloadResolution, /*CStyle=*/false,
5932 AllowObjCWritebackConversion,
5933 /*AllowObjCConversionOnExplicit=*/false);
5934 }
5935
5936 // C++14 [over.ics.list]p5:
5937 // C++11 [over.ics.list]p4:
5938 // Otherwise, if the parameter has an aggregate type which can be
5939 // initialized from the initializer list [...] the implicit conversion
5940 // sequence is a user-defined conversion sequence.
5941 if (ToType->isAggregateType()) {
5942 // Type is an aggregate, argument is an init list. At this point it comes
5943 // down to checking whether the initialization works.
5944 // FIXME: Find out whether this parameter is consumed or not.
5945 InitializedEntity Entity =
5947 /*Consumed=*/false);
5949 From)) {
5950 Result.setUserDefined();
5951 Result.UserDefined.Before.setAsIdentityConversion();
5952 // Initializer lists don't have a type.
5953 Result.UserDefined.Before.setFromType(QualType());
5954 Result.UserDefined.Before.setAllToTypes(QualType());
5955
5956 Result.UserDefined.After.setAsIdentityConversion();
5957 Result.UserDefined.After.setFromType(ToType);
5958 Result.UserDefined.After.setAllToTypes(ToType);
5959 Result.UserDefined.ConversionFunction = nullptr;
5960 }
5961 return Result;
5962 }
5963
5964 // C++14 [over.ics.list]p6:
5965 // C++11 [over.ics.list]p5:
5966 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5967 if (ToType->isReferenceType()) {
5968 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5969 // mention initializer lists in any way. So we go by what list-
5970 // initialization would do and try to extrapolate from that.
5971
5972 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5973
5974 // If the initializer list has a single element that is reference-related
5975 // to the parameter type, we initialize the reference from that.
5976 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5977 Expr *Init = From->getInit(0);
5978
5979 QualType T2 = Init->getType();
5980
5981 // If the initializer is the address of an overloaded function, try
5982 // to resolve the overloaded function. If all goes well, T2 is the
5983 // type of the resulting function.
5984 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5987 Init, ToType, false, Found))
5988 T2 = Fn->getType();
5989 }
5990
5991 // Compute some basic properties of the types and the initializer.
5992 Sema::ReferenceCompareResult RefRelationship =
5993 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5994
5995 if (RefRelationship >= Sema::Ref_Related) {
5996 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5997 SuppressUserConversions,
5998 /*AllowExplicit=*/false);
5999 }
6000 }
6001
6002 // Otherwise, we bind the reference to a temporary created from the
6003 // initializer list.
6004 Result = TryListConversion(S, From, T1, SuppressUserConversions,
6005 InOverloadResolution,
6006 AllowObjCWritebackConversion);
6007 if (Result.isFailure())
6008 return Result;
6009 assert(!Result.isEllipsis() &&
6010 "Sub-initialization cannot result in ellipsis conversion.");
6011
6012 // Can we even bind to a temporary?
6013 if (ToType->isRValueReferenceType() ||
6014 (T1.isConstQualified() && !T1.isVolatileQualified())) {
6015 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
6016 Result.UserDefined.After;
6017 SCS.ReferenceBinding = true;
6019 SCS.BindsToRvalue = true;
6020 SCS.BindsToFunctionLvalue = false;
6023 SCS.FromBracedInitList = false;
6024
6025 } else
6027 From, ToType);
6028 return Result;
6029 }
6030
6031 // C++14 [over.ics.list]p7:
6032 // C++11 [over.ics.list]p6:
6033 // Otherwise, if the parameter type is not a class:
6034 if (!ToType->isRecordType()) {
6035 // - if the initializer list has one element that is not itself an
6036 // initializer list, the implicit conversion sequence is the one
6037 // required to convert the element to the parameter type.
6038 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
6039 // single integer.
6040 unsigned NumInits = From->getNumInits();
6041 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)) &&
6042 !isa<EmbedExpr>(From->getInit(0))) {
6044 S, From->getInit(0), ToType, SuppressUserConversions,
6045 InOverloadResolution, AllowObjCWritebackConversion);
6046 if (Result.isStandard())
6047 Result.Standard.FromBracedInitList = true;
6048 }
6049 // - if the initializer list has no elements, the implicit conversion
6050 // sequence is the identity conversion.
6051 else if (NumInits == 0) {
6052 Result.setStandard();
6053 Result.Standard.setAsIdentityConversion();
6054 Result.Standard.setFromType(ToType);
6055 Result.Standard.setAllToTypes(ToType);
6056 }
6057 return Result;
6058 }
6059
6060 // C++14 [over.ics.list]p8:
6061 // C++11 [over.ics.list]p7:
6062 // In all cases other than those enumerated above, no conversion is possible
6063 return Result;
6064}
6065
6066/// TryCopyInitialization - Try to copy-initialize a value of type
6067/// ToType from the expression From. Return the implicit conversion
6068/// sequence required to pass this argument, which may be a bad
6069/// conversion sequence (meaning that the argument cannot be passed to
6070/// a parameter of this type). If @p SuppressUserConversions, then we
6071/// do not permit any user-defined conversion sequences.
6072static ImplicitConversionSequence
6074 bool SuppressUserConversions,
6075 bool InOverloadResolution,
6076 bool AllowObjCWritebackConversion,
6077 bool AllowExplicit) {
6078 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
6079 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
6080 InOverloadResolution,AllowObjCWritebackConversion);
6081
6082 if (ToType->isReferenceType())
6083 return TryReferenceInit(S, From, ToType,
6084 /*FIXME:*/ From->getBeginLoc(),
6085 SuppressUserConversions, AllowExplicit);
6086
6087 return TryImplicitConversion(S, From, ToType,
6088 SuppressUserConversions,
6089 AllowedExplicit::None,
6090 InOverloadResolution,
6091 /*CStyle=*/false,
6092 AllowObjCWritebackConversion,
6093 /*AllowObjCConversionOnExplicit=*/false);
6094}
6095
6096static bool TryCopyInitialization(const CanQualType FromQTy,
6097 const CanQualType ToQTy,
6098 Sema &S,
6099 SourceLocation Loc,
6100 ExprValueKind FromVK) {
6101 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
6103 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
6104
6105 return !ICS.isBad();
6106}
6107
6108/// TryObjectArgumentInitialization - Try to initialize the object
6109/// parameter of the given member function (@c Method) from the
6110/// expression @p From.
6112 Sema &S, SourceLocation Loc, QualType FromType,
6113 Expr::Classification FromClassification, CXXMethodDecl *Method,
6114 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
6115 QualType ExplicitParameterType = QualType(),
6116 bool SuppressUserConversion = false) {
6117
6118 // We need to have an object of class type.
6119 if (const auto *PT = FromType->getAs<PointerType>()) {
6120 FromType = PT->getPointeeType();
6121
6122 // When we had a pointer, it's implicitly dereferenced, so we
6123 // better have an lvalue.
6124 assert(FromClassification.isLValue());
6125 }
6126
6127 auto ValueKindFromClassification = [](Expr::Classification C) {
6128 if (C.isPRValue())
6129 return clang::VK_PRValue;
6130 if (C.isXValue())
6131 return VK_XValue;
6132 return clang::VK_LValue;
6133 };
6134
6135 if (Method->isExplicitObjectMemberFunction()) {
6136 if (ExplicitParameterType.isNull())
6137 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
6138 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
6139 ValueKindFromClassification(FromClassification));
6141 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
6142 /*InOverloadResolution=*/true, false);
6143 if (ICS.isBad())
6144 ICS.Bad.FromExpr = nullptr;
6145 return ICS;
6146 }
6147
6148 assert(FromType->isRecordType());
6149
6150 CanQualType ClassType = S.Context.getCanonicalTagType(ActingContext);
6151 // C++98 [class.dtor]p2:
6152 // A destructor can be invoked for a const, volatile or const volatile
6153 // object.
6154 // C++98 [over.match.funcs]p4:
6155 // For static member functions, the implicit object parameter is considered
6156 // to match any object (since if the function is selected, the object is
6157 // discarded).
6158 Qualifiers Quals = Method->getMethodQualifiers();
6159 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
6160 Quals.addConst();
6161 Quals.addVolatile();
6162 }
6163
6164 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
6165
6166 // Set up the conversion sequence as a "bad" conversion, to allow us
6167 // to exit early.
6169
6170 // C++0x [over.match.funcs]p4:
6171 // For non-static member functions, the type of the implicit object
6172 // parameter is
6173 //
6174 // - "lvalue reference to cv X" for functions declared without a
6175 // ref-qualifier or with the & ref-qualifier
6176 // - "rvalue reference to cv X" for functions declared with the &&
6177 // ref-qualifier
6178 //
6179 // where X is the class of which the function is a member and cv is the
6180 // cv-qualification on the member function declaration.
6181 //
6182 // However, when finding an implicit conversion sequence for the argument, we
6183 // are not allowed to perform user-defined conversions
6184 // (C++ [over.match.funcs]p5). We perform a simplified version of
6185 // reference binding here, that allows class rvalues to bind to
6186 // non-constant references.
6187
6188 // First check the qualifiers.
6189 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
6190 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
6191 if (ImplicitParamType.getCVRQualifiers() !=
6192 FromTypeCanon.getLocalCVRQualifiers() &&
6193 !ImplicitParamType.isAtLeastAsQualifiedAs(
6194 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
6196 FromType, ImplicitParamType);
6197 return ICS;
6198 }
6199
6200 if (FromTypeCanon.hasAddressSpace()) {
6201 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
6202 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
6203 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
6204 S.getASTContext())) {
6206 FromType, ImplicitParamType);
6207 return ICS;
6208 }
6209 }
6210
6211 // Check that we have either the same type or a derived type. It
6212 // affects the conversion rank.
6213 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
6214 ImplicitConversionKind SecondKind;
6215 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6216 SecondKind = ICK_Identity;
6217 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
6218 SecondKind = ICK_Derived_To_Base;
6219 } else if (!Method->isExplicitObjectMemberFunction()) {
6221 FromType, ImplicitParamType);
6222 return ICS;
6223 }
6224
6225 // Check the ref-qualifier.
6226 switch (Method->getRefQualifier()) {
6227 case RQ_None:
6228 // Do nothing; we don't care about lvalueness or rvalueness.
6229 break;
6230
6231 case RQ_LValue:
6232 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6233 // non-const lvalue reference cannot bind to an rvalue
6235 ImplicitParamType);
6236 return ICS;
6237 }
6238 break;
6239
6240 case RQ_RValue:
6241 if (!FromClassification.isRValue()) {
6242 // rvalue reference cannot bind to an lvalue
6244 ImplicitParamType);
6245 return ICS;
6246 }
6247 break;
6248 }
6249
6250 // Success. Mark this as a reference binding.
6251 ICS.setStandard();
6253 ICS.Standard.Second = SecondKind;
6254 ICS.Standard.setFromType(FromType);
6255 ICS.Standard.setAllToTypes(ImplicitParamType);
6256 ICS.Standard.ReferenceBinding = true;
6257 ICS.Standard.DirectBinding = true;
6258 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6259 ICS.Standard.BindsToFunctionLvalue = false;
6260 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6261 ICS.Standard.FromBracedInitList = false;
6263 = (Method->getRefQualifier() == RQ_None);
6264 return ICS;
6265}
6266
6267/// PerformObjectArgumentInitialization - Perform initialization of
6268/// the implicit object parameter for the given Method with the given
6269/// expression.
6271 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6273 QualType FromRecordType, DestType;
6274 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6275
6276 if (getLangOpts().HLSL &&
6279 From = ImplicitCastExpr::Create(Context, CastType, CK_LValueToRValue, From,
6280 /*BasePath=*/nullptr, VK_PRValue,
6282 }
6283
6284 Expr::Classification FromClassification;
6285 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6286 FromRecordType = PT->getPointeeType();
6287 DestType = Method->getThisType();
6288 FromClassification = Expr::Classification::makeSimpleLValue();
6289 } else {
6290 FromRecordType = From->getType();
6291 DestType = ImplicitParamRecordType;
6292 FromClassification = From->Classify(Context);
6293
6294 // CWG2813 [expr.call]p6:
6295 // If the function is an implicit object member function, the object
6296 // expression of the class member access shall be a glvalue [...]
6297 if (From->isPRValue()) {
6298 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
6299 Method->getRefQualifier() !=
6301 }
6302 }
6303
6304 // Note that we always use the true parent context when performing
6305 // the actual argument initialization.
6307 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
6308 Method->getParent());
6309 if (ICS.isBad()) {
6310 switch (ICS.Bad.Kind) {
6312 Qualifiers FromQs = FromRecordType.getQualifiers();
6313 Qualifiers ToQs = DestType.getQualifiers();
6314 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6315 if (CVR) {
6316 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
6317 << Method->getDeclName() << FromRecordType << (CVR - 1)
6318 << From->getSourceRange();
6319 Diag(Method->getLocation(), diag::note_previous_decl)
6320 << Method->getDeclName();
6321 return ExprError();
6322 }
6323 break;
6324 }
6325
6328 bool IsRValueQualified =
6329 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6330 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
6331 << Method->getDeclName() << FromClassification.isRValue()
6332 << IsRValueQualified;
6333 Diag(Method->getLocation(), diag::note_previous_decl)
6334 << Method->getDeclName();
6335 return ExprError();
6336 }
6337
6340 break;
6341
6344 llvm_unreachable("Lists are not objects");
6345 }
6346
6347 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6348 << ImplicitParamRecordType << FromRecordType
6349 << From->getSourceRange();
6350 }
6351
6352 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6353 ExprResult FromRes =
6354 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6355 if (FromRes.isInvalid())
6356 return ExprError();
6357 From = FromRes.get();
6358 }
6359
6360 if (!Context.hasSameType(From->getType(), DestType)) {
6361 CastKind CK;
6362 QualType PteeTy = DestType->getPointeeType();
6363 LangAS DestAS =
6364 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6365 if (FromRecordType.getAddressSpace() != DestAS)
6366 CK = CK_AddressSpaceConversion;
6367 else
6368 CK = CK_NoOp;
6369 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6370 }
6371 return From;
6372}
6373
6374/// TryContextuallyConvertToBool - Attempt to contextually convert the
6375/// expression From to bool (C++0x [conv]p3).
6378 // C++ [dcl.init]/17.8:
6379 // - Otherwise, if the initialization is direct-initialization, the source
6380 // type is std::nullptr_t, and the destination type is bool, the initial
6381 // value of the object being initialized is false.
6382 if (From->getType()->isNullPtrType())
6384 S.Context.BoolTy,
6385 From->isGLValue());
6386
6387 // All other direct-initialization of bool is equivalent to an implicit
6388 // conversion to bool in which explicit conversions are permitted.
6389 return TryImplicitConversion(S, From, S.Context.BoolTy,
6390 /*SuppressUserConversions=*/false,
6391 AllowedExplicit::Conversions,
6392 /*InOverloadResolution=*/false,
6393 /*CStyle=*/false,
6394 /*AllowObjCWritebackConversion=*/false,
6395 /*AllowObjCConversionOnExplicit=*/false);
6396}
6397
6399 if (checkPlaceholderForOverload(*this, From))
6400 return ExprError();
6401 if (From->getType() == Context.AMDGPUFeaturePredicateTy)
6402 return AMDGPU().ExpandAMDGPUPredicateBuiltIn(From);
6403
6405 if (!ICS.isBad())
6406 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6409 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6410 << From->getType() << From->getSourceRange();
6411 return ExprError();
6412}
6413
6414/// Check that the specified conversion is permitted in a converted constant
6415/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6416/// is acceptable.
6419 // Since we know that the target type is an integral or unscoped enumeration
6420 // type, most conversion kinds are impossible. All possible First and Third
6421 // conversions are fine.
6422 switch (SCS.Second) {
6423 case ICK_Identity:
6425 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6427 return true;
6428
6430 // Conversion from an integral or unscoped enumeration type to bool is
6431 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6432 // conversion, so we allow it in a converted constant expression.
6433 //
6434 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6435 // a lot of popular code. We should at least add a warning for this
6436 // (non-conforming) extension.
6438 SCS.getToType(2)->isBooleanType();
6439
6441 case ICK_Pointer_Member:
6442 // C++1z: null pointer conversions and null member pointer conversions are
6443 // only permitted if the source type is std::nullptr_t.
6444 return SCS.getFromType()->isNullPtrType();
6445
6458 case ICK_Vector_Splat:
6459 case ICK_Complex_Real:
6469 return false;
6470
6475 llvm_unreachable("found a first conversion kind in Second");
6476
6478 case ICK_Qualification:
6479 llvm_unreachable("found a third conversion kind in Second");
6480
6482 break;
6483 }
6484
6485 llvm_unreachable("unknown conversion kind");
6486}
6487
6488/// BuildConvertedConstantExpression - Check that the expression From is a
6489/// converted constant expression of type T, perform the conversion but
6490/// does not evaluate the expression
6492 QualType T, CCEKind CCE,
6493 NamedDecl *Dest,
6494 APValue &PreNarrowingValue) {
6495 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6497 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6498 "converted constant expression outside C++11 or TTP matching");
6499
6500 if (checkPlaceholderForOverload(S, From))
6501 return ExprError();
6502
6503 if (From->containsErrors()) {
6504 // The expression already has errors, so the correct cast kind can't be
6505 // determined. Use RecoveryExpr to keep the expected type T and mark the
6506 // result as invalid, preventing further cascading errors.
6507 return S.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(), {From},
6508 T);
6509 }
6510
6511 // C++1z [expr.const]p3:
6512 // A converted constant expression of type T is an expression,
6513 // implicitly converted to type T, where the converted
6514 // expression is a constant expression and the implicit conversion
6515 // sequence contains only [... list of conversions ...].
6517 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6519 : TryCopyInitialization(S, From, T,
6520 /*SuppressUserConversions=*/false,
6521 /*InOverloadResolution=*/false,
6522 /*AllowObjCWritebackConversion=*/false,
6523 /*AllowExplicit=*/false);
6524 StandardConversionSequence *SCS = nullptr;
6525 switch (ICS.getKind()) {
6527 SCS = &ICS.Standard;
6528 break;
6530 if (T->isRecordType())
6531 SCS = &ICS.UserDefined.Before;
6532 else
6533 SCS = &ICS.UserDefined.After;
6534 break;
6538 return S.Diag(From->getBeginLoc(),
6539 diag::err_typecheck_converted_constant_expression)
6540 << From->getType() << From->getSourceRange() << T;
6541 return ExprError();
6542
6545 llvm_unreachable("bad conversion in converted constant expression");
6546 }
6547
6548 // Check that we would only use permitted conversions.
6549 if (!CheckConvertedConstantConversions(S, *SCS)) {
6550 return S.Diag(From->getBeginLoc(),
6551 diag::err_typecheck_converted_constant_expression_disallowed)
6552 << From->getType() << From->getSourceRange() << T;
6553 }
6554 // [...] and where the reference binding (if any) binds directly.
6555 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6556 return S.Diag(From->getBeginLoc(),
6557 diag::err_typecheck_converted_constant_expression_indirect)
6558 << From->getType() << From->getSourceRange() << T;
6559 }
6560 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6561 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6562 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6563 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6564 // case explicitly.
6565 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6566 return S.Diag(From->getBeginLoc(),
6567 diag::err_reference_bind_to_bitfield_in_cce)
6568 << From->getSourceRange();
6569 }
6570
6571 // Usually we can simply apply the ImplicitConversionSequence we formed
6572 // earlier, but that's not guaranteed to work when initializing an object of
6573 // class type.
6575 bool IsTemplateArgument =
6577 if (T->isRecordType()) {
6578 assert(IsTemplateArgument &&
6579 "unexpected class type converted constant expr");
6583 SourceLocation(), From);
6584 } else {
6585 Result =
6587 }
6588 if (Result.isInvalid())
6589 return Result;
6590
6591 // C++2a [intro.execution]p5:
6592 // A full-expression is [...] a constant-expression [...]
6593 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6594 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6595 IsTemplateArgument);
6596 if (Result.isInvalid())
6597 return Result;
6598
6599 // Check for a narrowing implicit conversion.
6600 bool ReturnPreNarrowingValue = false;
6601 QualType PreNarrowingType;
6602 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6603 PreNarrowingType)) {
6605 // Implicit conversion to a narrower type, and the value is not a constant
6606 // expression. We'll diagnose this in a moment.
6607 case NK_Not_Narrowing:
6608 break;
6609
6611 if (CCE == CCEKind::ArrayBound &&
6612 PreNarrowingType->isIntegralOrEnumerationType() &&
6613 PreNarrowingValue.isInt()) {
6614 // Don't diagnose array bound narrowing here; we produce more precise
6615 // errors by allowing the un-narrowed value through.
6616 ReturnPreNarrowingValue = true;
6617 break;
6618 }
6619 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6620 << CCE << /*Constant*/ 1
6621 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6622 // If this is an SFINAE Context, treat the result as invalid so it stops
6623 // substitution at this point, respecting C++26 [temp.deduct.general]p7.
6624 // FIXME: Should do this whenever the above diagnostic is an error, but
6625 // without further changes this would degrade some other diagnostics.
6626 if (S.isSFINAEContext())
6627 return ExprError();
6628 break;
6629
6631 // Implicit conversion to a narrower type, but the expression is
6632 // value-dependent so we can't tell whether it's actually narrowing.
6633 // For matching the parameters of a TTP, the conversion is ill-formed
6634 // if it may narrow.
6635 if (CCE != CCEKind::TempArgStrict)
6636 break;
6637 [[fallthrough]];
6638 case NK_Type_Narrowing:
6639 // FIXME: It would be better to diagnose that the expression is not a
6640 // constant expression.
6641 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6642 << CCE << /*Constant*/ 0 << From->getType() << T;
6643 if (S.isSFINAEContext())
6644 return ExprError();
6645 break;
6646 }
6647 if (!ReturnPreNarrowingValue)
6648 PreNarrowingValue = {};
6649
6650 return Result;
6651}
6652
6653/// CheckConvertedConstantExpression - Check that the expression From is a
6654/// converted constant expression of type T, perform the conversion and produce
6655/// the converted expression, per C++11 [expr.const]p3.
6658 CCEKind CCE, bool RequireInt,
6659 NamedDecl *Dest) {
6660
6661 APValue PreNarrowingValue;
6662 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6663 PreNarrowingValue);
6664 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6665 Value = APValue();
6666 return Result;
6667 }
6668 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6669 RequireInt, PreNarrowingValue);
6670}
6671
6673 CCEKind CCE,
6674 NamedDecl *Dest) {
6675 APValue PreNarrowingValue;
6676 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6677 PreNarrowingValue);
6678}
6679
6681 APValue &Value, CCEKind CCE,
6682 NamedDecl *Dest) {
6683 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6684 Dest);
6685}
6686
6688 llvm::APSInt &Value,
6689 CCEKind CCE) {
6690 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6691
6692 APValue V;
6693 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6694 /*Dest=*/nullptr);
6695 if (!R.isInvalid() && !R.get()->isValueDependent())
6696 Value = V.getInt();
6697 return R;
6698}
6699
6702 CCEKind CCE, bool RequireInt,
6703 const APValue &PreNarrowingValue) {
6704
6705 ExprResult Result = E;
6706 // Check the expression is a constant expression.
6708 Expr::EvalResult Eval;
6709 Eval.Diag = &Notes;
6710
6711 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6712
6713 ConstantExprKind Kind;
6714 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6715 Kind = ConstantExprKind::ClassTemplateArgument;
6716 else if (CCE == CCEKind::TemplateArg)
6717 Kind = ConstantExprKind::NonClassTemplateArgument;
6718 else
6719 Kind = ConstantExprKind::Normal;
6720
6721 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6722 (RequireInt && !Eval.Val.isInt())) {
6723 // The expression can't be folded, so we can't keep it at this position in
6724 // the AST.
6725 Result = ExprError();
6726 } else {
6727 Value = Eval.Val;
6728
6729 if (Notes.empty()) {
6730 // It's a constant expression.
6731 Expr *E = Result.get();
6732 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6733 // We expect a ConstantExpr to have a value associated with it
6734 // by this point.
6735 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6736 "ConstantExpr has no value associated with it");
6737 (void)CE;
6738 } else {
6740 }
6741 if (!PreNarrowingValue.isAbsent())
6742 Value = std::move(PreNarrowingValue);
6743 return E;
6744 }
6745 }
6746
6747 // It's not a constant expression. Produce an appropriate diagnostic.
6748 if (Notes.size() == 1 &&
6749 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6750 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6751 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6752 diag::note_constexpr_invalid_template_arg) {
6753 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6754 for (unsigned I = 0; I < Notes.size(); ++I)
6755 Diag(Notes[I].first, Notes[I].second);
6756 } else {
6757 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6758 << CCE << E->getSourceRange();
6759 for (unsigned I = 0; I < Notes.size(); ++I)
6760 Diag(Notes[I].first, Notes[I].second);
6761 }
6762 return ExprError();
6763}
6764
6765/// dropPointerConversions - If the given standard conversion sequence
6766/// involves any pointer conversions, remove them. This may change
6767/// the result type of the conversion sequence.
6769 if (SCS.Second == ICK_Pointer_Conversion) {
6770 SCS.Second = ICK_Identity;
6771 SCS.Dimension = ICK_Identity;
6772 SCS.Third = ICK_Identity;
6773 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6774 }
6775}
6776
6777/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6778/// convert the expression From to an Objective-C pointer type.
6779static ImplicitConversionSequence
6781 // Do an implicit conversion to 'id'.
6784 = TryImplicitConversion(S, From, Ty,
6785 // FIXME: Are these flags correct?
6786 /*SuppressUserConversions=*/false,
6787 AllowedExplicit::Conversions,
6788 /*InOverloadResolution=*/false,
6789 /*CStyle=*/false,
6790 /*AllowObjCWritebackConversion=*/false,
6791 /*AllowObjCConversionOnExplicit=*/true);
6792
6793 // Strip off any final conversions to 'id'.
6794 switch (ICS.getKind()) {
6799 break;
6800
6803 break;
6804
6807 break;
6808 }
6809
6810 return ICS;
6811}
6812
6814 if (checkPlaceholderForOverload(*this, From))
6815 return ExprError();
6816
6817 QualType Ty = Context.getObjCIdType();
6820 if (!ICS.isBad())
6821 return PerformImplicitConversion(From, Ty, ICS,
6823 return ExprResult();
6824}
6825
6826static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6827 const Expr *Base = nullptr;
6828 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6829 "expected a member expression");
6830
6831 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6832 M && !M->isImplicitAccess())
6833 Base = M->getBase();
6834 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6835 M && !M->isImplicitAccess())
6836 Base = M->getBase();
6837
6838 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6839
6840 if (T->isPointerType())
6841 T = T->getPointeeType();
6842
6843 return T;
6844}
6845
6847 const FunctionDecl *Fun) {
6848 QualType ObjType = Obj->getType();
6849 if (ObjType->isPointerType()) {
6850 ObjType = ObjType->getPointeeType();
6851 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6853 /*CanOverflow=*/false, FPOptionsOverride());
6854 }
6855 return Obj;
6856}
6857
6865
6867 Expr *Object, MultiExprArg &Args,
6868 SmallVectorImpl<Expr *> &NewArgs) {
6869 assert(Method->isExplicitObjectMemberFunction() &&
6870 "Method is not an explicit member function");
6871 assert(NewArgs.empty() && "NewArgs should be empty");
6872
6873 NewArgs.reserve(Args.size() + 1);
6874 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6875 NewArgs.push_back(This);
6876 NewArgs.append(Args.begin(), Args.end());
6877 Args = NewArgs;
6879 Method, Object->getBeginLoc());
6880}
6881
6882/// Determine whether the provided type is an integral type, or an enumeration
6883/// type of a permitted flavor.
6885 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6886 : T->isIntegralOrUnscopedEnumerationType();
6887}
6888
6889static ExprResult
6892 QualType T, UnresolvedSetImpl &ViableConversions) {
6893
6894 if (Converter.Suppress)
6895 return ExprError();
6896
6897 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6898 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6899 CXXConversionDecl *Conv =
6900 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6902 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6903 }
6904 return From;
6905}
6906
6907static bool
6910 QualType T, bool HadMultipleCandidates,
6911 UnresolvedSetImpl &ExplicitConversions) {
6912 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6913 DeclAccessPair Found = ExplicitConversions[0];
6914 CXXConversionDecl *Conversion =
6915 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6916
6917 // The user probably meant to invoke the given explicit
6918 // conversion; use it.
6919 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6920 std::string TypeStr;
6921 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6922
6923 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6925 "static_cast<" + TypeStr + ">(")
6927 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6928 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6929
6930 // If we aren't in a SFINAE context, build a call to the
6931 // explicit conversion function.
6932 if (SemaRef.isSFINAEContext())
6933 return true;
6934
6935 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6936 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6937 HadMultipleCandidates);
6938 if (Result.isInvalid())
6939 return true;
6940
6941 // Replace the conversion with a RecoveryExpr, so we don't try to
6942 // instantiate it later, but can further diagnose here.
6943 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6944 From, Result.get()->getType());
6945 if (Result.isInvalid())
6946 return true;
6947 From = Result.get();
6948 }
6949 return false;
6950}
6951
6952static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6954 QualType T, bool HadMultipleCandidates,
6956 CXXConversionDecl *Conversion =
6957 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6958 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6959
6960 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6961 if (!Converter.SuppressConversion) {
6962 if (SemaRef.isSFINAEContext())
6963 return true;
6964
6965 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6966 << From->getSourceRange();
6967 }
6968
6969 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6970 HadMultipleCandidates);
6971 if (Result.isInvalid())
6972 return true;
6973 // Record usage of conversion in an implicit cast.
6974 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6975 CK_UserDefinedConversion, Result.get(),
6976 nullptr, Result.get()->getValueKind(),
6977 SemaRef.CurFPFeatureOverrides());
6978 return false;
6979}
6980
6982 Sema &SemaRef, SourceLocation Loc, Expr *From,
6984 if (!Converter.match(From->getType()) && !Converter.Suppress)
6985 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6986 << From->getSourceRange();
6987
6988 return SemaRef.DefaultLvalueConversion(From);
6989}
6990
6991static void
6993 UnresolvedSetImpl &ViableConversions,
6994 OverloadCandidateSet &CandidateSet) {
6995 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6996 NamedDecl *D = FoundDecl.getDecl();
6997 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6998 if (isa<UsingShadowDecl>(D))
6999 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7000
7001 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
7003 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
7004 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7005 continue;
7006 }
7008 SemaRef.AddConversionCandidate(
7009 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
7010 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
7011 }
7012}
7013
7014/// Attempt to convert the given expression to a type which is accepted
7015/// by the given converter.
7016///
7017/// This routine will attempt to convert an expression of class type to a
7018/// type accepted by the specified converter. In C++11 and before, the class
7019/// must have a single non-explicit conversion function converting to a matching
7020/// type. In C++1y, there can be multiple such conversion functions, but only
7021/// one target type.
7022///
7023/// \param Loc The source location of the construct that requires the
7024/// conversion.
7025///
7026/// \param From The expression we're converting from.
7027///
7028/// \param Converter Used to control and diagnose the conversion process.
7029///
7030/// \returns The expression, converted to an integral or enumeration type if
7031/// successful.
7033 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
7034 // We can't perform any more checking for type-dependent expressions.
7035 if (From->isTypeDependent())
7036 return From;
7037
7038 // Process placeholders immediately.
7039 if (From->hasPlaceholderType()) {
7040 ExprResult result = CheckPlaceholderExpr(From);
7041 if (result.isInvalid())
7042 return result;
7043 From = result.get();
7044 }
7045
7046 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
7047 ExprResult Converted = DefaultLvalueConversion(From);
7048 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
7049 From = Converted.isUsable() ? Converted.get() : nullptr;
7050 // If the expression already has a matching type, we're golden.
7051 if (Converter.match(T))
7052 return Converted;
7053
7054 // FIXME: Check for missing '()' if T is a function type?
7055
7056 // We can only perform contextual implicit conversions on objects of class
7057 // type.
7058 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
7059 if (!RecordTy || !getLangOpts().CPlusPlus) {
7060 if (!Converter.Suppress)
7061 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
7062 return From;
7063 }
7064
7065 // We must have a complete class type.
7066 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
7067 ContextualImplicitConverter &Converter;
7068 Expr *From;
7069
7070 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
7071 : Converter(Converter), From(From) {}
7072
7073 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
7074 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
7075 }
7076 } IncompleteDiagnoser(Converter, From);
7077
7078 if (Converter.Suppress ? !isCompleteType(Loc, T)
7079 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
7080 return From;
7081
7082 // Look for a conversion to an integral or enumeration type.
7084 ViableConversions; // These are *potentially* viable in C++1y.
7085 UnresolvedSet<4> ExplicitConversions;
7086 const auto &Conversions = cast<CXXRecordDecl>(RecordTy->getDecl())
7087 ->getDefinitionOrSelf()
7088 ->getVisibleConversionFunctions();
7089
7090 bool HadMultipleCandidates =
7091 (std::distance(Conversions.begin(), Conversions.end()) > 1);
7092
7093 // To check that there is only one target type, in C++1y:
7094 QualType ToType;
7095 bool HasUniqueTargetType = true;
7096
7097 // Collect explicit or viable (potentially in C++1y) conversions.
7098 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
7099 NamedDecl *D = (*I)->getUnderlyingDecl();
7100 CXXConversionDecl *Conversion;
7101 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
7102 if (ConvTemplate) {
7104 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
7105 else
7106 continue; // C++11 does not consider conversion operator templates(?).
7107 } else
7108 Conversion = cast<CXXConversionDecl>(D);
7109
7110 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
7111 "Conversion operator templates are considered potentially "
7112 "viable in C++1y");
7113
7114 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
7115 if (Converter.match(CurToType) || ConvTemplate) {
7116
7117 if (Conversion->isExplicit()) {
7118 // FIXME: For C++1y, do we need this restriction?
7119 // cf. diagnoseNoViableConversion()
7120 if (!ConvTemplate)
7121 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
7122 } else {
7123 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
7124 if (ToType.isNull())
7125 ToType = CurToType.getUnqualifiedType();
7126 else if (HasUniqueTargetType &&
7127 (CurToType.getUnqualifiedType() != ToType))
7128 HasUniqueTargetType = false;
7129 }
7130 ViableConversions.addDecl(I.getDecl(), I.getAccess());
7131 }
7132 }
7133 }
7134
7135 if (getLangOpts().CPlusPlus14) {
7136 // C++1y [conv]p6:
7137 // ... An expression e of class type E appearing in such a context
7138 // is said to be contextually implicitly converted to a specified
7139 // type T and is well-formed if and only if e can be implicitly
7140 // converted to a type T that is determined as follows: E is searched
7141 // for conversion functions whose return type is cv T or reference to
7142 // cv T such that T is allowed by the context. There shall be
7143 // exactly one such T.
7144
7145 // If no unique T is found:
7146 if (ToType.isNull()) {
7147 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7148 HadMultipleCandidates,
7149 ExplicitConversions))
7150 return ExprError();
7151 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7152 }
7153
7154 // If more than one unique Ts are found:
7155 if (!HasUniqueTargetType)
7156 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7157 ViableConversions);
7158
7159 // If one unique T is found:
7160 // First, build a candidate set from the previously recorded
7161 // potentially viable conversions.
7163 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
7164 CandidateSet);
7165
7166 // Then, perform overload resolution over the candidate set.
7168 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
7169 case OR_Success: {
7170 // Apply this conversion.
7172 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
7173 if (recordConversion(*this, Loc, From, Converter, T,
7174 HadMultipleCandidates, Found))
7175 return ExprError();
7176 break;
7177 }
7178 case OR_Ambiguous:
7179 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7180 ViableConversions);
7182 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7183 HadMultipleCandidates,
7184 ExplicitConversions))
7185 return ExprError();
7186 [[fallthrough]];
7187 case OR_Deleted:
7188 // We'll complain below about a non-integral condition type.
7189 break;
7190 }
7191 } else {
7192 switch (ViableConversions.size()) {
7193 case 0: {
7194 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
7195 HadMultipleCandidates,
7196 ExplicitConversions))
7197 return ExprError();
7198
7199 // We'll complain below about a non-integral condition type.
7200 break;
7201 }
7202 case 1: {
7203 // Apply this conversion.
7204 DeclAccessPair Found = ViableConversions[0];
7205 if (recordConversion(*this, Loc, From, Converter, T,
7206 HadMultipleCandidates, Found))
7207 return ExprError();
7208 break;
7209 }
7210 default:
7211 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
7212 ViableConversions);
7213 }
7214 }
7215
7216 return finishContextualImplicitConversion(*this, Loc, From, Converter);
7217}
7218
7219/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
7220/// an acceptable non-member overloaded operator for a call whose
7221/// arguments have types T1 (and, if non-empty, T2). This routine
7222/// implements the check in C++ [over.match.oper]p3b2 concerning
7223/// enumeration types.
7225 FunctionDecl *Fn,
7226 ArrayRef<Expr *> Args) {
7227 QualType T1 = Args[0]->getType();
7228 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
7229
7230 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
7231 return true;
7232
7233 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
7234 return true;
7235
7236 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
7237 if (Proto->getNumParams() < 1)
7238 return false;
7239
7240 if (T1->isEnumeralType()) {
7241 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
7242 if (Context.hasSameUnqualifiedType(T1, ArgType))
7243 return true;
7244 }
7245
7246 if (Proto->getNumParams() < 2)
7247 return false;
7248
7249 if (!T2.isNull() && T2->isEnumeralType()) {
7250 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
7251 if (Context.hasSameUnqualifiedType(T2, ArgType))
7252 return true;
7253 }
7254
7255 return false;
7256}
7257
7260 return false;
7261
7262 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7263 return FD->isTargetMultiVersion();
7264
7265 if (!FD->isMultiVersion())
7266 return false;
7267
7268 // Among multiple target versions consider either the default,
7269 // or the first non-default in the absence of default version.
7270 unsigned SeenAt = 0;
7271 unsigned I = 0;
7272 bool HasDefault = false;
7274 FD, [&](const FunctionDecl *CurFD) {
7275 if (FD == CurFD)
7276 SeenAt = I;
7277 else if (CurFD->isTargetMultiVersionDefault())
7278 HasDefault = true;
7279 ++I;
7280 });
7281 return HasDefault || SeenAt != 0;
7282}
7283
7286 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7287 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7288 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7289 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7290 bool StrictPackMatch) {
7291 const FunctionProtoType *Proto
7292 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
7293 assert(Proto && "Functions without a prototype cannot be overloaded");
7294 assert(!Function->getDescribedFunctionTemplate() &&
7295 "Use AddTemplateOverloadCandidate for function templates");
7296
7297 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
7299 // If we get here, it's because we're calling a member function
7300 // that is named without a member access expression (e.g.,
7301 // "this->f") that was either written explicitly or created
7302 // implicitly. This can happen with a qualified call to a member
7303 // function, e.g., X::f(). We use an empty type for the implied
7304 // object argument (C++ [over.call.func]p3), and the acting context
7305 // is irrelevant.
7306 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
7308 CandidateSet, SuppressUserConversions,
7309 PartialOverloading, EarlyConversions, PO,
7310 StrictPackMatch);
7311 return;
7312 }
7313 // We treat a constructor like a non-member function, since its object
7314 // argument doesn't participate in overload resolution.
7315 }
7316
7317 if (!CandidateSet.isNewCandidate(Function, PO))
7318 return;
7319
7320 // C++11 [class.copy]p11: [DR1402]
7321 // A defaulted move constructor that is defined as deleted is ignored by
7322 // overload resolution.
7323 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
7324 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7325 Constructor->isMoveConstructor())
7326 return;
7327
7328 // Overload resolution is always an unevaluated context.
7331
7332 // C++ [over.match.oper]p3:
7333 // if no operand has a class type, only those non-member functions in the
7334 // lookup set that have a first parameter of type T1 or "reference to
7335 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7336 // is a right operand) a second parameter of type T2 or "reference to
7337 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7338 // candidate functions.
7339 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7341 return;
7342
7343 // Add this candidate
7344 OverloadCandidate &Candidate =
7345 CandidateSet.addCandidate(Args.size(), EarlyConversions);
7346 Candidate.FoundDecl = FoundDecl;
7347 Candidate.Function = Function;
7348 Candidate.Viable = true;
7349 Candidate.RewriteKind =
7350 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
7351 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
7352 Candidate.ExplicitCallArguments = Args.size();
7353 Candidate.StrictPackMatch = StrictPackMatch;
7354
7355 // Explicit functions are not actually candidates at all if we're not
7356 // allowing them in this context, but keep them around so we can point
7357 // to them in diagnostics.
7358 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7359 Candidate.Viable = false;
7360 Candidate.FailureKind = ovl_fail_explicit;
7361 return;
7362 }
7363
7364 // Functions with internal linkage are only viable in the same module unit.
7365 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7366 /// FIXME: Currently, the semantics of linkage in clang is slightly
7367 /// different from the semantics in C++ spec. In C++ spec, only names
7368 /// have linkage. So that all entities of the same should share one
7369 /// linkage. But in clang, different entities of the same could have
7370 /// different linkage.
7371 const NamedDecl *ND = Function;
7372 bool IsImplicitlyInstantiated = false;
7373 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7374 ND = SpecInfo->getTemplate();
7375 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7377 }
7378
7379 /// Don't remove inline functions with internal linkage from the overload
7380 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7381 /// However:
7382 /// - Inline functions with internal linkage are a common pattern in
7383 /// headers to avoid ODR issues.
7384 /// - The global module is meant to be a transition mechanism for C and C++
7385 /// headers, and the current rules as written work against that goal.
7386 const bool IsInlineFunctionInGMF =
7387 Function->isFromGlobalModule() &&
7388 (IsImplicitlyInstantiated || Function->isInlined());
7389
7390 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7391 Candidate.Viable = false;
7393 return;
7394 }
7395 }
7396
7398 Candidate.Viable = false;
7400 return;
7401 }
7402
7403 if (Constructor) {
7404 // C++ [class.copy]p3:
7405 // A member function template is never instantiated to perform the copy
7406 // of a class object to an object of its class type.
7407 CanQualType ClassType =
7408 Context.getCanonicalTagType(Constructor->getParent());
7409 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7410 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7411 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7412 ClassType))) {
7413 Candidate.Viable = false;
7415 return;
7416 }
7417
7418 // C++ [over.match.funcs]p8: (proposed DR resolution)
7419 // A constructor inherited from class type C that has a first parameter
7420 // of type "reference to P" (including such a constructor instantiated
7421 // from a template) is excluded from the set of candidate functions when
7422 // constructing an object of type cv D if the argument list has exactly
7423 // one argument and D is reference-related to P and P is reference-related
7424 // to C.
7425 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7426 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7427 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7428 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7429 CanQualType C = Context.getCanonicalTagType(Constructor->getParent());
7430 CanQualType D = Context.getCanonicalTagType(Shadow->getParent());
7431 SourceLocation Loc = Args.front()->getExprLoc();
7432 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7433 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7434 Candidate.Viable = false;
7436 return;
7437 }
7438 }
7439
7440 // Check that the constructor is capable of constructing an object in the
7441 // destination address space.
7443 Constructor->getMethodQualifiers().getAddressSpace(),
7444 CandidateSet.getDestAS(), getASTContext())) {
7445 Candidate.Viable = false;
7447 }
7448 }
7449
7450 unsigned NumParams = Proto->getNumParams();
7451
7452 // (C++ 13.3.2p2): A candidate function having fewer than m
7453 // parameters is viable only if it has an ellipsis in its parameter
7454 // list (8.3.5).
7455 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7456 !Proto->isVariadic() &&
7457 shouldEnforceArgLimit(PartialOverloading, Function)) {
7458 Candidate.Viable = false;
7460 return;
7461 }
7462
7463 // (C++ 13.3.2p2): A candidate function having more than m parameters
7464 // is viable only if the (m+1)st parameter has a default argument
7465 // (8.3.6). For the purposes of overload resolution, the
7466 // parameter list is truncated on the right, so that there are
7467 // exactly m parameters.
7468 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7469 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7470 !PartialOverloading) {
7471 // Not enough arguments.
7472 Candidate.Viable = false;
7474 return;
7475 }
7476
7477 // (CUDA B.1): Check for invalid calls between targets.
7478 if (getLangOpts().CUDA) {
7479 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7480 // Skip the check for callers that are implicit members, because in this
7481 // case we may not yet know what the member's target is; the target is
7482 // inferred for the member automatically, based on the bases and fields of
7483 // the class.
7484 if (!(Caller && Caller->isImplicit()) &&
7485 !CUDA().IsAllowedCall(Caller, Function)) {
7486 Candidate.Viable = false;
7487 Candidate.FailureKind = ovl_fail_bad_target;
7488 return;
7489 }
7490 }
7491
7492 if (Function->getTrailingRequiresClause()) {
7493 ConstraintSatisfaction Satisfaction;
7494 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7495 /*ForOverloadResolution*/ true) ||
7496 !Satisfaction.IsSatisfied) {
7497 Candidate.Viable = false;
7499 return;
7500 }
7501 }
7502
7503 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7504 // Determine the implicit conversion sequences for each of the
7505 // arguments.
7506 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7507 unsigned ConvIdx =
7508 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7509 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7510 // We already formed a conversion sequence for this parameter during
7511 // template argument deduction.
7512 } else if (ArgIdx < NumParams) {
7513 // (C++ 13.3.2p3): for F to be a viable function, there shall
7514 // exist for each argument an implicit conversion sequence
7515 // (13.3.3.1) that converts that argument to the corresponding
7516 // parameter of F.
7517 QualType ParamType = Proto->getParamType(ArgIdx);
7518 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7519 if (ParamABI == ParameterABI::HLSLOut ||
7520 ParamABI == ParameterABI::HLSLInOut) {
7521 ParamType = ParamType.getNonReferenceType();
7522 if (ParamABI == ParameterABI::HLSLInOut &&
7523 Args[ArgIdx]->getType().getAddressSpace() ==
7525 Diag(Args[ArgIdx]->getBeginLoc(), diag::warn_hlsl_groupshared_inout);
7526 }
7527 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7528 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7529 /*InOverloadResolution=*/true,
7530 /*AllowObjCWritebackConversion=*/
7531 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7532 if (Candidate.Conversions[ConvIdx].isBad()) {
7533 Candidate.Viable = false;
7535 return;
7536 }
7537 } else {
7538 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7539 // argument for which there is no corresponding parameter is
7540 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7541 Candidate.Conversions[ConvIdx].setEllipsis();
7542 }
7543 }
7544
7545 if (EnableIfAttr *FailedAttr =
7546 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7547 Candidate.Viable = false;
7548 Candidate.FailureKind = ovl_fail_enable_if;
7549 Candidate.DeductionFailure.Data = FailedAttr;
7550 return;
7551 }
7552}
7553
7557 if (Methods.size() <= 1)
7558 return nullptr;
7559
7560 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7561 bool Match = true;
7562 ObjCMethodDecl *Method = Methods[b];
7563 unsigned NumNamedArgs = Sel.getNumArgs();
7564 // Method might have more arguments than selector indicates. This is due
7565 // to addition of c-style arguments in method.
7566 if (Method->param_size() > NumNamedArgs)
7567 NumNamedArgs = Method->param_size();
7568 if (Args.size() < NumNamedArgs)
7569 continue;
7570
7571 for (unsigned i = 0; i < NumNamedArgs; i++) {
7572 // We can't do any type-checking on a type-dependent argument.
7573 if (Args[i]->isTypeDependent()) {
7574 Match = false;
7575 break;
7576 }
7577
7578 ParmVarDecl *param = Method->parameters()[i];
7579 Expr *argExpr = Args[i];
7580 assert(argExpr && "SelectBestMethod(): missing expression");
7581
7582 // Strip the unbridged-cast placeholder expression off unless it's
7583 // a consumed argument.
7584 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7585 !param->hasAttr<CFConsumedAttr>())
7586 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7587
7588 // If the parameter is __unknown_anytype, move on to the next method.
7589 if (param->getType() == Context.UnknownAnyTy) {
7590 Match = false;
7591 break;
7592 }
7593
7594 ImplicitConversionSequence ConversionState
7595 = TryCopyInitialization(*this, argExpr, param->getType(),
7596 /*SuppressUserConversions*/false,
7597 /*InOverloadResolution=*/true,
7598 /*AllowObjCWritebackConversion=*/
7599 getLangOpts().ObjCAutoRefCount,
7600 /*AllowExplicit*/false);
7601 // This function looks for a reasonably-exact match, so we consider
7602 // incompatible pointer conversions to be a failure here.
7603 if (ConversionState.isBad() ||
7604 (ConversionState.isStandard() &&
7605 ConversionState.Standard.Second ==
7607 Match = false;
7608 break;
7609 }
7610 }
7611 // Promote additional arguments to variadic methods.
7612 if (Match && Method->isVariadic()) {
7613 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7614 if (Args[i]->isTypeDependent()) {
7615 Match = false;
7616 break;
7617 }
7619 Args[i], VariadicCallType::Method, nullptr);
7620 if (Arg.isInvalid()) {
7621 Match = false;
7622 break;
7623 }
7624 }
7625 } else {
7626 // Check for extra arguments to non-variadic methods.
7627 if (Args.size() != NumNamedArgs)
7628 Match = false;
7629 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7630 // Special case when selectors have no argument. In this case, select
7631 // one with the most general result type of 'id'.
7632 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7633 QualType ReturnT = Methods[b]->getReturnType();
7634 if (ReturnT->isObjCIdType())
7635 return Methods[b];
7636 }
7637 }
7638 }
7639
7640 if (Match)
7641 return Method;
7642 }
7643 return nullptr;
7644}
7645
7647 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7648 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7649 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7650 if (ThisArg) {
7651 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7652 assert(!isa<CXXConstructorDecl>(Method) &&
7653 "Shouldn't have `this` for ctors!");
7654 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7656 ThisArg, /*Qualifier=*/std::nullopt, Method, Method);
7657 if (R.isInvalid())
7658 return false;
7659 ConvertedThis = R.get();
7660 } else {
7661 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7662 (void)MD;
7663 assert((MissingImplicitThis || MD->isStatic() ||
7665 "Expected `this` for non-ctor instance methods");
7666 }
7667 ConvertedThis = nullptr;
7668 }
7669
7670 // Ignore any variadic arguments. Converting them is pointless, since the
7671 // user can't refer to them in the function condition.
7672 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7673
7674 // Convert the arguments.
7675 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7676 ExprResult R;
7678 S.Context, Function->getParamDecl(I)),
7679 SourceLocation(), Args[I]);
7680
7681 if (R.isInvalid())
7682 return false;
7683
7684 ConvertedArgs.push_back(R.get());
7685 }
7686
7687 if (Trap.hasErrorOccurred())
7688 return false;
7689
7690 // Push default arguments if needed.
7691 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7692 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7693 ParmVarDecl *P = Function->getParamDecl(i);
7694 if (!P->hasDefaultArg())
7695 return false;
7696 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7697 if (R.isInvalid())
7698 return false;
7699 ConvertedArgs.push_back(R.get());
7700 }
7701
7702 if (Trap.hasErrorOccurred())
7703 return false;
7704 }
7705 return true;
7706}
7707
7709 SourceLocation CallLoc,
7710 ArrayRef<Expr *> Args,
7711 bool MissingImplicitThis) {
7712 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7713 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7714 return nullptr;
7715
7716 SFINAETrap Trap(*this);
7717 // Perform the access checking immediately so any access diagnostics are
7718 // caught by the SFINAE trap.
7719 llvm::scope_exit UndelayDiags(
7720 [&, CurrentState(DelayedDiagnostics.pushUndelayed())] {
7721 DelayedDiagnostics.popUndelayed(CurrentState);
7722 });
7723 SmallVector<Expr *, 16> ConvertedArgs;
7724 // FIXME: We should look into making enable_if late-parsed.
7725 Expr *DiscardedThis;
7727 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7728 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7729 return *EnableIfAttrs.begin();
7730
7731 for (auto *EIA : EnableIfAttrs) {
7733 // FIXME: This doesn't consider value-dependent cases, because doing so is
7734 // very difficult. Ideally, we should handle them more gracefully.
7735 if (EIA->getCond()->isValueDependent() ||
7736 !EIA->getCond()->EvaluateWithSubstitution(
7737 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7738 return EIA;
7739
7740 if (!Result.isInt() || !Result.getInt().getBoolValue())
7741 return EIA;
7742 }
7743 return nullptr;
7744}
7745
7746template <typename CheckFn>
7748 bool ArgDependent, SourceLocation Loc,
7749 CheckFn &&IsSuccessful) {
7751 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7752 if (ArgDependent == DIA->getArgDependent())
7753 Attrs.push_back(DIA);
7754 }
7755
7756 // Common case: No diagnose_if attributes, so we can quit early.
7757 if (Attrs.empty())
7758 return false;
7759
7760 auto WarningBegin = std::stable_partition(
7761 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7762 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7763 DIA->getWarningGroup().empty();
7764 });
7765
7766 // Note that diagnose_if attributes are late-parsed, so they appear in the
7767 // correct order (unlike enable_if attributes).
7768 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7769 IsSuccessful);
7770 if (ErrAttr != WarningBegin) {
7771 const DiagnoseIfAttr *DIA = *ErrAttr;
7772 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7773 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7774 << DIA->getParent() << DIA->getCond()->getSourceRange();
7775 return true;
7776 }
7777
7778 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7779 switch (Sev) {
7780 case DiagnoseIfAttr::DS_warning:
7782 case DiagnoseIfAttr::DS_error:
7783 return diag::Severity::Error;
7784 }
7785 llvm_unreachable("Fully covered switch above!");
7786 };
7787
7788 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7789 if (IsSuccessful(DIA)) {
7790 if (DIA->getWarningGroup().empty() &&
7791 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7792 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7793 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7794 << DIA->getParent() << DIA->getCond()->getSourceRange();
7795 } else {
7796 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7797 DIA->getWarningGroup());
7798 assert(DiagGroup);
7799 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7800 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7801 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7802 S.Diag(Loc, DiagID) << DIA->getMessage();
7803 }
7804 }
7805
7806 return false;
7807}
7808
7810 const Expr *ThisArg,
7812 SourceLocation Loc) {
7814 *this, Function, /*ArgDependent=*/true, Loc,
7815 [&](const DiagnoseIfAttr *DIA) {
7817 // It's sane to use the same Args for any redecl of this function, since
7818 // EvaluateWithSubstitution only cares about the position of each
7819 // argument in the arg list, not the ParmVarDecl* it maps to.
7820 if (!DIA->getCond()->EvaluateWithSubstitution(
7821 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7822 return false;
7823 return Result.isInt() && Result.getInt().getBoolValue();
7824 });
7825}
7826
7828 SourceLocation Loc) {
7830 *this, ND, /*ArgDependent=*/false, Loc,
7831 [&](const DiagnoseIfAttr *DIA) {
7832 bool Result;
7833 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7834 Result;
7835 });
7836}
7837
7839 ArrayRef<Expr *> Args,
7840 OverloadCandidateSet &CandidateSet,
7841 TemplateArgumentListInfo *ExplicitTemplateArgs,
7842 bool SuppressUserConversions,
7843 bool PartialOverloading,
7844 bool FirstArgumentIsBase) {
7845 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7846 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7847 ArrayRef<Expr *> FunctionArgs = Args;
7848
7849 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7850 FunctionDecl *FD =
7851 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7852
7853 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7854 QualType ObjectType;
7855 Expr::Classification ObjectClassification;
7856 if (Args.size() > 0) {
7857 if (Expr *E = Args[0]) {
7858 // Use the explicit base to restrict the lookup:
7859 ObjectType = E->getType();
7860 // Pointers in the object arguments are implicitly dereferenced, so we
7861 // always classify them as l-values.
7862 if (!ObjectType.isNull() && ObjectType->isPointerType())
7863 ObjectClassification = Expr::Classification::makeSimpleLValue();
7864 else
7865 ObjectClassification = E->Classify(Context);
7866 } // .. else there is an implicit base.
7867 FunctionArgs = Args.slice(1);
7868 }
7869 if (FunTmpl) {
7871 FunTmpl, F.getPair(),
7873 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7874 FunctionArgs, CandidateSet, SuppressUserConversions,
7875 PartialOverloading);
7876 } else {
7877 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7878 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7879 ObjectClassification, FunctionArgs, CandidateSet,
7880 SuppressUserConversions, PartialOverloading);
7881 }
7882 } else {
7883 // This branch handles both standalone functions and static methods.
7884
7885 // Slice the first argument (which is the base) when we access
7886 // static method as non-static.
7887 if (Args.size() > 0 &&
7888 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7889 !isa<CXXConstructorDecl>(FD)))) {
7890 assert(cast<CXXMethodDecl>(FD)->isStatic());
7891 FunctionArgs = Args.slice(1);
7892 }
7893 if (FunTmpl) {
7894 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7895 ExplicitTemplateArgs, FunctionArgs,
7896 CandidateSet, SuppressUserConversions,
7897 PartialOverloading);
7898 } else {
7899 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7900 SuppressUserConversions, PartialOverloading);
7901 }
7902 }
7903 }
7904}
7905
7907 Expr::Classification ObjectClassification,
7908 ArrayRef<Expr *> Args,
7909 OverloadCandidateSet &CandidateSet,
7910 bool SuppressUserConversions,
7912 NamedDecl *Decl = FoundDecl.getDecl();
7914
7916 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7917
7918 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7919 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7920 "Expected a member function template");
7921 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7922 /*ExplicitArgs*/ nullptr, ObjectType,
7923 ObjectClassification, Args, CandidateSet,
7924 SuppressUserConversions, false, PO);
7925 } else {
7926 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7927 ObjectType, ObjectClassification, Args, CandidateSet,
7928 SuppressUserConversions, false, {}, PO);
7929 }
7930}
7931
7934 CXXRecordDecl *ActingContext, QualType ObjectType,
7935 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7936 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7937 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7938 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7939 const FunctionProtoType *Proto
7940 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7941 assert(Proto && "Methods without a prototype cannot be overloaded");
7943 "Use AddOverloadCandidate for constructors");
7944
7945 if (!CandidateSet.isNewCandidate(Method, PO))
7946 return;
7947
7948 // C++11 [class.copy]p23: [DR1402]
7949 // A defaulted move assignment operator that is defined as deleted is
7950 // ignored by overload resolution.
7951 if (Method->isDefaulted() && Method->isDeleted() &&
7952 Method->isMoveAssignmentOperator())
7953 return;
7954
7955 // Overload resolution is always an unevaluated context.
7958
7959 bool IgnoreExplicitObject =
7960 (Method->isExplicitObjectMemberFunction() &&
7961 CandidateSet.getKind() ==
7963 bool ImplicitObjectMethodTreatedAsStatic =
7964 CandidateSet.getKind() ==
7966 Method->isImplicitObjectMemberFunction();
7967
7968 unsigned ExplicitOffset =
7969 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7970
7971 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7972 int(ImplicitObjectMethodTreatedAsStatic);
7973
7974 unsigned ExtraArgs =
7976 ? 0
7977 : 1;
7978
7979 // Add this candidate
7980 OverloadCandidate &Candidate =
7981 CandidateSet.addCandidate(Args.size() + ExtraArgs, EarlyConversions);
7982 Candidate.FoundDecl = FoundDecl;
7983 Candidate.Function = Method;
7984 Candidate.RewriteKind =
7985 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7986 Candidate.TookAddressOfOverload =
7988 Candidate.ExplicitCallArguments = Args.size();
7989 Candidate.StrictPackMatch = StrictPackMatch;
7990
7991 // (C++ 13.3.2p2): A candidate function having fewer than m
7992 // parameters is viable only if it has an ellipsis in its parameter
7993 // list (8.3.5).
7994 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7995 !Proto->isVariadic() &&
7996 shouldEnforceArgLimit(PartialOverloading, Method)) {
7997 Candidate.Viable = false;
7999 return;
8000 }
8001
8002 // (C++ 13.3.2p2): A candidate function having more than m parameters
8003 // is viable only if the (m+1)st parameter has a default argument
8004 // (8.3.6). For the purposes of overload resolution, the
8005 // parameter list is truncated on the right, so that there are
8006 // exactly m parameters.
8007 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
8008 ExplicitOffset +
8009 int(ImplicitObjectMethodTreatedAsStatic);
8010
8011 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
8012 // Not enough arguments.
8013 Candidate.Viable = false;
8015 return;
8016 }
8017
8018 Candidate.Viable = true;
8019
8020 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8021 if (!IgnoreExplicitObject) {
8022 if (ObjectType.isNull())
8023 Candidate.IgnoreObjectArgument = true;
8024 else if (Method->isStatic()) {
8025 // [over.best.ics.general]p8
8026 // When the parameter is the implicit object parameter of a static member
8027 // function, the implicit conversion sequence is a standard conversion
8028 // sequence that is neither better nor worse than any other standard
8029 // conversion sequence.
8030 //
8031 // This is a rule that was introduced in C++23 to support static lambdas.
8032 // We apply it retroactively because we want to support static lambdas as
8033 // an extension and it doesn't hurt previous code.
8034 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
8035 } else {
8036 // Determine the implicit conversion sequence for the object
8037 // parameter.
8038 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
8039 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8040 Method, ActingContext, /*InOverloadResolution=*/true);
8041 if (Candidate.Conversions[FirstConvIdx].isBad()) {
8042 Candidate.Viable = false;
8044 return;
8045 }
8046 }
8047 }
8048
8049 // (CUDA B.1): Check for invalid calls between targets.
8050 if (getLangOpts().CUDA)
8051 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
8052 Method)) {
8053 Candidate.Viable = false;
8054 Candidate.FailureKind = ovl_fail_bad_target;
8055 return;
8056 }
8057
8058 if (Method->getTrailingRequiresClause()) {
8059 ConstraintSatisfaction Satisfaction;
8060 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
8061 /*ForOverloadResolution*/ true) ||
8062 !Satisfaction.IsSatisfied) {
8063 Candidate.Viable = false;
8065 return;
8066 }
8067 }
8068
8069 // Determine the implicit conversion sequences for each of the
8070 // arguments.
8071 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
8072 unsigned ConvIdx =
8073 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
8074 if (Candidate.Conversions[ConvIdx].isInitialized()) {
8075 // We already formed a conversion sequence for this parameter during
8076 // template argument deduction.
8077 } else if (ArgIdx < NumParams) {
8078 // (C++ 13.3.2p3): for F to be a viable function, there shall
8079 // exist for each argument an implicit conversion sequence
8080 // (13.3.3.1) that converts that argument to the corresponding
8081 // parameter of F.
8082 QualType ParamType;
8083 if (ImplicitObjectMethodTreatedAsStatic) {
8084 ParamType = ArgIdx == 0
8085 ? Method->getFunctionObjectParameterReferenceType()
8086 : Proto->getParamType(ArgIdx - 1);
8087 } else {
8088 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
8089 }
8090 Candidate.Conversions[ConvIdx]
8091 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8092 SuppressUserConversions,
8093 /*InOverloadResolution=*/true,
8094 /*AllowObjCWritebackConversion=*/
8095 getLangOpts().ObjCAutoRefCount);
8096 if (Candidate.Conversions[ConvIdx].isBad()) {
8097 Candidate.Viable = false;
8099 return;
8100 }
8101 } else {
8102 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8103 // argument for which there is no corresponding parameter is
8104 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
8105 Candidate.Conversions[ConvIdx].setEllipsis();
8106 }
8107 }
8108
8109 if (EnableIfAttr *FailedAttr =
8110 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
8111 Candidate.Viable = false;
8112 Candidate.FailureKind = ovl_fail_enable_if;
8113 Candidate.DeductionFailure.Data = FailedAttr;
8114 return;
8115 }
8116
8118 Candidate.Viable = false;
8120 }
8121}
8122
8124 Sema &S, OverloadCandidateSet &CandidateSet,
8125 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8126 CXXRecordDecl *ActingContext,
8127 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8128 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8129 bool SuppressUserConversions, bool PartialOverloading,
8131
8132 // C++ [over.match.funcs]p7:
8133 // In each case where a candidate is a function template, candidate
8134 // function template specializations are generated using template argument
8135 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8136 // candidate functions in the usual way.113) A given name can refer to one
8137 // or more function templates and also to a set of overloaded non-template
8138 // functions. In such a case, the candidate functions generated from each
8139 // function template are combined with the set of non-template candidate
8140 // functions.
8141 TemplateDeductionInfo Info(CandidateSet.getLocation());
8142 auto *Method = cast<CXXMethodDecl>(MethodTmpl->getTemplatedDecl());
8143 FunctionDecl *Specialization = nullptr;
8144 ConversionSequenceList Conversions;
8146 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
8147 PartialOverloading, /*AggregateDeductionCandidate=*/false,
8148 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
8149 CandidateSet.getKind() ==
8151 [&](ArrayRef<QualType> ParamTypes,
8152 bool OnlyInitializeNonUserDefinedConversions) {
8153 return S.CheckNonDependentConversions(
8154 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
8155 Sema::CheckNonDependentConversionsFlag(
8156 SuppressUserConversions,
8157 OnlyInitializeNonUserDefinedConversions),
8158 ActingContext, ObjectType, ObjectClassification, PO);
8159 });
8161 OverloadCandidate &Candidate =
8162 CandidateSet.addCandidate(Conversions.size(), Conversions);
8163 Candidate.FoundDecl = FoundDecl;
8164 Candidate.Function = Method;
8165 Candidate.Viable = false;
8166 Candidate.RewriteKind =
8167 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8168 Candidate.IsSurrogate = false;
8169 Candidate.TookAddressOfOverload =
8170 CandidateSet.getKind() ==
8172
8173 Candidate.IgnoreObjectArgument =
8174 Method->isStatic() ||
8175 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
8176 Candidate.ExplicitCallArguments = Args.size();
8179 else {
8181 Candidate.DeductionFailure =
8183 }
8184 return;
8185 }
8186
8187 // Add the function template specialization produced by template argument
8188 // deduction as a candidate.
8189 assert(Specialization && "Missing member function template specialization?");
8191 "Specialization is not a member function?");
8193 cast<CXXMethodDecl>(Specialization), FoundDecl, ActingContext, ObjectType,
8194 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
8195 PartialOverloading, Conversions, PO, Info.hasStrictPackMatch());
8196}
8197
8199 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
8200 CXXRecordDecl *ActingContext,
8201 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
8202 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
8203 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8204 bool PartialOverloading, OverloadCandidateParamOrder PO) {
8205 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
8206 return;
8207
8208 if (ExplicitTemplateArgs ||
8209 !CandidateSet.shouldDeferTemplateArgumentDeduction(*this)) {
8211 *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
8212 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
8213 SuppressUserConversions, PartialOverloading, PO);
8214 return;
8215 }
8216
8218 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
8219 Args, SuppressUserConversions, PartialOverloading, PO);
8220}
8221
8222/// Determine whether a given function template has a simple explicit specifier
8223/// or a non-value-dependent explicit-specification that evaluates to true.
8227
8232
8234 Sema &S, OverloadCandidateSet &CandidateSet,
8236 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8237 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
8239 bool AggregateCandidateDeduction) {
8240
8241 // If the function template has a non-dependent explicit specification,
8242 // exclude it now if appropriate; we are not permitted to perform deduction
8243 // and substitution in this case.
8244 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8245 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8246 Candidate.FoundDecl = FoundDecl;
8247 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8248 Candidate.Viable = false;
8249 Candidate.FailureKind = ovl_fail_explicit;
8250 return;
8251 }
8252
8253 // C++ [over.match.funcs]p7:
8254 // In each case where a candidate is a function template, candidate
8255 // function template specializations are generated using template argument
8256 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8257 // candidate functions in the usual way.113) A given name can refer to one
8258 // or more function templates and also to a set of overloaded non-template
8259 // functions. In such a case, the candidate functions generated from each
8260 // function template are combined with the set of non-template candidate
8261 // functions.
8262 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8263 FunctionTemplate->getTemplateDepth());
8264 FunctionDecl *Specialization = nullptr;
8265 ConversionSequenceList Conversions;
8267 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8268 PartialOverloading, AggregateCandidateDeduction,
8269 /*PartialOrdering=*/false,
8270 /*ObjectType=*/QualType(),
8271 /*ObjectClassification=*/Expr::Classification(),
8272 CandidateSet.getKind() ==
8274 [&](ArrayRef<QualType> ParamTypes,
8275 bool OnlyInitializeNonUserDefinedConversions) {
8276 return S.CheckNonDependentConversions(
8277 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8278 Sema::CheckNonDependentConversionsFlag(
8279 SuppressUserConversions,
8280 OnlyInitializeNonUserDefinedConversions),
8281 nullptr, QualType(), {}, PO);
8282 });
8284 OverloadCandidate &Candidate =
8285 CandidateSet.addCandidate(Conversions.size(), Conversions);
8286 Candidate.FoundDecl = FoundDecl;
8287 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8288 Candidate.Viable = false;
8289 Candidate.RewriteKind =
8290 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8291 Candidate.IsSurrogate = false;
8292 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
8293 // Ignore the object argument if there is one, since we don't have an object
8294 // type.
8295 Candidate.TookAddressOfOverload =
8296 CandidateSet.getKind() ==
8298
8299 Candidate.IgnoreObjectArgument =
8300 isa<CXXMethodDecl>(Candidate.Function) &&
8301 !cast<CXXMethodDecl>(Candidate.Function)
8302 ->isExplicitObjectMemberFunction() &&
8304
8305 Candidate.ExplicitCallArguments = Args.size();
8308 else {
8310 Candidate.DeductionFailure =
8312 }
8313 return;
8314 }
8315
8316 // Add the function template specialization produced by template argument
8317 // deduction as a candidate.
8318 assert(Specialization && "Missing function template specialization?");
8320 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8321 PartialOverloading, AllowExplicit,
8322 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
8323 Info.AggregateDeductionCandidateHasMismatchedArity,
8324 Info.hasStrictPackMatch());
8325}
8326
8329 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8330 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8331 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8332 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8333 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
8334 return;
8335
8336 bool DependentExplicitSpecifier = hasDependentExplicit(FunctionTemplate);
8337
8338 if (ExplicitTemplateArgs ||
8339 !CandidateSet.shouldDeferTemplateArgumentDeduction(*this) ||
8340 (isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl()) &&
8341 DependentExplicitSpecifier)) {
8342
8344 *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8345 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8346 IsADLCandidate, PO, AggregateCandidateDeduction);
8347
8348 if (DependentExplicitSpecifier)
8350 return;
8351 }
8352
8353 CandidateSet.AddDeferredTemplateCandidate(
8354 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8355 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8356 AggregateCandidateDeduction);
8357}
8358
8361 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8363 CheckNonDependentConversionsFlag UserConversionFlag,
8364 CXXRecordDecl *ActingContext, QualType ObjectType,
8365 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8366 // FIXME: The cases in which we allow explicit conversions for constructor
8367 // arguments never consider calling a constructor template. It's not clear
8368 // that is correct.
8369 const bool AllowExplicit = false;
8370
8371 bool ForOverloadSetAddressResolution =
8373 auto *FD = FunctionTemplate->getTemplatedDecl();
8374 auto *Method = dyn_cast<CXXMethodDecl>(FD);
8375 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8377 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8378
8379 if (Conversions.empty())
8380 Conversions =
8381 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
8382
8383 // Overload resolution is always an unevaluated context.
8386
8387 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8388 // require that, but this check should never result in a hard error, and
8389 // overload resolution is permitted to sidestep instantiations.
8390 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
8391 !ObjectType.isNull()) {
8392 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8393 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8394 !ParamTypes[0]->isDependentType()) {
8396 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8397 Method, ActingContext, /*InOverloadResolution=*/true,
8398 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8399 : QualType());
8400 if (Conversions[ConvIdx].isBad())
8401 return true;
8402 }
8403 }
8404
8405 // A speculative workaround for self-dependent constraint bugs that manifest
8406 // after CWG2369.
8407 // FIXME: Add references to the standard once P3606 is adopted.
8408 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8409 QualType ArgType) {
8410 ParamType = ParamType.getNonReferenceType();
8411 ArgType = ArgType.getNonReferenceType();
8412 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8413 if (PointerConv) {
8414 ParamType = ParamType->getPointeeType();
8415 ArgType = ArgType->getPointeeType();
8416 }
8417
8418 if (auto *RD = ParamType->getAsCXXRecordDecl();
8419 RD && RD->hasDefinition() &&
8420 llvm::any_of(LookupConstructors(RD), [](NamedDecl *ND) {
8421 auto Info = getConstructorInfo(ND);
8422 if (!Info)
8423 return false;
8424 CXXConstructorDecl *Ctor = Info.Constructor;
8425 /// isConvertingConstructor takes copy/move constructors into
8426 /// account!
8427 return !Ctor->isCopyOrMoveConstructor() &&
8429 /*AllowExplicit=*/true);
8430 }))
8431 return true;
8432 if (auto *RD = ArgType->getAsCXXRecordDecl();
8433 RD && RD->hasDefinition() &&
8434 !RD->getVisibleConversionFunctions().empty())
8435 return true;
8436
8437 return false;
8438 };
8439
8440 unsigned Offset =
8441 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8442 : 0;
8443
8444 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
8445 I != N; ++I) {
8446 QualType ParamType = ParamTypes[I + Offset];
8447 if (!ParamType->isDependentType()) {
8448 unsigned ConvIdx;
8450 ConvIdx = Args.size() - 1 - I;
8451 assert(Args.size() + ThisConversions == 2 &&
8452 "number of args (including 'this') must be exactly 2 for "
8453 "reversed order");
8454 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8455 // would also be 0. 'this' got ConvIdx = 1 previously.
8456 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8457 } else {
8458 // For members, 'this' got ConvIdx = 0 previously.
8459 ConvIdx = ThisConversions + I;
8460 }
8461 if (Conversions[ConvIdx].isInitialized())
8462 continue;
8463 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8464 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8465 continue;
8467 *this, Args[I], ParamType, UserConversionFlag.SuppressUserConversions,
8468 /*InOverloadResolution=*/true,
8469 /*AllowObjCWritebackConversion=*/
8470 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8471 if (Conversions[ConvIdx].isBad())
8472 return true;
8473 }
8474 }
8475
8476 return false;
8477}
8478
8479/// Determine whether this is an allowable conversion from the result
8480/// of an explicit conversion operator to the expected type, per C++
8481/// [over.match.conv]p1 and [over.match.ref]p1.
8482///
8483/// \param ConvType The return type of the conversion function.
8484///
8485/// \param ToType The type we are converting to.
8486///
8487/// \param AllowObjCPointerConversion Allow a conversion from one
8488/// Objective-C pointer to another.
8489///
8490/// \returns true if the conversion is allowable, false otherwise.
8492 QualType ConvType, QualType ToType,
8493 bool AllowObjCPointerConversion) {
8494 QualType ToNonRefType = ToType.getNonReferenceType();
8495
8496 // Easy case: the types are the same.
8497 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
8498 return true;
8499
8500 // Allow qualification conversions.
8501 bool ObjCLifetimeConversion;
8502 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
8503 ObjCLifetimeConversion))
8504 return true;
8505
8506 // If we're not allowed to consider Objective-C pointer conversions,
8507 // we're done.
8508 if (!AllowObjCPointerConversion)
8509 return false;
8510
8511 // Is this an Objective-C pointer conversion?
8512 bool IncompatibleObjC = false;
8513 QualType ConvertedType;
8514 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
8515 IncompatibleObjC);
8516}
8517
8519 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8520 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8521 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8522 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8523 assert(!Conversion->getDescribedFunctionTemplate() &&
8524 "Conversion function templates use AddTemplateConversionCandidate");
8525 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8526 if (!CandidateSet.isNewCandidate(Conversion))
8527 return;
8528
8529 // If the conversion function has an undeduced return type, trigger its
8530 // deduction now.
8531 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8532 if (DeduceReturnType(Conversion, From->getExprLoc()))
8533 return;
8534 ConvType = Conversion->getConversionType().getNonReferenceType();
8535 }
8536
8537 // If we don't allow any conversion of the result type, ignore conversion
8538 // functions that don't convert to exactly (possibly cv-qualified) T.
8539 if (!AllowResultConversion &&
8540 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8541 return;
8542
8543 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8544 // operator is only a candidate if its return type is the target type or
8545 // can be converted to the target type with a qualification conversion.
8546 //
8547 // FIXME: Include such functions in the candidate list and explain why we
8548 // can't select them.
8549 if (Conversion->isExplicit() &&
8550 !isAllowableExplicitConversion(*this, ConvType, ToType,
8551 AllowObjCConversionOnExplicit))
8552 return;
8553
8554 // Overload resolution is always an unevaluated context.
8557
8558 // Add this candidate
8559 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8560 Candidate.FoundDecl = FoundDecl;
8561 Candidate.Function = Conversion;
8563 Candidate.FinalConversion.setFromType(ConvType);
8564 Candidate.FinalConversion.setAllToTypes(ToType);
8565 Candidate.HasFinalConversion = true;
8566 Candidate.Viable = true;
8567 Candidate.ExplicitCallArguments = 1;
8568 Candidate.StrictPackMatch = StrictPackMatch;
8569
8570 // Explicit functions are not actually candidates at all if we're not
8571 // allowing them in this context, but keep them around so we can point
8572 // to them in diagnostics.
8573 if (!AllowExplicit && Conversion->isExplicit()) {
8574 Candidate.Viable = false;
8575 Candidate.FailureKind = ovl_fail_explicit;
8576 return;
8577 }
8578
8579 // C++ [over.match.funcs]p4:
8580 // For conversion functions, the function is considered to be a member of
8581 // the class of the implicit implied object argument for the purpose of
8582 // defining the type of the implicit object parameter.
8583 //
8584 // Determine the implicit conversion sequence for the implicit
8585 // object parameter.
8586 QualType ObjectType = From->getType();
8587 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8588 ObjectType = FromPtrType->getPointeeType();
8589 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8590 // C++23 [over.best.ics.general]
8591 // However, if the target is [...]
8592 // - the object parameter of a user-defined conversion function
8593 // [...] user-defined conversion sequences are not considered.
8595 *this, CandidateSet.getLocation(), From->getType(),
8596 From->Classify(Context), Conversion, ConversionContext,
8597 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8598 /*SuppressUserConversion*/ true);
8599
8600 if (Candidate.Conversions[0].isBad()) {
8601 Candidate.Viable = false;
8603 return;
8604 }
8605
8606 if (Conversion->getTrailingRequiresClause()) {
8607 ConstraintSatisfaction Satisfaction;
8608 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8609 !Satisfaction.IsSatisfied) {
8610 Candidate.Viable = false;
8612 return;
8613 }
8614 }
8615
8616 // We won't go through a user-defined type conversion function to convert a
8617 // derived to base as such conversions are given Conversion Rank. They only
8618 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8619 QualType FromCanon
8620 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8621 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8622 if (FromCanon == ToCanon ||
8623 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8624 Candidate.Viable = false;
8626 return;
8627 }
8628
8629 // To determine what the conversion from the result of calling the
8630 // conversion function to the type we're eventually trying to
8631 // convert to (ToType), we need to synthesize a call to the
8632 // conversion function and attempt copy initialization from it. This
8633 // makes sure that we get the right semantics with respect to
8634 // lvalues/rvalues and the type. Fortunately, we can allocate this
8635 // call on the stack and we don't need its arguments to be
8636 // well-formed.
8637 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8638 VK_LValue, From->getBeginLoc());
8640 Context.getPointerType(Conversion->getType()),
8641 CK_FunctionToPointerDecay, &ConversionRef,
8643
8644 QualType ConversionType = Conversion->getConversionType();
8645 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8646 Candidate.Viable = false;
8648 return;
8649 }
8650
8651 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8652
8653 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8654
8655 // Introduce a temporary expression with the right type and value category
8656 // that we can use for deduction purposes.
8657 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8658
8660 TryCopyInitialization(*this, &FakeCall, ToType,
8661 /*SuppressUserConversions=*/true,
8662 /*InOverloadResolution=*/false,
8663 /*AllowObjCWritebackConversion=*/false);
8664
8665 switch (ICS.getKind()) {
8667 Candidate.FinalConversion = ICS.Standard;
8668 Candidate.HasFinalConversion = true;
8669
8670 // C++ [over.ics.user]p3:
8671 // If the user-defined conversion is specified by a specialization of a
8672 // conversion function template, the second standard conversion sequence
8673 // shall have exact match rank.
8674 if (Conversion->getPrimaryTemplate() &&
8676 Candidate.Viable = false;
8678 return;
8679 }
8680
8681 // C++0x [dcl.init.ref]p5:
8682 // In the second case, if the reference is an rvalue reference and
8683 // the second standard conversion sequence of the user-defined
8684 // conversion sequence includes an lvalue-to-rvalue conversion, the
8685 // program is ill-formed.
8686 if (ToType->isRValueReferenceType() &&
8688 Candidate.Viable = false;
8690 return;
8691 }
8692 break;
8693
8695 Candidate.Viable = false;
8697 return;
8698
8699 default:
8700 llvm_unreachable(
8701 "Can only end up with a standard conversion sequence or failure");
8702 }
8703
8704 if (EnableIfAttr *FailedAttr =
8705 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8706 Candidate.Viable = false;
8707 Candidate.FailureKind = ovl_fail_enable_if;
8708 Candidate.DeductionFailure.Data = FailedAttr;
8709 return;
8710 }
8711
8712 if (isNonViableMultiVersionOverload(Conversion)) {
8713 Candidate.Viable = false;
8715 }
8716}
8717
8719 Sema &S, OverloadCandidateSet &CandidateSet,
8721 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8722 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8723 bool AllowResultConversion) {
8724
8725 // If the function template has a non-dependent explicit specification,
8726 // exclude it now if appropriate; we are not permitted to perform deduction
8727 // and substitution in this case.
8728 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8729 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8730 Candidate.FoundDecl = FoundDecl;
8731 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8732 Candidate.Viable = false;
8733 Candidate.FailureKind = ovl_fail_explicit;
8734 return;
8735 }
8736
8737 QualType ObjectType = From->getType();
8738 Expr::Classification ObjectClassification = From->Classify(S.Context);
8739
8740 TemplateDeductionInfo Info(CandidateSet.getLocation());
8743 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8744 Specialization, Info);
8746 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8747 Candidate.FoundDecl = FoundDecl;
8748 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8749 Candidate.Viable = false;
8751 Candidate.ExplicitCallArguments = 1;
8752 Candidate.DeductionFailure =
8754 return;
8755 }
8756
8757 // Add the conversion function template specialization produced by
8758 // template argument deduction as a candidate.
8759 assert(Specialization && "Missing function template specialization?");
8760 S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,
8761 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8762 AllowExplicit, AllowResultConversion,
8763 Info.hasStrictPackMatch());
8764}
8765
8768 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8769 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8770 bool AllowExplicit, bool AllowResultConversion) {
8771 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8772 "Only conversion function templates permitted here");
8773
8774 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8775 return;
8776
8777 if (!CandidateSet.shouldDeferTemplateArgumentDeduction(*this) ||
8778 CandidateSet.getKind() ==
8782 *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,
8783 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8784 AllowResultConversion);
8785
8787 return;
8788 }
8789
8791 FunctionTemplate, FoundDecl, ActingDC, From, ToType,
8792 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8793}
8794
8796 DeclAccessPair FoundDecl,
8797 CXXRecordDecl *ActingContext,
8798 const FunctionProtoType *Proto,
8799 Expr *Object,
8800 ArrayRef<Expr *> Args,
8801 OverloadCandidateSet& CandidateSet) {
8802 if (!CandidateSet.isNewCandidate(Conversion))
8803 return;
8804
8805 // Overload resolution is always an unevaluated context.
8808
8809 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8810 Candidate.FoundDecl = FoundDecl;
8811 Candidate.Function = nullptr;
8812 Candidate.Surrogate = Conversion;
8813 Candidate.IsSurrogate = true;
8814 Candidate.Viable = true;
8815 Candidate.ExplicitCallArguments = Args.size();
8816
8817 // Determine the implicit conversion sequence for the implicit
8818 // object parameter.
8819 ImplicitConversionSequence ObjectInit;
8820 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8821 ObjectInit = TryCopyInitialization(*this, Object,
8822 Conversion->getParamDecl(0)->getType(),
8823 /*SuppressUserConversions=*/false,
8824 /*InOverloadResolution=*/true, false);
8825 } else {
8827 *this, CandidateSet.getLocation(), Object->getType(),
8828 Object->Classify(Context), Conversion, ActingContext);
8829 }
8830
8831 if (ObjectInit.isBad()) {
8832 Candidate.Viable = false;
8834 Candidate.Conversions[0] = ObjectInit;
8835 return;
8836 }
8837
8838 // The first conversion is actually a user-defined conversion whose
8839 // first conversion is ObjectInit's standard conversion (which is
8840 // effectively a reference binding). Record it as such.
8841 Candidate.Conversions[0].setUserDefined();
8842 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8843 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8844 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8845 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8846 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8847 Candidate.Conversions[0].UserDefined.After
8848 = Candidate.Conversions[0].UserDefined.Before;
8849 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8850
8851 // Find the
8852 unsigned NumParams = Proto->getNumParams();
8853
8854 // (C++ 13.3.2p2): A candidate function having fewer than m
8855 // parameters is viable only if it has an ellipsis in its parameter
8856 // list (8.3.5).
8857 if (Args.size() > NumParams && !Proto->isVariadic()) {
8858 Candidate.Viable = false;
8860 return;
8861 }
8862
8863 // Function types don't have any default arguments, so just check if
8864 // we have enough arguments.
8865 if (Args.size() < NumParams) {
8866 // Not enough arguments.
8867 Candidate.Viable = false;
8869 return;
8870 }
8871
8872 // Determine the implicit conversion sequences for each of the
8873 // arguments.
8874 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8875 if (ArgIdx < NumParams) {
8876 // (C++ 13.3.2p3): for F to be a viable function, there shall
8877 // exist for each argument an implicit conversion sequence
8878 // (13.3.3.1) that converts that argument to the corresponding
8879 // parameter of F.
8880 QualType ParamType = Proto->getParamType(ArgIdx);
8881 Candidate.Conversions[ArgIdx + 1]
8882 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8883 /*SuppressUserConversions=*/false,
8884 /*InOverloadResolution=*/false,
8885 /*AllowObjCWritebackConversion=*/
8886 getLangOpts().ObjCAutoRefCount);
8887 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8888 Candidate.Viable = false;
8890 return;
8891 }
8892 } else {
8893 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8894 // argument for which there is no corresponding parameter is
8895 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8896 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8897 }
8898 }
8899
8900 if (Conversion->getTrailingRequiresClause()) {
8901 ConstraintSatisfaction Satisfaction;
8902 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8903 /*ForOverloadResolution*/ true) ||
8904 !Satisfaction.IsSatisfied) {
8905 Candidate.Viable = false;
8907 return;
8908 }
8909 }
8910
8911 if (EnableIfAttr *FailedAttr =
8912 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8913 Candidate.Viable = false;
8914 Candidate.FailureKind = ovl_fail_enable_if;
8915 Candidate.DeductionFailure.Data = FailedAttr;
8916 return;
8917 }
8918}
8919
8921 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8922 OverloadCandidateSet &CandidateSet,
8923 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8924 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8925 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8926 ArrayRef<Expr *> FunctionArgs = Args;
8927
8928 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8929 FunctionDecl *FD =
8930 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8931
8932 // Don't consider rewritten functions if we're not rewriting.
8933 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8934 continue;
8935
8936 assert(!isa<CXXMethodDecl>(FD) &&
8937 "unqualified operator lookup found a member function");
8938
8939 if (FunTmpl) {
8940 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8941 FunctionArgs, CandidateSet);
8942 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
8943
8944 // As template candidates are not deduced immediately,
8945 // persist the array in the overload set.
8947 FunctionArgs[1], FunctionArgs[0]);
8948 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8949 Reversed, CandidateSet, false, false, true,
8950 ADLCallKind::NotADL,
8952 }
8953 } else {
8954 if (ExplicitTemplateArgs)
8955 continue;
8956 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8957 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8958 AddOverloadCandidate(FD, F.getPair(),
8959 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8960 false, false, true, false, ADLCallKind::NotADL, {},
8962 }
8963 }
8964}
8965
8967 SourceLocation OpLoc,
8968 ArrayRef<Expr *> Args,
8969 OverloadCandidateSet &CandidateSet,
8971 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8972
8973 // C++ [over.match.oper]p3:
8974 // For a unary operator @ with an operand of a type whose
8975 // cv-unqualified version is T1, and for a binary operator @ with
8976 // a left operand of a type whose cv-unqualified version is T1 and
8977 // a right operand of a type whose cv-unqualified version is T2,
8978 // three sets of candidate functions, designated member
8979 // candidates, non-member candidates and built-in candidates, are
8980 // constructed as follows:
8981 QualType T1 = Args[0]->getType();
8982
8983 // -- If T1 is a complete class type or a class currently being
8984 // defined, the set of member candidates is the result of the
8985 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8986 // the set of member candidates is empty.
8987 if (T1->isRecordType()) {
8988 bool IsComplete = isCompleteType(OpLoc, T1);
8989 auto *T1RD = T1->getAsCXXRecordDecl();
8990 // Complete the type if it can be completed.
8991 // If the type is neither complete nor being defined, bail out now.
8992 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
8993 return;
8994
8995 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8996 LookupQualifiedName(Operators, T1RD);
8997 Operators.suppressAccessDiagnostics();
8998
8999 for (LookupResult::iterator Oper = Operators.begin(),
9000 OperEnd = Operators.end();
9001 Oper != OperEnd; ++Oper) {
9002 if (Oper->getAsFunction() &&
9004 !CandidateSet.getRewriteInfo().shouldAddReversed(
9005 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
9006 continue;
9007 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
9008 Args[0]->Classify(Context), Args.slice(1),
9009 CandidateSet, /*SuppressUserConversion=*/false, PO);
9010 }
9011 }
9012}
9013
9015 OverloadCandidateSet& CandidateSet,
9016 bool IsAssignmentOperator,
9017 unsigned NumContextualBoolArguments) {
9018 // Overload resolution is always an unevaluated context.
9021
9022 // Add this candidate
9023 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
9024 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
9025 Candidate.Function = nullptr;
9026 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
9027
9028 // Determine the implicit conversion sequences for each of the
9029 // arguments.
9030 Candidate.Viable = true;
9031 Candidate.ExplicitCallArguments = Args.size();
9032 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9033 // C++ [over.match.oper]p4:
9034 // For the built-in assignment operators, conversions of the
9035 // left operand are restricted as follows:
9036 // -- no temporaries are introduced to hold the left operand, and
9037 // -- no user-defined conversions are applied to the left
9038 // operand to achieve a type match with the left-most
9039 // parameter of a built-in candidate.
9040 //
9041 // We block these conversions by turning off user-defined
9042 // conversions, since that is the only way that initialization of
9043 // a reference to a non-class type can occur from something that
9044 // is not of the same type.
9045 if (ArgIdx < NumContextualBoolArguments) {
9046 assert(ParamTys[ArgIdx] == Context.BoolTy &&
9047 "Contextual conversion to bool requires bool type");
9048 Candidate.Conversions[ArgIdx]
9049 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
9050 } else {
9051 Candidate.Conversions[ArgIdx]
9052 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
9053 ArgIdx == 0 && IsAssignmentOperator,
9054 /*InOverloadResolution=*/false,
9055 /*AllowObjCWritebackConversion=*/
9056 getLangOpts().ObjCAutoRefCount);
9057 }
9058 if (Candidate.Conversions[ArgIdx].isBad()) {
9059 Candidate.Viable = false;
9061 break;
9062 }
9063 }
9064}
9065
9066namespace {
9067
9068/// BuiltinCandidateTypeSet - A set of types that will be used for the
9069/// candidate operator functions for built-in operators (C++
9070/// [over.built]). The types are separated into pointer types and
9071/// enumeration types.
9072class BuiltinCandidateTypeSet {
9073 /// TypeSet - A set of types.
9074 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
9075
9076 /// PointerTypes - The set of pointer types that will be used in the
9077 /// built-in candidates.
9078 TypeSet PointerTypes;
9079
9080 /// MemberPointerTypes - The set of member pointer types that will be
9081 /// used in the built-in candidates.
9082 TypeSet MemberPointerTypes;
9083
9084 /// EnumerationTypes - The set of enumeration types that will be
9085 /// used in the built-in candidates.
9086 TypeSet EnumerationTypes;
9087
9088 /// The set of vector types that will be used in the built-in
9089 /// candidates.
9090 TypeSet VectorTypes;
9091
9092 /// The set of matrix types that will be used in the built-in
9093 /// candidates.
9094 TypeSet MatrixTypes;
9095
9096 /// The set of _BitInt types that will be used in the built-in candidates.
9097 TypeSet BitIntTypes;
9098
9099 /// A flag indicating non-record types are viable candidates
9100 bool HasNonRecordTypes;
9101
9102 /// A flag indicating whether either arithmetic or enumeration types
9103 /// were present in the candidate set.
9104 bool HasArithmeticOrEnumeralTypes;
9105
9106 /// A flag indicating whether the nullptr type was present in the
9107 /// candidate set.
9108 bool HasNullPtrType;
9109
9110 /// Sema - The semantic analysis instance where we are building the
9111 /// candidate type set.
9112 Sema &SemaRef;
9113
9114 /// Context - The AST context in which we will build the type sets.
9115 ASTContext &Context;
9116
9117 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9118 const Qualifiers &VisibleQuals);
9119 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
9120
9121public:
9122 /// iterator - Iterates through the types that are part of the set.
9123 typedef TypeSet::iterator iterator;
9124
9125 BuiltinCandidateTypeSet(Sema &SemaRef)
9126 : HasNonRecordTypes(false),
9127 HasArithmeticOrEnumeralTypes(false),
9128 HasNullPtrType(false),
9129 SemaRef(SemaRef),
9130 Context(SemaRef.Context) { }
9131
9132 void AddTypesConvertedFrom(QualType Ty,
9133 SourceLocation Loc,
9134 bool AllowUserConversions,
9135 bool AllowExplicitConversions,
9136 const Qualifiers &VisibleTypeConversionsQuals);
9137
9138 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
9139 llvm::iterator_range<iterator> member_pointer_types() {
9140 return MemberPointerTypes;
9141 }
9142 llvm::iterator_range<iterator> enumeration_types() {
9143 return EnumerationTypes;
9144 }
9145 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
9146 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
9147 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
9148
9149 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
9150 bool hasNonRecordTypes() { return HasNonRecordTypes; }
9151 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
9152 bool hasNullPtrType() const { return HasNullPtrType; }
9153};
9154
9155} // end anonymous namespace
9156
9157/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
9158/// the set of pointer types along with any more-qualified variants of
9159/// that type. For example, if @p Ty is "int const *", this routine
9160/// will add "int const *", "int const volatile *", "int const
9161/// restrict *", and "int const volatile restrict *" to the set of
9162/// pointer types. Returns true if the add of @p Ty itself succeeded,
9163/// false otherwise.
9164///
9165/// FIXME: what to do about extended qualifiers?
9166bool
9167BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
9168 const Qualifiers &VisibleQuals) {
9169
9170 // Insert this type.
9171 if (!PointerTypes.insert(Ty))
9172 return false;
9173
9174 QualType PointeeTy;
9175 const PointerType *PointerTy = Ty->getAs<PointerType>();
9176 bool buildObjCPtr = false;
9177 if (!PointerTy) {
9178 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
9179 PointeeTy = PTy->getPointeeType();
9180 buildObjCPtr = true;
9181 } else {
9182 PointeeTy = PointerTy->getPointeeType();
9183 }
9184
9185 // Don't add qualified variants of arrays. For one, they're not allowed
9186 // (the qualifier would sink to the element type), and for another, the
9187 // only overload situation where it matters is subscript or pointer +- int,
9188 // and those shouldn't have qualifier variants anyway.
9189 if (PointeeTy->isArrayType())
9190 return true;
9191
9192 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9193 bool hasVolatile = VisibleQuals.hasVolatile();
9194 bool hasRestrict = VisibleQuals.hasRestrict();
9195
9196 // Iterate through all strict supersets of BaseCVR.
9197 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9198 if ((CVR | BaseCVR) != CVR) continue;
9199 // Skip over volatile if no volatile found anywhere in the types.
9200 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
9201
9202 // Skip over restrict if no restrict found anywhere in the types, or if
9203 // the type cannot be restrict-qualified.
9204 if ((CVR & Qualifiers::Restrict) &&
9205 (!hasRestrict ||
9206 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
9207 continue;
9208
9209 // Build qualified pointee type.
9210 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9211
9212 // Build qualified pointer type.
9213 QualType QPointerTy;
9214 if (!buildObjCPtr)
9215 QPointerTy = Context.getPointerType(QPointeeTy);
9216 else
9217 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
9218
9219 // Insert qualified pointer type.
9220 PointerTypes.insert(QPointerTy);
9221 }
9222
9223 return true;
9224}
9225
9226/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
9227/// to the set of pointer types along with any more-qualified variants of
9228/// that type. For example, if @p Ty is "int const *", this routine
9229/// will add "int const *", "int const volatile *", "int const
9230/// restrict *", and "int const volatile restrict *" to the set of
9231/// pointer types. Returns true if the add of @p Ty itself succeeded,
9232/// false otherwise.
9233///
9234/// FIXME: what to do about extended qualifiers?
9235bool
9236BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
9237 QualType Ty) {
9238 // Insert this type.
9239 if (!MemberPointerTypes.insert(Ty))
9240 return false;
9241
9242 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
9243 assert(PointerTy && "type was not a member pointer type!");
9244
9245 QualType PointeeTy = PointerTy->getPointeeType();
9246 // Don't add qualified variants of arrays. For one, they're not allowed
9247 // (the qualifier would sink to the element type), and for another, the
9248 // only overload situation where it matters is subscript or pointer +- int,
9249 // and those shouldn't have qualifier variants anyway.
9250 if (PointeeTy->isArrayType())
9251 return true;
9252 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9253
9254 // Iterate through all strict supersets of the pointee type's CVR
9255 // qualifiers.
9256 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9257 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9258 if ((CVR | BaseCVR) != CVR) continue;
9259
9260 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9261 MemberPointerTypes.insert(Context.getMemberPointerType(
9262 QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9263 }
9264
9265 return true;
9266}
9267
9268/// AddTypesConvertedFrom - Add each of the types to which the type @p
9269/// Ty can be implicit converted to the given set of @p Types. We're
9270/// primarily interested in pointer types and enumeration types. We also
9271/// take member pointer types, for the conditional operator.
9272/// AllowUserConversions is true if we should look at the conversion
9273/// functions of a class type, and AllowExplicitConversions if we
9274/// should also include the explicit conversion functions of a class
9275/// type.
9276void
9277BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9278 SourceLocation Loc,
9279 bool AllowUserConversions,
9280 bool AllowExplicitConversions,
9281 const Qualifiers &VisibleQuals) {
9282 // Only deal with canonical types.
9283 Ty = Context.getCanonicalType(Ty);
9284
9285 // Look through reference types; they aren't part of the type of an
9286 // expression for the purposes of conversions.
9287 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9288 Ty = RefTy->getPointeeType();
9289
9290 // If we're dealing with an array type, decay to the pointer.
9291 if (Ty->isArrayType())
9292 Ty = SemaRef.Context.getArrayDecayedType(Ty);
9293
9294 // Otherwise, we don't care about qualifiers on the type.
9295 Ty = Ty.getLocalUnqualifiedType();
9296
9297 // Flag if we ever add a non-record type.
9298 bool TyIsRec = Ty->isRecordType();
9299 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9300
9301 // Flag if we encounter an arithmetic type.
9302 HasArithmeticOrEnumeralTypes =
9303 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9304
9305 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9306 PointerTypes.insert(Ty);
9307 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9308 // Insert our type, and its more-qualified variants, into the set
9309 // of types.
9310 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9311 return;
9312 } else if (Ty->isMemberPointerType()) {
9313 // Member pointers are far easier, since the pointee can't be converted.
9314 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9315 return;
9316 } else if (Ty->isEnumeralType()) {
9317 HasArithmeticOrEnumeralTypes = true;
9318 EnumerationTypes.insert(Ty);
9319 } else if (Ty->isBitIntType()) {
9320 HasArithmeticOrEnumeralTypes = true;
9321 BitIntTypes.insert(Ty);
9322 } else if (Ty->isVectorType()) {
9323 // We treat vector types as arithmetic types in many contexts as an
9324 // extension.
9325 HasArithmeticOrEnumeralTypes = true;
9326 VectorTypes.insert(Ty);
9327 } else if (Ty->isMatrixType()) {
9328 // Similar to vector types, we treat vector types as arithmetic types in
9329 // many contexts as an extension.
9330 HasArithmeticOrEnumeralTypes = true;
9331 MatrixTypes.insert(Ty);
9332 } else if (Ty->isNullPtrType()) {
9333 HasNullPtrType = true;
9334 } else if (AllowUserConversions && TyIsRec) {
9335 // No conversion functions in incomplete types.
9336 if (!SemaRef.isCompleteType(Loc, Ty))
9337 return;
9338
9339 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9340 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9341 if (isa<UsingShadowDecl>(D))
9342 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9343
9344 // Skip conversion function templates; they don't tell us anything
9345 // about which builtin types we can convert to.
9347 continue;
9348
9349 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9350 if (AllowExplicitConversions || !Conv->isExplicit()) {
9351 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
9352 VisibleQuals);
9353 }
9354 }
9355 }
9356}
9357/// Helper function for adjusting address spaces for the pointer or reference
9358/// operands of builtin operators depending on the argument.
9363
9364/// Helper function for AddBuiltinOperatorCandidates() that adds
9365/// the volatile- and non-volatile-qualified assignment operators for the
9366/// given type to the candidate set.
9368 QualType T,
9369 ArrayRef<Expr *> Args,
9370 OverloadCandidateSet &CandidateSet) {
9371 QualType ParamTypes[2];
9372
9373 // T& operator=(T&, T)
9374 ParamTypes[0] = S.Context.getLValueReferenceType(
9376 ParamTypes[1] = T;
9377 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9378 /*IsAssignmentOperator=*/true);
9379
9381 // volatile T& operator=(volatile T&, T)
9382 ParamTypes[0] = S.Context.getLValueReferenceType(
9384 Args[0]));
9385 ParamTypes[1] = T;
9386 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9387 /*IsAssignmentOperator=*/true);
9388 }
9389}
9390
9391/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9392/// if any, found in visible type conversion functions found in ArgExpr's type.
9393static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9394 Qualifiers VRQuals;
9395 CXXRecordDecl *ClassDecl;
9396 if (const MemberPointerType *RHSMPType =
9397 ArgExpr->getType()->getAs<MemberPointerType>())
9398 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9399 else
9400 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9401 if (!ClassDecl) {
9402 // Just to be safe, assume the worst case.
9403 VRQuals.addVolatile();
9404 VRQuals.addRestrict();
9405 return VRQuals;
9406 }
9407 if (!ClassDecl->hasDefinition())
9408 return VRQuals;
9409
9410 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9411 if (isa<UsingShadowDecl>(D))
9412 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9413 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
9414 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
9415 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9416 CanTy = ResTypeRef->getPointeeType();
9417 // Need to go down the pointer/mempointer chain and add qualifiers
9418 // as see them.
9419 bool done = false;
9420 while (!done) {
9421 if (CanTy.isRestrictQualified())
9422 VRQuals.addRestrict();
9423 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9424 CanTy = ResTypePtr->getPointeeType();
9425 else if (const MemberPointerType *ResTypeMPtr =
9426 CanTy->getAs<MemberPointerType>())
9427 CanTy = ResTypeMPtr->getPointeeType();
9428 else
9429 done = true;
9430 if (CanTy.isVolatileQualified())
9431 VRQuals.addVolatile();
9432 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9433 return VRQuals;
9434 }
9435 }
9436 }
9437 return VRQuals;
9438}
9439
9440// Note: We're currently only handling qualifiers that are meaningful for the
9441// LHS of compound assignment overloading.
9443 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9444 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9445 // _Atomic
9446 if (Available.hasAtomic()) {
9447 Available.removeAtomic();
9448 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
9449 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9450 return;
9451 }
9452
9453 // volatile
9454 if (Available.hasVolatile()) {
9455 Available.removeVolatile();
9456 assert(!Applied.hasVolatile());
9457 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
9458 Callback);
9459 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9460 return;
9461 }
9462
9463 Callback(Applied);
9464}
9465
9467 QualifiersAndAtomic Quals,
9468 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9470 Callback);
9471}
9472
9474 QualifiersAndAtomic Quals,
9475 Sema &S) {
9476 if (Quals.hasAtomic())
9478 if (Quals.hasVolatile())
9481}
9482
9483namespace {
9484
9485/// Helper class to manage the addition of builtin operator overload
9486/// candidates. It provides shared state and utility methods used throughout
9487/// the process, as well as a helper method to add each group of builtin
9488/// operator overloads from the standard to a candidate set.
9489class BuiltinOperatorOverloadBuilder {
9490 // Common instance state available to all overload candidate addition methods.
9491 Sema &S;
9492 ArrayRef<Expr *> Args;
9493 QualifiersAndAtomic VisibleTypeConversionsQuals;
9494 bool HasArithmeticOrEnumeralCandidateType;
9495 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9496 OverloadCandidateSet &CandidateSet;
9497
9498 static constexpr int ArithmeticTypesCap = 26;
9499 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9500
9501 // Define some indices used to iterate over the arithmetic types in
9502 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9503 // types are that preserved by promotion (C++ [over.built]p2).
9504 unsigned FirstIntegralType,
9505 LastIntegralType;
9506 unsigned FirstPromotedIntegralType,
9507 LastPromotedIntegralType;
9508 unsigned FirstPromotedArithmeticType,
9509 LastPromotedArithmeticType;
9510 unsigned NumArithmeticTypes;
9511
9512 void InitArithmeticTypes() {
9513 // Start of promoted types.
9514 FirstPromotedArithmeticType = 0;
9515 ArithmeticTypes.push_back(S.Context.FloatTy);
9516 ArithmeticTypes.push_back(S.Context.DoubleTy);
9517 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
9519 ArithmeticTypes.push_back(S.Context.Float128Ty);
9521 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
9522
9523 // Start of integral types.
9524 FirstIntegralType = ArithmeticTypes.size();
9525 FirstPromotedIntegralType = ArithmeticTypes.size();
9526 ArithmeticTypes.push_back(S.Context.IntTy);
9527 ArithmeticTypes.push_back(S.Context.LongTy);
9528 ArithmeticTypes.push_back(S.Context.LongLongTy);
9532 ArithmeticTypes.push_back(S.Context.Int128Ty);
9533 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
9534 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
9535 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
9539 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9540
9541 /// We add candidates for the unique, unqualified _BitInt types present in
9542 /// the candidate type set. The candidate set already handled ensuring the
9543 /// type is unqualified and canonical, but because we're adding from N
9544 /// different sets, we need to do some extra work to unique things. Insert
9545 /// the candidates into a unique set, then move from that set into the list
9546 /// of arithmetic types.
9547 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9548 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9549 for (QualType BitTy : Candidate.bitint_types())
9550 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9551 }
9552 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9553 LastPromotedIntegralType = ArithmeticTypes.size();
9554 LastPromotedArithmeticType = ArithmeticTypes.size();
9555 // End of promoted types.
9556
9557 ArithmeticTypes.push_back(S.Context.BoolTy);
9558 ArithmeticTypes.push_back(S.Context.CharTy);
9559 ArithmeticTypes.push_back(S.Context.WCharTy);
9560 if (S.Context.getLangOpts().Char8)
9561 ArithmeticTypes.push_back(S.Context.Char8Ty);
9562 ArithmeticTypes.push_back(S.Context.Char16Ty);
9563 ArithmeticTypes.push_back(S.Context.Char32Ty);
9564 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9565 ArithmeticTypes.push_back(S.Context.ShortTy);
9566 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9567 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9568 LastIntegralType = ArithmeticTypes.size();
9569 NumArithmeticTypes = ArithmeticTypes.size();
9570 // End of integral types.
9571 // FIXME: What about complex? What about half?
9572
9573 // We don't know for sure how many bit-precise candidates were involved, so
9574 // we subtract those from the total when testing whether we're under the
9575 // cap or not.
9576 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9577 ArithmeticTypesCap &&
9578 "Enough inline storage for all arithmetic types.");
9579 }
9580
9581 /// Helper method to factor out the common pattern of adding overloads
9582 /// for '++' and '--' builtin operators.
9583 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9584 bool HasVolatile,
9585 bool HasRestrict) {
9586 QualType ParamTypes[2] = {
9587 S.Context.getLValueReferenceType(CandidateTy),
9588 S.Context.IntTy
9589 };
9590
9591 // Non-volatile version.
9592 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9593
9594 // Use a heuristic to reduce number of builtin candidates in the set:
9595 // add volatile version only if there are conversions to a volatile type.
9596 if (HasVolatile) {
9597 ParamTypes[0] =
9599 S.Context.getVolatileType(CandidateTy));
9600 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9601 }
9602
9603 // Add restrict version only if there are conversions to a restrict type
9604 // and our candidate type is a non-restrict-qualified pointer.
9605 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9606 !CandidateTy.isRestrictQualified()) {
9607 ParamTypes[0]
9610 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9611
9612 if (HasVolatile) {
9613 ParamTypes[0]
9615 S.Context.getCVRQualifiedType(CandidateTy,
9618 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9619 }
9620 }
9621
9622 }
9623
9624 /// Helper to add an overload candidate for a binary builtin with types \p L
9625 /// and \p R.
9626 void AddCandidate(QualType L, QualType R) {
9627 QualType LandR[2] = {L, R};
9628 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9629 }
9630
9631public:
9632 BuiltinOperatorOverloadBuilder(
9633 Sema &S, ArrayRef<Expr *> Args,
9634 QualifiersAndAtomic VisibleTypeConversionsQuals,
9635 bool HasArithmeticOrEnumeralCandidateType,
9636 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9637 OverloadCandidateSet &CandidateSet)
9638 : S(S), Args(Args),
9639 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9640 HasArithmeticOrEnumeralCandidateType(
9641 HasArithmeticOrEnumeralCandidateType),
9642 CandidateTypes(CandidateTypes),
9643 CandidateSet(CandidateSet) {
9644
9645 InitArithmeticTypes();
9646 }
9647
9648 // Increment is deprecated for bool since C++17.
9649 //
9650 // C++ [over.built]p3:
9651 //
9652 // For every pair (T, VQ), where T is an arithmetic type other
9653 // than bool, and VQ is either volatile or empty, there exist
9654 // candidate operator functions of the form
9655 //
9656 // VQ T& operator++(VQ T&);
9657 // T operator++(VQ T&, int);
9658 //
9659 // C++ [over.built]p4:
9660 //
9661 // For every pair (T, VQ), where T is an arithmetic type other
9662 // than bool, and VQ is either volatile or empty, there exist
9663 // candidate operator functions of the form
9664 //
9665 // VQ T& operator--(VQ T&);
9666 // T operator--(VQ T&, int);
9667 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9668 if (!HasArithmeticOrEnumeralCandidateType)
9669 return;
9670
9671 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9672 const auto TypeOfT = ArithmeticTypes[Arith];
9673 if (TypeOfT == S.Context.BoolTy) {
9674 if (Op == OO_MinusMinus)
9675 continue;
9676 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9677 continue;
9678 }
9679 addPlusPlusMinusMinusStyleOverloads(
9680 TypeOfT,
9681 VisibleTypeConversionsQuals.hasVolatile(),
9682 VisibleTypeConversionsQuals.hasRestrict());
9683 }
9684 }
9685
9686 // C++ [over.built]p5:
9687 //
9688 // For every pair (T, VQ), where T is a cv-qualified or
9689 // cv-unqualified object type, and VQ is either volatile or
9690 // empty, there exist candidate operator functions of the form
9691 //
9692 // T*VQ& operator++(T*VQ&);
9693 // T*VQ& operator--(T*VQ&);
9694 // T* operator++(T*VQ&, int);
9695 // T* operator--(T*VQ&, int);
9696 void addPlusPlusMinusMinusPointerOverloads() {
9697 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9698 // Skip pointer types that aren't pointers to object types.
9699 if (!PtrTy->getPointeeType()->isObjectType())
9700 continue;
9701
9702 addPlusPlusMinusMinusStyleOverloads(
9703 PtrTy,
9704 (!PtrTy.isVolatileQualified() &&
9705 VisibleTypeConversionsQuals.hasVolatile()),
9706 (!PtrTy.isRestrictQualified() &&
9707 VisibleTypeConversionsQuals.hasRestrict()));
9708 }
9709 }
9710
9711 // C++ [over.built]p6:
9712 // For every cv-qualified or cv-unqualified object type T, there
9713 // exist candidate operator functions of the form
9714 //
9715 // T& operator*(T*);
9716 //
9717 // C++ [over.built]p7:
9718 // For every function type T that does not have cv-qualifiers or a
9719 // ref-qualifier, there exist candidate operator functions of the form
9720 // T& operator*(T*);
9721 void addUnaryStarPointerOverloads() {
9722 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9723 QualType PointeeTy = ParamTy->getPointeeType();
9724 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9725 continue;
9726
9727 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9728 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9729 continue;
9730
9731 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9732 }
9733 }
9734
9735 // C++ [over.built]p9:
9736 // For every promoted arithmetic type T, there exist candidate
9737 // operator functions of the form
9738 //
9739 // T operator+(T);
9740 // T operator-(T);
9741 void addUnaryPlusOrMinusArithmeticOverloads() {
9742 if (!HasArithmeticOrEnumeralCandidateType)
9743 return;
9744
9745 for (unsigned Arith = FirstPromotedArithmeticType;
9746 Arith < LastPromotedArithmeticType; ++Arith) {
9747 QualType ArithTy = ArithmeticTypes[Arith];
9748 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9749 }
9750
9751 // Extension: We also add these operators for vector types.
9752 for (QualType VecTy : CandidateTypes[0].vector_types())
9753 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9754 }
9755
9756 // C++ [over.built]p8:
9757 // For every type T, there exist candidate operator functions of
9758 // the form
9759 //
9760 // T* operator+(T*);
9761 void addUnaryPlusPointerOverloads() {
9762 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9763 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9764 }
9765
9766 // C++ [over.built]p10:
9767 // For every promoted integral type T, there exist candidate
9768 // operator functions of the form
9769 //
9770 // T operator~(T);
9771 void addUnaryTildePromotedIntegralOverloads() {
9772 if (!HasArithmeticOrEnumeralCandidateType)
9773 return;
9774
9775 for (unsigned Int = FirstPromotedIntegralType;
9776 Int < LastPromotedIntegralType; ++Int) {
9777 QualType IntTy = ArithmeticTypes[Int];
9778 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9779 }
9780
9781 // Extension: We also add this operator for vector types.
9782 for (QualType VecTy : CandidateTypes[0].vector_types())
9783 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9784 }
9785
9786 // C++ [over.match.oper]p16:
9787 // For every pointer to member type T or type std::nullptr_t, there
9788 // exist candidate operator functions of the form
9789 //
9790 // bool operator==(T,T);
9791 // bool operator!=(T,T);
9792 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9793 /// Set of (canonical) types that we've already handled.
9794 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9795
9796 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9797 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9798 // Don't add the same builtin candidate twice.
9799 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9800 continue;
9801
9802 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9803 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9804 }
9805
9806 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9808 if (AddedTypes.insert(NullPtrTy).second) {
9809 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9810 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9811 }
9812 }
9813 }
9814 }
9815
9816 // C++ [over.built]p15:
9817 //
9818 // For every T, where T is an enumeration type or a pointer type,
9819 // there exist candidate operator functions of the form
9820 //
9821 // bool operator<(T, T);
9822 // bool operator>(T, T);
9823 // bool operator<=(T, T);
9824 // bool operator>=(T, T);
9825 // bool operator==(T, T);
9826 // bool operator!=(T, T);
9827 // R operator<=>(T, T)
9828 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9829 // C++ [over.match.oper]p3:
9830 // [...]the built-in candidates include all of the candidate operator
9831 // functions defined in 13.6 that, compared to the given operator, [...]
9832 // do not have the same parameter-type-list as any non-template non-member
9833 // candidate.
9834 //
9835 // Note that in practice, this only affects enumeration types because there
9836 // aren't any built-in candidates of record type, and a user-defined operator
9837 // must have an operand of record or enumeration type. Also, the only other
9838 // overloaded operator with enumeration arguments, operator=,
9839 // cannot be overloaded for enumeration types, so this is the only place
9840 // where we must suppress candidates like this.
9841 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9842 UserDefinedBinaryOperators;
9843
9844 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9845 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9846 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9847 CEnd = CandidateSet.end();
9848 C != CEnd; ++C) {
9849 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9850 continue;
9851
9852 if (C->Function->isFunctionTemplateSpecialization())
9853 continue;
9854
9855 // We interpret "same parameter-type-list" as applying to the
9856 // "synthesized candidate, with the order of the two parameters
9857 // reversed", not to the original function.
9858 bool Reversed = C->isReversed();
9859 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9860 ->getType()
9861 .getUnqualifiedType();
9862 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9863 ->getType()
9864 .getUnqualifiedType();
9865
9866 // Skip if either parameter isn't of enumeral type.
9867 if (!FirstParamType->isEnumeralType() ||
9868 !SecondParamType->isEnumeralType())
9869 continue;
9870
9871 // Add this operator to the set of known user-defined operators.
9872 UserDefinedBinaryOperators.insert(
9873 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9874 S.Context.getCanonicalType(SecondParamType)));
9875 }
9876 }
9877 }
9878
9879 /// Set of (canonical) types that we've already handled.
9880 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9881
9882 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9883 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9884 // Don't add the same builtin candidate twice.
9885 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9886 continue;
9887 if (IsSpaceship && PtrTy->isFunctionPointerType())
9888 continue;
9889
9890 QualType ParamTypes[2] = {PtrTy, PtrTy};
9891 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9892 }
9893 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9894 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9895
9896 // Don't add the same builtin candidate twice, or if a user defined
9897 // candidate exists.
9898 if (!AddedTypes.insert(CanonType).second ||
9899 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9900 CanonType)))
9901 continue;
9902 QualType ParamTypes[2] = {EnumTy, EnumTy};
9903 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9904 }
9905 }
9906 }
9907
9908 // C++ [over.built]p13:
9909 //
9910 // For every cv-qualified or cv-unqualified object type T
9911 // there exist candidate operator functions of the form
9912 //
9913 // T* operator+(T*, ptrdiff_t);
9914 // T& operator[](T*, ptrdiff_t); [BELOW]
9915 // T* operator-(T*, ptrdiff_t);
9916 // T* operator+(ptrdiff_t, T*);
9917 // T& operator[](ptrdiff_t, T*); [BELOW]
9918 //
9919 // C++ [over.built]p14:
9920 //
9921 // For every T, where T is a pointer to object type, there
9922 // exist candidate operator functions of the form
9923 //
9924 // ptrdiff_t operator-(T, T);
9925 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9926 /// Set of (canonical) types that we've already handled.
9927 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9928
9929 for (int Arg = 0; Arg < 2; ++Arg) {
9930 QualType AsymmetricParamTypes[2] = {
9933 };
9934 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9935 QualType PointeeTy = PtrTy->getPointeeType();
9936 if (!PointeeTy->isObjectType())
9937 continue;
9938
9939 AsymmetricParamTypes[Arg] = PtrTy;
9940 if (Arg == 0 || Op == OO_Plus) {
9941 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9942 // T* operator+(ptrdiff_t, T*);
9943 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9944 }
9945 if (Op == OO_Minus) {
9946 // ptrdiff_t operator-(T, T);
9947 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9948 continue;
9949
9950 QualType ParamTypes[2] = {PtrTy, PtrTy};
9951 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9952 }
9953 }
9954 }
9955 }
9956
9957 // C++ [over.built]p12:
9958 //
9959 // For every pair of promoted arithmetic types L and R, there
9960 // exist candidate operator functions of the form
9961 //
9962 // LR operator*(L, R);
9963 // LR operator/(L, R);
9964 // LR operator+(L, R);
9965 // LR operator-(L, R);
9966 // bool operator<(L, R);
9967 // bool operator>(L, R);
9968 // bool operator<=(L, R);
9969 // bool operator>=(L, R);
9970 // bool operator==(L, R);
9971 // bool operator!=(L, R);
9972 //
9973 // where LR is the result of the usual arithmetic conversions
9974 // between types L and R.
9975 //
9976 // C++ [over.built]p24:
9977 //
9978 // For every pair of promoted arithmetic types L and R, there exist
9979 // candidate operator functions of the form
9980 //
9981 // LR operator?(bool, L, R);
9982 //
9983 // where LR is the result of the usual arithmetic conversions
9984 // between types L and R.
9985 // Our candidates ignore the first parameter.
9986 void addGenericBinaryArithmeticOverloads() {
9987 if (!HasArithmeticOrEnumeralCandidateType)
9988 return;
9989
9990 for (unsigned Left = FirstPromotedArithmeticType;
9991 Left < LastPromotedArithmeticType; ++Left) {
9992 for (unsigned Right = FirstPromotedArithmeticType;
9993 Right < LastPromotedArithmeticType; ++Right) {
9994 QualType LandR[2] = { ArithmeticTypes[Left],
9995 ArithmeticTypes[Right] };
9996 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9997 }
9998 }
9999
10000 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
10001 // conditional operator for vector types.
10002 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10003 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
10004 QualType LandR[2] = {Vec1Ty, Vec2Ty};
10005 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10006 }
10007 }
10008
10009 /// Add binary operator overloads for each candidate matrix type M1, M2:
10010 /// * (M1, M1) -> M1
10011 /// * (M1, M1.getElementType()) -> M1
10012 /// * (M2.getElementType(), M2) -> M2
10013 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
10014 void addMatrixBinaryArithmeticOverloads() {
10015 if (!HasArithmeticOrEnumeralCandidateType)
10016 return;
10017
10018 for (QualType M1 : CandidateTypes[0].matrix_types()) {
10019 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
10020 AddCandidate(M1, M1);
10021 }
10022
10023 for (QualType M2 : CandidateTypes[1].matrix_types()) {
10024 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
10025 if (!CandidateTypes[0].containsMatrixType(M2))
10026 AddCandidate(M2, M2);
10027 }
10028 }
10029
10030 // C++2a [over.built]p14:
10031 //
10032 // For every integral type T there exists a candidate operator function
10033 // of the form
10034 //
10035 // std::strong_ordering operator<=>(T, T)
10036 //
10037 // C++2a [over.built]p15:
10038 //
10039 // For every pair of floating-point types L and R, there exists a candidate
10040 // operator function of the form
10041 //
10042 // std::partial_ordering operator<=>(L, R);
10043 //
10044 // FIXME: The current specification for integral types doesn't play nice with
10045 // the direction of p0946r0, which allows mixed integral and unscoped-enum
10046 // comparisons. Under the current spec this can lead to ambiguity during
10047 // overload resolution. For example:
10048 //
10049 // enum A : int {a};
10050 // auto x = (a <=> (long)42);
10051 //
10052 // error: call is ambiguous for arguments 'A' and 'long'.
10053 // note: candidate operator<=>(int, int)
10054 // note: candidate operator<=>(long, long)
10055 //
10056 // To avoid this error, this function deviates from the specification and adds
10057 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
10058 // arithmetic types (the same as the generic relational overloads).
10059 //
10060 // For now this function acts as a placeholder.
10061 void addThreeWayArithmeticOverloads() {
10062 addGenericBinaryArithmeticOverloads();
10063 }
10064
10065 // C++ [over.built]p17:
10066 //
10067 // For every pair of promoted integral types L and R, there
10068 // exist candidate operator functions of the form
10069 //
10070 // LR operator%(L, R);
10071 // LR operator&(L, R);
10072 // LR operator^(L, R);
10073 // LR operator|(L, R);
10074 // L operator<<(L, R);
10075 // L operator>>(L, R);
10076 //
10077 // where LR is the result of the usual arithmetic conversions
10078 // between types L and R.
10079 void addBinaryBitwiseArithmeticOverloads() {
10080 if (!HasArithmeticOrEnumeralCandidateType)
10081 return;
10082
10083 for (unsigned Left = FirstPromotedIntegralType;
10084 Left < LastPromotedIntegralType; ++Left) {
10085 for (unsigned Right = FirstPromotedIntegralType;
10086 Right < LastPromotedIntegralType; ++Right) {
10087 QualType LandR[2] = { ArithmeticTypes[Left],
10088 ArithmeticTypes[Right] };
10089 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
10090 }
10091 }
10092 }
10093
10094 // C++ [over.built]p20:
10095 //
10096 // For every pair (T, VQ), where T is an enumeration or
10097 // pointer to member type and VQ is either volatile or
10098 // empty, there exist candidate operator functions of the form
10099 //
10100 // VQ T& operator=(VQ T&, T);
10101 void addAssignmentMemberPointerOrEnumeralOverloads() {
10102 /// Set of (canonical) types that we've already handled.
10103 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10104
10105 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10106 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10107 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10108 continue;
10109
10110 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
10111 }
10112
10113 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10114 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10115 continue;
10116
10117 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
10118 }
10119 }
10120 }
10121
10122 // C++ [over.built]p19:
10123 //
10124 // For every pair (T, VQ), where T is any type and VQ is either
10125 // volatile or empty, there exist candidate operator functions
10126 // of the form
10127 //
10128 // T*VQ& operator=(T*VQ&, T*);
10129 //
10130 // C++ [over.built]p21:
10131 //
10132 // For every pair (T, VQ), where T is a cv-qualified or
10133 // cv-unqualified object type and VQ is either volatile or
10134 // empty, there exist candidate operator functions of the form
10135 //
10136 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
10137 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
10138 void addAssignmentPointerOverloads(bool isEqualOp) {
10139 /// Set of (canonical) types that we've already handled.
10140 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10141
10142 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10143 // If this is operator=, keep track of the builtin candidates we added.
10144 if (isEqualOp)
10145 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
10146 else if (!PtrTy->getPointeeType()->isObjectType())
10147 continue;
10148
10149 // non-volatile version
10150 QualType ParamTypes[2] = {
10152 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
10153 };
10154 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10155 /*IsAssignmentOperator=*/ isEqualOp);
10156
10157 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10158 VisibleTypeConversionsQuals.hasVolatile();
10159 if (NeedVolatile) {
10160 // volatile version
10161 ParamTypes[0] =
10163 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10164 /*IsAssignmentOperator=*/isEqualOp);
10165 }
10166
10167 if (!PtrTy.isRestrictQualified() &&
10168 VisibleTypeConversionsQuals.hasRestrict()) {
10169 // restrict version
10170 ParamTypes[0] =
10172 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10173 /*IsAssignmentOperator=*/isEqualOp);
10174
10175 if (NeedVolatile) {
10176 // volatile restrict version
10177 ParamTypes[0] =
10180 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10181 /*IsAssignmentOperator=*/isEqualOp);
10182 }
10183 }
10184 }
10185
10186 if (isEqualOp) {
10187 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10188 // Make sure we don't add the same candidate twice.
10189 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10190 continue;
10191
10192 QualType ParamTypes[2] = {
10194 PtrTy,
10195 };
10196
10197 // non-volatile version
10198 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10199 /*IsAssignmentOperator=*/true);
10200
10201 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
10202 VisibleTypeConversionsQuals.hasVolatile();
10203 if (NeedVolatile) {
10204 // volatile version
10205 ParamTypes[0] = S.Context.getLValueReferenceType(
10206 S.Context.getVolatileType(PtrTy));
10207 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10208 /*IsAssignmentOperator=*/true);
10209 }
10210
10211 if (!PtrTy.isRestrictQualified() &&
10212 VisibleTypeConversionsQuals.hasRestrict()) {
10213 // restrict version
10214 ParamTypes[0] = S.Context.getLValueReferenceType(
10215 S.Context.getRestrictType(PtrTy));
10216 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10217 /*IsAssignmentOperator=*/true);
10218
10219 if (NeedVolatile) {
10220 // volatile restrict version
10221 ParamTypes[0] =
10224 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10225 /*IsAssignmentOperator=*/true);
10226 }
10227 }
10228 }
10229 }
10230 }
10231
10232 // C++ [over.built]p18:
10233 //
10234 // For every triple (L, VQ, R), where L is an arithmetic type,
10235 // VQ is either volatile or empty, and R is a promoted
10236 // arithmetic type, there exist candidate operator functions of
10237 // the form
10238 //
10239 // VQ L& operator=(VQ L&, R);
10240 // VQ L& operator*=(VQ L&, R);
10241 // VQ L& operator/=(VQ L&, R);
10242 // VQ L& operator+=(VQ L&, R);
10243 // VQ L& operator-=(VQ L&, R);
10244 void addAssignmentArithmeticOverloads(bool isEqualOp) {
10245 if (!HasArithmeticOrEnumeralCandidateType)
10246 return;
10247
10248 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
10249 for (unsigned Right = FirstPromotedArithmeticType;
10250 Right < LastPromotedArithmeticType; ++Right) {
10251 QualType ParamTypes[2];
10252 ParamTypes[1] = ArithmeticTypes[Right];
10254 S, ArithmeticTypes[Left], Args[0]);
10255
10257 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10258 ParamTypes[0] =
10259 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10260 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10261 /*IsAssignmentOperator=*/isEqualOp);
10262 });
10263 }
10264 }
10265
10266 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10267 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10268 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10269 QualType ParamTypes[2];
10270 ParamTypes[1] = Vec2Ty;
10271 // Add this built-in operator as a candidate (VQ is empty).
10272 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
10273 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10274 /*IsAssignmentOperator=*/isEqualOp);
10275
10276 // Add this built-in operator as a candidate (VQ is 'volatile').
10277 if (VisibleTypeConversionsQuals.hasVolatile()) {
10278 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
10279 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
10280 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10281 /*IsAssignmentOperator=*/isEqualOp);
10282 }
10283 }
10284 }
10285
10286 // C++ [over.built]p22:
10287 //
10288 // For every triple (L, VQ, R), where L is an integral type, VQ
10289 // is either volatile or empty, and R is a promoted integral
10290 // type, there exist candidate operator functions of the form
10291 //
10292 // VQ L& operator%=(VQ L&, R);
10293 // VQ L& operator<<=(VQ L&, R);
10294 // VQ L& operator>>=(VQ L&, R);
10295 // VQ L& operator&=(VQ L&, R);
10296 // VQ L& operator^=(VQ L&, R);
10297 // VQ L& operator|=(VQ L&, R);
10298 void addAssignmentIntegralOverloads() {
10299 if (!HasArithmeticOrEnumeralCandidateType)
10300 return;
10301
10302 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10303 for (unsigned Right = FirstPromotedIntegralType;
10304 Right < LastPromotedIntegralType; ++Right) {
10305 QualType ParamTypes[2];
10306 ParamTypes[1] = ArithmeticTypes[Right];
10308 S, ArithmeticTypes[Left], Args[0]);
10309
10311 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10312 ParamTypes[0] =
10313 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10314 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10315 });
10316 }
10317 }
10318 }
10319
10320 // C++ [over.operator]p23:
10321 //
10322 // There also exist candidate operator functions of the form
10323 //
10324 // bool operator!(bool);
10325 // bool operator&&(bool, bool);
10326 // bool operator||(bool, bool);
10327 void addExclaimOverload() {
10328 QualType ParamTy = S.Context.BoolTy;
10329 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
10330 /*IsAssignmentOperator=*/false,
10331 /*NumContextualBoolArguments=*/1);
10332 }
10333 void addAmpAmpOrPipePipeOverload() {
10334 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10335 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10336 /*IsAssignmentOperator=*/false,
10337 /*NumContextualBoolArguments=*/2);
10338 }
10339
10340 // C++ [over.built]p13:
10341 //
10342 // For every cv-qualified or cv-unqualified object type T there
10343 // exist candidate operator functions of the form
10344 //
10345 // T* operator+(T*, ptrdiff_t); [ABOVE]
10346 // T& operator[](T*, ptrdiff_t);
10347 // T* operator-(T*, ptrdiff_t); [ABOVE]
10348 // T* operator+(ptrdiff_t, T*); [ABOVE]
10349 // T& operator[](ptrdiff_t, T*);
10350 void addSubscriptOverloads() {
10351 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10352 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10353 QualType PointeeType = PtrTy->getPointeeType();
10354 if (!PointeeType->isObjectType())
10355 continue;
10356
10357 // T& operator[](T*, ptrdiff_t)
10358 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10359 }
10360
10361 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10362 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10363 QualType PointeeType = PtrTy->getPointeeType();
10364 if (!PointeeType->isObjectType())
10365 continue;
10366
10367 // T& operator[](ptrdiff_t, T*)
10368 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10369 }
10370 }
10371
10372 // C++ [over.built]p11:
10373 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10374 // C1 is the same type as C2 or is a derived class of C2, T is an object
10375 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10376 // there exist candidate operator functions of the form
10377 //
10378 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10379 //
10380 // where CV12 is the union of CV1 and CV2.
10381 void addArrowStarOverloads() {
10382 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10383 QualType C1Ty = PtrTy;
10384 QualType C1;
10385 QualifierCollector Q1;
10386 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
10387 if (!isa<RecordType>(C1))
10388 continue;
10389 // heuristic to reduce number of builtin candidates in the set.
10390 // Add volatile/restrict version only if there are conversions to a
10391 // volatile/restrict type.
10392 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10393 continue;
10394 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10395 continue;
10396 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10397 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
10398 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10399 *D2 = mptr->getMostRecentCXXRecordDecl();
10400 if (!declaresSameEntity(D1, D2) &&
10401 !S.IsDerivedFrom(CandidateSet.getLocation(), D1, D2))
10402 break;
10403 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10404 // build CV12 T&
10405 QualType T = mptr->getPointeeType();
10406 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10408 continue;
10409 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10411 continue;
10412 T = Q1.apply(S.Context, T);
10413 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10414 }
10415 }
10416 }
10417
10418 // Note that we don't consider the first argument, since it has been
10419 // contextually converted to bool long ago. The candidates below are
10420 // therefore added as binary.
10421 //
10422 // C++ [over.built]p25:
10423 // For every type T, where T is a pointer, pointer-to-member, or scoped
10424 // enumeration type, there exist candidate operator functions of the form
10425 //
10426 // T operator?(bool, T, T);
10427 //
10428 void addConditionalOperatorOverloads() {
10429 /// Set of (canonical) types that we've already handled.
10430 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10431
10432 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10433 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10434 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10435 continue;
10436
10437 QualType ParamTypes[2] = {PtrTy, PtrTy};
10438 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10439 }
10440
10441 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10442 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10443 continue;
10444
10445 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10446 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10447 }
10448
10449 if (S.getLangOpts().CPlusPlus11) {
10450 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10451 if (!EnumTy->castAsCanonical<EnumType>()->getDecl()->isScoped())
10452 continue;
10453
10454 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10455 continue;
10456
10457 QualType ParamTypes[2] = {EnumTy, EnumTy};
10458 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10459 }
10460 }
10461 }
10462 }
10463};
10464
10465} // end anonymous namespace
10466
10468 SourceLocation OpLoc,
10469 ArrayRef<Expr *> Args,
10470 OverloadCandidateSet &CandidateSet) {
10471 // Find all of the types that the arguments can convert to, but only
10472 // if the operator we're looking at has built-in operator candidates
10473 // that make use of these types. Also record whether we encounter non-record
10474 // candidate types or either arithmetic or enumeral candidate types.
10475 QualifiersAndAtomic VisibleTypeConversionsQuals;
10476 VisibleTypeConversionsQuals.addConst();
10477 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10478 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
10479 if (Args[ArgIdx]->getType()->isAtomicType())
10480 VisibleTypeConversionsQuals.addAtomic();
10481 }
10482
10483 bool HasNonRecordCandidateType = false;
10484 bool HasArithmeticOrEnumeralCandidateType = false;
10486 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10487 CandidateTypes.emplace_back(*this);
10488 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
10489 OpLoc,
10490 true,
10491 (Op == OO_Exclaim ||
10492 Op == OO_AmpAmp ||
10493 Op == OO_PipePipe),
10494 VisibleTypeConversionsQuals);
10495 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10496 CandidateTypes[ArgIdx].hasNonRecordTypes();
10497 HasArithmeticOrEnumeralCandidateType =
10498 HasArithmeticOrEnumeralCandidateType ||
10499 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10500 }
10501
10502 // Exit early when no non-record types have been added to the candidate set
10503 // for any of the arguments to the operator.
10504 //
10505 // We can't exit early for !, ||, or &&, since there we have always have
10506 // 'bool' overloads.
10507 if (!HasNonRecordCandidateType &&
10508 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10509 return;
10510
10511 // Setup an object to manage the common state for building overloads.
10512 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10513 VisibleTypeConversionsQuals,
10514 HasArithmeticOrEnumeralCandidateType,
10515 CandidateTypes, CandidateSet);
10516
10517 // Dispatch over the operation to add in only those overloads which apply.
10518 switch (Op) {
10519 case OO_None:
10521 llvm_unreachable("Expected an overloaded operator");
10522
10523 case OO_New:
10524 case OO_Delete:
10525 case OO_Array_New:
10526 case OO_Array_Delete:
10527 case OO_Call:
10528 llvm_unreachable(
10529 "Special operators don't use AddBuiltinOperatorCandidates");
10530
10531 case OO_Comma:
10532 case OO_Arrow:
10533 case OO_Coawait:
10534 // C++ [over.match.oper]p3:
10535 // -- For the operator ',', the unary operator '&', the
10536 // operator '->', or the operator 'co_await', the
10537 // built-in candidates set is empty.
10538 break;
10539
10540 case OO_Plus: // '+' is either unary or binary
10541 if (Args.size() == 1)
10542 OpBuilder.addUnaryPlusPointerOverloads();
10543 [[fallthrough]];
10544
10545 case OO_Minus: // '-' is either unary or binary
10546 if (Args.size() == 1) {
10547 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10548 } else {
10549 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10550 OpBuilder.addGenericBinaryArithmeticOverloads();
10551 OpBuilder.addMatrixBinaryArithmeticOverloads();
10552 }
10553 break;
10554
10555 case OO_Star: // '*' is either unary or binary
10556 if (Args.size() == 1)
10557 OpBuilder.addUnaryStarPointerOverloads();
10558 else {
10559 OpBuilder.addGenericBinaryArithmeticOverloads();
10560 OpBuilder.addMatrixBinaryArithmeticOverloads();
10561 }
10562 break;
10563
10564 case OO_Slash:
10565 OpBuilder.addGenericBinaryArithmeticOverloads();
10566 break;
10567
10568 case OO_PlusPlus:
10569 case OO_MinusMinus:
10570 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10571 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10572 break;
10573
10574 case OO_EqualEqual:
10575 case OO_ExclaimEqual:
10576 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10577 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10578 OpBuilder.addGenericBinaryArithmeticOverloads();
10579 break;
10580
10581 case OO_Less:
10582 case OO_Greater:
10583 case OO_LessEqual:
10584 case OO_GreaterEqual:
10585 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10586 OpBuilder.addGenericBinaryArithmeticOverloads();
10587 break;
10588
10589 case OO_Spaceship:
10590 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10591 OpBuilder.addThreeWayArithmeticOverloads();
10592 break;
10593
10594 case OO_Percent:
10595 case OO_Caret:
10596 case OO_Pipe:
10597 case OO_LessLess:
10598 case OO_GreaterGreater:
10599 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10600 break;
10601
10602 case OO_Amp: // '&' is either unary or binary
10603 if (Args.size() == 1)
10604 // C++ [over.match.oper]p3:
10605 // -- For the operator ',', the unary operator '&', or the
10606 // operator '->', the built-in candidates set is empty.
10607 break;
10608
10609 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10610 break;
10611
10612 case OO_Tilde:
10613 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10614 break;
10615
10616 case OO_Equal:
10617 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10618 [[fallthrough]];
10619
10620 case OO_PlusEqual:
10621 case OO_MinusEqual:
10622 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10623 [[fallthrough]];
10624
10625 case OO_StarEqual:
10626 case OO_SlashEqual:
10627 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10628 break;
10629
10630 case OO_PercentEqual:
10631 case OO_LessLessEqual:
10632 case OO_GreaterGreaterEqual:
10633 case OO_AmpEqual:
10634 case OO_CaretEqual:
10635 case OO_PipeEqual:
10636 OpBuilder.addAssignmentIntegralOverloads();
10637 break;
10638
10639 case OO_Exclaim:
10640 OpBuilder.addExclaimOverload();
10641 break;
10642
10643 case OO_AmpAmp:
10644 case OO_PipePipe:
10645 OpBuilder.addAmpAmpOrPipePipeOverload();
10646 break;
10647
10648 case OO_Subscript:
10649 if (Args.size() == 2)
10650 OpBuilder.addSubscriptOverloads();
10651 break;
10652
10653 case OO_ArrowStar:
10654 OpBuilder.addArrowStarOverloads();
10655 break;
10656
10657 case OO_Conditional:
10658 OpBuilder.addConditionalOperatorOverloads();
10659 OpBuilder.addGenericBinaryArithmeticOverloads();
10660 break;
10661 }
10662}
10663
10664void
10666 SourceLocation Loc,
10667 ArrayRef<Expr *> Args,
10668 TemplateArgumentListInfo *ExplicitTemplateArgs,
10669 OverloadCandidateSet& CandidateSet,
10670 bool PartialOverloading) {
10671 ADLResult Fns;
10672
10673 // FIXME: This approach for uniquing ADL results (and removing
10674 // redundant candidates from the set) relies on pointer-equality,
10675 // which means we need to key off the canonical decl. However,
10676 // always going back to the canonical decl might not get us the
10677 // right set of default arguments. What default arguments are
10678 // we supposed to consider on ADL candidates, anyway?
10679
10680 // FIXME: Pass in the explicit template arguments?
10681 ArgumentDependentLookup(Name, Loc, Args, Fns);
10682
10683 ArrayRef<Expr *> ReversedArgs;
10684
10685 // Erase all of the candidates we already knew about.
10686 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10687 CandEnd = CandidateSet.end();
10688 Cand != CandEnd; ++Cand)
10689 if (Cand->Function) {
10690 FunctionDecl *Fn = Cand->Function;
10691 Fns.erase(Fn);
10692 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10693 Fns.erase(FunTmpl);
10694 }
10695
10696 // For each of the ADL candidates we found, add it to the overload
10697 // set.
10698 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10700
10701 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10702 if (ExplicitTemplateArgs)
10703 continue;
10704
10706 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10707 PartialOverloading, /*AllowExplicit=*/true,
10708 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10709 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10711 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10712 /*SuppressUserConversions=*/false, PartialOverloading,
10713 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10714 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10715 }
10716 } else {
10717 auto *FTD = cast<FunctionTemplateDecl>(*I);
10719 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10720 /*SuppressUserConversions=*/false, PartialOverloading,
10721 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10722 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10723 *this, Args, FTD->getTemplatedDecl())) {
10724
10725 // As template candidates are not deduced immediately,
10726 // persist the array in the overload set.
10727 if (ReversedArgs.empty())
10728 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
10729
10731 FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs, CandidateSet,
10732 /*SuppressUserConversions=*/false, PartialOverloading,
10733 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10735 }
10736 }
10737 }
10738}
10739
10740namespace {
10741enum class Comparison { Equal, Better, Worse };
10742}
10743
10744/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10745/// overload resolution.
10746///
10747/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10748/// Cand1's first N enable_if attributes have precisely the same conditions as
10749/// Cand2's first N enable_if attributes (where N = the number of enable_if
10750/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10751///
10752/// Note that you can have a pair of candidates such that Cand1's enable_if
10753/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10754/// worse than Cand1's.
10755static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10756 const FunctionDecl *Cand2) {
10757 // Common case: One (or both) decls don't have enable_if attrs.
10758 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10759 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10760 if (!Cand1Attr || !Cand2Attr) {
10761 if (Cand1Attr == Cand2Attr)
10762 return Comparison::Equal;
10763 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10764 }
10765
10766 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10767 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10768
10769 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10770 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10771 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10772 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10773
10774 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10775 // has fewer enable_if attributes than Cand2, and vice versa.
10776 if (!Cand1A)
10777 return Comparison::Worse;
10778 if (!Cand2A)
10779 return Comparison::Better;
10780
10781 Cand1ID.clear();
10782 Cand2ID.clear();
10783
10784 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10785 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10786 if (Cand1ID != Cand2ID)
10787 return Comparison::Worse;
10788 }
10789
10790 return Comparison::Equal;
10791}
10792
10793static Comparison
10795 const OverloadCandidate &Cand2) {
10796 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10797 !Cand2.Function->isMultiVersion())
10798 return Comparison::Equal;
10799
10800 // If both are invalid, they are equal. If one of them is invalid, the other
10801 // is better.
10802 if (Cand1.Function->isInvalidDecl()) {
10803 if (Cand2.Function->isInvalidDecl())
10804 return Comparison::Equal;
10805 return Comparison::Worse;
10806 }
10807 if (Cand2.Function->isInvalidDecl())
10808 return Comparison::Better;
10809
10810 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10811 // cpu_dispatch, else arbitrarily based on the identifiers.
10812 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10813 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10814 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10815 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10816
10817 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10818 return Comparison::Equal;
10819
10820 if (Cand1CPUDisp && !Cand2CPUDisp)
10821 return Comparison::Better;
10822 if (Cand2CPUDisp && !Cand1CPUDisp)
10823 return Comparison::Worse;
10824
10825 if (Cand1CPUSpec && Cand2CPUSpec) {
10826 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10827 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10828 ? Comparison::Better
10829 : Comparison::Worse;
10830
10831 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10832 FirstDiff = std::mismatch(
10833 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10834 Cand2CPUSpec->cpus_begin(),
10835 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10836 return LHS->getName() == RHS->getName();
10837 });
10838
10839 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10840 "Two different cpu-specific versions should not have the same "
10841 "identifier list, otherwise they'd be the same decl!");
10842 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10843 ? Comparison::Better
10844 : Comparison::Worse;
10845 }
10846 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10847}
10848
10849/// Compute the type of the implicit object parameter for the given function,
10850/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10851/// null QualType if there is a 'matches anything' implicit object parameter.
10852static std::optional<QualType>
10855 return std::nullopt;
10856
10857 auto *M = cast<CXXMethodDecl>(F);
10858 // Static member functions' object parameters match all types.
10859 if (M->isStatic())
10860 return QualType();
10861 return M->getFunctionObjectParameterReferenceType();
10862}
10863
10864// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10865// represent the same entity.
10866static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10867 const FunctionDecl *F2) {
10868 if (declaresSameEntity(F1, F2))
10869 return true;
10870 auto PT1 = F1->getPrimaryTemplate();
10871 auto PT2 = F2->getPrimaryTemplate();
10872 if (PT1 && PT2) {
10873 if (declaresSameEntity(PT1, PT2) ||
10874 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10875 PT2->getInstantiatedFromMemberTemplate()))
10876 return true;
10877 }
10878 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10879 // different functions with same params). Consider removing this (as no test
10880 // fail w/o it).
10881 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10882 if (First) {
10883 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10884 return *T;
10885 }
10886 assert(I < F->getNumParams());
10887 return F->getParamDecl(I++)->getType();
10888 };
10889
10890 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10891 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10892
10893 if (F1NumParams != F2NumParams)
10894 return false;
10895
10896 unsigned I1 = 0, I2 = 0;
10897 for (unsigned I = 0; I != F1NumParams; ++I) {
10898 QualType T1 = NextParam(F1, I1, I == 0);
10899 QualType T2 = NextParam(F2, I2, I == 0);
10900 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10901 if (!Context.hasSameUnqualifiedType(T1, T2))
10902 return false;
10903 }
10904 return true;
10905}
10906
10907/// We're allowed to use constraints partial ordering only if the candidates
10908/// have the same parameter types:
10909/// [over.match.best.general]p2.6
10910/// F1 and F2 are non-template functions with the same
10911/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10913 FunctionDecl *Fn2,
10914 bool IsFn1Reversed,
10915 bool IsFn2Reversed) {
10916 assert(Fn1 && Fn2);
10917 if (Fn1->isVariadic() != Fn2->isVariadic())
10918 return false;
10919
10920 if (!S.FunctionNonObjectParamTypesAreEqual(Fn1, Fn2, nullptr,
10921 IsFn1Reversed ^ IsFn2Reversed))
10922 return false;
10923
10924 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10925 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10926 if (Mem1 && Mem2) {
10927 // if they are member functions, both are direct members of the same class,
10928 // and
10929 if (Mem1->getParent() != Mem2->getParent())
10930 return false;
10931 // if both are non-static member functions, they have the same types for
10932 // their object parameters
10933 if (Mem1->isInstance() && Mem2->isInstance() &&
10935 Mem1->getFunctionObjectParameterReferenceType(),
10936 Mem1->getFunctionObjectParameterReferenceType()))
10937 return false;
10938 }
10939 return true;
10940}
10941
10942static FunctionDecl *
10944 bool IsFn1Reversed, bool IsFn2Reversed) {
10945 if (!Fn1 || !Fn2)
10946 return nullptr;
10947
10948 // C++ [temp.constr.order]:
10949 // A non-template function F1 is more partial-ordering-constrained than a
10950 // non-template function F2 if:
10951 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10952 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10953
10954 if (Cand1IsSpecialization || Cand2IsSpecialization)
10955 return nullptr;
10956
10957 // - they have the same non-object-parameter-type-lists, and [...]
10958 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10959 IsFn2Reversed))
10960 return nullptr;
10961
10962 // - the declaration of F1 is more constrained than the declaration of F2.
10963 return S.getMoreConstrainedFunction(Fn1, Fn2);
10964}
10965
10966/// isBetterOverloadCandidate - Determines whether the first overload
10967/// candidate is a better candidate than the second (C++ 13.3.3p1).
10969 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10971 bool PartialOverloading) {
10972 // Define viable functions to be better candidates than non-viable
10973 // functions.
10974 if (!Cand2.Viable)
10975 return Cand1.Viable;
10976 else if (!Cand1.Viable)
10977 return false;
10978
10979 // [CUDA] A function with 'never' preference is marked not viable, therefore
10980 // is never shown up here. The worst preference shown up here is 'wrong side',
10981 // e.g. an H function called by a HD function in device compilation. This is
10982 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10983 // function which is called only by an H function. A deferred diagnostic will
10984 // be triggered if it is emitted. However a wrong-sided function is still
10985 // a viable candidate here.
10986 //
10987 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10988 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10989 // can be emitted, Cand1 is not better than Cand2. This rule should have
10990 // precedence over other rules.
10991 //
10992 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10993 // other rules should be used to determine which is better. This is because
10994 // host/device based overloading resolution is mostly for determining
10995 // viability of a function. If two functions are both viable, other factors
10996 // should take precedence in preference, e.g. the standard-defined preferences
10997 // like argument conversion ranks or enable_if partial-ordering. The
10998 // preference for pass-object-size parameters is probably most similar to a
10999 // type-based-overloading decision and so should take priority.
11000 //
11001 // If other rules cannot determine which is better, CUDA preference will be
11002 // used again to determine which is better.
11003 //
11004 // TODO: Currently IdentifyPreference does not return correct values
11005 // for functions called in global variable initializers due to missing
11006 // correct context about device/host. Therefore we can only enforce this
11007 // rule when there is a caller. We should enforce this rule for functions
11008 // in global variable initializers once proper context is added.
11009 //
11010 // TODO: We can only enable the hostness based overloading resolution when
11011 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
11012 // overloading resolution diagnostics.
11013 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
11014 S.getLangOpts().GPUExcludeWrongSideOverloads) {
11015 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
11016 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
11017 bool IsCand1ImplicitHD =
11019 bool IsCand2ImplicitHD =
11021 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
11022 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11023 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
11024 // The implicit HD function may be a function in a system header which
11025 // is forced by pragma. In device compilation, if we prefer HD candidates
11026 // over wrong-sided candidates, overloading resolution may change, which
11027 // may result in non-deferrable diagnostics. As a workaround, we let
11028 // implicit HD candidates take equal preference as wrong-sided candidates.
11029 // This will preserve the overloading resolution.
11030 // TODO: We still need special handling of implicit HD functions since
11031 // they may incur other diagnostics to be deferred. We should make all
11032 // host/device related diagnostics deferrable and remove special handling
11033 // of implicit HD functions.
11034 auto EmitThreshold =
11035 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
11036 (IsCand1ImplicitHD || IsCand2ImplicitHD))
11039 auto Cand1Emittable = P1 > EmitThreshold;
11040 auto Cand2Emittable = P2 > EmitThreshold;
11041 if (Cand1Emittable && !Cand2Emittable)
11042 return true;
11043 if (!Cand1Emittable && Cand2Emittable)
11044 return false;
11045 }
11046 }
11047
11048 // C++ [over.match.best]p1: (Changed in C++23)
11049 //
11050 // -- if F is a static member function, ICS1(F) is defined such
11051 // that ICS1(F) is neither better nor worse than ICS1(G) for
11052 // any function G, and, symmetrically, ICS1(G) is neither
11053 // better nor worse than ICS1(F).
11054 unsigned StartArg = 0;
11055 if (!Cand1.TookAddressOfOverload &&
11057 StartArg = 1;
11058
11059 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
11060 // We don't allow incompatible pointer conversions in C++.
11061 if (!S.getLangOpts().CPlusPlus)
11062 return ICS.isStandard() &&
11063 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
11064
11065 // The only ill-formed conversion we allow in C++ is the string literal to
11066 // char* conversion, which is only considered ill-formed after C++11.
11067 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
11069 };
11070
11071 // Define functions that don't require ill-formed conversions for a given
11072 // argument to be better candidates than functions that do.
11073 unsigned NumArgs = Cand1.Conversions.size();
11074 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
11075 bool HasBetterConversion = false;
11076 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11077 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
11078 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
11079 if (Cand1Bad != Cand2Bad) {
11080 if (Cand1Bad)
11081 return false;
11082 HasBetterConversion = true;
11083 }
11084 }
11085
11086 if (HasBetterConversion)
11087 return true;
11088
11089 // C++ [over.match.best]p1:
11090 // A viable function F1 is defined to be a better function than another
11091 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
11092 // conversion sequence than ICSi(F2), and then...
11093 bool HasWorseConversion = false;
11094 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
11096 Cand1.Conversions[ArgIdx],
11097 Cand2.Conversions[ArgIdx])) {
11099 // Cand1 has a better conversion sequence.
11100 HasBetterConversion = true;
11101 break;
11102
11104 if (Cand1.Function && Cand2.Function &&
11105 Cand1.isReversed() != Cand2.isReversed() &&
11106 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
11107 // Work around large-scale breakage caused by considering reversed
11108 // forms of operator== in C++20:
11109 //
11110 // When comparing a function against a reversed function, if we have a
11111 // better conversion for one argument and a worse conversion for the
11112 // other, the implicit conversion sequences are treated as being equally
11113 // good.
11114 //
11115 // This prevents a comparison function from being considered ambiguous
11116 // with a reversed form that is written in the same way.
11117 //
11118 // We diagnose this as an extension from CreateOverloadedBinOp.
11119 HasWorseConversion = true;
11120 break;
11121 }
11122
11123 // Cand1 can't be better than Cand2.
11124 return false;
11125
11127 // Do nothing.
11128 break;
11129 }
11130 }
11131
11132 // -- for some argument j, ICSj(F1) is a better conversion sequence than
11133 // ICSj(F2), or, if not that,
11134 if (HasBetterConversion && !HasWorseConversion)
11135 return true;
11136
11137 // -- the context is an initialization by user-defined conversion
11138 // (see 8.5, 13.3.1.5) and the standard conversion sequence
11139 // from the return type of F1 to the destination type (i.e.,
11140 // the type of the entity being initialized) is a better
11141 // conversion sequence than the standard conversion sequence
11142 // from the return type of F2 to the destination type.
11144 Cand1.Function && Cand2.Function &&
11147
11148 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
11149 // First check whether we prefer one of the conversion functions over the
11150 // other. This only distinguishes the results in non-standard, extension
11151 // cases such as the conversion from a lambda closure type to a function
11152 // pointer or block.
11157 Cand1.FinalConversion,
11158 Cand2.FinalConversion);
11159
11162
11163 // FIXME: Compare kind of reference binding if conversion functions
11164 // convert to a reference type used in direct reference binding, per
11165 // C++14 [over.match.best]p1 section 2 bullet 3.
11166 }
11167
11168 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
11169 // as combined with the resolution to CWG issue 243.
11170 //
11171 // When the context is initialization by constructor ([over.match.ctor] or
11172 // either phase of [over.match.list]), a constructor is preferred over
11173 // a conversion function.
11174 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
11175 Cand1.Function && Cand2.Function &&
11178 return isa<CXXConstructorDecl>(Cand1.Function);
11179
11180 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
11181 return Cand2.StrictPackMatch;
11182
11183 // -- F1 is a non-template function and F2 is a function template
11184 // specialization, or, if not that,
11185 bool Cand1IsSpecialization = Cand1.Function &&
11187 bool Cand2IsSpecialization = Cand2.Function &&
11189 if (Cand1IsSpecialization != Cand2IsSpecialization)
11190 return Cand2IsSpecialization;
11191
11192 // -- F1 and F2 are function template specializations, and the function
11193 // template for F1 is more specialized than the template for F2
11194 // according to the partial ordering rules described in 14.5.5.2, or,
11195 // if not that,
11196 if (Cand1IsSpecialization && Cand2IsSpecialization) {
11197 const auto *Obj1Context =
11198 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
11199 const auto *Obj2Context =
11200 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
11201 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
11203 Cand2.Function->getPrimaryTemplate(), Loc,
11205 : TPOC_Call,
11207 Obj1Context ? S.Context.getCanonicalTagType(Obj1Context)
11208 : QualType{},
11209 Obj2Context ? S.Context.getCanonicalTagType(Obj2Context)
11210 : QualType{},
11211 Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
11212 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
11213 }
11214 }
11215
11216 // -— F1 and F2 are non-template functions and F1 is more
11217 // partial-ordering-constrained than F2 [...],
11219 S, Cand1.Function, Cand2.Function, Cand1.isReversed(),
11220 Cand2.isReversed());
11221 F && F == Cand1.Function)
11222 return true;
11223
11224 // -- F1 is a constructor for a class D, F2 is a constructor for a base
11225 // class B of D, and for all arguments the corresponding parameters of
11226 // F1 and F2 have the same type.
11227 // FIXME: Implement the "all parameters have the same type" check.
11228 bool Cand1IsInherited =
11229 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
11230 bool Cand2IsInherited =
11231 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
11232 if (Cand1IsInherited != Cand2IsInherited)
11233 return Cand2IsInherited;
11234 else if (Cand1IsInherited) {
11235 assert(Cand2IsInherited);
11236 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
11237 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
11238 if (Cand1Class->isDerivedFrom(Cand2Class))
11239 return true;
11240 if (Cand2Class->isDerivedFrom(Cand1Class))
11241 return false;
11242 // Inherited from sibling base classes: still ambiguous.
11243 }
11244
11245 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
11246 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
11247 // with reversed order of parameters and F1 is not
11248 //
11249 // We rank reversed + different operator as worse than just reversed, but
11250 // that comparison can never happen, because we only consider reversing for
11251 // the maximally-rewritten operator (== or <=>).
11252 if (Cand1.RewriteKind != Cand2.RewriteKind)
11253 return Cand1.RewriteKind < Cand2.RewriteKind;
11254
11255 // Check C++17 tie-breakers for deduction guides.
11256 {
11257 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
11258 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
11259 if (Guide1 && Guide2) {
11260 // -- F1 is generated from a deduction-guide and F2 is not
11261 if (Guide1->isImplicit() != Guide2->isImplicit())
11262 return Guide2->isImplicit();
11263
11264 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11265 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11266 return true;
11267 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11268 return false;
11269
11270 // --F1 is generated from a non-template constructor and F2 is generated
11271 // from a constructor template
11272 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11273 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11274 if (Constructor1 && Constructor2) {
11275 bool isC1Templated = Constructor1->getTemplatedKind() !=
11277 bool isC2Templated = Constructor2->getTemplatedKind() !=
11279 if (isC1Templated != isC2Templated)
11280 return isC2Templated;
11281 }
11282 }
11283 }
11284
11285 // Check for enable_if value-based overload resolution.
11286 if (Cand1.Function && Cand2.Function) {
11288 if (Cmp != Comparison::Equal)
11289 return Cmp == Comparison::Better;
11290 }
11291
11292 bool HasPS1 = Cand1.Function != nullptr &&
11294 bool HasPS2 = Cand2.Function != nullptr &&
11296 if (HasPS1 != HasPS2 && HasPS1)
11297 return true;
11298
11299 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11300 if (MV == Comparison::Better)
11301 return true;
11302 if (MV == Comparison::Worse)
11303 return false;
11304
11305 // If other rules cannot determine which is better, CUDA preference is used
11306 // to determine which is better.
11307 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11308 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11309 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
11310 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11311 }
11312
11313 // General member function overloading is handled above, so this only handles
11314 // constructors with address spaces.
11315 // This only handles address spaces since C++ has no other
11316 // qualifier that can be used with constructors.
11317 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
11318 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
11319 if (CD1 && CD2) {
11320 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11321 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11322 if (AS1 != AS2) {
11324 return true;
11326 return false;
11327 }
11328 }
11329
11330 return false;
11331}
11332
11333/// Determine whether two declarations are "equivalent" for the purposes of
11334/// name lookup and overload resolution. This applies when the same internal/no
11335/// linkage entity is defined by two modules (probably by textually including
11336/// the same header). In such a case, we don't consider the declarations to
11337/// declare the same entity, but we also don't want lookups with both
11338/// declarations visible to be ambiguous in some cases (this happens when using
11339/// a modularized libstdc++).
11341 const NamedDecl *B) {
11342 auto *VA = dyn_cast_or_null<ValueDecl>(A);
11343 auto *VB = dyn_cast_or_null<ValueDecl>(B);
11344 if (!VA || !VB)
11345 return false;
11346
11347 // The declarations must be declaring the same name as an internal linkage
11348 // entity in different modules.
11349 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11350 VB->getDeclContext()->getRedeclContext()) ||
11351 getOwningModule(VA) == getOwningModule(VB) ||
11352 VA->isExternallyVisible() || VB->isExternallyVisible())
11353 return false;
11354
11355 // Check that the declarations appear to be equivalent.
11356 //
11357 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11358 // For constants and functions, we should check the initializer or body is
11359 // the same. For non-constant variables, we shouldn't allow it at all.
11360 if (Context.hasSameType(VA->getType(), VB->getType()))
11361 return true;
11362
11363 // Enum constants within unnamed enumerations will have different types, but
11364 // may still be similar enough to be interchangeable for our purposes.
11365 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
11366 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
11367 // Only handle anonymous enums. If the enumerations were named and
11368 // equivalent, they would have been merged to the same type.
11369 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
11370 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
11371 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11372 !Context.hasSameType(EnumA->getIntegerType(),
11373 EnumB->getIntegerType()))
11374 return false;
11375 // Allow this only if the value is the same for both enumerators.
11376 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
11377 }
11378 }
11379
11380 // Nothing else is sufficiently similar.
11381 return false;
11382}
11383
11386 assert(D && "Unknown declaration");
11387 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11388
11389 Module *M = getOwningModule(D);
11390 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
11391 << !M << (M ? M->getFullModuleName() : "");
11392
11393 for (auto *E : Equiv) {
11394 Module *M = getOwningModule(E);
11395 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
11396 << !M << (M ? M->getFullModuleName() : "");
11397 }
11398}
11399
11402 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11404 static_cast<CNSInfo *>(DeductionFailure.Data)
11405 ->Satisfaction.ContainsErrors;
11406}
11407
11410 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11411 bool PartialOverloading, bool AllowExplicit,
11413 bool AggregateCandidateDeduction) {
11414
11415 auto *C =
11416 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11417
11420 /*AllowObjCConversionOnExplicit=*/false,
11421 /*AllowResultConversion=*/false, AllowExplicit, SuppressUserConversions,
11422 PartialOverloading, AggregateCandidateDeduction},
11424 FoundDecl,
11425 Args,
11426 IsADLCandidate,
11427 PO};
11428
11429 HasDeferredTemplateConstructors |=
11430 isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl());
11431}
11432
11434 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11435 CXXRecordDecl *ActingContext, QualType ObjectType,
11436 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11437 bool SuppressUserConversions, bool PartialOverloading,
11439
11440 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11441
11442 auto *C =
11443 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11444
11447 /*AllowObjCConversionOnExplicit=*/false,
11448 /*AllowResultConversion=*/false,
11449 /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,
11450 /*AggregateCandidateDeduction=*/false},
11451 MethodTmpl,
11452 FoundDecl,
11453 Args,
11454 ActingContext,
11455 ObjectClassification,
11456 ObjectType,
11457 PO};
11458}
11459
11462 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11463 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11464 bool AllowResultConversion) {
11465
11466 auto *C =
11467 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11468
11471 AllowObjCConversionOnExplicit, AllowResultConversion,
11472 /*AllowExplicit=*/false,
11473 /*SuppressUserConversions=*/false,
11474 /*PartialOverloading*/ false,
11475 /*AggregateCandidateDeduction=*/false},
11477 FoundDecl,
11478 ActingContext,
11479 From,
11480 ToType};
11481}
11482
11483static void
11486
11488 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,
11489 /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,
11490 C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);
11491}
11492
11493static void
11497 S, CandidateSet, C.FunctionTemplate, C.FoundDecl,
11498 /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions,
11499 C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO,
11500 C.AggregateCandidateDeduction);
11501}
11502
11503static void
11507 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
11508 C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
11509 C.AllowResultConversion);
11510}
11511
11513 Candidates.reserve(Candidates.size() + DeferredCandidatesCount);
11514 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11515 while (Cand) {
11516 switch (Cand->Kind) {
11519 S, *this,
11520 *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11521 break;
11524 S, *this,
11525 *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11526 break;
11529 S, *this,
11530 *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11531 break;
11532 }
11533 Cand = Cand->Next;
11534 }
11535 FirstDeferredCandidate = nullptr;
11536 DeferredCandidatesCount = 0;
11537}
11538
11540OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11541 Best->Best = true;
11542 if (Best->Function && Best->Function->isDeleted())
11543 return OR_Deleted;
11544 return OR_Success;
11545}
11546
11547void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11549 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11550 // are accepted by both clang and NVCC. However, during a particular
11551 // compilation mode only one call variant is viable. We need to
11552 // exclude non-viable overload candidates from consideration based
11553 // only on their host/device attributes. Specifically, if one
11554 // candidate call is WrongSide and the other is SameSide, we ignore
11555 // the WrongSide candidate.
11556 // We only need to remove wrong-sided candidates here if
11557 // -fgpu-exclude-wrong-side-overloads is off. When
11558 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11559 // uniformly in isBetterOverloadCandidate.
11560 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11561 return;
11562 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11563
11564 bool ContainsSameSideCandidate =
11565 llvm::any_of(Candidates, [&](const OverloadCandidate *Cand) {
11566 // Check viable function only.
11567 return Cand->Viable && Cand->Function &&
11568 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11570 });
11571
11572 if (!ContainsSameSideCandidate)
11573 return;
11574
11575 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11576 // Check viable function only to avoid unnecessary data copying/moving.
11577 return Cand->Viable && Cand->Function &&
11578 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11580 };
11581 llvm::erase_if(Candidates, IsWrongSideCandidate);
11582}
11583
11584/// Computes the best viable function (C++ 13.3.3)
11585/// within an overload candidate set.
11586///
11587/// \param Loc The location of the function name (or operator symbol) for
11588/// which overload resolution occurs.
11589///
11590/// \param Best If overload resolution was successful or found a deleted
11591/// function, \p Best points to the candidate function found.
11592///
11593/// \returns The result of overload resolution.
11595 SourceLocation Loc,
11596 iterator &Best) {
11597
11599 DeferredCandidatesCount == 0) &&
11600 "Unexpected deferred template candidates");
11601
11602 bool TwoPhaseResolution =
11603 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11604
11605 if (TwoPhaseResolution) {
11606 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11607 if (Best != end() && Best->isPerfectMatch(S.Context)) {
11608 if (!(HasDeferredTemplateConstructors &&
11609 isa_and_nonnull<CXXConversionDecl>(Best->Function)))
11610 return Res;
11611 }
11612 }
11613
11615 return BestViableFunctionImpl(S, Loc, Best);
11616}
11617
11618OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11620
11622 Candidates.reserve(this->Candidates.size());
11623 std::transform(this->Candidates.begin(), this->Candidates.end(),
11624 std::back_inserter(Candidates),
11625 [](OverloadCandidate &Cand) { return &Cand; });
11626
11627 if (S.getLangOpts().CUDA)
11628 CudaExcludeWrongSideCandidates(S, Candidates);
11629
11630 Best = end();
11631 for (auto *Cand : Candidates) {
11632 Cand->Best = false;
11633 if (Cand->Viable) {
11634 if (Best == end() ||
11635 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
11636 Best = Cand;
11637 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11638 // This candidate has constraint that we were unable to evaluate because
11639 // it referenced an expression that contained an error. Rather than fall
11640 // back onto a potentially unintended candidate (made worse by
11641 // subsuming constraints), treat this as 'no viable candidate'.
11642 Best = end();
11643 return OR_No_Viable_Function;
11644 }
11645 }
11646
11647 // If we didn't find any viable functions, abort.
11648 if (Best == end())
11649 return OR_No_Viable_Function;
11650
11651 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11652 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11653 PendingBest.push_back(&*Best);
11654 Best->Best = true;
11655
11656 // Make sure that this function is better than every other viable
11657 // function. If not, we have an ambiguity.
11658 while (!PendingBest.empty()) {
11659 auto *Curr = PendingBest.pop_back_val();
11660 for (auto *Cand : Candidates) {
11661 if (Cand->Viable && !Cand->Best &&
11662 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
11663 PendingBest.push_back(Cand);
11664 Cand->Best = true;
11665
11667 Curr->Function))
11668 EquivalentCands.push_back(Cand->Function);
11669 else
11670 Best = end();
11671 }
11672 }
11673 }
11674
11675 if (Best == end())
11676 return OR_Ambiguous;
11677
11678 OverloadingResult R = ResultForBestCandidate(Best);
11679
11680 if (!EquivalentCands.empty())
11682 EquivalentCands);
11683 return R;
11684}
11685
11686namespace {
11687
11688enum OverloadCandidateKind {
11689 oc_function,
11690 oc_method,
11691 oc_reversed_binary_operator,
11692 oc_constructor,
11693 oc_implicit_default_constructor,
11694 oc_implicit_copy_constructor,
11695 oc_implicit_move_constructor,
11696 oc_implicit_copy_assignment,
11697 oc_implicit_move_assignment,
11698 oc_implicit_equality_comparison,
11699 oc_inherited_constructor
11700};
11701
11702enum OverloadCandidateSelect {
11703 ocs_non_template,
11704 ocs_template,
11705 ocs_described_template,
11706};
11707
11708static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11709ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11710 const FunctionDecl *Fn,
11712 std::string &Description) {
11713
11714 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11715 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11716 isTemplate = true;
11717 Description = S.getTemplateArgumentBindingsText(
11718 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11719 }
11720
11721 OverloadCandidateSelect Select = [&]() {
11722 if (!Description.empty())
11723 return ocs_described_template;
11724 return isTemplate ? ocs_template : ocs_non_template;
11725 }();
11726
11727 OverloadCandidateKind Kind = [&]() {
11728 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11729 return oc_implicit_equality_comparison;
11730
11731 if (CRK & CRK_Reversed)
11732 return oc_reversed_binary_operator;
11733
11734 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11735 if (!Ctor->isImplicit()) {
11737 return oc_inherited_constructor;
11738 else
11739 return oc_constructor;
11740 }
11741
11742 if (Ctor->isDefaultConstructor())
11743 return oc_implicit_default_constructor;
11744
11745 if (Ctor->isMoveConstructor())
11746 return oc_implicit_move_constructor;
11747
11748 assert(Ctor->isCopyConstructor() &&
11749 "unexpected sort of implicit constructor");
11750 return oc_implicit_copy_constructor;
11751 }
11752
11753 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11754 // This actually gets spelled 'candidate function' for now, but
11755 // it doesn't hurt to split it out.
11756 if (!Meth->isImplicit())
11757 return oc_method;
11758
11759 if (Meth->isMoveAssignmentOperator())
11760 return oc_implicit_move_assignment;
11761
11762 if (Meth->isCopyAssignmentOperator())
11763 return oc_implicit_copy_assignment;
11764
11765 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11766 return oc_method;
11767 }
11768
11769 return oc_function;
11770 }();
11771
11772 return std::make_pair(Kind, Select);
11773}
11774
11775void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11776 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11777 // set.
11778 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11779 S.Diag(FoundDecl->getLocation(),
11780 diag::note_ovl_candidate_inherited_constructor)
11781 << Shadow->getNominatedBaseClass();
11782}
11783
11784} // end anonymous namespace
11785
11787 const FunctionDecl *FD) {
11788 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11789 bool AlwaysTrue;
11790 if (EnableIf->getCond()->isValueDependent() ||
11791 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11792 return false;
11793 if (!AlwaysTrue)
11794 return false;
11795 }
11796 return true;
11797}
11798
11799/// Returns true if we can take the address of the function.
11800///
11801/// \param Complain - If true, we'll emit a diagnostic
11802/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11803/// we in overload resolution?
11804/// \param Loc - The location of the statement we're complaining about. Ignored
11805/// if we're not complaining, or if we're in overload resolution.
11807 bool Complain,
11808 bool InOverloadResolution,
11809 SourceLocation Loc) {
11810 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11811 if (Complain) {
11812 if (InOverloadResolution)
11813 S.Diag(FD->getBeginLoc(),
11814 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11815 else
11816 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11817 }
11818 return false;
11819 }
11820
11821 if (FD->getTrailingRequiresClause()) {
11822 ConstraintSatisfaction Satisfaction;
11823 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11824 return false;
11825 if (!Satisfaction.IsSatisfied) {
11826 if (Complain) {
11827 if (InOverloadResolution) {
11828 SmallString<128> TemplateArgString;
11829 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11830 TemplateArgString += " ";
11831 TemplateArgString += S.getTemplateArgumentBindingsText(
11832 FunTmpl->getTemplateParameters(),
11834 }
11835
11836 S.Diag(FD->getBeginLoc(),
11837 diag::note_ovl_candidate_unsatisfied_constraints)
11838 << TemplateArgString;
11839 } else
11840 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11841 << FD;
11842 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11843 }
11844 return false;
11845 }
11846 }
11847
11848 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11849 return P->hasAttr<PassObjectSizeAttr>();
11850 });
11851 if (I == FD->param_end())
11852 return true;
11853
11854 if (Complain) {
11855 // Add one to ParamNo because it's user-facing
11856 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11857 if (InOverloadResolution)
11858 S.Diag(FD->getLocation(),
11859 diag::note_ovl_candidate_has_pass_object_size_params)
11860 << ParamNo;
11861 else
11862 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11863 << FD << ParamNo;
11864 }
11865 return false;
11866}
11867
11869 const FunctionDecl *FD) {
11870 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11871 /*InOverloadResolution=*/true,
11872 /*Loc=*/SourceLocation());
11873}
11874
11876 bool Complain,
11877 SourceLocation Loc) {
11878 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11879 /*InOverloadResolution=*/false,
11880 Loc);
11881}
11882
11883// Don't print candidates other than the one that matches the calling
11884// convention of the call operator, since that is guaranteed to exist.
11886 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11887
11888 if (!ConvD)
11889 return false;
11890 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11891 if (!RD->isLambda())
11892 return false;
11893
11894 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11895 CallingConv CallOpCC =
11896 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11897 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11898 CallingConv ConvToCC =
11899 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11900
11901 return ConvToCC != CallOpCC;
11902}
11903
11904// Notes the location of an overload candidate.
11906 OverloadCandidateRewriteKind RewriteKind,
11907 QualType DestType, bool TakingAddress) {
11908 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11909 return;
11910 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11911 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11912 return;
11913 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11914 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11915 return;
11917 return;
11918
11919 std::string FnDesc;
11920 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11921 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11922 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11923 << (unsigned)KSPair.first << (unsigned)KSPair.second
11924 << Fn << FnDesc;
11925
11926 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11927 Diag(Fn->getLocation(), PD);
11928 MaybeEmitInheritedConstructorNote(*this, Found);
11929}
11930
11931static void
11933 // Perhaps the ambiguity was caused by two atomic constraints that are
11934 // 'identical' but not equivalent:
11935 //
11936 // void foo() requires (sizeof(T) > 4) { } // #1
11937 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11938 //
11939 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11940 // #2 to subsume #1, but these constraint are not considered equivalent
11941 // according to the subsumption rules because they are not the same
11942 // source-level construct. This behavior is quite confusing and we should try
11943 // to help the user figure out what happened.
11944
11945 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11946 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11947 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11948 if (!I->Function)
11949 continue;
11951 if (auto *Template = I->Function->getPrimaryTemplate())
11952 Template->getAssociatedConstraints(AC);
11953 else
11954 I->Function->getAssociatedConstraints(AC);
11955 if (AC.empty())
11956 continue;
11957 if (FirstCand == nullptr) {
11958 FirstCand = I->Function;
11959 FirstAC = AC;
11960 } else if (SecondCand == nullptr) {
11961 SecondCand = I->Function;
11962 SecondAC = AC;
11963 } else {
11964 // We have more than one pair of constrained functions - this check is
11965 // expensive and we'd rather not try to diagnose it.
11966 return;
11967 }
11968 }
11969 if (!SecondCand)
11970 return;
11971 // The diagnostic can only happen if there are associated constraints on
11972 // both sides (there needs to be some identical atomic constraint).
11973 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11974 SecondCand, SecondAC))
11975 // Just show the user one diagnostic, they'll probably figure it out
11976 // from here.
11977 return;
11978}
11979
11980// Notes the location of all overload candidates designated through
11981// OverloadedExpr
11982void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11983 bool TakingAddress) {
11984 assert(OverloadedExpr->getType() == Context.OverloadTy);
11985
11986 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11987 OverloadExpr *OvlExpr = Ovl.Expression;
11988
11989 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11990 IEnd = OvlExpr->decls_end();
11991 I != IEnd; ++I) {
11992 if (FunctionTemplateDecl *FunTmpl =
11993 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11994 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11995 TakingAddress);
11996 } else if (FunctionDecl *Fun
11997 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11998 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11999 }
12000 }
12001}
12002
12003/// Diagnoses an ambiguous conversion. The partial diagnostic is the
12004/// "lead" diagnostic; it will be given two arguments, the source and
12005/// target types of the conversion.
12007 Sema &S,
12008 SourceLocation CaretLoc,
12009 const PartialDiagnostic &PDiag) const {
12010 S.Diag(CaretLoc, PDiag)
12011 << Ambiguous.getFromType() << Ambiguous.getToType();
12012 unsigned CandsShown = 0;
12014 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
12015 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
12016 break;
12017 ++CandsShown;
12018 S.NoteOverloadCandidate(I->first, I->second);
12019 }
12020 S.Diags.overloadCandidatesShown(CandsShown);
12021 if (I != E)
12022 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
12023}
12024
12026 unsigned I, bool TakingCandidateAddress) {
12027 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
12028 assert(Conv.isBad());
12029 assert(Cand->Function && "for now, candidate must be a function");
12030 FunctionDecl *Fn = Cand->Function;
12031
12032 // There's a conversion slot for the object argument if this is a
12033 // non-constructor method. Note that 'I' corresponds the
12034 // conversion-slot index.
12035 bool isObjectArgument = false;
12036 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Fn) &&
12038 if (I == 0)
12039 isObjectArgument = true;
12040 else if (!cast<CXXMethodDecl>(Fn)->isExplicitObjectMemberFunction())
12041 I--;
12042 }
12043
12044 std::string FnDesc;
12045 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12046 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
12047 FnDesc);
12048
12049 Expr *FromExpr = Conv.Bad.FromExpr;
12050 QualType FromTy = Conv.Bad.getFromType();
12051 QualType ToTy = Conv.Bad.getToType();
12052 SourceRange ToParamRange;
12053
12054 // FIXME: In presence of parameter packs we can't determine parameter range
12055 // reliably, as we don't have access to instantiation.
12056 bool HasParamPack =
12057 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
12058 return Parm->isParameterPack();
12059 });
12060 if (!isObjectArgument && !HasParamPack && I < Fn->getNumParams())
12061 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
12062
12063 if (FromTy == S.Context.OverloadTy) {
12064 assert(FromExpr && "overload set argument came from implicit argument?");
12065 Expr *E = FromExpr->IgnoreParens();
12066 if (isa<UnaryOperator>(E))
12067 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
12068 DeclarationName Name = cast<OverloadExpr>(E)->getName();
12069
12070 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
12071 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12072 << ToParamRange << ToTy << Name << I + 1;
12073 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12074 return;
12075 }
12076
12077 // Do some hand-waving analysis to see if the non-viability is due
12078 // to a qualifier mismatch.
12079 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
12080 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
12081 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
12082 CToTy = RT->getPointeeType();
12083 else {
12084 // TODO: detect and diagnose the full richness of const mismatches.
12085 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
12086 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
12087 CFromTy = FromPT->getPointeeType();
12088 CToTy = ToPT->getPointeeType();
12089 }
12090 }
12091
12092 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
12093 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
12094 Qualifiers FromQs = CFromTy.getQualifiers();
12095 Qualifiers ToQs = CToTy.getQualifiers();
12096
12097 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
12098 if (isObjectArgument)
12099 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
12100 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12101 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
12102 else
12103 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
12104 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12105 << FnDesc << ToParamRange << FromQs.getAddressSpace()
12106 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
12107 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12108 return;
12109 }
12110
12111 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12112 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
12113 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12114 << ToParamRange << FromTy << FromQs.getObjCLifetime()
12115 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
12116 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12117 return;
12118 }
12119
12120 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
12121 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
12122 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12123 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
12124 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
12125 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12126 return;
12127 }
12128
12129 if (!FromQs.getPointerAuth().isEquivalent(ToQs.getPointerAuth())) {
12130 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)
12131 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12132 << FromTy << !!FromQs.getPointerAuth()
12133 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
12134 << ToQs.getPointerAuth().getAsString() << I + 1
12135 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
12136 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12137 return;
12138 }
12139
12140 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
12141 assert(CVR && "expected qualifiers mismatch");
12142
12143 if (isObjectArgument) {
12144 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
12145 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12146 << FromTy << (CVR - 1);
12147 } else {
12148 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
12149 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12150 << ToParamRange << FromTy << (CVR - 1) << I + 1;
12151 }
12152 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12153 return;
12154 }
12155
12158 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
12159 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12160 << (unsigned)isObjectArgument << I + 1
12162 << ToParamRange;
12163 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12164 return;
12165 }
12166
12167 // Special diagnostic for failure to convert an initializer list, since
12168 // telling the user that it has type void is not useful.
12169 if (FromExpr && isa<InitListExpr>(FromExpr)) {
12170 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
12171 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12172 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12175 ? 2
12176 : 0);
12177 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12178 return;
12179 }
12180
12181 // Diagnose references or pointers to incomplete types differently,
12182 // since it's far from impossible that the incompleteness triggered
12183 // the failure.
12184 QualType TempFromTy = FromTy.getNonReferenceType();
12185 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
12186 TempFromTy = PTy->getPointeeType();
12187 if (TempFromTy->isIncompleteType()) {
12188 // Emit the generic diagnostic and, optionally, add the hints to it.
12189 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
12190 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12191 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12192 << (unsigned)(Cand->Fix.Kind);
12193
12194 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12195 return;
12196 }
12197
12198 // Diagnose base -> derived pointer conversions.
12199 unsigned BaseToDerivedConversion = 0;
12200 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
12201 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
12202 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12203 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12204 !FromPtrTy->getPointeeType()->isIncompleteType() &&
12205 !ToPtrTy->getPointeeType()->isIncompleteType() &&
12206 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
12207 FromPtrTy->getPointeeType()))
12208 BaseToDerivedConversion = 1;
12209 }
12210 } else if (const ObjCObjectPointerType *FromPtrTy
12211 = FromTy->getAs<ObjCObjectPointerType>()) {
12212 if (const ObjCObjectPointerType *ToPtrTy
12213 = ToTy->getAs<ObjCObjectPointerType>())
12214 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
12215 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
12216 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
12217 FromPtrTy->getPointeeType(), S.getASTContext()) &&
12218 FromIface->isSuperClassOf(ToIface))
12219 BaseToDerivedConversion = 2;
12220 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
12221 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
12222 S.getASTContext()) &&
12223 !FromTy->isIncompleteType() &&
12224 !ToRefTy->getPointeeType()->isIncompleteType() &&
12225 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
12226 BaseToDerivedConversion = 3;
12227 }
12228 }
12229
12230 if (BaseToDerivedConversion) {
12231 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
12232 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12233 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
12234 << I + 1;
12235 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12236 return;
12237 }
12238
12239 if (isa<ObjCObjectPointerType>(CFromTy) &&
12240 isa<PointerType>(CToTy)) {
12241 Qualifiers FromQs = CFromTy.getQualifiers();
12242 Qualifiers ToQs = CToTy.getQualifiers();
12243 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
12244 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
12245 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12246 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
12247 << I + 1;
12248 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12249 return;
12250 }
12251 }
12252
12253 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
12254 return;
12255
12256 // __amdgpu_feature_predicate_t can be explicitly cast to the logical op type,
12257 // although this is almost always an error and we advise against it.
12258 if (FromTy == S.Context.AMDGPUFeaturePredicateTy &&
12259 ToTy == S.Context.getLogicalOperationType()) {
12260 S.Diag(Conv.Bad.FromExpr->getExprLoc(),
12261 diag::err_amdgcn_predicate_type_needs_explicit_bool_cast)
12262 << Conv.Bad.FromExpr << ToTy;
12263 return;
12264 }
12265
12266 // Emit the generic diagnostic and, optionally, add the hints to it.
12267 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
12268 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12269 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12270 << (unsigned)(Cand->Fix.Kind);
12271
12272 // Check that location of Fn is not in system header.
12273 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
12274 // If we can fix the conversion, suggest the FixIts.
12275 for (const FixItHint &HI : Cand->Fix.Hints)
12276 FDiag << HI;
12277 }
12278
12279 S.Diag(Fn->getLocation(), FDiag);
12280
12281 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12282}
12283
12284/// Additional arity mismatch diagnosis specific to a function overload
12285/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12286/// over a candidate in any candidate set.
12288 unsigned NumArgs, bool IsAddressOf = false) {
12289 assert(Cand->Function && "Candidate is required to be a function.");
12290 FunctionDecl *Fn = Cand->Function;
12291 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12292 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12293
12294 // With invalid overloaded operators, it's possible that we think we
12295 // have an arity mismatch when in fact it looks like we have the
12296 // right number of arguments, because only overloaded operators have
12297 // the weird behavior of overloading member and non-member functions.
12298 // Just don't report anything.
12299 if (Fn->isInvalidDecl() &&
12300 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12301 return true;
12302
12303 if (NumArgs < MinParams) {
12304 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12306 Cand->DeductionFailure.getResult() ==
12308 } else {
12309 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12311 Cand->DeductionFailure.getResult() ==
12313 }
12314
12315 return false;
12316}
12317
12318/// General arity mismatch diagnosis over a candidate in a candidate set.
12320 unsigned NumFormalArgs,
12321 bool IsAddressOf = false) {
12322 assert(isa<FunctionDecl>(D) &&
12323 "The templated declaration should at least be a function"
12324 " when diagnosing bad template argument deduction due to too many"
12325 " or too few arguments");
12326
12328
12329 // TODO: treat calls to a missing default constructor as a special case
12330 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12331 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12332 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12333
12334 // at least / at most / exactly
12335 bool HasExplicitObjectParam =
12336 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12337
12338 unsigned ParamCount =
12339 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12340 unsigned mode, modeCount;
12341
12342 if (NumFormalArgs < MinParams) {
12343 if (MinParams != ParamCount || FnTy->isVariadic() ||
12344 FnTy->isTemplateVariadic())
12345 mode = 0; // "at least"
12346 else
12347 mode = 2; // "exactly"
12348 modeCount = MinParams;
12349 } else {
12350 if (MinParams != ParamCount)
12351 mode = 1; // "at most"
12352 else
12353 mode = 2; // "exactly"
12354 modeCount = ParamCount;
12355 }
12356
12357 std::string Description;
12358 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12359 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
12360
12361 unsigned FirstNonObjectParamIdx = HasExplicitObjectParam ? 1 : 0;
12362 if (modeCount == 1 && !IsAddressOf &&
12363 FirstNonObjectParamIdx < Fn->getNumParams() &&
12364 Fn->getParamDecl(FirstNonObjectParamIdx)->getDeclName())
12365 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
12366 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12367 << Description << mode << Fn->getParamDecl(FirstNonObjectParamIdx)
12368 << NumFormalArgs << HasExplicitObjectParam
12369 << Fn->getParametersSourceRange();
12370 else
12371 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
12372 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12373 << Description << mode << modeCount << NumFormalArgs
12374 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12375
12376 MaybeEmitInheritedConstructorNote(S, Found);
12377}
12378
12379/// Arity mismatch diagnosis specific to a function overload candidate.
12381 unsigned NumFormalArgs) {
12382 assert(Cand->Function && "Candidate must be a function");
12383 FunctionDecl *Fn = Cand->Function;
12384 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
12385 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
12386 Cand->TookAddressOfOverload);
12387}
12388
12390 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12391 return TD;
12392 llvm_unreachable("Unsupported: Getting the described template declaration"
12393 " for bad deduction diagnosis");
12394}
12395
12396/// Diagnose a failed template-argument deduction.
12397static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12398 DeductionFailureInfo &DeductionFailure,
12399 unsigned NumArgs,
12400 bool TakingCandidateAddress) {
12401 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12402 NamedDecl *ParamD;
12403 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12404 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12405 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12406 switch (DeductionFailure.getResult()) {
12408 llvm_unreachable(
12409 "TemplateDeductionResult::Success while diagnosing bad deduction");
12411 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12412 "while diagnosing bad deduction");
12415 return;
12416
12418 assert(ParamD && "no parameter found for incomplete deduction result");
12419 S.Diag(Templated->getLocation(),
12420 diag::note_ovl_candidate_incomplete_deduction)
12421 << ParamD->getDeclName();
12422 MaybeEmitInheritedConstructorNote(S, Found);
12423 return;
12424 }
12425
12427 assert(ParamD && "no parameter found for incomplete deduction result");
12428 S.Diag(Templated->getLocation(),
12429 diag::note_ovl_candidate_incomplete_deduction_pack)
12430 << ParamD->getDeclName()
12431 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12432 << *DeductionFailure.getFirstArg();
12433 MaybeEmitInheritedConstructorNote(S, Found);
12434 return;
12435 }
12436
12438 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12440
12441 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12442
12443 // Param will have been canonicalized, but it should just be a
12444 // qualified version of ParamD, so move the qualifiers to that.
12446 Qs.strip(Param);
12447 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
12448 assert(S.Context.hasSameType(Param, NonCanonParam));
12449
12450 // Arg has also been canonicalized, but there's nothing we can do
12451 // about that. It also doesn't matter as much, because it won't
12452 // have any template parameters in it (because deduction isn't
12453 // done on dependent types).
12454 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12455
12456 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
12457 << ParamD->getDeclName() << Arg << NonCanonParam;
12458 MaybeEmitInheritedConstructorNote(S, Found);
12459 return;
12460 }
12461
12463 assert(ParamD && "no parameter found for inconsistent deduction result");
12464 int which = 0;
12465 if (isa<TemplateTypeParmDecl>(ParamD))
12466 which = 0;
12467 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
12468 // Deduction might have failed because we deduced arguments of two
12469 // different types for a non-type template parameter.
12470 // FIXME: Use a different TDK value for this.
12471 QualType T1 =
12472 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12473 QualType T2 =
12474 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12475 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12476 S.Diag(Templated->getLocation(),
12477 diag::note_ovl_candidate_inconsistent_deduction_types)
12478 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12479 << *DeductionFailure.getSecondArg() << T2;
12480 MaybeEmitInheritedConstructorNote(S, Found);
12481 return;
12482 }
12483
12484 which = 1;
12485 } else {
12486 which = 2;
12487 }
12488
12489 // Tweak the diagnostic if the problem is that we deduced packs of
12490 // different arities. We'll print the actual packs anyway in case that
12491 // includes additional useful information.
12492 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12493 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12494 DeductionFailure.getFirstArg()->pack_size() !=
12495 DeductionFailure.getSecondArg()->pack_size()) {
12496 which = 3;
12497 }
12498
12499 S.Diag(Templated->getLocation(),
12500 diag::note_ovl_candidate_inconsistent_deduction)
12501 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12502 << *DeductionFailure.getSecondArg();
12503 MaybeEmitInheritedConstructorNote(S, Found);
12504 return;
12505 }
12506
12508 assert(ParamD && "no parameter found for invalid explicit arguments");
12509
12510 auto Diag = S.Diag(Templated->getLocation(),
12511 diag::note_ovl_candidate_explicit_arg_mismatch);
12512 if (ParamD->getDeclName())
12513 Diag << diag::ExplicitArgMismatchNameKind::Named << ParamD->getDeclName();
12514 else
12515 Diag << diag::ExplicitArgMismatchNameKind::Unnamed
12516 << (getDepthAndIndex(ParamD).second + 1);
12517 if (PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic()) {
12518 SmallString<128> DiagContent;
12519 PDiag->second.EmitToString(S.getDiagnostics(), DiagContent);
12520 Diag << diag::ExplicitArgMismatchReasonKind::Detailed << DiagContent;
12521 } else {
12522 Diag << diag::ExplicitArgMismatchReasonKind::Vague;
12523 }
12524
12525 MaybeEmitInheritedConstructorNote(S, Found);
12526 return;
12527 }
12529 // Format the template argument list into the argument string.
12530 SmallString<128> TemplateArgString;
12531 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12532 TemplateArgString = " ";
12533 TemplateArgString += S.getTemplateArgumentBindingsText(
12534 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12535 if (TemplateArgString.size() == 1)
12536 TemplateArgString.clear();
12537 S.Diag(Templated->getLocation(),
12538 diag::note_ovl_candidate_unsatisfied_constraints)
12539 << TemplateArgString;
12540
12542 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12543 return;
12544 }
12547 DiagnoseArityMismatch(S, Found, Templated, NumArgs, TakingCandidateAddress);
12548 return;
12549
12551 S.Diag(Templated->getLocation(),
12552 diag::note_ovl_candidate_instantiation_depth);
12553 MaybeEmitInheritedConstructorNote(S, Found);
12554 return;
12555
12557 // Format the template argument list into the argument string.
12558 SmallString<128> TemplateArgString;
12559 if (TemplateArgumentList *Args =
12560 DeductionFailure.getTemplateArgumentList()) {
12561 TemplateArgString = " ";
12562 TemplateArgString += S.getTemplateArgumentBindingsText(
12563 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12564 if (TemplateArgString.size() == 1)
12565 TemplateArgString.clear();
12566 }
12567
12568 // If this candidate was disabled by enable_if, say so.
12569 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12570 if (PDiag && PDiag->second.getDiagID() ==
12571 diag::err_typename_nested_not_found_enable_if) {
12572 // FIXME: Use the source range of the condition, and the fully-qualified
12573 // name of the enable_if template. These are both present in PDiag.
12574 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
12575 << "'enable_if'" << TemplateArgString;
12576 return;
12577 }
12578
12579 // We found a specific requirement that disabled the enable_if.
12580 if (PDiag && PDiag->second.getDiagID() ==
12581 diag::err_typename_nested_not_found_requirement) {
12582 S.Diag(Templated->getLocation(),
12583 diag::note_ovl_candidate_disabled_by_requirement)
12584 << PDiag->second.getStringArg(0) << TemplateArgString;
12585 return;
12586 }
12587
12588 // Format the SFINAE diagnostic into the argument string.
12589 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12590 // formatted message in another diagnostic.
12591 SmallString<128> SFINAEArgString;
12592 SourceRange R;
12593 if (PDiag) {
12594 SFINAEArgString = ": ";
12595 R = SourceRange(PDiag->first, PDiag->first);
12596 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
12597 }
12598
12599 S.Diag(Templated->getLocation(),
12600 diag::note_ovl_candidate_substitution_failure)
12601 << TemplateArgString << SFINAEArgString << R;
12602 MaybeEmitInheritedConstructorNote(S, Found);
12603 return;
12604 }
12605
12608 // Format the template argument list into the argument string.
12609 SmallString<128> TemplateArgString;
12610 if (TemplateArgumentList *Args =
12611 DeductionFailure.getTemplateArgumentList()) {
12612 TemplateArgString = " ";
12613 TemplateArgString += S.getTemplateArgumentBindingsText(
12614 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12615 if (TemplateArgString.size() == 1)
12616 TemplateArgString.clear();
12617 }
12618
12619 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
12620 << (*DeductionFailure.getCallArgIndex() + 1)
12621 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12622 << TemplateArgString
12623 << (DeductionFailure.getResult() ==
12625 break;
12626 }
12627
12629 // FIXME: Provide a source location to indicate what we couldn't match.
12630 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12631 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12632 if (FirstTA.getKind() == TemplateArgument::Template &&
12633 SecondTA.getKind() == TemplateArgument::Template) {
12634 TemplateName FirstTN = FirstTA.getAsTemplate();
12635 TemplateName SecondTN = SecondTA.getAsTemplate();
12636 if (FirstTN.getKind() == TemplateName::Template &&
12637 SecondTN.getKind() == TemplateName::Template) {
12638 if (FirstTN.getAsTemplateDecl()->getName() ==
12639 SecondTN.getAsTemplateDecl()->getName()) {
12640 // FIXME: This fixes a bad diagnostic where both templates are named
12641 // the same. This particular case is a bit difficult since:
12642 // 1) It is passed as a string to the diagnostic printer.
12643 // 2) The diagnostic printer only attempts to find a better
12644 // name for types, not decls.
12645 // Ideally, this should folded into the diagnostic printer.
12646 S.Diag(Templated->getLocation(),
12647 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12648 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12649 return;
12650 }
12651 }
12652 }
12653
12654 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
12656 return;
12657
12658 // FIXME: For generic lambda parameters, check if the function is a lambda
12659 // call operator, and if so, emit a prettier and more informative
12660 // diagnostic that mentions 'auto' and lambda in addition to
12661 // (or instead of?) the canonical template type parameters.
12662 S.Diag(Templated->getLocation(),
12663 diag::note_ovl_candidate_non_deduced_mismatch)
12664 << FirstTA << SecondTA;
12665 return;
12666 }
12667 // TODO: diagnose these individually, then kill off
12668 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12670 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
12671 MaybeEmitInheritedConstructorNote(S, Found);
12672 return;
12674 S.Diag(Templated->getLocation(),
12675 diag::note_cuda_ovl_candidate_target_mismatch);
12676 return;
12677 }
12678}
12679
12680/// Diagnose a failed template-argument deduction, for function calls.
12682 unsigned NumArgs,
12683 bool TakingCandidateAddress) {
12684 assert(Cand->Function && "Candidate must be a function");
12685 FunctionDecl *Fn = Cand->Function;
12689 if (CheckArityMismatch(S, Cand, NumArgs))
12690 return;
12691 }
12692 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
12693 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12694}
12695
12696/// CUDA: diagnose an invalid call across targets.
12698 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12699 assert(Cand->Function && "Candidate must be a Function.");
12700 FunctionDecl *Callee = Cand->Function;
12701
12702 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
12703 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
12704
12705 std::string FnDesc;
12706 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12707 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
12708 Cand->getRewriteKind(), FnDesc);
12709
12710 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
12711 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12712 << FnDesc /* Ignored */
12713 << CalleeTarget << CallerTarget;
12714
12715 // This could be an implicit constructor for which we could not infer the
12716 // target due to a collsion. Diagnose that case.
12717 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
12718 if (Meth != nullptr && Meth->isImplicit()) {
12719 CXXRecordDecl *ParentClass = Meth->getParent();
12721
12722 switch (FnKindPair.first) {
12723 default:
12724 return;
12725 case oc_implicit_default_constructor:
12727 break;
12728 case oc_implicit_copy_constructor:
12730 break;
12731 case oc_implicit_move_constructor:
12733 break;
12734 case oc_implicit_copy_assignment:
12736 break;
12737 case oc_implicit_move_assignment:
12739 break;
12740 };
12741
12742 bool ConstRHS = false;
12743 if (Meth->getNumParams()) {
12744 if (const ReferenceType *RT =
12745 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
12746 ConstRHS = RT->getPointeeType().isConstQualified();
12747 }
12748 }
12749
12750 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
12751 /* ConstRHS */ ConstRHS,
12752 /* Diagnose */ true);
12753 }
12754}
12755
12757 assert(Cand->Function && "Candidate must be a function");
12758 FunctionDecl *Callee = Cand->Function;
12759 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12760
12761 S.Diag(Callee->getLocation(),
12762 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12763 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12764}
12765
12767 assert(Cand->Function && "Candidate must be a function");
12768 FunctionDecl *Fn = Cand->Function;
12770 assert(ES.isExplicit() && "not an explicit candidate");
12771
12772 unsigned Kind;
12773 switch (Fn->getDeclKind()) {
12774 case Decl::Kind::CXXConstructor:
12775 Kind = 0;
12776 break;
12777 case Decl::Kind::CXXConversion:
12778 Kind = 1;
12779 break;
12780 case Decl::Kind::CXXDeductionGuide:
12781 Kind = Fn->isImplicit() ? 0 : 2;
12782 break;
12783 default:
12784 llvm_unreachable("invalid Decl");
12785 }
12786
12787 // Note the location of the first (in-class) declaration; a redeclaration
12788 // (particularly an out-of-class definition) will typically lack the
12789 // 'explicit' specifier.
12790 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12791 FunctionDecl *First = Fn->getFirstDecl();
12792 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12793 First = Pattern->getFirstDecl();
12794
12795 S.Diag(First->getLocation(),
12796 diag::note_ovl_candidate_explicit)
12797 << Kind << (ES.getExpr() ? 1 : 0)
12798 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12799}
12800
12802 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12803 if (!DG)
12804 return;
12805 TemplateDecl *OriginTemplate =
12807 // We want to always print synthesized deduction guides for type aliases.
12808 // They would retain the explicit bit of the corresponding constructor.
12809 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12810 return;
12811 std::string FunctionProto;
12812 llvm::raw_string_ostream OS(FunctionProto);
12813 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12814 if (!Template) {
12815 // This also could be an instantiation. Find out the primary template.
12816 FunctionDecl *Pattern =
12817 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12818 if (!Pattern) {
12819 // The implicit deduction guide is built on an explicit non-template
12820 // deduction guide. Currently, this might be the case only for type
12821 // aliases.
12822 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12823 // gets merged.
12824 assert(OriginTemplate->isTypeAlias() &&
12825 "Non-template implicit deduction guides are only possible for "
12826 "type aliases");
12827 DG->print(OS);
12828 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12829 << FunctionProto;
12830 return;
12831 }
12833 assert(Template && "Cannot find the associated function template of "
12834 "CXXDeductionGuideDecl?");
12835 }
12836 Template->print(OS);
12837 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12838 << FunctionProto;
12839}
12840
12841/// Generates a 'note' diagnostic for an overload candidate. We've
12842/// already generated a primary error at the call site.
12843///
12844/// It really does need to be a single diagnostic with its caret
12845/// pointed at the candidate declaration. Yes, this creates some
12846/// major challenges of technical writing. Yes, this makes pointing
12847/// out problems with specific arguments quite awkward. It's still
12848/// better than generating twenty screens of text for every failed
12849/// overload.
12850///
12851/// It would be great to be able to express per-candidate problems
12852/// more richly for those diagnostic clients that cared, but we'd
12853/// still have to be just as careful with the default diagnostics.
12854/// \param CtorDestAS Addr space of object being constructed (for ctor
12855/// candidates only).
12857 unsigned NumArgs,
12858 bool TakingCandidateAddress,
12859 LangAS CtorDestAS = LangAS::Default) {
12860 assert(Cand->Function && "Candidate must be a function");
12861 FunctionDecl *Fn = Cand->Function;
12863 return;
12864
12865 // There is no physical candidate declaration to point to for OpenCL builtins.
12866 // Except for failed conversions, the notes are identical for each candidate,
12867 // so do not generate such notes.
12868 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12870 return;
12871
12872 // Skip implicit member functions when trying to resolve
12873 // the address of a an overload set for a function pointer.
12874 if (Cand->TookAddressOfOverload &&
12875 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12876 return;
12877
12878 // Note deleted candidates, but only if they're viable.
12879 if (Cand->Viable) {
12880 if (Fn->isDeleted()) {
12881 std::string FnDesc;
12882 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12883 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12884 Cand->getRewriteKind(), FnDesc);
12885
12886 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12887 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12888 << (Fn->isDeleted()
12889 ? (Fn->getCanonicalDecl()->isDeletedAsWritten() ? 1 : 2)
12890 : 0);
12891 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12892 return;
12893 }
12894
12895 // We don't really have anything else to say about viable candidates.
12896 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12897 return;
12898 }
12899
12900 // If this is a synthesized deduction guide we're deducing against, add a note
12901 // for it. These deduction guides are not explicitly spelled in the source
12902 // code, so simply printing a deduction failure note mentioning synthesized
12903 // template parameters or pointing to the header of the surrounding RecordDecl
12904 // would be confusing.
12905 //
12906 // We prefer adding such notes at the end of the deduction failure because
12907 // duplicate code snippets appearing in the diagnostic would likely become
12908 // noisy.
12909 llvm::scope_exit _([&] { NoteImplicitDeductionGuide(S, Fn); });
12910
12911 switch (Cand->FailureKind) {
12914 return DiagnoseArityMismatch(S, Cand, NumArgs);
12915
12917 return DiagnoseBadDeduction(S, Cand, NumArgs,
12918 TakingCandidateAddress);
12919
12921 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12922 << (Fn->getPrimaryTemplate() ? 1 : 0);
12923 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12924 return;
12925 }
12926
12928 Qualifiers QualsForPrinting;
12929 QualsForPrinting.setAddressSpace(CtorDestAS);
12930 S.Diag(Fn->getLocation(),
12931 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12932 << QualsForPrinting;
12933 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12934 return;
12935 }
12936
12940 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12941
12943 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12944 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12945 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12946 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12947
12948 // FIXME: this currently happens when we're called from SemaInit
12949 // when user-conversion overload fails. Figure out how to handle
12950 // those conditions and diagnose them well.
12951 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12952 }
12953
12955 return DiagnoseBadTarget(S, Cand);
12956
12957 case ovl_fail_enable_if:
12958 return DiagnoseFailedEnableIfAttr(S, Cand);
12959
12960 case ovl_fail_explicit:
12961 return DiagnoseFailedExplicitSpec(S, Cand);
12962
12964 // It's generally not interesting to note copy/move constructors here.
12965 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12966 return;
12967 S.Diag(Fn->getLocation(),
12968 diag::note_ovl_candidate_inherited_constructor_slice)
12969 << (Fn->getPrimaryTemplate() ? 1 : 0)
12970 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12971 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12972 return;
12973
12975 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
12976 (void)Available;
12977 assert(!Available);
12978 break;
12979 }
12981 // Do nothing, these should simply be ignored.
12982 break;
12983
12985 std::string FnDesc;
12986 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12987 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12988 Cand->getRewriteKind(), FnDesc);
12989
12990 S.Diag(Fn->getLocation(),
12991 diag::note_ovl_candidate_constraints_not_satisfied)
12992 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12993 << FnDesc /* Ignored */;
12994 ConstraintSatisfaction Satisfaction;
12995 if (S.CheckFunctionConstraints(Fn, Satisfaction, SourceLocation(),
12996 /*ForOverloadResolution=*/true))
12997 break;
12998 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12999 }
13000 }
13001}
13002
13005 return;
13006
13007 // Desugar the type of the surrogate down to a function type,
13008 // retaining as many typedefs as possible while still showing
13009 // the function type (and, therefore, its parameter types).
13010 QualType FnType = Cand->Surrogate->getConversionType();
13011 bool isLValueReference = false;
13012 bool isRValueReference = false;
13013 bool isPointer = false;
13014 if (const LValueReferenceType *FnTypeRef =
13015 FnType->getAs<LValueReferenceType>()) {
13016 FnType = FnTypeRef->getPointeeType();
13017 isLValueReference = true;
13018 } else if (const RValueReferenceType *FnTypeRef =
13019 FnType->getAs<RValueReferenceType>()) {
13020 FnType = FnTypeRef->getPointeeType();
13021 isRValueReference = true;
13022 }
13023 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
13024 FnType = FnTypePtr->getPointeeType();
13025 isPointer = true;
13026 }
13027 // Desugar down to a function type.
13028 FnType = QualType(FnType->getAs<FunctionType>(), 0);
13029 // Reconstruct the pointer/reference as appropriate.
13030 if (isPointer) FnType = S.Context.getPointerType(FnType);
13031 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
13032 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
13033
13034 if (!Cand->Viable &&
13036 S.Diag(Cand->Surrogate->getLocation(),
13037 diag::note_ovl_surrogate_constraints_not_satisfied)
13038 << Cand->Surrogate;
13039 ConstraintSatisfaction Satisfaction;
13040 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
13041 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
13042 } else {
13043 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
13044 << FnType;
13045 }
13046}
13047
13048static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
13049 SourceLocation OpLoc,
13050 OverloadCandidate *Cand) {
13051 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
13052 std::string TypeStr("operator");
13053 TypeStr += Opc;
13054 TypeStr += "(";
13055 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
13056 if (Cand->Conversions.size() == 1) {
13057 TypeStr += ")";
13058 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
13059 } else {
13060 TypeStr += ", ";
13061 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
13062 TypeStr += ")";
13063 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
13064 }
13065}
13066
13068 OverloadCandidate *Cand) {
13069 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
13070 if (ICS.isBad()) break; // all meaningless after first invalid
13071 if (!ICS.isAmbiguous()) continue;
13072
13074 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
13075 }
13076}
13077
13079 if (Cand->Function)
13080 return Cand->Function->getLocation();
13081 if (Cand->IsSurrogate)
13082 return Cand->Surrogate->getLocation();
13083 return SourceLocation();
13084}
13085
13086static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
13087 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
13091 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
13092
13096 return 1;
13097
13100 return 2;
13101
13109 return 3;
13110
13112 return 4;
13113
13115 return 5;
13116
13119 return 6;
13120 }
13121 llvm_unreachable("Unhandled deduction result");
13122}
13123
13124namespace {
13125
13126struct CompareOverloadCandidatesForDisplay {
13127 Sema &S;
13128 SourceLocation Loc;
13129 size_t NumArgs;
13131
13132 CompareOverloadCandidatesForDisplay(
13133 Sema &S, SourceLocation Loc, size_t NArgs,
13135 : S(S), NumArgs(NArgs), CSK(CSK) {}
13136
13137 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
13138 // If there are too many or too few arguments, that's the high-order bit we
13139 // want to sort by, even if the immediate failure kind was something else.
13140 if (C->FailureKind == ovl_fail_too_many_arguments ||
13141 C->FailureKind == ovl_fail_too_few_arguments)
13142 return static_cast<OverloadFailureKind>(C->FailureKind);
13143
13144 if (C->Function) {
13145 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
13147 if (NumArgs < C->Function->getMinRequiredArguments())
13149 }
13150
13151 return static_cast<OverloadFailureKind>(C->FailureKind);
13152 }
13153
13154 bool operator()(const OverloadCandidate *L,
13155 const OverloadCandidate *R) {
13156 // Fast-path this check.
13157 if (L == R) return false;
13158
13159 // Order first by viability.
13160 if (L->Viable) {
13161 if (!R->Viable) return true;
13162
13163 if (int Ord = CompareConversions(*L, *R))
13164 return Ord < 0;
13165 // Use other tie breakers.
13166 } else if (R->Viable)
13167 return false;
13168
13169 assert(L->Viable == R->Viable);
13170
13171 // Criteria by which we can sort non-viable candidates:
13172 if (!L->Viable) {
13173 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
13174 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
13175
13176 // 1. Arity mismatches come after other candidates.
13177 if (LFailureKind == ovl_fail_too_many_arguments ||
13178 LFailureKind == ovl_fail_too_few_arguments) {
13179 if (RFailureKind == ovl_fail_too_many_arguments ||
13180 RFailureKind == ovl_fail_too_few_arguments) {
13181 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
13182 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
13183 if (LDist == RDist) {
13184 if (LFailureKind == RFailureKind)
13185 // Sort non-surrogates before surrogates.
13186 return !L->IsSurrogate && R->IsSurrogate;
13187 // Sort candidates requiring fewer parameters than there were
13188 // arguments given after candidates requiring more parameters
13189 // than there were arguments given.
13190 return LFailureKind == ovl_fail_too_many_arguments;
13191 }
13192 return LDist < RDist;
13193 }
13194 return false;
13195 }
13196 if (RFailureKind == ovl_fail_too_many_arguments ||
13197 RFailureKind == ovl_fail_too_few_arguments)
13198 return true;
13199
13200 // 2. Bad conversions come first and are ordered by the number
13201 // of bad conversions and quality of good conversions.
13202 if (LFailureKind == ovl_fail_bad_conversion) {
13203 if (RFailureKind != ovl_fail_bad_conversion)
13204 return true;
13205
13206 // The conversion that can be fixed with a smaller number of changes,
13207 // comes first.
13208 unsigned numLFixes = L->Fix.NumConversionsFixed;
13209 unsigned numRFixes = R->Fix.NumConversionsFixed;
13210 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
13211 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
13212 if (numLFixes != numRFixes) {
13213 return numLFixes < numRFixes;
13214 }
13215
13216 // If there's any ordering between the defined conversions...
13217 if (int Ord = CompareConversions(*L, *R))
13218 return Ord < 0;
13219 } else if (RFailureKind == ovl_fail_bad_conversion)
13220 return false;
13221
13222 if (LFailureKind == ovl_fail_bad_deduction) {
13223 if (RFailureKind != ovl_fail_bad_deduction)
13224 return true;
13225
13226 if (L->DeductionFailure.Result != R->DeductionFailure.Result) {
13227 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
13228 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
13229 if (LRank != RRank)
13230 return LRank < RRank;
13231 }
13232 } else if (RFailureKind == ovl_fail_bad_deduction)
13233 return false;
13234
13235 // TODO: others?
13236 }
13237
13238 // Sort everything else by location.
13239 SourceLocation LLoc = GetLocationForCandidate(L);
13240 SourceLocation RLoc = GetLocationForCandidate(R);
13241
13242 // Put candidates without locations (e.g. builtins) at the end.
13243 if (LLoc.isValid() && RLoc.isValid())
13244 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13245 if (LLoc.isValid() && !RLoc.isValid())
13246 return true;
13247 if (RLoc.isValid() && !LLoc.isValid())
13248 return false;
13249 assert(!LLoc.isValid() && !RLoc.isValid());
13250 // For builtins and other functions without locations, fallback to the order
13251 // in which they were added into the candidate set.
13252 return L < R;
13253 }
13254
13255private:
13256 struct ConversionSignals {
13257 unsigned KindRank = 0;
13259
13260 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
13261 ConversionSignals Sig;
13262 Sig.KindRank = Seq.getKindRank();
13263 if (Seq.isStandard())
13264 Sig.Rank = Seq.Standard.getRank();
13265 else if (Seq.isUserDefined())
13266 Sig.Rank = Seq.UserDefined.After.getRank();
13267 // We intend StaticObjectArgumentConversion to compare the same as
13268 // StandardConversion with ICR_ExactMatch rank.
13269 return Sig;
13270 }
13271
13272 static ConversionSignals ForObjectArgument() {
13273 // We intend StaticObjectArgumentConversion to compare the same as
13274 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13275 return {};
13276 }
13277 };
13278
13279 // Returns -1 if conversions in L are considered better.
13280 // 0 if they are considered indistinguishable.
13281 // 1 if conversions in R are better.
13282 int CompareConversions(const OverloadCandidate &L,
13283 const OverloadCandidate &R) {
13284 // We cannot use `isBetterOverloadCandidate` because it is defined
13285 // according to the C++ standard and provides a partial order, but we need
13286 // a total order as this function is used in sort.
13287 assert(L.Conversions.size() == R.Conversions.size());
13288 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13289 auto LS = L.IgnoreObjectArgument && I == 0
13290 ? ConversionSignals::ForObjectArgument()
13291 : ConversionSignals::ForSequence(L.Conversions[I]);
13292 auto RS = R.IgnoreObjectArgument
13293 ? ConversionSignals::ForObjectArgument()
13294 : ConversionSignals::ForSequence(R.Conversions[I]);
13295 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
13296 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
13297 ? -1
13298 : 1;
13299 }
13300 // FIXME: find a way to compare templates for being more or less
13301 // specialized that provides a strict weak ordering.
13302 return 0;
13303 }
13304};
13305}
13306
13307/// CompleteNonViableCandidate - Normally, overload resolution only
13308/// computes up to the first bad conversion. Produces the FixIt set if
13309/// possible.
13310static void
13312 ArrayRef<Expr *> Args,
13314 assert(!Cand->Viable);
13315
13316 // Don't do anything on failures other than bad conversion.
13318 return;
13319
13320 // We only want the FixIts if all the arguments can be corrected.
13321 bool Unfixable = false;
13322 // Use a implicit copy initialization to check conversion fixes.
13324
13325 // Attempt to fix the bad conversion.
13326 unsigned ConvCount = Cand->Conversions.size();
13327 for (unsigned ConvIdx =
13328 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13329 : 0);
13330 /**/; ++ConvIdx) {
13331 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13332 if (Cand->Conversions[ConvIdx].isInitialized() &&
13333 Cand->Conversions[ConvIdx].isBad()) {
13334 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13335 break;
13336 }
13337 }
13338
13339 // FIXME: this should probably be preserved from the overload
13340 // operation somehow.
13341 bool SuppressUserConversions = false;
13342
13343 unsigned ConvIdx = 0;
13344 unsigned ArgIdx = 0;
13345 ArrayRef<QualType> ParamTypes;
13346 bool Reversed = Cand->isReversed();
13347
13348 if (Cand->IsSurrogate) {
13349 QualType ConvType
13351 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13352 ConvType = ConvPtrType->getPointeeType();
13353 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13354 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13355 ConvIdx = 1;
13356 } else if (Cand->Function) {
13357 ParamTypes =
13358 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13359 if (isa<CXXMethodDecl>(Cand->Function) &&
13362 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13363 ConvIdx = 1;
13365 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13367 OO_Subscript)
13368 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13369 ArgIdx = 1;
13370 }
13371 } else {
13372 // Builtin operator.
13373 assert(ConvCount <= 3);
13374 ParamTypes = Cand->BuiltinParamTypes;
13375 }
13376
13377 // Fill in the rest of the conversions.
13378 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13379 ConvIdx != ConvCount && ArgIdx < Args.size();
13380 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13381 if (Cand->Conversions[ConvIdx].isInitialized()) {
13382 // We've already checked this conversion.
13383 } else if (ParamIdx < ParamTypes.size()) {
13384 if (ParamTypes[ParamIdx]->isDependentType())
13385 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13386 Args[ArgIdx]->getType());
13387 else {
13388 Cand->Conversions[ConvIdx] =
13389 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
13390 SuppressUserConversions,
13391 /*InOverloadResolution=*/true,
13392 /*AllowObjCWritebackConversion=*/
13393 S.getLangOpts().ObjCAutoRefCount);
13394 // Store the FixIt in the candidate if it exists.
13395 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13396 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13397 }
13398 } else
13399 Cand->Conversions[ConvIdx].setEllipsis();
13400 }
13401}
13402
13405 SourceLocation OpLoc,
13406 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13407
13409
13410 // Sort the candidates by viability and position. Sorting directly would
13411 // be prohibitive, so we make a set of pointers and sort those.
13413 if (OCD == OCD_AllCandidates) Cands.reserve(size());
13414 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13415 Cand != LastCand; ++Cand) {
13416 if (!Filter(*Cand))
13417 continue;
13418 switch (OCD) {
13419 case OCD_AllCandidates:
13420 if (!Cand->Viable) {
13421 if (!Cand->Function && !Cand->IsSurrogate) {
13422 // This a non-viable builtin candidate. We do not, in general,
13423 // want to list every possible builtin candidate.
13424 continue;
13425 }
13426 CompleteNonViableCandidate(S, Cand, Args, Kind);
13427 }
13428 break;
13429
13431 if (!Cand->Viable)
13432 continue;
13433 break;
13434
13436 if (!Cand->Best)
13437 continue;
13438 break;
13439 }
13440
13441 Cands.push_back(Cand);
13442 }
13443
13444 llvm::stable_sort(
13445 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13446
13447 return Cands;
13448}
13449
13451 SourceLocation OpLoc) {
13452 bool DeferHint = false;
13453 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13454 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13455 // host device candidates.
13456 auto WrongSidedCands =
13457 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
13458 return (Cand.Viable == false &&
13460 (Cand.Function &&
13461 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13462 Cand.Function->template hasAttr<CUDADeviceAttr>());
13463 });
13464 DeferHint = !WrongSidedCands.empty();
13465 }
13466 return DeferHint;
13467}
13468
13469/// When overload resolution fails, prints diagnostic messages containing the
13470/// candidates in the candidate set.
13473 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13474 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13475
13476 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13477
13478 {
13479 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13480 S.Diag(PD.first, PD.second);
13481 }
13482
13483 // In WebAssembly we don't want to emit further diagnostics if a table is
13484 // passed as an argument to a function.
13485 bool NoteCands = true;
13486 for (const Expr *Arg : Args) {
13487 if (Arg->getType()->isWebAssemblyTableType())
13488 NoteCands = false;
13489 }
13490
13491 if (NoteCands)
13492 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13493
13494 if (OCD == OCD_AmbiguousCandidates)
13496 {Candidates.begin(), Candidates.end()});
13497}
13498
13501 StringRef Opc, SourceLocation OpLoc) {
13502 bool ReportedAmbiguousConversions = false;
13503
13504 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13505 unsigned CandsShown = 0;
13506 auto I = Cands.begin(), E = Cands.end();
13507 for (; I != E; ++I) {
13508 OverloadCandidate *Cand = *I;
13509
13510 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13511 ShowOverloads == Ovl_Best) {
13512 break;
13513 }
13514 ++CandsShown;
13515
13516 if (Cand->Function)
13517 NoteFunctionCandidate(S, Cand, Args.size(),
13518 Kind == CSK_AddressOfOverloadSet, DestAS);
13519 else if (Cand->IsSurrogate)
13520 NoteSurrogateCandidate(S, Cand);
13521 else {
13522 assert(Cand->Viable &&
13523 "Non-viable built-in candidates are not added to Cands.");
13524 // Generally we only see ambiguities including viable builtin
13525 // operators if overload resolution got screwed up by an
13526 // ambiguous user-defined conversion.
13527 //
13528 // FIXME: It's quite possible for different conversions to see
13529 // different ambiguities, though.
13530 if (!ReportedAmbiguousConversions) {
13531 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13532 ReportedAmbiguousConversions = true;
13533 }
13534
13535 // If this is a viable builtin, print it.
13536 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13537 }
13538 }
13539
13540 // Inform S.Diags that we've shown an overload set with N elements. This may
13541 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13542 S.Diags.overloadCandidatesShown(CandsShown);
13543
13544 if (I != E) {
13545 Sema::DeferDiagsRAII RAII{S, shouldDeferDiags(S, Args, OpLoc)};
13546 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
13547 }
13548}
13549
13551 const Sema &S) const {
13552 if (S.getLangOpts().CUDA) {
13553 auto *Caller = S.getCurFunctionDecl(true);
13554 // Overloading based on __host__ and __device__ attributes takes
13555 // higher priority, HD functions may favor template candidates even when a
13556 // non-template candidate would be a perfect match.
13557 if (Caller && Caller->hasAttr<CUDAHostAttr>() &&
13558 Caller->hasAttr<CUDADeviceAttr>())
13559 return false;
13560 }
13561
13562 return
13563 // For user defined conversion we need to check against different
13564 // combination of CV qualifiers and look at any explicit specifier, so
13565 // always deduce template candidates.
13567 // When doing code completion, we want to see all the
13568 // viable candidates.
13569 && Kind != CSK_CodeCompletion;
13570}
13571
13572static SourceLocation
13574 return Cand->Specialization ? Cand->Specialization->getLocation()
13575 : SourceLocation();
13576}
13577
13578namespace {
13579struct CompareTemplateSpecCandidatesForDisplay {
13580 Sema &S;
13581 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13582
13583 bool operator()(const TemplateSpecCandidate *L,
13584 const TemplateSpecCandidate *R) {
13585 // Fast-path this check.
13586 if (L == R)
13587 return false;
13588
13589 // Assuming that both candidates are not matches...
13590
13591 // Sort by the ranking of deduction failures.
13592 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
13594 RankDeductionFailure(R->DeductionFailure);
13595
13596 // Sort everything else by location.
13597 SourceLocation LLoc = GetLocationForCandidate(L);
13598 SourceLocation RLoc = GetLocationForCandidate(R);
13599
13600 // Put candidates without locations (e.g. builtins) at the end.
13601 if (LLoc.isInvalid())
13602 return false;
13603 if (RLoc.isInvalid())
13604 return true;
13605
13606 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13607 }
13608};
13609}
13610
13611/// Diagnose a template argument deduction failure.
13612/// We are treating these failures as overload failures due to bad
13613/// deductions.
13615 bool ForTakingAddress) {
13617 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
13618}
13619
13620void TemplateSpecCandidateSet::destroyCandidates() {
13621 for (iterator i = begin(), e = end(); i != e; ++i) {
13622 i->DeductionFailure.Destroy();
13623 }
13624}
13625
13627 destroyCandidates();
13628 Candidates.clear();
13629}
13630
13631/// NoteCandidates - When no template specialization match is found, prints
13632/// diagnostic messages containing the non-matching specializations that form
13633/// the candidate set.
13634/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13635/// OCD == OCD_AllCandidates and Cand->Viable == false.
13637 // Sort the candidates by position (assuming no candidate is a match).
13638 // Sorting directly would be prohibitive, so we make a set of pointers
13639 // and sort those.
13641 Cands.reserve(size());
13642 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13643 if (Cand->Specialization)
13644 Cands.push_back(Cand);
13645 // Otherwise, this is a non-matching builtin candidate. We do not,
13646 // in general, want to list every possible builtin candidate.
13647 }
13648
13649 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
13650
13651 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13652 // for generalization purposes (?).
13653 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13654
13656 unsigned CandsShown = 0;
13657 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13658 TemplateSpecCandidate *Cand = *I;
13659
13660 // Set an arbitrary limit on the number of candidates we'll spam
13661 // the user with. FIXME: This limit should depend on details of the
13662 // candidate list.
13663 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13664 break;
13665 ++CandsShown;
13666
13667 assert(Cand->Specialization &&
13668 "Non-matching built-in candidates are not added to Cands.");
13669 Cand->NoteDeductionFailure(S, ForTakingAddress);
13670 }
13671
13672 if (I != E)
13673 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
13674}
13675
13676// [PossiblyAFunctionType] --> [Return]
13677// NonFunctionType --> NonFunctionType
13678// R (A) --> R(A)
13679// R (*)(A) --> R (A)
13680// R (&)(A) --> R (A)
13681// R (S::*)(A) --> R (A)
13683 QualType Ret = PossiblyAFunctionType;
13684 if (const PointerType *ToTypePtr =
13685 PossiblyAFunctionType->getAs<PointerType>())
13686 Ret = ToTypePtr->getPointeeType();
13687 else if (const ReferenceType *ToTypeRef =
13688 PossiblyAFunctionType->getAs<ReferenceType>())
13689 Ret = ToTypeRef->getPointeeType();
13690 else if (const MemberPointerType *MemTypePtr =
13691 PossiblyAFunctionType->getAs<MemberPointerType>())
13692 Ret = MemTypePtr->getPointeeType();
13693 Ret =
13694 Context.getCanonicalType(Ret).getUnqualifiedType();
13695 return Ret;
13696}
13697
13699 bool Complain = true) {
13700 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13701 S.DeduceReturnType(FD, Loc, Complain))
13702 return true;
13703
13704 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13705 if (S.getLangOpts().CPlusPlus17 &&
13706 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
13707 !S.ResolveExceptionSpec(Loc, FPT))
13708 return true;
13709
13710 return false;
13711}
13712
13713namespace {
13714// A helper class to help with address of function resolution
13715// - allows us to avoid passing around all those ugly parameters
13716class AddressOfFunctionResolver {
13717 Sema& S;
13718 Expr* SourceExpr;
13719 const QualType& TargetType;
13720 QualType TargetFunctionType; // Extracted function type from target type
13721
13722 bool Complain;
13723 //DeclAccessPair& ResultFunctionAccessPair;
13724 ASTContext& Context;
13725
13726 bool TargetTypeIsNonStaticMemberFunction;
13727 bool FoundNonTemplateFunction;
13728 bool StaticMemberFunctionFromBoundPointer;
13729 bool HasComplained;
13730
13731 OverloadExpr::FindResult OvlExprInfo;
13732 OverloadExpr *OvlExpr;
13733 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13734 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13735 TemplateSpecCandidateSet FailedCandidates;
13736
13737public:
13738 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13739 const QualType &TargetType, bool Complain)
13740 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13741 Complain(Complain), Context(S.getASTContext()),
13742 TargetTypeIsNonStaticMemberFunction(
13743 !!TargetType->getAs<MemberPointerType>()),
13744 FoundNonTemplateFunction(false),
13745 StaticMemberFunctionFromBoundPointer(false),
13746 HasComplained(false),
13747 OvlExprInfo(OverloadExpr::find(SourceExpr)),
13748 OvlExpr(OvlExprInfo.Expression),
13749 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13750 ExtractUnqualifiedFunctionTypeFromTargetType();
13751
13752 if (TargetFunctionType->isFunctionType()) {
13753 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
13754 if (!UME->isImplicitAccess() &&
13756 StaticMemberFunctionFromBoundPointer = true;
13757 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13758 DeclAccessPair dap;
13759 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13760 OvlExpr, false, &dap)) {
13761 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
13762 if (!Method->isStatic()) {
13763 // If the target type is a non-function type and the function found
13764 // is a non-static member function, pretend as if that was the
13765 // target, it's the only possible type to end up with.
13766 TargetTypeIsNonStaticMemberFunction = true;
13767
13768 // And skip adding the function if its not in the proper form.
13769 // We'll diagnose this due to an empty set of functions.
13770 if (!OvlExprInfo.HasFormOfMemberPointer)
13771 return;
13772 }
13773
13774 Matches.push_back(std::make_pair(dap, Fn));
13775 }
13776 return;
13777 }
13778
13779 if (OvlExpr->hasExplicitTemplateArgs())
13780 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
13781
13782 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13783 if (Matches.size() > 1 && S.getLangOpts().CUDA)
13784 EliminateSuboptimalCudaMatches();
13785
13786 // C++ [over.over]p4:
13787 // If more than one function is selected, [...]
13788 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13789 if (FoundNonTemplateFunction) {
13790 EliminateAllTemplateMatches();
13791 EliminateLessPartialOrderingConstrainedMatches();
13792 } else
13793 EliminateAllExceptMostSpecializedTemplate();
13794 }
13795 }
13796 }
13797
13798 bool hasComplained() const { return HasComplained; }
13799
13800private:
13801 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13802 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
13803 S.IsFunctionConversion(FD->getType(), TargetFunctionType);
13804 }
13805
13806 /// \return true if A is considered a better overload candidate for the
13807 /// desired type than B.
13808 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13809 // If A doesn't have exactly the correct type, we don't want to classify it
13810 // as "better" than anything else. This way, the user is required to
13811 // disambiguate for us if there are multiple candidates and no exact match.
13812 return candidateHasExactlyCorrectType(A) &&
13813 (!candidateHasExactlyCorrectType(B) ||
13814 compareEnableIfAttrs(S, A, B) == Comparison::Better);
13815 }
13816
13817 /// \return true if we were able to eliminate all but one overload candidate,
13818 /// false otherwise.
13819 bool eliminiateSuboptimalOverloadCandidates() {
13820 // Same algorithm as overload resolution -- one pass to pick the "best",
13821 // another pass to be sure that nothing is better than the best.
13822 auto Best = Matches.begin();
13823 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13824 if (isBetterCandidate(I->second, Best->second))
13825 Best = I;
13826
13827 const FunctionDecl *BestFn = Best->second;
13828 auto IsBestOrInferiorToBest = [this, BestFn](
13829 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13830 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
13831 };
13832
13833 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13834 // option, so we can potentially give the user a better error
13835 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
13836 return false;
13837 Matches[0] = *Best;
13838 Matches.resize(1);
13839 return true;
13840 }
13841
13842 bool isTargetTypeAFunction() const {
13843 return TargetFunctionType->isFunctionType();
13844 }
13845
13846 // [ToType] [Return]
13847
13848 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13849 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13850 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13851 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13852 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13853 }
13854
13855 // return true if any matching specializations were found
13856 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13857 const DeclAccessPair& CurAccessFunPair) {
13858 if (CXXMethodDecl *Method
13859 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13860 // Skip non-static function templates when converting to pointer, and
13861 // static when converting to member pointer.
13862 bool CanConvertToFunctionPointer =
13863 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13864 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13865 return false;
13866 }
13867 else if (TargetTypeIsNonStaticMemberFunction)
13868 return false;
13869
13870 // C++ [over.over]p2:
13871 // If the name is a function template, template argument deduction is
13872 // done (14.8.2.2), and if the argument deduction succeeds, the
13873 // resulting template argument list is used to generate a single
13874 // function template specialization, which is added to the set of
13875 // overloaded functions considered.
13876 FunctionDecl *Specialization = nullptr;
13877 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13879 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13880 Specialization, Info, /*IsAddressOfFunction*/ true);
13881 Result != TemplateDeductionResult::Success) {
13882 // Make a note of the failed deduction for diagnostics.
13883 FailedCandidates.addCandidate()
13884 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13885 MakeDeductionFailureInfo(Context, Result, Info));
13886 return false;
13887 }
13888
13889 // Template argument deduction ensures that we have an exact match or
13890 // compatible pointer-to-function arguments that would be adjusted by ICS.
13891 // This function template specicalization works.
13893 Context.getCanonicalType(Specialization->getType()),
13894 Context.getCanonicalType(TargetFunctionType)));
13895
13897 return false;
13898
13899 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13900 return true;
13901 }
13902
13903 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13904 const DeclAccessPair& CurAccessFunPair) {
13905 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13906 // Skip non-static functions when converting to pointer, and static
13907 // when converting to member pointer.
13908 bool CanConvertToFunctionPointer =
13909 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13910 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13911 return false;
13912 }
13913 else if (TargetTypeIsNonStaticMemberFunction)
13914 return false;
13915
13916 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13917 if (S.getLangOpts().CUDA) {
13918 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13919 if (!(Caller && Caller->isImplicit()) &&
13920 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13921 return false;
13922 }
13923 if (FunDecl->isMultiVersion()) {
13924 const auto *TA = FunDecl->getAttr<TargetAttr>();
13925 if (TA && !TA->isDefaultVersion())
13926 return false;
13927 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13928 if (TVA && !TVA->isDefaultVersion())
13929 return false;
13930 }
13931
13932 // If any candidate has a placeholder return type, trigger its deduction
13933 // now.
13934 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13935 Complain)) {
13936 HasComplained |= Complain;
13937 return false;
13938 }
13939
13940 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13941 return false;
13942
13943 // If we're in C, we need to support types that aren't exactly identical.
13944 if (!S.getLangOpts().CPlusPlus ||
13945 candidateHasExactlyCorrectType(FunDecl)) {
13946 Matches.push_back(std::make_pair(
13947 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13948 FoundNonTemplateFunction = true;
13949 return true;
13950 }
13951 }
13952
13953 return false;
13954 }
13955
13956 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13957 bool Ret = false;
13958
13959 // If the overload expression doesn't have the form of a pointer to
13960 // member, don't try to convert it to a pointer-to-member type.
13961 if (IsInvalidFormOfPointerToMemberFunction())
13962 return false;
13963
13964 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13965 E = OvlExpr->decls_end();
13966 I != E; ++I) {
13967 // Look through any using declarations to find the underlying function.
13968 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13969
13970 // C++ [over.over]p3:
13971 // Non-member functions and static member functions match
13972 // targets of type "pointer-to-function" or "reference-to-function."
13973 // Nonstatic member functions match targets of
13974 // type "pointer-to-member-function."
13975 // Note that according to DR 247, the containing class does not matter.
13976 if (FunctionTemplateDecl *FunctionTemplate
13977 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13978 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13979 Ret = true;
13980 }
13981 // If we have explicit template arguments supplied, skip non-templates.
13982 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13983 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13984 Ret = true;
13985 }
13986 assert(Ret || Matches.empty());
13987 return Ret;
13988 }
13989
13990 void EliminateAllExceptMostSpecializedTemplate() {
13991 // [...] and any given function template specialization F1 is
13992 // eliminated if the set contains a second function template
13993 // specialization whose function template is more specialized
13994 // than the function template of F1 according to the partial
13995 // ordering rules of 14.5.5.2.
13996
13997 // The algorithm specified above is quadratic. We instead use a
13998 // two-pass algorithm (similar to the one used to identify the
13999 // best viable function in an overload set) that identifies the
14000 // best function template (if it exists).
14001
14002 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
14003 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
14004 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
14005
14006 // TODO: It looks like FailedCandidates does not serve much purpose
14007 // here, since the no_viable diagnostic has index 0.
14008 UnresolvedSetIterator Result = S.getMostSpecialized(
14009 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
14010 SourceExpr->getBeginLoc(), S.PDiag(),
14011 S.PDiag(diag::err_addr_ovl_ambiguous)
14012 << Matches[0].second->getDeclName(),
14013 S.PDiag(diag::note_ovl_candidate)
14014 << (unsigned)oc_function << (unsigned)ocs_described_template,
14015 Complain, TargetFunctionType);
14016
14017 if (Result != MatchesCopy.end()) {
14018 // Make it the first and only element
14019 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
14020 Matches[0].second = cast<FunctionDecl>(*Result);
14021 Matches.resize(1);
14022 } else
14023 HasComplained |= Complain;
14024 }
14025
14026 void EliminateAllTemplateMatches() {
14027 // [...] any function template specializations in the set are
14028 // eliminated if the set also contains a non-template function, [...]
14029 for (unsigned I = 0, N = Matches.size(); I != N; ) {
14030 if (Matches[I].second->getPrimaryTemplate() == nullptr)
14031 ++I;
14032 else {
14033 Matches[I] = Matches[--N];
14034 Matches.resize(N);
14035 }
14036 }
14037 }
14038
14039 void EliminateLessPartialOrderingConstrainedMatches() {
14040 // C++ [over.over]p5:
14041 // [...] Any given non-template function F0 is eliminated if the set
14042 // contains a second non-template function that is more
14043 // partial-ordering-constrained than F0. [...]
14044 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
14045 "Call EliminateAllTemplateMatches() first");
14046 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
14047 Results.push_back(Matches[0]);
14048 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
14049 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
14050 FunctionDecl *F = getMorePartialOrderingConstrained(
14051 S, Matches[I].second, Results[0].second,
14052 /*IsFn1Reversed=*/false,
14053 /*IsFn2Reversed=*/false);
14054 if (!F) {
14055 Results.push_back(Matches[I]);
14056 continue;
14057 }
14058 if (F == Matches[I].second) {
14059 Results.clear();
14060 Results.push_back(Matches[I]);
14061 }
14062 }
14063 std::swap(Matches, Results);
14064 }
14065
14066 void EliminateSuboptimalCudaMatches() {
14067 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
14068 Matches);
14069 }
14070
14071public:
14072 void ComplainNoMatchesFound() const {
14073 assert(Matches.empty());
14074 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
14075 << OvlExpr->getName() << TargetFunctionType
14076 << OvlExpr->getSourceRange();
14077 if (FailedCandidates.empty())
14078 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
14079 /*TakingAddress=*/true);
14080 else {
14081 // We have some deduction failure messages. Use them to diagnose
14082 // the function templates, and diagnose the non-template candidates
14083 // normally.
14084 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
14085 IEnd = OvlExpr->decls_end();
14086 I != IEnd; ++I)
14087 if (FunctionDecl *Fun =
14088 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
14090 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
14091 /*TakingAddress=*/true);
14092 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
14093 }
14094 }
14095
14096 bool IsInvalidFormOfPointerToMemberFunction() const {
14097 return TargetTypeIsNonStaticMemberFunction &&
14098 !OvlExprInfo.HasFormOfMemberPointer;
14099 }
14100
14101 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
14102 // TODO: Should we condition this on whether any functions might
14103 // have matched, or is it more appropriate to do that in callers?
14104 // TODO: a fixit wouldn't hurt.
14105 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
14106 << TargetType << OvlExpr->getSourceRange();
14107 }
14108
14109 bool IsStaticMemberFunctionFromBoundPointer() const {
14110 return StaticMemberFunctionFromBoundPointer;
14111 }
14112
14113 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
14114 S.Diag(OvlExpr->getBeginLoc(),
14115 diag::err_invalid_form_pointer_member_function)
14116 << OvlExpr->getSourceRange();
14117 }
14118
14119 void ComplainOfInvalidConversion() const {
14120 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
14121 << OvlExpr->getName() << TargetType;
14122 }
14123
14124 void ComplainMultipleMatchesFound() const {
14125 assert(Matches.size() > 1);
14126 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
14127 << OvlExpr->getName() << OvlExpr->getSourceRange();
14128 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
14129 /*TakingAddress=*/true);
14130 }
14131
14132 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
14133
14134 int getNumMatches() const { return Matches.size(); }
14135
14136 FunctionDecl* getMatchingFunctionDecl() const {
14137 if (Matches.size() != 1) return nullptr;
14138 return Matches[0].second;
14139 }
14140
14141 const DeclAccessPair* getMatchingFunctionAccessPair() const {
14142 if (Matches.size() != 1) return nullptr;
14143 return &Matches[0].first;
14144 }
14145};
14146}
14147
14148FunctionDecl *
14150 QualType TargetType,
14151 bool Complain,
14152 DeclAccessPair &FoundResult,
14153 bool *pHadMultipleCandidates) {
14154 assert(AddressOfExpr->getType() == Context.OverloadTy);
14155
14156 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
14157 Complain);
14158 int NumMatches = Resolver.getNumMatches();
14159 FunctionDecl *Fn = nullptr;
14160 bool ShouldComplain = Complain && !Resolver.hasComplained();
14161 if (NumMatches == 0 && ShouldComplain) {
14162 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
14163 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
14164 else
14165 Resolver.ComplainNoMatchesFound();
14166 }
14167 else if (NumMatches > 1 && ShouldComplain)
14168 Resolver.ComplainMultipleMatchesFound();
14169 else if (NumMatches == 1) {
14170 Fn = Resolver.getMatchingFunctionDecl();
14171 assert(Fn);
14172 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
14173 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
14174 FoundResult = *Resolver.getMatchingFunctionAccessPair();
14175 if (Complain) {
14176 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
14177 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
14178 else
14179 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
14180 }
14181 }
14182
14183 if (pHadMultipleCandidates)
14184 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
14185 return Fn;
14186}
14187
14191 OverloadExpr *Ovl = R.Expression;
14192 bool IsResultAmbiguous = false;
14193 FunctionDecl *Result = nullptr;
14194 DeclAccessPair DAP;
14195 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
14196
14197 // Return positive for better, negative for worse, 0 for equal preference.
14198 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
14199 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
14200 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
14201 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
14202 };
14203
14204 // Don't use the AddressOfResolver because we're specifically looking for
14205 // cases where we have one overload candidate that lacks
14206 // enable_if/pass_object_size/...
14207 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
14208 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
14209 if (!FD)
14210 return nullptr;
14211
14213 continue;
14214
14215 // If we found a better result, update Result.
14216 auto FoundBetter = [&]() {
14217 IsResultAmbiguous = false;
14218 DAP = I.getPair();
14219 Result = FD;
14220 };
14221
14222 // We have more than one result - see if it is more
14223 // partial-ordering-constrained than the previous one.
14224 if (Result) {
14225 // Check CUDA preference first. If the candidates have differennt CUDA
14226 // preference, choose the one with higher CUDA preference. Otherwise,
14227 // choose the one with more constraints.
14228 if (getLangOpts().CUDA) {
14229 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
14230 // FD has different preference than Result.
14231 if (PreferenceByCUDA != 0) {
14232 // FD is more preferable than Result.
14233 if (PreferenceByCUDA > 0)
14234 FoundBetter();
14235 continue;
14236 }
14237 }
14238 // FD has the same CUDA preference than Result. Continue to check
14239 // constraints.
14240
14241 // C++ [over.over]p5:
14242 // [...] Any given non-template function F0 is eliminated if the set
14243 // contains a second non-template function that is more
14244 // partial-ordering-constrained than F0 [...]
14245 FunctionDecl *MoreConstrained =
14247 /*IsFn1Reversed=*/false,
14248 /*IsFn2Reversed=*/false);
14249 if (MoreConstrained != FD) {
14250 if (!MoreConstrained) {
14251 IsResultAmbiguous = true;
14252 AmbiguousDecls.push_back(FD);
14253 }
14254 continue;
14255 }
14256 // FD is more constrained - replace Result with it.
14257 }
14258 FoundBetter();
14259 }
14260
14261 if (IsResultAmbiguous)
14262 return nullptr;
14263
14264 if (Result) {
14265 // We skipped over some ambiguous declarations which might be ambiguous with
14266 // the selected result.
14267 for (FunctionDecl *Skipped : AmbiguousDecls) {
14268 // If skipped candidate has different CUDA preference than the result,
14269 // there is no ambiguity. Otherwise check whether they have different
14270 // constraints.
14271 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
14272 continue;
14273 if (!getMoreConstrainedFunction(Skipped, Result))
14274 return nullptr;
14275 }
14276 Pair = DAP;
14277 }
14278 return Result;
14279}
14280
14282 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
14283 Expr *E = SrcExpr.get();
14284 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
14285
14286 DeclAccessPair DAP;
14288 if (!Found || Found->isCPUDispatchMultiVersion() ||
14289 Found->isCPUSpecificMultiVersion())
14290 return false;
14291
14292 // Emitting multiple diagnostics for a function that is both inaccessible and
14293 // unavailable is consistent with our behavior elsewhere. So, always check
14294 // for both.
14298 if (Res.isInvalid())
14299 return false;
14300 Expr *Fixed = Res.get();
14301 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14302 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
14303 else
14304 SrcExpr = Fixed;
14305 return true;
14306}
14307
14309 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14310 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14311 // C++ [over.over]p1:
14312 // [...] [Note: any redundant set of parentheses surrounding the
14313 // overloaded function name is ignored (5.1). ]
14314 // C++ [over.over]p1:
14315 // [...] The overloaded function name can be preceded by the &
14316 // operator.
14317
14318 // If we didn't actually find any template-ids, we're done.
14319 if (!ovl->hasExplicitTemplateArgs())
14320 return nullptr;
14321
14322 TemplateArgumentListInfo ExplicitTemplateArgs;
14323 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
14324
14325 // Look through all of the overloaded functions, searching for one
14326 // whose type matches exactly.
14327 FunctionDecl *Matched = nullptr;
14328 for (UnresolvedSetIterator I = ovl->decls_begin(),
14329 E = ovl->decls_end(); I != E; ++I) {
14330 // C++0x [temp.arg.explicit]p3:
14331 // [...] In contexts where deduction is done and fails, or in contexts
14332 // where deduction is not done, if a template argument list is
14333 // specified and it, along with any default template arguments,
14334 // identifies a single function template specialization, then the
14335 // template-id is an lvalue for the function template specialization.
14337 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
14338 if (!FunctionTemplate)
14339 continue;
14340
14341 // C++ [over.over]p2:
14342 // If the name is a function template, template argument deduction is
14343 // done (14.8.2.2), and if the argument deduction succeeds, the
14344 // resulting template argument list is used to generate a single
14345 // function template specialization, which is added to the set of
14346 // overloaded functions considered.
14347 FunctionDecl *Specialization = nullptr;
14348 TemplateDeductionInfo Info(ovl->getNameLoc());
14350 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
14351 /*IsAddressOfFunction*/ true);
14353 // Make a note of the failed deduction for diagnostics.
14354 if (FailedTSC)
14355 FailedTSC->addCandidate().set(
14356 I.getPair(), FunctionTemplate->getTemplatedDecl(),
14358 continue;
14359 }
14360
14361 assert(Specialization && "no specialization and no error?");
14362
14363 // C++ [temp.deduct.call]p6:
14364 // [...] If all successful deductions yield the same deduced A, that
14365 // deduced A is the result of deduction; otherwise, the parameter is
14366 // treated as a non-deduced context.
14367 if (Matched) {
14368 if (ForTypeDeduction &&
14370 Specialization->getType()))
14371 continue;
14372 // Multiple matches; we can't resolve to a single declaration.
14373 if (Complain) {
14374 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
14375 << ovl->getName();
14377 }
14378 return nullptr;
14379 }
14380
14381 Matched = Specialization;
14382 if (FoundResult) *FoundResult = I.getPair();
14383 }
14384
14385 if (Matched &&
14386 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
14387 return nullptr;
14388
14389 return Matched;
14390}
14391
14393 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14394 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14395 unsigned DiagIDForComplaining) {
14396 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14397
14399
14400 DeclAccessPair found;
14401 ExprResult SingleFunctionExpression;
14403 ovl.Expression, /*complain*/ false, &found)) {
14404 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
14405 SrcExpr = ExprError();
14406 return true;
14407 }
14408
14409 // It is only correct to resolve to an instance method if we're
14410 // resolving a form that's permitted to be a pointer to member.
14411 // Otherwise we'll end up making a bound member expression, which
14412 // is illegal in all the contexts we resolve like this.
14413 if (!ovl.HasFormOfMemberPointer &&
14414 isa<CXXMethodDecl>(fn) &&
14415 cast<CXXMethodDecl>(fn)->isInstance()) {
14416 if (!complain) return false;
14417
14418 Diag(ovl.Expression->getExprLoc(),
14419 diag::err_bound_member_function)
14420 << 0 << ovl.Expression->getSourceRange();
14421
14422 // TODO: I believe we only end up here if there's a mix of
14423 // static and non-static candidates (otherwise the expression
14424 // would have 'bound member' type, not 'overload' type).
14425 // Ideally we would note which candidate was chosen and why
14426 // the static candidates were rejected.
14427 SrcExpr = ExprError();
14428 return true;
14429 }
14430
14431 // Fix the expression to refer to 'fn'.
14432 SingleFunctionExpression =
14433 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
14434
14435 // If desired, do function-to-pointer decay.
14436 if (doFunctionPointerConversion) {
14437 SingleFunctionExpression =
14438 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
14439 if (SingleFunctionExpression.isInvalid()) {
14440 SrcExpr = ExprError();
14441 return true;
14442 }
14443 }
14444 }
14445
14446 if (!SingleFunctionExpression.isUsable()) {
14447 if (complain) {
14448 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
14449 << ovl.Expression->getName()
14450 << DestTypeForComplaining
14451 << OpRangeForComplaining
14453 NoteAllOverloadCandidates(SrcExpr.get());
14454
14455 SrcExpr = ExprError();
14456 return true;
14457 }
14458
14459 return false;
14460 }
14461
14462 SrcExpr = SingleFunctionExpression;
14463 return true;
14464}
14465
14466/// Add a single candidate to the overload set.
14468 DeclAccessPair FoundDecl,
14469 TemplateArgumentListInfo *ExplicitTemplateArgs,
14470 ArrayRef<Expr *> Args,
14471 OverloadCandidateSet &CandidateSet,
14472 bool PartialOverloading,
14473 bool KnownValid) {
14474 NamedDecl *Callee = FoundDecl.getDecl();
14475 if (isa<UsingShadowDecl>(Callee))
14476 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
14477
14478 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
14479 if (ExplicitTemplateArgs) {
14480 assert(!KnownValid && "Explicit template arguments?");
14481 return;
14482 }
14483 // Prevent ill-formed function decls to be added as overload candidates.
14484 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
14485 return;
14486
14487 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
14488 /*SuppressUserConversions=*/false,
14489 PartialOverloading);
14490 return;
14491 }
14492
14493 if (FunctionTemplateDecl *FuncTemplate
14494 = dyn_cast<FunctionTemplateDecl>(Callee)) {
14495 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
14496 ExplicitTemplateArgs, Args, CandidateSet,
14497 /*SuppressUserConversions=*/false,
14498 PartialOverloading);
14499 return;
14500 }
14501
14502 assert(!KnownValid && "unhandled case in overloaded call candidate");
14503}
14504
14506 ArrayRef<Expr *> Args,
14507 OverloadCandidateSet &CandidateSet,
14508 bool PartialOverloading) {
14509
14510#ifndef NDEBUG
14511 // Verify that ArgumentDependentLookup is consistent with the rules
14512 // in C++0x [basic.lookup.argdep]p3:
14513 //
14514 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14515 // and let Y be the lookup set produced by argument dependent
14516 // lookup (defined as follows). If X contains
14517 //
14518 // -- a declaration of a class member, or
14519 //
14520 // -- a block-scope function declaration that is not a
14521 // using-declaration, or
14522 //
14523 // -- a declaration that is neither a function or a function
14524 // template
14525 //
14526 // then Y is empty.
14527
14528 if (ULE->requiresADL()) {
14530 E = ULE->decls_end(); I != E; ++I) {
14531 assert(!(*I)->getDeclContext()->isRecord());
14532 assert(isa<UsingShadowDecl>(*I) ||
14533 !(*I)->getDeclContext()->isFunctionOrMethod());
14534 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14535 }
14536 }
14537#endif
14538
14539 // It would be nice to avoid this copy.
14540 TemplateArgumentListInfo TABuffer;
14541 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14542 if (ULE->hasExplicitTemplateArgs()) {
14543 ULE->copyTemplateArgumentsInto(TABuffer);
14544 ExplicitTemplateArgs = &TABuffer;
14545 }
14546
14548 E = ULE->decls_end(); I != E; ++I)
14549 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14550 CandidateSet, PartialOverloading,
14551 /*KnownValid*/ true);
14552
14553 if (ULE->requiresADL())
14555 Args, ExplicitTemplateArgs,
14556 CandidateSet, PartialOverloading);
14557}
14558
14560 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14561 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14562 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14563 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14564 CandidateSet, false, /*KnownValid*/ false);
14565}
14566
14567/// Determine whether a declaration with the specified name could be moved into
14568/// a different namespace.
14570 switch (Name.getCXXOverloadedOperator()) {
14571 case OO_New: case OO_Array_New:
14572 case OO_Delete: case OO_Array_Delete:
14573 return false;
14574
14575 default:
14576 return true;
14577 }
14578}
14579
14580/// Attempt to recover from an ill-formed use of a non-dependent name in a
14581/// template, where the non-dependent name was declared after the template
14582/// was defined. This is common in code written for a compilers which do not
14583/// correctly implement two-stage name lookup.
14584///
14585/// Returns true if a viable candidate was found and a diagnostic was issued.
14587 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14589 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14590 CXXRecordDecl **FoundInClass = nullptr) {
14591 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14592 return false;
14593
14594 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14595 if (DC->isTransparentContext())
14596 continue;
14597
14598 SemaRef.LookupQualifiedName(R, DC);
14599
14600 if (!R.empty()) {
14601 R.suppressDiagnostics();
14602
14603 OverloadCandidateSet Candidates(FnLoc, CSK);
14604 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14605 Candidates);
14606
14609 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
14610
14611 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
14612 // We either found non-function declarations or a best viable function
14613 // at class scope. A class-scope lookup result disables ADL. Don't
14614 // look past this, but let the caller know that we found something that
14615 // either is, or might be, usable in this class.
14616 if (FoundInClass) {
14617 *FoundInClass = RD;
14618 if (OR == OR_Success) {
14619 R.clear();
14620 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
14621 R.resolveKind();
14622 }
14623 }
14624 return false;
14625 }
14626
14627 if (OR != OR_Success) {
14628 // There wasn't a unique best function or function template.
14629 return false;
14630 }
14631
14632 // Find the namespaces where ADL would have looked, and suggest
14633 // declaring the function there instead.
14634 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14635 Sema::AssociatedClassSet AssociatedClasses;
14636 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
14637 AssociatedNamespaces,
14638 AssociatedClasses);
14639 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14640 if (canBeDeclaredInNamespace(R.getLookupName())) {
14641 DeclContext *Std = SemaRef.getStdNamespace();
14642 for (Sema::AssociatedNamespaceSet::iterator
14643 it = AssociatedNamespaces.begin(),
14644 end = AssociatedNamespaces.end(); it != end; ++it) {
14645 // Never suggest declaring a function within namespace 'std'.
14646 if (Std && Std->Encloses(*it))
14647 continue;
14648
14649 // Never suggest declaring a function within a namespace with a
14650 // reserved name, like __gnu_cxx.
14651 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
14652 if (NS &&
14653 NS->getQualifiedNameAsString().find("__") != std::string::npos)
14654 continue;
14655
14656 SuggestedNamespaces.insert(*it);
14657 }
14658 }
14659
14660 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
14661 << R.getLookupName();
14662 if (SuggestedNamespaces.empty()) {
14663 SemaRef.Diag(Best->Function->getLocation(),
14664 diag::note_not_found_by_two_phase_lookup)
14665 << R.getLookupName() << 0;
14666 } else if (SuggestedNamespaces.size() == 1) {
14667 SemaRef.Diag(Best->Function->getLocation(),
14668 diag::note_not_found_by_two_phase_lookup)
14669 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14670 } else {
14671 // FIXME: It would be useful to list the associated namespaces here,
14672 // but the diagnostics infrastructure doesn't provide a way to produce
14673 // a localized representation of a list of items.
14674 SemaRef.Diag(Best->Function->getLocation(),
14675 diag::note_not_found_by_two_phase_lookup)
14676 << R.getLookupName() << 2;
14677 }
14678
14679 // Try to recover by calling this function.
14680 return true;
14681 }
14682
14683 R.clear();
14684 }
14685
14686 return false;
14687}
14688
14689/// Attempt to recover from ill-formed use of a non-dependent operator in a
14690/// template, where the non-dependent operator was declared after the template
14691/// was defined.
14692///
14693/// Returns true if a viable candidate was found and a diagnostic was issued.
14694static bool
14696 SourceLocation OpLoc,
14697 ArrayRef<Expr *> Args) {
14698 DeclarationName OpName =
14700 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14701 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
14703 /*ExplicitTemplateArgs=*/nullptr, Args);
14704}
14705
14706namespace {
14707class BuildRecoveryCallExprRAII {
14708 Sema &SemaRef;
14709 Sema::SatisfactionStackResetRAII SatStack;
14710
14711public:
14712 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14713 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14714 SemaRef.IsBuildingRecoveryCallExpr = true;
14715 }
14716
14717 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14718};
14719}
14720
14721/// Attempts to recover from a call where no functions were found.
14722///
14723/// This function will do one of three things:
14724/// * Diagnose, recover, and return a recovery expression.
14725/// * Diagnose, fail to recover, and return ExprError().
14726/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14727/// expected to diagnose as appropriate.
14728static ExprResult
14731 SourceLocation LParenLoc,
14733 SourceLocation RParenLoc,
14734 bool EmptyLookup, bool AllowTypoCorrection) {
14735 // Do not try to recover if it is already building a recovery call.
14736 // This stops infinite loops for template instantiations like
14737 //
14738 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14739 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14740 if (SemaRef.IsBuildingRecoveryCallExpr)
14741 return ExprResult();
14742 BuildRecoveryCallExprRAII RCE(SemaRef);
14743
14744 CXXScopeSpec SS;
14745 SS.Adopt(ULE->getQualifierLoc());
14746 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14747
14748 TemplateArgumentListInfo TABuffer;
14749 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14750 if (ULE->hasExplicitTemplateArgs()) {
14751 ULE->copyTemplateArgumentsInto(TABuffer);
14752 ExplicitTemplateArgs = &TABuffer;
14753 }
14754
14755 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14757 CXXRecordDecl *FoundInClass = nullptr;
14758 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
14760 ExplicitTemplateArgs, Args, &FoundInClass)) {
14761 // OK, diagnosed a two-phase lookup issue.
14762 } else if (EmptyLookup) {
14763 // Try to recover from an empty lookup with typo correction.
14764 R.clear();
14765 NoTypoCorrectionCCC NoTypoValidator{};
14766 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14767 ExplicitTemplateArgs != nullptr,
14768 dyn_cast<MemberExpr>(Fn));
14769 CorrectionCandidateCallback &Validator =
14770 AllowTypoCorrection
14771 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14772 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14773 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
14774 Args))
14775 return ExprError();
14776 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14777 // We found a usable declaration of the name in a dependent base of some
14778 // enclosing class.
14779 // FIXME: We should also explain why the candidates found by name lookup
14780 // were not viable.
14781 if (SemaRef.DiagnoseDependentMemberLookup(R))
14782 return ExprError();
14783 } else {
14784 // We had viable candidates and couldn't recover; let the caller diagnose
14785 // this.
14786 return ExprResult();
14787 }
14788
14789 // If we get here, we should have issued a diagnostic and formed a recovery
14790 // lookup result.
14791 assert(!R.empty() && "lookup results empty despite recovery");
14792
14793 // If recovery created an ambiguity, just bail out.
14794 if (R.isAmbiguous()) {
14795 R.suppressDiagnostics();
14796 return ExprError();
14797 }
14798
14799 // Build an implicit member call if appropriate. Just drop the
14800 // casts and such from the call, we don't really care.
14801 ExprResult NewFn = ExprError();
14802 if ((*R.begin())->isCXXClassMember())
14803 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14804 ExplicitTemplateArgs, S);
14805 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14806 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
14807 ExplicitTemplateArgs);
14808 else
14809 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
14810
14811 if (NewFn.isInvalid())
14812 return ExprError();
14813
14814 // This shouldn't cause an infinite loop because we're giving it
14815 // an expression with viable lookup results, which should never
14816 // end up here.
14817 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
14818 MultiExprArg(Args.data(), Args.size()),
14819 RParenLoc);
14820}
14821
14824 MultiExprArg Args,
14825 SourceLocation RParenLoc,
14826 OverloadCandidateSet *CandidateSet,
14827 ExprResult *Result) {
14828#ifndef NDEBUG
14829 if (ULE->requiresADL()) {
14830 // To do ADL, we must have found an unqualified name.
14831 assert(!ULE->getQualifier() && "qualified name with ADL");
14832
14833 // We don't perform ADL for implicit declarations of builtins.
14834 // Verify that this was correctly set up.
14835 FunctionDecl *F;
14836 if (ULE->decls_begin() != ULE->decls_end() &&
14837 ULE->decls_begin() + 1 == ULE->decls_end() &&
14838 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14839 F->getBuiltinID() && F->isImplicit())
14840 llvm_unreachable("performing ADL for builtin");
14841
14842 // We don't perform ADL in C.
14843 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14844 }
14845#endif
14846
14847 UnbridgedCastsSet UnbridgedCasts;
14848 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14849 *Result = ExprError();
14850 return true;
14851 }
14852
14853 // Add the functions denoted by the callee to the set of candidate
14854 // functions, including those from argument-dependent lookup.
14855 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
14856
14857 if (getLangOpts().MSVCCompat &&
14858 CurContext->isDependentContext() && !isSFINAEContext() &&
14860
14862 if (CandidateSet->empty() ||
14863 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
14865 // In Microsoft mode, if we are inside a template class member function
14866 // then create a type dependent CallExpr. The goal is to postpone name
14867 // lookup to instantiation time to be able to search into type dependent
14868 // base classes.
14869 CallExpr *CE =
14870 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
14871 RParenLoc, CurFPFeatureOverrides());
14873 *Result = CE;
14874 return true;
14875 }
14876 }
14877
14878 if (CandidateSet->empty())
14879 return false;
14880
14881 UnbridgedCasts.restore();
14882 return false;
14883}
14884
14885// Guess at what the return type for an unresolvable overload should be.
14888 std::optional<QualType> Result;
14889 // Adjust Type after seeing a candidate.
14890 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14891 if (!Candidate.Function)
14892 return;
14893 if (Candidate.Function->isInvalidDecl())
14894 return;
14895 QualType T = Candidate.Function->getReturnType();
14896 if (T.isNull())
14897 return;
14898 if (!Result)
14899 Result = T;
14900 else if (Result != T)
14901 Result = QualType();
14902 };
14903
14904 // Look for an unambiguous type from a progressively larger subset.
14905 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14906 //
14907 // First, consider only the best candidate.
14908 if (Best && *Best != CS.end())
14909 ConsiderCandidate(**Best);
14910 // Next, consider only viable candidates.
14911 if (!Result)
14912 for (const auto &C : CS)
14913 if (C.Viable)
14914 ConsiderCandidate(C);
14915 // Finally, consider all candidates.
14916 if (!Result)
14917 for (const auto &C : CS)
14918 ConsiderCandidate(C);
14919
14920 if (!Result)
14921 return QualType();
14922 auto Value = *Result;
14923 if (Value.isNull() || Value->isUndeducedType())
14924 return QualType();
14925 return Value;
14926}
14927
14928/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14929/// the completed call expression. If overload resolution fails, emits
14930/// diagnostics and returns ExprError()
14933 SourceLocation LParenLoc,
14934 MultiExprArg Args,
14935 SourceLocation RParenLoc,
14936 Expr *ExecConfig,
14937 OverloadCandidateSet *CandidateSet,
14939 OverloadingResult OverloadResult,
14940 bool AllowTypoCorrection) {
14941 switch (OverloadResult) {
14942 case OR_Success: {
14943 FunctionDecl *FDecl = (*Best)->Function;
14944 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14945 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14946 return ExprError();
14947 ExprResult Res =
14948 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14949 if (Res.isInvalid())
14950 return ExprError();
14951 return SemaRef.BuildResolvedCallExpr(
14952 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14953 /*IsExecConfig=*/false,
14954 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14955 }
14956
14957 case OR_No_Viable_Function: {
14958 if (*Best != CandidateSet->end() &&
14959 CandidateSet->getKind() ==
14961 if (CXXMethodDecl *M =
14962 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
14964 CandidateSet->NoteCandidates(
14966 Fn->getBeginLoc(),
14967 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
14968 SemaRef, OCD_AmbiguousCandidates, Args);
14969 return ExprError();
14970 }
14971 }
14972
14973 // Try to recover by looking for viable functions which the user might
14974 // have meant to call.
14975 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14976 Args, RParenLoc,
14977 CandidateSet->empty(),
14978 AllowTypoCorrection);
14979 if (Recovery.isInvalid() || Recovery.isUsable())
14980 return Recovery;
14981
14982 // If the user passes in a function that we can't take the address of, we
14983 // generally end up emitting really bad error messages. Here, we attempt to
14984 // emit better ones.
14985 for (const Expr *Arg : Args) {
14986 if (!Arg->getType()->isFunctionType())
14987 continue;
14988 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14989 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14990 if (FD &&
14991 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14992 Arg->getExprLoc()))
14993 return ExprError();
14994 }
14995 }
14996
14997 CandidateSet->NoteCandidates(
14999 Fn->getBeginLoc(),
15000 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
15001 << ULE->getName() << Fn->getSourceRange()),
15002 SemaRef, OCD_AllCandidates, Args);
15003 break;
15004 }
15005
15006 case OR_Ambiguous:
15007 CandidateSet->NoteCandidates(
15008 PartialDiagnosticAt(Fn->getBeginLoc(),
15009 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
15010 << ULE->getName() << Fn->getSourceRange()),
15011 SemaRef, OCD_AmbiguousCandidates, Args);
15012 break;
15013
15014 case OR_Deleted: {
15015 FunctionDecl *FDecl = (*Best)->Function;
15016 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
15017 Fn->getSourceRange(), ULE->getName(),
15018 *CandidateSet, FDecl, Args);
15019
15020 // We emitted an error for the unavailable/deleted function call but keep
15021 // the call in the AST.
15022 ExprResult Res =
15023 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
15024 if (Res.isInvalid())
15025 return ExprError();
15026 return SemaRef.BuildResolvedCallExpr(
15027 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
15028 /*IsExecConfig=*/false,
15029 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
15030 }
15031 }
15032
15033 // Overload resolution failed, try to recover.
15034 SmallVector<Expr *, 8> SubExprs = {Fn};
15035 SubExprs.append(Args.begin(), Args.end());
15036 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
15037 chooseRecoveryType(*CandidateSet, Best));
15038}
15039
15042 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
15043 if (I->Viable &&
15044 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
15045 I->Viable = false;
15046 I->FailureKind = ovl_fail_addr_not_available;
15047 }
15048 }
15049}
15050
15053 SourceLocation LParenLoc,
15054 MultiExprArg Args,
15055 SourceLocation RParenLoc,
15056 Expr *ExecConfig,
15057 bool AllowTypoCorrection,
15058 bool CalleesAddressIsTaken) {
15059
15063
15064 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
15065 ExprResult result;
15066
15067 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
15068 &result))
15069 return result;
15070
15071 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
15072 // functions that aren't addressible are considered unviable.
15073 if (CalleesAddressIsTaken)
15074 markUnaddressableCandidatesUnviable(*this, CandidateSet);
15075
15077 OverloadingResult OverloadResult =
15078 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
15079
15080 // [C++23][over.call.func]
15081 // if overload resolution selects a non-static member function,
15082 // the call is ill-formed;
15084 Best != CandidateSet.end()) {
15085 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
15086 M && M->isImplicitObjectMemberFunction()) {
15087 OverloadResult = OR_No_Viable_Function;
15088 }
15089 }
15090
15091 // Model the case with a call to a templated function whose definition
15092 // encloses the call and whose return type contains a placeholder type as if
15093 // the UnresolvedLookupExpr was type-dependent.
15094 if (OverloadResult == OR_Success) {
15095 const FunctionDecl *FDecl = Best->Function;
15096 if (LangOpts.CUDA)
15097 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
15098 if (FDecl && FDecl->isTemplateInstantiation() &&
15099 FDecl->getReturnType()->isUndeducedType()) {
15100
15101 // Creating dependent CallExpr is not okay if the enclosing context itself
15102 // is not dependent. This situation notably arises if a non-dependent
15103 // member function calls the later-defined overloaded static function.
15104 //
15105 // For example, in
15106 // class A {
15107 // void c() { callee(1); }
15108 // static auto callee(auto x) { }
15109 // };
15110 //
15111 // Here callee(1) is unresolved at the call site, but is not inside a
15112 // dependent context. There will be no further attempt to resolve this
15113 // call if it is made dependent.
15114
15115 if (const auto *TP =
15116 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
15117 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
15118 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
15119 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
15120 }
15121 }
15122 }
15123
15124 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
15125 ExecConfig, &CandidateSet, &Best,
15126 OverloadResult, AllowTypoCorrection);
15127}
15128
15132 const UnresolvedSetImpl &Fns,
15133 bool PerformADL) {
15135 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
15136 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
15137}
15138
15141 bool HadMultipleCandidates) {
15142 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
15143 // the FoundDecl as it impedes TransformMemberExpr.
15144 // We go a bit further here: if there's no difference in UnderlyingDecl,
15145 // then using FoundDecl vs Method shouldn't make a difference either.
15146 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
15147 FoundDecl = Method;
15148 // Convert the expression to match the conversion function's implicit object
15149 // parameter.
15150 ExprResult Exp;
15151 if (Method->isExplicitObjectMemberFunction())
15153 else
15155 E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
15156 if (Exp.isInvalid())
15157 return true;
15158
15159 if (Method->getParent()->isLambda() &&
15160 Method->getConversionType()->isBlockPointerType()) {
15161 // This is a lambda conversion to block pointer; check if the argument
15162 // was a LambdaExpr.
15163 Expr *SubE = E;
15164 auto *CE = dyn_cast<CastExpr>(SubE);
15165 if (CE && CE->getCastKind() == CK_NoOp)
15166 SubE = CE->getSubExpr();
15167 SubE = SubE->IgnoreParens();
15168 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
15169 SubE = BE->getSubExpr();
15170 if (isa<LambdaExpr>(SubE)) {
15171 // For the conversion to block pointer on a lambda expression, we
15172 // construct a special BlockLiteral instead; this doesn't really make
15173 // a difference in ARC, but outside of ARC the resulting block literal
15174 // follows the normal lifetime rules for block literals instead of being
15175 // autoreleased.
15179 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
15181
15182 // FIXME: This note should be produced by a CodeSynthesisContext.
15183 if (BlockExp.isInvalid())
15184 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
15185 return BlockExp;
15186 }
15187 }
15188 CallExpr *CE;
15189 QualType ResultType = Method->getReturnType();
15191 ResultType = ResultType.getNonLValueExprType(Context);
15192 if (Method->isExplicitObjectMemberFunction()) {
15193 ExprResult FnExpr =
15194 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
15195 HadMultipleCandidates, E->getBeginLoc());
15196 if (FnExpr.isInvalid())
15197 return ExprError();
15198 Expr *ObjectParam = Exp.get();
15199 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
15200 ResultType, VK, Exp.get()->getEndLoc(),
15202 CE->setUsesMemberSyntax(true);
15203 } else {
15204 MemberExpr *ME =
15205 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
15207 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
15208 HadMultipleCandidates, DeclarationNameInfo(),
15209 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
15210
15211 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
15212 Exp.get()->getEndLoc(),
15214 }
15215
15216 if (CheckFunctionCall(Method, CE,
15217 Method->getType()->castAs<FunctionProtoType>()))
15218 return ExprError();
15219
15221}
15222
15225 const UnresolvedSetImpl &Fns,
15226 Expr *Input, bool PerformADL) {
15228 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
15229 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15230 // TODO: provide better source location info.
15231 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15232
15233 if (checkPlaceholderForOverload(*this, Input))
15234 return ExprError();
15235
15236 Expr *Args[2] = { Input, nullptr };
15237 unsigned NumArgs = 1;
15238
15239 // For post-increment and post-decrement, add the implicit '0' as
15240 // the second argument, so that we know this is a post-increment or
15241 // post-decrement.
15242 if (Opc == UO_PostInc || Opc == UO_PostDec) {
15243 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15244 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
15245 SourceLocation());
15246 NumArgs = 2;
15247 }
15248
15249 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
15250
15251 if (Input->isTypeDependent()) {
15253 // [C++26][expr.unary.op][expr.pre.incr]
15254 // The * operator yields an lvalue of type
15255 // The pre/post increment operators yied an lvalue.
15256 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
15257 VK = VK_LValue;
15258
15259 if (Fns.empty())
15260 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
15261 OK_Ordinary, OpLoc, false,
15263
15264 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15266 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
15267 if (Fn.isInvalid())
15268 return ExprError();
15269 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
15270 Context.DependentTy, VK_PRValue, OpLoc,
15272 }
15273
15274 // Build an empty overload set.
15276
15277 // Add the candidates from the given function set.
15278 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
15279
15280 // Add operator candidates that are member functions.
15281 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15282
15283 // Add candidates from ADL.
15284 if (PerformADL) {
15285 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
15286 /*ExplicitTemplateArgs*/nullptr,
15287 CandidateSet);
15288 }
15289
15290 // Add builtin operator candidates.
15291 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15292
15293 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15294
15295 // Perform overload resolution.
15297 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15298 case OR_Success: {
15299 // We found a built-in operator or an overloaded operator.
15300 FunctionDecl *FnDecl = Best->Function;
15301
15302 if (FnDecl) {
15303 Expr *Base = nullptr;
15304 // We matched an overloaded operator. Build a call to that
15305 // operator.
15306
15307 // Convert the arguments.
15308 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15309 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
15310
15311 ExprResult InputInit;
15312 if (Method->isExplicitObjectMemberFunction())
15313 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
15314 else
15316 Input, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15317 if (InputInit.isInvalid())
15318 return ExprError();
15319 Base = Input = InputInit.get();
15320 } else {
15321 // Convert the arguments.
15322 ExprResult InputInit
15324 Context,
15325 FnDecl->getParamDecl(0)),
15327 Input);
15328 if (InputInit.isInvalid())
15329 return ExprError();
15330 Input = InputInit.get();
15331 }
15332
15333 // Build the actual expression node.
15334 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
15335 Base, HadMultipleCandidates,
15336 OpLoc);
15337 if (FnExpr.isInvalid())
15338 return ExprError();
15339
15340 // Determine the result type.
15341 QualType ResultTy = FnDecl->getReturnType();
15343 ResultTy = ResultTy.getNonLValueExprType(Context);
15344
15345 Args[0] = Input;
15347 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
15349 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15350
15351 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
15352 return ExprError();
15353
15354 if (CheckFunctionCall(FnDecl, TheCall,
15355 FnDecl->getType()->castAs<FunctionProtoType>()))
15356 return ExprError();
15357 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
15358 } else {
15359 // We matched a built-in operator. Convert the arguments, then
15360 // break out so that we will build the appropriate built-in
15361 // operator node.
15363 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
15366 if (InputRes.isInvalid())
15367 return ExprError();
15368 Input = InputRes.get();
15369 break;
15370 }
15371 }
15372
15374 // This is an erroneous use of an operator which can be overloaded by
15375 // a non-member function. Check for non-member operators which were
15376 // defined too late to be candidates.
15377 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
15378 // FIXME: Recover by calling the found function.
15379 return ExprError();
15380
15381 // No viable function; fall through to handling this as a
15382 // built-in operator, which will produce an error message for us.
15383 break;
15384
15385 case OR_Ambiguous:
15386 CandidateSet.NoteCandidates(
15387 PartialDiagnosticAt(OpLoc,
15388 PDiag(diag::err_ovl_ambiguous_oper_unary)
15390 << Input->getType() << Input->getSourceRange()),
15391 *this, OCD_AmbiguousCandidates, ArgsArray,
15392 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15393 return ExprError();
15394
15395 case OR_Deleted: {
15396 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15397 // object whose method was called. Later in NoteCandidates size of ArgsArray
15398 // is passed further and it eventually ends up compared to number of
15399 // function candidate parameters which never includes the object parameter,
15400 // so slice ArgsArray to make sure apples are compared to apples.
15401 StringLiteral *Msg = Best->Function->getDeletedMessage();
15402 CandidateSet.NoteCandidates(
15403 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15405 << (Msg != nullptr)
15406 << (Msg ? Msg->getString() : StringRef())
15407 << Input->getSourceRange()),
15408 *this, OCD_AllCandidates, ArgsArray.drop_front(),
15409 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15410 return ExprError();
15411 }
15412 }
15413
15414 // Either we found no viable overloaded operator or we matched a
15415 // built-in operator. In either case, fall through to trying to
15416 // build a built-in operation.
15417 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15418}
15419
15422 const UnresolvedSetImpl &Fns,
15423 ArrayRef<Expr *> Args, bool PerformADL) {
15424 SourceLocation OpLoc = CandidateSet.getLocation();
15425
15426 OverloadedOperatorKind ExtraOp =
15429 : OO_None;
15430
15431 // Add the candidates from the given function set. This also adds the
15432 // rewritten candidates using these functions if necessary.
15433 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15434
15435 // As template candidates are not deduced immediately,
15436 // persist the array in the overload set.
15437 ArrayRef<Expr *> ReversedArgs;
15438 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15439 CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15440 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
15441
15442 // Add operator candidates that are member functions.
15443 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15444 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15445 AddMemberOperatorCandidates(Op, OpLoc, ReversedArgs, CandidateSet,
15447
15448 // In C++20, also add any rewritten member candidates.
15449 if (ExtraOp) {
15450 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
15451 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15452 AddMemberOperatorCandidates(ExtraOp, OpLoc, ReversedArgs, CandidateSet,
15454 }
15455
15456 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15457 // performed for an assignment operator (nor for operator[] nor operator->,
15458 // which don't get here).
15459 if (Op != OO_Equal && PerformADL) {
15460 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15461 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15462 /*ExplicitTemplateArgs*/ nullptr,
15463 CandidateSet);
15464 if (ExtraOp) {
15465 DeclarationName ExtraOpName =
15466 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
15467 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
15468 /*ExplicitTemplateArgs*/ nullptr,
15469 CandidateSet);
15470 }
15471 }
15472
15473 // Add builtin operator candidates.
15474 //
15475 // FIXME: We don't add any rewritten candidates here. This is strictly
15476 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15477 // resulting in our selecting a rewritten builtin candidate. For example:
15478 //
15479 // enum class E { e };
15480 // bool operator!=(E, E) requires false;
15481 // bool k = E::e != E::e;
15482 //
15483 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15484 // it seems unreasonable to consider rewritten builtin candidates. A core
15485 // issue has been filed proposing to removed this requirement.
15486 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15487}
15488
15491 const UnresolvedSetImpl &Fns, Expr *LHS,
15492 Expr *RHS, bool PerformADL,
15493 bool AllowRewrittenCandidates,
15494 FunctionDecl *DefaultedFn) {
15495 Expr *Args[2] = { LHS, RHS };
15496 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15497
15498 if (!getLangOpts().CPlusPlus20)
15499 AllowRewrittenCandidates = false;
15500
15502
15503 // If either side is type-dependent, create an appropriate dependent
15504 // expression.
15505 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15506 if (Fns.empty()) {
15507 // If there are no functions to store, just build a dependent
15508 // BinaryOperator or CompoundAssignment.
15511 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
15512 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
15513 Context.DependentTy);
15515 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
15517 }
15518
15519 // FIXME: save results of ADL from here?
15520 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15521 // TODO: provide better source location info in DNLoc component.
15522 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15523 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15525 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
15526 if (Fn.isInvalid())
15527 return ExprError();
15528 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
15529 Context.DependentTy, VK_PRValue, OpLoc,
15531 }
15532
15533 // If this is the .* operator, which is not overloadable, just
15534 // create a built-in binary operator.
15535 if (Opc == BO_PtrMemD) {
15536 auto CheckPlaceholder = [&](Expr *&Arg) {
15538 if (Res.isUsable())
15539 Arg = Res.get();
15540 return !Res.isUsable();
15541 };
15542
15543 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15544 // expression that contains placeholders (in either the LHS or RHS).
15545 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15546 return ExprError();
15547 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15548 }
15549
15550 // Always do placeholder-like conversions on the RHS.
15551 if (checkPlaceholderForOverload(*this, Args[1]))
15552 return ExprError();
15553
15554 // Do placeholder-like conversion on the LHS; note that we should
15555 // not get here with a PseudoObject LHS.
15556 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15557 if (checkPlaceholderForOverload(*this, Args[0]))
15558 return ExprError();
15559
15560 // If this is the assignment operator, we only perform overload resolution
15561 // if the left-hand side is a class or enumeration type. This is actually
15562 // a hack. The standard requires that we do overload resolution between the
15563 // various built-in candidates, but as DR507 points out, this can lead to
15564 // problems. So we do it this way, which pretty much follows what GCC does.
15565 // Note that we go the traditional code path for compound assignment forms.
15566 // In HLSL, user-defined structs/classes do not have constructors or
15567 // overloadable assignment operators, so we can take this shortcut too.
15568 const Type *LHSTy = Args[0]->getType().getTypePtr();
15569 if (Opc == BO_Assign &&
15570 (!LHSTy->isOverloadableType() ||
15571 (getLangOpts().HLSL && LHSTy->isRecordType() &&
15573 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15574
15575 // Build the overload set.
15578 Op, OpLoc, AllowRewrittenCandidates));
15579 if (DefaultedFn)
15580 CandidateSet.exclude(DefaultedFn);
15581 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15582
15583 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15584
15585 // Perform overload resolution.
15587 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15588 case OR_Success: {
15589 // We found a built-in operator or an overloaded operator.
15590 FunctionDecl *FnDecl = Best->Function;
15591
15592 bool IsReversed = Best->isReversed();
15593 if (IsReversed)
15594 std::swap(Args[0], Args[1]);
15595
15596 if (FnDecl) {
15597
15598 if (FnDecl->isInvalidDecl())
15599 return ExprError();
15600
15601 Expr *Base = nullptr;
15602 // We matched an overloaded operator. Build a call to that
15603 // operator.
15604
15605 OverloadedOperatorKind ChosenOp =
15607
15608 // C++2a [over.match.oper]p9:
15609 // If a rewritten operator== candidate is selected by overload
15610 // resolution for an operator@, its return type shall be cv bool
15611 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15612 !FnDecl->getReturnType()->isBooleanType()) {
15613 bool IsExtension =
15615 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15616 : diag::err_ovl_rewrite_equalequal_not_bool)
15617 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
15618 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15619 Diag(FnDecl->getLocation(), diag::note_declared_at);
15620 if (!IsExtension)
15621 return ExprError();
15622 }
15623
15624 if (AllowRewrittenCandidates && !IsReversed &&
15625 CandidateSet.getRewriteInfo().isReversible()) {
15626 // We could have reversed this operator, but didn't. Check if some
15627 // reversed form was a viable candidate, and if so, if it had a
15628 // better conversion for either parameter. If so, this call is
15629 // formally ambiguous, and allowing it is an extension.
15631 for (OverloadCandidate &Cand : CandidateSet) {
15632 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15633 allowAmbiguity(Context, Cand.Function, FnDecl)) {
15634 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15636 *this, OpLoc, Cand.Conversions[ArgIdx],
15637 Best->Conversions[ArgIdx]) ==
15639 AmbiguousWith.push_back(Cand.Function);
15640 break;
15641 }
15642 }
15643 }
15644 }
15645
15646 if (!AmbiguousWith.empty()) {
15647 bool AmbiguousWithSelf =
15648 AmbiguousWith.size() == 1 &&
15649 declaresSameEntity(AmbiguousWith.front(), FnDecl);
15650 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
15652 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15653 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15654 if (AmbiguousWithSelf) {
15655 Diag(FnDecl->getLocation(),
15656 diag::note_ovl_ambiguous_oper_binary_reversed_self);
15657 // Mark member== const or provide matching != to disallow reversed
15658 // args. Eg.
15659 // struct S { bool operator==(const S&); };
15660 // S()==S();
15661 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
15662 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15663 !MD->isConst() &&
15664 !MD->hasCXXExplicitFunctionObjectParameter() &&
15665 Context.hasSameUnqualifiedType(
15666 MD->getFunctionObjectParameterType(),
15667 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
15668 Context.hasSameUnqualifiedType(
15669 MD->getFunctionObjectParameterType(),
15670 Args[0]->getType()) &&
15671 Context.hasSameUnqualifiedType(
15672 MD->getFunctionObjectParameterType(),
15673 Args[1]->getType()))
15674 Diag(FnDecl->getLocation(),
15675 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15676 } else {
15677 Diag(FnDecl->getLocation(),
15678 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15679 for (auto *F : AmbiguousWith)
15680 Diag(F->getLocation(),
15681 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15682 }
15683 }
15684 }
15685
15686 // Check for nonnull = nullable.
15687 // This won't be caught in the arg's initialization: the parameter to
15688 // the assignment operator is not marked nonnull.
15689 if (Op == OO_Equal)
15691 Args[1]->getType(), OpLoc);
15692
15693 // Convert the arguments.
15694 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15695 // Best->Access is only meaningful for class members.
15696 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
15697
15698 ExprResult Arg0, Arg1;
15699 unsigned ParamIdx = 0;
15700 if (Method->isExplicitObjectMemberFunction()) {
15701 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
15702 ParamIdx = 1;
15703 } else {
15705 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15706 }
15709 Context, FnDecl->getParamDecl(ParamIdx)),
15710 SourceLocation(), Args[1]);
15711 if (Arg0.isInvalid() || Arg1.isInvalid())
15712 return ExprError();
15713
15714 Base = Args[0] = Arg0.getAs<Expr>();
15715 Args[1] = RHS = Arg1.getAs<Expr>();
15716 } else {
15717 // Convert the arguments.
15720 FnDecl->getParamDecl(0)),
15721 SourceLocation(), Args[0]);
15722 if (Arg0.isInvalid())
15723 return ExprError();
15724
15725 ExprResult Arg1 =
15728 FnDecl->getParamDecl(1)),
15729 SourceLocation(), Args[1]);
15730 if (Arg1.isInvalid())
15731 return ExprError();
15732 Args[0] = LHS = Arg0.getAs<Expr>();
15733 Args[1] = RHS = Arg1.getAs<Expr>();
15734 }
15735
15736 // Build the actual expression node.
15737 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
15738 Best->FoundDecl, Base,
15739 HadMultipleCandidates, OpLoc);
15740 if (FnExpr.isInvalid())
15741 return ExprError();
15742
15743 // Determine the result type.
15744 QualType ResultTy = FnDecl->getReturnType();
15746 ResultTy = ResultTy.getNonLValueExprType(Context);
15747
15748 CallExpr *TheCall;
15749 ArrayRef<const Expr *> ArgsArray(Args, 2);
15750 const Expr *ImplicitThis = nullptr;
15751
15752 // We always create a CXXOperatorCallExpr, even for explicit object
15753 // members; CodeGen should take care not to emit the this pointer.
15755 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
15757 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate),
15758 IsReversed);
15759
15760 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
15761 Method && Method->isImplicitObjectMemberFunction()) {
15762 // Cut off the implicit 'this'.
15763 ImplicitThis = ArgsArray[0];
15764 ArgsArray = ArgsArray.slice(1);
15765 }
15766
15767 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
15768 FnDecl))
15769 return ExprError();
15770
15771 if (Op == OO_Equal) {
15772 // Check for a self move.
15773 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
15774 // lifetime check.
15776 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
15777 Args[1]);
15778 }
15779 if (ImplicitThis) {
15780 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
15781 QualType ThisTypeFromDecl = Context.getPointerType(
15782 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
15783
15784 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
15785 ThisTypeFromDecl);
15786 }
15787
15788 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
15789 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
15791
15792 ExprResult R = MaybeBindToTemporary(TheCall);
15793 if (R.isInvalid())
15794 return ExprError();
15795
15796 R = CheckForImmediateInvocation(R, FnDecl);
15797 if (R.isInvalid())
15798 return ExprError();
15799
15800 // For a rewritten candidate, we've already reversed the arguments
15801 // if needed. Perform the rest of the rewrite now.
15802 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15803 (Op == OO_Spaceship && IsReversed)) {
15804 if (Op == OO_ExclaimEqual) {
15805 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15806 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
15807 } else {
15808 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15809 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15810 Expr *ZeroLiteral =
15812
15815 Ctx.Entity = FnDecl;
15817
15819 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
15820 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15821 /*AllowRewrittenCandidates=*/false);
15822
15824 }
15825 if (R.isInvalid())
15826 return ExprError();
15827 } else {
15828 assert(ChosenOp == Op && "unexpected operator name");
15829 }
15830
15831 // Make a note in the AST if we did any rewriting.
15832 if (Best->RewriteKind != CRK_None)
15833 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15834
15835 return R;
15836 } else {
15837 // We matched a built-in operator. Convert the arguments, then
15838 // break out so that we will build the appropriate built-in
15839 // operator node.
15841 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15844 if (ArgsRes0.isInvalid())
15845 return ExprError();
15846 Args[0] = ArgsRes0.get();
15847
15849 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15852 if (ArgsRes1.isInvalid())
15853 return ExprError();
15854 Args[1] = ArgsRes1.get();
15855 break;
15856 }
15857 }
15858
15859 case OR_No_Viable_Function: {
15860 // C++ [over.match.oper]p9:
15861 // If the operator is the operator , [...] and there are no
15862 // viable functions, then the operator is assumed to be the
15863 // built-in operator and interpreted according to clause 5.
15864 if (Opc == BO_Comma)
15865 break;
15866
15867 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15868 // compare result using '==' and '<'.
15869 if (DefaultedFn && Opc == BO_Cmp) {
15870 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
15871 Args[1], DefaultedFn);
15872 if (E.isInvalid() || E.isUsable())
15873 return E;
15874 }
15875
15876 // For class as left operand for assignment or compound assignment
15877 // operator do not fall through to handling in built-in, but report that
15878 // no overloaded assignment operator found
15880 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
15881 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
15882 Args, OpLoc);
15883 DeferDiagsRAII DDR(*this,
15884 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
15885 if (Args[0]->getType()->isRecordType() &&
15886 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15887 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15889 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15890 if (Args[0]->getType()->isIncompleteType()) {
15891 Diag(OpLoc, diag::note_assign_lhs_incomplete)
15892 << Args[0]->getType()
15893 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15894 }
15895 } else {
15896 // This is an erroneous use of an operator which can be overloaded by
15897 // a non-member function. Check for non-member operators which were
15898 // defined too late to be candidates.
15899 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
15900 // FIXME: Recover by calling the found function.
15901 return ExprError();
15902
15903 // No viable function; try to create a built-in operation, which will
15904 // produce an error. Then, show the non-viable candidates.
15905 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15906 }
15907 assert(Result.isInvalid() &&
15908 "C++ binary operator overloading is missing candidates!");
15909 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
15910 return Result;
15911 }
15912
15913 case OR_Ambiguous:
15914 CandidateSet.NoteCandidates(
15915 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15917 << Args[0]->getType()
15918 << Args[1]->getType()
15919 << Args[0]->getSourceRange()
15920 << Args[1]->getSourceRange()),
15922 OpLoc);
15923 return ExprError();
15924
15925 case OR_Deleted: {
15926 if (isImplicitlyDeleted(Best->Function)) {
15927 FunctionDecl *DeletedFD = Best->Function;
15929 if (DFK.isSpecialMember()) {
15930 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15931 << Args[0]->getType() << DFK.asSpecialMember();
15932 } else {
15933 assert(DFK.isComparison());
15934 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15935 << Args[0]->getType() << DeletedFD;
15936 }
15937
15938 // The user probably meant to call this special member. Just
15939 // explain why it's deleted.
15940 NoteDeletedFunction(DeletedFD);
15941 return ExprError();
15942 }
15943
15944 StringLiteral *Msg = Best->Function->getDeletedMessage();
15945 CandidateSet.NoteCandidates(
15947 OpLoc,
15948 PDiag(diag::err_ovl_deleted_oper)
15949 << getOperatorSpelling(Best->Function->getDeclName()
15950 .getCXXOverloadedOperator())
15951 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15952 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15954 OpLoc);
15955 return ExprError();
15956 }
15957 }
15958
15959 // We matched a built-in operator; build it.
15960 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15961}
15962
15964 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15965 FunctionDecl *DefaultedFn) {
15966 const ComparisonCategoryInfo *Info =
15967 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15968 // If we're not producing a known comparison category type, we can't
15969 // synthesize a three-way comparison. Let the caller diagnose this.
15970 if (!Info)
15971 return ExprResult((Expr*)nullptr);
15972
15973 // If we ever want to perform this synthesis more generally, we will need to
15974 // apply the temporary materialization conversion to the operands.
15975 assert(LHS->isGLValue() && RHS->isGLValue() &&
15976 "cannot use prvalue expressions more than once");
15977 Expr *OrigLHS = LHS;
15978 Expr *OrigRHS = RHS;
15979
15980 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15981 // each of them multiple times below.
15982 LHS = new (Context)
15983 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15984 LHS->getObjectKind(), LHS);
15985 RHS = new (Context)
15986 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15987 RHS->getObjectKind(), RHS);
15988
15989 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15990 DefaultedFn);
15991 if (Eq.isInvalid())
15992 return ExprError();
15993
15994 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15995 true, DefaultedFn);
15996 if (Less.isInvalid())
15997 return ExprError();
15998
16000 if (Info->isPartial()) {
16001 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
16002 DefaultedFn);
16003 if (Greater.isInvalid())
16004 return ExprError();
16005 }
16006
16007 // Form the list of comparisons we're going to perform.
16008 struct Comparison {
16011 } Comparisons[4] =
16017 };
16018
16019 int I = Info->isPartial() ? 3 : 2;
16020
16021 // Combine the comparisons with suitable conditional expressions.
16023 for (; I >= 0; --I) {
16024 // Build a reference to the comparison category constant.
16025 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
16026 // FIXME: Missing a constant for a comparison category. Diagnose this?
16027 if (!VI)
16028 return ExprResult((Expr*)nullptr);
16029 ExprResult ThisResult =
16031 if (ThisResult.isInvalid())
16032 return ExprError();
16033
16034 // Build a conditional unless this is the final case.
16035 if (Result.get()) {
16036 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
16037 ThisResult.get(), Result.get());
16038 if (Result.isInvalid())
16039 return ExprError();
16040 } else {
16041 Result = ThisResult;
16042 }
16043 }
16044
16045 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
16046 // bind the OpaqueValueExprs before they're (repeatedly) used.
16047 Expr *SyntacticForm = BinaryOperator::Create(
16048 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
16049 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
16051 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
16052 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
16053}
16054
16056 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
16057 MultiExprArg Args, SourceLocation LParenLoc) {
16058
16059 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16060 unsigned NumParams = Proto->getNumParams();
16061 unsigned NumArgsSlots =
16062 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
16063 // Build the full argument list for the method call (the implicit object
16064 // parameter is placed at the beginning of the list).
16065 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
16066 bool IsError = false;
16067 // Initialize the implicit object parameter.
16068 // Check the argument types.
16069 for (unsigned i = 0; i != NumParams; i++) {
16070 Expr *Arg;
16071 if (i < Args.size()) {
16072 Arg = Args[i];
16073 ExprResult InputInit =
16075 S.Context, Method->getParamDecl(i)),
16076 SourceLocation(), Arg);
16077 IsError |= InputInit.isInvalid();
16078 Arg = InputInit.getAs<Expr>();
16079 } else {
16080 ExprResult DefArg =
16081 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
16082 if (DefArg.isInvalid()) {
16083 IsError = true;
16084 break;
16085 }
16086 Arg = DefArg.getAs<Expr>();
16087 }
16088
16089 MethodArgs.push_back(Arg);
16090 }
16091 return IsError;
16092}
16093
16095 SourceLocation RLoc,
16096 Expr *Base,
16097 MultiExprArg ArgExpr) {
16099 Args.push_back(Base);
16100 for (auto *e : ArgExpr) {
16101 Args.push_back(e);
16102 }
16103 DeclarationName OpName =
16104 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
16105
16106 SourceRange Range = ArgExpr.empty()
16107 ? SourceRange{}
16108 : SourceRange(ArgExpr.front()->getBeginLoc(),
16109 ArgExpr.back()->getEndLoc());
16110
16111 // If either side is type-dependent, create an appropriate dependent
16112 // expression.
16114
16115 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
16116 // CHECKME: no 'operator' keyword?
16117 DeclarationNameInfo OpNameInfo(OpName, LLoc);
16118 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16120 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
16121 if (Fn.isInvalid())
16122 return ExprError();
16123 // Can't add any actual overloads yet
16124
16125 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
16126 Context.DependentTy, VK_PRValue, RLoc,
16128 }
16129
16130 // Handle placeholders
16131 UnbridgedCastsSet UnbridgedCasts;
16132 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
16133 return ExprError();
16134 }
16135 // Build an empty overload set.
16137
16138 // Subscript can only be overloaded as a member function.
16139
16140 // Add operator candidates that are member functions.
16141 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
16142
16143 // Add builtin operator candidates.
16144 if (Args.size() == 2)
16145 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
16146
16147 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16148
16149 // Perform overload resolution.
16151 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
16152 case OR_Success: {
16153 // We found a built-in operator or an overloaded operator.
16154 FunctionDecl *FnDecl = Best->Function;
16155
16156 if (FnDecl) {
16157 // We matched an overloaded operator. Build a call to that
16158 // operator.
16159
16160 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
16161
16162 // Convert the arguments.
16164 SmallVector<Expr *, 2> MethodArgs;
16165
16166 // Initialize the object parameter.
16167 if (Method->isExplicitObjectMemberFunction()) {
16168 ExprResult Res =
16170 if (Res.isInvalid())
16171 return ExprError();
16172 Args[0] = Res.get();
16173 ArgExpr = Args;
16174 } else {
16176 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16177 if (Arg0.isInvalid())
16178 return ExprError();
16179
16180 MethodArgs.push_back(Arg0.get());
16181 }
16182
16184 *this, MethodArgs, Method, ArgExpr, LLoc);
16185 if (IsError)
16186 return ExprError();
16187
16188 // Build the actual expression node.
16189 DeclarationNameInfo OpLocInfo(OpName, LLoc);
16190 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
16192 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
16193 OpLocInfo.getLoc(), OpLocInfo.getInfo());
16194 if (FnExpr.isInvalid())
16195 return ExprError();
16196
16197 // Determine the result type
16198 QualType ResultTy = FnDecl->getReturnType();
16200 ResultTy = ResultTy.getNonLValueExprType(Context);
16201
16203 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
16205
16206 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
16207 return ExprError();
16208
16209 if (CheckFunctionCall(Method, TheCall,
16210 Method->getType()->castAs<FunctionProtoType>()))
16211 return ExprError();
16212
16214 FnDecl);
16215 } else {
16216 // We matched a built-in operator. Convert the arguments, then
16217 // break out so that we will build the appropriate built-in
16218 // operator node.
16220 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
16223 if (ArgsRes0.isInvalid())
16224 return ExprError();
16225 Args[0] = ArgsRes0.get();
16226
16228 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
16231 if (ArgsRes1.isInvalid())
16232 return ExprError();
16233 Args[1] = ArgsRes1.get();
16234
16235 break;
16236 }
16237 }
16238
16239 case OR_No_Viable_Function: {
16241 CandidateSet.empty()
16242 ? (PDiag(diag::err_ovl_no_oper)
16243 << Args[0]->getType() << /*subscript*/ 0
16244 << Args[0]->getSourceRange() << Range)
16245 : (PDiag(diag::err_ovl_no_viable_subscript)
16246 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
16247 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
16248 OCD_AllCandidates, ArgExpr, "[]", LLoc);
16249 return ExprError();
16250 }
16251
16252 case OR_Ambiguous:
16253 if (Args.size() == 2) {
16254 CandidateSet.NoteCandidates(
16256 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
16257 << "[]" << Args[0]->getType() << Args[1]->getType()
16258 << Args[0]->getSourceRange() << Range),
16259 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16260 } else {
16261 CandidateSet.NoteCandidates(
16263 PDiag(diag::err_ovl_ambiguous_subscript_call)
16264 << Args[0]->getType()
16265 << Args[0]->getSourceRange() << Range),
16266 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
16267 }
16268 return ExprError();
16269
16270 case OR_Deleted: {
16271 StringLiteral *Msg = Best->Function->getDeletedMessage();
16272 CandidateSet.NoteCandidates(
16274 PDiag(diag::err_ovl_deleted_oper)
16275 << "[]" << (Msg != nullptr)
16276 << (Msg ? Msg->getString() : StringRef())
16277 << Args[0]->getSourceRange() << Range),
16278 *this, OCD_AllCandidates, Args, "[]", LLoc);
16279 return ExprError();
16280 }
16281 }
16282
16283 // We matched a built-in operator; build it.
16284 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
16285}
16286
16288 SourceLocation LParenLoc,
16289 MultiExprArg Args,
16290 SourceLocation RParenLoc,
16291 Expr *ExecConfig, bool IsExecConfig,
16292 bool AllowRecovery) {
16293 assert(MemExprE->getType() == Context.BoundMemberTy ||
16294 MemExprE->getType() == Context.OverloadTy);
16295
16296 // Dig out the member expression. This holds both the object
16297 // argument and the member function we're referring to.
16298 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16299
16300 // Determine whether this is a call to a pointer-to-member function.
16301 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
16302 assert(op->getType() == Context.BoundMemberTy);
16303 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16304
16305 QualType fnType =
16306 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16307
16308 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16309 QualType resultType = proto->getCallResultType(Context);
16311
16312 // Check that the object type isn't more qualified than the
16313 // member function we're calling.
16314 Qualifiers funcQuals = proto->getMethodQuals();
16315
16316 QualType objectType = op->getLHS()->getType();
16317 if (op->getOpcode() == BO_PtrMemI)
16318 objectType = objectType->castAs<PointerType>()->getPointeeType();
16319 Qualifiers objectQuals = objectType.getQualifiers();
16320
16321 Qualifiers difference = objectQuals - funcQuals;
16322 difference.removeObjCGCAttr();
16323 difference.removeAddressSpace();
16324 if (difference) {
16325 std::string qualsString = difference.getAsString();
16326 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
16327 << fnType.getUnqualifiedType()
16328 << qualsString
16329 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
16330 }
16331
16333 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
16335
16336 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
16337 call, nullptr))
16338 return ExprError();
16339
16340 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
16341 return ExprError();
16342
16343 if (CheckOtherCall(call, proto))
16344 return ExprError();
16345
16346 return MaybeBindToTemporary(call);
16347 }
16348
16349 // We only try to build a recovery expr at this level if we can preserve
16350 // the return type, otherwise we return ExprError() and let the caller
16351 // recover.
16352 auto BuildRecoveryExpr = [&](QualType Type) {
16353 if (!AllowRecovery)
16354 return ExprError();
16355 std::vector<Expr *> SubExprs = {MemExprE};
16356 llvm::append_range(SubExprs, Args);
16357 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
16358 Type);
16359 };
16360 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
16361 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
16362 RParenLoc, CurFPFeatureOverrides());
16363
16364 UnbridgedCastsSet UnbridgedCasts;
16365 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16366 return ExprError();
16367
16368 MemberExpr *MemExpr;
16369 CXXMethodDecl *Method = nullptr;
16370 bool HadMultipleCandidates = false;
16371 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
16372 NestedNameSpecifier Qualifier = std::nullopt;
16373 if (isa<MemberExpr>(NakedMemExpr)) {
16374 MemExpr = cast<MemberExpr>(NakedMemExpr);
16376 FoundDecl = MemExpr->getFoundDecl();
16377 Qualifier = MemExpr->getQualifier();
16378 UnbridgedCasts.restore();
16379 } else {
16380 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
16381 Qualifier = UnresExpr->getQualifier();
16382
16383 QualType ObjectType = UnresExpr->getBaseType();
16384 Expr::Classification ObjectClassification
16386 : UnresExpr->getBase()->Classify(Context);
16387
16388 // Add overload candidates
16389 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16391
16392 // FIXME: avoid copy.
16393 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16394 if (UnresExpr->hasExplicitTemplateArgs()) {
16395 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16396 TemplateArgs = &TemplateArgsBuffer;
16397 }
16398
16400 E = UnresExpr->decls_end(); I != E; ++I) {
16401
16402 QualType ExplicitObjectType = ObjectType;
16403
16404 NamedDecl *Func = *I;
16405 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
16407 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
16408
16409 bool HasExplicitParameter = false;
16410 if (const auto *M = dyn_cast<FunctionDecl>(Func);
16411 M && M->hasCXXExplicitFunctionObjectParameter())
16412 HasExplicitParameter = true;
16413 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
16414 M &&
16415 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16416 HasExplicitParameter = true;
16417
16418 if (HasExplicitParameter)
16419 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
16420
16421 // Microsoft supports direct constructor calls.
16422 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
16424 CandidateSet,
16425 /*SuppressUserConversions*/ false);
16426 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
16427 // If explicit template arguments were provided, we can't call a
16428 // non-template member function.
16429 if (TemplateArgs)
16430 continue;
16431
16432 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
16433 ObjectClassification, Args, CandidateSet,
16434 /*SuppressUserConversions=*/false);
16435 } else {
16437 I.getPair(), ActingDC, TemplateArgs,
16438 ExplicitObjectType, ObjectClassification,
16439 Args, CandidateSet,
16440 /*SuppressUserConversions=*/false);
16441 }
16442 }
16443
16444 HadMultipleCandidates = (CandidateSet.size() > 1);
16445
16446 DeclarationName DeclName = UnresExpr->getMemberName();
16447
16448 UnbridgedCasts.restore();
16449
16451 bool Succeeded = false;
16452 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
16453 Best)) {
16454 case OR_Success:
16455 Method = cast<CXXMethodDecl>(Best->Function);
16456 FoundDecl = Best->FoundDecl;
16457 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
16458 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
16459 break;
16460 // If FoundDecl is different from Method (such as if one is a template
16461 // and the other a specialization), make sure DiagnoseUseOfDecl is
16462 // called on both.
16463 // FIXME: This would be more comprehensively addressed by modifying
16464 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16465 // being used.
16466 if (Method != FoundDecl.getDecl() &&
16468 break;
16469 Succeeded = true;
16470 break;
16471
16473 CandidateSet.NoteCandidates(
16475 UnresExpr->getMemberLoc(),
16476 PDiag(diag::err_ovl_no_viable_member_function_in_call)
16477 << DeclName << MemExprE->getSourceRange()),
16478 *this, OCD_AllCandidates, Args);
16479 break;
16480 case OR_Ambiguous:
16481 CandidateSet.NoteCandidates(
16482 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16483 PDiag(diag::err_ovl_ambiguous_member_call)
16484 << DeclName << MemExprE->getSourceRange()),
16485 *this, OCD_AmbiguousCandidates, Args);
16486 break;
16487 case OR_Deleted:
16489 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
16490 CandidateSet, Best->Function, Args, /*IsMember=*/true);
16491 break;
16492 }
16493 // Overload resolution fails, try to recover.
16494 if (!Succeeded)
16495 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
16496
16497 ExprResult Res =
16498 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
16499 if (Res.isInvalid())
16500 return ExprError();
16501 MemExprE = Res.get();
16502
16503 // If overload resolution picked a static member
16504 // build a non-member call based on that function.
16505 if (Method->isStatic()) {
16506 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
16507 ExecConfig, IsExecConfig);
16508 }
16509
16510 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
16511 }
16512
16513 QualType ResultType = Method->getReturnType();
16515 ResultType = ResultType.getNonLValueExprType(Context);
16516
16517 assert(Method && "Member call to something that isn't a method?");
16518 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16519
16520 CallExpr *TheCall = nullptr;
16522 if (Method->isExplicitObjectMemberFunction()) {
16523 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
16524 NewArgs))
16525 return ExprError();
16526
16527 // Build the actual expression node.
16528 ExprResult FnExpr =
16529 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
16530 HadMultipleCandidates, MemExpr->getExprLoc());
16531 if (FnExpr.isInvalid())
16532 return ExprError();
16533
16534 TheCall =
16535 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
16536 CurFPFeatureOverrides(), Proto->getNumParams());
16537 TheCall->setUsesMemberSyntax(true);
16538 } else {
16539 // Convert the object argument (for a non-static member function call).
16541 MemExpr->getBase(), Qualifier, FoundDecl, Method);
16542 if (ObjectArg.isInvalid())
16543 return ExprError();
16544 MemExpr->setBase(ObjectArg.get());
16545 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
16546 RParenLoc, CurFPFeatureOverrides(),
16547 Proto->getNumParams());
16548 }
16549
16550 // Check for a valid return type.
16551 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
16552 TheCall, Method))
16553 return BuildRecoveryExpr(ResultType);
16554
16555 // Convert the rest of the arguments
16556 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
16557 RParenLoc))
16558 return BuildRecoveryExpr(ResultType);
16559
16560 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16561
16562 if (CheckFunctionCall(Method, TheCall, Proto))
16563 return ExprError();
16564
16565 // In the case the method to call was not selected by the overloading
16566 // resolution process, we still need to handle the enable_if attribute. Do
16567 // that here, so it will not hide previous -- and more relevant -- errors.
16568 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
16569 if (const EnableIfAttr *Attr =
16570 CheckEnableIf(Method, LParenLoc, Args, true)) {
16571 Diag(MemE->getMemberLoc(),
16572 diag::err_ovl_no_viable_member_function_in_call)
16573 << Method << Method->getSourceRange();
16574 Diag(Method->getLocation(),
16575 diag::note_ovl_candidate_disabled_by_function_cond_attr)
16576 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16577 return ExprError();
16578 }
16579 }
16580
16582 TheCall->getDirectCallee()->isPureVirtual()) {
16583 const FunctionDecl *MD = TheCall->getDirectCallee();
16584
16585 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
16587 Diag(MemExpr->getBeginLoc(),
16588 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16590 << MD->getParent();
16591
16592 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
16593 if (getLangOpts().AppleKext)
16594 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
16595 << MD->getParent() << MD->getDeclName();
16596 }
16597 }
16598
16599 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
16600 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16601 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16602 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
16603 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16604 MemExpr->getMemberLoc());
16605 }
16606
16608 TheCall->getDirectCallee());
16609}
16610
16613 SourceLocation LParenLoc,
16614 MultiExprArg Args,
16615 SourceLocation RParenLoc) {
16616 if (checkPlaceholderForOverload(*this, Obj))
16617 return ExprError();
16618 ExprResult Object = Obj;
16619
16620 UnbridgedCastsSet UnbridgedCasts;
16621 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16622 return ExprError();
16623
16624 assert(Object.get()->getType()->isRecordType() &&
16625 "Requires object type argument");
16626
16627 // C++ [over.call.object]p1:
16628 // If the primary-expression E in the function call syntax
16629 // evaluates to a class object of type "cv T", then the set of
16630 // candidate functions includes at least the function call
16631 // operators of T. The function call operators of T are obtained by
16632 // ordinary lookup of the name operator() in the context of
16633 // (E).operator().
16634 OverloadCandidateSet CandidateSet(LParenLoc,
16636 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
16637
16638 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
16639 diag::err_incomplete_object_call, Object.get()))
16640 return true;
16641
16642 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16643 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16645 R.suppressAccessDiagnostics();
16646
16647 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16648 Oper != OperEnd; ++Oper) {
16649 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
16650 Object.get()->Classify(Context), Args, CandidateSet,
16651 /*SuppressUserConversion=*/false);
16652 }
16653
16654 // When calling a lambda, both the call operator, and
16655 // the conversion operator to function pointer
16656 // are considered. But when constraint checking
16657 // on the call operator fails, it will also fail on the
16658 // conversion operator as the constraints are always the same.
16659 // As the user probably does not intend to perform a surrogate call,
16660 // we filter them out to produce better error diagnostics, ie to avoid
16661 // showing 2 failed overloads instead of one.
16662 bool IgnoreSurrogateFunctions = false;
16663 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16664 const OverloadCandidate &Candidate = *CandidateSet.begin();
16665 if (!Candidate.Viable &&
16667 IgnoreSurrogateFunctions = true;
16668 }
16669
16670 // C++ [over.call.object]p2:
16671 // In addition, for each (non-explicit in C++0x) conversion function
16672 // declared in T of the form
16673 //
16674 // operator conversion-type-id () cv-qualifier;
16675 //
16676 // where cv-qualifier is the same cv-qualification as, or a
16677 // greater cv-qualification than, cv, and where conversion-type-id
16678 // denotes the type "pointer to function of (P1,...,Pn) returning
16679 // R", or the type "reference to pointer to function of
16680 // (P1,...,Pn) returning R", or the type "reference to function
16681 // of (P1,...,Pn) returning R", a surrogate call function [...]
16682 // is also considered as a candidate function. Similarly,
16683 // surrogate call functions are added to the set of candidate
16684 // functions for each conversion function declared in an
16685 // accessible base class provided the function is not hidden
16686 // within T by another intervening declaration.
16687 const auto &Conversions = Record->getVisibleConversionFunctions();
16688 for (auto I = Conversions.begin(), E = Conversions.end();
16689 !IgnoreSurrogateFunctions && I != E; ++I) {
16690 NamedDecl *D = *I;
16691 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
16692 if (isa<UsingShadowDecl>(D))
16693 D = cast<UsingShadowDecl>(D)->getTargetDecl();
16694
16695 // Skip over templated conversion functions; they aren't
16696 // surrogates.
16698 continue;
16699
16701 if (!Conv->isExplicit()) {
16702 // Strip the reference type (if any) and then the pointer type (if
16703 // any) to get down to what might be a function type.
16704 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16705 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16706 ConvType = ConvPtrType->getPointeeType();
16707
16708 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16709 {
16710 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
16711 Object.get(), Args, CandidateSet);
16712 }
16713 }
16714 }
16715
16716 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16717
16718 // Perform overload resolution.
16720 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
16721 Best)) {
16722 case OR_Success:
16723 // Overload resolution succeeded; we'll build the appropriate call
16724 // below.
16725 break;
16726
16727 case OR_No_Viable_Function: {
16729 CandidateSet.empty()
16730 ? (PDiag(diag::err_ovl_no_oper)
16731 << Object.get()->getType() << /*call*/ 1
16732 << Object.get()->getSourceRange())
16733 : (PDiag(diag::err_ovl_no_viable_object_call)
16734 << Object.get()->getType() << Object.get()->getSourceRange());
16735 CandidateSet.NoteCandidates(
16736 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
16737 OCD_AllCandidates, Args);
16738 break;
16739 }
16740 case OR_Ambiguous:
16741 if (!R.isAmbiguous())
16742 CandidateSet.NoteCandidates(
16743 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16744 PDiag(diag::err_ovl_ambiguous_object_call)
16745 << Object.get()->getType()
16746 << Object.get()->getSourceRange()),
16747 *this, OCD_AmbiguousCandidates, Args);
16748 break;
16749
16750 case OR_Deleted: {
16751 // FIXME: Is this diagnostic here really necessary? It seems that
16752 // 1. we don't have any tests for this diagnostic, and
16753 // 2. we already issue err_deleted_function_use for this later on anyway.
16754 StringLiteral *Msg = Best->Function->getDeletedMessage();
16755 CandidateSet.NoteCandidates(
16756 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16757 PDiag(diag::err_ovl_deleted_object_call)
16758 << Object.get()->getType() << (Msg != nullptr)
16759 << (Msg ? Msg->getString() : StringRef())
16760 << Object.get()->getSourceRange()),
16761 *this, OCD_AllCandidates, Args);
16762 break;
16763 }
16764 }
16765
16766 if (Best == CandidateSet.end())
16767 return true;
16768
16769 UnbridgedCasts.restore();
16770
16771 if (Best->Function == nullptr) {
16772 // Since there is no function declaration, this is one of the
16773 // surrogate candidates. Dig out the conversion function.
16774 CXXConversionDecl *Conv
16776 Best->Conversions[0].UserDefined.ConversionFunction);
16777
16778 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
16779 Best->FoundDecl);
16780 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
16781 return ExprError();
16782 assert(Conv == Best->FoundDecl.getDecl() &&
16783 "Found Decl & conversion-to-functionptr should be same, right?!");
16784 // We selected one of the surrogate functions that converts the
16785 // object parameter to a function pointer. Perform the conversion
16786 // on the object argument, then let BuildCallExpr finish the job.
16787
16788 // Create an implicit member expr to refer to the conversion operator.
16789 // and then call it.
16790 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
16791 Conv, HadMultipleCandidates);
16792 if (Call.isInvalid())
16793 return ExprError();
16794 // Record usage of conversion in an implicit cast.
16796 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
16797 nullptr, VK_PRValue, CurFPFeatureOverrides());
16798
16799 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
16800 }
16801
16802 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
16803
16804 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16805 // that calls this method, using Object for the implicit object
16806 // parameter and passing along the remaining arguments.
16807 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16808
16809 // An error diagnostic has already been printed when parsing the declaration.
16810 if (Method->isInvalidDecl())
16811 return ExprError();
16812
16813 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16814 unsigned NumParams = Proto->getNumParams();
16815
16816 DeclarationNameInfo OpLocInfo(
16817 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
16818 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16819 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16820 Obj, HadMultipleCandidates,
16821 OpLocInfo.getLoc(),
16822 OpLocInfo.getInfo());
16823 if (NewFn.isInvalid())
16824 return true;
16825
16826 SmallVector<Expr *, 8> MethodArgs;
16827 MethodArgs.reserve(NumParams + 1);
16828
16829 bool IsError = false;
16830
16831 // Initialize the object parameter.
16833 if (Method->isExplicitObjectMemberFunction()) {
16834 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
16835 } else {
16837 Object.get(), /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16838 if (ObjRes.isInvalid())
16839 IsError = true;
16840 else
16841 Object = ObjRes;
16842 MethodArgs.push_back(Object.get());
16843 }
16844
16846 *this, MethodArgs, Method, Args, LParenLoc);
16847
16848 // If this is a variadic call, handle args passed through "...".
16849 if (Proto->isVariadic()) {
16850 // Promote the arguments (C99 6.5.2.2p7).
16851 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16853 Args[i], VariadicCallType::Method, nullptr);
16854 IsError |= Arg.isInvalid();
16855 MethodArgs.push_back(Arg.get());
16856 }
16857 }
16858
16859 if (IsError)
16860 return true;
16861
16862 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16863
16864 // Once we've built TheCall, all of the expressions are properly owned.
16865 QualType ResultTy = Method->getReturnType();
16867 ResultTy = ResultTy.getNonLValueExprType(Context);
16868
16870 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
16872
16873 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
16874 return true;
16875
16876 if (CheckFunctionCall(Method, TheCall, Proto))
16877 return true;
16878
16880}
16881
16883 SourceLocation OpLoc,
16884 bool *NoArrowOperatorFound) {
16885 assert(Base->getType()->isRecordType() &&
16886 "left-hand side must have class type");
16887
16889 return ExprError();
16890
16891 SourceLocation Loc = Base->getExprLoc();
16892
16893 // C++ [over.ref]p1:
16894 //
16895 // [...] An expression x->m is interpreted as (x.operator->())->m
16896 // for a class object x of type T if T::operator->() exists and if
16897 // the operator is selected as the best match function by the
16898 // overload resolution mechanism (13.3).
16899 DeclarationName OpName =
16900 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
16902
16903 if (RequireCompleteType(Loc, Base->getType(),
16904 diag::err_typecheck_incomplete_tag, Base))
16905 return ExprError();
16906
16907 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16908 LookupQualifiedName(R, Base->getType()->castAsRecordDecl());
16909 R.suppressAccessDiagnostics();
16910
16911 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16912 Oper != OperEnd; ++Oper) {
16913 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16914 {}, CandidateSet,
16915 /*SuppressUserConversion=*/false);
16916 }
16917
16918 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16919
16920 // Perform overload resolution.
16922 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16923 case OR_Success:
16924 // Overload resolution succeeded; we'll build the call below.
16925 break;
16926
16927 case OR_No_Viable_Function: {
16928 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16929 if (CandidateSet.empty()) {
16930 QualType BaseType = Base->getType();
16931 if (NoArrowOperatorFound) {
16932 // Report this specific error to the caller instead of emitting a
16933 // diagnostic, as requested.
16934 *NoArrowOperatorFound = true;
16935 return ExprError();
16936 }
16937 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16938 << BaseType << Base->getSourceRange();
16939 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16940 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16941 << FixItHint::CreateReplacement(OpLoc, ".");
16942 }
16943 } else
16944 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16945 << "operator->" << Base->getSourceRange();
16946 CandidateSet.NoteCandidates(*this, Base, Cands);
16947 return ExprError();
16948 }
16949 case OR_Ambiguous:
16950 if (!R.isAmbiguous())
16951 CandidateSet.NoteCandidates(
16952 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16953 << "->" << Base->getType()
16954 << Base->getSourceRange()),
16956 return ExprError();
16957
16958 case OR_Deleted: {
16959 StringLiteral *Msg = Best->Function->getDeletedMessage();
16960 CandidateSet.NoteCandidates(
16961 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16962 << "->" << (Msg != nullptr)
16963 << (Msg ? Msg->getString() : StringRef())
16964 << Base->getSourceRange()),
16965 *this, OCD_AllCandidates, Base);
16966 return ExprError();
16967 }
16968 }
16969
16970 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16971
16972 // Convert the object parameter.
16973 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16974
16975 if (Method->isExplicitObjectMemberFunction()) {
16977 if (R.isInvalid())
16978 return ExprError();
16979 Base = R.get();
16980 } else {
16982 Base, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16983 if (BaseResult.isInvalid())
16984 return ExprError();
16985 Base = BaseResult.get();
16986 }
16987
16988 // Build the operator call.
16989 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16990 Base, HadMultipleCandidates, OpLoc);
16991 if (FnExpr.isInvalid())
16992 return ExprError();
16993
16994 QualType ResultTy = Method->getReturnType();
16996 ResultTy = ResultTy.getNonLValueExprType(Context);
16997
16998 CallExpr *TheCall =
16999 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
17000 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
17001
17002 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
17003 return ExprError();
17004
17005 if (CheckFunctionCall(Method, TheCall,
17006 Method->getType()->castAs<FunctionProtoType>()))
17007 return ExprError();
17008
17010}
17011
17013 DeclarationNameInfo &SuffixInfo,
17014 ArrayRef<Expr*> Args,
17015 SourceLocation LitEndLoc,
17016 TemplateArgumentListInfo *TemplateArgs) {
17017 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
17018
17019 OverloadCandidateSet CandidateSet(UDSuffixLoc,
17021 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
17022 TemplateArgs);
17023
17024 bool HadMultipleCandidates = (CandidateSet.size() > 1);
17025
17026 // Perform overload resolution. This will usually be trivial, but might need
17027 // to perform substitutions for a literal operator template.
17029 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
17030 case OR_Success:
17031 case OR_Deleted:
17032 break;
17033
17035 CandidateSet.NoteCandidates(
17036 PartialDiagnosticAt(UDSuffixLoc,
17037 PDiag(diag::err_ovl_no_viable_function_in_call)
17038 << R.getLookupName()),
17039 *this, OCD_AllCandidates, Args);
17040 return ExprError();
17041
17042 case OR_Ambiguous:
17043 CandidateSet.NoteCandidates(
17044 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
17045 << R.getLookupName()),
17046 *this, OCD_AmbiguousCandidates, Args);
17047 return ExprError();
17048 }
17049
17050 FunctionDecl *FD = Best->Function;
17051 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
17052 nullptr, HadMultipleCandidates,
17053 SuffixInfo.getLoc(),
17054 SuffixInfo.getInfo());
17055 if (Fn.isInvalid())
17056 return true;
17057
17058 // Check the argument types. This should almost always be a no-op, except
17059 // that array-to-pointer decay is applied to string literals.
17060 Expr *ConvArgs[2];
17061 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
17064 SourceLocation(), Args[ArgIdx]);
17065 if (InputInit.isInvalid())
17066 return true;
17067 ConvArgs[ArgIdx] = InputInit.get();
17068 }
17069
17070 QualType ResultTy = FD->getReturnType();
17072 ResultTy = ResultTy.getNonLValueExprType(Context);
17073
17075 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
17076 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
17077
17078 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
17079 return ExprError();
17080
17081 if (CheckFunctionCall(FD, UDL, nullptr))
17082 return ExprError();
17083
17085}
17086
17089 SourceLocation RangeLoc,
17090 const DeclarationNameInfo &NameInfo,
17091 LookupResult &MemberLookup,
17092 OverloadCandidateSet *CandidateSet,
17093 Expr *Range, ExprResult *CallExpr) {
17094 Scope *S = nullptr;
17095
17097 if (!MemberLookup.empty()) {
17098 ExprResult MemberRef =
17099 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
17100 /*IsPtr=*/false, CXXScopeSpec(),
17101 /*TemplateKWLoc=*/SourceLocation(),
17102 /*FirstQualifierInScope=*/nullptr,
17103 MemberLookup,
17104 /*TemplateArgs=*/nullptr, S);
17105 if (MemberRef.isInvalid()) {
17106 *CallExpr = ExprError();
17107 return FRS_DiagnosticIssued;
17108 }
17109 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
17110 if (CallExpr->isInvalid()) {
17111 *CallExpr = ExprError();
17112 return FRS_DiagnosticIssued;
17113 }
17114 } else {
17115 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
17117 NameInfo, UnresolvedSet<0>());
17118 if (FnR.isInvalid())
17119 return FRS_DiagnosticIssued;
17121
17122 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
17123 CandidateSet, CallExpr);
17124 if (CandidateSet->empty() || CandidateSetError) {
17125 *CallExpr = ExprError();
17126 return FRS_NoViableFunction;
17127 }
17129 OverloadingResult OverloadResult =
17130 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
17131
17132 if (OverloadResult == OR_No_Viable_Function) {
17133 *CallExpr = ExprError();
17134 return FRS_NoViableFunction;
17135 }
17136 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
17137 Loc, nullptr, CandidateSet, &Best,
17138 OverloadResult,
17139 /*AllowTypoCorrection=*/false);
17140 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
17141 *CallExpr = ExprError();
17142 return FRS_DiagnosticIssued;
17143 }
17144 }
17145 return FRS_Success;
17146}
17147
17149 FunctionDecl *Fn) {
17150 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
17151 ExprResult SubExpr =
17152 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
17153 if (SubExpr.isInvalid())
17154 return ExprError();
17155 if (SubExpr.get() == PE->getSubExpr())
17156 return PE;
17157
17158 return new (Context)
17159 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
17160 }
17161
17162 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
17163 ExprResult SubExpr =
17164 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
17165 if (SubExpr.isInvalid())
17166 return ExprError();
17167 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
17168 SubExpr.get()->getType()) &&
17169 "Implicit cast type cannot be determined from overload");
17170 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
17171 if (SubExpr.get() == ICE->getSubExpr())
17172 return ICE;
17173
17174 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
17175 SubExpr.get(), nullptr, ICE->getValueKind(),
17177 }
17178
17179 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
17180 if (!GSE->isResultDependent()) {
17181 ExprResult SubExpr =
17182 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
17183 if (SubExpr.isInvalid())
17184 return ExprError();
17185 if (SubExpr.get() == GSE->getResultExpr())
17186 return GSE;
17187
17188 // Replace the resulting type information before rebuilding the generic
17189 // selection expression.
17190 ArrayRef<Expr *> A = GSE->getAssocExprs();
17191 SmallVector<Expr *, 4> AssocExprs(A);
17192 unsigned ResultIdx = GSE->getResultIndex();
17193 AssocExprs[ResultIdx] = SubExpr.get();
17194
17195 if (GSE->isExprPredicate())
17197 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
17198 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17199 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17200 ResultIdx);
17202 Context, GSE->getGenericLoc(), GSE->getControllingType(),
17203 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
17204 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
17205 ResultIdx);
17206 }
17207 // Rather than fall through to the unreachable, return the original generic
17208 // selection expression.
17209 return GSE;
17210 }
17211
17212 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
17213 assert(UnOp->getOpcode() == UO_AddrOf &&
17214 "Can only take the address of an overloaded function");
17215 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
17216 if (!Method->isImplicitObjectMemberFunction()) {
17217 // Do nothing: the address of static and
17218 // explicit object member functions is a (non-member) function pointer.
17219 } else {
17220 // Fix the subexpression, which really has to be an
17221 // UnresolvedLookupExpr holding an overloaded member function
17222 // or template.
17223 ExprResult SubExpr =
17224 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17225 if (SubExpr.isInvalid())
17226 return ExprError();
17227 if (SubExpr.get() == UnOp->getSubExpr())
17228 return UnOp;
17229
17230 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
17231 SubExpr.get(), Method))
17232 return ExprError();
17233
17234 assert(isa<DeclRefExpr>(SubExpr.get()) &&
17235 "fixed to something other than a decl ref");
17236 NestedNameSpecifier Qualifier =
17237 cast<DeclRefExpr>(SubExpr.get())->getQualifier();
17238 assert(Qualifier &&
17239 "fixed to a member ref with no nested name qualifier");
17240
17241 // We have taken the address of a pointer to member
17242 // function. Perform the computation here so that we get the
17243 // appropriate pointer to member type.
17244 QualType MemPtrType = Context.getMemberPointerType(
17245 Fn->getType(), Qualifier,
17246 cast<CXXRecordDecl>(Method->getDeclContext()));
17247 // Under the MS ABI, lock down the inheritance model now.
17248 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
17249 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
17250
17251 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
17252 MemPtrType, VK_PRValue, OK_Ordinary,
17253 UnOp->getOperatorLoc(), false,
17255 }
17256 }
17257 ExprResult SubExpr =
17258 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
17259 if (SubExpr.isInvalid())
17260 return ExprError();
17261 if (SubExpr.get() == UnOp->getSubExpr())
17262 return UnOp;
17263
17264 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
17265 SubExpr.get());
17266 }
17267
17268 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
17269 if (Found.getAccess() == AS_none) {
17271 }
17272 // FIXME: avoid copy.
17273 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17274 if (ULE->hasExplicitTemplateArgs()) {
17275 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
17276 TemplateArgs = &TemplateArgsBuffer;
17277 }
17278
17279 QualType Type = Fn->getType();
17280 ExprValueKind ValueKind =
17281 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
17282 ? VK_LValue
17283 : VK_PRValue;
17284
17285 // FIXME: Duplicated from BuildDeclarationNameExpr.
17286 if (unsigned BID = Fn->getBuiltinID()) {
17287 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
17288 Type = Context.BuiltinFnTy;
17289 ValueKind = VK_PRValue;
17290 }
17291 }
17292
17294 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
17295 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
17296 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17297 return DRE;
17298 }
17299
17300 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
17301 // FIXME: avoid copy.
17302 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17303 if (MemExpr->hasExplicitTemplateArgs()) {
17304 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
17305 TemplateArgs = &TemplateArgsBuffer;
17306 }
17307
17308 Expr *Base;
17309
17310 // If we're filling in a static method where we used to have an
17311 // implicit member access, rewrite to a simple decl ref.
17312 if (MemExpr->isImplicitAccess()) {
17313 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17315 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
17316 MemExpr->getQualifierLoc(), Found.getDecl(),
17317 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17318 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17319 return DRE;
17320 } else {
17321 SourceLocation Loc = MemExpr->getMemberLoc();
17322 if (MemExpr->getQualifier())
17323 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17324 Base =
17325 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
17326 }
17327 } else
17328 Base = MemExpr->getBase();
17329
17330 ExprValueKind valueKind;
17331 QualType type;
17332 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17333 valueKind = VK_LValue;
17334 type = Fn->getType();
17335 } else {
17336 valueKind = VK_PRValue;
17337 type = Context.BoundMemberTy;
17338 }
17339
17340 return BuildMemberExpr(
17341 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
17342 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
17343 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
17344 type, valueKind, OK_Ordinary, TemplateArgs);
17345 }
17346
17347 llvm_unreachable("Invalid reference to overloaded function");
17348}
17349
17355
17356bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17358 if (!PartialOverloading || !Function)
17359 return true;
17360 if (Function->isVariadic())
17361 return false;
17362 if (const auto *Proto =
17363 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
17364 if (Proto->isTemplateVariadic())
17365 return false;
17366 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17367 if (const auto *Proto =
17368 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
17369 if (Proto->isTemplateVariadic())
17370 return false;
17371 return true;
17372}
17373
17375 DeclarationName Name,
17376 OverloadCandidateSet &CandidateSet,
17377 FunctionDecl *Fn, MultiExprArg Args,
17378 bool IsMember) {
17379 StringLiteral *Msg = Fn->getDeletedMessage();
17380 CandidateSet.NoteCandidates(
17381 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
17382 << IsMember << Name << (Msg != nullptr)
17383 << (Msg ? Msg->getString() : StringRef())
17384 << Range),
17385 *this, OCD_AllCandidates, Args);
17386}
Defines the clang::ASTContext interface.
#define V(N, I)
Defines the Diagnostic-related interfaces.
static bool isBooleanType(QualType Ty)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
TokenType getType() const
Returns the token's type, e.g.
Result
Implement __builtin_bit_cast and related operations.
#define X(type, name)
Definition Value.h:97
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
llvm::json::Object Object
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:183
static bool hasExplicitAttr(const VarDecl *D)
Definition SemaCUDA.cpp:31
This file declares semantic analysis for CUDA constructs.
CastType
Definition SemaCast.cpp:50
static void BuildBasePathArray(const CXXBasePath &Path, CXXCastPath &BasePathArray)
static bool isRecordType(QualType T)
static void TryUserDefinedConversion(Sema &S, QualType DestType, const InitializationKind &Kind, Expr *Initializer, InitializationSequence &Sequence, bool TopLevelOfInitList)
Attempt a user-defined conversion between two types (C++ [dcl.init]), which enumerates all conversion...
This file declares semantic analysis for Objective-C.
static ImplicitConversionSequence::CompareKind CompareStandardConversionSequences(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareStandardConversionSequences - Compare two standard conversion sequences to determine whether o...
static bool sameFunctionParameterTypeLists(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2, bool IsFn1Reversed, bool IsFn2Reversed)
We're allowed to use constraints partial ordering only if the candidates have the same parameter type...
static bool isNullPointerConstantForConversion(Expr *Expr, bool InOverloadResolution, ASTContext &Context)
static bool shouldSkipNotingLambdaConversionDecl(const FunctionDecl *Fn)
static const FunctionType * getConversionOpReturnTyAsFunction(CXXConversionDecl *Conv)
static bool functionHasPassObjectSizeParams(const FunctionDecl *FD)
static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1, const FunctionDecl *Cand2)
Compares the enable_if attributes of two FunctionDecls, for the purposes of overload resolution.
static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr *ArgExpr)
CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers, if any, found in visible typ...
FixedEnumPromotion
static void AddOverloadedCallCandidate(Sema &S, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading, bool KnownValid)
Add a single candidate to the overload set.
static void AddTemplateOverloadCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit, Sema::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction)
static bool IsVectorOrMatrixElementConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, Expr *From)
static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, OverloadCandidateSet *CandidateSet, OverloadCandidateSet::iterator *Best, OverloadingResult OverloadResult, bool AllowTypoCorrection)
FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns the completed call expre...
static bool isQualificationConversionStep(QualType FromType, QualType ToType, bool CStyle, bool IsTopLevel, bool &PreviousToQualsIncludeConst, bool &ObjCLifetimeConversion, const ASTContext &Ctx)
Perform a single iteration of the loop for checking if a qualification conversion is valid.
static ImplicitConversionSequence::CompareKind CompareQualificationConversions(Sema &S, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareQualificationConversions - Compares two standard conversion sequences to determine whether the...
static void dropPointerConversion(StandardConversionSequence &SCS)
dropPointerConversions - If the given standard conversion sequence involves any pointer conversions,...
static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand)
static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D, unsigned NumFormalArgs, bool IsAddressOf=false)
General arity mismatch diagnosis over a candidate in a candidate set.
static const Expr * IgnoreNarrowingConversion(ASTContext &Ctx, const Expr *Converted)
Skip any implicit casts which could be either part of a narrowing conversion or after one in an impli...
static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1, const FunctionDecl *F2)
static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI)
static QualType BuildSimilarlyQualifiedPointerType(const Type *FromPtr, QualType ToPointee, QualType ToType, ASTContext &Context, bool StripObjCLifetime=false)
BuildSimilarlyQualifiedPointerType - In a pointer conversion from the pointer type FromPtr to a point...
static void forAllQualifierCombinations(QualifiersAndAtomic Quals, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static bool FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS, QualType DeclType, SourceLocation DeclLoc, Expr *Init, QualType T2, bool AllowRvalues, bool AllowExplicit)
Look for a user-defined conversion to a value reference-compatible with DeclType.
static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static Expr * GetExplicitObjectExpr(Sema &S, Expr *Obj, const FunctionDecl *Fun)
static bool hasDeprecatedStringLiteralToCharPtrConversion(const ImplicitConversionSequence &ICS)
static void AddBuiltinAssignmentOperatorCandidates(Sema &S, QualType T, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
Helper function for AddBuiltinOperatorCandidates() that adds the volatile- and non-volatile-qualified...
static bool CheckConvertedConstantConversions(Sema &S, StandardConversionSequence &SCS)
Check that the specified conversion is permitted in a converted constant expression,...
static bool tryOverflowBehaviorTypeConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc, SourceLocation OpLoc, OverloadCandidate *Cand)
static ImplicitConversionSequence::CompareKind compareConversionFunctions(Sema &S, FunctionDecl *Function1, FunctionDecl *Function2)
Compare the user-defined conversion functions or constructors of two user-defined conversion sequence...
static void forAllQualifierCombinationsImpl(QualifiersAndAtomic Available, QualifiersAndAtomic Applied, llvm::function_ref< void(QualifiersAndAtomic)> Callback)
static const char * GetImplicitConversionName(ImplicitConversionKind Kind)
GetImplicitConversionName - Return the name of this kind of implicit conversion.
static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD, bool Complain, bool InOverloadResolution, SourceLocation Loc)
Returns true if we can take the address of the function.
static ImplicitConversionSequence::CompareKind CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareDerivedToBaseConversions - Compares two standard conversion sequences to determine whether the...
static bool convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc, ArrayRef< Expr * > Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis, Expr *&ConvertedThis, SmallVectorImpl< Expr * > &ConvertedArgs)
static TemplateDecl * getDescribedTemplate(Decl *Templated)
static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand, ArrayRef< Expr * > Args, OverloadCandidateSet::CandidateSetKind CSK)
CompleteNonViableCandidate - Normally, overload resolution only computes up to the first bad conversi...
static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs)
Adopt the given qualifiers for the given type.
static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc, OverloadCandidate *Cand)
static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool IsAddressOf=false)
Additional arity mismatch diagnosis specific to a function overload candidates.
static ImplicitConversionSequence::CompareKind compareStandardConversionSubsets(ASTContext &Context, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
static bool hasDependentExplicit(FunctionTemplateDecl *FTD)
static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, ImplicitConversionKind &ElConv, Expr *From, bool InOverloadResolution, bool CStyle)
Determine whether the conversion from FromType to ToType is a valid vector conversion.
static ImplicitConversionSequence TryContextuallyConvertToObjCPointer(Sema &S, Expr *From)
TryContextuallyConvertToObjCPointer - Attempt to contextually convert the expression From to an Objec...
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static ExprResult CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base, bool HadMultipleCandidates, SourceLocation Loc=SourceLocation(), const DeclarationNameLoc &LocInfo=DeclarationNameLoc())
A convenience routine for creating a decayed reference to a function.
static std::optional< QualType > getImplicitObjectParamType(ASTContext &Context, const FunctionDecl *F)
Compute the type of the implicit object parameter for the given function, if any.
static bool checkPlaceholderForOverload(Sema &S, Expr *&E, UnbridgedCastsSet *unbridgedCasts=nullptr)
checkPlaceholderForOverload - Do any interesting placeholder-like preprocessing on the given expressi...
static FixedEnumPromotion getFixedEnumPromtion(Sema &S, const StandardConversionSequence &SCS)
Returns kind of fixed enum promotion the SCS uses.
static bool isAllowableExplicitConversion(Sema &S, QualType ConvType, QualType ToType, bool AllowObjCPointerConversion)
Determine whether this is an allowable conversion from the result of an explicit conversion operator ...
@ ft_different_class
@ ft_parameter_mismatch
@ ft_noexcept
@ ft_return_type
@ ft_parameter_arity
@ ft_default
@ ft_qualifer_mismatch
static bool isNonViableMultiVersionOverload(FunctionDecl *FD)
static bool FunctionsCorrespond(ASTContext &Ctx, const FunctionDecl *X, const FunctionDecl *Y)
static ImplicitConversionSequence TryImplicitConversion(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion, bool AllowObjCConversionOnExplicit)
TryImplicitConversion - Attempt to perform an implicit conversion from the given expression (Expr) to...
static ExprResult BuildConvertedConstantExpression(Sema &S, Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest, APValue &PreNarrowingValue)
BuildConvertedConstantExpression - Check that the expression From is a converted constant expression ...
static ImplicitConversionSequence TryListConversion(Sema &S, InitListExpr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion)
TryListConversion - Try to copy-initialize a value of type ToType from the initializer list From.
static bool IsOverloadOrOverrideImpl(Sema &SemaRef, FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs, bool UseOverrideRules=false)
static QualType withoutUnaligned(ASTContext &Ctx, QualType T)
static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand)
CUDA: diagnose an invalid call across targets.
static void MaybeDiagnoseAmbiguousConstraints(Sema &S, ArrayRef< OverloadCandidate > Cands)
static bool diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, UnresolvedSetImpl &ExplicitConversions)
static void AddMethodTemplateCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, OverloadCandidateParamOrder PO)
static void AddTemplateConversionCandidateImmediately(Sema &S, OverloadCandidateSet &CandidateSet, FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion)
static ImplicitConversionSequence TryContextuallyConvertToBool(Sema &S, Expr *From)
TryContextuallyConvertToBool - Attempt to contextually convert the expression From to bool (C++0x [co...
static ImplicitConversionSequence TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType, Expr::Classification FromClassification, CXXMethodDecl *Method, const CXXRecordDecl *ActingContext, bool InOverloadResolution=false, QualType ExplicitParameterType=QualType(), bool SuppressUserConversion=false)
TryObjectArgumentInitialization - Try to initialize the object parameter of the given member function...
static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From, Sema::ContextualImplicitConverter &Converter, QualType T, bool HadMultipleCandidates, DeclAccessPair &Found)
static ImplicitConversionSequence::CompareKind CompareImplicitConversionSequences(Sema &S, SourceLocation Loc, const ImplicitConversionSequence &ICS1, const ImplicitConversionSequence &ICS2)
CompareImplicitConversionSequences - Compare two implicit conversion sequences to determine whether o...
static ImplicitConversionSequence::CompareKind CompareOverflowBehaviorConversions(Sema &S, const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
CompareOverflowBehaviorConversions - Compares two standard conversion sequences to determine whether ...
static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand, unsigned NumArgs, bool TakingCandidateAddress, LangAS CtorDestAS=LangAS::Default)
Generates a 'note' diagnostic for an overload candidate.
static ImplicitConversionSequence TryCopyInitialization(Sema &S, Expr *From, QualType ToType, bool SuppressUserConversions, bool InOverloadResolution, bool AllowObjCWritebackConversion, bool AllowExplicit=false)
TryCopyInitialization - Try to copy-initialize a value of type ToType from the expression From.
static ExprResult diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter, QualType T, UnresolvedSetImpl &ViableConversions)
static void markUnaddressableCandidatesUnviable(Sema &S, OverloadCandidateSet &CS)
static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE)
Sema::AllowedExplicit AllowedExplicit
static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T, Expr *Arg)
Helper function for adjusting address spaces for the pointer or reference operands of builtin operato...
static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand)
static bool DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS, LookupResult &R, OverloadCandidateSet::CandidateSetKind CSK, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, CXXRecordDecl **FoundInClass=nullptr)
Attempt to recover from an ill-formed use of a non-dependent name in a template, where the non-depend...
static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1, const StandardConversionSequence &SCS2)
Determine whether one of the given reference bindings is better than the other based on what kind of ...
static bool canBeDeclaredInNamespace(const DeclarationName &Name)
Determine whether a declaration with the specified name could be moved into a different namespace.
static ExprResult finishContextualImplicitConversion(Sema &SemaRef, SourceLocation Loc, Expr *From, Sema::ContextualImplicitConverter &Converter)
static bool IsStandardConversion(Sema &S, Expr *From, QualType ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle, bool AllowObjCWritebackConversion)
IsStandardConversion - Determines whether there is a standard conversion sequence (C++ [conv],...
static bool DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args)
Attempt to recover from ill-formed use of a non-dependent operator in a template, where the non-depen...
static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals, Qualifiers ToQuals)
Determine whether the lifetime conversion between the two given qualifiers sets is nontrivial.
static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I, bool TakingCandidateAddress)
static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc, bool Complain=true)
static bool shouldAddReversedEqEq(Sema &S, SourceLocation OpLoc, Expr *FirstOperand, FunctionDecl *EqFD)
static bool isFunctionAlwaysEnabled(const ASTContext &Ctx, const FunctionDecl *FD)
static bool PrepareExplicitObjectArgument(Sema &S, CXXMethodDecl *Method, Expr *Object, MultiExprArg &Args, SmallVectorImpl< Expr * > &NewArgs)
static OverloadingResult IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType, CXXRecordDecl *To, UserDefinedConversionSequence &User, OverloadCandidateSet &CandidateSet, bool AllowExplicit)
static bool IsMatrixConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, ImplicitConversionKind &ElConv, Expr *From, bool InOverloadResolution, bool CStyle)
Determine whether the conversion from FromType to ToType is a valid matrix conversion.
static bool checkAddressOfCandidateIsAvailable(Sema &S, const FunctionDecl *FD)
static bool IsFloatingPointConversion(Sema &S, QualType FromType, QualType ToType)
Determine whether the conversion from FromType to ToType is a valid floating point conversion.
static bool isFirstArgumentCompatibleWithType(ASTContext &Context, CXXConstructorDecl *Constructor, QualType Type)
static Comparison isBetterMultiversionCandidate(const OverloadCandidate &Cand1, const OverloadCandidate &Cand2)
static void NoteImplicitDeductionGuide(Sema &S, FunctionDecl *Fn)
static void collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType, UnresolvedSetImpl &ViableConversions, OverloadCandidateSet &CandidateSet)
static ImplicitConversionSequence TryReferenceInit(Sema &S, Expr *Init, QualType DeclType, SourceLocation DeclLoc, bool SuppressUserConversions, bool AllowExplicit)
Compute an implicit conversion sequence for reference initialization.
static bool isNonDependentlyExplicit(FunctionTemplateDecl *FTD)
Determine whether a given function template has a simple explicit specifier or a non-value-dependent ...
static bool checkArgPlaceholdersForOverload(Sema &S, MultiExprArg Args, UnbridgedCastsSet &unbridged)
checkArgPlaceholdersForOverload - Check a set of call operands for placeholders.
static QualType makeQualifiedLValueReferenceType(QualType Base, QualifiersAndAtomic Quals, Sema &S)
static QualType chooseRecoveryType(OverloadCandidateSet &CS, OverloadCandidateSet::iterator *Best)
static void AddTemplateOverloadCandidate(Sema &S, OverloadCandidateSet &CandidateSet, DeferredMethodTemplateOverloadCandidate &C)
static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand)
static ExprResult BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MutableArrayRef< Expr * > Args, SourceLocation RParenLoc, bool EmptyLookup, bool AllowTypoCorrection)
Attempts to recover from a call where no functions were found.
static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand)
static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND, bool ArgDependent, SourceLocation Loc, CheckFn &&IsSuccessful)
static OverloadingResult IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType, UserDefinedConversionSequence &User, OverloadCandidateSet &Conversions, AllowedExplicit AllowExplicit, bool AllowObjCConversionOnExplicit)
Determines whether there is a user-defined conversion sequence (C++ [over.ics.user]) that converts ex...
static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context, FunctionDecl *Fn, ArrayRef< Expr * > Args)
IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is an acceptable non-member overloaded ...
static FunctionDecl * getMorePartialOrderingConstrained(Sema &S, FunctionDecl *Fn1, FunctionDecl *Fn2, bool IsFn1Reversed, bool IsFn2Reversed)
static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated, DeductionFailureInfo &DeductionFailure, unsigned NumArgs, bool TakingCandidateAddress)
Diagnose a failed template-argument deduction.
static bool IsTransparentUnionStandardConversion(Sema &S, Expr *From, QualType &ToType, bool InOverloadResolution, StandardConversionSequence &SCS, bool CStyle)
static const FunctionProtoType * tryGetFunctionProtoType(QualType FromType)
Attempts to get the FunctionProtoType from a Type.
static bool PrepareArgumentsForCallToObjectOfClassType(Sema &S, SmallVectorImpl< Expr * > &MethodArgs, CXXMethodDecl *Method, MultiExprArg Args, SourceLocation LParenLoc)
static TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< TemplateArgument > Ps, ArrayRef< TemplateArgument > As, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool NumberOfArgumentsMustMatch, bool PartialOrdering, PackFold PackFold, bool *HasDeducedAnyParam)
Defines the SourceManager interface.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
a trap message and trap category.
A class for storing results from argument-dependent lookup.
Definition Lookup.h:871
iterator end()
Definition Lookup.h:895
void erase(NamedDecl *D)
Removes any data associated with a given decl.
Definition Lookup.h:887
iterator begin()
Definition Lookup.h:894
llvm::mapped_iterator< decltype(Decls)::iterator, select_second > iterator
Definition Lookup.h:891
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
bool isAbsent() const
Definition APValue.h:481
bool isFloat() const
Definition APValue.h:486
bool isInt() const
Definition APValue.h:485
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:974
APFloat & getFloat()
Definition APValue.h:522
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
const ConstantArrayType * getAsConstantArrayType(QualType T) const
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
CanQualType LongTy
unsigned getIntWidth(QualType T) const
CanQualType Int128Ty
bool areCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an RISC-V vector builtin type and a VectorType that is a fixed-len...
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
DeclarationNameTable DeclarationNames
Definition ASTContext.h:809
CanQualType FloatTy
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
CanQualType DoubleTy
CanQualType LongDoubleTy
CanQualType Char16Ty
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
bool canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, const ObjCObjectPointerType *RHSOPT)
canAssignObjCInterfaces - Return true if the two interface types are compatible for assignment from R...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
CanQualType NullPtrTy
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition ASTContext.h:962
CanQualType getLogicalOperationType() const
The result type of logical operations, '<', '>', '!=', etc.
bool areLaxCompatibleRVVTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible RISC-V vector types as defined by -flax-vect...
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
CanQualType Ibm128Ty
void forEachMultiversionedFunctionVersion(const FunctionDecl *FD, llvm::function_ref< void(FunctionDecl *)> Pred) const
Visits all versions of a multiversioned function with the passed predicate.
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
CanQualType BoolTy
const TargetInfo * getAuxTargetInfo() const
Definition ASTContext.h:925
CanQualType Float128Ty
CanQualType UnsignedLongTy
QualType getRestrictType(QualType T) const
Return the uniqued reference to the type for a restrict qualified type.
CanQualType CharTy
CanQualType IntTy
bool areCompatibleOverflowBehaviorTypes(QualType LHS, QualType RHS)
Return true if two OverflowBehaviorTypes are compatible for assignment.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
CanQualType SignedCharTy
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
CanQualType OverloadTy
QualType getObjCIdType() const
Represents the Objective-CC id type.
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
bool isSameTemplateParameterList(const TemplateParameterList *X, const TemplateParameterList *Y) const
Determine whether two template parameter lists are similar enough that they may be used in declaratio...
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CanQualType UnsignedInt128Ty
CanQualType VoidTy
CanQualType UnsignedCharTy
CanQualType UnsignedIntTy
QualType getVolatileType(QualType T) const
Return the uniqued reference to the type for a volatile qualified type.
CanQualType UnsignedLongLongTy
QualType getArrayDecayedType(QualType T) const
Return the properly qualified result of decaying the specified array type to a pointer.
CanQualType UnsignedShortTy
QualType getMemberPointerType(QualType T, NestedNameSpecifier Qualifier, const CXXRecordDecl *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
CanQualType ShortTy
CanQualType Char32Ty
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getCVRQualifiedType(QualType T, unsigned CVR) const
Return a type with additional const, volatile, or restrict qualifiers.
bool areCompatibleVectorTypes(QualType FirstVec, QualType SecondVec)
Return true if the given vector types are of the same unqualified type or if they are equivalent to t...
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:924
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType LongLongTy
CanQualType getCanonicalTagType(const TagDecl *TD) const
CanQualType WCharTy
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
CanQualType Char8Ty
QualType getUnqualifiedArrayType(QualType T, Qualifiers &Quals) const
Return this type as a completely-unqualified array type, capturing the qualifiers in Quals.
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition TypeBase.h:3956
QualType getConstantArrayType(const ASTContext &Ctx) const
Definition Type.cpp:316
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3786
QualType getElementType() const
Definition TypeBase.h:3798
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8246
Attr - This represents one attribute.
Definition Attr.h:46
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4044
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2187
StringRef getOpcodeStr() const
Definition Expr.h:4110
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2140
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5104
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4185
Pointer to a block type.
Definition TypeBase.h:3606
This class is used for builtin types like 'int'.
Definition TypeBase.h:3228
Kind getKind() const
Definition TypeBase.h:3276
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
const RecordType * getDetectedVirtual() const
The virtual base discovered on the path (if we are merely detecting virtuals).
CXXBasePath & front()
bool isAmbiguous(CanQualType BaseType) const
Determine whether the path from the most-derived type to the given base type is ambiguous (i....
Represents a C++ constructor within a class.
Definition DeclCXX.h:2633
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3067
bool isConvertingConstructor(bool AllowExplicit) const
Whether this constructor is a converting constructor (C++ [class.conv.ctor]), which can be used for u...
Definition DeclCXX.cpp:3104
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2968
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition DeclCXX.h:3000
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:3004
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:183
static CXXMemberCallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RP, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0)
Definition ExprCXX.cpp:699
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
bool isExplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An explicit object member function is a non-static member function with an explic...
Definition DeclCXX.cpp:2717
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition DeclCXX.cpp:2724
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2868
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2284
static CXXOperatorCallExpr * Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation OperatorLoc, FPOptionsOverride FPFeatures, ADLCallKind UsesADL=NotADL, bool IsReversed=false)
Definition ExprCXX.cpp:629
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1023
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition DeclCXX.cpp:1987
bool isHLSLBuiltinRecord() const
Returns true if the class is a built-in HLSL record.
Definition DeclCXX.h:1564
bool hasDefinition() const
Definition DeclCXX.h:561
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1742
A rewritten comparison expression that was originally written using operator syntax.
Definition ExprCXX.h:290
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:76
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:181
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition DeclSpec.cpp:103
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2949
static CallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0, ADLCallKind UsesADL=NotADL)
Create a call expression.
Definition Expr.cpp:1523
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3132
void setUsesMemberSyntax(bool V=true)
Definition Expr.h:3113
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition Expr.h:3331
Represents a canonical, potentially-qualified type.
bool isAtLeastAsQualifiedAs(CanQual< T > Other, const ASTContext &Ctx) const
Determines whether this canonical type is at least as qualified as the Other canonical type.
static CanQual< Type > CreateUnsafe(QualType Other)
CanProxy< U > castAs() const
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
Qualifiers getQualifiers() const
Retrieve all qualifiers.
CanProxy< U > getAs() const
Retrieve a canonical type pointer with a different static type, upcasting or downcasting as needed.
bool isVolatileQualified() const
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
bool isPartial() const
True iff the comparison is not totally ordered.
bool isStrong() const
True iff the comparison is "strong".
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3339
QualType getElementType() const
Definition TypeBase.h:3349
static CompoundAssignOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures, QualType CompLHSType=QualType(), QualType CompResultType=QualType())
Definition Expr.cpp:5126
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3824
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:356
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4451
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4470
unsigned getNumRows() const
Returns the number of rows in the matrix.
Definition TypeBase.h:4467
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
NamedDecl * getDecl() const
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1466
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context semantically encloses the declaration context DC.
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
void setHadMultipleCandidates(bool V=true)
Sets the flag telling whether this expression refers to a function that was resolved from an overload...
Definition Expr.h:1469
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition DeclBase.cpp:285
T * getAttr() const
Definition DeclBase.h:581
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:547
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:601
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition DeclBase.cpp:273
bool isInvalidDecl() const
Definition DeclBase.h:596
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:567
SourceLocation getLocation() const
Definition DeclBase.h:447
DeclContext * getDeclContext()
Definition DeclBase.h:456
AccessSpecifier getAccess() const
Definition DeclBase.h:515
specific_attr_iterator< T > specific_attr_end() const
Definition DeclBase.h:577
specific_attr_iterator< T > specific_attr_begin() const
Definition DeclBase.h:572
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:935
bool hasAttr() const
Definition DeclBase.h:585
DeclarationNameLoc - Additional source/type location info for a declaration name.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
TemplateDecl * getCXXDeductionGuideTemplate() const
If this name is the name of a C++ deduction guide, return the template associated with that name.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:831
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:855
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition Diagnostic.h:787
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition Diagnostic.h:772
OverloadsShown getShowOverloads() const
Definition Diagnostic.h:763
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:599
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4030
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition Decl.h:4248
EnumDecl * getDefinitionOrSelf() const
Definition Decl.h:4146
Store information needed for an explicit specifier.
Definition DeclCXX.h:1944
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition DeclCXX.h:1968
ExplicitSpecKind getKind() const
Definition DeclCXX.h:1952
const Expr * getExpr() const
Definition DeclCXX.h:1953
static ExplicitSpecifier getFromDecl(const FunctionDecl *Function)
Definition DeclCXX.cpp:2368
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1471
The return type of classify().
Definition Expr.h:339
bool isLValue() const
Definition Expr.h:390
bool isPRValue() const
Definition Expr.h:393
bool isXValue() const
Definition Expr.h:391
static Classification makeSimpleLValue()
Create a simple, modifiable lvalue.
Definition Expr.h:398
bool isRValue() const
Definition Expr.h:394
This represents one expression.
Definition Expr.h:112
bool isIntegerConstantExpr(const ASTContext &Ctx) const
bool isGLValue() const
Definition Expr.h:287
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3104
void setType(QualType t)
Definition Expr.h:145
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:447
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3095
bool isPRValue() const
Definition Expr.h:285
static bool hasAnyTypeDependentArguments(ArrayRef< Expr * > Exprs)
hasAnyTypeDependentArguments - Determines if any of the expressions in Exprs is type-dependent.
Definition Expr.cpp:3348
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4238
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:837
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:841
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:454
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
Definition Expr.h:817
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Definition Expr.cpp:4077
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:479
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition Expr.h:415
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:526
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:437
ExtVectorType - Extended vector type.
Definition TypeBase.h:4331
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3179
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:81
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:142
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:105
Represents a function declaration or definition.
Definition Decl.h:2027
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2694
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2802
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4171
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3740
param_iterator param_end()
Definition Decl.h:2792
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition Decl.cpp:3644
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3843
QualType getReturnType() const
Definition Decl.h:2850
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2779
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition Decl.cpp:4243
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4292
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:3725
param_iterator param_begin()
Definition Decl.h:2791
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3111
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4308
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4236
unsigned getNumNonObjectParams() const
Definition Decl.cpp:3847
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2471
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4108
bool isConsteval() const
Definition Decl.h:2483
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition Decl.cpp:3688
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition Decl.h:2867
bool isTargetMultiVersionDefault() const
True if this function is the default version of a multiversioned dispatch function as a part of the t...
Definition Decl.cpp:3693
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3804
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2690
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5371
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5875
unsigned getNumParams() const
Definition TypeBase.h:5649
Qualifiers getMethodQuals() const
Definition TypeBase.h:5797
QualType getParamType(unsigned i) const
Definition TypeBase.h:5651
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5775
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5811
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
A class which abstracts out some details necessary for making a call.
Definition TypeBase.h:4678
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4749
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4606
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4567
ExtInfo getExtInfo() const
Definition TypeBase.h:4923
CallingConv getCallConv() const
Definition TypeBase.h:4922
QualType getReturnType() const
Definition TypeBase.h:4907
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4935
static GenericSelectionExpr * Create(const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, ArrayRef< TypeSourceInfo * > AssocTypes, ArrayRef< Expr * > AssocExprs, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
Create a non-result-dependent generic selection expression accepting an expression predicate.
Definition Expr.cpp:4725
One of these records is kept for each identifier that is lexed.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3859
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2079
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:622
void dump() const
dump - Print this implicit conversion sequence to standard error.
StandardConversionSequence Standard
When ConversionKind == StandardConversion, provides the details of the standard conversion sequence.
Definition Overload.h:673
void setBad(BadConversionSequence::FailureKind Failure, Expr *FromExpr, QualType ToType)
Sets this sequence as a bad conversion for an explicit argument.
Definition Overload.h:770
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition Overload.h:677
static ImplicitConversionSequence getNullptrToBool(QualType SourceType, QualType DestType, bool NeedLValToRVal)
Form an "implicit" conversion sequence from nullptr_t to bool, for a direct-initialization of a bool ...
Definition Overload.h:827
AmbiguousConversionSequence Ambiguous
When ConversionKind == AmbiguousConversion, provides the details of the ambiguous conversion.
Definition Overload.h:681
bool hasInitializerListContainerType() const
Definition Overload.h:809
unsigned getKindRank() const
Return a ranking of the implicit conversion sequence kind, where smaller ranks represent better conve...
Definition Overload.h:734
bool isInitializerListOfIncompleteArray() const
Definition Overload.h:816
BadConversionSequence Bad
When ConversionKind == BadConversion, provides the details of the bad conversion.
Definition Overload.h:685
QualType getInitializerListContainerType() const
Definition Overload.h:819
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition Expr.h:5305
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition Expr.h:5421
unsigned getNumInits() const
Definition Expr.h:5338
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:2505
const Expr * getInit(unsigned Init) const
Definition Expr.h:5360
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:2523
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static InitializedEntity InitializeTemplateParameter(QualType T, NamedDecl *Param)
Create the initialization entity for a template parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition Expr.cpp:981
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3681
bool isCompatibleWithMSVC() const
Represents the results of name lookup.
Definition Lookup.h:147
void addAllDecls(const LookupResult &Other)
Add all the declarations from another set of lookup results.
Definition Lookup.h:488
DeclClass * getAsSingle() const
Definition Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition Lookup.h:275
void suppressAccessDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup due to access control violat...
Definition Lookup.h:643
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
QualType getElementType() const
Returns type of the elements being stored in the matrix.
Definition TypeBase.h:4415
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3370
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3559
NestedNameSpecifier getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition Expr.h:3481
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3453
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition Expr.h:3467
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3588
Expr * getBase() const
Definition Expr.h:3447
void setBase(Expr *E)
Definition Expr.h:3446
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1800
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3565
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition Expr.h:3457
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3717
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3749
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5646
QualType getPointeeType() const
Definition TypeBase.h:3735
Describes a module or submodule.
Definition Module.h:340
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition Module.cpp:240
This represents a decl that may have a name.
Definition Decl.h:274
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:487
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1682
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1208
Represent a C++ namespace.
Definition Decl.h:592
A C++ nested-name-specifier augmented with source location information.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
Represents an ObjC class declaration.
Definition DeclObjC.h:1154
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition TypeBase.h:8009
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition TypeBase.h:8065
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition TypeBase.h:8154
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8123
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8077
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8117
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1889
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:8129
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1184
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1160
void clear(CandidateSetKind CSK)
Clear out all of the candidates.
void AddDeferredTemplateCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit, CallExpr::ADLCallKind IsADLCandidate, OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction)
bool isNewCandidate(Decl *F, OverloadCandidateParamOrder PO=OverloadCandidateParamOrder::Normal)
Determine when this overload candidate will be new to the overload set.
Definition Overload.h:1360
bool shouldDeferTemplateArgumentDeduction(const Sema &S) const
void AddDeferredConversionTemplateCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion)
void AddDeferredMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, bool SuppressUserConversions, bool PartialOverloading, OverloadCandidateParamOrder PO)
void DisableResolutionByPerfectCandidate()
Definition Overload.h:1458
ConversionSequenceList allocateConversionSequences(unsigned NumConversions)
Allocate storage for conversion sequences for NumConversions conversions.
Definition Overload.h:1392
llvm::MutableArrayRef< Expr * > getPersistentArgsArray(unsigned N)
Provide storage for any Expr* arg that must be preserved until deferred template candidates are deduc...
Definition Overload.h:1408
OperatorRewriteInfo getRewriteInfo() const
Definition Overload.h:1350
@ CSK_AddressOfOverloadSet
C++ [over.match.call.general] Resolve a call through the address of an overload set.
Definition Overload.h:1185
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition Overload.h:1181
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition Overload.h:1176
@ CSK_Normal
Normal lookup.
Definition Overload.h:1164
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition Overload.h:1171
@ CSK_CodeCompletion
When doing overload resolution during code completion, we want to show all viable candidates,...
Definition Overload.h:1190
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1376
void NoteCandidates(PartialDiagnosticAt PA, Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, StringRef Opc="", SourceLocation Loc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
When overload resolution fails, prints diagnostic messages containing the candidates in the candidate...
bool shouldDeferDiags(Sema &S, ArrayRef< Expr * > Args, SourceLocation OpLoc)
Whether diagnostics should be deferred.
OverloadingResult BestViableFunction(Sema &S, SourceLocation Loc, OverloadCandidateSet::iterator &Best)
Find the best viable function on this overload set, if it exists.
void exclude(Decl *F)
Exclude a function from being considered by overload resolution.
Definition Overload.h:1368
SourceLocation getLocation() const
Definition Overload.h:1348
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition Overload.h:1423
void InjectNonDeducedTemplateCandidates(Sema &S)
CandidateSetKind getKind() const
Definition Overload.h:1349
size_t nonDeferredCandidatesCount() const
Definition Overload.h:1383
SmallVector< OverloadCandidate *, 32 > CompleteCandidates(Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef< Expr * > Args, SourceLocation OpLoc=SourceLocation(), llvm::function_ref< bool(OverloadCandidate &)> Filter=[](OverloadCandidate &) { return true;})
A reference to an overloaded function set, either an UnresolvedLookupExpr or an UnresolvedMemberExpr.
Definition ExprCXX.h:3132
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition ExprCXX.h:3284
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3193
NestedNameSpecifier getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition ExprCXX.h:3248
SourceLocation getNameLoc() const
Gets the location of the name.
Definition ExprCXX.h:3245
UnresolvedSetImpl::iterator decls_iterator
Definition ExprCXX.h:3223
decls_iterator decls_begin() const
Definition ExprCXX.h:3225
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition ExprCXX.h:3236
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition ExprCXX.h:3258
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition ExprCXX.h:3254
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition ExprCXX.h:3342
decls_iterator decls_end() const
Definition ExprCXX.h:3228
DeclarationName getName() const
Gets the name looked up.
Definition ExprCXX.h:3242
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:279
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2188
Represents a parameter to a function.
Definition Decl.h:1817
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3036
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:301
std::string getAsString() const
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3392
QualType getPointeeType() const
Definition TypeBase.h:3402
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5198
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8531
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8525
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8536
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3686
QualType withConst() const
Definition TypeBase.h:1174
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1240
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8447
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8573
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8487
void getAsStringInternal(std::string &Str, const PrintingPolicy &Policy) const
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8632
QualType getCanonicalType() const
Definition TypeBase.h:8499
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8541
unsigned getLocalCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers local to this particular QualType instan...
Definition TypeBase.h:1089
bool isMoreQualifiedThan(QualType Other, const ASTContext &Ctx) const
Determine whether this type is more qualified than the other given type, requiring exact equality for...
Definition TypeBase.h:8601
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8520
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8568
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8493
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1347
bool isAtLeastAsQualifiedAs(QualType Other, const ASTContext &Ctx) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
Definition TypeBase.h:8612
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8479
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8387
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8394
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4796
QualifiersAndAtomic withVolatile()
Definition TypeBase.h:853
QualifiersAndAtomic withAtomic()
Definition TypeBase.h:860
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
unsigned getCVRQualifiers() const
Definition TypeBase.h:488
GC getObjCGCAttr() const
Definition TypeBase.h:519
bool hasOnlyConst() const
Definition TypeBase.h:458
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:354
void removeObjCLifetime()
Definition TypeBase.h:551
bool hasConst() const
Definition TypeBase.h:457
bool compatiblyIncludes(Qualifiers other, const ASTContext &Ctx) const
Determines if these qualifiers compatibly include another set.
Definition TypeBase.h:727
bool hasRestrict() const
Definition TypeBase.h:477
static bool isAddressSpaceSupersetOf(LangAS A, LangAS B, const ASTContext &Ctx)
Returns true if address space A is equal to or a superset of B.
Definition TypeBase.h:708
void removeObjCGCAttr()
Definition TypeBase.h:523
void removeUnaligned()
Definition TypeBase.h:515
void removeAddressSpace()
Definition TypeBase.h:596
void setAddressSpace(LangAS space)
Definition TypeBase.h:591
bool hasVolatile() const
Definition TypeBase.h:467
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:603
bool hasObjCGCAttr() const
Definition TypeBase.h:518
ObjCLifetime getObjCLifetime() const
Definition TypeBase.h:545
void removeVolatile()
Definition TypeBase.h:469
std::string getAsString() const
LangAS getAddressSpace() const
Definition TypeBase.h:571
bool compatiblyIncludesObjCLifetime(Qualifiers other) const
Determines if these qualifiers compatibly include another set of qualifiers from the narrow perspecti...
Definition TypeBase.h:750
An rvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3699
Represents a struct/union/class.
Definition Decl.h:4344
field_range fields() const
Definition Decl.h:4547
RecordDecl * getDefinitionOrSelf() const
Definition Decl.h:4532
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3637
QualType getPointeeType() const
Definition TypeBase.h:3655
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
Smart pointer class that efficiently represents Objective-C method names.
unsigned getNumArgs() const
bool areCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given types are an SVE builtin and a VectorType that is a fixed-length representat...
Definition SemaARM.cpp:1516
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
Definition SemaARM.cpp:1561
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
bool IsAllowedCall(const FunctionDecl *Caller, const FunctionDecl *Callee)
Determines whether Caller may invoke Callee, based on their CUDA host/device attributes.
Definition SemaCUDA.h:187
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:208
bool inferTargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose)
Given a implicit special member, infer its CUDA target from the calls it needs to make to underlying ...
Definition SemaCUDA.cpp:459
static bool isImplicitHostDeviceFunction(const FunctionDecl *D)
Definition SemaCUDA.cpp:396
void EraseUnwantedMatches(const FunctionDecl *Caller, llvm::SmallVectorImpl< std::pair< DeclAccessPair, FunctionDecl * > > &Matches)
Finds a function in Matches with highest calling priority from Caller context and erases all function...
Definition SemaCUDA.cpp:406
CUDAFunctionPreference IdentifyPreference(const FunctionDecl *Caller, const FunctionDecl *Callee)
Identifies relative preference of a given Caller/Callee combination, based on their host/device attri...
Definition SemaCUDA.cpp:308
bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
Determine whether this is an Objective-C writeback conversion, used for parameter passing when perfor...
Expr * stripARCUnbridgedCast(Expr *e)
stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast type, remove the placeholder cast.
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
Definition Sema.h:10404
virtual SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy)=0
Emits a note for one of the candidate conversions.
virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic complaining that the expression does not have integral or enumeration type.
virtual SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy)=0
Emits a note for the explicit conversion function.
virtual SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy)=0
Emits a diagnostic when the only matching conversion function is explicit.
virtual SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy)=0
Emits a diagnostic when we picked a conversion function (for cases when we are not allowed to pick a ...
virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic when there are multiple possible conversion functions.
virtual bool match(QualType T)=0
Determine whether the specified type is a valid destination type for this conversion.
virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T)=0
Emits a diagnostic when the expression has incomplete class type.
For a defaulted function, the kind of defaulted function that it is.
Definition Sema.h:6443
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6472
RAII class to control scope of DeferDiags.
Definition Sema.h:10127
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition Sema.h:1387
DelayedDiagnosticsState pushUndelayed()
Enter a new scope where access and deprecation diagnostics are not delayed.
Definition Sema.h:1422
bool match(QualType T) override
Match an integral or (possibly scoped) enumeration type.
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12500
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12534
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:869
bool TryFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy) const
Same as IsFunctionConversion, but if this would return true, it sets ResultTy to ToType.
SemaAMDGPU & AMDGPU()
Definition Sema.h:1449
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef< const Expr * > Args, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any non-ArgDependent DiagnoseIf...
ExprResult PerformContextuallyConvertToObjCPointer(Expr *From)
PerformContextuallyConvertToObjCPointer - Perform a contextual conversion of the expression From to a...
bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, MultiExprArg Args, SourceLocation RParenLoc, OverloadCandidateSet *CandidateSet, ExprResult *Result)
Constructs and populates an OverloadedCandidateSet from the given function.
void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow)
Hides a using shadow declaration.
bool IsBuildingRecoveryCallExpr
Flag indicating if Sema is building a recovery call expression.
Definition Sema.h:10145
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs=nullptr)
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9415
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9442
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9427
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9423
void DiagnoseSentinelCalls(const NamedDecl *D, SourceLocation Loc, ArrayRef< Expr * > Args)
DiagnoseSentinelCalls - This routine checks whether a call or message-send is to a declaration with t...
Definition SemaExpr.cpp:417
ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion)
ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef< Expr * > Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to a literal operator descri...
bool IsStringInit(Expr *Init, const ArrayType *AT)
Definition SemaInit.cpp:170
ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr, bool ForFoldExpression=false)
CreateBuiltinBinOp - Creates a new built-in binary operation with operator Opc at location TokLoc.
ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base, MultiExprArg Args)
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateParameterList *TemplateParams, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef< Expr * > Args, bool RequiresADL=true)
Perform lookup for an overloaded binary operator.
SemaCUDA & CUDA()
Definition Sema.h:1474
bool isImplicitlyDeleted(FunctionDecl *FD)
Determine whether the given function is an implicitly-deleted special member function.
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
ReferenceCompareResult
ReferenceCompareResult - Expresses the result of comparing two types (cv1 T1 and cv2 T2) to determine...
Definition Sema.h:10487
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10490
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10496
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10494
@ AR_dependent
Definition Sema.h:1689
@ AR_accessible
Definition Sema.h:1687
@ AR_inaccessible
Definition Sema.h:1688
@ AR_delayed
Definition Sema.h:1690
void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true)
Adds a conversion function template specialization candidate to the overload set, using template argu...
FunctionDecl * getMoreConstrainedFunction(FunctionDecl *FD1, FunctionDecl *FD2)
Returns the more constrained function according to the rules of partial ordering by constraints (C++ ...
void AddBuiltinCandidate(QualType *ParamTys, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool IsAssignmentOperator=false, unsigned NumContextualBoolArguments=0)
AddBuiltinCandidate - Add a candidate for a built-in operator.
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor,...
void AddArgumentDependentLookupCandidates(DeclarationName Name, SourceLocation Loc, ArrayRef< Expr * > Args, TemplateArgumentListInfo *ExplicitTemplateArgs, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add function candidates found via argument-dependent lookup to the set of overloading candidates.
ExprResult EvaluateConvertedConstantExpression(Expr *E, QualType T, APValue &Value, CCEKind CCE, bool RequireInt, const APValue &PreNarrowingValue)
EvaluateConvertedConstantExpression - Evaluate an Expression That is a converted constant expression ...
FPOptionsOverride CurFPFeatureOverrides()
Definition Sema.h:2078
ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound=nullptr)
BuildOverloadedArrowExpr - Build a call to an overloaded operator-> (if one exists),...
ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallToMemberFunction - Build a call to a member function.
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
Check assignment constraints for an assignment of RHS to LHSType.
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
Definition Sema.cpp:1725
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose=true)
ASTContext & Context
Definition Sema.h:1309
bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion)
IsQualificationConversion - Determines whether the conversion from an rvalue of type FromType to ToTy...
void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc)
Warn if we're implicitly casting from a _Nullable pointer type to a _Nonnull one.
Definition Sema.cpp:686
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:227
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:937
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate, ArrayRef< QualType > ParamTypes, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, CheckNonDependentConversionsFlag UserConversionFlag, CXXRecordDecl *ActingContext=nullptr, QualType ObjectType=QualType(), Expr::Classification ObjectClassification={}, OverloadCandidateParamOrder PO={})
Check that implicit conversion sequences can be formed for each argument whose corresponding paramete...
bool isObjCPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType, bool &IncompatibleObjC)
isObjCPointerConversion - Determines whether this is an Objective-C pointer conversion.
SemaObjC & ObjC()
Definition Sema.h:1519
FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates=nullptr)
ResolveAddressOfOverloadedFunction - Try to resolve the address of an overloaded function (C++ [over....
bool FunctionParamTypesAreEqual(ArrayRef< QualType > Old, ArrayRef< QualType > New, unsigned *ArgPos=nullptr, bool Reversed=false)
FunctionParamTypesAreEqual - This routine checks two function proto types for equality of their param...
ExprResult PerformImplicitObjectArgumentInitialization(Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method)
PerformObjectArgumentInitialization - Perform initialization of the implicit object parameter for the...
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
Definition SemaExpr.cpp:761
ASTContext & getASTContext() const
Definition Sema.h:940
UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain=true, QualType TargetType=QualType())
Retrieve the most specialized of the given function template specializations.
bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType)
IsIntegralPromotion - Determines whether the conversion from the expression From (whose potentially-a...
bool IsFloatingPointPromotion(QualType FromType, QualType ToType)
IsFloatingPointPromotion - Determines whether the conversion from FromType to ToType is a floating po...
ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs)
void PopExpressionEvaluationContext()
ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL=true, bool AllowRewrittenCandidates=true, FunctionDecl *DefaultedFn=nullptr)
Create a binary operation that may resolve to an overloaded operator.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
Definition Sema.cpp:762
bool FunctionNonObjectParamTypesAreEqual(const FunctionDecl *OldFunction, const FunctionDecl *NewFunction, unsigned *ArgPos=nullptr, bool Reversed=false)
bool isInitListConstructor(const FunctionDecl *Ctor)
Determine whether Ctor is an initializer-list constructor, as defined in [dcl.init....
@ FRS_Success
Definition Sema.h:10875
@ FRS_DiagnosticIssued
Definition Sema.h:10877
@ FRS_NoViableFunction
Definition Sema.h:10876
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9408
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths)
Builds a string representing ambiguous paths from a specific derived class to different subobjects of...
AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, const SourceRange &, DeclAccessPair FoundDecl)
OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool UseMemberUsingDeclRules)
Determine whether the given New declaration is an overload of the declarations in Old.
QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType)
bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType, bool &IncompatibleObjC)
IsPointerConversion - Determines whether the conversion of the expression From, which has the (possib...
@ Conversions
Allow explicit conversion functions but not explicit constructors.
Definition Sema.h:10196
void DiagnoseUseOfDeletedFunction(SourceLocation Loc, SourceRange Range, DeclarationName Name, OverloadCandidateSet &CandidateSet, FunctionDecl *Fn, MultiExprArg Args, bool IsMember=false)
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1213
bool IsComplexPromotion(QualType FromType, QualType ToType)
Determine if a conversion is a complex promotion.
bool pushCodeSynthesisContext(CodeSynthesisContext Ctx)
Module * getOwningModule(const Decl *Entity)
Get the module owning an entity.
Definition Sema.h:3643
DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS=nullptr)
ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE)
@ TPL_TemplateMatch
We are matching the template parameter lists of two templates that might be redeclarations.
Definition Sema.h:12246
void AddConversionCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion=true, bool StrictPackMatch=false)
AddConversionCandidate - Add a C++ conversion function as a candidate in the candidate set (C++ [over...
bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType &ConvertedType)
void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef< Expr * > Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses)
Find the associated classes and namespaces for argument-dependent lookup for a call with the given se...
void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, OverloadCandidateParamOrder PO={})
Add a C++ member function template as a candidate to the candidate set, using template argument deduc...
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
DiagnoseSelfMove - Emits a warning if a value is moved to itself.
bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg)
Compare types for equality with respect to possibly compatible function types (noreturn adjustment,...
void AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false)
Add a C++ function template specialization as a candidate in the candidate set, using template argume...
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:273
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
const LangOptions & getLangOpts() const
Definition Sema.h:933
const FunctionProtoType * ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT)
bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B)
Determine if A and B are equivalent internal linkage declarations from different modules,...
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args={}, DeclContext *LookupCtx=nullptr)
Diagnose an empty lookup.
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, FunctionDecl *DefaultedFn)
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck=false, bool ForceUnprivileged=false)
Checks access for a hierarchy conversion.
bool CheckUseOfCXXMethodAsAddressOfOperand(SourceLocation OpLoc, const Expr *Op, const CXXMethodDecl *MD)
AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, DeclAccessPair FoundDecl)
Perform access-control checking on a previously-unresolved member access which has now been resolved ...
void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddBuiltinOperatorCandidates - Add the appropriate built-in operator overloads to the candidate set (...
void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions=false, bool PartialOverloading=false, bool AllowExplicit=true, bool AllowExplicitConversion=false, ADLCallKind IsADLCandidate=ADLCallKind::NotADL, ConversionSequenceList EarlyConversions={}, OverloadCandidateParamOrder PO={}, bool AggregateCandidateDeduction=false, bool StrictPackMatch=false)
AddOverloadCandidate - Adds the given function to the set of candidate functions, using the given fun...
const LangOptions & LangOpts
Definition Sema.h:1307
bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType)
IsMemberPointerConversion - Determines whether the conversion of the expression From,...
ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef< Expr * > Arg, SourceLocation RParenLoc, Expr *Config=nullptr, bool IsExecConfig=false, ADLCallKind UsesADL=ADLCallKind::NotADL)
BuildResolvedCallExpr - Build a call to a resolved expression, i.e.
ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates)
ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl)
Wrap the expression in a ConstantExpr if it is a potential immediate invocation.
SemaHLSL & HLSL()
Definition Sema.h:1484
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9407
MemberPointerConversionDirection
Definition Sema.h:10328
bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any ArgDependent DiagnoseIfAttr...
ExprResult BuildConvertedConstantExpression(Expr *From, QualType T, CCEKind CCE, NamedDecl *Dest=nullptr)
ReferenceConversionsScope::ReferenceConversions ReferenceConversions
Definition Sema.h:10515
MemberPointerConversionResult CheckMemberPointerConversion(QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind, CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange, bool IgnoreBaseAccess, MemberPointerConversionDirection Direction)
CheckMemberPointerConversion - Check the member pointer conversion from the expression From to the ty...
Expr * BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit)
Build a CXXThisExpr and mark it referenced in the current context.
bool IsOverflowBehaviorTypeConversion(QualType FromType, QualType ToType)
IsOverflowBehaviorTypeConversion - Determines whether the conversion from FromType to ToType necessar...
ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL=true)
Create a unary operation that may resolve to an overloaded operator.
void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading=false)
Add the overload candidates named by callee and/or found by argument dependent lookup to the given ov...
ExprResult DefaultLvalueConversion(Expr *E)
Definition SemaExpr.cpp:645
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition Sema.h:15549
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
bool TemplateParameterListsAreEqual(const Decl *NewInstFrom, TemplateParameterList *New, const Decl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
void NoteOverloadCandidate(const NamedDecl *Found, const FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind=OverloadCandidateRewriteKind(), QualType DestType=QualType(), bool TakingAddress=false)
bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType)
bool DiagnoseUseOfOverloadedDecl(NamedDecl *D, SourceLocation Loc)
Definition Sema.h:7065
void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, ArrayRef< Expr * > Args, ADLResult &Functions)
FunctionDecl * resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult)
Given an expression that refers to an overloaded function, try to resolve that function to a single f...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1447
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
bool IsOverflowBehaviorTypePromotion(QualType FromType, QualType ToType)
IsOverflowBehaviorTypePromotion - Determines whether the conversion from FromType to ToType involves ...
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, SourceLocation Loc={}, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
ExprResult PerformContextuallyConvertToBool(Expr *From)
PerformContextuallyConvertToBool - Perform a contextual conversion of the expression From to bool (C+...
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
Definition Sema.h:8258
ObjCMethodDecl * SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl< ObjCMethodDecl * > &Methods)
FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain=false, DeclAccessPair *Found=nullptr, TemplateSpecCandidateSet *FailedTSC=nullptr, bool ForTypeDeduction=false)
Given an expression that refers to an overloaded function, try to resolve that overloaded function ex...
AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, DeclAccessPair FoundDecl)
void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base=nullptr)
Perform reference-marking and odr-use handling for a DeclRefExpr.
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
EnableIfAttr * CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, ArrayRef< Expr * > Args, bool MissingImplicitThis=false)
Check the enable_if expressions on the given function.
ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, NestedNameSpecifierLoc NNSLoc, DeclarationNameInfo DNI, const UnresolvedSetImpl &Fns, bool PerformADL=true)
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:13985
void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversion=false, OverloadCandidateParamOrder PO={})
AddMethodCandidate - Adds a named decl (which is some kind of method) as a method candidate to the gi...
void diagnoseEquivalentInternalLinkageDeclarations(SourceLocation Loc, const NamedDecl *D, ArrayRef< const NamedDecl * > Equiv)
ExprResult FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn)
FixOverloadedFunctionReference - E is an expression that refers to a C++ overloaded function (possibl...
ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr)
ActOnConditionalOp - Parse a ?
ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S)
Builds an expression which might be an implicit member expression.
bool resolveAndFixAddressOfSingleOverloadCandidate(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false)
Given an overloaded function, tries to turn it into a non-overloaded function reference using resolve...
CallExpr::ADLCallKind ADLCallKind
Definition Sema.h:7562
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
bool anyAltivecTypes(QualType srcType, QualType destType)
bool isLaxVectorConversion(QualType srcType, QualType destType)
Is this a legal conversion between two types, one of which is known to be a vector type?
ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false)
BuildOverloadedCallExpr - Given the call expression that calls Fn (which eventually refers to the dec...
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool isSFINAEContext() const
Definition Sema.h:13718
ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc)
BuildCallToObjectOfClassType - Build a call to an object of class type (C++ [over....
bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind=CompleteTypeKind::Default)
Definition Sema.h:15504
bool CanPerformAggregateInitializationForOverloadResolution(const InitializedEntity &Entity, InitListExpr *From)
Determine whether we can perform aggregate initialization for the purposes of overload resolution.
bool IsOverride(FunctionDecl *MD, FunctionDecl *BaseMD, bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs=true)
bool isStdInitializerList(QualType Ty, QualType *Element)
Tests whether Ty is an instance of std::initializer_list and, if it is and Element is not NULL,...
void AddFunctionCandidates(const UnresolvedSetImpl &Functions, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, bool SuppressUserConversions=false, bool PartialOverloading=false, bool FirstArgumentIsBase=false)
Add all of the function declarations in the given function set to the overload candidate set.
bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess, bool Diagnose=true)
CheckPointerConversion - Check the pointer conversion from the expression From to the type ToType.
void NoteDeletedFunction(FunctionDecl *FD)
Emit a note explaining that this function is deleted.
Definition SemaExpr.cpp:126
ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc)
void NoteAllOverloadCandidates(Expr *E, QualType DestType=QualType(), bool TakingAddress=false)
AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, DeclAccessPair FoundDecl)
void AddNonMemberOperatorCandidates(const UnresolvedSetImpl &Functions, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr)
Add all of the non-member operator function declarations in the given function set to the overload ca...
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6828
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6797
bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD)
CheckCallReturnType - Checks that a call expression's return type is complete.
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, ReferenceConversions *Conv=nullptr)
CompareReferenceRelationship - Compare the two types T1 and T2 to determine whether they are referenc...
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl, NamedDecl *Member)
Cast a base object to a member's actual type.
bool AreConstraintExpressionsEqual(const Decl *Old, const Expr *OldConstr, const Decl *New, const Expr *NewConstr)
MemberPointerConversionResult
Definition Sema.h:10320
SourceManager & SourceMgr
Definition Sema.h:1312
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
DiagnosticsEngine & Diags
Definition Sema.h:1311
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:521
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
bool ResolveAndFixSingleFunctionTemplateSpecialization(ExprResult &SrcExpr, bool DoFunctionPointerConversion=false, bool Complain=false, SourceRange OpRangeForComplaining=SourceRange(), QualType DestTypeForComplaining=QualType(), unsigned DiagIDForComplaining=0)
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
void AddSurrogateCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, const FunctionProtoType *Proto, Expr *Object, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet)
AddSurrogateCandidate - Adds a "surrogate" candidate function that converts the given Object to a fun...
MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs=nullptr)
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
bool IsFunctionConversion(QualType FromType, QualType ToType) const
Determine whether the conversion from FromType to ToType is a valid conversion of ExtInfo/ExtProtoInf...
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(const NamedDecl *D1, ArrayRef< AssociatedConstraint > AC1, const NamedDecl *D2, ArrayRef< AssociatedConstraint > AC2)
If D1 was not at least as constrained as D2, but would've been if a pair of atomic constraints involv...
ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr)
Build a call to 'begin' or 'end' for a C++11 for-range statement.
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
Definition Sema.h:6505
ExprResult InitializeExplicitObjectArgument(Sema &S, Expr *Obj, FunctionDecl *Fun)
bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init)
bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method, SourceLocation CallLoc)
Returns true if the explicit object parameter was invalid.
bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType)
Helper function to determine whether this is the (deprecated) C++ conversion from a string literal to...
void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType)
HandleFunctionTypeMismatch - Gives diagnostic information for differeing function types.
bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< Expr * > Args, SourceLocation RParenLoc, bool ExecConfig=false)
ConvertArgumentsForCall - Converts the arguments specified in Args/NumArgs to the parameter types of ...
DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class)
Look up the constructors for the given class.
FunctionTemplateDecl * getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, QualType RawObj1Ty={}, QualType RawObj2Ty={}, bool Reversed=false, bool PartialOverloading=false)
Returns the more specialized function template according to the rules of function template partial or...
SemaARM & ARM()
Definition Sema.h:1454
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef< Expr * > Args, OverloadCandidateSet &CandidateSet, OverloadCandidateParamOrder PO={})
Add overload candidates for overloaded operators that are member functions.
void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, bool IsDelete, bool CallCanBeVirtual, bool WarnOnNonAbstractTypes, SourceLocation DtorLoc)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8743
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef< const Expr * > Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType)
Handles the checks for format strings, non-POD arguments to vararg functions, NULL arguments passed t...
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
StandardConversionSequence - represents a standard conversion sequence (C++ 13.3.3....
Definition Overload.h:298
void dump() const
dump - Print this standard conversion sequence to standard error.
DeclAccessPair FoundCopyConstructor
Definition Overload.h:392
unsigned BindsToRvalue
Whether we're binding to an rvalue.
Definition Overload.h:357
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition Overload.h:309
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition Overload.h:303
unsigned BindsImplicitObjectArgumentWithoutRefQualifier
Whether this binds an implicit object argument to a non-static member function without a ref-qualifie...
Definition Overload.h:362
unsigned ReferenceBinding
ReferenceBinding - True when this is a reference binding (C++ [over.ics.ref]).
Definition Overload.h:339
void setAsIdentityConversion()
StandardConversionSequence - Set the standard conversion sequence to the identity conversion.
unsigned DeprecatedStringLiteralToCharPtr
Whether this is the deprecated conversion of a string literal to a pointer to non-const character dat...
Definition Overload.h:324
CXXConstructorDecl * CopyConstructor
CopyConstructor - The copy constructor that is used to perform this conversion, when the conversion i...
Definition Overload.h:391
unsigned IncompatibleObjC
IncompatibleObjC - Whether this is an Objective-C conversion that we should warn about (if we actuall...
Definition Overload.h:334
unsigned ObjCLifetimeConversionBinding
Whether this binds a reference to an object with a different Objective-C lifetime qualifier.
Definition Overload.h:367
ImplicitConversionKind Third
Third - The third conversion can be a qualification conversion or a function conversion.
Definition Overload.h:318
unsigned QualificationIncludesObjCLifetime
Whether the qualification conversion involves a change in the Objective-C lifetime (for automatic ref...
Definition Overload.h:329
void setToType(unsigned Idx, QualType T)
Definition Overload.h:396
bool isPointerConversionToBool() const
isPointerConversionToBool - Determines whether this conversion is a conversion of a pointer or pointe...
void * ToTypePtrs[3]
ToType - The types that this conversion is converting to in each step.
Definition Overload.h:384
NarrowingKind getNarrowingKind(ASTContext &Context, const Expr *Converted, APValue &ConstantValue, QualType &ConstantType, bool IgnoreFloatToIntegralConversion=false) const
Check if this standard conversion sequence represents a narrowing conversion, according to C++11 [dcl...
unsigned IsLvalueReference
Whether this is an lvalue reference binding (otherwise, it's an rvalue reference binding).
Definition Overload.h:349
ImplicitConversionKind Dimension
Dimension - Between the second and third conversion a vector or matrix dimension conversion may occur...
Definition Overload.h:314
unsigned BindsToFunctionLvalue
Whether we're binding to a function lvalue.
Definition Overload.h:353
unsigned DirectBinding
DirectBinding - True when this is a reference binding that is a direct binding (C++ [dcl....
Definition Overload.h:344
ImplicitConversionRank getRank() const
getRank - Retrieve the rank of this standard conversion sequence (C++ 13.3.3.1.1p3).
bool isPointerConversionToVoidPointer(ASTContext &Context) const
isPointerConversionToVoidPointer - Determines whether this conversion is a conversion of a pointer to...
unsigned FromBracedInitList
Whether the source expression was originally a single element braced-init-list.
Definition Overload.h:374
QualType getToType(unsigned Idx) const
Definition Overload.h:411
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:355
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1805
StringRef getString() const
Definition Expr.h:1873
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
virtual bool hasInt128Type() const
Determine whether the __int128 type is supported on this target.
Definition TargetInfo.h:679
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition TargetInfo.h:733
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition TargetInfo.h:718
A convenient class for passing around template argument information.
A template argument list.
Represents a template argument.
QualType getNonTypeTemplateArgumentType() const
If this is a non-type template argument, get its type.
QualType getAsType() const
Retrieve the type for a type template argument.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
@ Template
The template argument is a template name that was provided for a template template parameter.
@ Pack
The template argument is actually a parameter pack.
ArgKind getKind() const
Return the kind of stored template argument.
The base class of all kinds of template declarations (e.g., class, function, etc.).
bool isTypeAlias() const
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
NameKind getKind() const
@ Template
A single template declaration.
bool hasAssociatedConstraints() const
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
SmallVector< TemplateSpecCandidate, 16 >::iterator iterator
void NoteCandidates(Sema &S, SourceLocation Loc)
NoteCandidates - When no template specialization match is found, prints diagnostic messages containin...
void clear()
Clear out all of the candidates.
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
Declaration of a template type parameter.
const Type * getTypeForDecl() const
Definition Decl.h:3557
The base class of the type hierarchy.
Definition TypeBase.h:1875
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2545
bool isBlockPointerType() const
Definition TypeBase.h:8704
bool isVoidType() const
Definition TypeBase.h:9050
bool isBooleanType() const
Definition TypeBase.h:9187
bool isObjCBuiltinType() const
Definition TypeBase.h:8914
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2293
bool hasAttr(attr::Kind AK) const
Determine whether this type had the specified attribute applied to it (looking through top-level type...
Definition Type.cpp:2000
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:824
bool isIncompleteArrayType() const
Definition TypeBase.h:8791
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2270
bool isFloat16Type() const
Definition TypeBase.h:9059
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:761
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2177
bool isRValueReferenceType() const
Definition TypeBase.h:8716
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isConstantArrayType() const
Definition TypeBase.h:8787
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9217
bool isArrayType() const
Definition TypeBase.h:8783
bool isCharType() const
Definition Type.cpp:2197
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition TypeBase.h:9122
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2426
bool isPointerType() const
Definition TypeBase.h:8684
bool isArrayParameterType() const
Definition TypeBase.h:8799
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9094
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2671
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9344
bool isReferenceType() const
Definition TypeBase.h:8708
bool isEnumeralType() const
Definition TypeBase.h:8815
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2160
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8884
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9172
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2233
bool isExtVectorBoolType() const
Definition TypeBase.h:8831
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8871
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2854
bool isLValueReferenceType() const
Definition TypeBase.h:8712
bool isBitIntType() const
Definition TypeBase.h:8959
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2846
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2507
bool isAnyComplexType() const
Definition TypeBase.h:8819
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9110
bool isHalfType() const
Definition TypeBase.h:9054
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:9032
bool isQueueT() const
Definition TypeBase.h:8940
bool isMemberPointerType() const
Definition TypeBase.h:8765
bool isOverloadableType() const
Determines whether this is a type for which one can define an overloaded operator.
Definition TypeBase.h:9200
bool isObjCIdType() const
Definition TypeBase.h:8896
bool isMatrixType() const
Definition TypeBase.h:8847
bool isOverflowBehaviorType() const
Definition TypeBase.h:8855
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9193
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2570
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isEventT() const
Definition TypeBase.h:8932
bool isBFloat16Type() const
Definition TypeBase.h:9071
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2531
bool isFunctionType() const
Definition TypeBase.h:8680
bool isObjCObjectPointerType() const
Definition TypeBase.h:8863
bool isVectorType() const
Definition TypeBase.h:8823
bool isObjCClassType() const
Definition TypeBase.h:8902
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2409
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2692
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2985
bool isHLSLAttributedResourceType() const
Definition TypeBase.h:9007
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Definition Type.cpp:2336
bool isAnyPointerType() const
Definition TypeBase.h:8692
TypeClass getTypeClass() const
Definition TypeBase.h:2445
bool isSamplerT() const
Definition TypeBase.h:8928
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:690
bool isNullPtrType() const
Definition TypeBase.h:9087
bool isRecordType() const
Definition TypeBase.h:8811
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2250
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1436
static UnaryOperator * Create(const ASTContext &C, Expr *input, Opcode opc, QualType type, ExprValueKind VK, ExprObjectKind OK, SourceLocation l, bool CanOverflow, FPOptionsOverride FPFeatures)
Definition Expr.cpp:5161
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:1412
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3390
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition ExprCXX.h:3459
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent, bool KnownInstantiationDependent)
Definition ExprCXX.cpp:437
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4126
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition ExprCXX.h:4234
QualType getBaseType() const
Definition ExprCXX.h:4208
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition ExprCXX.h:4218
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition ExprCXX.h:4199
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:4244
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition ExprCXX.h:4238
A set of unresolved declarations.
ArrayRef< DeclAccessPair > pairs() const
void addDecl(NamedDecl *D)
The iterator over UnresolvedSets.
A set of unresolved declarations.
A call to a literal operator (C++11 [over.literal]) written as a user-defined literal (C++11 [lit....
Definition ExprCXX.h:644
static UserDefinedLiteral * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation LitEndLoc, SourceLocation SuffixLoc, FPOptionsOverride FPFeatures)
Definition ExprCXX.cpp:973
QualType getType() const
Definition Decl.h:723
unsigned getNumElements() const
Definition TypeBase.h:4254
QualType getElementType() const
Definition TypeBase.h:4253
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeSugared()
Take ownership of the deduced template argument lists.
TemplateArgument SecondArg
The second template argument to which the template argument deduction failure refers.
TemplateParameter Param
The template parameter to which a template argument deduction failure refers.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
TemplateArgument FirstArg
The first template argument to which the template argument deduction failure refers.
ConstraintSatisfaction AssociatedConstraintsSatisfaction
The constraint satisfaction details resulting from the associated constraints satisfaction tests.
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
unsigned CallArgIndex
The index of the function argument that caused a deduction failure.
specific_attr_iterator - Iterates over a subrange of an AttrVec, only providing attributes that are o...
Defines the clang::TargetInfo interface.
#define UINT_MAX
Definition limits.h:64
Definition SPIR.cpp:47
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
@ Warning
Present this diagnostic as a warning.
@ Error
Present this diagnostic as an error.
PRESERVE_NONE bool Ret(InterpState &S)
Definition Interp.h:271
void checkAssignmentLifetime(Sema &SemaRef, const AssignedEntity &Entity, Expr *Init)
Check that the lifetime of the given expr (and its subobjects) is sufficient for assigning to the ent...
The JSON file list parser is used to communicate input to InstallAPI.
ImplicitConversionRank GetDimensionConversionRank(ImplicitConversionRank Base, ImplicitConversionKind Dimension)
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ OO_None
Not an overloaded operator.
@ NUM_OVERLOADED_OPERATORS
OverloadKind
Definition Sema.h:823
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:834
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:830
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:826
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus14
OverloadingResult
OverloadingResult - Capture the result of performing overload resolution.
Definition Overload.h:50
@ OR_Deleted
Succeeded, but refers to a deleted function.
Definition Overload.h:61
@ OR_Success
Overload resolution succeeded.
Definition Overload.h:52
@ OR_Ambiguous
Ambiguous candidates found.
Definition Overload.h:58
@ OR_No_Viable_Function
No viable function found.
Definition Overload.h:55
CUDAFunctionTarget
Definition Cuda.h:63
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
bool isBetterOverloadCandidate(Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2, SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind, bool PartialOverloading=false)
isBetterOverloadCandidate - Determines whether the first overload candidate is a better candidate tha...
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
OverloadFailureKind
Definition Overload.h:859
@ ovl_fail_final_conversion_not_exact
This conversion function template specialization candidate is not viable because the final conversion...
Definition Overload.h:887
@ ovl_fail_enable_if
This candidate function was not viable because an enable_if attribute disabled it.
Definition Overload.h:896
@ ovl_fail_illegal_constructor
This conversion candidate was not considered because it is an illegal instantiation of a constructor ...
Definition Overload.h:879
@ ovl_fail_bad_final_conversion
This conversion candidate is not viable because its result type is not implicitly convertible to the ...
Definition Overload.h:883
@ ovl_fail_module_mismatched
This candidate was not viable because it has internal linkage and is from a different module unit tha...
Definition Overload.h:924
@ ovl_fail_too_few_arguments
Definition Overload.h:861
@ ovl_fail_addr_not_available
This candidate was not viable because its address could not be taken.
Definition Overload.h:903
@ ovl_fail_too_many_arguments
Definition Overload.h:860
@ ovl_non_default_multiversion_function
This candidate was not viable because it is a non-default multiversioned function.
Definition Overload.h:911
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition Overload.h:920
@ ovl_fail_bad_conversion
Definition Overload.h:862
@ ovl_fail_bad_target
(CUDA) This candidate was not viable because the callee was not accessible from the caller's target (...
Definition Overload.h:892
@ ovl_fail_bad_deduction
Definition Overload.h:863
@ ovl_fail_inhctor_slice
This inherited constructor is not viable because it would slice the argument.
Definition Overload.h:907
@ ovl_fail_object_addrspace_mismatch
This constructor/conversion candidate fail due to an address space mismatch between the object being ...
Definition Overload.h:916
@ ovl_fail_explicit
This candidate constructor or conversion function is explicit but the context doesn't permit explicit...
Definition Overload.h:900
@ ovl_fail_trivial_conversion
This conversion candidate was not considered because it duplicates the work of a trivial or derived-t...
Definition Overload.h:868
@ Comparison
A comparison.
Definition Sema.h:667
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1797
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition TypeBase.h:1800
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1803
ImplicitConversionRank
ImplicitConversionRank - The rank of an implicit conversion kind.
Definition Overload.h:221
@ ICR_Conversion
Conversion.
Definition Overload.h:235
@ ICR_Writeback_Conversion
ObjC ARC writeback conversion.
Definition Overload.h:247
@ ICR_HLSL_Dimension_Reduction
HLSL Matching Dimension Reduction.
Definition Overload.h:257
@ ICR_HLSL_Dimension_Reduction_Conversion
HLSL Dimension reduction with conversion.
Definition Overload.h:263
@ ICR_HLSL_Scalar_Widening
HLSL Scalar Widening.
Definition Overload.h:226
@ ICR_C_Conversion
Conversion only allowed in the C standard (e.g. void* to char*).
Definition Overload.h:250
@ ICR_OCL_Scalar_Widening
OpenCL Scalar Widening.
Definition Overload.h:238
@ ICR_Complex_Real_Conversion
Complex <-> Real conversion.
Definition Overload.h:244
@ ICR_HLSL_Scalar_Widening_Conversion
HLSL Scalar Widening with conversion.
Definition Overload.h:241
@ ICR_HLSL_Dimension_Reduction_Promotion
HLSL Dimension reduction with promotion.
Definition Overload.h:260
@ ICR_Promotion
Promotion.
Definition Overload.h:229
@ ICR_Exact_Match
Exact Match.
Definition Overload.h:223
@ ICR_C_Conversion_Extension
Conversion not allowed by the C standard, but that we accept as an extension anyway.
Definition Overload.h:254
@ ICR_HLSL_Scalar_Widening_Promotion
HLSL Scalar Widening with promotion.
Definition Overload.h:232
OverloadCandidateDisplayKind
Definition Overload.h:64
@ OCD_AmbiguousCandidates
Requests that only tied-for-best candidates be shown.
Definition Overload.h:73
@ OCD_ViableCandidates
Requests that only viable candidates be shown.
Definition Overload.h:70
@ OCD_AllCandidates
Requests that all candidates be shown.
Definition Overload.h:67
@ OK_ObjCProperty
An Objective-C property is a logical field of an Objective-C object which is read and written via Obj...
Definition Specifiers.h:162
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:152
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1048
OverloadCandidateParamOrder
The parameter ordering that will be used for the candidate.
Definition Overload.h:84
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
@ AS_public
Definition Specifiers.h:125
@ AS_none
Definition Specifiers.h:128
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
OverloadsShown
Specifies which overload candidates to display when overload resolution fails.
@ Ovl_Best
Show just the "best" overload candidates.
llvm::MutableArrayRef< ImplicitConversionSequence > ConversionSequenceList
A list of implicit conversion sequences for the arguments of an OverloadCandidate.
Definition Overload.h:929
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
OverloadCandidateRewriteKind
The kinds of rewrite we perform on overload candidates.
Definition Overload.h:89
@ CRK_Reversed
Candidate is a rewritten candidate with a reversed order of parameters.
Definition Overload.h:97
@ CRK_None
Candidate is not a rewritten candidate.
Definition Overload.h:91
@ CRK_DifferentOperator
Candidate is a rewritten candidate with a different operator name.
Definition Overload.h:94
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition Linkage.h:35
@ Result
The result type of a method or function.
Definition TypeBase.h:905
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
OptionalUnsigned< unsigned > UnsignedOrNone
ImplicitConversionKind
ImplicitConversionKind - The kind of implicit conversion used to convert an argument to a parameter's...
Definition Overload.h:104
@ ICK_Complex_Conversion
Complex conversions (C99 6.3.1.6)
Definition Overload.h:139
@ ICK_Floating_Promotion
Floating point promotions (C++ [conv.fpprom])
Definition Overload.h:127
@ ICK_Boolean_Conversion
Boolean conversions (C++ [conv.bool])
Definition Overload.h:151
@ ICK_Integral_Conversion
Integral conversions (C++ [conv.integral])
Definition Overload.h:133
@ ICK_HLSL_Vector_Splat
Definition Overload.h:208
@ ICK_Fixed_Point_Conversion
Fixed point type conversions according to N1169.
Definition Overload.h:196
@ ICK_Vector_Conversion
Vector conversions.
Definition Overload.h:160
@ ICK_Block_Pointer_Conversion
Block Pointer conversions.
Definition Overload.h:175
@ ICK_Pointer_Member
Pointer-to-member conversions (C++ [conv.mem])
Definition Overload.h:148
@ ICK_Floating_Integral
Floating-integral conversions (C++ [conv.fpint])
Definition Overload.h:142
@ ICK_HLSL_Array_RValue
HLSL non-decaying array rvalue cast.
Definition Overload.h:205
@ ICK_SVE_Vector_Conversion
Arm SVE Vector conversions.
Definition Overload.h:163
@ ICK_HLSL_Vector_Truncation
HLSL vector truncation.
Definition Overload.h:199
@ ICK_Incompatible_Pointer_Conversion
C-only conversion between pointers with incompatible types.
Definition Overload.h:193
@ ICK_Array_To_Pointer
Array-to-pointer conversion (C++ [conv.array])
Definition Overload.h:112
@ ICK_RVV_Vector_Conversion
RISC-V RVV Vector conversions.
Definition Overload.h:166
@ ICK_Complex_Promotion
Complex promotions (Clang extension)
Definition Overload.h:130
@ ICK_Num_Conversion_Kinds
The number of conversion kinds.
Definition Overload.h:214
@ ICK_HLSL_Matrix_Splat
HLSL matrix splat from scalar or boolean type.
Definition Overload.h:211
@ ICK_Function_Conversion
Function pointer conversion (C++17 [conv.fctptr])
Definition Overload.h:118
@ ICK_Vector_Splat
A vector splat from an arithmetic type.
Definition Overload.h:169
@ ICK_Zero_Queue_Conversion
Zero constant to queue.
Definition Overload.h:187
@ ICK_Identity
Identity conversion (no conversion)
Definition Overload.h:106
@ ICK_Derived_To_Base
Derived-to-base (C++ [over.best.ics])
Definition Overload.h:157
@ ICK_Lvalue_To_Rvalue
Lvalue-to-rvalue conversion (C++ [conv.lval])
Definition Overload.h:109
@ ICK_Qualification
Qualification conversions (C++ [conv.qual])
Definition Overload.h:121
@ ICK_Pointer_Conversion
Pointer conversions (C++ [conv.ptr])
Definition Overload.h:145
@ ICK_TransparentUnionConversion
Transparent Union Conversions.
Definition Overload.h:178
@ ICK_Integral_Promotion
Integral promotions (C++ [conv.prom])
Definition Overload.h:124
@ ICK_HLSL_Matrix_Truncation
HLSL Matrix truncation.
Definition Overload.h:202
@ ICK_Floating_Conversion
Floating point conversions (C++ [conv.double].
Definition Overload.h:136
@ ICK_Compatible_Conversion
Conversions between compatible types in C99.
Definition Overload.h:154
@ ICK_C_Only_Conversion
Conversions allowed in C, but not C++.
Definition Overload.h:190
@ ICK_Writeback_Conversion
Objective-C ARC writeback conversion.
Definition Overload.h:181
@ ICK_Zero_Event_Conversion
Zero constant to event (OpenCL1.2 6.12.10)
Definition Overload.h:184
@ ICK_Complex_Real
Complex-real conversions (C99 6.3.1.7)
Definition Overload.h:172
@ ICK_Function_To_Pointer
Function-to-pointer (C++ [conv.array])
Definition Overload.h:115
@ Template
We are parsing a template declaration.
Definition Parser.h:81
ActionResult< CXXBaseSpecifier * > BaseResult
Definition Ownership.h:252
AssignConvertType
AssignConvertType - All of the 'assignment' semantic checks return this enum to indicate whether the ...
Definition Sema.h:689
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:712
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:733
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:691
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:729
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
ExprResult ExprError()
Definition Ownership.h:265
@ FunctionTemplate
The name was classified as a function template name.
Definition Sema.h:587
LangAS
Defines the address space values used by the address space qualifier of QualType.
CastKind
CastKind - The kind of operation required for a conversion.
AssignmentAction
Definition Sema.h:216
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:427
OverloadedOperatorKind getRewrittenOverloadedOperator(OverloadedOperatorKind Kind)
Get the other overloaded operator that the given operator can be rewritten into, if any such operator...
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition Specifiers.h:133
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:136
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:145
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:140
bool shouldEnforceArgLimit(bool PartialOverloading, FunctionDecl *Function)
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:147
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
NarrowingKind
NarrowingKind - The kind of narrowing conversion being performed by a standard conversion sequence ac...
Definition Overload.h:274
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition Overload.h:276
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition Overload.h:282
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition Overload.h:290
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition Overload.h:279
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition Overload.h:286
@ TPOC_Conversion
Partial ordering of function templates for a call to a conversion function.
Definition Template.h:310
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition Template.h:306
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1305
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:369
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:419
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:414
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:417
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:390
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:376
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:412
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:421
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:409
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:379
@ Invalid
The declaration was invalid; do nothing.
Definition Sema.h:373
@ Success
Template argument deduction was successful.
Definition Sema.h:371
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:393
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:382
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:396
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:385
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:406
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:423
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:400
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:403
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:201
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:195
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:282
const char * getOperatorSpelling(OverloadedOperatorKind Operator)
Retrieve the spelling of the given overloaded operator, without the preceding "operator" keyword.
U cast(CodeGen::Address addr)
Definition Address.h:327
ConstructorInfo getConstructorInfo(NamedDecl *ND)
Definition Overload.h:1519
@ None
The alignment was not explicit in code.
Definition ASTContext.h:176
CCEKind
Contexts in which a converted constant expression is required.
Definition Sema.h:838
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:841
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:846
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:844
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:842
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:845
ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind)
GetConversionRank - Retrieve the implicit conversion rank corresponding to the given implicit convers...
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5984
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ EST_None
no exception specification
@ ForBuiltinOverloadedOp
A conversion for an operand of a builtin overloaded operator.
Definition Sema.h:448
__DEVICE__ _Tp abs(const std::complex< _Tp > &__c)
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
Represents an ambiguous user-defined conversion sequence.
Definition Overload.h:522
ConversionSet::const_iterator const_iterator
Definition Overload.h:558
SmallVector< std::pair< NamedDecl *, FunctionDecl * >, 4 > ConversionSet
Definition Overload.h:523
void addConversion(NamedDecl *Found, FunctionDecl *D)
Definition Overload.h:549
void copyFrom(const AmbiguousConversionSequence &)
const Expr * ConstraintExpr
Definition Decl.h:88
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:89
QualType getToType() const
Definition Overload.h:607
QualType getFromType() const
Definition Overload.h:606
OverloadFixItKind Kind
The type of fix applied.
unsigned NumConversionsFixed
The number of Conversions fixed.
void setConversionChecker(TypeComparisonFuncTy Foo)
Resets the default conversion checker method.
std::vector< FixItHint > Hints
The list of Hints generated so far.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
void setCXXOperatorNameRange(SourceRange R)
setCXXOperatorNameRange - Sets the range of the operator name (without the operator keyword).
const DeclarationNameLoc & getInfo() const
SourceLocation getCXXLiteralOperatorNameLoc() const
getCXXLiteralOperatorNameLoc - Returns the location of the literal operator name (not the operator ke...
A structure used to record information about a failed template argument deduction,...
void * Data
Opaque pointer containing additional data about this deduction failure.
const TemplateArgument * getSecondArg()
Return the second template argument this deduction failure refers to, if any.
unsigned Result
A Sema::TemplateDeductionResult.
PartialDiagnosticAt * getSFINAEDiagnostic()
Retrieve the diagnostic which caused this deduction failure, if any.
unsigned HasDiagnostic
Indicates whether a diagnostic is stored in Diagnostic.
TemplateDeductionResult getResult() const
void Destroy()
Free any memory associated with this deduction failure.
char Diagnostic[sizeof(PartialDiagnosticAt)]
A diagnostic indicating why deduction failed.
UnsignedOrNone getCallArgIndex()
Return the index of the call argument that this deduction failure refers to, if any.
TemplateParameter getTemplateParameter()
Retrieve the template parameter this deduction failure refers to, if any.
TemplateArgumentList * getTemplateArgumentList()
Retrieve the template argument list associated with this deduction failure, if any.
const TemplateArgument * getFirstArg()
Return the first template argument this deduction failure refers to, if any.
DeferredTemplateOverloadCandidate * Next
Definition Overload.h:1102
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:652
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:654
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Definition Expr.h:640
Extra information about a function prototype.
Definition TypeBase.h:5456
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5461
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition Overload.h:1195
bool allowsReversed(OverloadedOperatorKind Op) const
Determine whether reversing parameter order is allowed for operator Op.
bool shouldAddReversed(Sema &S, ArrayRef< Expr * > OriginalArgs, FunctionDecl *FD) const
Determine whether we should add a rewritten candidate for FD with reversed parameter order.
bool isAcceptableCandidate(const FunctionDecl *FD) const
Definition Overload.h:1217
bool isReversible() const
Determines whether this operator could be implemented by a function with reversed parameter order.
Definition Overload.h:1244
SourceLocation OpLoc
The source location of the operator.
Definition Overload.h:1206
bool AllowRewrittenCandidates
Whether we should include rewritten candidates in the overload set.
Definition Overload.h:1208
OverloadCandidateRewriteKind getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO)
Determine the kind of rewrite that should be performed for this candidate.
Definition Overload.h:1234
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:933
unsigned StrictPackMatch
Have we matched any packs on the parameter side, versus any non-packs on the argument side,...
Definition Overload.h:998
unsigned IgnoreObjectArgument
IgnoreObjectArgument - True to indicate that the first argument's conversion, which for this function...
Definition Overload.h:989
bool TryToFixBadConversion(unsigned Idx, Sema &S)
Definition Overload.h:1063
bool NotValidBecauseConstraintExprHasError() const
bool isReversed() const
Definition Overload.h:1037
unsigned IsADLCandidate
True if the candidate was found using ADL.
Definition Overload.h:1002
unsigned IsSurrogate
IsSurrogate - True to indicate that this candidate is a surrogate for a conversion to a function poin...
Definition Overload.h:979
QualType BuiltinParamTypes[3]
BuiltinParamTypes - Provides the parameter types of a built-in overload candidate.
Definition Overload.h:947
DeclAccessPair FoundDecl
FoundDecl - The original declaration that was looked up / invented / otherwise found,...
Definition Overload.h:943
FunctionDecl * Function
Function - The actual function that this candidate represents.
Definition Overload.h:938
unsigned RewriteKind
Whether this is a rewritten candidate, and if so, of what kind?
Definition Overload.h:1010
ConversionFixItGenerator Fix
The FixIt hints which can be used to fix the Bad candidate.
Definition Overload.h:959
unsigned Best
Whether this candidate is the best viable function, or tied for being the best viable function.
Definition Overload.h:973
StandardConversionSequence FinalConversion
FinalConversion - For a conversion function (where Function is a CXXConversionDecl),...
Definition Overload.h:1028
unsigned getNumParams() const
Definition Overload.h:1076
unsigned HasFinalConversion
Whether FinalConversion has been set.
Definition Overload.h:1006
unsigned TookAddressOfOverload
Definition Overload.h:992
unsigned FailureKind
FailureKind - The reason why this candidate is not viable.
Definition Overload.h:1015
unsigned ExplicitCallArguments
The number of call arguments that were explicitly provided, to be used while performing partial order...
Definition Overload.h:1019
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition Overload.h:956
DeductionFailureInfo DeductionFailure
Definition Overload.h:1022
unsigned Viable
Viable - True to indicate that this overload candidate is viable.
Definition Overload.h:963
CXXConversionDecl * Surrogate
Surrogate - The conversion function for which this candidate is a surrogate, but only if IsSurrogate ...
Definition Overload.h:951
OverloadCandidateRewriteKind getRewriteKind() const
Get RewriteKind value in OverloadCandidateRewriteKind type (This function is to workaround the spurio...
Definition Overload.h:1033
bool SuppressUserConversions
Do not consider any user-defined conversions when constructing the initializing sequence.
Definition Sema.h:10607
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition Sema.h:10614
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13147
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13232
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13278
Abstract class used to diagnose incomplete types.
Definition Sema.h:8339
A std::pair-like structure for storing a qualified type split into its local qualifiers and its local...
Definition TypeBase.h:870
const Type * Ty
The locally-unqualified type.
Definition TypeBase.h:872
Qualifiers Quals
The local qualifiers.
Definition TypeBase.h:875
TemplateSpecCandidate - This is a generalization of OverloadCandidate which keeps track of template a...
void NoteDeductionFailure(Sema &S, bool ForTakingAddress)
Diagnose a template argument deduction failure.
DeductionFailureInfo DeductionFailure
Template argument deduction info.
Decl * Specialization
Specialization - The actual specialization that this candidate represents.
DeclAccessPair FoundDecl
The declaration that was looked up, together with its access.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
UserDefinedConversionSequence - Represents a user-defined conversion sequence (C++ 13....
Definition Overload.h:477
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition Overload.h:489
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition Overload.h:511
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition Overload.h:502
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition Overload.h:506
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition Overload.h:497
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition Overload.h:516
void dump() const
dump - Print this user-defined conversion sequence to standard error.
Describes an entity that is being assigned.