clang 22.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"
33#include "clang/Sema/SemaARM.h"
34#include "clang/Sema/SemaCUDA.h"
35#include "clang/Sema/SemaObjC.h"
36#include "clang/Sema/Template.h"
38#include "llvm/ADT/DenseSet.h"
39#include "llvm/ADT/STLExtras.h"
40#include "llvm/ADT/STLForwardCompat.h"
41#include "llvm/ADT/ScopeExit.h"
42#include "llvm/ADT/SmallPtrSet.h"
43#include "llvm/ADT/SmallVector.h"
44#include <algorithm>
45#include <cassert>
46#include <cstddef>
47#include <cstdlib>
48#include <optional>
49
50using namespace clang;
51using namespace sema;
52
54
56 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
57 return P->hasAttr<PassObjectSizeAttr>();
58 });
59}
60
61/// A convenience routine for creating a decayed reference to a function.
63 Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl, const Expr *Base,
64 bool HadMultipleCandidates, SourceLocation Loc = SourceLocation(),
65 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()) {
66 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
67 return ExprError();
68 // If FoundDecl is different from Fn (such as if one is a template
69 // and the other a specialization), make sure DiagnoseUseOfDecl is
70 // called on both.
71 // FIXME: This would be more comprehensively addressed by modifying
72 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
73 // being used.
74 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
75 return ExprError();
76 DeclRefExpr *DRE = new (S.Context)
77 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
78 if (HadMultipleCandidates)
79 DRE->setHadMultipleCandidates(true);
80
82 if (auto *FPT = DRE->getType()->getAs<FunctionProtoType>()) {
83 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
84 S.ResolveExceptionSpec(Loc, FPT);
85 DRE->setType(Fn->getType());
86 }
87 }
88 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
89 CK_FunctionToPointerDecay);
90}
91
92static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
93 bool InOverloadResolution,
95 bool CStyle,
96 bool AllowObjCWritebackConversion);
97
99 QualType &ToType,
100 bool InOverloadResolution,
102 bool CStyle);
104IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
106 OverloadCandidateSet& Conversions,
107 AllowedExplicit AllowExplicit,
108 bool AllowObjCConversionOnExplicit);
109
112 const StandardConversionSequence& SCS1,
113 const StandardConversionSequence& SCS2);
114
117 const StandardConversionSequence& SCS1,
118 const StandardConversionSequence& SCS2);
119
122 const StandardConversionSequence& SCS1,
123 const StandardConversionSequence& SCS2);
124
125/// GetConversionRank - Retrieve the implicit conversion rank
126/// corresponding to the given implicit conversion kind.
128 static const ImplicitConversionRank Rank[] = {
155 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
156 // it was omitted by the patch that added
157 // ICK_Zero_Event_Conversion
158 ICR_Exact_Match, // NOTE(ctopper): This may not be completely right --
159 // it was omitted by the patch that added
160 // ICK_Zero_Queue_Conversion
167 };
168 static_assert(std::size(Rank) == (int)ICK_Num_Conversion_Kinds);
169 return Rank[(int)Kind];
170}
171
190
191/// GetImplicitConversionName - Return the name of this kind of
192/// implicit conversion.
194 static const char *const Name[] = {
195 "No conversion",
196 "Lvalue-to-rvalue",
197 "Array-to-pointer",
198 "Function-to-pointer",
199 "Function pointer conversion",
200 "Qualification",
201 "Integral promotion",
202 "Floating point promotion",
203 "Complex promotion",
204 "Integral conversion",
205 "Floating conversion",
206 "Complex conversion",
207 "Floating-integral conversion",
208 "Pointer conversion",
209 "Pointer-to-member conversion",
210 "Boolean conversion",
211 "Compatible-types conversion",
212 "Derived-to-base conversion",
213 "Vector conversion",
214 "SVE Vector conversion",
215 "RVV Vector conversion",
216 "Vector splat",
217 "Complex-real conversion",
218 "Block Pointer conversion",
219 "Transparent Union Conversion",
220 "Writeback conversion",
221 "OpenCL Zero Event Conversion",
222 "OpenCL Zero Queue Conversion",
223 "C specific type conversion",
224 "Incompatible pointer conversion",
225 "Fixed point conversion",
226 "HLSL vector truncation",
227 "Non-decaying array conversion",
228 "HLSL vector splat",
229 };
230 static_assert(std::size(Name) == (int)ICK_Num_Conversion_Kinds);
231 return Name[Kind];
232}
233
234/// StandardConversionSequence - Set the standard conversion
235/// sequence to the identity conversion.
253
254/// getRank - Retrieve the rank of this standard conversion sequence
255/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
256/// implicit conversions.
269
270/// isPointerConversionToBool - Determines whether this conversion is
271/// a conversion of a pointer or pointer-to-member to bool. This is
272/// used as part of the ranking of standard conversion sequences
273/// (C++ 13.3.3.2p4).
275 // Note that FromType has not necessarily been transformed by the
276 // array-to-pointer or function-to-pointer implicit conversions, so
277 // check for their presence as well as checking whether FromType is
278 // a pointer.
279 if (getToType(1)->isBooleanType() &&
280 (getFromType()->isPointerType() ||
281 getFromType()->isMemberPointerType() ||
282 getFromType()->isObjCObjectPointerType() ||
283 getFromType()->isBlockPointerType() ||
285 return true;
286
287 return false;
288}
289
290/// isPointerConversionToVoidPointer - Determines whether this
291/// conversion is a conversion of a pointer to a void pointer. This is
292/// used as part of the ranking of standard conversion sequences (C++
293/// 13.3.3.2p4).
294bool
297 QualType FromType = getFromType();
298 QualType ToType = getToType(1);
299
300 // Note that FromType has not necessarily been transformed by the
301 // array-to-pointer implicit conversion, so check for its presence
302 // and redo the conversion to get a pointer.
304 FromType = Context.getArrayDecayedType(FromType);
305
306 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
307 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
308 return ToPtrType->getPointeeType()->isVoidType();
309
310 return false;
311}
312
313/// Skip any implicit casts which could be either part of a narrowing conversion
314/// or after one in an implicit conversion.
316 const Expr *Converted) {
317 // We can have cleanups wrapping the converted expression; these need to be
318 // preserved so that destructors run if necessary.
319 if (auto *EWC = dyn_cast<ExprWithCleanups>(Converted)) {
320 Expr *Inner =
321 const_cast<Expr *>(IgnoreNarrowingConversion(Ctx, EWC->getSubExpr()));
322 return ExprWithCleanups::Create(Ctx, Inner, EWC->cleanupsHaveSideEffects(),
323 EWC->getObjects());
324 }
325
326 while (auto *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
327 switch (ICE->getCastKind()) {
328 case CK_NoOp:
329 case CK_IntegralCast:
330 case CK_IntegralToBoolean:
331 case CK_IntegralToFloating:
332 case CK_BooleanToSignedIntegral:
333 case CK_FloatingToIntegral:
334 case CK_FloatingToBoolean:
335 case CK_FloatingCast:
336 Converted = ICE->getSubExpr();
337 continue;
338
339 default:
340 return Converted;
341 }
342 }
343
344 return Converted;
345}
346
347/// Check if this standard conversion sequence represents a narrowing
348/// conversion, according to C++11 [dcl.init.list]p7.
349///
350/// \param Ctx The AST context.
351/// \param Converted The result of applying this standard conversion sequence.
352/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
353/// value of the expression prior to the narrowing conversion.
354/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
355/// type of the expression prior to the narrowing conversion.
356/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
357/// from floating point types to integral types should be ignored.
359 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
360 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
361 assert((Ctx.getLangOpts().CPlusPlus || Ctx.getLangOpts().C23) &&
362 "narrowing check outside C++");
363
364 // C++11 [dcl.init.list]p7:
365 // A narrowing conversion is an implicit conversion ...
366 QualType FromType = getToType(0);
367 QualType ToType = getToType(1);
368
369 // A conversion to an enumeration type is narrowing if the conversion to
370 // the underlying type is narrowing. This only arises for expressions of
371 // the form 'Enum{init}'.
372 if (const auto *ED = ToType->getAsEnumDecl())
373 ToType = ED->getIntegerType();
374
375 switch (Second) {
376 // 'bool' is an integral type; dispatch to the right place to handle it.
378 if (FromType->isRealFloatingType())
379 goto FloatingIntegralConversion;
381 goto IntegralConversion;
382 // -- from a pointer type or pointer-to-member type to bool, or
383 return NK_Type_Narrowing;
384
385 // -- from a floating-point type to an integer type, or
386 //
387 // -- from an integer type or unscoped enumeration type to a floating-point
388 // type, except where the source is a constant expression and the actual
389 // value after conversion will fit into the target type and will produce
390 // the original value when converted back to the original type, or
392 FloatingIntegralConversion:
393 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
394 return NK_Type_Narrowing;
395 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
396 ToType->isRealFloatingType()) {
397 if (IgnoreFloatToIntegralConversion)
398 return NK_Not_Narrowing;
399 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
400 assert(Initializer && "Unknown conversion expression");
401
402 // If it's value-dependent, we can't tell whether it's narrowing.
403 if (Initializer->isValueDependent())
405
406 if (std::optional<llvm::APSInt> IntConstantValue =
407 Initializer->getIntegerConstantExpr(Ctx)) {
408 // Convert the integer to the floating type.
409 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
410 Result.convertFromAPInt(*IntConstantValue, IntConstantValue->isSigned(),
411 llvm::APFloat::rmNearestTiesToEven);
412 // And back.
413 llvm::APSInt ConvertedValue = *IntConstantValue;
414 bool ignored;
415 llvm::APFloat::opStatus Status = Result.convertToInteger(
416 ConvertedValue, llvm::APFloat::rmTowardZero, &ignored);
417 // If the converted-back integer has unspecified value, or if the
418 // resulting value is different, this was a narrowing conversion.
419 if (Status == llvm::APFloat::opInvalidOp ||
420 *IntConstantValue != ConvertedValue) {
421 ConstantValue = APValue(*IntConstantValue);
422 ConstantType = Initializer->getType();
424 }
425 } else {
426 // Variables are always narrowings.
428 }
429 }
430 return NK_Not_Narrowing;
431
432 // -- from long double to double or float, or from double to float, except
433 // where the source is a constant expression and the actual value after
434 // conversion is within the range of values that can be represented (even
435 // if it cannot be represented exactly), or
437 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
438 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
439 // FromType is larger than ToType.
440 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
441
442 // If it's value-dependent, we can't tell whether it's narrowing.
443 if (Initializer->isValueDependent())
445
447 if ((Ctx.getLangOpts().C23 && Initializer->EvaluateAsRValue(R, Ctx)) ||
448 Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
449 // Constant!
450 if (Ctx.getLangOpts().C23)
451 ConstantValue = R.Val;
452 assert(ConstantValue.isFloat());
453 llvm::APFloat FloatVal = ConstantValue.getFloat();
454 // Convert the source value into the target type.
455 bool ignored;
456 llvm::APFloat Converted = FloatVal;
457 llvm::APFloat::opStatus ConvertStatus =
458 Converted.convert(Ctx.getFloatTypeSemantics(ToType),
459 llvm::APFloat::rmNearestTiesToEven, &ignored);
460 Converted.convert(Ctx.getFloatTypeSemantics(FromType),
461 llvm::APFloat::rmNearestTiesToEven, &ignored);
462 if (Ctx.getLangOpts().C23) {
463 if (FloatVal.isNaN() && Converted.isNaN() &&
464 !FloatVal.isSignaling() && !Converted.isSignaling()) {
465 // Quiet NaNs are considered the same value, regardless of
466 // payloads.
467 return NK_Not_Narrowing;
468 }
469 // For normal values, check exact equality.
470 if (!Converted.bitwiseIsEqual(FloatVal)) {
471 ConstantType = Initializer->getType();
473 }
474 } else {
475 // If there was no overflow, the source value is within the range of
476 // values that can be represented.
477 if (ConvertStatus & llvm::APFloat::opOverflow) {
478 ConstantType = Initializer->getType();
480 }
481 }
482 } else {
484 }
485 }
486 return NK_Not_Narrowing;
487
488 // -- from an integer type or unscoped enumeration type to an integer type
489 // that cannot represent all the values of the original type, except where
490 // (CWG2627) -- the source is a bit-field whose width w is less than that
491 // of its type (or, for an enumeration type, its underlying type) and the
492 // target type can represent all the values of a hypothetical extended
493 // integer type with width w and with the same signedness as the original
494 // type or
495 // -- the source is a constant expression and the actual value after
496 // conversion will fit into the target type and will produce the original
497 // value when converted back to the original type.
499 IntegralConversion: {
500 assert(FromType->isIntegralOrUnscopedEnumerationType());
501 assert(ToType->isIntegralOrUnscopedEnumerationType());
502 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
503 unsigned FromWidth = Ctx.getIntWidth(FromType);
504 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
505 const unsigned ToWidth = Ctx.getIntWidth(ToType);
506
507 constexpr auto CanRepresentAll = [](bool FromSigned, unsigned FromWidth,
508 bool ToSigned, unsigned ToWidth) {
509 return (FromWidth < ToWidth + (FromSigned == ToSigned)) &&
510 !(FromSigned && !ToSigned);
511 };
512
513 if (CanRepresentAll(FromSigned, FromWidth, ToSigned, ToWidth))
514 return NK_Not_Narrowing;
515
516 // Not all values of FromType can be represented in ToType.
517 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
518
519 bool DependentBitField = false;
520 if (const FieldDecl *BitField = Initializer->getSourceBitField()) {
521 if (BitField->getBitWidth()->isValueDependent())
522 DependentBitField = true;
523 else if (unsigned BitFieldWidth = BitField->getBitWidthValue();
524 BitFieldWidth < FromWidth) {
525 if (CanRepresentAll(FromSigned, BitFieldWidth, ToSigned, ToWidth))
526 return NK_Not_Narrowing;
527
528 // The initializer will be truncated to the bit-field width
529 FromWidth = BitFieldWidth;
530 }
531 }
532
533 // If it's value-dependent, we can't tell whether it's narrowing.
534 if (Initializer->isValueDependent())
536
537 std::optional<llvm::APSInt> OptInitializerValue =
538 Initializer->getIntegerConstantExpr(Ctx);
539 if (!OptInitializerValue) {
540 // If the bit-field width was dependent, it might end up being small
541 // enough to fit in the target type (unless the target type is unsigned
542 // and the source type is signed, in which case it will never fit)
543 if (DependentBitField && !(FromSigned && !ToSigned))
545
546 // Otherwise, such a conversion is always narrowing
548 }
549 llvm::APSInt &InitializerValue = *OptInitializerValue;
550 bool Narrowing = false;
551 if (FromWidth < ToWidth) {
552 // Negative -> unsigned is narrowing. Otherwise, more bits is never
553 // narrowing.
554 if (InitializerValue.isSigned() && InitializerValue.isNegative())
555 Narrowing = true;
556 } else {
557 // Add a bit to the InitializerValue so we don't have to worry about
558 // signed vs. unsigned comparisons.
559 InitializerValue =
560 InitializerValue.extend(InitializerValue.getBitWidth() + 1);
561 // Convert the initializer to and from the target width and signed-ness.
562 llvm::APSInt ConvertedValue = InitializerValue;
563 ConvertedValue = ConvertedValue.trunc(ToWidth);
564 ConvertedValue.setIsSigned(ToSigned);
565 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
566 ConvertedValue.setIsSigned(InitializerValue.isSigned());
567 // If the result is different, this was a narrowing conversion.
568 if (ConvertedValue != InitializerValue)
569 Narrowing = true;
570 }
571 if (Narrowing) {
572 ConstantType = Initializer->getType();
573 ConstantValue = APValue(InitializerValue);
575 }
576
577 return NK_Not_Narrowing;
578 }
579 case ICK_Complex_Real:
580 if (FromType->isComplexType() && !ToType->isComplexType())
581 return NK_Type_Narrowing;
582 return NK_Not_Narrowing;
583
585 if (Ctx.getLangOpts().C23) {
586 const Expr *Initializer = IgnoreNarrowingConversion(Ctx, Converted);
588 if (Initializer->EvaluateAsRValue(R, Ctx)) {
589 ConstantValue = R.Val;
590 assert(ConstantValue.isFloat());
591 llvm::APFloat FloatVal = ConstantValue.getFloat();
592 // C23 6.7.3p6 If the initializer has real type and a signaling NaN
593 // value, the unqualified versions of the type of the initializer and
594 // the corresponding real type of the object declared shall be
595 // compatible.
596 if (FloatVal.isNaN() && FloatVal.isSignaling()) {
597 ConstantType = Initializer->getType();
599 }
600 }
601 }
602 return NK_Not_Narrowing;
603 default:
604 // Other kinds of conversions are not narrowings.
605 return NK_Not_Narrowing;
606 }
607}
608
609/// dump - Print this standard conversion sequence to standard
610/// error. Useful for debugging overloading issues.
611LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
612 raw_ostream &OS = llvm::errs();
613 bool PrintedSomething = false;
614 if (First != ICK_Identity) {
616 PrintedSomething = true;
617 }
618
619 if (Second != ICK_Identity) {
620 if (PrintedSomething) {
621 OS << " -> ";
622 }
624
625 if (CopyConstructor) {
626 OS << " (by copy constructor)";
627 } else if (DirectBinding) {
628 OS << " (direct reference binding)";
629 } else if (ReferenceBinding) {
630 OS << " (reference binding)";
631 }
632 PrintedSomething = true;
633 }
634
635 if (Third != ICK_Identity) {
636 if (PrintedSomething) {
637 OS << " -> ";
638 }
640 PrintedSomething = true;
641 }
642
643 if (!PrintedSomething) {
644 OS << "No conversions required";
645 }
646}
647
648/// dump - Print this user-defined conversion sequence to standard
649/// error. Useful for debugging overloading issues.
651 raw_ostream &OS = llvm::errs();
652 if (Before.First || Before.Second || Before.Third) {
653 Before.dump();
654 OS << " -> ";
655 }
657 OS << '\'' << *ConversionFunction << '\'';
658 else
659 OS << "aggregate initialization";
660 if (After.First || After.Second || After.Third) {
661 OS << " -> ";
662 After.dump();
663 }
664}
665
666/// dump - Print this implicit conversion sequence to standard
667/// error. Useful for debugging overloading issues.
669 raw_ostream &OS = llvm::errs();
671 OS << "Worst list element conversion: ";
672 switch (ConversionKind) {
674 OS << "Standard conversion: ";
675 Standard.dump();
676 break;
678 OS << "User-defined conversion: ";
679 UserDefined.dump();
680 break;
682 OS << "Ellipsis conversion";
683 break;
685 OS << "Ambiguous conversion";
686 break;
687 case BadConversion:
688 OS << "Bad conversion";
689 break;
690 }
691
692 OS << "\n";
693}
694
698
700 conversions().~ConversionSet();
701}
702
703void
709
710namespace {
711 // Structure used by DeductionFailureInfo to store
712 // template argument information.
713 struct DFIArguments {
714 TemplateArgument FirstArg;
715 TemplateArgument SecondArg;
716 };
717 // Structure used by DeductionFailureInfo to store
718 // template parameter and template argument information.
719 struct DFIParamWithArguments : DFIArguments {
720 TemplateParameter Param;
721 };
722 // Structure used by DeductionFailureInfo to store template argument
723 // information and the index of the problematic call argument.
724 struct DFIDeducedMismatchArgs : DFIArguments {
725 TemplateArgumentList *TemplateArgs;
726 unsigned CallArgIndex;
727 };
728 // Structure used by DeductionFailureInfo to store information about
729 // unsatisfied constraints.
730 struct CNSInfo {
731 TemplateArgumentList *TemplateArgs;
732 ConstraintSatisfaction Satisfaction;
733 };
734}
735
736/// Convert from Sema's representation of template deduction information
737/// to the form used in overload-candidate information.
741 TemplateDeductionInfo &Info) {
743 Result.Result = static_cast<unsigned>(TDK);
744 Result.HasDiagnostic = false;
745 switch (TDK) {
752 Result.Data = nullptr;
753 break;
754
757 Result.Data = Info.Param.getOpaqueValue();
758 break;
759
762 // FIXME: Should allocate from normal heap so that we can free this later.
763 auto *Saved = new (Context) DFIDeducedMismatchArgs;
764 Saved->FirstArg = Info.FirstArg;
765 Saved->SecondArg = Info.SecondArg;
766 Saved->TemplateArgs = Info.takeSugared();
767 Saved->CallArgIndex = Info.CallArgIndex;
768 Result.Data = Saved;
769 break;
770 }
771
773 // FIXME: Should allocate from normal heap so that we can free this later.
774 DFIArguments *Saved = new (Context) DFIArguments;
775 Saved->FirstArg = Info.FirstArg;
776 Saved->SecondArg = Info.SecondArg;
777 Result.Data = Saved;
778 break;
779 }
780
782 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
785 // FIXME: Should allocate from normal heap so that we can free this later.
786 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
787 Saved->Param = Info.Param;
788 Saved->FirstArg = Info.FirstArg;
789 Saved->SecondArg = Info.SecondArg;
790 Result.Data = Saved;
791 break;
792 }
793
795 Result.Data = Info.takeSugared();
796 if (Info.hasSFINAEDiagnostic()) {
800 Result.HasDiagnostic = true;
801 }
802 break;
803
805 CNSInfo *Saved = new (Context) CNSInfo;
806 Saved->TemplateArgs = Info.takeSugared();
807 Saved->Satisfaction = Info.AssociatedConstraintsSatisfaction;
808 Result.Data = Saved;
809 break;
810 }
811
815 llvm_unreachable("not a deduction failure");
816 }
817
818 return Result;
819}
820
822 switch (static_cast<TemplateDeductionResult>(Result)) {
832 break;
833
840 // FIXME: Destroy the data?
841 Data = nullptr;
842 break;
843
845 // FIXME: Destroy the template argument list?
846 Data = nullptr;
848 Diag->~PartialDiagnosticAt();
849 HasDiagnostic = false;
850 }
851 break;
852
854 // FIXME: Destroy the template argument list?
855 Data = nullptr;
857 Diag->~PartialDiagnosticAt();
858 HasDiagnostic = false;
859 }
860 break;
861
862 // Unhandled
865 break;
866 }
867}
868
870 if (HasDiagnostic)
871 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
872 return nullptr;
873}
874
908
944
976
1008
1010 switch (static_cast<TemplateDeductionResult>(Result)) {
1013 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
1014
1015 default:
1016 return std::nullopt;
1017 }
1018}
1019
1021 const FunctionDecl *Y) {
1022 if (!X || !Y)
1023 return false;
1024 if (X->getNumParams() != Y->getNumParams())
1025 return false;
1026 // FIXME: when do rewritten comparison operators
1027 // with explicit object parameters correspond?
1028 // https://cplusplus.github.io/CWG/issues/2797.html
1029 for (unsigned I = 0; I < X->getNumParams(); ++I)
1030 if (!Ctx.hasSameUnqualifiedType(X->getParamDecl(I)->getType(),
1031 Y->getParamDecl(I)->getType()))
1032 return false;
1033 if (auto *FTX = X->getDescribedFunctionTemplate()) {
1034 auto *FTY = Y->getDescribedFunctionTemplate();
1035 if (!FTY)
1036 return false;
1037 if (!Ctx.isSameTemplateParameterList(FTX->getTemplateParameters(),
1038 FTY->getTemplateParameters()))
1039 return false;
1040 }
1041 return true;
1042}
1043
1045 Expr *FirstOperand, FunctionDecl *EqFD) {
1046 assert(EqFD->getOverloadedOperator() ==
1047 OverloadedOperatorKind::OO_EqualEqual);
1048 // C++2a [over.match.oper]p4:
1049 // A non-template function or function template F named operator== is a
1050 // rewrite target with first operand o unless a search for the name operator!=
1051 // in the scope S from the instantiation context of the operator expression
1052 // finds a function or function template that would correspond
1053 // ([basic.scope.scope]) to F if its name were operator==, where S is the
1054 // scope of the class type of o if F is a class member, and the namespace
1055 // scope of which F is a member otherwise. A function template specialization
1056 // named operator== is a rewrite target if its function template is a rewrite
1057 // target.
1059 OverloadedOperatorKind::OO_ExclaimEqual);
1060 if (isa<CXXMethodDecl>(EqFD)) {
1061 // If F is a class member, search scope is class type of first operand.
1062 QualType RHS = FirstOperand->getType();
1063 auto *RHSRec = RHS->getAsCXXRecordDecl();
1064 if (!RHSRec)
1065 return true;
1066 LookupResult Members(S, NotEqOp, OpLoc,
1068 S.LookupQualifiedName(Members, RHSRec);
1069 Members.suppressAccessDiagnostics();
1070 for (NamedDecl *Op : Members)
1071 if (FunctionsCorrespond(S.Context, EqFD, Op->getAsFunction()))
1072 return false;
1073 return true;
1074 }
1075 // Otherwise the search scope is the namespace scope of which F is a member.
1076 for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
1077 auto *NotEqFD = Op->getAsFunction();
1078 if (auto *UD = dyn_cast<UsingShadowDecl>(Op))
1079 NotEqFD = UD->getUnderlyingDecl()->getAsFunction();
1080 if (FunctionsCorrespond(S.Context, EqFD, NotEqFD) && S.isVisible(NotEqFD) &&
1082 cast<Decl>(Op->getLexicalDeclContext())))
1083 return false;
1084 }
1085 return true;
1086}
1087
1091 return false;
1092 return Op == OO_EqualEqual || Op == OO_Spaceship;
1093}
1094
1096 Sema &S, ArrayRef<Expr *> OriginalArgs, FunctionDecl *FD) {
1097 auto Op = FD->getOverloadedOperator();
1098 if (!allowsReversed(Op))
1099 return false;
1100 if (Op == OverloadedOperatorKind::OO_EqualEqual) {
1101 assert(OriginalArgs.size() == 2);
1103 S, OpLoc, /*FirstOperand in reversed args*/ OriginalArgs[1], FD))
1104 return false;
1105 }
1106 // Don't bother adding a reversed candidate that can never be a better
1107 // match than the non-reversed version.
1108 return FD->getNumNonObjectParams() != 2 ||
1110 FD->getParamDecl(1)->getType()) ||
1111 FD->hasAttr<EnableIfAttr>();
1112}
1113
1114void OverloadCandidateSet::destroyCandidates() {
1115 for (iterator i = Candidates.begin(), e = Candidates.end(); i != e; ++i) {
1116 for (auto &C : i->Conversions)
1117 C.~ImplicitConversionSequence();
1118 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
1119 i->DeductionFailure.Destroy();
1120 }
1121}
1122
1124 destroyCandidates();
1125 SlabAllocator.Reset();
1126 NumInlineBytesUsed = 0;
1127 Candidates.clear();
1128 Functions.clear();
1129 Kind = CSK;
1130 FirstDeferredCandidate = nullptr;
1131 DeferredCandidatesCount = 0;
1132 HasDeferredTemplateConstructors = false;
1133 ResolutionByPerfectCandidateIsDisabled = false;
1134}
1135
1136namespace {
1137 class UnbridgedCastsSet {
1138 struct Entry {
1139 Expr **Addr;
1140 Expr *Saved;
1141 };
1142 SmallVector<Entry, 2> Entries;
1143
1144 public:
1145 void save(Sema &S, Expr *&E) {
1146 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
1147 Entry entry = { &E, E };
1148 Entries.push_back(entry);
1149 E = S.ObjC().stripARCUnbridgedCast(E);
1150 }
1151
1152 void restore() {
1153 for (SmallVectorImpl<Entry>::iterator
1154 i = Entries.begin(), e = Entries.end(); i != e; ++i)
1155 *i->Addr = i->Saved;
1156 }
1157 };
1158}
1159
1160/// checkPlaceholderForOverload - Do any interesting placeholder-like
1161/// preprocessing on the given expression.
1162///
1163/// \param unbridgedCasts a collection to which to add unbridged casts;
1164/// without this, they will be immediately diagnosed as errors
1165///
1166/// Return true on unrecoverable error.
1167static bool
1169 UnbridgedCastsSet *unbridgedCasts = nullptr) {
1170 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
1171 // We can't handle overloaded expressions here because overload
1172 // resolution might reasonably tweak them.
1173 if (placeholder->getKind() == BuiltinType::Overload) return false;
1174
1175 // If the context potentially accepts unbridged ARC casts, strip
1176 // the unbridged cast and add it to the collection for later restoration.
1177 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
1178 unbridgedCasts) {
1179 unbridgedCasts->save(S, E);
1180 return false;
1181 }
1182
1183 // Go ahead and check everything else.
1184 ExprResult result = S.CheckPlaceholderExpr(E);
1185 if (result.isInvalid())
1186 return true;
1187
1188 E = result.get();
1189 return false;
1190 }
1191
1192 // Nothing to do.
1193 return false;
1194}
1195
1196/// checkArgPlaceholdersForOverload - Check a set of call operands for
1197/// placeholders.
1199 UnbridgedCastsSet &unbridged) {
1200 for (unsigned i = 0, e = Args.size(); i != e; ++i)
1201 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
1202 return true;
1203
1204 return false;
1205}
1206
1208 const LookupResult &Old, NamedDecl *&Match,
1209 bool NewIsUsingDecl) {
1210 for (LookupResult::iterator I = Old.begin(), E = Old.end();
1211 I != E; ++I) {
1212 NamedDecl *OldD = *I;
1213
1214 bool OldIsUsingDecl = false;
1215 if (isa<UsingShadowDecl>(OldD)) {
1216 OldIsUsingDecl = true;
1217
1218 // We can always introduce two using declarations into the same
1219 // context, even if they have identical signatures.
1220 if (NewIsUsingDecl) continue;
1221
1222 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
1223 }
1224
1225 // A using-declaration does not conflict with another declaration
1226 // if one of them is hidden.
1227 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
1228 continue;
1229
1230 // If either declaration was introduced by a using declaration,
1231 // we'll need to use slightly different rules for matching.
1232 // Essentially, these rules are the normal rules, except that
1233 // function templates hide function templates with different
1234 // return types or template parameter lists.
1235 bool UseMemberUsingDeclRules =
1236 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
1237 !New->getFriendObjectKind();
1238
1239 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1240 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1241 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1243 continue;
1244 }
1245
1246 if (!isa<FunctionTemplateDecl>(OldD) &&
1247 !shouldLinkPossiblyHiddenDecl(*I, New))
1248 continue;
1249
1250 Match = *I;
1251 return OverloadKind::Match;
1252 }
1253
1254 // Builtins that have custom typechecking or have a reference should
1255 // not be overloadable or redeclarable.
1256 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1257 Match = *I;
1259 }
1260 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1261 // We can overload with these, which can show up when doing
1262 // redeclaration checks for UsingDecls.
1263 assert(Old.getLookupKind() == LookupUsingDeclName);
1264 } else if (isa<TagDecl>(OldD)) {
1265 // We can always overload with tags by hiding them.
1266 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1267 // Optimistically assume that an unresolved using decl will
1268 // overload; if it doesn't, we'll have to diagnose during
1269 // template instantiation.
1270 //
1271 // Exception: if the scope is dependent and this is not a class
1272 // member, the using declaration can only introduce an enumerator.
1273 if (UUD->getQualifier().isDependent() && !UUD->isCXXClassMember()) {
1274 Match = *I;
1276 }
1277 } else {
1278 // (C++ 13p1):
1279 // Only function declarations can be overloaded; object and type
1280 // declarations cannot be overloaded.
1281 Match = *I;
1283 }
1284 }
1285
1286 // C++ [temp.friend]p1:
1287 // For a friend function declaration that is not a template declaration:
1288 // -- if the name of the friend is a qualified or unqualified template-id,
1289 // [...], otherwise
1290 // -- if the name of the friend is a qualified-id and a matching
1291 // non-template function is found in the specified class or namespace,
1292 // the friend declaration refers to that function, otherwise,
1293 // -- if the name of the friend is a qualified-id and a matching function
1294 // template is found in the specified class or namespace, the friend
1295 // declaration refers to the deduced specialization of that function
1296 // template, otherwise
1297 // -- the name shall be an unqualified-id [...]
1298 // If we get here for a qualified friend declaration, we've just reached the
1299 // third bullet. If the type of the friend is dependent, skip this lookup
1300 // until instantiation.
1301 if (New->getFriendObjectKind() && New->getQualifier() &&
1302 !New->getDescribedFunctionTemplate() &&
1303 !New->getDependentSpecializationInfo() &&
1304 !New->getType()->isDependentType()) {
1305 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1306 TemplateSpecResult.addAllDecls(Old);
1307 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1308 /*QualifiedFriend*/true)) {
1309 New->setInvalidDecl();
1311 }
1312
1313 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1314 return OverloadKind::Match;
1315 }
1316
1318}
1319
1320template <typename AttrT> static bool hasExplicitAttr(const FunctionDecl *D) {
1321 assert(D && "function decl should not be null");
1322 if (auto *A = D->getAttr<AttrT>())
1323 return !A->isImplicit();
1324 return false;
1325}
1326
1328 FunctionDecl *Old,
1329 bool UseMemberUsingDeclRules,
1330 bool ConsiderCudaAttrs,
1331 bool UseOverrideRules = false) {
1332 // C++ [basic.start.main]p2: This function shall not be overloaded.
1333 if (New->isMain())
1334 return false;
1335
1336 // MSVCRT user defined entry points cannot be overloaded.
1337 if (New->isMSVCRTEntryPoint())
1338 return false;
1339
1340 NamedDecl *OldDecl = Old;
1341 NamedDecl *NewDecl = New;
1343 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1344
1345 // C++ [temp.fct]p2:
1346 // A function template can be overloaded with other function templates
1347 // and with normal (non-template) functions.
1348 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1349 return true;
1350
1351 // Is the function New an overload of the function Old?
1352 QualType OldQType = SemaRef.Context.getCanonicalType(Old->getType());
1353 QualType NewQType = SemaRef.Context.getCanonicalType(New->getType());
1354
1355 // Compare the signatures (C++ 1.3.10) of the two functions to
1356 // determine whether they are overloads. If we find any mismatch
1357 // in the signature, they are overloads.
1358
1359 // If either of these functions is a K&R-style function (no
1360 // prototype), then we consider them to have matching signatures.
1361 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1363 return false;
1364
1365 const auto *OldType = cast<FunctionProtoType>(OldQType);
1366 const auto *NewType = cast<FunctionProtoType>(NewQType);
1367
1368 // The signature of a function includes the types of its
1369 // parameters (C++ 1.3.10), which includes the presence or absence
1370 // of the ellipsis; see C++ DR 357).
1371 if (OldQType != NewQType && OldType->isVariadic() != NewType->isVariadic())
1372 return true;
1373
1374 // For member-like friends, the enclosing class is part of the signature.
1375 if ((New->isMemberLikeConstrainedFriend() ||
1377 !New->getLexicalDeclContext()->Equals(Old->getLexicalDeclContext()))
1378 return true;
1379
1380 // Compare the parameter lists.
1381 // This can only be done once we have establish that friend functions
1382 // inhabit the same context, otherwise we might tried to instantiate
1383 // references to non-instantiated entities during constraint substitution.
1384 // GH78101.
1385 if (NewTemplate) {
1386 OldDecl = OldTemplate;
1387 NewDecl = NewTemplate;
1388 // C++ [temp.over.link]p4:
1389 // The signature of a function template consists of its function
1390 // signature, its return type and its template parameter list. The names
1391 // of the template parameters are significant only for establishing the
1392 // relationship between the template parameters and the rest of the
1393 // signature.
1394 //
1395 // We check the return type and template parameter lists for function
1396 // templates first; the remaining checks follow.
1397 bool SameTemplateParameterList = SemaRef.TemplateParameterListsAreEqual(
1398 NewTemplate, NewTemplate->getTemplateParameters(), OldTemplate,
1399 OldTemplate->getTemplateParameters(), false, Sema::TPL_TemplateMatch);
1400 bool SameReturnType = SemaRef.Context.hasSameType(
1401 Old->getDeclaredReturnType(), New->getDeclaredReturnType());
1402 // FIXME(GH58571): Match template parameter list even for non-constrained
1403 // template heads. This currently ensures that the code prior to C++20 is
1404 // not newly broken.
1405 bool ConstraintsInTemplateHead =
1408 // C++ [namespace.udecl]p11:
1409 // The set of declarations named by a using-declarator that inhabits a
1410 // class C does not include member functions and member function
1411 // templates of a base class that "correspond" to (and thus would
1412 // conflict with) a declaration of a function or function template in
1413 // C.
1414 // Comparing return types is not required for the "correspond" check to
1415 // decide whether a member introduced by a shadow declaration is hidden.
1416 if (UseMemberUsingDeclRules && ConstraintsInTemplateHead &&
1417 !SameTemplateParameterList)
1418 return true;
1419 if (!UseMemberUsingDeclRules &&
1420 (!SameTemplateParameterList || !SameReturnType))
1421 return true;
1422 }
1423
1424 const auto *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1425 const auto *NewMethod = dyn_cast<CXXMethodDecl>(New);
1426
1427 int OldParamsOffset = 0;
1428 int NewParamsOffset = 0;
1429
1430 // When determining if a method is an overload from a base class, act as if
1431 // the implicit object parameter are of the same type.
1432
1433 auto NormalizeQualifiers = [&](const CXXMethodDecl *M, Qualifiers Q) {
1435 auto ThisType = M->getFunctionObjectParameterReferenceType();
1436 if (ThisType.isConstQualified())
1437 Q.removeConst();
1438 return Q;
1439 }
1440
1441 // We do not allow overloading based off of '__restrict'.
1442 Q.removeRestrict();
1443
1444 // We may not have applied the implicit const for a constexpr member
1445 // function yet (because we haven't yet resolved whether this is a static
1446 // or non-static member function). Add it now, on the assumption that this
1447 // is a redeclaration of OldMethod.
1448 if (!SemaRef.getLangOpts().CPlusPlus14 &&
1449 (M->isConstexpr() || M->isConsteval()) &&
1450 !isa<CXXConstructorDecl>(NewMethod))
1451 Q.addConst();
1452 return Q;
1453 };
1454
1455 auto AreQualifiersEqual = [&](SplitQualType BS, SplitQualType DS) {
1456 BS.Quals = NormalizeQualifiers(OldMethod, BS.Quals);
1457 DS.Quals = NormalizeQualifiers(NewMethod, DS.Quals);
1458
1459 if (OldMethod->isExplicitObjectMemberFunction()) {
1460 BS.Quals.removeVolatile();
1461 DS.Quals.removeVolatile();
1462 }
1463
1464 return BS.Quals == DS.Quals;
1465 };
1466
1467 auto CompareType = [&](QualType Base, QualType D) {
1468 auto BS = Base.getNonReferenceType().getCanonicalType().split();
1469 auto DS = D.getNonReferenceType().getCanonicalType().split();
1470
1471 if (!AreQualifiersEqual(BS, DS))
1472 return false;
1473
1474 if (OldMethod->isImplicitObjectMemberFunction() &&
1475 OldMethod->getParent() != NewMethod->getParent()) {
1476 CanQualType ParentType =
1477 SemaRef.Context.getCanonicalTagType(OldMethod->getParent());
1478 if (ParentType.getTypePtr() != BS.Ty)
1479 return false;
1480 BS.Ty = DS.Ty;
1481 }
1482
1483 // FIXME: should we ignore some type attributes here?
1484 if (BS.Ty != DS.Ty)
1485 return false;
1486
1487 if (Base->isLValueReferenceType())
1488 return D->isLValueReferenceType();
1489 return Base->isRValueReferenceType() == D->isRValueReferenceType();
1490 };
1491
1492 // If the function is a class member, its signature includes the
1493 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1494 auto DiagnoseInconsistentRefQualifiers = [&]() {
1495 if (SemaRef.LangOpts.CPlusPlus23 && !UseOverrideRules)
1496 return false;
1497 if (OldMethod->getRefQualifier() == NewMethod->getRefQualifier())
1498 return false;
1499 if (OldMethod->isExplicitObjectMemberFunction() ||
1500 NewMethod->isExplicitObjectMemberFunction())
1501 return false;
1502 if (!UseMemberUsingDeclRules && (OldMethod->getRefQualifier() == RQ_None ||
1503 NewMethod->getRefQualifier() == RQ_None)) {
1504 SemaRef.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1505 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1506 SemaRef.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1507 return true;
1508 }
1509 return false;
1510 };
1511
1512 if (OldMethod && OldMethod->isExplicitObjectMemberFunction())
1513 OldParamsOffset++;
1514 if (NewMethod && NewMethod->isExplicitObjectMemberFunction())
1515 NewParamsOffset++;
1516
1517 if (OldType->getNumParams() - OldParamsOffset !=
1518 NewType->getNumParams() - NewParamsOffset ||
1520 {OldType->param_type_begin() + OldParamsOffset,
1521 OldType->param_type_end()},
1522 {NewType->param_type_begin() + NewParamsOffset,
1523 NewType->param_type_end()},
1524 nullptr)) {
1525 return true;
1526 }
1527
1528 if (OldMethod && NewMethod && !OldMethod->isStatic() &&
1529 !NewMethod->isStatic()) {
1530 bool HaveCorrespondingObjectParameters = [&](const CXXMethodDecl *Old,
1531 const CXXMethodDecl *New) {
1532 auto NewObjectType = New->getFunctionObjectParameterReferenceType();
1533 auto OldObjectType = Old->getFunctionObjectParameterReferenceType();
1534
1535 auto IsImplicitWithNoRefQual = [](const CXXMethodDecl *F) {
1536 return F->getRefQualifier() == RQ_None &&
1537 !F->isExplicitObjectMemberFunction();
1538 };
1539
1540 if (IsImplicitWithNoRefQual(Old) != IsImplicitWithNoRefQual(New) &&
1541 CompareType(OldObjectType.getNonReferenceType(),
1542 NewObjectType.getNonReferenceType()))
1543 return true;
1544 return CompareType(OldObjectType, NewObjectType);
1545 }(OldMethod, NewMethod);
1546
1547 if (!HaveCorrespondingObjectParameters) {
1548 if (DiagnoseInconsistentRefQualifiers())
1549 return true;
1550 // CWG2554
1551 // and, if at least one is an explicit object member function, ignoring
1552 // object parameters
1553 if (!UseOverrideRules || (!NewMethod->isExplicitObjectMemberFunction() &&
1554 !OldMethod->isExplicitObjectMemberFunction()))
1555 return true;
1556 }
1557 }
1558
1559 if (!UseOverrideRules &&
1560 New->getTemplateSpecializationKind() != TSK_ExplicitSpecialization) {
1561 AssociatedConstraint NewRC = New->getTrailingRequiresClause(),
1562 OldRC = Old->getTrailingRequiresClause();
1563 if (!NewRC != !OldRC)
1564 return true;
1565 if (NewRC.ArgPackSubstIndex != OldRC.ArgPackSubstIndex)
1566 return true;
1567 if (NewRC &&
1568 !SemaRef.AreConstraintExpressionsEqual(OldDecl, OldRC.ConstraintExpr,
1569 NewDecl, NewRC.ConstraintExpr))
1570 return true;
1571 }
1572
1573 if (NewMethod && OldMethod && OldMethod->isImplicitObjectMemberFunction() &&
1574 NewMethod->isImplicitObjectMemberFunction()) {
1575 if (DiagnoseInconsistentRefQualifiers())
1576 return true;
1577 }
1578
1579 // Though pass_object_size is placed on parameters and takes an argument, we
1580 // consider it to be a function-level modifier for the sake of function
1581 // identity. Either the function has one or more parameters with
1582 // pass_object_size or it doesn't.
1585 return true;
1586
1587 // enable_if attributes are an order-sensitive part of the signature.
1589 NewI = New->specific_attr_begin<EnableIfAttr>(),
1590 NewE = New->specific_attr_end<EnableIfAttr>(),
1591 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1592 OldE = Old->specific_attr_end<EnableIfAttr>();
1593 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1594 if (NewI == NewE || OldI == OldE)
1595 return true;
1596 llvm::FoldingSetNodeID NewID, OldID;
1597 NewI->getCond()->Profile(NewID, SemaRef.Context, true);
1598 OldI->getCond()->Profile(OldID, SemaRef.Context, true);
1599 if (NewID != OldID)
1600 return true;
1601 }
1602
1603 // At this point, it is known that the two functions have the same signature.
1604 if (SemaRef.getLangOpts().CUDA && ConsiderCudaAttrs) {
1605 // Don't allow overloading of destructors. (In theory we could, but it
1606 // would be a giant change to clang.)
1608 CUDAFunctionTarget NewTarget = SemaRef.CUDA().IdentifyTarget(New),
1609 OldTarget = SemaRef.CUDA().IdentifyTarget(Old);
1610 if (NewTarget != CUDAFunctionTarget::InvalidTarget) {
1611 assert((OldTarget != CUDAFunctionTarget::InvalidTarget) &&
1612 "Unexpected invalid target.");
1613
1614 // Allow overloading of functions with same signature and different CUDA
1615 // target attributes.
1616 if (NewTarget != OldTarget) {
1617 // Special case: non-constexpr function is allowed to override
1618 // constexpr virtual function
1619 if (OldMethod && NewMethod && OldMethod->isVirtual() &&
1620 OldMethod->isConstexpr() && !NewMethod->isConstexpr() &&
1625 return false;
1626 }
1627 return true;
1628 }
1629 }
1630 }
1631 }
1632
1633 // The signatures match; this is not an overload.
1634 return false;
1635}
1636
1638 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1639 return IsOverloadOrOverrideImpl(*this, New, Old, UseMemberUsingDeclRules,
1640 ConsiderCudaAttrs);
1641}
1642
1644 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1645 return IsOverloadOrOverrideImpl(*this, MD, BaseMD,
1646 /*UseMemberUsingDeclRules=*/false,
1647 /*ConsiderCudaAttrs=*/true,
1648 /*UseOverrideRules=*/true);
1649}
1650
1651/// Tries a user-defined conversion from From to ToType.
1652///
1653/// Produces an implicit conversion sequence for when a standard conversion
1654/// is not an option. See TryImplicitConversion for more information.
1657 bool SuppressUserConversions,
1658 AllowedExplicit AllowExplicit,
1659 bool InOverloadResolution,
1660 bool CStyle,
1661 bool AllowObjCWritebackConversion,
1662 bool AllowObjCConversionOnExplicit) {
1664
1665 if (SuppressUserConversions) {
1666 // We're not in the case above, so there is no conversion that
1667 // we can perform.
1669 return ICS;
1670 }
1671
1672 // Attempt user-defined conversion.
1673 OverloadCandidateSet Conversions(From->getExprLoc(),
1675 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1676 Conversions, AllowExplicit,
1677 AllowObjCConversionOnExplicit)) {
1678 case OR_Success:
1679 case OR_Deleted:
1680 ICS.setUserDefined();
1681 // C++ [over.ics.user]p4:
1682 // A conversion of an expression of class type to the same class
1683 // type is given Exact Match rank, and a conversion of an
1684 // expression of class type to a base class of that type is
1685 // given Conversion rank, in spite of the fact that a copy
1686 // constructor (i.e., a user-defined conversion function) is
1687 // called for those cases.
1689 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1690 QualType FromType;
1691 SourceLocation FromLoc;
1692 // C++11 [over.ics.list]p6, per DR2137:
1693 // C++17 [over.ics.list]p6:
1694 // If C is not an initializer-list constructor and the initializer list
1695 // has a single element of type cv U, where U is X or a class derived
1696 // from X, the implicit conversion sequence has Exact Match rank if U is
1697 // X, or Conversion rank if U is derived from X.
1698 bool FromListInit = false;
1699 if (const auto *InitList = dyn_cast<InitListExpr>(From);
1700 InitList && InitList->getNumInits() == 1 &&
1702 const Expr *SingleInit = InitList->getInit(0);
1703 FromType = SingleInit->getType();
1704 FromLoc = SingleInit->getBeginLoc();
1705 FromListInit = true;
1706 } else {
1707 FromType = From->getType();
1708 FromLoc = From->getBeginLoc();
1709 }
1710 QualType FromCanon =
1712 QualType ToCanon
1714 if ((FromCanon == ToCanon ||
1715 S.IsDerivedFrom(FromLoc, FromCanon, ToCanon))) {
1716 // Turn this into a "standard" conversion sequence, so that it
1717 // gets ranked with standard conversion sequences.
1719 ICS.setStandard();
1721 ICS.Standard.setFromType(FromType);
1722 ICS.Standard.setAllToTypes(ToType);
1723 ICS.Standard.FromBracedInitList = FromListInit;
1726 if (ToCanon != FromCanon)
1728 }
1729 }
1730 break;
1731
1732 case OR_Ambiguous:
1733 ICS.setAmbiguous();
1734 ICS.Ambiguous.setFromType(From->getType());
1735 ICS.Ambiguous.setToType(ToType);
1736 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1737 Cand != Conversions.end(); ++Cand)
1738 if (Cand->Best)
1739 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1740 break;
1741
1742 // Fall through.
1745 break;
1746 }
1747
1748 return ICS;
1749}
1750
1751/// TryImplicitConversion - Attempt to perform an implicit conversion
1752/// from the given expression (Expr) to the given type (ToType). This
1753/// function returns an implicit conversion sequence that can be used
1754/// to perform the initialization. Given
1755///
1756/// void f(float f);
1757/// void g(int i) { f(i); }
1758///
1759/// this routine would produce an implicit conversion sequence to
1760/// describe the initialization of f from i, which will be a standard
1761/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1762/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1763//
1764/// Note that this routine only determines how the conversion can be
1765/// performed; it does not actually perform the conversion. As such,
1766/// it will not produce any diagnostics if no conversion is available,
1767/// but will instead return an implicit conversion sequence of kind
1768/// "BadConversion".
1769///
1770/// If @p SuppressUserConversions, then user-defined conversions are
1771/// not permitted.
1772/// If @p AllowExplicit, then explicit user-defined conversions are
1773/// permitted.
1774///
1775/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1776/// writeback conversion, which allows __autoreleasing id* parameters to
1777/// be initialized with __strong id* or __weak id* arguments.
1778static ImplicitConversionSequence
1780 bool SuppressUserConversions,
1781 AllowedExplicit AllowExplicit,
1782 bool InOverloadResolution,
1783 bool CStyle,
1784 bool AllowObjCWritebackConversion,
1785 bool AllowObjCConversionOnExplicit) {
1787 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1788 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1789 ICS.setStandard();
1790 return ICS;
1791 }
1792
1793 if (!S.getLangOpts().CPlusPlus) {
1795 return ICS;
1796 }
1797
1798 // C++ [over.ics.user]p4:
1799 // A conversion of an expression of class type to the same class
1800 // type is given Exact Match rank, and a conversion of an
1801 // expression of class type to a base class of that type is
1802 // given Conversion rank, in spite of the fact that a copy/move
1803 // constructor (i.e., a user-defined conversion function) is
1804 // called for those cases.
1805 QualType FromType = From->getType();
1806 if (ToType->isRecordType() &&
1807 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1808 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1809 ICS.setStandard();
1811 ICS.Standard.setFromType(FromType);
1812 ICS.Standard.setAllToTypes(ToType);
1813
1814 // We don't actually check at this point whether there is a valid
1815 // copy/move constructor, since overloading just assumes that it
1816 // exists. When we actually perform initialization, we'll find the
1817 // appropriate constructor to copy the returned object, if needed.
1818 ICS.Standard.CopyConstructor = nullptr;
1819
1820 // Determine whether this is considered a derived-to-base conversion.
1821 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1823
1824 return ICS;
1825 }
1826
1827 if (S.getLangOpts().HLSL && ToType->isHLSLAttributedResourceType() &&
1828 FromType->isHLSLAttributedResourceType()) {
1829 auto *ToResType = cast<HLSLAttributedResourceType>(ToType);
1830 auto *FromResType = cast<HLSLAttributedResourceType>(FromType);
1831 if (S.Context.hasSameUnqualifiedType(ToResType->getWrappedType(),
1832 FromResType->getWrappedType()) &&
1833 S.Context.hasSameUnqualifiedType(ToResType->getContainedType(),
1834 FromResType->getContainedType()) &&
1835 ToResType->getAttrs() == FromResType->getAttrs()) {
1836 ICS.setStandard();
1838 ICS.Standard.setFromType(FromType);
1839 ICS.Standard.setAllToTypes(ToType);
1840 return ICS;
1841 }
1842 }
1843
1844 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1845 AllowExplicit, InOverloadResolution, CStyle,
1846 AllowObjCWritebackConversion,
1847 AllowObjCConversionOnExplicit);
1848}
1849
1850ImplicitConversionSequence
1852 bool SuppressUserConversions,
1853 AllowedExplicit AllowExplicit,
1854 bool InOverloadResolution,
1855 bool CStyle,
1856 bool AllowObjCWritebackConversion) {
1857 return ::TryImplicitConversion(*this, From, ToType, SuppressUserConversions,
1858 AllowExplicit, InOverloadResolution, CStyle,
1859 AllowObjCWritebackConversion,
1860 /*AllowObjCConversionOnExplicit=*/false);
1861}
1862
1864 AssignmentAction Action,
1865 bool AllowExplicit) {
1866 if (checkPlaceholderForOverload(*this, From))
1867 return ExprError();
1868
1869 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1870 bool AllowObjCWritebackConversion =
1871 getLangOpts().ObjCAutoRefCount && (Action == AssignmentAction::Passing ||
1872 Action == AssignmentAction::Sending);
1873 if (getLangOpts().ObjC)
1874 ObjC().CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1875 From->getType(), From);
1877 *this, From, ToType,
1878 /*SuppressUserConversions=*/false,
1879 AllowExplicit ? AllowedExplicit::All : AllowedExplicit::None,
1880 /*InOverloadResolution=*/false,
1881 /*CStyle=*/false, AllowObjCWritebackConversion,
1882 /*AllowObjCConversionOnExplicit=*/false);
1883 return PerformImplicitConversion(From, ToType, ICS, Action);
1884}
1885
1887 QualType &ResultTy) const {
1888 bool Changed = IsFunctionConversion(FromType, ToType);
1889 if (Changed)
1890 ResultTy = ToType;
1891 return Changed;
1892}
1893
1896 bool *AddingCFIUncheckedCallee) const {
1900 *AddingCFIUncheckedCallee = false;
1901
1902 if (Context.hasSameUnqualifiedType(FromType, ToType))
1903 return false;
1904
1905 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1906 // or F(t noexcept) -> F(t)
1907 // where F adds one of the following at most once:
1908 // - a pointer
1909 // - a member pointer
1910 // - a block pointer
1911 // Changes here need matching changes in FindCompositePointerType.
1912 CanQualType CanTo = Context.getCanonicalType(ToType);
1913 CanQualType CanFrom = Context.getCanonicalType(FromType);
1914 Type::TypeClass TyClass = CanTo->getTypeClass();
1915 if (TyClass != CanFrom->getTypeClass()) return false;
1916 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1917 if (TyClass == Type::Pointer) {
1918 CanTo = CanTo.castAs<PointerType>()->getPointeeType();
1919 CanFrom = CanFrom.castAs<PointerType>()->getPointeeType();
1920 } else if (TyClass == Type::BlockPointer) {
1921 CanTo = CanTo.castAs<BlockPointerType>()->getPointeeType();
1922 CanFrom = CanFrom.castAs<BlockPointerType>()->getPointeeType();
1923 } else if (TyClass == Type::MemberPointer) {
1924 auto ToMPT = CanTo.castAs<MemberPointerType>();
1925 auto FromMPT = CanFrom.castAs<MemberPointerType>();
1926 // A function pointer conversion cannot change the class of the function.
1927 if (!declaresSameEntity(ToMPT->getMostRecentCXXRecordDecl(),
1928 FromMPT->getMostRecentCXXRecordDecl()))
1929 return false;
1930 CanTo = ToMPT->getPointeeType();
1931 CanFrom = FromMPT->getPointeeType();
1932 } else {
1933 return false;
1934 }
1935
1936 TyClass = CanTo->getTypeClass();
1937 if (TyClass != CanFrom->getTypeClass()) return false;
1938 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1939 return false;
1940 }
1941
1942 const auto *FromFn = cast<FunctionType>(CanFrom);
1943 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1944
1945 const auto *ToFn = cast<FunctionType>(CanTo);
1946 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1947
1948 bool Changed = false;
1949
1950 // Drop 'noreturn' if not present in target type.
1951 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1952 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1953 Changed = true;
1954 }
1955
1956 const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn);
1957 const auto *ToFPT = dyn_cast<FunctionProtoType>(ToFn);
1958
1959 if (FromFPT && ToFPT) {
1960 if (FromFPT->hasCFIUncheckedCallee() && !ToFPT->hasCFIUncheckedCallee()) {
1961 QualType NewTy = Context.getFunctionType(
1962 FromFPT->getReturnType(), FromFPT->getParamTypes(),
1963 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(false));
1964 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
1965 FromFn = FromFPT;
1966 Changed = true;
1969 } else if (!FromFPT->hasCFIUncheckedCallee() &&
1970 ToFPT->hasCFIUncheckedCallee()) {
1971 QualType NewTy = Context.getFunctionType(
1972 FromFPT->getReturnType(), FromFPT->getParamTypes(),
1973 FromFPT->getExtProtoInfo().withCFIUncheckedCallee(true));
1974 FromFPT = cast<FunctionProtoType>(NewTy.getTypePtr());
1975 FromFn = FromFPT;
1976 Changed = true;
1979 }
1980 }
1981
1982 // Drop 'noexcept' if not present in target type.
1983 if (FromFPT && ToFPT) {
1984 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1985 FromFn = cast<FunctionType>(
1986 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1987 EST_None)
1988 .getTypePtr());
1989 Changed = true;
1990 }
1991
1992 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1993 // only if the ExtParameterInfo lists of the two function prototypes can be
1994 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1996 bool CanUseToFPT, CanUseFromFPT;
1997 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1998 CanUseFromFPT, NewParamInfos) &&
1999 CanUseToFPT && !CanUseFromFPT) {
2000 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2001 ExtInfo.ExtParameterInfos =
2002 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
2003 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
2004 FromFPT->getParamTypes(), ExtInfo);
2005 FromFn = QT->getAs<FunctionType>();
2006 Changed = true;
2007 }
2008
2009 // For C, when called from checkPointerTypesForAssignment,
2010 // we need to not alter FromFn, or else even an innocuous cast
2011 // like dropping effects will fail. In C++ however we do want to
2012 // alter FromFn (because of the way PerformImplicitConversion works).
2013 if (Context.hasAnyFunctionEffects() && getLangOpts().CPlusPlus) {
2014 FromFPT = cast<FunctionProtoType>(FromFn); // in case FromFn changed above
2015
2016 // Transparently add/drop effects; here we are concerned with
2017 // language rules/canonicalization. Adding/dropping effects is a warning.
2018 const auto FromFX = FromFPT->getFunctionEffects();
2019 const auto ToFX = ToFPT->getFunctionEffects();
2020 if (FromFX != ToFX) {
2021 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
2022 ExtInfo.FunctionEffects = ToFX;
2023 QualType QT = Context.getFunctionType(
2024 FromFPT->getReturnType(), FromFPT->getParamTypes(), ExtInfo);
2025 FromFn = QT->getAs<FunctionType>();
2026 Changed = true;
2027 }
2028 }
2029 }
2030
2031 if (!Changed)
2032 return false;
2033
2034 assert(QualType(FromFn, 0).isCanonical());
2035 if (QualType(FromFn, 0) != CanTo) return false;
2036
2037 return true;
2038}
2039
2040/// Determine whether the conversion from FromType to ToType is a valid
2041/// floating point conversion.
2042///
2043static bool IsFloatingPointConversion(Sema &S, QualType FromType,
2044 QualType ToType) {
2045 if (!FromType->isRealFloatingType() || !ToType->isRealFloatingType())
2046 return false;
2047 // FIXME: disable conversions between long double, __ibm128 and __float128
2048 // if their representation is different until there is back end support
2049 // We of course allow this conversion if long double is really double.
2050
2051 // Conversions between bfloat16 and float16 are currently not supported.
2052 if ((FromType->isBFloat16Type() &&
2053 (ToType->isFloat16Type() || ToType->isHalfType())) ||
2054 (ToType->isBFloat16Type() &&
2055 (FromType->isFloat16Type() || FromType->isHalfType())))
2056 return false;
2057
2058 // Conversions between IEEE-quad and IBM-extended semantics are not
2059 // permitted.
2060 const llvm::fltSemantics &FromSem = S.Context.getFloatTypeSemantics(FromType);
2061 const llvm::fltSemantics &ToSem = S.Context.getFloatTypeSemantics(ToType);
2062 if ((&FromSem == &llvm::APFloat::PPCDoubleDouble() &&
2063 &ToSem == &llvm::APFloat::IEEEquad()) ||
2064 (&FromSem == &llvm::APFloat::IEEEquad() &&
2065 &ToSem == &llvm::APFloat::PPCDoubleDouble()))
2066 return false;
2067 return true;
2068}
2069
2070static bool IsVectorElementConversion(Sema &S, QualType FromType,
2071 QualType ToType,
2072 ImplicitConversionKind &ICK, Expr *From) {
2073 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2074 return true;
2075
2076 if (S.IsFloatingPointPromotion(FromType, ToType)) {
2078 return true;
2079 }
2080
2081 if (IsFloatingPointConversion(S, FromType, ToType)) {
2083 return true;
2084 }
2085
2086 if (ToType->isBooleanType() && FromType->isArithmeticType()) {
2088 return true;
2089 }
2090
2091 if ((FromType->isRealFloatingType() && ToType->isIntegralType(S.Context)) ||
2093 ToType->isRealFloatingType())) {
2095 return true;
2096 }
2097
2098 if (S.IsIntegralPromotion(From, FromType, ToType)) {
2100 return true;
2101 }
2102
2103 if (FromType->isIntegralOrUnscopedEnumerationType() &&
2104 ToType->isIntegralType(S.Context)) {
2106 return true;
2107 }
2108
2109 return false;
2110}
2111
2112/// Determine whether the conversion from FromType to ToType is a valid
2113/// vector conversion.
2114///
2115/// \param ICK Will be set to the vector conversion kind, if this is a vector
2116/// conversion.
2117static bool IsVectorConversion(Sema &S, QualType FromType, QualType ToType,
2119 ImplicitConversionKind &ElConv, Expr *From,
2120 bool InOverloadResolution, bool CStyle) {
2121 // We need at least one of these types to be a vector type to have a vector
2122 // conversion.
2123 if (!ToType->isVectorType() && !FromType->isVectorType())
2124 return false;
2125
2126 // Identical types require no conversions.
2127 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
2128 return false;
2129
2130 // HLSL allows implicit truncation of vector types.
2131 if (S.getLangOpts().HLSL) {
2132 auto *ToExtType = ToType->getAs<ExtVectorType>();
2133 auto *FromExtType = FromType->getAs<ExtVectorType>();
2134
2135 // If both arguments are vectors, handle possible vector truncation and
2136 // element conversion.
2137 if (ToExtType && FromExtType) {
2138 unsigned FromElts = FromExtType->getNumElements();
2139 unsigned ToElts = ToExtType->getNumElements();
2140 if (FromElts < ToElts)
2141 return false;
2142 if (FromElts == ToElts)
2143 ElConv = ICK_Identity;
2144 else
2146
2147 QualType FromElTy = FromExtType->getElementType();
2148 QualType ToElTy = ToExtType->getElementType();
2149 if (S.Context.hasSameUnqualifiedType(FromElTy, ToElTy))
2150 return true;
2151 return IsVectorElementConversion(S, FromElTy, ToElTy, ICK, From);
2152 }
2153 if (FromExtType && !ToExtType) {
2155 QualType FromElTy = FromExtType->getElementType();
2156 if (S.Context.hasSameUnqualifiedType(FromElTy, ToType))
2157 return true;
2158 return IsVectorElementConversion(S, FromElTy, ToType, ICK, From);
2159 }
2160 // Fallthrough for the case where ToType is a vector and FromType is not.
2161 }
2162
2163 // There are no conversions between extended vector types, only identity.
2164 if (auto *ToExtType = ToType->getAs<ExtVectorType>()) {
2165 if (FromType->getAs<ExtVectorType>()) {
2166 // There are no conversions between extended vector types other than the
2167 // identity conversion.
2168 return false;
2169 }
2170
2171 // Vector splat from any arithmetic type to a vector.
2172 if (FromType->isArithmeticType()) {
2173 if (S.getLangOpts().HLSL) {
2174 ElConv = ICK_HLSL_Vector_Splat;
2175 QualType ToElTy = ToExtType->getElementType();
2176 return IsVectorElementConversion(S, FromType, ToElTy, ICK, From);
2177 }
2178 ICK = ICK_Vector_Splat;
2179 return true;
2180 }
2181 }
2182
2183 if (ToType->isSVESizelessBuiltinType() ||
2184 FromType->isSVESizelessBuiltinType())
2185 if (S.ARM().areCompatibleSveTypes(FromType, ToType) ||
2186 S.ARM().areLaxCompatibleSveTypes(FromType, ToType)) {
2188 return true;
2189 }
2190
2191 if (ToType->isRVVSizelessBuiltinType() ||
2192 FromType->isRVVSizelessBuiltinType())
2193 if (S.Context.areCompatibleRVVTypes(FromType, ToType) ||
2194 S.Context.areLaxCompatibleRVVTypes(FromType, ToType)) {
2196 return true;
2197 }
2198
2199 // We can perform the conversion between vector types in the following cases:
2200 // 1)vector types are equivalent AltiVec and GCC vector types
2201 // 2)lax vector conversions are permitted and the vector types are of the
2202 // same size
2203 // 3)the destination type does not have the ARM MVE strict-polymorphism
2204 // attribute, which inhibits lax vector conversion for overload resolution
2205 // only
2206 if (ToType->isVectorType() && FromType->isVectorType()) {
2207 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
2208 (S.isLaxVectorConversion(FromType, ToType) &&
2209 !ToType->hasAttr(attr::ArmMveStrictPolymorphism))) {
2210 if (S.getASTContext().getTargetInfo().getTriple().isPPC() &&
2211 S.isLaxVectorConversion(FromType, ToType) &&
2212 S.anyAltivecTypes(FromType, ToType) &&
2213 !S.Context.areCompatibleVectorTypes(FromType, ToType) &&
2214 !InOverloadResolution && !CStyle) {
2215 S.Diag(From->getBeginLoc(), diag::warn_deprecated_lax_vec_conv_all)
2216 << FromType << ToType;
2217 }
2219 return true;
2220 }
2221 }
2222
2223 return false;
2224}
2225
2226static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2227 bool InOverloadResolution,
2228 StandardConversionSequence &SCS,
2229 bool CStyle);
2230
2231/// IsStandardConversion - Determines whether there is a standard
2232/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
2233/// expression From to the type ToType. Standard conversion sequences
2234/// only consider non-class types; for conversions that involve class
2235/// types, use TryImplicitConversion. If a conversion exists, SCS will
2236/// contain the standard conversion sequence required to perform this
2237/// conversion and this routine will return true. Otherwise, this
2238/// routine will return false and the value of SCS is unspecified.
2239static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
2240 bool InOverloadResolution,
2242 bool CStyle,
2243 bool AllowObjCWritebackConversion) {
2244 QualType FromType = From->getType();
2245
2246 // Standard conversions (C++ [conv])
2248 SCS.IncompatibleObjC = false;
2249 SCS.setFromType(FromType);
2250 SCS.CopyConstructor = nullptr;
2251
2252 // There are no standard conversions for class types in C++, so
2253 // abort early. When overloading in C, however, we do permit them.
2254 if (S.getLangOpts().CPlusPlus &&
2255 (FromType->isRecordType() || ToType->isRecordType()))
2256 return false;
2257
2258 // The first conversion can be an lvalue-to-rvalue conversion,
2259 // array-to-pointer conversion, or function-to-pointer conversion
2260 // (C++ 4p1).
2261
2262 if (FromType == S.Context.OverloadTy) {
2263 DeclAccessPair AccessPair;
2264 if (FunctionDecl *Fn
2265 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
2266 AccessPair)) {
2267 // We were able to resolve the address of the overloaded function,
2268 // so we can convert to the type of that function.
2269 FromType = Fn->getType();
2270 SCS.setFromType(FromType);
2271
2272 // we can sometimes resolve &foo<int> regardless of ToType, so check
2273 // if the type matches (identity) or we are converting to bool
2275 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
2276 // if the function type matches except for [[noreturn]], it's ok
2277 if (!S.IsFunctionConversion(FromType,
2279 // otherwise, only a boolean conversion is standard
2280 if (!ToType->isBooleanType())
2281 return false;
2282 }
2283
2284 // Check if the "from" expression is taking the address of an overloaded
2285 // function and recompute the FromType accordingly. Take advantage of the
2286 // fact that non-static member functions *must* have such an address-of
2287 // expression.
2288 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
2289 if (Method && !Method->isStatic() &&
2290 !Method->isExplicitObjectMemberFunction()) {
2291 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
2292 "Non-unary operator on non-static member address");
2293 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
2294 == UO_AddrOf &&
2295 "Non-address-of operator on non-static member address");
2296 FromType = S.Context.getMemberPointerType(
2297 FromType, /*Qualifier=*/std::nullopt, Method->getParent());
2298 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
2299 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
2300 UO_AddrOf &&
2301 "Non-address-of operator for overloaded function expression");
2302 FromType = S.Context.getPointerType(FromType);
2303 }
2304 } else {
2305 return false;
2306 }
2307 }
2308
2309 bool argIsLValue = From->isGLValue();
2310 // To handle conversion from ArrayParameterType to ConstantArrayType
2311 // this block must be above the one below because Array parameters
2312 // do not decay and when handling HLSLOutArgExprs and
2313 // the From expression is an LValue.
2314 if (S.getLangOpts().HLSL && FromType->isConstantArrayType() &&
2315 ToType->isConstantArrayType()) {
2316 // HLSL constant array parameters do not decay, so if the argument is a
2317 // constant array and the parameter is an ArrayParameterType we have special
2318 // handling here.
2319 if (ToType->isArrayParameterType()) {
2320 FromType = S.Context.getArrayParameterType(FromType);
2321 } else if (FromType->isArrayParameterType()) {
2322 const ArrayParameterType *APT = cast<ArrayParameterType>(FromType);
2323 FromType = APT->getConstantArrayType(S.Context);
2324 }
2325
2327
2328 // Don't consider qualifiers, which include things like address spaces
2329 if (FromType.getCanonicalType().getUnqualifiedType() !=
2331 return false;
2332
2333 SCS.setAllToTypes(ToType);
2334 return true;
2335 } else if (argIsLValue && !FromType->canDecayToPointerType() &&
2336 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
2337 // Lvalue-to-rvalue conversion (C++11 4.1):
2338 // A glvalue (3.10) of a non-function, non-array type T can
2339 // be converted to a prvalue.
2340
2342
2343 // C11 6.3.2.1p2:
2344 // ... if the lvalue has atomic type, the value has the non-atomic version
2345 // of the type of the lvalue ...
2346 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
2347 FromType = Atomic->getValueType();
2348
2349 // If T is a non-class type, the type of the rvalue is the
2350 // cv-unqualified version of T. Otherwise, the type of the rvalue
2351 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
2352 // just strip the qualifiers because they don't matter.
2353 FromType = FromType.getUnqualifiedType();
2354 } else if (FromType->isArrayType()) {
2355 // Array-to-pointer conversion (C++ 4.2)
2357
2358 // An lvalue or rvalue of type "array of N T" or "array of unknown
2359 // bound of T" can be converted to an rvalue of type "pointer to
2360 // T" (C++ 4.2p1).
2361 FromType = S.Context.getArrayDecayedType(FromType);
2362
2363 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
2364 // This conversion is deprecated in C++03 (D.4)
2366
2367 // For the purpose of ranking in overload resolution
2368 // (13.3.3.1.1), this conversion is considered an
2369 // array-to-pointer conversion followed by a qualification
2370 // conversion (4.4). (C++ 4.2p2)
2371 SCS.Second = ICK_Identity;
2374 SCS.setAllToTypes(FromType);
2375 return true;
2376 }
2377 } else if (FromType->isFunctionType() && argIsLValue) {
2378 // Function-to-pointer conversion (C++ 4.3).
2380
2381 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
2382 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
2384 return false;
2385
2386 // An lvalue of function type T can be converted to an rvalue of
2387 // type "pointer to T." The result is a pointer to the
2388 // function. (C++ 4.3p1).
2389 FromType = S.Context.getPointerType(FromType);
2390 } else {
2391 // We don't require any conversions for the first step.
2392 SCS.First = ICK_Identity;
2393 }
2394 SCS.setToType(0, FromType);
2395
2396 // The second conversion can be an integral promotion, floating
2397 // point promotion, integral conversion, floating point conversion,
2398 // floating-integral conversion, pointer conversion,
2399 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
2400 // For overloading in C, this can also be a "compatible-type"
2401 // conversion.
2402 bool IncompatibleObjC = false;
2404 ImplicitConversionKind DimensionICK = ICK_Identity;
2405 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
2406 // The unqualified versions of the types are the same: there's no
2407 // conversion to do.
2408 SCS.Second = ICK_Identity;
2409 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
2410 // Integral promotion (C++ 4.5).
2412 FromType = ToType.getUnqualifiedType();
2413 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
2414 // Floating point promotion (C++ 4.6).
2416 FromType = ToType.getUnqualifiedType();
2417 } else if (S.IsComplexPromotion(FromType, ToType)) {
2418 // Complex promotion (Clang extension)
2420 FromType = ToType.getUnqualifiedType();
2421 } else if (ToType->isBooleanType() &&
2422 (FromType->isArithmeticType() ||
2423 FromType->isAnyPointerType() ||
2424 FromType->isBlockPointerType() ||
2425 FromType->isMemberPointerType())) {
2426 // Boolean conversions (C++ 4.12).
2428 FromType = S.Context.BoolTy;
2429 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
2430 ToType->isIntegralType(S.Context)) {
2431 // Integral conversions (C++ 4.7).
2433 FromType = ToType.getUnqualifiedType();
2434 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
2435 // Complex conversions (C99 6.3.1.6)
2437 FromType = ToType.getUnqualifiedType();
2438 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
2439 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
2440 // Complex-real conversions (C99 6.3.1.7)
2442 FromType = ToType.getUnqualifiedType();
2443 } else if (IsFloatingPointConversion(S, FromType, ToType)) {
2444 // Floating point conversions (C++ 4.8).
2446 FromType = ToType.getUnqualifiedType();
2447 } else if ((FromType->isRealFloatingType() &&
2448 ToType->isIntegralType(S.Context)) ||
2450 ToType->isRealFloatingType())) {
2451
2452 // Floating-integral conversions (C++ 4.9).
2454 FromType = ToType.getUnqualifiedType();
2455 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
2457 } else if (AllowObjCWritebackConversion &&
2458 S.ObjC().isObjCWritebackConversion(FromType, ToType, FromType)) {
2460 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
2461 FromType, IncompatibleObjC)) {
2462 // Pointer conversions (C++ 4.10).
2464 SCS.IncompatibleObjC = IncompatibleObjC;
2465 FromType = FromType.getUnqualifiedType();
2466 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
2467 InOverloadResolution, FromType)) {
2468 // Pointer to member conversions (4.11).
2470 } else if (IsVectorConversion(S, FromType, ToType, SecondICK, DimensionICK,
2471 From, InOverloadResolution, CStyle)) {
2472 SCS.Second = SecondICK;
2473 SCS.Dimension = DimensionICK;
2474 FromType = ToType.getUnqualifiedType();
2475 } else if (!S.getLangOpts().CPlusPlus &&
2476 S.Context.typesAreCompatible(ToType, FromType)) {
2477 // Compatible conversions (Clang extension for C function overloading)
2479 FromType = ToType.getUnqualifiedType();
2481 S, From, ToType, InOverloadResolution, SCS, CStyle)) {
2483 FromType = ToType;
2484 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
2485 CStyle)) {
2486 // tryAtomicConversion has updated the standard conversion sequence
2487 // appropriately.
2488 return true;
2489 } else if (ToType->isEventT() &&
2491 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
2493 FromType = ToType;
2494 } else if (ToType->isQueueT() &&
2496 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
2498 FromType = ToType;
2499 } else if (ToType->isSamplerT() &&
2502 FromType = ToType;
2503 } else if ((ToType->isFixedPointType() &&
2504 FromType->isConvertibleToFixedPointType()) ||
2505 (FromType->isFixedPointType() &&
2506 ToType->isConvertibleToFixedPointType())) {
2508 FromType = ToType;
2509 } else {
2510 // No second conversion required.
2511 SCS.Second = ICK_Identity;
2512 }
2513 SCS.setToType(1, FromType);
2514
2515 // The third conversion can be a function pointer conversion or a
2516 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
2517 bool ObjCLifetimeConversion;
2518 if (S.TryFunctionConversion(FromType, ToType, FromType)) {
2519 // Function pointer conversions (removing 'noexcept') including removal of
2520 // 'noreturn' (Clang extension).
2522 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
2523 ObjCLifetimeConversion)) {
2525 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
2526 FromType = ToType;
2527 } else {
2528 // No conversion required
2529 SCS.Third = ICK_Identity;
2530 }
2531
2532 // C++ [over.best.ics]p6:
2533 // [...] Any difference in top-level cv-qualification is
2534 // subsumed by the initialization itself and does not constitute
2535 // a conversion. [...]
2536 QualType CanonFrom = S.Context.getCanonicalType(FromType);
2537 QualType CanonTo = S.Context.getCanonicalType(ToType);
2538 if (CanonFrom.getLocalUnqualifiedType()
2539 == CanonTo.getLocalUnqualifiedType() &&
2540 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
2541 FromType = ToType;
2542 CanonFrom = CanonTo;
2543 }
2544
2545 SCS.setToType(2, FromType);
2546
2547 // If we have not converted the argument type to the parameter type,
2548 // this is a bad conversion sequence, unless we're resolving an overload in C.
2549 //
2550 // Permit conversions from a function without `cfi_unchecked_callee` to a
2551 // function with `cfi_unchecked_callee`.
2552 if (CanonFrom == CanonTo || S.AddingCFIUncheckedCallee(CanonFrom, CanonTo))
2553 return true;
2554
2555 if ((S.getLangOpts().CPlusPlus || !InOverloadResolution))
2556 return false;
2557
2558 ExprResult ER = ExprResult{From};
2559 AssignConvertType Conv =
2561 /*Diagnose=*/false,
2562 /*DiagnoseCFAudited=*/false,
2563 /*ConvertRHS=*/false);
2564 ImplicitConversionKind SecondConv;
2565 switch (Conv) {
2567 case AssignConvertType::
2568 CompatibleVoidPtrToNonVoidPtr: // __attribute__((overloadable))
2569 SecondConv = ICK_C_Only_Conversion;
2570 break;
2571 // For our purposes, discarding qualifiers is just as bad as using an
2572 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
2573 // qualifiers, as well.
2578 break;
2579 default:
2580 return false;
2581 }
2582
2583 // First can only be an lvalue conversion, so we pretend that this was the
2584 // second conversion. First should already be valid from earlier in the
2585 // function.
2586 SCS.Second = SecondConv;
2587 SCS.setToType(1, ToType);
2588
2589 // Third is Identity, because Second should rank us worse than any other
2590 // conversion. This could also be ICK_Qualification, but it's simpler to just
2591 // lump everything in with the second conversion, and we don't gain anything
2592 // from making this ICK_Qualification.
2593 SCS.Third = ICK_Identity;
2594 SCS.setToType(2, ToType);
2595 return true;
2596}
2597
2598static bool
2600 QualType &ToType,
2601 bool InOverloadResolution,
2603 bool CStyle) {
2604
2605 const RecordType *UT = ToType->getAsUnionType();
2606 if (!UT)
2607 return false;
2608 // The field to initialize within the transparent union.
2609 const RecordDecl *UD = UT->getOriginalDecl()->getDefinitionOrSelf();
2610 if (!UD->hasAttr<TransparentUnionAttr>())
2611 return false;
2612 // It's compatible if the expression matches any of the fields.
2613 for (const auto *it : UD->fields()) {
2614 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
2615 CStyle, /*AllowObjCWritebackConversion=*/false)) {
2616 ToType = it->getType();
2617 return true;
2618 }
2619 }
2620 return false;
2621}
2622
2623bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
2624 const BuiltinType *To = ToType->getAs<BuiltinType>();
2625 // All integers are built-in.
2626 if (!To) {
2627 return false;
2628 }
2629
2630 // An rvalue of type char, signed char, unsigned char, short int, or
2631 // unsigned short int can be converted to an rvalue of type int if
2632 // int can represent all the values of the source type; otherwise,
2633 // the source rvalue can be converted to an rvalue of type unsigned
2634 // int (C++ 4.5p1).
2635 if (Context.isPromotableIntegerType(FromType) && !FromType->isBooleanType() &&
2636 !FromType->isEnumeralType()) {
2637 if ( // We can promote any signed, promotable integer type to an int
2638 (FromType->isSignedIntegerType() ||
2639 // We can promote any unsigned integer type whose size is
2640 // less than int to an int.
2641 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2642 return To->getKind() == BuiltinType::Int;
2643 }
2644
2645 return To->getKind() == BuiltinType::UInt;
2646 }
2647
2648 // C++11 [conv.prom]p3:
2649 // A prvalue of an unscoped enumeration type whose underlying type is not
2650 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2651 // following types that can represent all the values of the enumeration
2652 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2653 // unsigned int, long int, unsigned long int, long long int, or unsigned
2654 // long long int. If none of the types in that list can represent all the
2655 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2656 // type can be converted to an rvalue a prvalue of the extended integer type
2657 // with lowest integer conversion rank (4.13) greater than the rank of long
2658 // long in which all the values of the enumeration can be represented. If
2659 // there are two such extended types, the signed one is chosen.
2660 // C++11 [conv.prom]p4:
2661 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2662 // can be converted to a prvalue of its underlying type. Moreover, if
2663 // integral promotion can be applied to its underlying type, a prvalue of an
2664 // unscoped enumeration type whose underlying type is fixed can also be
2665 // converted to a prvalue of the promoted underlying type.
2666 if (const auto *FromED = FromType->getAsEnumDecl()) {
2667 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2668 // provided for a scoped enumeration.
2669 if (FromED->isScoped())
2670 return false;
2671
2672 // We can perform an integral promotion to the underlying type of the enum,
2673 // even if that's not the promoted type. Note that the check for promoting
2674 // the underlying type is based on the type alone, and does not consider
2675 // the bitfield-ness of the actual source expression.
2676 if (FromED->isFixed()) {
2677 QualType Underlying = FromED->getIntegerType();
2678 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2679 IsIntegralPromotion(nullptr, Underlying, ToType);
2680 }
2681
2682 // We have already pre-calculated the promotion type, so this is trivial.
2683 if (ToType->isIntegerType() &&
2684 isCompleteType(From->getBeginLoc(), FromType))
2685 return Context.hasSameUnqualifiedType(ToType, FromED->getPromotionType());
2686
2687 // C++ [conv.prom]p5:
2688 // If the bit-field has an enumerated type, it is treated as any other
2689 // value of that type for promotion purposes.
2690 //
2691 // ... so do not fall through into the bit-field checks below in C++.
2692 if (getLangOpts().CPlusPlus)
2693 return false;
2694 }
2695
2696 // C++0x [conv.prom]p2:
2697 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2698 // to an rvalue a prvalue of the first of the following types that can
2699 // represent all the values of its underlying type: int, unsigned int,
2700 // long int, unsigned long int, long long int, or unsigned long long int.
2701 // If none of the types in that list can represent all the values of its
2702 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2703 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2704 // type.
2705 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2706 ToType->isIntegerType()) {
2707 // Determine whether the type we're converting from is signed or
2708 // unsigned.
2709 bool FromIsSigned = FromType->isSignedIntegerType();
2710 uint64_t FromSize = Context.getTypeSize(FromType);
2711
2712 // The types we'll try to promote to, in the appropriate
2713 // order. Try each of these types.
2714 QualType PromoteTypes[6] = {
2715 Context.IntTy, Context.UnsignedIntTy,
2716 Context.LongTy, Context.UnsignedLongTy ,
2717 Context.LongLongTy, Context.UnsignedLongLongTy
2718 };
2719 for (int Idx = 0; Idx < 6; ++Idx) {
2720 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2721 if (FromSize < ToSize ||
2722 (FromSize == ToSize &&
2723 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2724 // We found the type that we can promote to. If this is the
2725 // type we wanted, we have a promotion. Otherwise, no
2726 // promotion.
2727 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2728 }
2729 }
2730 }
2731
2732 // An rvalue for an integral bit-field (9.6) can be converted to an
2733 // rvalue of type int if int can represent all the values of the
2734 // bit-field; otherwise, it can be converted to unsigned int if
2735 // unsigned int can represent all the values of the bit-field. If
2736 // the bit-field is larger yet, no integral promotion applies to
2737 // it. If the bit-field has an enumerated type, it is treated as any
2738 // other value of that type for promotion purposes (C++ 4.5p3).
2739 // FIXME: We should delay checking of bit-fields until we actually perform the
2740 // conversion.
2741 //
2742 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2743 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2744 // bit-fields and those whose underlying type is larger than int) for GCC
2745 // compatibility.
2746 if (From) {
2747 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2748 std::optional<llvm::APSInt> BitWidth;
2749 if (FromType->isIntegralType(Context) &&
2750 (BitWidth =
2751 MemberDecl->getBitWidth()->getIntegerConstantExpr(Context))) {
2752 llvm::APSInt ToSize(BitWidth->getBitWidth(), BitWidth->isUnsigned());
2753 ToSize = Context.getTypeSize(ToType);
2754
2755 // Are we promoting to an int from a bitfield that fits in an int?
2756 if (*BitWidth < ToSize ||
2757 (FromType->isSignedIntegerType() && *BitWidth <= ToSize)) {
2758 return To->getKind() == BuiltinType::Int;
2759 }
2760
2761 // Are we promoting to an unsigned int from an unsigned bitfield
2762 // that fits into an unsigned int?
2763 if (FromType->isUnsignedIntegerType() && *BitWidth <= ToSize) {
2764 return To->getKind() == BuiltinType::UInt;
2765 }
2766
2767 return false;
2768 }
2769 }
2770 }
2771
2772 // An rvalue of type bool can be converted to an rvalue of type int,
2773 // with false becoming zero and true becoming one (C++ 4.5p4).
2774 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2775 return true;
2776 }
2777
2778 // In HLSL an rvalue of integral type can be promoted to an rvalue of a larger
2779 // integral type.
2780 if (Context.getLangOpts().HLSL && FromType->isIntegerType() &&
2781 ToType->isIntegerType())
2782 return Context.getTypeSize(FromType) < Context.getTypeSize(ToType);
2783
2784 return false;
2785}
2786
2788 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2789 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2790 /// An rvalue of type float can be converted to an rvalue of type
2791 /// double. (C++ 4.6p1).
2792 if (FromBuiltin->getKind() == BuiltinType::Float &&
2793 ToBuiltin->getKind() == BuiltinType::Double)
2794 return true;
2795
2796 // C99 6.3.1.5p1:
2797 // When a float is promoted to double or long double, or a
2798 // double is promoted to long double [...].
2799 if (!getLangOpts().CPlusPlus &&
2800 (FromBuiltin->getKind() == BuiltinType::Float ||
2801 FromBuiltin->getKind() == BuiltinType::Double) &&
2802 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2803 ToBuiltin->getKind() == BuiltinType::Float128 ||
2804 ToBuiltin->getKind() == BuiltinType::Ibm128))
2805 return true;
2806
2807 // In HLSL, `half` promotes to `float` or `double`, regardless of whether
2808 // or not native half types are enabled.
2809 if (getLangOpts().HLSL && FromBuiltin->getKind() == BuiltinType::Half &&
2810 (ToBuiltin->getKind() == BuiltinType::Float ||
2811 ToBuiltin->getKind() == BuiltinType::Double))
2812 return true;
2813
2814 // Half can be promoted to float.
2815 if (!getLangOpts().NativeHalfType &&
2816 FromBuiltin->getKind() == BuiltinType::Half &&
2817 ToBuiltin->getKind() == BuiltinType::Float)
2818 return true;
2819 }
2820
2821 return false;
2822}
2823
2825 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2826 if (!FromComplex)
2827 return false;
2828
2829 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2830 if (!ToComplex)
2831 return false;
2832
2833 return IsFloatingPointPromotion(FromComplex->getElementType(),
2834 ToComplex->getElementType()) ||
2835 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2836 ToComplex->getElementType());
2837}
2838
2839/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2840/// the pointer type FromPtr to a pointer to type ToPointee, with the
2841/// same type qualifiers as FromPtr has on its pointee type. ToType,
2842/// if non-empty, will be a pointer to ToType that may or may not have
2843/// the right set of qualifiers on its pointee.
2844///
2845static QualType
2847 QualType ToPointee, QualType ToType,
2848 ASTContext &Context,
2849 bool StripObjCLifetime = false) {
2850 assert((FromPtr->getTypeClass() == Type::Pointer ||
2851 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2852 "Invalid similarly-qualified pointer type");
2853
2854 /// Conversions to 'id' subsume cv-qualifier conversions.
2855 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2856 return ToType.getUnqualifiedType();
2857
2858 QualType CanonFromPointee
2859 = Context.getCanonicalType(FromPtr->getPointeeType());
2860 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2861 Qualifiers Quals = CanonFromPointee.getQualifiers();
2862
2863 if (StripObjCLifetime)
2864 Quals.removeObjCLifetime();
2865
2866 // Exact qualifier match -> return the pointer type we're converting to.
2867 if (CanonToPointee.getLocalQualifiers() == Quals) {
2868 // ToType is exactly what we need. Return it.
2869 if (!ToType.isNull())
2870 return ToType.getUnqualifiedType();
2871
2872 // Build a pointer to ToPointee. It has the right qualifiers
2873 // already.
2874 if (isa<ObjCObjectPointerType>(ToType))
2875 return Context.getObjCObjectPointerType(ToPointee);
2876 return Context.getPointerType(ToPointee);
2877 }
2878
2879 // Just build a canonical type that has the right qualifiers.
2880 QualType QualifiedCanonToPointee
2881 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2882
2883 if (isa<ObjCObjectPointerType>(ToType))
2884 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2885 return Context.getPointerType(QualifiedCanonToPointee);
2886}
2887
2889 bool InOverloadResolution,
2890 ASTContext &Context) {
2891 // Handle value-dependent integral null pointer constants correctly.
2892 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2893 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2895 return !InOverloadResolution;
2896
2897 return Expr->isNullPointerConstant(Context,
2898 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2900}
2901
2903 bool InOverloadResolution,
2904 QualType& ConvertedType,
2905 bool &IncompatibleObjC) {
2906 IncompatibleObjC = false;
2907 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2908 IncompatibleObjC))
2909 return true;
2910
2911 // Conversion from a null pointer constant to any Objective-C pointer type.
2912 if (ToType->isObjCObjectPointerType() &&
2913 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2914 ConvertedType = ToType;
2915 return true;
2916 }
2917
2918 // Blocks: Block pointers can be converted to void*.
2919 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2920 ToType->castAs<PointerType>()->getPointeeType()->isVoidType()) {
2921 ConvertedType = ToType;
2922 return true;
2923 }
2924 // Blocks: A null pointer constant can be converted to a block
2925 // pointer type.
2926 if (ToType->isBlockPointerType() &&
2927 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2928 ConvertedType = ToType;
2929 return true;
2930 }
2931
2932 // If the left-hand-side is nullptr_t, the right side can be a null
2933 // pointer constant.
2934 if (ToType->isNullPtrType() &&
2935 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2936 ConvertedType = ToType;
2937 return true;
2938 }
2939
2940 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2941 if (!ToTypePtr)
2942 return false;
2943
2944 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2945 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2946 ConvertedType = ToType;
2947 return true;
2948 }
2949
2950 // Beyond this point, both types need to be pointers
2951 // , including objective-c pointers.
2952 QualType ToPointeeType = ToTypePtr->getPointeeType();
2953 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2954 !getLangOpts().ObjCAutoRefCount) {
2955 ConvertedType = BuildSimilarlyQualifiedPointerType(
2956 FromType->castAs<ObjCObjectPointerType>(), ToPointeeType, ToType,
2957 Context);
2958 return true;
2959 }
2960 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2961 if (!FromTypePtr)
2962 return false;
2963
2964 QualType FromPointeeType = FromTypePtr->getPointeeType();
2965
2966 // If the unqualified pointee types are the same, this can't be a
2967 // pointer conversion, so don't do all of the work below.
2968 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2969 return false;
2970
2971 // An rvalue of type "pointer to cv T," where T is an object type,
2972 // can be converted to an rvalue of type "pointer to cv void" (C++
2973 // 4.10p2).
2974 if (FromPointeeType->isIncompleteOrObjectType() &&
2975 ToPointeeType->isVoidType()) {
2976 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2977 ToPointeeType,
2978 ToType, Context,
2979 /*StripObjCLifetime=*/true);
2980 return true;
2981 }
2982
2983 // MSVC allows implicit function to void* type conversion.
2984 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2985 ToPointeeType->isVoidType()) {
2986 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2987 ToPointeeType,
2988 ToType, Context);
2989 return true;
2990 }
2991
2992 // When we're overloading in C, we allow a special kind of pointer
2993 // conversion for compatible-but-not-identical pointee types.
2994 if (!getLangOpts().CPlusPlus &&
2995 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2996 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2997 ToPointeeType,
2998 ToType, Context);
2999 return true;
3000 }
3001
3002 // C++ [conv.ptr]p3:
3003 //
3004 // An rvalue of type "pointer to cv D," where D is a class type,
3005 // can be converted to an rvalue of type "pointer to cv B," where
3006 // B is a base class (clause 10) of D. If B is an inaccessible
3007 // (clause 11) or ambiguous (10.2) base class of D, a program that
3008 // necessitates this conversion is ill-formed. The result of the
3009 // conversion is a pointer to the base class sub-object of the
3010 // derived class object. The null pointer value is converted to
3011 // the null pointer value of the destination type.
3012 //
3013 // Note that we do not check for ambiguity or inaccessibility
3014 // here. That is handled by CheckPointerConversion.
3015 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
3016 ToPointeeType->isRecordType() &&
3017 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
3018 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
3019 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3020 ToPointeeType,
3021 ToType, Context);
3022 return true;
3023 }
3024
3025 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
3026 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
3027 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
3028 ToPointeeType,
3029 ToType, Context);
3030 return true;
3031 }
3032
3033 return false;
3034}
3035
3036/// Adopt the given qualifiers for the given type.
3038 Qualifiers TQs = T.getQualifiers();
3039
3040 // Check whether qualifiers already match.
3041 if (TQs == Qs)
3042 return T;
3043
3044 if (Qs.compatiblyIncludes(TQs, Context))
3045 return Context.getQualifiedType(T, Qs);
3046
3047 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
3048}
3049
3051 QualType& ConvertedType,
3052 bool &IncompatibleObjC) {
3053 if (!getLangOpts().ObjC)
3054 return false;
3055
3056 // The set of qualifiers on the type we're converting from.
3057 Qualifiers FromQualifiers = FromType.getQualifiers();
3058
3059 // First, we handle all conversions on ObjC object pointer types.
3060 const ObjCObjectPointerType* ToObjCPtr =
3061 ToType->getAs<ObjCObjectPointerType>();
3062 const ObjCObjectPointerType *FromObjCPtr =
3063 FromType->getAs<ObjCObjectPointerType>();
3064
3065 if (ToObjCPtr && FromObjCPtr) {
3066 // If the pointee types are the same (ignoring qualifications),
3067 // then this is not a pointer conversion.
3068 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
3069 FromObjCPtr->getPointeeType()))
3070 return false;
3071
3072 // Conversion between Objective-C pointers.
3073 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
3074 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
3075 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
3076 if (getLangOpts().CPlusPlus && LHS && RHS &&
3078 FromObjCPtr->getPointeeType(), getASTContext()))
3079 return false;
3080 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3081 ToObjCPtr->getPointeeType(),
3082 ToType, Context);
3083 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3084 return true;
3085 }
3086
3087 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
3088 // Okay: this is some kind of implicit downcast of Objective-C
3089 // interfaces, which is permitted. However, we're going to
3090 // complain about it.
3091 IncompatibleObjC = true;
3092 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
3093 ToObjCPtr->getPointeeType(),
3094 ToType, Context);
3095 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3096 return true;
3097 }
3098 }
3099 // Beyond this point, both types need to be C pointers or block pointers.
3100 QualType ToPointeeType;
3101 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
3102 ToPointeeType = ToCPtr->getPointeeType();
3103 else if (const BlockPointerType *ToBlockPtr =
3104 ToType->getAs<BlockPointerType>()) {
3105 // Objective C++: We're able to convert from a pointer to any object
3106 // to a block pointer type.
3107 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
3108 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3109 return true;
3110 }
3111 ToPointeeType = ToBlockPtr->getPointeeType();
3112 }
3113 else if (FromType->getAs<BlockPointerType>() &&
3114 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
3115 // Objective C++: We're able to convert from a block pointer type to a
3116 // pointer to any object.
3117 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3118 return true;
3119 }
3120 else
3121 return false;
3122
3123 QualType FromPointeeType;
3124 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
3125 FromPointeeType = FromCPtr->getPointeeType();
3126 else if (const BlockPointerType *FromBlockPtr =
3127 FromType->getAs<BlockPointerType>())
3128 FromPointeeType = FromBlockPtr->getPointeeType();
3129 else
3130 return false;
3131
3132 // If we have pointers to pointers, recursively check whether this
3133 // is an Objective-C conversion.
3134 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
3135 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3136 IncompatibleObjC)) {
3137 // We always complain about this conversion.
3138 IncompatibleObjC = true;
3139 ConvertedType = Context.getPointerType(ConvertedType);
3140 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3141 return true;
3142 }
3143 // Allow conversion of pointee being objective-c pointer to another one;
3144 // as in I* to id.
3145 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
3146 ToPointeeType->getAs<ObjCObjectPointerType>() &&
3147 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
3148 IncompatibleObjC)) {
3149
3150 ConvertedType = Context.getPointerType(ConvertedType);
3151 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
3152 return true;
3153 }
3154
3155 // If we have pointers to functions or blocks, check whether the only
3156 // differences in the argument and result types are in Objective-C
3157 // pointer conversions. If so, we permit the conversion (but
3158 // complain about it).
3159 const FunctionProtoType *FromFunctionType
3160 = FromPointeeType->getAs<FunctionProtoType>();
3161 const FunctionProtoType *ToFunctionType
3162 = ToPointeeType->getAs<FunctionProtoType>();
3163 if (FromFunctionType && ToFunctionType) {
3164 // If the function types are exactly the same, this isn't an
3165 // Objective-C pointer conversion.
3166 if (Context.getCanonicalType(FromPointeeType)
3167 == Context.getCanonicalType(ToPointeeType))
3168 return false;
3169
3170 // Perform the quick checks that will tell us whether these
3171 // function types are obviously different.
3172 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3173 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
3174 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
3175 return false;
3176
3177 bool HasObjCConversion = false;
3178 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
3179 Context.getCanonicalType(ToFunctionType->getReturnType())) {
3180 // Okay, the types match exactly. Nothing to do.
3181 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
3182 ToFunctionType->getReturnType(),
3183 ConvertedType, IncompatibleObjC)) {
3184 // Okay, we have an Objective-C pointer conversion.
3185 HasObjCConversion = true;
3186 } else {
3187 // Function types are too different. Abort.
3188 return false;
3189 }
3190
3191 // Check argument types.
3192 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3193 ArgIdx != NumArgs; ++ArgIdx) {
3194 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3195 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3196 if (Context.getCanonicalType(FromArgType)
3197 == Context.getCanonicalType(ToArgType)) {
3198 // Okay, the types match exactly. Nothing to do.
3199 } else if (isObjCPointerConversion(FromArgType, ToArgType,
3200 ConvertedType, IncompatibleObjC)) {
3201 // Okay, we have an Objective-C pointer conversion.
3202 HasObjCConversion = true;
3203 } else {
3204 // Argument types are too different. Abort.
3205 return false;
3206 }
3207 }
3208
3209 if (HasObjCConversion) {
3210 // We had an Objective-C conversion. Allow this pointer
3211 // conversion, but complain about it.
3212 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
3213 IncompatibleObjC = true;
3214 return true;
3215 }
3216 }
3217
3218 return false;
3219}
3220
3222 QualType& ConvertedType) {
3223 QualType ToPointeeType;
3224 if (const BlockPointerType *ToBlockPtr =
3225 ToType->getAs<BlockPointerType>())
3226 ToPointeeType = ToBlockPtr->getPointeeType();
3227 else
3228 return false;
3229
3230 QualType FromPointeeType;
3231 if (const BlockPointerType *FromBlockPtr =
3232 FromType->getAs<BlockPointerType>())
3233 FromPointeeType = FromBlockPtr->getPointeeType();
3234 else
3235 return false;
3236 // We have pointer to blocks, check whether the only
3237 // differences in the argument and result types are in Objective-C
3238 // pointer conversions. If so, we permit the conversion.
3239
3240 const FunctionProtoType *FromFunctionType
3241 = FromPointeeType->getAs<FunctionProtoType>();
3242 const FunctionProtoType *ToFunctionType
3243 = ToPointeeType->getAs<FunctionProtoType>();
3244
3245 if (!FromFunctionType || !ToFunctionType)
3246 return false;
3247
3248 if (Context.hasSameType(FromPointeeType, ToPointeeType))
3249 return true;
3250
3251 // Perform the quick checks that will tell us whether these
3252 // function types are obviously different.
3253 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
3254 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
3255 return false;
3256
3257 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
3258 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
3259 if (FromEInfo != ToEInfo)
3260 return false;
3261
3262 bool IncompatibleObjC = false;
3263 if (Context.hasSameType(FromFunctionType->getReturnType(),
3264 ToFunctionType->getReturnType())) {
3265 // Okay, the types match exactly. Nothing to do.
3266 } else {
3267 QualType RHS = FromFunctionType->getReturnType();
3268 QualType LHS = ToFunctionType->getReturnType();
3269 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
3270 !RHS.hasQualifiers() && LHS.hasQualifiers())
3271 LHS = LHS.getUnqualifiedType();
3272
3273 if (Context.hasSameType(RHS,LHS)) {
3274 // OK exact match.
3275 } else if (isObjCPointerConversion(RHS, LHS,
3276 ConvertedType, IncompatibleObjC)) {
3277 if (IncompatibleObjC)
3278 return false;
3279 // Okay, we have an Objective-C pointer conversion.
3280 }
3281 else
3282 return false;
3283 }
3284
3285 // Check argument types.
3286 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
3287 ArgIdx != NumArgs; ++ArgIdx) {
3288 IncompatibleObjC = false;
3289 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
3290 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
3291 if (Context.hasSameType(FromArgType, ToArgType)) {
3292 // Okay, the types match exactly. Nothing to do.
3293 } else if (isObjCPointerConversion(ToArgType, FromArgType,
3294 ConvertedType, IncompatibleObjC)) {
3295 if (IncompatibleObjC)
3296 return false;
3297 // Okay, we have an Objective-C pointer conversion.
3298 } else
3299 // Argument types are too different. Abort.
3300 return false;
3301 }
3302
3304 bool CanUseToFPT, CanUseFromFPT;
3305 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
3306 CanUseToFPT, CanUseFromFPT,
3307 NewParamInfos))
3308 return false;
3309
3310 ConvertedType = ToType;
3311 return true;
3312}
3313
3314enum {
3322};
3323
3324/// Attempts to get the FunctionProtoType from a Type. Handles
3325/// MemberFunctionPointers properly.
3327 if (auto *FPT = FromType->getAs<FunctionProtoType>())
3328 return FPT;
3329
3330 if (auto *MPT = FromType->getAs<MemberPointerType>())
3331 return MPT->getPointeeType()->getAs<FunctionProtoType>();
3332
3333 return nullptr;
3334}
3335
3337 QualType FromType, QualType ToType) {
3338 // If either type is not valid, include no extra info.
3339 if (FromType.isNull() || ToType.isNull()) {
3340 PDiag << ft_default;
3341 return;
3342 }
3343
3344 // Get the function type from the pointers.
3345 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
3346 const auto *FromMember = FromType->castAs<MemberPointerType>(),
3347 *ToMember = ToType->castAs<MemberPointerType>();
3348 if (!declaresSameEntity(FromMember->getMostRecentCXXRecordDecl(),
3349 ToMember->getMostRecentCXXRecordDecl())) {
3351 if (ToMember->isSugared())
3352 PDiag << Context.getCanonicalTagType(
3353 ToMember->getMostRecentCXXRecordDecl());
3354 else
3355 PDiag << ToMember->getQualifier();
3356 if (FromMember->isSugared())
3357 PDiag << Context.getCanonicalTagType(
3358 FromMember->getMostRecentCXXRecordDecl());
3359 else
3360 PDiag << FromMember->getQualifier();
3361 return;
3362 }
3363 FromType = FromMember->getPointeeType();
3364 ToType = ToMember->getPointeeType();
3365 }
3366
3367 if (FromType->isPointerType())
3368 FromType = FromType->getPointeeType();
3369 if (ToType->isPointerType())
3370 ToType = ToType->getPointeeType();
3371
3372 // Remove references.
3373 FromType = FromType.getNonReferenceType();
3374 ToType = ToType.getNonReferenceType();
3375
3376 // Don't print extra info for non-specialized template functions.
3377 if (FromType->isInstantiationDependentType() &&
3378 !FromType->getAs<TemplateSpecializationType>()) {
3379 PDiag << ft_default;
3380 return;
3381 }
3382
3383 // No extra info for same types.
3384 if (Context.hasSameType(FromType, ToType)) {
3385 PDiag << ft_default;
3386 return;
3387 }
3388
3389 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
3390 *ToFunction = tryGetFunctionProtoType(ToType);
3391
3392 // Both types need to be function types.
3393 if (!FromFunction || !ToFunction) {
3394 PDiag << ft_default;
3395 return;
3396 }
3397
3398 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
3399 PDiag << ft_parameter_arity << ToFunction->getNumParams()
3400 << FromFunction->getNumParams();
3401 return;
3402 }
3403
3404 // Handle different parameter types.
3405 unsigned ArgPos;
3406 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
3407 PDiag << ft_parameter_mismatch << ArgPos + 1
3408 << ToFunction->getParamType(ArgPos)
3409 << FromFunction->getParamType(ArgPos);
3410 return;
3411 }
3412
3413 // Handle different return type.
3414 if (!Context.hasSameType(FromFunction->getReturnType(),
3415 ToFunction->getReturnType())) {
3416 PDiag << ft_return_type << ToFunction->getReturnType()
3417 << FromFunction->getReturnType();
3418 return;
3419 }
3420
3421 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
3422 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
3423 << FromFunction->getMethodQuals();
3424 return;
3425 }
3426
3427 // Handle exception specification differences on canonical type (in C++17
3428 // onwards).
3430 ->isNothrow() !=
3431 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
3432 ->isNothrow()) {
3433 PDiag << ft_noexcept;
3434 return;
3435 }
3436
3437 // Unable to find a difference, so add no extra info.
3438 PDiag << ft_default;
3439}
3440
3442 ArrayRef<QualType> New, unsigned *ArgPos,
3443 bool Reversed) {
3444 assert(llvm::size(Old) == llvm::size(New) &&
3445 "Can't compare parameters of functions with different number of "
3446 "parameters!");
3447
3448 for (auto &&[Idx, Type] : llvm::enumerate(Old)) {
3449 // Reverse iterate over the parameters of `OldType` if `Reversed` is true.
3450 size_t J = Reversed ? (llvm::size(New) - Idx - 1) : Idx;
3451
3452 // Ignore address spaces in pointee type. This is to disallow overloading
3453 // on __ptr32/__ptr64 address spaces.
3454 QualType OldType =
3455 Context.removePtrSizeAddrSpace(Type.getUnqualifiedType());
3456 QualType NewType =
3457 Context.removePtrSizeAddrSpace((New.begin() + J)->getUnqualifiedType());
3458
3459 if (!Context.hasSameType(OldType, NewType)) {
3460 if (ArgPos)
3461 *ArgPos = Idx;
3462 return false;
3463 }
3464 }
3465 return true;
3466}
3467
3469 const FunctionProtoType *NewType,
3470 unsigned *ArgPos, bool Reversed) {
3471 return FunctionParamTypesAreEqual(OldType->param_types(),
3472 NewType->param_types(), ArgPos, Reversed);
3473}
3474
3476 const FunctionDecl *NewFunction,
3477 unsigned *ArgPos,
3478 bool Reversed) {
3479
3480 if (OldFunction->getNumNonObjectParams() !=
3481 NewFunction->getNumNonObjectParams())
3482 return false;
3483
3484 unsigned OldIgnore =
3486 unsigned NewIgnore =
3488
3489 auto *OldPT = cast<FunctionProtoType>(OldFunction->getFunctionType());
3490 auto *NewPT = cast<FunctionProtoType>(NewFunction->getFunctionType());
3491
3492 return FunctionParamTypesAreEqual(OldPT->param_types().slice(OldIgnore),
3493 NewPT->param_types().slice(NewIgnore),
3494 ArgPos, Reversed);
3495}
3496
3498 CastKind &Kind,
3499 CXXCastPath& BasePath,
3500 bool IgnoreBaseAccess,
3501 bool Diagnose) {
3502 QualType FromType = From->getType();
3503 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
3504
3505 Kind = CK_BitCast;
3506
3507 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
3510 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
3511 DiagRuntimeBehavior(From->getExprLoc(), From,
3512 PDiag(diag::warn_impcast_bool_to_null_pointer)
3513 << ToType << From->getSourceRange());
3514 else if (!isUnevaluatedContext())
3515 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
3516 << ToType << From->getSourceRange();
3517 }
3518 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
3519 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
3520 QualType FromPointeeType = FromPtrType->getPointeeType(),
3521 ToPointeeType = ToPtrType->getPointeeType();
3522
3523 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
3524 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
3525 // We must have a derived-to-base conversion. Check an
3526 // ambiguous or inaccessible conversion.
3527 unsigned InaccessibleID = 0;
3528 unsigned AmbiguousID = 0;
3529 if (Diagnose) {
3530 InaccessibleID = diag::err_upcast_to_inaccessible_base;
3531 AmbiguousID = diag::err_ambiguous_derived_to_base_conv;
3532 }
3534 FromPointeeType, ToPointeeType, InaccessibleID, AmbiguousID,
3535 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
3536 &BasePath, IgnoreBaseAccess))
3537 return true;
3538
3539 // The conversion was successful.
3540 Kind = CK_DerivedToBase;
3541 }
3542
3543 if (Diagnose && !IsCStyleOrFunctionalCast &&
3544 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
3545 assert(getLangOpts().MSVCCompat &&
3546 "this should only be possible with MSVCCompat!");
3547 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
3548 << From->getSourceRange();
3549 }
3550 }
3551 } else if (const ObjCObjectPointerType *ToPtrType =
3552 ToType->getAs<ObjCObjectPointerType>()) {
3553 if (const ObjCObjectPointerType *FromPtrType =
3554 FromType->getAs<ObjCObjectPointerType>()) {
3555 // Objective-C++ conversions are always okay.
3556 // FIXME: We should have a different class of conversions for the
3557 // Objective-C++ implicit conversions.
3558 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
3559 return false;
3560 } else if (FromType->isBlockPointerType()) {
3561 Kind = CK_BlockPointerToObjCPointerCast;
3562 } else {
3563 Kind = CK_CPointerToObjCPointerCast;
3564 }
3565 } else if (ToType->isBlockPointerType()) {
3566 if (!FromType->isBlockPointerType())
3567 Kind = CK_AnyPointerToBlockPointerCast;
3568 }
3569
3570 // We shouldn't fall into this case unless it's valid for other
3571 // reasons.
3573 Kind = CK_NullToPointer;
3574
3575 return false;
3576}
3577
3579 QualType ToType,
3580 bool InOverloadResolution,
3581 QualType &ConvertedType) {
3582 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
3583 if (!ToTypePtr)
3584 return false;
3585
3586 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3588 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3590 ConvertedType = ToType;
3591 return true;
3592 }
3593
3594 // Otherwise, both types have to be member pointers.
3595 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3596 if (!FromTypePtr)
3597 return false;
3598
3599 // A pointer to member of B can be converted to a pointer to member of D,
3600 // where D is derived from B (C++ 4.11p2).
3601 CXXRecordDecl *FromClass = FromTypePtr->getMostRecentCXXRecordDecl();
3602 CXXRecordDecl *ToClass = ToTypePtr->getMostRecentCXXRecordDecl();
3603
3604 if (!declaresSameEntity(FromClass, ToClass) &&
3605 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3606 ConvertedType = Context.getMemberPointerType(
3607 FromTypePtr->getPointeeType(), FromTypePtr->getQualifier(), ToClass);
3608 return true;
3609 }
3610
3611 return false;
3612}
3613
3615 QualType FromType, const MemberPointerType *ToPtrType, CastKind &Kind,
3616 CXXCastPath &BasePath, SourceLocation CheckLoc, SourceRange OpRange,
3617 bool IgnoreBaseAccess, MemberPointerConversionDirection Direction) {
3618 // Lock down the inheritance model right now in MS ABI, whether or not the
3619 // pointee types are the same.
3620 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3621 (void)isCompleteType(CheckLoc, FromType);
3622 (void)isCompleteType(CheckLoc, QualType(ToPtrType, 0));
3623 }
3624
3625 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3626 if (!FromPtrType) {
3627 // This must be a null pointer to member pointer conversion
3628 Kind = CK_NullToMemberPointer;
3630 }
3631
3632 // T == T, modulo cv
3634 !Context.hasSameUnqualifiedType(FromPtrType->getPointeeType(),
3635 ToPtrType->getPointeeType()))
3637
3638 CXXRecordDecl *FromClass = FromPtrType->getMostRecentCXXRecordDecl(),
3639 *ToClass = ToPtrType->getMostRecentCXXRecordDecl();
3640
3641 auto DiagCls = [&](PartialDiagnostic &PD, NestedNameSpecifier Qual,
3642 const CXXRecordDecl *Cls) {
3643 if (declaresSameEntity(Qual.getAsRecordDecl(), Cls))
3644 PD << Qual;
3645 else
3646 PD << Context.getCanonicalTagType(Cls);
3647 };
3648 auto DiagFromTo = [&](PartialDiagnostic &PD) -> PartialDiagnostic & {
3649 DiagCls(PD, FromPtrType->getQualifier(), FromClass);
3650 DiagCls(PD, ToPtrType->getQualifier(), ToClass);
3651 return PD;
3652 };
3653
3654 CXXRecordDecl *Base = FromClass, *Derived = ToClass;
3656 std::swap(Base, Derived);
3657
3658 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3659 /*DetectVirtual=*/true);
3660 if (!IsDerivedFrom(OpRange.getBegin(), Derived, Base, Paths))
3662
3663 if (Paths.isAmbiguous(Context.getCanonicalTagType(Base))) {
3664 PartialDiagnostic PD = PDiag(diag::err_ambiguous_memptr_conv);
3665 PD << int(Direction);
3666 DiagFromTo(PD) << getAmbiguousPathsDisplayString(Paths) << OpRange;
3667 Diag(CheckLoc, PD);
3669 }
3670
3671 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3672 PartialDiagnostic PD = PDiag(diag::err_memptr_conv_via_virtual);
3673 DiagFromTo(PD) << QualType(VBase, 0) << OpRange;
3674 Diag(CheckLoc, PD);
3676 }
3677
3678 // Must be a base to derived member conversion.
3679 BuildBasePathArray(Paths, BasePath);
3681 ? CK_DerivedToBaseMemberPointer
3682 : CK_BaseToDerivedMemberPointer;
3683
3684 if (!IgnoreBaseAccess)
3685 switch (CheckBaseClassAccess(
3686 CheckLoc, Base, Derived, Paths.front(),
3688 ? diag::err_upcast_to_inaccessible_base
3689 : diag::err_downcast_from_inaccessible_base,
3690 [&](PartialDiagnostic &PD) {
3691 NestedNameSpecifier BaseQual = FromPtrType->getQualifier(),
3692 DerivedQual = ToPtrType->getQualifier();
3693 if (Direction == MemberPointerConversionDirection::Upcast)
3694 std::swap(BaseQual, DerivedQual);
3695 DiagCls(PD, DerivedQual, Derived);
3696 DiagCls(PD, BaseQual, Base);
3697 })) {
3699 case Sema::AR_delayed:
3700 case Sema::AR_dependent:
3701 // Optimistically assume that the delayed and dependent cases
3702 // will work out.
3703 break;
3704
3707 }
3708
3710}
3711
3712/// Determine whether the lifetime conversion between the two given
3713/// qualifiers sets is nontrivial.
3715 Qualifiers ToQuals) {
3716 // Converting anything to const __unsafe_unretained is trivial.
3717 if (ToQuals.hasConst() &&
3719 return false;
3720
3721 return true;
3722}
3723
3724/// Perform a single iteration of the loop for checking if a qualification
3725/// conversion is valid.
3726///
3727/// Specifically, check whether any change between the qualifiers of \p
3728/// FromType and \p ToType is permissible, given knowledge about whether every
3729/// outer layer is const-qualified.
3731 bool CStyle, bool IsTopLevel,
3732 bool &PreviousToQualsIncludeConst,
3733 bool &ObjCLifetimeConversion,
3734 const ASTContext &Ctx) {
3735 Qualifiers FromQuals = FromType.getQualifiers();
3736 Qualifiers ToQuals = ToType.getQualifiers();
3737
3738 // Ignore __unaligned qualifier.
3739 FromQuals.removeUnaligned();
3740
3741 // Objective-C ARC:
3742 // Check Objective-C lifetime conversions.
3743 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime()) {
3744 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3745 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3746 ObjCLifetimeConversion = true;
3747 FromQuals.removeObjCLifetime();
3748 ToQuals.removeObjCLifetime();
3749 } else {
3750 // Qualification conversions cannot cast between different
3751 // Objective-C lifetime qualifiers.
3752 return false;
3753 }
3754 }
3755
3756 // Allow addition/removal of GC attributes but not changing GC attributes.
3757 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3758 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3759 FromQuals.removeObjCGCAttr();
3760 ToQuals.removeObjCGCAttr();
3761 }
3762
3763 // __ptrauth qualifiers must match exactly.
3764 if (FromQuals.getPointerAuth() != ToQuals.getPointerAuth())
3765 return false;
3766
3767 // -- for every j > 0, if const is in cv 1,j then const is in cv
3768 // 2,j, and similarly for volatile.
3769 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals, Ctx))
3770 return false;
3771
3772 // If address spaces mismatch:
3773 // - in top level it is only valid to convert to addr space that is a
3774 // superset in all cases apart from C-style casts where we allow
3775 // conversions between overlapping address spaces.
3776 // - in non-top levels it is not a valid conversion.
3777 if (ToQuals.getAddressSpace() != FromQuals.getAddressSpace() &&
3778 (!IsTopLevel ||
3779 !(ToQuals.isAddressSpaceSupersetOf(FromQuals, Ctx) ||
3780 (CStyle && FromQuals.isAddressSpaceSupersetOf(ToQuals, Ctx)))))
3781 return false;
3782
3783 // -- if the cv 1,j and cv 2,j are different, then const is in
3784 // every cv for 0 < k < j.
3785 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers() &&
3786 !PreviousToQualsIncludeConst)
3787 return false;
3788
3789 // The following wording is from C++20, where the result of the conversion
3790 // is T3, not T2.
3791 // -- if [...] P1,i [...] is "array of unknown bound of", P3,i is
3792 // "array of unknown bound of"
3793 if (FromType->isIncompleteArrayType() && !ToType->isIncompleteArrayType())
3794 return false;
3795
3796 // -- if the resulting P3,i is different from P1,i [...], then const is
3797 // added to every cv 3_k for 0 < k < i.
3798 if (!CStyle && FromType->isConstantArrayType() &&
3799 ToType->isIncompleteArrayType() && !PreviousToQualsIncludeConst)
3800 return false;
3801
3802 // Keep track of whether all prior cv-qualifiers in the "to" type
3803 // include const.
3804 PreviousToQualsIncludeConst =
3805 PreviousToQualsIncludeConst && ToQuals.hasConst();
3806 return true;
3807}
3808
3809bool
3811 bool CStyle, bool &ObjCLifetimeConversion) {
3812 FromType = Context.getCanonicalType(FromType);
3813 ToType = Context.getCanonicalType(ToType);
3814 ObjCLifetimeConversion = false;
3815
3816 // If FromType and ToType are the same type, this is not a
3817 // qualification conversion.
3818 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3819 return false;
3820
3821 // (C++ 4.4p4):
3822 // A conversion can add cv-qualifiers at levels other than the first
3823 // in multi-level pointers, subject to the following rules: [...]
3824 bool PreviousToQualsIncludeConst = true;
3825 bool UnwrappedAnyPointer = false;
3826 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3827 if (!isQualificationConversionStep(FromType, ToType, CStyle,
3828 !UnwrappedAnyPointer,
3829 PreviousToQualsIncludeConst,
3830 ObjCLifetimeConversion, getASTContext()))
3831 return false;
3832 UnwrappedAnyPointer = true;
3833 }
3834
3835 // We are left with FromType and ToType being the pointee types
3836 // after unwrapping the original FromType and ToType the same number
3837 // of times. If we unwrapped any pointers, and if FromType and
3838 // ToType have the same unqualified type (since we checked
3839 // qualifiers above), then this is a qualification conversion.
3840 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3841}
3842
3843/// - Determine whether this is a conversion from a scalar type to an
3844/// atomic type.
3845///
3846/// If successful, updates \c SCS's second and third steps in the conversion
3847/// sequence to finish the conversion.
3848static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3849 bool InOverloadResolution,
3851 bool CStyle) {
3852 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3853 if (!ToAtomic)
3854 return false;
3855
3857 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3858 InOverloadResolution, InnerSCS,
3859 CStyle, /*AllowObjCWritebackConversion=*/false))
3860 return false;
3861
3862 SCS.Second = InnerSCS.Second;
3863 SCS.setToType(1, InnerSCS.getToType(1));
3864 SCS.Third = InnerSCS.Third;
3867 SCS.setToType(2, InnerSCS.getToType(2));
3868 return true;
3869}
3870
3873 QualType Type) {
3874 const auto *CtorType = Constructor->getType()->castAs<FunctionProtoType>();
3875 if (CtorType->getNumParams() > 0) {
3876 QualType FirstArg = CtorType->getParamType(0);
3877 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3878 return true;
3879 }
3880 return false;
3881}
3882
3883static OverloadingResult
3885 CXXRecordDecl *To,
3887 OverloadCandidateSet &CandidateSet,
3888 bool AllowExplicit) {
3890 for (auto *D : S.LookupConstructors(To)) {
3891 auto Info = getConstructorInfo(D);
3892 if (!Info)
3893 continue;
3894
3895 bool Usable = !Info.Constructor->isInvalidDecl() &&
3896 S.isInitListConstructor(Info.Constructor);
3897 if (Usable) {
3898 bool SuppressUserConversions = false;
3899 if (Info.ConstructorTmpl)
3900 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3901 /*ExplicitArgs*/ nullptr, From,
3902 CandidateSet, SuppressUserConversions,
3903 /*PartialOverloading*/ false,
3904 AllowExplicit);
3905 else
3906 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3907 CandidateSet, SuppressUserConversions,
3908 /*PartialOverloading*/ false, AllowExplicit);
3909 }
3910 }
3911
3912 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3913
3915 switch (auto Result =
3916 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3917 case OR_Deleted:
3918 case OR_Success: {
3919 // Record the standard conversion we used and the conversion function.
3921 QualType ThisType = Constructor->getFunctionObjectParameterType();
3922 // Initializer lists don't have conversions as such.
3924 User.HadMultipleCandidates = HadMultipleCandidates;
3926 User.FoundConversionFunction = Best->FoundDecl;
3928 User.After.setFromType(ThisType);
3929 User.After.setAllToTypes(ToType);
3930 return Result;
3931 }
3932
3934 return OR_No_Viable_Function;
3935 case OR_Ambiguous:
3936 return OR_Ambiguous;
3937 }
3938
3939 llvm_unreachable("Invalid OverloadResult!");
3940}
3941
3942/// Determines whether there is a user-defined conversion sequence
3943/// (C++ [over.ics.user]) that converts expression From to the type
3944/// ToType. If such a conversion exists, User will contain the
3945/// user-defined conversion sequence that performs such a conversion
3946/// and this routine will return true. Otherwise, this routine returns
3947/// false and User is unspecified.
3948///
3949/// \param AllowExplicit true if the conversion should consider C++0x
3950/// "explicit" conversion functions as well as non-explicit conversion
3951/// functions (C++0x [class.conv.fct]p2).
3952///
3953/// \param AllowObjCConversionOnExplicit true if the conversion should
3954/// allow an extra Objective-C pointer conversion on uses of explicit
3955/// constructors. Requires \c AllowExplicit to also be set.
3956static OverloadingResult
3959 OverloadCandidateSet &CandidateSet,
3960 AllowedExplicit AllowExplicit,
3961 bool AllowObjCConversionOnExplicit) {
3962 assert(AllowExplicit != AllowedExplicit::None ||
3963 !AllowObjCConversionOnExplicit);
3965
3966 // Whether we will only visit constructors.
3967 bool ConstructorsOnly = false;
3968
3969 // If the type we are conversion to is a class type, enumerate its
3970 // constructors.
3971 if (const RecordType *ToRecordType = ToType->getAsCanonical<RecordType>()) {
3972 // C++ [over.match.ctor]p1:
3973 // When objects of class type are direct-initialized (8.5), or
3974 // copy-initialized from an expression of the same or a
3975 // derived class type (8.5), overload resolution selects the
3976 // constructor. [...] For copy-initialization, the candidate
3977 // functions are all the converting constructors (12.3.1) of
3978 // that class. The argument list is the expression-list within
3979 // the parentheses of the initializer.
3980 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3981 (From->getType()->isRecordType() &&
3982 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3983 ConstructorsOnly = true;
3984
3985 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3986 // We're not going to find any constructors.
3987 } else if (auto *ToRecordDecl =
3988 dyn_cast<CXXRecordDecl>(ToRecordType->getOriginalDecl())) {
3989 ToRecordDecl = ToRecordDecl->getDefinitionOrSelf();
3990
3991 Expr **Args = &From;
3992 unsigned NumArgs = 1;
3993 bool ListInitializing = false;
3994 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3995 // But first, see if there is an init-list-constructor that will work.
3997 S, From, ToType, ToRecordDecl, User, CandidateSet,
3998 AllowExplicit == AllowedExplicit::All);
3999 if (Result != OR_No_Viable_Function)
4000 return Result;
4001 // Never mind.
4002 CandidateSet.clear(
4004
4005 // If we're list-initializing, we pass the individual elements as
4006 // arguments, not the entire list.
4007 Args = InitList->getInits();
4008 NumArgs = InitList->getNumInits();
4009 ListInitializing = true;
4010 }
4011
4012 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
4013 auto Info = getConstructorInfo(D);
4014 if (!Info)
4015 continue;
4016
4017 bool Usable = !Info.Constructor->isInvalidDecl();
4018 if (!ListInitializing)
4019 Usable = Usable && Info.Constructor->isConvertingConstructor(
4020 /*AllowExplicit*/ true);
4021 if (Usable) {
4022 bool SuppressUserConversions = !ConstructorsOnly;
4023 // C++20 [over.best.ics.general]/4.5:
4024 // if the target is the first parameter of a constructor [of class
4025 // X] and the constructor [...] is a candidate by [...] the second
4026 // phase of [over.match.list] when the initializer list has exactly
4027 // one element that is itself an initializer list, [...] and the
4028 // conversion is to X or reference to cv X, user-defined conversion
4029 // sequences are not considered.
4030 if (SuppressUserConversions && ListInitializing) {
4031 SuppressUserConversions =
4032 NumArgs == 1 && isa<InitListExpr>(Args[0]) &&
4033 isFirstArgumentCompatibleWithType(S.Context, Info.Constructor,
4034 ToType);
4035 }
4036 if (Info.ConstructorTmpl)
4038 Info.ConstructorTmpl, Info.FoundDecl,
4039 /*ExplicitArgs*/ nullptr, llvm::ArrayRef(Args, NumArgs),
4040 CandidateSet, SuppressUserConversions,
4041 /*PartialOverloading*/ false,
4042 AllowExplicit == AllowedExplicit::All);
4043 else
4044 // Allow one user-defined conversion when user specifies a
4045 // From->ToType conversion via an static cast (c-style, etc).
4046 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
4047 llvm::ArrayRef(Args, NumArgs), CandidateSet,
4048 SuppressUserConversions,
4049 /*PartialOverloading*/ false,
4050 AllowExplicit == AllowedExplicit::All);
4051 }
4052 }
4053 }
4054 }
4055
4056 // Enumerate conversion functions, if we're allowed to.
4057 if (ConstructorsOnly || isa<InitListExpr>(From)) {
4058 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
4059 // No conversion functions from incomplete types.
4060 } else if (const RecordType *FromRecordType =
4061 From->getType()->getAsCanonical<RecordType>()) {
4062 if (auto *FromRecordDecl =
4063 dyn_cast<CXXRecordDecl>(FromRecordType->getOriginalDecl())) {
4064 FromRecordDecl = FromRecordDecl->getDefinitionOrSelf();
4065 // Add all of the conversion functions as candidates.
4066 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
4067 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4068 DeclAccessPair FoundDecl = I.getPair();
4069 NamedDecl *D = FoundDecl.getDecl();
4070 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
4071 if (isa<UsingShadowDecl>(D))
4072 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4073
4074 CXXConversionDecl *Conv;
4075 FunctionTemplateDecl *ConvTemplate;
4076 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
4077 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4078 else
4079 Conv = cast<CXXConversionDecl>(D);
4080
4081 if (ConvTemplate)
4083 ConvTemplate, FoundDecl, ActingContext, From, ToType,
4084 CandidateSet, AllowObjCConversionOnExplicit,
4085 AllowExplicit != AllowedExplicit::None);
4086 else
4087 S.AddConversionCandidate(Conv, FoundDecl, ActingContext, From, ToType,
4088 CandidateSet, AllowObjCConversionOnExplicit,
4089 AllowExplicit != AllowedExplicit::None);
4090 }
4091 }
4092 }
4093
4094 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4095
4097 switch (auto Result =
4098 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
4099 case OR_Success:
4100 case OR_Deleted:
4101 // Record the standard conversion we used and the conversion function.
4103 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
4104 // C++ [over.ics.user]p1:
4105 // If the user-defined conversion is specified by a
4106 // constructor (12.3.1), the initial standard conversion
4107 // sequence converts the source type to the type required by
4108 // the argument of the constructor.
4109 //
4110 if (isa<InitListExpr>(From)) {
4111 // Initializer lists don't have conversions as such.
4113 User.Before.FromBracedInitList = true;
4114 } else {
4115 if (Best->Conversions[0].isEllipsis())
4116 User.EllipsisConversion = true;
4117 else {
4118 User.Before = Best->Conversions[0].Standard;
4119 User.EllipsisConversion = false;
4120 }
4121 }
4122 User.HadMultipleCandidates = HadMultipleCandidates;
4124 User.FoundConversionFunction = Best->FoundDecl;
4126 User.After.setFromType(Constructor->getFunctionObjectParameterType());
4127 User.After.setAllToTypes(ToType);
4128 return Result;
4129 }
4130 if (CXXConversionDecl *Conversion
4131 = dyn_cast<CXXConversionDecl>(Best->Function)) {
4132
4133 assert(Best->HasFinalConversion);
4134
4135 // C++ [over.ics.user]p1:
4136 //
4137 // [...] If the user-defined conversion is specified by a
4138 // conversion function (12.3.2), the initial standard
4139 // conversion sequence converts the source type to the
4140 // implicit object parameter of the conversion function.
4141 User.Before = Best->Conversions[0].Standard;
4142 User.HadMultipleCandidates = HadMultipleCandidates;
4143 User.ConversionFunction = Conversion;
4144 User.FoundConversionFunction = Best->FoundDecl;
4145 User.EllipsisConversion = false;
4146
4147 // C++ [over.ics.user]p2:
4148 // The second standard conversion sequence converts the
4149 // result of the user-defined conversion to the target type
4150 // for the sequence. Since an implicit conversion sequence
4151 // is an initialization, the special rules for
4152 // initialization by user-defined conversion apply when
4153 // selecting the best user-defined conversion for a
4154 // user-defined conversion sequence (see 13.3.3 and
4155 // 13.3.3.1).
4156 User.After = Best->FinalConversion;
4157 return Result;
4158 }
4159 llvm_unreachable("Not a constructor or conversion function?");
4160
4162 return OR_No_Viable_Function;
4163
4164 case OR_Ambiguous:
4165 return OR_Ambiguous;
4166 }
4167
4168 llvm_unreachable("Invalid OverloadResult!");
4169}
4170
4171bool
4174 OverloadCandidateSet CandidateSet(From->getExprLoc(),
4176 OverloadingResult OvResult =
4177 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
4178 CandidateSet, AllowedExplicit::None, false);
4179
4180 if (!(OvResult == OR_Ambiguous ||
4181 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
4182 return false;
4183
4184 auto Cands = CandidateSet.CompleteCandidates(
4185 *this,
4187 From);
4188 if (OvResult == OR_Ambiguous)
4189 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
4190 << From->getType() << ToType << From->getSourceRange();
4191 else { // OR_No_Viable_Function && !CandidateSet.empty()
4192 if (!RequireCompleteType(From->getBeginLoc(), ToType,
4193 diag::err_typecheck_nonviable_condition_incomplete,
4194 From->getType(), From->getSourceRange()))
4195 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
4196 << false << From->getType() << From->getSourceRange() << ToType;
4197 }
4198
4199 CandidateSet.NoteCandidates(
4200 *this, From, Cands);
4201 return true;
4202}
4203
4204// Helper for compareConversionFunctions that gets the FunctionType that the
4205// conversion-operator return value 'points' to, or nullptr.
4206static const FunctionType *
4208 const FunctionType *ConvFuncTy = Conv->getType()->castAs<FunctionType>();
4209 const PointerType *RetPtrTy =
4210 ConvFuncTy->getReturnType()->getAs<PointerType>();
4211
4212 if (!RetPtrTy)
4213 return nullptr;
4214
4215 return RetPtrTy->getPointeeType()->getAs<FunctionType>();
4216}
4217
4218/// Compare the user-defined conversion functions or constructors
4219/// of two user-defined conversion sequences to determine whether any ordering
4220/// is possible.
4223 FunctionDecl *Function2) {
4224 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
4225 CXXConversionDecl *Conv2 = dyn_cast_or_null<CXXConversionDecl>(Function2);
4226 if (!Conv1 || !Conv2)
4228
4229 if (!Conv1->getParent()->isLambda() || !Conv2->getParent()->isLambda())
4231
4232 // Objective-C++:
4233 // If both conversion functions are implicitly-declared conversions from
4234 // a lambda closure type to a function pointer and a block pointer,
4235 // respectively, always prefer the conversion to a function pointer,
4236 // because the function pointer is more lightweight and is more likely
4237 // to keep code working.
4238 if (S.getLangOpts().ObjC && S.getLangOpts().CPlusPlus11) {
4239 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
4240 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
4241 if (Block1 != Block2)
4242 return Block1 ? ImplicitConversionSequence::Worse
4244 }
4245
4246 // In order to support multiple calling conventions for the lambda conversion
4247 // operator (such as when the free and member function calling convention is
4248 // different), prefer the 'free' mechanism, followed by the calling-convention
4249 // of operator(). The latter is in place to support the MSVC-like solution of
4250 // defining ALL of the possible conversions in regards to calling-convention.
4251 const FunctionType *Conv1FuncRet = getConversionOpReturnTyAsFunction(Conv1);
4252 const FunctionType *Conv2FuncRet = getConversionOpReturnTyAsFunction(Conv2);
4253
4254 if (Conv1FuncRet && Conv2FuncRet &&
4255 Conv1FuncRet->getCallConv() != Conv2FuncRet->getCallConv()) {
4256 CallingConv Conv1CC = Conv1FuncRet->getCallConv();
4257 CallingConv Conv2CC = Conv2FuncRet->getCallConv();
4258
4259 CXXMethodDecl *CallOp = Conv2->getParent()->getLambdaCallOperator();
4260 const auto *CallOpProto = CallOp->getType()->castAs<FunctionProtoType>();
4261
4262 CallingConv CallOpCC =
4263 CallOp->getType()->castAs<FunctionType>()->getCallConv();
4265 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
4267 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
4268
4269 CallingConv PrefOrder[] = {DefaultFree, DefaultMember, CallOpCC};
4270 for (CallingConv CC : PrefOrder) {
4271 if (Conv1CC == CC)
4273 if (Conv2CC == CC)
4275 }
4276 }
4277
4279}
4280
4287
4288/// CompareImplicitConversionSequences - Compare two implicit
4289/// conversion sequences to determine whether one is better than the
4290/// other or if they are indistinguishable (C++ 13.3.3.2).
4293 const ImplicitConversionSequence& ICS1,
4294 const ImplicitConversionSequence& ICS2)
4295{
4296 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
4297 // conversion sequences (as defined in 13.3.3.1)
4298 // -- a standard conversion sequence (13.3.3.1.1) is a better
4299 // conversion sequence than a user-defined conversion sequence or
4300 // an ellipsis conversion sequence, and
4301 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
4302 // conversion sequence than an ellipsis conversion sequence
4303 // (13.3.3.1.3).
4304 //
4305 // C++0x [over.best.ics]p10:
4306 // For the purpose of ranking implicit conversion sequences as
4307 // described in 13.3.3.2, the ambiguous conversion sequence is
4308 // treated as a user-defined sequence that is indistinguishable
4309 // from any other user-defined conversion sequence.
4310
4311 // String literal to 'char *' conversion has been deprecated in C++03. It has
4312 // been removed from C++11. We still accept this conversion, if it happens at
4313 // the best viable function. Otherwise, this conversion is considered worse
4314 // than ellipsis conversion. Consider this as an extension; this is not in the
4315 // standard. For example:
4316 //
4317 // int &f(...); // #1
4318 // void f(char*); // #2
4319 // void g() { int &r = f("foo"); }
4320 //
4321 // In C++03, we pick #2 as the best viable function.
4322 // In C++11, we pick #1 as the best viable function, because ellipsis
4323 // conversion is better than string-literal to char* conversion (since there
4324 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
4325 // convert arguments, #2 would be the best viable function in C++11.
4326 // If the best viable function has this conversion, a warning will be issued
4327 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
4328
4329 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
4332 // Ill-formedness must not differ
4333 ICS1.isBad() == ICS2.isBad())
4337
4338 if (ICS1.getKindRank() < ICS2.getKindRank())
4340 if (ICS2.getKindRank() < ICS1.getKindRank())
4342
4343 // The following checks require both conversion sequences to be of
4344 // the same kind.
4345 if (ICS1.getKind() != ICS2.getKind())
4347
4350
4351 // Two implicit conversion sequences of the same form are
4352 // indistinguishable conversion sequences unless one of the
4353 // following rules apply: (C++ 13.3.3.2p3):
4354
4355 // List-initialization sequence L1 is a better conversion sequence than
4356 // list-initialization sequence L2 if:
4357 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
4358 // if not that,
4359 // — L1 and L2 convert to arrays of the same element type, and either the
4360 // number of elements n_1 initialized by L1 is less than the number of
4361 // elements n_2 initialized by L2, or (C++20) n_1 = n_2 and L2 converts to
4362 // an array of unknown bound and L1 does not,
4363 // even if one of the other rules in this paragraph would otherwise apply.
4364 if (!ICS1.isBad()) {
4365 bool StdInit1 = false, StdInit2 = false;
4368 nullptr);
4371 nullptr);
4372 if (StdInit1 != StdInit2)
4373 return StdInit1 ? ImplicitConversionSequence::Better
4375
4378 if (auto *CAT1 = S.Context.getAsConstantArrayType(
4380 if (auto *CAT2 = S.Context.getAsConstantArrayType(
4382 if (S.Context.hasSameUnqualifiedType(CAT1->getElementType(),
4383 CAT2->getElementType())) {
4384 // Both to arrays of the same element type
4385 if (CAT1->getSize() != CAT2->getSize())
4386 // Different sized, the smaller wins
4387 return CAT1->getSize().ult(CAT2->getSize())
4392 // One is incomplete, it loses
4396 }
4397 }
4398 }
4399
4400 if (ICS1.isStandard())
4401 // Standard conversion sequence S1 is a better conversion sequence than
4402 // standard conversion sequence S2 if [...]
4403 Result = CompareStandardConversionSequences(S, Loc,
4404 ICS1.Standard, ICS2.Standard);
4405 else if (ICS1.isUserDefined()) {
4406 // User-defined conversion sequence U1 is a better conversion
4407 // sequence than another user-defined conversion sequence U2 if
4408 // they contain the same user-defined conversion function or
4409 // constructor and if the second standard conversion sequence of
4410 // U1 is better than the second standard conversion sequence of
4411 // U2 (C++ 13.3.3.2p3).
4414 Result = CompareStandardConversionSequences(S, Loc,
4415 ICS1.UserDefined.After,
4416 ICS2.UserDefined.After);
4417 else
4418 Result = compareConversionFunctions(S,
4421 }
4422
4423 return Result;
4424}
4425
4426// Per 13.3.3.2p3, compare the given standard conversion sequences to
4427// determine if one is a proper subset of the other.
4430 const StandardConversionSequence& SCS1,
4431 const StandardConversionSequence& SCS2) {
4434
4435 // the identity conversion sequence is considered to be a subsequence of
4436 // any non-identity conversion sequence
4437 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
4439 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
4441
4442 if (SCS1.Second != SCS2.Second) {
4443 if (SCS1.Second == ICK_Identity)
4445 else if (SCS2.Second == ICK_Identity)
4447 else
4449 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
4451
4452 if (SCS1.Third == SCS2.Third) {
4453 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
4455 }
4456
4457 if (SCS1.Third == ICK_Identity)
4458 return Result == ImplicitConversionSequence::Worse
4461
4462 if (SCS2.Third == ICK_Identity)
4463 return Result == ImplicitConversionSequence::Better
4466
4468}
4469
4470/// Determine whether one of the given reference bindings is better
4471/// than the other based on what kind of bindings they are.
4472static bool
4474 const StandardConversionSequence &SCS2) {
4475 // C++0x [over.ics.rank]p3b4:
4476 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
4477 // implicit object parameter of a non-static member function declared
4478 // without a ref-qualifier, and *either* S1 binds an rvalue reference
4479 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
4480 // lvalue reference to a function lvalue and S2 binds an rvalue
4481 // reference*.
4482 //
4483 // FIXME: Rvalue references. We're going rogue with the above edits,
4484 // because the semantics in the current C++0x working paper (N3225 at the
4485 // time of this writing) break the standard definition of std::forward
4486 // and std::reference_wrapper when dealing with references to functions.
4487 // Proposed wording changes submitted to CWG for consideration.
4490 return false;
4491
4492 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
4493 SCS2.IsLvalueReference) ||
4496}
4497
4503
4504/// Returns kind of fixed enum promotion the \a SCS uses.
4505static FixedEnumPromotion
4507
4508 if (SCS.Second != ICK_Integral_Promotion)
4510
4511 const auto *Enum = SCS.getFromType()->getAsEnumDecl();
4512 if (!Enum)
4514
4515 if (!Enum->isFixed())
4517
4518 QualType UnderlyingType = Enum->getIntegerType();
4519 if (S.Context.hasSameType(SCS.getToType(1), UnderlyingType))
4521
4523}
4524
4525/// CompareStandardConversionSequences - Compare two standard
4526/// conversion sequences to determine whether one is better than the
4527/// other or if they are indistinguishable (C++ 13.3.3.2p3).
4530 const StandardConversionSequence& SCS1,
4531 const StandardConversionSequence& SCS2)
4532{
4533 // Standard conversion sequence S1 is a better conversion sequence
4534 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
4535
4536 // -- S1 is a proper subsequence of S2 (comparing the conversion
4537 // sequences in the canonical form defined by 13.3.3.1.1,
4538 // excluding any Lvalue Transformation; the identity conversion
4539 // sequence is considered to be a subsequence of any
4540 // non-identity conversion sequence) or, if not that,
4543 return CK;
4544
4545 // -- the rank of S1 is better than the rank of S2 (by the rules
4546 // defined below), or, if not that,
4547 ImplicitConversionRank Rank1 = SCS1.getRank();
4548 ImplicitConversionRank Rank2 = SCS2.getRank();
4549 if (Rank1 < Rank2)
4551 else if (Rank2 < Rank1)
4553
4554 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
4555 // are indistinguishable unless one of the following rules
4556 // applies:
4557
4558 // A conversion that is not a conversion of a pointer, or
4559 // pointer to member, to bool is better than another conversion
4560 // that is such a conversion.
4562 return SCS2.isPointerConversionToBool()
4565
4566 // C++14 [over.ics.rank]p4b2:
4567 // This is retroactively applied to C++11 by CWG 1601.
4568 //
4569 // A conversion that promotes an enumeration whose underlying type is fixed
4570 // to its underlying type is better than one that promotes to the promoted
4571 // underlying type, if the two are different.
4574 if (FEP1 != FixedEnumPromotion::None && FEP2 != FixedEnumPromotion::None &&
4575 FEP1 != FEP2)
4579
4580 // C++ [over.ics.rank]p4b2:
4581 //
4582 // If class B is derived directly or indirectly from class A,
4583 // conversion of B* to A* is better than conversion of B* to
4584 // void*, and conversion of A* to void* is better than conversion
4585 // of B* to void*.
4586 bool SCS1ConvertsToVoid
4588 bool SCS2ConvertsToVoid
4590 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
4591 // Exactly one of the conversion sequences is a conversion to
4592 // a void pointer; it's the worse conversion.
4593 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
4595 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
4596 // Neither conversion sequence converts to a void pointer; compare
4597 // their derived-to-base conversions.
4599 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
4600 return DerivedCK;
4601 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
4602 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
4603 // Both conversion sequences are conversions to void
4604 // pointers. Compare the source types to determine if there's an
4605 // inheritance relationship in their sources.
4606 QualType FromType1 = SCS1.getFromType();
4607 QualType FromType2 = SCS2.getFromType();
4608
4609 // Adjust the types we're converting from via the array-to-pointer
4610 // conversion, if we need to.
4611 if (SCS1.First == ICK_Array_To_Pointer)
4612 FromType1 = S.Context.getArrayDecayedType(FromType1);
4613 if (SCS2.First == ICK_Array_To_Pointer)
4614 FromType2 = S.Context.getArrayDecayedType(FromType2);
4615
4616 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
4617 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
4618
4619 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4621 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4623
4624 // Objective-C++: If one interface is more specific than the
4625 // other, it is the better one.
4626 const ObjCObjectPointerType* FromObjCPtr1
4627 = FromType1->getAs<ObjCObjectPointerType>();
4628 const ObjCObjectPointerType* FromObjCPtr2
4629 = FromType2->getAs<ObjCObjectPointerType>();
4630 if (FromObjCPtr1 && FromObjCPtr2) {
4631 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
4632 FromObjCPtr2);
4633 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
4634 FromObjCPtr1);
4635 if (AssignLeft != AssignRight) {
4636 return AssignLeft? ImplicitConversionSequence::Better
4638 }
4639 }
4640 }
4641
4642 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4643 // Check for a better reference binding based on the kind of bindings.
4644 if (isBetterReferenceBindingKind(SCS1, SCS2))
4646 else if (isBetterReferenceBindingKind(SCS2, SCS1))
4648 }
4649
4650 // Compare based on qualification conversions (C++ 13.3.3.2p3,
4651 // bullet 3).
4653 = CompareQualificationConversions(S, SCS1, SCS2))
4654 return QualCK;
4655
4656 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
4657 // C++ [over.ics.rank]p3b4:
4658 // -- S1 and S2 are reference bindings (8.5.3), and the types to
4659 // which the references refer are the same type except for
4660 // top-level cv-qualifiers, and the type to which the reference
4661 // initialized by S2 refers is more cv-qualified than the type
4662 // to which the reference initialized by S1 refers.
4663 QualType T1 = SCS1.getToType(2);
4664 QualType T2 = SCS2.getToType(2);
4665 T1 = S.Context.getCanonicalType(T1);
4666 T2 = S.Context.getCanonicalType(T2);
4667 Qualifiers T1Quals, T2Quals;
4668 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4669 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4670 if (UnqualT1 == UnqualT2) {
4671 // Objective-C++ ARC: If the references refer to objects with different
4672 // lifetimes, prefer bindings that don't change lifetime.
4678 }
4679
4680 // If the type is an array type, promote the element qualifiers to the
4681 // type for comparison.
4682 if (isa<ArrayType>(T1) && T1Quals)
4683 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4684 if (isa<ArrayType>(T2) && T2Quals)
4685 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4686 if (T2.isMoreQualifiedThan(T1, S.getASTContext()))
4688 if (T1.isMoreQualifiedThan(T2, S.getASTContext()))
4690 }
4691 }
4692
4693 // In Microsoft mode (below 19.28), prefer an integral conversion to a
4694 // floating-to-integral conversion if the integral conversion
4695 // is between types of the same size.
4696 // For example:
4697 // void f(float);
4698 // void f(int);
4699 // int main {
4700 // long a;
4701 // f(a);
4702 // }
4703 // Here, MSVC will call f(int) instead of generating a compile error
4704 // as clang will do in standard mode.
4705 if (S.getLangOpts().MSVCCompat &&
4708 SCS2.Second == ICK_Floating_Integral &&
4709 S.Context.getTypeSize(SCS1.getFromType()) ==
4710 S.Context.getTypeSize(SCS1.getToType(2)))
4712
4713 // Prefer a compatible vector conversion over a lax vector conversion
4714 // For example:
4715 //
4716 // typedef float __v4sf __attribute__((__vector_size__(16)));
4717 // void f(vector float);
4718 // void f(vector signed int);
4719 // int main() {
4720 // __v4sf a;
4721 // f(a);
4722 // }
4723 // Here, we'd like to choose f(vector float) and not
4724 // report an ambiguous call error
4725 if (SCS1.Second == ICK_Vector_Conversion &&
4726 SCS2.Second == ICK_Vector_Conversion) {
4727 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4728 SCS1.getFromType(), SCS1.getToType(2));
4729 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
4730 SCS2.getFromType(), SCS2.getToType(2));
4731
4732 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
4733 return SCS1IsCompatibleVectorConversion
4736 }
4737
4738 if (SCS1.Second == ICK_SVE_Vector_Conversion &&
4740 bool SCS1IsCompatibleSVEVectorConversion =
4741 S.ARM().areCompatibleSveTypes(SCS1.getFromType(), SCS1.getToType(2));
4742 bool SCS2IsCompatibleSVEVectorConversion =
4743 S.ARM().areCompatibleSveTypes(SCS2.getFromType(), SCS2.getToType(2));
4744
4745 if (SCS1IsCompatibleSVEVectorConversion !=
4746 SCS2IsCompatibleSVEVectorConversion)
4747 return SCS1IsCompatibleSVEVectorConversion
4750 }
4751
4752 if (SCS1.Second == ICK_RVV_Vector_Conversion &&
4754 bool SCS1IsCompatibleRVVVectorConversion =
4756 bool SCS2IsCompatibleRVVVectorConversion =
4758
4759 if (SCS1IsCompatibleRVVVectorConversion !=
4760 SCS2IsCompatibleRVVVectorConversion)
4761 return SCS1IsCompatibleRVVVectorConversion
4764 }
4766}
4767
4768/// CompareQualificationConversions - Compares two standard conversion
4769/// sequences to determine whether they can be ranked based on their
4770/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
4773 const StandardConversionSequence& SCS1,
4774 const StandardConversionSequence& SCS2) {
4775 // C++ [over.ics.rank]p3:
4776 // -- S1 and S2 differ only in their qualification conversion and
4777 // yield similar types T1 and T2 (C++ 4.4), respectively, [...]
4778 // [C++98]
4779 // [...] and the cv-qualification signature of type T1 is a proper subset
4780 // of the cv-qualification signature of type T2, and S1 is not the
4781 // deprecated string literal array-to-pointer conversion (4.2).
4782 // [C++2a]
4783 // [...] where T1 can be converted to T2 by a qualification conversion.
4784 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
4785 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
4787
4788 // FIXME: the example in the standard doesn't use a qualification
4789 // conversion (!)
4790 QualType T1 = SCS1.getToType(2);
4791 QualType T2 = SCS2.getToType(2);
4792 T1 = S.Context.getCanonicalType(T1);
4793 T2 = S.Context.getCanonicalType(T2);
4794 assert(!T1->isReferenceType() && !T2->isReferenceType());
4795 Qualifiers T1Quals, T2Quals;
4796 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4797 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4798
4799 // If the types are the same, we won't learn anything by unwrapping
4800 // them.
4801 if (UnqualT1 == UnqualT2)
4803
4804 // Don't ever prefer a standard conversion sequence that uses the deprecated
4805 // string literal array to pointer conversion.
4806 bool CanPick1 = !SCS1.DeprecatedStringLiteralToCharPtr;
4807 bool CanPick2 = !SCS2.DeprecatedStringLiteralToCharPtr;
4808
4809 // Objective-C++ ARC:
4810 // Prefer qualification conversions not involving a change in lifetime
4811 // to qualification conversions that do change lifetime.
4814 CanPick1 = false;
4817 CanPick2 = false;
4818
4819 bool ObjCLifetimeConversion;
4820 if (CanPick1 &&
4821 !S.IsQualificationConversion(T1, T2, false, ObjCLifetimeConversion))
4822 CanPick1 = false;
4823 // FIXME: In Objective-C ARC, we can have qualification conversions in both
4824 // directions, so we can't short-cut this second check in general.
4825 if (CanPick2 &&
4826 !S.IsQualificationConversion(T2, T1, false, ObjCLifetimeConversion))
4827 CanPick2 = false;
4828
4829 if (CanPick1 != CanPick2)
4830 return CanPick1 ? ImplicitConversionSequence::Better
4833}
4834
4835/// CompareDerivedToBaseConversions - Compares two standard conversion
4836/// sequences to determine whether they can be ranked based on their
4837/// various kinds of derived-to-base conversions (C++
4838/// [over.ics.rank]p4b3). As part of these checks, we also look at
4839/// conversions between Objective-C interface types.
4842 const StandardConversionSequence& SCS1,
4843 const StandardConversionSequence& SCS2) {
4844 QualType FromType1 = SCS1.getFromType();
4845 QualType ToType1 = SCS1.getToType(1);
4846 QualType FromType2 = SCS2.getFromType();
4847 QualType ToType2 = SCS2.getToType(1);
4848
4849 // Adjust the types we're converting from via the array-to-pointer
4850 // conversion, if we need to.
4851 if (SCS1.First == ICK_Array_To_Pointer)
4852 FromType1 = S.Context.getArrayDecayedType(FromType1);
4853 if (SCS2.First == ICK_Array_To_Pointer)
4854 FromType2 = S.Context.getArrayDecayedType(FromType2);
4855
4856 // Canonicalize all of the types.
4857 FromType1 = S.Context.getCanonicalType(FromType1);
4858 ToType1 = S.Context.getCanonicalType(ToType1);
4859 FromType2 = S.Context.getCanonicalType(FromType2);
4860 ToType2 = S.Context.getCanonicalType(ToType2);
4861
4862 // C++ [over.ics.rank]p4b3:
4863 //
4864 // If class B is derived directly or indirectly from class A and
4865 // class C is derived directly or indirectly from B,
4866 //
4867 // Compare based on pointer conversions.
4868 if (SCS1.Second == ICK_Pointer_Conversion &&
4870 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4871 FromType1->isPointerType() && FromType2->isPointerType() &&
4872 ToType1->isPointerType() && ToType2->isPointerType()) {
4873 QualType FromPointee1 =
4875 QualType ToPointee1 =
4877 QualType FromPointee2 =
4879 QualType ToPointee2 =
4881
4882 // -- conversion of C* to B* is better than conversion of C* to A*,
4883 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4884 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4886 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4888 }
4889
4890 // -- conversion of B* to A* is better than conversion of C* to A*,
4891 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4892 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4894 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4896 }
4897 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4899 const ObjCObjectPointerType *FromPtr1
4900 = FromType1->getAs<ObjCObjectPointerType>();
4901 const ObjCObjectPointerType *FromPtr2
4902 = FromType2->getAs<ObjCObjectPointerType>();
4903 const ObjCObjectPointerType *ToPtr1
4904 = ToType1->getAs<ObjCObjectPointerType>();
4905 const ObjCObjectPointerType *ToPtr2
4906 = ToType2->getAs<ObjCObjectPointerType>();
4907
4908 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4909 // Apply the same conversion ranking rules for Objective-C pointer types
4910 // that we do for C++ pointers to class types. However, we employ the
4911 // Objective-C pseudo-subtyping relationship used for assignment of
4912 // Objective-C pointer types.
4913 bool FromAssignLeft
4914 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4915 bool FromAssignRight
4916 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4917 bool ToAssignLeft
4918 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4919 bool ToAssignRight
4920 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4921
4922 // A conversion to an a non-id object pointer type or qualified 'id'
4923 // type is better than a conversion to 'id'.
4924 if (ToPtr1->isObjCIdType() &&
4925 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4927 if (ToPtr2->isObjCIdType() &&
4928 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4930
4931 // A conversion to a non-id object pointer type is better than a
4932 // conversion to a qualified 'id' type
4933 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4935 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4937
4938 // A conversion to an a non-Class object pointer type or qualified 'Class'
4939 // type is better than a conversion to 'Class'.
4940 if (ToPtr1->isObjCClassType() &&
4941 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4943 if (ToPtr2->isObjCClassType() &&
4944 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4946
4947 // A conversion to a non-Class object pointer type is better than a
4948 // conversion to a qualified 'Class' type.
4949 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4951 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4953
4954 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4955 if (S.Context.hasSameType(FromType1, FromType2) &&
4956 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4957 (ToAssignLeft != ToAssignRight)) {
4958 if (FromPtr1->isSpecialized()) {
4959 // "conversion of B<A> * to B * is better than conversion of B * to
4960 // C *.
4961 bool IsFirstSame =
4962 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4963 bool IsSecondSame =
4964 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4965 if (IsFirstSame) {
4966 if (!IsSecondSame)
4968 } else if (IsSecondSame)
4970 }
4971 return ToAssignLeft? ImplicitConversionSequence::Worse
4973 }
4974
4975 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4976 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4977 (FromAssignLeft != FromAssignRight))
4978 return FromAssignLeft? ImplicitConversionSequence::Better
4980 }
4981 }
4982
4983 // Ranking of member-pointer types.
4984 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4985 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4986 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4987 const auto *FromMemPointer1 = FromType1->castAs<MemberPointerType>();
4988 const auto *ToMemPointer1 = ToType1->castAs<MemberPointerType>();
4989 const auto *FromMemPointer2 = FromType2->castAs<MemberPointerType>();
4990 const auto *ToMemPointer2 = ToType2->castAs<MemberPointerType>();
4991 CXXRecordDecl *FromPointee1 = FromMemPointer1->getMostRecentCXXRecordDecl();
4992 CXXRecordDecl *ToPointee1 = ToMemPointer1->getMostRecentCXXRecordDecl();
4993 CXXRecordDecl *FromPointee2 = FromMemPointer2->getMostRecentCXXRecordDecl();
4994 CXXRecordDecl *ToPointee2 = ToMemPointer2->getMostRecentCXXRecordDecl();
4995 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4996 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4997 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4999 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
5001 }
5002 // conversion of B::* to C::* is better than conversion of A::* to C::*
5003 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
5004 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
5006 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
5008 }
5009 }
5010
5011 if (SCS1.Second == ICK_Derived_To_Base) {
5012 // -- conversion of C to B is better than conversion of C to A,
5013 // -- binding of an expression of type C to a reference of type
5014 // B& is better than binding an expression of type C to a
5015 // reference of type A&,
5016 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5017 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5018 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
5020 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
5022 }
5023
5024 // -- conversion of B to A is better than conversion of C to A.
5025 // -- binding of an expression of type B to a reference of type
5026 // A& is better than binding an expression of type C to a
5027 // reference of type A&,
5028 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
5029 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
5030 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
5032 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
5034 }
5035 }
5036
5038}
5039
5041 if (!T.getQualifiers().hasUnaligned())
5042 return T;
5043
5044 Qualifiers Q;
5045 T = Ctx.getUnqualifiedArrayType(T, Q);
5046 Q.removeUnaligned();
5047 return Ctx.getQualifiedType(T, Q);
5048}
5049
5052 QualType OrigT1, QualType OrigT2,
5053 ReferenceConversions *ConvOut) {
5054 assert(!OrigT1->isReferenceType() &&
5055 "T1 must be the pointee type of the reference type");
5056 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
5057
5058 QualType T1 = Context.getCanonicalType(OrigT1);
5059 QualType T2 = Context.getCanonicalType(OrigT2);
5060 Qualifiers T1Quals, T2Quals;
5061 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
5062 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
5063
5064 ReferenceConversions ConvTmp;
5065 ReferenceConversions &Conv = ConvOut ? *ConvOut : ConvTmp;
5066 Conv = ReferenceConversions();
5067
5068 // C++2a [dcl.init.ref]p4:
5069 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
5070 // reference-related to "cv2 T2" if T1 is similar to T2, or
5071 // T1 is a base class of T2.
5072 // "cv1 T1" is reference-compatible with "cv2 T2" if
5073 // a prvalue of type "pointer to cv2 T2" can be converted to the type
5074 // "pointer to cv1 T1" via a standard conversion sequence.
5075
5076 // Check for standard conversions we can apply to pointers: derived-to-base
5077 // conversions, ObjC pointer conversions, and function pointer conversions.
5078 // (Qualification conversions are checked last.)
5079 if (UnqualT1 == UnqualT2) {
5080 // Nothing to do.
5081 } else if (isCompleteType(Loc, OrigT2) &&
5082 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
5083 Conv |= ReferenceConversions::DerivedToBase;
5084 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
5085 UnqualT2->isObjCObjectOrInterfaceType() &&
5086 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
5087 Conv |= ReferenceConversions::ObjC;
5088 else if (UnqualT2->isFunctionType() &&
5089 IsFunctionConversion(UnqualT2, UnqualT1)) {
5090 Conv |= ReferenceConversions::Function;
5091 // No need to check qualifiers; function types don't have them.
5092 return Ref_Compatible;
5093 }
5094 bool ConvertedReferent = Conv != 0;
5095
5096 // We can have a qualification conversion. Compute whether the types are
5097 // similar at the same time.
5098 bool PreviousToQualsIncludeConst = true;
5099 bool TopLevel = true;
5100 do {
5101 if (T1 == T2)
5102 break;
5103
5104 // We will need a qualification conversion.
5105 Conv |= ReferenceConversions::Qualification;
5106
5107 // Track whether we performed a qualification conversion anywhere other
5108 // than the top level. This matters for ranking reference bindings in
5109 // overload resolution.
5110 if (!TopLevel)
5111 Conv |= ReferenceConversions::NestedQualification;
5112
5113 // MS compiler ignores __unaligned qualifier for references; do the same.
5114 T1 = withoutUnaligned(Context, T1);
5115 T2 = withoutUnaligned(Context, T2);
5116
5117 // If we find a qualifier mismatch, the types are not reference-compatible,
5118 // but are still be reference-related if they're similar.
5119 bool ObjCLifetimeConversion = false;
5120 if (!isQualificationConversionStep(T2, T1, /*CStyle=*/false, TopLevel,
5121 PreviousToQualsIncludeConst,
5122 ObjCLifetimeConversion, getASTContext()))
5123 return (ConvertedReferent || Context.hasSimilarType(T1, T2))
5124 ? Ref_Related
5126
5127 // FIXME: Should we track this for any level other than the first?
5128 if (ObjCLifetimeConversion)
5129 Conv |= ReferenceConversions::ObjCLifetime;
5130
5131 TopLevel = false;
5132 } while (Context.UnwrapSimilarTypes(T1, T2));
5133
5134 // At this point, if the types are reference-related, we must either have the
5135 // same inner type (ignoring qualifiers), or must have already worked out how
5136 // to convert the referent.
5137 return (ConvertedReferent || Context.hasSameUnqualifiedType(T1, T2))
5140}
5141
5142/// Look for a user-defined conversion to a value reference-compatible
5143/// with DeclType. Return true if something definite is found.
5144static bool
5146 QualType DeclType, SourceLocation DeclLoc,
5147 Expr *Init, QualType T2, bool AllowRvalues,
5148 bool AllowExplicit) {
5149 assert(T2->isRecordType() && "Can only find conversions of record types.");
5150 auto *T2RecordDecl = T2->castAsCXXRecordDecl();
5151 OverloadCandidateSet CandidateSet(
5153 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
5154 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5155 NamedDecl *D = *I;
5157 if (isa<UsingShadowDecl>(D))
5158 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5159
5160 FunctionTemplateDecl *ConvTemplate
5161 = dyn_cast<FunctionTemplateDecl>(D);
5162 CXXConversionDecl *Conv;
5163 if (ConvTemplate)
5164 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5165 else
5166 Conv = cast<CXXConversionDecl>(D);
5167
5168 if (AllowRvalues) {
5169 // If we are initializing an rvalue reference, don't permit conversion
5170 // functions that return lvalues.
5171 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
5172 const ReferenceType *RefType
5174 if (RefType && !RefType->getPointeeType()->isFunctionType())
5175 continue;
5176 }
5177
5178 if (!ConvTemplate &&
5180 DeclLoc,
5181 Conv->getConversionType()
5186 continue;
5187 } else {
5188 // If the conversion function doesn't return a reference type,
5189 // it can't be considered for this conversion. An rvalue reference
5190 // is only acceptable if its referencee is a function type.
5191
5192 const ReferenceType *RefType =
5194 if (!RefType ||
5195 (!RefType->isLValueReferenceType() &&
5196 !RefType->getPointeeType()->isFunctionType()))
5197 continue;
5198 }
5199
5200 if (ConvTemplate)
5202 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5203 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5204 else
5206 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
5207 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
5208 }
5209
5210 bool HadMultipleCandidates = (CandidateSet.size() > 1);
5211
5213 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
5214 case OR_Success:
5215
5216 assert(Best->HasFinalConversion);
5217
5218 // C++ [over.ics.ref]p1:
5219 //
5220 // [...] If the parameter binds directly to the result of
5221 // applying a conversion function to the argument
5222 // expression, the implicit conversion sequence is a
5223 // user-defined conversion sequence (13.3.3.1.2), with the
5224 // second standard conversion sequence either an identity
5225 // conversion or, if the conversion function returns an
5226 // entity of a type that is a derived class of the parameter
5227 // type, a derived-to-base Conversion.
5228 if (!Best->FinalConversion.DirectBinding)
5229 return false;
5230
5231 ICS.setUserDefined();
5232 ICS.UserDefined.Before = Best->Conversions[0].Standard;
5233 ICS.UserDefined.After = Best->FinalConversion;
5234 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
5235 ICS.UserDefined.ConversionFunction = Best->Function;
5236 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
5237 ICS.UserDefined.EllipsisConversion = false;
5238 assert(ICS.UserDefined.After.ReferenceBinding &&
5240 "Expected a direct reference binding!");
5241 return true;
5242
5243 case OR_Ambiguous:
5244 ICS.setAmbiguous();
5245 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5246 Cand != CandidateSet.end(); ++Cand)
5247 if (Cand->Best)
5248 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
5249 return true;
5250
5252 case OR_Deleted:
5253 // There was no suitable conversion, or we found a deleted
5254 // conversion; continue with other checks.
5255 return false;
5256 }
5257
5258 llvm_unreachable("Invalid OverloadResult!");
5259}
5260
5261/// Compute an implicit conversion sequence for reference
5262/// initialization.
5263static ImplicitConversionSequence
5265 SourceLocation DeclLoc,
5266 bool SuppressUserConversions,
5267 bool AllowExplicit) {
5268 assert(DeclType->isReferenceType() && "Reference init needs a reference");
5269
5270 // Most paths end in a failed conversion.
5273
5274 QualType T1 = DeclType->castAs<ReferenceType>()->getPointeeType();
5275 QualType T2 = Init->getType();
5276
5277 // If the initializer is the address of an overloaded function, try
5278 // to resolve the overloaded function. If all goes well, T2 is the
5279 // type of the resulting function.
5280 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5283 false, Found))
5284 T2 = Fn->getType();
5285 }
5286
5287 // Compute some basic properties of the types and the initializer.
5288 bool isRValRef = DeclType->isRValueReferenceType();
5289 Expr::Classification InitCategory = Init->Classify(S.Context);
5290
5292 Sema::ReferenceCompareResult RefRelationship =
5293 S.CompareReferenceRelationship(DeclLoc, T1, T2, &RefConv);
5294
5295 auto SetAsReferenceBinding = [&](bool BindsDirectly) {
5296 ICS.setStandard();
5298 // FIXME: A reference binding can be a function conversion too. We should
5299 // consider that when ordering reference-to-function bindings.
5300 ICS.Standard.Second = (RefConv & Sema::ReferenceConversions::DerivedToBase)
5302 : (RefConv & Sema::ReferenceConversions::ObjC)
5304 : ICK_Identity;
5306 // FIXME: As a speculative fix to a defect introduced by CWG2352, we rank
5307 // a reference binding that performs a non-top-level qualification
5308 // conversion as a qualification conversion, not as an identity conversion.
5309 ICS.Standard.Third = (RefConv &
5310 Sema::ReferenceConversions::NestedQualification)
5312 : ICK_Identity;
5313 ICS.Standard.setFromType(T2);
5314 ICS.Standard.setToType(0, T2);
5315 ICS.Standard.setToType(1, T1);
5316 ICS.Standard.setToType(2, T1);
5317 ICS.Standard.ReferenceBinding = true;
5318 ICS.Standard.DirectBinding = BindsDirectly;
5319 ICS.Standard.IsLvalueReference = !isRValRef;
5321 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
5324 (RefConv & Sema::ReferenceConversions::ObjCLifetime) != 0;
5325 ICS.Standard.FromBracedInitList = false;
5326 ICS.Standard.CopyConstructor = nullptr;
5328 };
5329
5330 // C++0x [dcl.init.ref]p5:
5331 // A reference to type "cv1 T1" is initialized by an expression
5332 // of type "cv2 T2" as follows:
5333
5334 // -- If reference is an lvalue reference and the initializer expression
5335 if (!isRValRef) {
5336 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
5337 // reference-compatible with "cv2 T2," or
5338 //
5339 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
5340 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
5341 // C++ [over.ics.ref]p1:
5342 // When a parameter of reference type binds directly (8.5.3)
5343 // to an argument expression, the implicit conversion sequence
5344 // is the identity conversion, unless the argument expression
5345 // has a type that is a derived class of the parameter type,
5346 // in which case the implicit conversion sequence is a
5347 // derived-to-base Conversion (13.3.3.1).
5348 SetAsReferenceBinding(/*BindsDirectly=*/true);
5349
5350 // Nothing more to do: the inaccessibility/ambiguity check for
5351 // derived-to-base conversions is suppressed when we're
5352 // computing the implicit conversion sequence (C++
5353 // [over.best.ics]p2).
5354 return ICS;
5355 }
5356
5357 // -- has a class type (i.e., T2 is a class type), where T1 is
5358 // not reference-related to T2, and can be implicitly
5359 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
5360 // is reference-compatible with "cv3 T3" 92) (this
5361 // conversion is selected by enumerating the applicable
5362 // conversion functions (13.3.1.6) and choosing the best
5363 // one through overload resolution (13.3)),
5364 if (!SuppressUserConversions && T2->isRecordType() &&
5365 S.isCompleteType(DeclLoc, T2) &&
5366 RefRelationship == Sema::Ref_Incompatible) {
5367 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5368 Init, T2, /*AllowRvalues=*/false,
5369 AllowExplicit))
5370 return ICS;
5371 }
5372 }
5373
5374 // -- Otherwise, the reference shall be an lvalue reference to a
5375 // non-volatile const type (i.e., cv1 shall be const), or the reference
5376 // shall be an rvalue reference.
5377 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified())) {
5378 if (InitCategory.isRValue() && RefRelationship != Sema::Ref_Incompatible)
5380 return ICS;
5381 }
5382
5383 // -- If the initializer expression
5384 //
5385 // -- is an xvalue, class prvalue, array prvalue or function
5386 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
5387 if (RefRelationship == Sema::Ref_Compatible &&
5388 (InitCategory.isXValue() ||
5389 (InitCategory.isPRValue() &&
5390 (T2->isRecordType() || T2->isArrayType())) ||
5391 (InitCategory.isLValue() && T2->isFunctionType()))) {
5392 // In C++11, this is always a direct binding. In C++98/03, it's a direct
5393 // binding unless we're binding to a class prvalue.
5394 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
5395 // allow the use of rvalue references in C++98/03 for the benefit of
5396 // standard library implementors; therefore, we need the xvalue check here.
5397 SetAsReferenceBinding(/*BindsDirectly=*/S.getLangOpts().CPlusPlus11 ||
5398 !(InitCategory.isPRValue() || T2->isRecordType()));
5399 return ICS;
5400 }
5401
5402 // -- has a class type (i.e., T2 is a class type), where T1 is not
5403 // reference-related to T2, and can be implicitly converted to
5404 // an xvalue, class prvalue, or function lvalue of type
5405 // "cv3 T3", where "cv1 T1" is reference-compatible with
5406 // "cv3 T3",
5407 //
5408 // then the reference is bound to the value of the initializer
5409 // expression in the first case and to the result of the conversion
5410 // in the second case (or, in either case, to an appropriate base
5411 // class subobject).
5412 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5413 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
5414 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
5415 Init, T2, /*AllowRvalues=*/true,
5416 AllowExplicit)) {
5417 // In the second case, if the reference is an rvalue reference
5418 // and the second standard conversion sequence of the
5419 // user-defined conversion sequence includes an lvalue-to-rvalue
5420 // conversion, the program is ill-formed.
5421 if (ICS.isUserDefined() && isRValRef &&
5424
5425 return ICS;
5426 }
5427
5428 // A temporary of function type cannot be created; don't even try.
5429 if (T1->isFunctionType())
5430 return ICS;
5431
5432 // -- Otherwise, a temporary of type "cv1 T1" is created and
5433 // initialized from the initializer expression using the
5434 // rules for a non-reference copy initialization (8.5). The
5435 // reference is then bound to the temporary. If T1 is
5436 // reference-related to T2, cv1 must be the same
5437 // cv-qualification as, or greater cv-qualification than,
5438 // cv2; otherwise, the program is ill-formed.
5439 if (RefRelationship == Sema::Ref_Related) {
5440 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
5441 // we would be reference-compatible or reference-compatible with
5442 // added qualification. But that wasn't the case, so the reference
5443 // initialization fails.
5444 //
5445 // Note that we only want to check address spaces and cvr-qualifiers here.
5446 // ObjC GC, lifetime and unaligned qualifiers aren't important.
5447 Qualifiers T1Quals = T1.getQualifiers();
5448 Qualifiers T2Quals = T2.getQualifiers();
5449 T1Quals.removeObjCGCAttr();
5450 T1Quals.removeObjCLifetime();
5451 T2Quals.removeObjCGCAttr();
5452 T2Quals.removeObjCLifetime();
5453 // MS compiler ignores __unaligned qualifier for references; do the same.
5454 T1Quals.removeUnaligned();
5455 T2Quals.removeUnaligned();
5456 if (!T1Quals.compatiblyIncludes(T2Quals, S.getASTContext()))
5457 return ICS;
5458 }
5459
5460 // If at least one of the types is a class type, the types are not
5461 // related, and we aren't allowed any user conversions, the
5462 // reference binding fails. This case is important for breaking
5463 // recursion, since TryImplicitConversion below will attempt to
5464 // create a temporary through the use of a copy constructor.
5465 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
5466 (T1->isRecordType() || T2->isRecordType()))
5467 return ICS;
5468
5469 // If T1 is reference-related to T2 and the reference is an rvalue
5470 // reference, the initializer expression shall not be an lvalue.
5471 if (RefRelationship >= Sema::Ref_Related && isRValRef &&
5472 Init->Classify(S.Context).isLValue()) {
5474 return ICS;
5475 }
5476
5477 // C++ [over.ics.ref]p2:
5478 // When a parameter of reference type is not bound directly to
5479 // an argument expression, the conversion sequence is the one
5480 // required to convert the argument expression to the
5481 // underlying type of the reference according to
5482 // 13.3.3.1. Conceptually, this conversion sequence corresponds
5483 // to copy-initializing a temporary of the underlying type with
5484 // the argument expression. Any difference in top-level
5485 // cv-qualification is subsumed by the initialization itself
5486 // and does not constitute a conversion.
5487 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
5488 AllowedExplicit::None,
5489 /*InOverloadResolution=*/false,
5490 /*CStyle=*/false,
5491 /*AllowObjCWritebackConversion=*/false,
5492 /*AllowObjCConversionOnExplicit=*/false);
5493
5494 // Of course, that's still a reference binding.
5495 if (ICS.isStandard()) {
5496 ICS.Standard.ReferenceBinding = true;
5497 ICS.Standard.IsLvalueReference = !isRValRef;
5498 ICS.Standard.BindsToFunctionLvalue = false;
5499 ICS.Standard.BindsToRvalue = true;
5502 } else if (ICS.isUserDefined()) {
5503 const ReferenceType *LValRefType =
5506
5507 // C++ [over.ics.ref]p3:
5508 // Except for an implicit object parameter, for which see 13.3.1, a
5509 // standard conversion sequence cannot be formed if it requires [...]
5510 // binding an rvalue reference to an lvalue other than a function
5511 // lvalue.
5512 // Note that the function case is not possible here.
5513 if (isRValRef && LValRefType) {
5515 return ICS;
5516 }
5517
5519 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
5521 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
5525 }
5526
5527 return ICS;
5528}
5529
5530static ImplicitConversionSequence
5531TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5532 bool SuppressUserConversions,
5533 bool InOverloadResolution,
5534 bool AllowObjCWritebackConversion,
5535 bool AllowExplicit = false);
5536
5537/// TryListConversion - Try to copy-initialize a value of type ToType from the
5538/// initializer list From.
5539static ImplicitConversionSequence
5541 bool SuppressUserConversions,
5542 bool InOverloadResolution,
5543 bool AllowObjCWritebackConversion) {
5544 // C++11 [over.ics.list]p1:
5545 // When an argument is an initializer list, it is not an expression and
5546 // special rules apply for converting it to a parameter type.
5547
5549 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
5550
5551 // We need a complete type for what follows. With one C++20 exception,
5552 // incomplete types can never be initialized from init lists.
5553 QualType InitTy = ToType;
5554 const ArrayType *AT = S.Context.getAsArrayType(ToType);
5555 if (AT && S.getLangOpts().CPlusPlus20)
5556 if (const auto *IAT = dyn_cast<IncompleteArrayType>(AT))
5557 // C++20 allows list initialization of an incomplete array type.
5558 InitTy = IAT->getElementType();
5559 if (!S.isCompleteType(From->getBeginLoc(), InitTy))
5560 return Result;
5561
5562 // C++20 [over.ics.list]/2:
5563 // If the initializer list is a designated-initializer-list, a conversion
5564 // is only possible if the parameter has an aggregate type
5565 //
5566 // FIXME: The exception for reference initialization here is not part of the
5567 // language rules, but follow other compilers in adding it as a tentative DR
5568 // resolution.
5569 bool IsDesignatedInit = From->hasDesignatedInit();
5570 if (!ToType->isAggregateType() && !ToType->isReferenceType() &&
5571 IsDesignatedInit)
5572 return Result;
5573
5574 // Per DR1467 and DR2137:
5575 // If the parameter type is an aggregate class X and the initializer list
5576 // has a single element of type cv U, where U is X or a class derived from
5577 // X, the implicit conversion sequence is the one required to convert the
5578 // element to the parameter type.
5579 //
5580 // Otherwise, if the parameter type is a character array [... ]
5581 // and the initializer list has a single element that is an
5582 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
5583 // implicit conversion sequence is the identity conversion.
5584 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5585 if (ToType->isRecordType() && ToType->isAggregateType()) {
5586 QualType InitType = From->getInit(0)->getType();
5587 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
5588 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
5589 return TryCopyInitialization(S, From->getInit(0), ToType,
5590 SuppressUserConversions,
5591 InOverloadResolution,
5592 AllowObjCWritebackConversion);
5593 }
5594
5595 if (AT && S.IsStringInit(From->getInit(0), AT)) {
5596 InitializedEntity Entity =
5598 /*Consumed=*/false);
5599 if (S.CanPerformCopyInitialization(Entity, From)) {
5600 Result.setStandard();
5601 Result.Standard.setAsIdentityConversion();
5602 Result.Standard.setFromType(ToType);
5603 Result.Standard.setAllToTypes(ToType);
5604 return Result;
5605 }
5606 }
5607 }
5608
5609 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
5610 // C++11 [over.ics.list]p2:
5611 // If the parameter type is std::initializer_list<X> or "array of X" and
5612 // all the elements can be implicitly converted to X, the implicit
5613 // conversion sequence is the worst conversion necessary to convert an
5614 // element of the list to X.
5615 //
5616 // C++14 [over.ics.list]p3:
5617 // Otherwise, if the parameter type is "array of N X", if the initializer
5618 // list has exactly N elements or if it has fewer than N elements and X is
5619 // default-constructible, and if all the elements of the initializer list
5620 // can be implicitly converted to X, the implicit conversion sequence is
5621 // the worst conversion necessary to convert an element of the list to X.
5622 if ((AT || S.isStdInitializerList(ToType, &InitTy)) && !IsDesignatedInit) {
5623 unsigned e = From->getNumInits();
5626 QualType());
5627 QualType ContTy = ToType;
5628 bool IsUnbounded = false;
5629 if (AT) {
5630 InitTy = AT->getElementType();
5631 if (ConstantArrayType const *CT = dyn_cast<ConstantArrayType>(AT)) {
5632 if (CT->getSize().ult(e)) {
5633 // Too many inits, fatally bad
5635 ToType);
5636 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5637 return Result;
5638 }
5639 if (CT->getSize().ugt(e)) {
5640 // Need an init from empty {}, is there one?
5641 InitListExpr EmptyList(S.Context, From->getEndLoc(), {},
5642 From->getEndLoc());
5643 EmptyList.setType(S.Context.VoidTy);
5644 DfltElt = TryListConversion(
5645 S, &EmptyList, InitTy, SuppressUserConversions,
5646 InOverloadResolution, AllowObjCWritebackConversion);
5647 if (DfltElt.isBad()) {
5648 // No {} init, fatally bad
5650 ToType);
5651 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5652 return Result;
5653 }
5654 }
5655 } else {
5656 assert(isa<IncompleteArrayType>(AT) && "Expected incomplete array");
5657 IsUnbounded = true;
5658 if (!e) {
5659 // Cannot convert to zero-sized.
5661 ToType);
5662 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5663 return Result;
5664 }
5665 llvm::APInt Size(S.Context.getTypeSize(S.Context.getSizeType()), e);
5666 ContTy = S.Context.getConstantArrayType(InitTy, Size, nullptr,
5668 }
5669 }
5670
5671 Result.setStandard();
5672 Result.Standard.setAsIdentityConversion();
5673 Result.Standard.setFromType(InitTy);
5674 Result.Standard.setAllToTypes(InitTy);
5675 for (unsigned i = 0; i < e; ++i) {
5676 Expr *Init = From->getInit(i);
5678 S, Init, InitTy, SuppressUserConversions, InOverloadResolution,
5679 AllowObjCWritebackConversion);
5680
5681 // Keep the worse conversion seen so far.
5682 // FIXME: Sequences are not totally ordered, so 'worse' can be
5683 // ambiguous. CWG has been informed.
5685 Result) ==
5687 Result = ICS;
5688 // Bail as soon as we find something unconvertible.
5689 if (Result.isBad()) {
5690 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5691 return Result;
5692 }
5693 }
5694 }
5695
5696 // If we needed any implicit {} initialization, compare that now.
5697 // over.ics.list/6 indicates we should compare that conversion. Again CWG
5698 // has been informed that this might not be the best thing.
5699 if (!DfltElt.isBad() && CompareImplicitConversionSequences(
5700 S, From->getEndLoc(), DfltElt, Result) ==
5702 Result = DfltElt;
5703 // Record the type being initialized so that we may compare sequences
5704 Result.setInitializerListContainerType(ContTy, IsUnbounded);
5705 return Result;
5706 }
5707
5708 // C++14 [over.ics.list]p4:
5709 // C++11 [over.ics.list]p3:
5710 // Otherwise, if the parameter is a non-aggregate class X and overload
5711 // resolution chooses a single best constructor [...] the implicit
5712 // conversion sequence is a user-defined conversion sequence. If multiple
5713 // constructors are viable but none is better than the others, the
5714 // implicit conversion sequence is a user-defined conversion sequence.
5715 if (ToType->isRecordType() && !ToType->isAggregateType()) {
5716 // This function can deal with initializer lists.
5717 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
5718 AllowedExplicit::None,
5719 InOverloadResolution, /*CStyle=*/false,
5720 AllowObjCWritebackConversion,
5721 /*AllowObjCConversionOnExplicit=*/false);
5722 }
5723
5724 // C++14 [over.ics.list]p5:
5725 // C++11 [over.ics.list]p4:
5726 // Otherwise, if the parameter has an aggregate type which can be
5727 // initialized from the initializer list [...] the implicit conversion
5728 // sequence is a user-defined conversion sequence.
5729 if (ToType->isAggregateType()) {
5730 // Type is an aggregate, argument is an init list. At this point it comes
5731 // down to checking whether the initialization works.
5732 // FIXME: Find out whether this parameter is consumed or not.
5733 InitializedEntity Entity =
5735 /*Consumed=*/false);
5737 From)) {
5738 Result.setUserDefined();
5739 Result.UserDefined.Before.setAsIdentityConversion();
5740 // Initializer lists don't have a type.
5741 Result.UserDefined.Before.setFromType(QualType());
5742 Result.UserDefined.Before.setAllToTypes(QualType());
5743
5744 Result.UserDefined.After.setAsIdentityConversion();
5745 Result.UserDefined.After.setFromType(ToType);
5746 Result.UserDefined.After.setAllToTypes(ToType);
5747 Result.UserDefined.ConversionFunction = nullptr;
5748 }
5749 return Result;
5750 }
5751
5752 // C++14 [over.ics.list]p6:
5753 // C++11 [over.ics.list]p5:
5754 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
5755 if (ToType->isReferenceType()) {
5756 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
5757 // mention initializer lists in any way. So we go by what list-
5758 // initialization would do and try to extrapolate from that.
5759
5760 QualType T1 = ToType->castAs<ReferenceType>()->getPointeeType();
5761
5762 // If the initializer list has a single element that is reference-related
5763 // to the parameter type, we initialize the reference from that.
5764 if (From->getNumInits() == 1 && !IsDesignatedInit) {
5765 Expr *Init = From->getInit(0);
5766
5767 QualType T2 = Init->getType();
5768
5769 // If the initializer is the address of an overloaded function, try
5770 // to resolve the overloaded function. If all goes well, T2 is the
5771 // type of the resulting function.
5772 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
5775 Init, ToType, false, Found))
5776 T2 = Fn->getType();
5777 }
5778
5779 // Compute some basic properties of the types and the initializer.
5780 Sema::ReferenceCompareResult RefRelationship =
5781 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2);
5782
5783 if (RefRelationship >= Sema::Ref_Related) {
5784 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
5785 SuppressUserConversions,
5786 /*AllowExplicit=*/false);
5787 }
5788 }
5789
5790 // Otherwise, we bind the reference to a temporary created from the
5791 // initializer list.
5792 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5793 InOverloadResolution,
5794 AllowObjCWritebackConversion);
5795 if (Result.isFailure())
5796 return Result;
5797 assert(!Result.isEllipsis() &&
5798 "Sub-initialization cannot result in ellipsis conversion.");
5799
5800 // Can we even bind to a temporary?
5801 if (ToType->isRValueReferenceType() ||
5802 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5803 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5804 Result.UserDefined.After;
5805 SCS.ReferenceBinding = true;
5807 SCS.BindsToRvalue = true;
5808 SCS.BindsToFunctionLvalue = false;
5811 SCS.FromBracedInitList = false;
5812
5813 } else
5815 From, ToType);
5816 return Result;
5817 }
5818
5819 // C++14 [over.ics.list]p7:
5820 // C++11 [over.ics.list]p6:
5821 // Otherwise, if the parameter type is not a class:
5822 if (!ToType->isRecordType()) {
5823 // - if the initializer list has one element that is not itself an
5824 // initializer list, the implicit conversion sequence is the one
5825 // required to convert the element to the parameter type.
5826 // Bail out on EmbedExpr as well since we never create EmbedExpr for a
5827 // single integer.
5828 unsigned NumInits = From->getNumInits();
5829 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)) &&
5830 !isa<EmbedExpr>(From->getInit(0))) {
5831 Result = TryCopyInitialization(
5832 S, From->getInit(0), ToType, SuppressUserConversions,
5833 InOverloadResolution, AllowObjCWritebackConversion);
5834 if (Result.isStandard())
5835 Result.Standard.FromBracedInitList = true;
5836 }
5837 // - if the initializer list has no elements, the implicit conversion
5838 // sequence is the identity conversion.
5839 else if (NumInits == 0) {
5840 Result.setStandard();
5841 Result.Standard.setAsIdentityConversion();
5842 Result.Standard.setFromType(ToType);
5843 Result.Standard.setAllToTypes(ToType);
5844 }
5845 return Result;
5846 }
5847
5848 // C++14 [over.ics.list]p8:
5849 // C++11 [over.ics.list]p7:
5850 // In all cases other than those enumerated above, no conversion is possible
5851 return Result;
5852}
5853
5854/// TryCopyInitialization - Try to copy-initialize a value of type
5855/// ToType from the expression From. Return the implicit conversion
5856/// sequence required to pass this argument, which may be a bad
5857/// conversion sequence (meaning that the argument cannot be passed to
5858/// a parameter of this type). If @p SuppressUserConversions, then we
5859/// do not permit any user-defined conversion sequences.
5860static ImplicitConversionSequence
5862 bool SuppressUserConversions,
5863 bool InOverloadResolution,
5864 bool AllowObjCWritebackConversion,
5865 bool AllowExplicit) {
5866 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5867 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5868 InOverloadResolution,AllowObjCWritebackConversion);
5869
5870 if (ToType->isReferenceType())
5871 return TryReferenceInit(S, From, ToType,
5872 /*FIXME:*/ From->getBeginLoc(),
5873 SuppressUserConversions, AllowExplicit);
5874
5875 return TryImplicitConversion(S, From, ToType,
5876 SuppressUserConversions,
5877 AllowedExplicit::None,
5878 InOverloadResolution,
5879 /*CStyle=*/false,
5880 AllowObjCWritebackConversion,
5881 /*AllowObjCConversionOnExplicit=*/false);
5882}
5883
5884static bool TryCopyInitialization(const CanQualType FromQTy,
5885 const CanQualType ToQTy,
5886 Sema &S,
5887 SourceLocation Loc,
5888 ExprValueKind FromVK) {
5889 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5891 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5892
5893 return !ICS.isBad();
5894}
5895
5896/// TryObjectArgumentInitialization - Try to initialize the object
5897/// parameter of the given member function (@c Method) from the
5898/// expression @p From.
5900 Sema &S, SourceLocation Loc, QualType FromType,
5901 Expr::Classification FromClassification, CXXMethodDecl *Method,
5902 const CXXRecordDecl *ActingContext, bool InOverloadResolution = false,
5903 QualType ExplicitParameterType = QualType(),
5904 bool SuppressUserConversion = false) {
5905
5906 // We need to have an object of class type.
5907 if (const auto *PT = FromType->getAs<PointerType>()) {
5908 FromType = PT->getPointeeType();
5909
5910 // When we had a pointer, it's implicitly dereferenced, so we
5911 // better have an lvalue.
5912 assert(FromClassification.isLValue());
5913 }
5914
5915 auto ValueKindFromClassification = [](Expr::Classification C) {
5916 if (C.isPRValue())
5917 return clang::VK_PRValue;
5918 if (C.isXValue())
5919 return VK_XValue;
5920 return clang::VK_LValue;
5921 };
5922
5923 if (Method->isExplicitObjectMemberFunction()) {
5924 if (ExplicitParameterType.isNull())
5925 ExplicitParameterType = Method->getFunctionObjectParameterReferenceType();
5926 OpaqueValueExpr TmpExpr(Loc, FromType.getNonReferenceType(),
5927 ValueKindFromClassification(FromClassification));
5929 S, &TmpExpr, ExplicitParameterType, SuppressUserConversion,
5930 /*InOverloadResolution=*/true, false);
5931 if (ICS.isBad())
5932 ICS.Bad.FromExpr = nullptr;
5933 return ICS;
5934 }
5935
5936 assert(FromType->isRecordType());
5937
5938 CanQualType ClassType = S.Context.getCanonicalTagType(ActingContext);
5939 // C++98 [class.dtor]p2:
5940 // A destructor can be invoked for a const, volatile or const volatile
5941 // object.
5942 // C++98 [over.match.funcs]p4:
5943 // For static member functions, the implicit object parameter is considered
5944 // to match any object (since if the function is selected, the object is
5945 // discarded).
5946 Qualifiers Quals = Method->getMethodQualifiers();
5947 if (isa<CXXDestructorDecl>(Method) || Method->isStatic()) {
5948 Quals.addConst();
5949 Quals.addVolatile();
5950 }
5951
5952 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5953
5954 // Set up the conversion sequence as a "bad" conversion, to allow us
5955 // to exit early.
5957
5958 // C++0x [over.match.funcs]p4:
5959 // For non-static member functions, the type of the implicit object
5960 // parameter is
5961 //
5962 // - "lvalue reference to cv X" for functions declared without a
5963 // ref-qualifier or with the & ref-qualifier
5964 // - "rvalue reference to cv X" for functions declared with the &&
5965 // ref-qualifier
5966 //
5967 // where X is the class of which the function is a member and cv is the
5968 // cv-qualification on the member function declaration.
5969 //
5970 // However, when finding an implicit conversion sequence for the argument, we
5971 // are not allowed to perform user-defined conversions
5972 // (C++ [over.match.funcs]p5). We perform a simplified version of
5973 // reference binding here, that allows class rvalues to bind to
5974 // non-constant references.
5975
5976 // First check the qualifiers.
5977 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5978 // MSVC ignores __unaligned qualifier for overload candidates; do the same.
5979 if (ImplicitParamType.getCVRQualifiers() !=
5980 FromTypeCanon.getLocalCVRQualifiers() &&
5981 !ImplicitParamType.isAtLeastAsQualifiedAs(
5982 withoutUnaligned(S.Context, FromTypeCanon), S.getASTContext())) {
5984 FromType, ImplicitParamType);
5985 return ICS;
5986 }
5987
5988 if (FromTypeCanon.hasAddressSpace()) {
5989 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5990 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5991 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType,
5992 S.getASTContext())) {
5994 FromType, ImplicitParamType);
5995 return ICS;
5996 }
5997 }
5998
5999 // Check that we have either the same type or a derived type. It
6000 // affects the conversion rank.
6001 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
6002 ImplicitConversionKind SecondKind;
6003 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
6004 SecondKind = ICK_Identity;
6005 } else if (S.IsDerivedFrom(Loc, FromType, ClassType)) {
6006 SecondKind = ICK_Derived_To_Base;
6007 } else if (!Method->isExplicitObjectMemberFunction()) {
6009 FromType, ImplicitParamType);
6010 return ICS;
6011 }
6012
6013 // Check the ref-qualifier.
6014 switch (Method->getRefQualifier()) {
6015 case RQ_None:
6016 // Do nothing; we don't care about lvalueness or rvalueness.
6017 break;
6018
6019 case RQ_LValue:
6020 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
6021 // non-const lvalue reference cannot bind to an rvalue
6023 ImplicitParamType);
6024 return ICS;
6025 }
6026 break;
6027
6028 case RQ_RValue:
6029 if (!FromClassification.isRValue()) {
6030 // rvalue reference cannot bind to an lvalue
6032 ImplicitParamType);
6033 return ICS;
6034 }
6035 break;
6036 }
6037
6038 // Success. Mark this as a reference binding.
6039 ICS.setStandard();
6041 ICS.Standard.Second = SecondKind;
6042 ICS.Standard.setFromType(FromType);
6043 ICS.Standard.setAllToTypes(ImplicitParamType);
6044 ICS.Standard.ReferenceBinding = true;
6045 ICS.Standard.DirectBinding = true;
6046 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
6047 ICS.Standard.BindsToFunctionLvalue = false;
6048 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
6049 ICS.Standard.FromBracedInitList = false;
6051 = (Method->getRefQualifier() == RQ_None);
6052 return ICS;
6053}
6054
6055/// PerformObjectArgumentInitialization - Perform initialization of
6056/// the implicit object parameter for the given Method with the given
6057/// expression.
6059 Expr *From, NestedNameSpecifier Qualifier, NamedDecl *FoundDecl,
6061 QualType FromRecordType, DestType;
6062 QualType ImplicitParamRecordType = Method->getFunctionObjectParameterType();
6063
6064 Expr::Classification FromClassification;
6065 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
6066 FromRecordType = PT->getPointeeType();
6067 DestType = Method->getThisType();
6068 FromClassification = Expr::Classification::makeSimpleLValue();
6069 } else {
6070 FromRecordType = From->getType();
6071 DestType = ImplicitParamRecordType;
6072 FromClassification = From->Classify(Context);
6073
6074 // CWG2813 [expr.call]p6:
6075 // If the function is an implicit object member function, the object
6076 // expression of the class member access shall be a glvalue [...]
6077 if (From->isPRValue()) {
6078 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
6079 Method->getRefQualifier() !=
6081 }
6082 }
6083
6084 // Note that we always use the true parent context when performing
6085 // the actual argument initialization.
6087 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
6088 Method->getParent());
6089 if (ICS.isBad()) {
6090 switch (ICS.Bad.Kind) {
6092 Qualifiers FromQs = FromRecordType.getQualifiers();
6093 Qualifiers ToQs = DestType.getQualifiers();
6094 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6095 if (CVR) {
6096 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
6097 << Method->getDeclName() << FromRecordType << (CVR - 1)
6098 << From->getSourceRange();
6099 Diag(Method->getLocation(), diag::note_previous_decl)
6100 << Method->getDeclName();
6101 return ExprError();
6102 }
6103 break;
6104 }
6105
6108 bool IsRValueQualified =
6109 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
6110 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
6111 << Method->getDeclName() << FromClassification.isRValue()
6112 << IsRValueQualified;
6113 Diag(Method->getLocation(), diag::note_previous_decl)
6114 << Method->getDeclName();
6115 return ExprError();
6116 }
6117
6120 break;
6121
6124 llvm_unreachable("Lists are not objects");
6125 }
6126
6127 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
6128 << ImplicitParamRecordType << FromRecordType
6129 << From->getSourceRange();
6130 }
6131
6132 if (ICS.Standard.Second == ICK_Derived_To_Base) {
6133 ExprResult FromRes =
6134 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
6135 if (FromRes.isInvalid())
6136 return ExprError();
6137 From = FromRes.get();
6138 }
6139
6140 if (!Context.hasSameType(From->getType(), DestType)) {
6141 CastKind CK;
6142 QualType PteeTy = DestType->getPointeeType();
6143 LangAS DestAS =
6144 PteeTy.isNull() ? DestType.getAddressSpace() : PteeTy.getAddressSpace();
6145 if (FromRecordType.getAddressSpace() != DestAS)
6146 CK = CK_AddressSpaceConversion;
6147 else
6148 CK = CK_NoOp;
6149 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
6150 }
6151 return From;
6152}
6153
6154/// TryContextuallyConvertToBool - Attempt to contextually convert the
6155/// expression From to bool (C++0x [conv]p3).
6158 // C++ [dcl.init]/17.8:
6159 // - Otherwise, if the initialization is direct-initialization, the source
6160 // type is std::nullptr_t, and the destination type is bool, the initial
6161 // value of the object being initialized is false.
6162 if (From->getType()->isNullPtrType())
6164 S.Context.BoolTy,
6165 From->isGLValue());
6166
6167 // All other direct-initialization of bool is equivalent to an implicit
6168 // conversion to bool in which explicit conversions are permitted.
6169 return TryImplicitConversion(S, From, S.Context.BoolTy,
6170 /*SuppressUserConversions=*/false,
6171 AllowedExplicit::Conversions,
6172 /*InOverloadResolution=*/false,
6173 /*CStyle=*/false,
6174 /*AllowObjCWritebackConversion=*/false,
6175 /*AllowObjCConversionOnExplicit=*/false);
6176}
6177
6179 if (checkPlaceholderForOverload(*this, From))
6180 return ExprError();
6181
6183 if (!ICS.isBad())
6184 return PerformImplicitConversion(From, Context.BoolTy, ICS,
6186
6188 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
6189 << From->getType() << From->getSourceRange();
6190 return ExprError();
6191}
6192
6193/// Check that the specified conversion is permitted in a converted constant
6194/// expression, according to C++11 [expr.const]p3. Return true if the conversion
6195/// is acceptable.
6198 // Since we know that the target type is an integral or unscoped enumeration
6199 // type, most conversion kinds are impossible. All possible First and Third
6200 // conversions are fine.
6201 switch (SCS.Second) {
6202 case ICK_Identity:
6204 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
6206 return true;
6207
6209 // Conversion from an integral or unscoped enumeration type to bool is
6210 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
6211 // conversion, so we allow it in a converted constant expression.
6212 //
6213 // FIXME: Per core issue 1407, we should not allow this, but that breaks
6214 // a lot of popular code. We should at least add a warning for this
6215 // (non-conforming) extension.
6217 SCS.getToType(2)->isBooleanType();
6218
6220 case ICK_Pointer_Member:
6221 // C++1z: null pointer conversions and null member pointer conversions are
6222 // only permitted if the source type is std::nullptr_t.
6223 return SCS.getFromType()->isNullPtrType();
6224
6236 case ICK_Vector_Splat:
6237 case ICK_Complex_Real:
6246 return false;
6247
6252 llvm_unreachable("found a first conversion kind in Second");
6253
6255 case ICK_Qualification:
6256 llvm_unreachable("found a third conversion kind in Second");
6257
6259 break;
6260 }
6261
6262 llvm_unreachable("unknown conversion kind");
6263}
6264
6265/// BuildConvertedConstantExpression - Check that the expression From is a
6266/// converted constant expression of type T, perform the conversion but
6267/// does not evaluate the expression
6269 QualType T, CCEKind CCE,
6270 NamedDecl *Dest,
6271 APValue &PreNarrowingValue) {
6272 [[maybe_unused]] bool isCCEAllowedPreCXX11 =
6274 assert((S.getLangOpts().CPlusPlus11 || isCCEAllowedPreCXX11) &&
6275 "converted constant expression outside C++11 or TTP matching");
6276
6277 if (checkPlaceholderForOverload(S, From))
6278 return ExprError();
6279
6280 // C++1z [expr.const]p3:
6281 // A converted constant expression of type T is an expression,
6282 // implicitly converted to type T, where the converted
6283 // expression is a constant expression and the implicit conversion
6284 // sequence contains only [... list of conversions ...].
6286 (CCE == CCEKind::ExplicitBool || CCE == CCEKind::Noexcept)
6288 : TryCopyInitialization(S, From, T,
6289 /*SuppressUserConversions=*/false,
6290 /*InOverloadResolution=*/false,
6291 /*AllowObjCWritebackConversion=*/false,
6292 /*AllowExplicit=*/false);
6293 StandardConversionSequence *SCS = nullptr;
6294 switch (ICS.getKind()) {
6296 SCS = &ICS.Standard;
6297 break;
6299 if (T->isRecordType())
6300 SCS = &ICS.UserDefined.Before;
6301 else
6302 SCS = &ICS.UserDefined.After;
6303 break;
6307 return S.Diag(From->getBeginLoc(),
6308 diag::err_typecheck_converted_constant_expression)
6309 << From->getType() << From->getSourceRange() << T;
6310 return ExprError();
6311
6314 llvm_unreachable("bad conversion in converted constant expression");
6315 }
6316
6317 // Check that we would only use permitted conversions.
6318 if (!CheckConvertedConstantConversions(S, *SCS)) {
6319 return S.Diag(From->getBeginLoc(),
6320 diag::err_typecheck_converted_constant_expression_disallowed)
6321 << From->getType() << From->getSourceRange() << T;
6322 }
6323 // [...] and where the reference binding (if any) binds directly.
6324 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
6325 return S.Diag(From->getBeginLoc(),
6326 diag::err_typecheck_converted_constant_expression_indirect)
6327 << From->getType() << From->getSourceRange() << T;
6328 }
6329 // 'TryCopyInitialization' returns incorrect info for attempts to bind
6330 // a reference to a bit-field due to C++ [over.ics.ref]p4. Namely,
6331 // 'SCS->DirectBinding' occurs to be set to 'true' despite it is not
6332 // the direct binding according to C++ [dcl.init.ref]p5. Hence, check this
6333 // case explicitly.
6334 if (From->refersToBitField() && T.getTypePtr()->isReferenceType()) {
6335 return S.Diag(From->getBeginLoc(),
6336 diag::err_reference_bind_to_bitfield_in_cce)
6337 << From->getSourceRange();
6338 }
6339
6340 // Usually we can simply apply the ImplicitConversionSequence we formed
6341 // earlier, but that's not guaranteed to work when initializing an object of
6342 // class type.
6343 ExprResult Result;
6344 bool IsTemplateArgument =
6346 if (T->isRecordType()) {
6347 assert(IsTemplateArgument &&
6348 "unexpected class type converted constant expr");
6349 Result = S.PerformCopyInitialization(
6352 SourceLocation(), From);
6353 } else {
6354 Result =
6356 }
6357 if (Result.isInvalid())
6358 return Result;
6359
6360 // C++2a [intro.execution]p5:
6361 // A full-expression is [...] a constant-expression [...]
6362 Result = S.ActOnFinishFullExpr(Result.get(), From->getExprLoc(),
6363 /*DiscardedValue=*/false, /*IsConstexpr=*/true,
6364 IsTemplateArgument);
6365 if (Result.isInvalid())
6366 return Result;
6367
6368 // Check for a narrowing implicit conversion.
6369 bool ReturnPreNarrowingValue = false;
6370 QualType PreNarrowingType;
6371 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
6372 PreNarrowingType)) {
6374 // Implicit conversion to a narrower type, and the value is not a constant
6375 // expression. We'll diagnose this in a moment.
6376 case NK_Not_Narrowing:
6377 break;
6378
6380 if (CCE == CCEKind::ArrayBound &&
6381 PreNarrowingType->isIntegralOrEnumerationType() &&
6382 PreNarrowingValue.isInt()) {
6383 // Don't diagnose array bound narrowing here; we produce more precise
6384 // errors by allowing the un-narrowed value through.
6385 ReturnPreNarrowingValue = true;
6386 break;
6387 }
6388 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6389 << CCE << /*Constant*/ 1
6390 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
6391 break;
6392
6394 // Implicit conversion to a narrower type, but the expression is
6395 // value-dependent so we can't tell whether it's actually narrowing.
6396 // For matching the parameters of a TTP, the conversion is ill-formed
6397 // if it may narrow.
6398 if (CCE != CCEKind::TempArgStrict)
6399 break;
6400 [[fallthrough]];
6401 case NK_Type_Narrowing:
6402 // FIXME: It would be better to diagnose that the expression is not a
6403 // constant expression.
6404 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
6405 << CCE << /*Constant*/ 0 << From->getType() << T;
6406 break;
6407 }
6408 if (!ReturnPreNarrowingValue)
6409 PreNarrowingValue = {};
6410
6411 return Result;
6412}
6413
6414/// CheckConvertedConstantExpression - Check that the expression From is a
6415/// converted constant expression of type T, perform the conversion and produce
6416/// the converted expression, per C++11 [expr.const]p3.
6419 CCEKind CCE, bool RequireInt,
6420 NamedDecl *Dest) {
6421
6422 APValue PreNarrowingValue;
6423 ExprResult Result = BuildConvertedConstantExpression(S, From, T, CCE, Dest,
6424 PreNarrowingValue);
6425 if (Result.isInvalid() || Result.get()->isValueDependent()) {
6426 Value = APValue();
6427 return Result;
6428 }
6429 return S.EvaluateConvertedConstantExpression(Result.get(), T, Value, CCE,
6430 RequireInt, PreNarrowingValue);
6431}
6432
6434 CCEKind CCE,
6435 NamedDecl *Dest) {
6436 APValue PreNarrowingValue;
6437 return ::BuildConvertedConstantExpression(*this, From, T, CCE, Dest,
6438 PreNarrowingValue);
6439}
6440
6442 APValue &Value, CCEKind CCE,
6443 NamedDecl *Dest) {
6444 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false,
6445 Dest);
6446}
6447
6449 llvm::APSInt &Value,
6450 CCEKind CCE) {
6451 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
6452
6453 APValue V;
6454 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true,
6455 /*Dest=*/nullptr);
6456 if (!R.isInvalid() && !R.get()->isValueDependent())
6457 Value = V.getInt();
6458 return R;
6459}
6460
6463 CCEKind CCE, bool RequireInt,
6464 const APValue &PreNarrowingValue) {
6465
6466 ExprResult Result = E;
6467 // Check the expression is a constant expression.
6469 Expr::EvalResult Eval;
6470 Eval.Diag = &Notes;
6471
6472 assert(CCE != CCEKind::TempArgStrict && "unnexpected CCE Kind");
6473
6474 ConstantExprKind Kind;
6475 if (CCE == CCEKind::TemplateArg && T->isRecordType())
6476 Kind = ConstantExprKind::ClassTemplateArgument;
6477 else if (CCE == CCEKind::TemplateArg)
6478 Kind = ConstantExprKind::NonClassTemplateArgument;
6479 else
6480 Kind = ConstantExprKind::Normal;
6481
6482 if (!E->EvaluateAsConstantExpr(Eval, Context, Kind) ||
6483 (RequireInt && !Eval.Val.isInt())) {
6484 // The expression can't be folded, so we can't keep it at this position in
6485 // the AST.
6486 Result = ExprError();
6487 } else {
6488 Value = Eval.Val;
6489
6490 if (Notes.empty()) {
6491 // It's a constant expression.
6492 Expr *E = Result.get();
6493 if (const auto *CE = dyn_cast<ConstantExpr>(E)) {
6494 // We expect a ConstantExpr to have a value associated with it
6495 // by this point.
6496 assert(CE->getResultStorageKind() != ConstantResultStorageKind::None &&
6497 "ConstantExpr has no value associated with it");
6498 (void)CE;
6499 } else {
6501 }
6502 if (!PreNarrowingValue.isAbsent())
6503 Value = std::move(PreNarrowingValue);
6504 return E;
6505 }
6506 }
6507
6508 // It's not a constant expression. Produce an appropriate diagnostic.
6509 if (Notes.size() == 1 &&
6510 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr) {
6511 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
6512 } else if (!Notes.empty() && Notes[0].second.getDiagID() ==
6513 diag::note_constexpr_invalid_template_arg) {
6514 Notes[0].second.setDiagID(diag::err_constexpr_invalid_template_arg);
6515 for (unsigned I = 0; I < Notes.size(); ++I)
6516 Diag(Notes[I].first, Notes[I].second);
6517 } else {
6518 Diag(E->getBeginLoc(), diag::err_expr_not_cce)
6519 << CCE << E->getSourceRange();
6520 for (unsigned I = 0; I < Notes.size(); ++I)
6521 Diag(Notes[I].first, Notes[I].second);
6522 }
6523 return ExprError();
6524}
6525
6526/// dropPointerConversions - If the given standard conversion sequence
6527/// involves any pointer conversions, remove them. This may change
6528/// the result type of the conversion sequence.
6530 if (SCS.Second == ICK_Pointer_Conversion) {
6531 SCS.Second = ICK_Identity;
6532 SCS.Dimension = ICK_Identity;
6533 SCS.Third = ICK_Identity;
6534 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
6535 }
6536}
6537
6538/// TryContextuallyConvertToObjCPointer - Attempt to contextually
6539/// convert the expression From to an Objective-C pointer type.
6540static ImplicitConversionSequence
6542 // Do an implicit conversion to 'id'.
6545 = TryImplicitConversion(S, From, Ty,
6546 // FIXME: Are these flags correct?
6547 /*SuppressUserConversions=*/false,
6548 AllowedExplicit::Conversions,
6549 /*InOverloadResolution=*/false,
6550 /*CStyle=*/false,
6551 /*AllowObjCWritebackConversion=*/false,
6552 /*AllowObjCConversionOnExplicit=*/true);
6553
6554 // Strip off any final conversions to 'id'.
6555 switch (ICS.getKind()) {
6560 break;
6561
6564 break;
6565
6568 break;
6569 }
6570
6571 return ICS;
6572}
6573
6575 if (checkPlaceholderForOverload(*this, From))
6576 return ExprError();
6577
6578 QualType Ty = Context.getObjCIdType();
6581 if (!ICS.isBad())
6582 return PerformImplicitConversion(From, Ty, ICS,
6584 return ExprResult();
6585}
6586
6587static QualType GetExplicitObjectType(Sema &S, const Expr *MemExprE) {
6588 const Expr *Base = nullptr;
6589 assert((isa<UnresolvedMemberExpr, MemberExpr>(MemExprE)) &&
6590 "expected a member expression");
6591
6592 if (const auto M = dyn_cast<UnresolvedMemberExpr>(MemExprE);
6593 M && !M->isImplicitAccess())
6594 Base = M->getBase();
6595 else if (const auto M = dyn_cast<MemberExpr>(MemExprE);
6596 M && !M->isImplicitAccess())
6597 Base = M->getBase();
6598
6599 QualType T = Base ? Base->getType() : S.getCurrentThisType();
6600
6601 if (T->isPointerType())
6602 T = T->getPointeeType();
6603
6604 return T;
6605}
6606
6608 const FunctionDecl *Fun) {
6609 QualType ObjType = Obj->getType();
6610 if (ObjType->isPointerType()) {
6611 ObjType = ObjType->getPointeeType();
6612 Obj = UnaryOperator::Create(S.getASTContext(), Obj, UO_Deref, ObjType,
6614 /*CanOverflow=*/false, FPOptionsOverride());
6615 }
6616 return Obj;
6617}
6618
6626
6628 Expr *Object, MultiExprArg &Args,
6629 SmallVectorImpl<Expr *> &NewArgs) {
6630 assert(Method->isExplicitObjectMemberFunction() &&
6631 "Method is not an explicit member function");
6632 assert(NewArgs.empty() && "NewArgs should be empty");
6633
6634 NewArgs.reserve(Args.size() + 1);
6635 Expr *This = GetExplicitObjectExpr(S, Object, Method);
6636 NewArgs.push_back(This);
6637 NewArgs.append(Args.begin(), Args.end());
6638 Args = NewArgs;
6640 Method, Object->getBeginLoc());
6641}
6642
6643/// Determine whether the provided type is an integral type, or an enumeration
6644/// type of a permitted flavor.
6646 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
6647 : T->isIntegralOrUnscopedEnumerationType();
6648}
6649
6650static ExprResult
6653 QualType T, UnresolvedSetImpl &ViableConversions) {
6654
6655 if (Converter.Suppress)
6656 return ExprError();
6657
6658 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
6659 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
6660 CXXConversionDecl *Conv =
6661 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
6663 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
6664 }
6665 return From;
6666}
6667
6668static bool
6671 QualType T, bool HadMultipleCandidates,
6672 UnresolvedSetImpl &ExplicitConversions) {
6673 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
6674 DeclAccessPair Found = ExplicitConversions[0];
6675 CXXConversionDecl *Conversion =
6676 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6677
6678 // The user probably meant to invoke the given explicit
6679 // conversion; use it.
6680 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
6681 std::string TypeStr;
6682 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
6683
6684 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
6686 "static_cast<" + TypeStr + ">(")
6688 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
6689 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
6690
6691 // If we aren't in a SFINAE context, build a call to the
6692 // explicit conversion function.
6693 if (SemaRef.isSFINAEContext())
6694 return true;
6695
6696 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6697 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6698 HadMultipleCandidates);
6699 if (Result.isInvalid())
6700 return true;
6701
6702 // Replace the conversion with a RecoveryExpr, so we don't try to
6703 // instantiate it later, but can further diagnose here.
6704 Result = SemaRef.CreateRecoveryExpr(From->getBeginLoc(), From->getEndLoc(),
6705 From, Result.get()->getType());
6706 if (Result.isInvalid())
6707 return true;
6708 From = Result.get();
6709 }
6710 return false;
6711}
6712
6713static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
6715 QualType T, bool HadMultipleCandidates,
6717 CXXConversionDecl *Conversion =
6718 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
6719 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
6720
6721 QualType ToType = Conversion->getConversionType().getNonReferenceType();
6722 if (!Converter.SuppressConversion) {
6723 if (SemaRef.isSFINAEContext())
6724 return true;
6725
6726 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
6727 << From->getSourceRange();
6728 }
6729
6730 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
6731 HadMultipleCandidates);
6732 if (Result.isInvalid())
6733 return true;
6734 // Record usage of conversion in an implicit cast.
6735 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
6736 CK_UserDefinedConversion, Result.get(),
6737 nullptr, Result.get()->getValueKind(),
6738 SemaRef.CurFPFeatureOverrides());
6739 return false;
6740}
6741
6743 Sema &SemaRef, SourceLocation Loc, Expr *From,
6745 if (!Converter.match(From->getType()) && !Converter.Suppress)
6746 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
6747 << From->getSourceRange();
6748
6749 return SemaRef.DefaultLvalueConversion(From);
6750}
6751
6752static void
6754 UnresolvedSetImpl &ViableConversions,
6755 OverloadCandidateSet &CandidateSet) {
6756 for (const DeclAccessPair &FoundDecl : ViableConversions.pairs()) {
6757 NamedDecl *D = FoundDecl.getDecl();
6758 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6759 if (isa<UsingShadowDecl>(D))
6760 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6761
6762 if (auto *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)) {
6764 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
6765 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6766 continue;
6767 }
6769 SemaRef.AddConversionCandidate(
6770 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
6771 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit=*/true);
6772 }
6773}
6774
6775/// Attempt to convert the given expression to a type which is accepted
6776/// by the given converter.
6777///
6778/// This routine will attempt to convert an expression of class type to a
6779/// type accepted by the specified converter. In C++11 and before, the class
6780/// must have a single non-explicit conversion function converting to a matching
6781/// type. In C++1y, there can be multiple such conversion functions, but only
6782/// one target type.
6783///
6784/// \param Loc The source location of the construct that requires the
6785/// conversion.
6786///
6787/// \param From The expression we're converting from.
6788///
6789/// \param Converter Used to control and diagnose the conversion process.
6790///
6791/// \returns The expression, converted to an integral or enumeration type if
6792/// successful.
6794 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
6795 // We can't perform any more checking for type-dependent expressions.
6796 if (From->isTypeDependent())
6797 return From;
6798
6799 // Process placeholders immediately.
6800 if (From->hasPlaceholderType()) {
6801 ExprResult result = CheckPlaceholderExpr(From);
6802 if (result.isInvalid())
6803 return result;
6804 From = result.get();
6805 }
6806
6807 // Try converting the expression to an Lvalue first, to get rid of qualifiers.
6808 ExprResult Converted = DefaultLvalueConversion(From);
6809 QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
6810 // If the expression already has a matching type, we're golden.
6811 if (Converter.match(T))
6812 return Converted;
6813
6814 // FIXME: Check for missing '()' if T is a function type?
6815
6816 // We can only perform contextual implicit conversions on objects of class
6817 // type.
6818 const RecordType *RecordTy = T->getAsCanonical<RecordType>();
6819 if (!RecordTy || !getLangOpts().CPlusPlus) {
6820 if (!Converter.Suppress)
6821 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
6822 return From;
6823 }
6824
6825 // We must have a complete class type.
6826 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
6827 ContextualImplicitConverter &Converter;
6828 Expr *From;
6829
6830 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
6831 : Converter(Converter), From(From) {}
6832
6833 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6834 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
6835 }
6836 } IncompleteDiagnoser(Converter, From);
6837
6838 if (Converter.Suppress ? !isCompleteType(Loc, T)
6839 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
6840 return From;
6841
6842 // Look for a conversion to an integral or enumeration type.
6844 ViableConversions; // These are *potentially* viable in C++1y.
6845 UnresolvedSet<4> ExplicitConversions;
6846 const auto &Conversions = cast<CXXRecordDecl>(RecordTy->getOriginalDecl())
6847 ->getDefinitionOrSelf()
6848 ->getVisibleConversionFunctions();
6849
6850 bool HadMultipleCandidates =
6851 (std::distance(Conversions.begin(), Conversions.end()) > 1);
6852
6853 // To check that there is only one target type, in C++1y:
6854 QualType ToType;
6855 bool HasUniqueTargetType = true;
6856
6857 // Collect explicit or viable (potentially in C++1y) conversions.
6858 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
6859 NamedDecl *D = (*I)->getUnderlyingDecl();
6860 CXXConversionDecl *Conversion;
6861 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
6862 if (ConvTemplate) {
6864 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
6865 else
6866 continue; // C++11 does not consider conversion operator templates(?).
6867 } else
6868 Conversion = cast<CXXConversionDecl>(D);
6869
6870 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
6871 "Conversion operator templates are considered potentially "
6872 "viable in C++1y");
6873
6874 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
6875 if (Converter.match(CurToType) || ConvTemplate) {
6876
6877 if (Conversion->isExplicit()) {
6878 // FIXME: For C++1y, do we need this restriction?
6879 // cf. diagnoseNoViableConversion()
6880 if (!ConvTemplate)
6881 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
6882 } else {
6883 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
6884 if (ToType.isNull())
6885 ToType = CurToType.getUnqualifiedType();
6886 else if (HasUniqueTargetType &&
6887 (CurToType.getUnqualifiedType() != ToType))
6888 HasUniqueTargetType = false;
6889 }
6890 ViableConversions.addDecl(I.getDecl(), I.getAccess());
6891 }
6892 }
6893 }
6894
6895 if (getLangOpts().CPlusPlus14) {
6896 // C++1y [conv]p6:
6897 // ... An expression e of class type E appearing in such a context
6898 // is said to be contextually implicitly converted to a specified
6899 // type T and is well-formed if and only if e can be implicitly
6900 // converted to a type T that is determined as follows: E is searched
6901 // for conversion functions whose return type is cv T or reference to
6902 // cv T such that T is allowed by the context. There shall be
6903 // exactly one such T.
6904
6905 // If no unique T is found:
6906 if (ToType.isNull()) {
6907 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6908 HadMultipleCandidates,
6909 ExplicitConversions))
6910 return ExprError();
6911 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6912 }
6913
6914 // If more than one unique Ts are found:
6915 if (!HasUniqueTargetType)
6916 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6917 ViableConversions);
6918
6919 // If one unique T is found:
6920 // First, build a candidate set from the previously recorded
6921 // potentially viable conversions.
6923 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
6924 CandidateSet);
6925
6926 // Then, perform overload resolution over the candidate set.
6928 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
6929 case OR_Success: {
6930 // Apply this conversion.
6932 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
6933 if (recordConversion(*this, Loc, From, Converter, T,
6934 HadMultipleCandidates, Found))
6935 return ExprError();
6936 break;
6937 }
6938 case OR_Ambiguous:
6939 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6940 ViableConversions);
6942 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6943 HadMultipleCandidates,
6944 ExplicitConversions))
6945 return ExprError();
6946 [[fallthrough]];
6947 case OR_Deleted:
6948 // We'll complain below about a non-integral condition type.
6949 break;
6950 }
6951 } else {
6952 switch (ViableConversions.size()) {
6953 case 0: {
6954 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
6955 HadMultipleCandidates,
6956 ExplicitConversions))
6957 return ExprError();
6958
6959 // We'll complain below about a non-integral condition type.
6960 break;
6961 }
6962 case 1: {
6963 // Apply this conversion.
6964 DeclAccessPair Found = ViableConversions[0];
6965 if (recordConversion(*this, Loc, From, Converter, T,
6966 HadMultipleCandidates, Found))
6967 return ExprError();
6968 break;
6969 }
6970 default:
6971 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
6972 ViableConversions);
6973 }
6974 }
6975
6976 return finishContextualImplicitConversion(*this, Loc, From, Converter);
6977}
6978
6979/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
6980/// an acceptable non-member overloaded operator for a call whose
6981/// arguments have types T1 (and, if non-empty, T2). This routine
6982/// implements the check in C++ [over.match.oper]p3b2 concerning
6983/// enumeration types.
6985 FunctionDecl *Fn,
6986 ArrayRef<Expr *> Args) {
6987 QualType T1 = Args[0]->getType();
6988 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
6989
6990 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
6991 return true;
6992
6993 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
6994 return true;
6995
6996 const auto *Proto = Fn->getType()->castAs<FunctionProtoType>();
6997 if (Proto->getNumParams() < 1)
6998 return false;
6999
7000 if (T1->isEnumeralType()) {
7001 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
7002 if (Context.hasSameUnqualifiedType(T1, ArgType))
7003 return true;
7004 }
7005
7006 if (Proto->getNumParams() < 2)
7007 return false;
7008
7009 if (!T2.isNull() && T2->isEnumeralType()) {
7010 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
7011 if (Context.hasSameUnqualifiedType(T2, ArgType))
7012 return true;
7013 }
7014
7015 return false;
7016}
7017
7020 return false;
7021
7022 if (!FD->getASTContext().getTargetInfo().getTriple().isAArch64())
7023 return FD->isTargetMultiVersion();
7024
7025 if (!FD->isMultiVersion())
7026 return false;
7027
7028 // Among multiple target versions consider either the default,
7029 // or the first non-default in the absence of default version.
7030 unsigned SeenAt = 0;
7031 unsigned I = 0;
7032 bool HasDefault = false;
7034 FD, [&](const FunctionDecl *CurFD) {
7035 if (FD == CurFD)
7036 SeenAt = I;
7037 else if (CurFD->isTargetMultiVersionDefault())
7038 HasDefault = true;
7039 ++I;
7040 });
7041 return HasDefault || SeenAt != 0;
7042}
7043
7046 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7047 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
7048 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions,
7049 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction,
7050 bool StrictPackMatch) {
7051 const FunctionProtoType *Proto
7052 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
7053 assert(Proto && "Functions without a prototype cannot be overloaded");
7054 assert(!Function->getDescribedFunctionTemplate() &&
7055 "Use AddTemplateOverloadCandidate for function templates");
7056
7057 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
7059 // If we get here, it's because we're calling a member function
7060 // that is named without a member access expression (e.g.,
7061 // "this->f") that was either written explicitly or created
7062 // implicitly. This can happen with a qualified call to a member
7063 // function, e.g., X::f(). We use an empty type for the implied
7064 // object argument (C++ [over.call.func]p3), and the acting context
7065 // is irrelevant.
7066 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
7068 CandidateSet, SuppressUserConversions,
7069 PartialOverloading, EarlyConversions, PO,
7070 StrictPackMatch);
7071 return;
7072 }
7073 // We treat a constructor like a non-member function, since its object
7074 // argument doesn't participate in overload resolution.
7075 }
7076
7077 if (!CandidateSet.isNewCandidate(Function, PO))
7078 return;
7079
7080 // C++11 [class.copy]p11: [DR1402]
7081 // A defaulted move constructor that is defined as deleted is ignored by
7082 // overload resolution.
7083 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
7084 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
7085 Constructor->isMoveConstructor())
7086 return;
7087
7088 // Overload resolution is always an unevaluated context.
7091
7092 // C++ [over.match.oper]p3:
7093 // if no operand has a class type, only those non-member functions in the
7094 // lookup set that have a first parameter of type T1 or "reference to
7095 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
7096 // is a right operand) a second parameter of type T2 or "reference to
7097 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
7098 // candidate functions.
7099 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
7101 return;
7102
7103 // Add this candidate
7104 OverloadCandidate &Candidate =
7105 CandidateSet.addCandidate(Args.size(), EarlyConversions);
7106 Candidate.FoundDecl = FoundDecl;
7107 Candidate.Function = Function;
7108 Candidate.Viable = true;
7109 Candidate.RewriteKind =
7110 CandidateSet.getRewriteInfo().getRewriteKind(Function, PO);
7111 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
7112 Candidate.ExplicitCallArguments = Args.size();
7113 Candidate.StrictPackMatch = StrictPackMatch;
7114
7115 // Explicit functions are not actually candidates at all if we're not
7116 // allowing them in this context, but keep them around so we can point
7117 // to them in diagnostics.
7118 if (!AllowExplicit && ExplicitSpecifier::getFromDecl(Function).isExplicit()) {
7119 Candidate.Viable = false;
7120 Candidate.FailureKind = ovl_fail_explicit;
7121 return;
7122 }
7123
7124 // Functions with internal linkage are only viable in the same module unit.
7125 if (getLangOpts().CPlusPlusModules && Function->isInAnotherModuleUnit()) {
7126 /// FIXME: Currently, the semantics of linkage in clang is slightly
7127 /// different from the semantics in C++ spec. In C++ spec, only names
7128 /// have linkage. So that all entities of the same should share one
7129 /// linkage. But in clang, different entities of the same could have
7130 /// different linkage.
7131 const NamedDecl *ND = Function;
7132 bool IsImplicitlyInstantiated = false;
7133 if (auto *SpecInfo = Function->getTemplateSpecializationInfo()) {
7134 ND = SpecInfo->getTemplate();
7135 IsImplicitlyInstantiated = SpecInfo->getTemplateSpecializationKind() ==
7137 }
7138
7139 /// Don't remove inline functions with internal linkage from the overload
7140 /// set if they are declared in a GMF, in violation of C++ [basic.link]p17.
7141 /// However:
7142 /// - Inline functions with internal linkage are a common pattern in
7143 /// headers to avoid ODR issues.
7144 /// - The global module is meant to be a transition mechanism for C and C++
7145 /// headers, and the current rules as written work against that goal.
7146 const bool IsInlineFunctionInGMF =
7147 Function->isFromGlobalModule() &&
7148 (IsImplicitlyInstantiated || Function->isInlined());
7149
7150 if (ND->getFormalLinkage() == Linkage::Internal && !IsInlineFunctionInGMF) {
7151 Candidate.Viable = false;
7153 return;
7154 }
7155 }
7156
7158 Candidate.Viable = false;
7160 return;
7161 }
7162
7163 if (Constructor) {
7164 // C++ [class.copy]p3:
7165 // A member function template is never instantiated to perform the copy
7166 // of a class object to an object of its class type.
7167 CanQualType ClassType =
7168 Context.getCanonicalTagType(Constructor->getParent());
7169 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
7170 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
7171 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
7172 ClassType))) {
7173 Candidate.Viable = false;
7175 return;
7176 }
7177
7178 // C++ [over.match.funcs]p8: (proposed DR resolution)
7179 // A constructor inherited from class type C that has a first parameter
7180 // of type "reference to P" (including such a constructor instantiated
7181 // from a template) is excluded from the set of candidate functions when
7182 // constructing an object of type cv D if the argument list has exactly
7183 // one argument and D is reference-related to P and P is reference-related
7184 // to C.
7185 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
7186 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
7187 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
7188 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
7189 CanQualType C = Context.getCanonicalTagType(Constructor->getParent());
7190 CanQualType D = Context.getCanonicalTagType(Shadow->getParent());
7191 SourceLocation Loc = Args.front()->getExprLoc();
7192 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
7193 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
7194 Candidate.Viable = false;
7196 return;
7197 }
7198 }
7199
7200 // Check that the constructor is capable of constructing an object in the
7201 // destination address space.
7203 Constructor->getMethodQualifiers().getAddressSpace(),
7204 CandidateSet.getDestAS(), getASTContext())) {
7205 Candidate.Viable = false;
7207 }
7208 }
7209
7210 unsigned NumParams = Proto->getNumParams();
7211
7212 // (C++ 13.3.2p2): A candidate function having fewer than m
7213 // parameters is viable only if it has an ellipsis in its parameter
7214 // list (8.3.5).
7215 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7216 !Proto->isVariadic() &&
7217 shouldEnforceArgLimit(PartialOverloading, Function)) {
7218 Candidate.Viable = false;
7220 return;
7221 }
7222
7223 // (C++ 13.3.2p2): A candidate function having more than m parameters
7224 // is viable only if the (m+1)st parameter has a default argument
7225 // (8.3.6). For the purposes of overload resolution, the
7226 // parameter list is truncated on the right, so that there are
7227 // exactly m parameters.
7228 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
7229 if (!AggregateCandidateDeduction && Args.size() < MinRequiredArgs &&
7230 !PartialOverloading) {
7231 // Not enough arguments.
7232 Candidate.Viable = false;
7234 return;
7235 }
7236
7237 // (CUDA B.1): Check for invalid calls between targets.
7238 if (getLangOpts().CUDA) {
7239 const FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
7240 // Skip the check for callers that are implicit members, because in this
7241 // case we may not yet know what the member's target is; the target is
7242 // inferred for the member automatically, based on the bases and fields of
7243 // the class.
7244 if (!(Caller && Caller->isImplicit()) &&
7245 !CUDA().IsAllowedCall(Caller, Function)) {
7246 Candidate.Viable = false;
7247 Candidate.FailureKind = ovl_fail_bad_target;
7248 return;
7249 }
7250 }
7251
7252 if (Function->getTrailingRequiresClause()) {
7253 ConstraintSatisfaction Satisfaction;
7254 if (CheckFunctionConstraints(Function, Satisfaction, /*Loc*/ {},
7255 /*ForOverloadResolution*/ true) ||
7256 !Satisfaction.IsSatisfied) {
7257 Candidate.Viable = false;
7259 return;
7260 }
7261 }
7262
7263 assert(PO != OverloadCandidateParamOrder::Reversed || Args.size() == 2);
7264 // Determine the implicit conversion sequences for each of the
7265 // arguments.
7266 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7267 unsigned ConvIdx =
7268 PO == OverloadCandidateParamOrder::Reversed ? 1 - ArgIdx : ArgIdx;
7269 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7270 // We already formed a conversion sequence for this parameter during
7271 // template argument deduction.
7272 } else if (ArgIdx < NumParams) {
7273 // (C++ 13.3.2p3): for F to be a viable function, there shall
7274 // exist for each argument an implicit conversion sequence
7275 // (13.3.3.1) that converts that argument to the corresponding
7276 // parameter of F.
7277 QualType ParamType = Proto->getParamType(ArgIdx);
7278 auto ParamABI = Proto->getExtParameterInfo(ArgIdx).getABI();
7279 if (ParamABI == ParameterABI::HLSLOut ||
7280 ParamABI == ParameterABI::HLSLInOut)
7281 ParamType = ParamType.getNonReferenceType();
7282 Candidate.Conversions[ConvIdx] = TryCopyInitialization(
7283 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
7284 /*InOverloadResolution=*/true,
7285 /*AllowObjCWritebackConversion=*/
7286 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
7287 if (Candidate.Conversions[ConvIdx].isBad()) {
7288 Candidate.Viable = false;
7290 return;
7291 }
7292 } else {
7293 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7294 // argument for which there is no corresponding parameter is
7295 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7296 Candidate.Conversions[ConvIdx].setEllipsis();
7297 }
7298 }
7299
7300 if (EnableIfAttr *FailedAttr =
7301 CheckEnableIf(Function, CandidateSet.getLocation(), Args)) {
7302 Candidate.Viable = false;
7303 Candidate.FailureKind = ovl_fail_enable_if;
7304 Candidate.DeductionFailure.Data = FailedAttr;
7305 return;
7306 }
7307}
7308
7312 if (Methods.size() <= 1)
7313 return nullptr;
7314
7315 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7316 bool Match = true;
7317 ObjCMethodDecl *Method = Methods[b];
7318 unsigned NumNamedArgs = Sel.getNumArgs();
7319 // Method might have more arguments than selector indicates. This is due
7320 // to addition of c-style arguments in method.
7321 if (Method->param_size() > NumNamedArgs)
7322 NumNamedArgs = Method->param_size();
7323 if (Args.size() < NumNamedArgs)
7324 continue;
7325
7326 for (unsigned i = 0; i < NumNamedArgs; i++) {
7327 // We can't do any type-checking on a type-dependent argument.
7328 if (Args[i]->isTypeDependent()) {
7329 Match = false;
7330 break;
7331 }
7332
7333 ParmVarDecl *param = Method->parameters()[i];
7334 Expr *argExpr = Args[i];
7335 assert(argExpr && "SelectBestMethod(): missing expression");
7336
7337 // Strip the unbridged-cast placeholder expression off unless it's
7338 // a consumed argument.
7339 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
7340 !param->hasAttr<CFConsumedAttr>())
7341 argExpr = ObjC().stripARCUnbridgedCast(argExpr);
7342
7343 // If the parameter is __unknown_anytype, move on to the next method.
7344 if (param->getType() == Context.UnknownAnyTy) {
7345 Match = false;
7346 break;
7347 }
7348
7349 ImplicitConversionSequence ConversionState
7350 = TryCopyInitialization(*this, argExpr, param->getType(),
7351 /*SuppressUserConversions*/false,
7352 /*InOverloadResolution=*/true,
7353 /*AllowObjCWritebackConversion=*/
7354 getLangOpts().ObjCAutoRefCount,
7355 /*AllowExplicit*/false);
7356 // This function looks for a reasonably-exact match, so we consider
7357 // incompatible pointer conversions to be a failure here.
7358 if (ConversionState.isBad() ||
7359 (ConversionState.isStandard() &&
7360 ConversionState.Standard.Second ==
7362 Match = false;
7363 break;
7364 }
7365 }
7366 // Promote additional arguments to variadic methods.
7367 if (Match && Method->isVariadic()) {
7368 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
7369 if (Args[i]->isTypeDependent()) {
7370 Match = false;
7371 break;
7372 }
7374 Args[i], VariadicCallType::Method, nullptr);
7375 if (Arg.isInvalid()) {
7376 Match = false;
7377 break;
7378 }
7379 }
7380 } else {
7381 // Check for extra arguments to non-variadic methods.
7382 if (Args.size() != NumNamedArgs)
7383 Match = false;
7384 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
7385 // Special case when selectors have no argument. In this case, select
7386 // one with the most general result type of 'id'.
7387 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
7388 QualType ReturnT = Methods[b]->getReturnType();
7389 if (ReturnT->isObjCIdType())
7390 return Methods[b];
7391 }
7392 }
7393 }
7394
7395 if (Match)
7396 return Method;
7397 }
7398 return nullptr;
7399}
7400
7402 Sema &S, FunctionDecl *Function, Expr *ThisArg, SourceLocation CallLoc,
7403 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap, bool MissingImplicitThis,
7404 Expr *&ConvertedThis, SmallVectorImpl<Expr *> &ConvertedArgs) {
7405 if (ThisArg) {
7406 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
7407 assert(!isa<CXXConstructorDecl>(Method) &&
7408 "Shouldn't have `this` for ctors!");
7409 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
7411 ThisArg, /*Qualifier=*/std::nullopt, Method, Method);
7412 if (R.isInvalid())
7413 return false;
7414 ConvertedThis = R.get();
7415 } else {
7416 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
7417 (void)MD;
7418 assert((MissingImplicitThis || MD->isStatic() ||
7420 "Expected `this` for non-ctor instance methods");
7421 }
7422 ConvertedThis = nullptr;
7423 }
7424
7425 // Ignore any variadic arguments. Converting them is pointless, since the
7426 // user can't refer to them in the function condition.
7427 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
7428
7429 // Convert the arguments.
7430 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
7431 ExprResult R;
7433 S.Context, Function->getParamDecl(I)),
7434 SourceLocation(), Args[I]);
7435
7436 if (R.isInvalid())
7437 return false;
7438
7439 ConvertedArgs.push_back(R.get());
7440 }
7441
7442 if (Trap.hasErrorOccurred())
7443 return false;
7444
7445 // Push default arguments if needed.
7446 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
7447 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
7448 ParmVarDecl *P = Function->getParamDecl(i);
7449 if (!P->hasDefaultArg())
7450 return false;
7451 ExprResult R = S.BuildCXXDefaultArgExpr(CallLoc, Function, P);
7452 if (R.isInvalid())
7453 return false;
7454 ConvertedArgs.push_back(R.get());
7455 }
7456
7457 if (Trap.hasErrorOccurred())
7458 return false;
7459 }
7460 return true;
7461}
7462
7464 SourceLocation CallLoc,
7465 ArrayRef<Expr *> Args,
7466 bool MissingImplicitThis) {
7467 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
7468 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
7469 return nullptr;
7470
7471 SFINAETrap Trap(*this);
7472 SmallVector<Expr *, 16> ConvertedArgs;
7473 // FIXME: We should look into making enable_if late-parsed.
7474 Expr *DiscardedThis;
7476 *this, Function, /*ThisArg=*/nullptr, CallLoc, Args, Trap,
7477 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
7478 return *EnableIfAttrs.begin();
7479
7480 for (auto *EIA : EnableIfAttrs) {
7482 // FIXME: This doesn't consider value-dependent cases, because doing so is
7483 // very difficult. Ideally, we should handle them more gracefully.
7484 if (EIA->getCond()->isValueDependent() ||
7485 !EIA->getCond()->EvaluateWithSubstitution(
7486 Result, Context, Function, llvm::ArrayRef(ConvertedArgs)))
7487 return EIA;
7488
7489 if (!Result.isInt() || !Result.getInt().getBoolValue())
7490 return EIA;
7491 }
7492 return nullptr;
7493}
7494
7495template <typename CheckFn>
7497 bool ArgDependent, SourceLocation Loc,
7498 CheckFn &&IsSuccessful) {
7500 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
7501 if (ArgDependent == DIA->getArgDependent())
7502 Attrs.push_back(DIA);
7503 }
7504
7505 // Common case: No diagnose_if attributes, so we can quit early.
7506 if (Attrs.empty())
7507 return false;
7508
7509 auto WarningBegin = std::stable_partition(
7510 Attrs.begin(), Attrs.end(), [](const DiagnoseIfAttr *DIA) {
7511 return DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_error &&
7512 DIA->getWarningGroup().empty();
7513 });
7514
7515 // Note that diagnose_if attributes are late-parsed, so they appear in the
7516 // correct order (unlike enable_if attributes).
7517 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
7518 IsSuccessful);
7519 if (ErrAttr != WarningBegin) {
7520 const DiagnoseIfAttr *DIA = *ErrAttr;
7521 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
7522 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7523 << DIA->getParent() << DIA->getCond()->getSourceRange();
7524 return true;
7525 }
7526
7527 auto ToSeverity = [](DiagnoseIfAttr::DefaultSeverity Sev) {
7528 switch (Sev) {
7529 case DiagnoseIfAttr::DS_warning:
7531 case DiagnoseIfAttr::DS_error:
7532 return diag::Severity::Error;
7533 }
7534 llvm_unreachable("Fully covered switch above!");
7535 };
7536
7537 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
7538 if (IsSuccessful(DIA)) {
7539 if (DIA->getWarningGroup().empty() &&
7540 DIA->getDefaultSeverity() == DiagnoseIfAttr::DS_warning) {
7541 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
7542 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
7543 << DIA->getParent() << DIA->getCond()->getSourceRange();
7544 } else {
7545 auto DiagGroup = S.Diags.getDiagnosticIDs()->getGroupForWarningOption(
7546 DIA->getWarningGroup());
7547 assert(DiagGroup);
7548 auto DiagID = S.Diags.getDiagnosticIDs()->getCustomDiagID(
7549 {ToSeverity(DIA->getDefaultSeverity()), "%0",
7550 DiagnosticIDs::CLASS_WARNING, false, false, *DiagGroup});
7551 S.Diag(Loc, DiagID) << DIA->getMessage();
7552 }
7553 }
7554
7555 return false;
7556}
7557
7559 const Expr *ThisArg,
7561 SourceLocation Loc) {
7563 *this, Function, /*ArgDependent=*/true, Loc,
7564 [&](const DiagnoseIfAttr *DIA) {
7566 // It's sane to use the same Args for any redecl of this function, since
7567 // EvaluateWithSubstitution only cares about the position of each
7568 // argument in the arg list, not the ParmVarDecl* it maps to.
7569 if (!DIA->getCond()->EvaluateWithSubstitution(
7570 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
7571 return false;
7572 return Result.isInt() && Result.getInt().getBoolValue();
7573 });
7574}
7575
7577 SourceLocation Loc) {
7579 *this, ND, /*ArgDependent=*/false, Loc,
7580 [&](const DiagnoseIfAttr *DIA) {
7581 bool Result;
7582 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
7583 Result;
7584 });
7585}
7586
7588 ArrayRef<Expr *> Args,
7589 OverloadCandidateSet &CandidateSet,
7590 TemplateArgumentListInfo *ExplicitTemplateArgs,
7591 bool SuppressUserConversions,
7592 bool PartialOverloading,
7593 bool FirstArgumentIsBase) {
7594 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
7595 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
7596 ArrayRef<Expr *> FunctionArgs = Args;
7597
7598 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
7599 FunctionDecl *FD =
7600 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
7601
7602 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
7603 QualType ObjectType;
7604 Expr::Classification ObjectClassification;
7605 if (Args.size() > 0) {
7606 if (Expr *E = Args[0]) {
7607 // Use the explicit base to restrict the lookup:
7608 ObjectType = E->getType();
7609 // Pointers in the object arguments are implicitly dereferenced, so we
7610 // always classify them as l-values.
7611 if (!ObjectType.isNull() && ObjectType->isPointerType())
7612 ObjectClassification = Expr::Classification::makeSimpleLValue();
7613 else
7614 ObjectClassification = E->Classify(Context);
7615 } // .. else there is an implicit base.
7616 FunctionArgs = Args.slice(1);
7617 }
7618 if (FunTmpl) {
7620 FunTmpl, F.getPair(),
7622 ExplicitTemplateArgs, ObjectType, ObjectClassification,
7623 FunctionArgs, CandidateSet, SuppressUserConversions,
7624 PartialOverloading);
7625 } else {
7626 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
7627 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
7628 ObjectClassification, FunctionArgs, CandidateSet,
7629 SuppressUserConversions, PartialOverloading);
7630 }
7631 } else {
7632 // This branch handles both standalone functions and static methods.
7633
7634 // Slice the first argument (which is the base) when we access
7635 // static method as non-static.
7636 if (Args.size() > 0 &&
7637 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
7638 !isa<CXXConstructorDecl>(FD)))) {
7639 assert(cast<CXXMethodDecl>(FD)->isStatic());
7640 FunctionArgs = Args.slice(1);
7641 }
7642 if (FunTmpl) {
7643 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
7644 ExplicitTemplateArgs, FunctionArgs,
7645 CandidateSet, SuppressUserConversions,
7646 PartialOverloading);
7647 } else {
7648 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
7649 SuppressUserConversions, PartialOverloading);
7650 }
7651 }
7652 }
7653}
7654
7656 Expr::Classification ObjectClassification,
7657 ArrayRef<Expr *> Args,
7658 OverloadCandidateSet &CandidateSet,
7659 bool SuppressUserConversions,
7661 NamedDecl *Decl = FoundDecl.getDecl();
7663
7665 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
7666
7667 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
7668 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
7669 "Expected a member function template");
7670 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
7671 /*ExplicitArgs*/ nullptr, ObjectType,
7672 ObjectClassification, Args, CandidateSet,
7673 SuppressUserConversions, false, PO);
7674 } else {
7675 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
7676 ObjectType, ObjectClassification, Args, CandidateSet,
7677 SuppressUserConversions, false, {}, PO);
7678 }
7679}
7680
7683 CXXRecordDecl *ActingContext, QualType ObjectType,
7684 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7685 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7686 bool PartialOverloading, ConversionSequenceList EarlyConversions,
7687 OverloadCandidateParamOrder PO, bool StrictPackMatch) {
7688 const FunctionProtoType *Proto
7689 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
7690 assert(Proto && "Methods without a prototype cannot be overloaded");
7692 "Use AddOverloadCandidate for constructors");
7693
7694 if (!CandidateSet.isNewCandidate(Method, PO))
7695 return;
7696
7697 // C++11 [class.copy]p23: [DR1402]
7698 // A defaulted move assignment operator that is defined as deleted is
7699 // ignored by overload resolution.
7700 if (Method->isDefaulted() && Method->isDeleted() &&
7701 Method->isMoveAssignmentOperator())
7702 return;
7703
7704 // Overload resolution is always an unevaluated context.
7707
7708 bool IgnoreExplicitObject =
7709 (Method->isExplicitObjectMemberFunction() &&
7710 CandidateSet.getKind() ==
7712 bool ImplicitObjectMethodTreatedAsStatic =
7713 CandidateSet.getKind() ==
7715 Method->isImplicitObjectMemberFunction();
7716
7717 unsigned ExplicitOffset =
7718 !IgnoreExplicitObject && Method->isExplicitObjectMemberFunction() ? 1 : 0;
7719
7720 unsigned NumParams = Method->getNumParams() - ExplicitOffset +
7721 int(ImplicitObjectMethodTreatedAsStatic);
7722
7723 unsigned ExtraArgs =
7725 ? 0
7726 : 1;
7727
7728 // Add this candidate
7729 OverloadCandidate &Candidate =
7730 CandidateSet.addCandidate(Args.size() + ExtraArgs, EarlyConversions);
7731 Candidate.FoundDecl = FoundDecl;
7732 Candidate.Function = Method;
7733 Candidate.RewriteKind =
7734 CandidateSet.getRewriteInfo().getRewriteKind(Method, PO);
7735 Candidate.TookAddressOfOverload =
7737 Candidate.ExplicitCallArguments = Args.size();
7738 Candidate.StrictPackMatch = StrictPackMatch;
7739
7740 // (C++ 13.3.2p2): A candidate function having fewer than m
7741 // parameters is viable only if it has an ellipsis in its parameter
7742 // list (8.3.5).
7743 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
7744 !Proto->isVariadic() &&
7745 shouldEnforceArgLimit(PartialOverloading, Method)) {
7746 Candidate.Viable = false;
7748 return;
7749 }
7750
7751 // (C++ 13.3.2p2): A candidate function having more than m parameters
7752 // is viable only if the (m+1)st parameter has a default argument
7753 // (8.3.6). For the purposes of overload resolution, the
7754 // parameter list is truncated on the right, so that there are
7755 // exactly m parameters.
7756 unsigned MinRequiredArgs = Method->getMinRequiredArguments() -
7757 ExplicitOffset +
7758 int(ImplicitObjectMethodTreatedAsStatic);
7759
7760 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
7761 // Not enough arguments.
7762 Candidate.Viable = false;
7764 return;
7765 }
7766
7767 Candidate.Viable = true;
7768
7769 unsigned FirstConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
7770 if (!IgnoreExplicitObject) {
7771 if (ObjectType.isNull())
7772 Candidate.IgnoreObjectArgument = true;
7773 else if (Method->isStatic()) {
7774 // [over.best.ics.general]p8
7775 // When the parameter is the implicit object parameter of a static member
7776 // function, the implicit conversion sequence is a standard conversion
7777 // sequence that is neither better nor worse than any other standard
7778 // conversion sequence.
7779 //
7780 // This is a rule that was introduced in C++23 to support static lambdas.
7781 // We apply it retroactively because we want to support static lambdas as
7782 // an extension and it doesn't hurt previous code.
7783 Candidate.Conversions[FirstConvIdx].setStaticObjectArgument();
7784 } else {
7785 // Determine the implicit conversion sequence for the object
7786 // parameter.
7787 Candidate.Conversions[FirstConvIdx] = TryObjectArgumentInitialization(
7788 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
7789 Method, ActingContext, /*InOverloadResolution=*/true);
7790 if (Candidate.Conversions[FirstConvIdx].isBad()) {
7791 Candidate.Viable = false;
7793 return;
7794 }
7795 }
7796 }
7797
7798 // (CUDA B.1): Check for invalid calls between targets.
7799 if (getLangOpts().CUDA)
7800 if (!CUDA().IsAllowedCall(getCurFunctionDecl(/*AllowLambda=*/true),
7801 Method)) {
7802 Candidate.Viable = false;
7803 Candidate.FailureKind = ovl_fail_bad_target;
7804 return;
7805 }
7806
7807 if (Method->getTrailingRequiresClause()) {
7808 ConstraintSatisfaction Satisfaction;
7809 if (CheckFunctionConstraints(Method, Satisfaction, /*Loc*/ {},
7810 /*ForOverloadResolution*/ true) ||
7811 !Satisfaction.IsSatisfied) {
7812 Candidate.Viable = false;
7814 return;
7815 }
7816 }
7817
7818 // Determine the implicit conversion sequences for each of the
7819 // arguments.
7820 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
7821 unsigned ConvIdx =
7822 PO == OverloadCandidateParamOrder::Reversed ? 0 : (ArgIdx + ExtraArgs);
7823 if (Candidate.Conversions[ConvIdx].isInitialized()) {
7824 // We already formed a conversion sequence for this parameter during
7825 // template argument deduction.
7826 } else if (ArgIdx < NumParams) {
7827 // (C++ 13.3.2p3): for F to be a viable function, there shall
7828 // exist for each argument an implicit conversion sequence
7829 // (13.3.3.1) that converts that argument to the corresponding
7830 // parameter of F.
7831 QualType ParamType;
7832 if (ImplicitObjectMethodTreatedAsStatic) {
7833 ParamType = ArgIdx == 0
7834 ? Method->getFunctionObjectParameterReferenceType()
7835 : Proto->getParamType(ArgIdx - 1);
7836 } else {
7837 ParamType = Proto->getParamType(ArgIdx + ExplicitOffset);
7838 }
7839 Candidate.Conversions[ConvIdx]
7840 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7841 SuppressUserConversions,
7842 /*InOverloadResolution=*/true,
7843 /*AllowObjCWritebackConversion=*/
7844 getLangOpts().ObjCAutoRefCount);
7845 if (Candidate.Conversions[ConvIdx].isBad()) {
7846 Candidate.Viable = false;
7848 return;
7849 }
7850 } else {
7851 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7852 // argument for which there is no corresponding parameter is
7853 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
7854 Candidate.Conversions[ConvIdx].setEllipsis();
7855 }
7856 }
7857
7858 if (EnableIfAttr *FailedAttr =
7859 CheckEnableIf(Method, CandidateSet.getLocation(), Args, true)) {
7860 Candidate.Viable = false;
7861 Candidate.FailureKind = ovl_fail_enable_if;
7862 Candidate.DeductionFailure.Data = FailedAttr;
7863 return;
7864 }
7865
7867 Candidate.Viable = false;
7869 }
7870}
7871
7873 Sema &S, OverloadCandidateSet &CandidateSet,
7874 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7875 CXXRecordDecl *ActingContext,
7876 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7877 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7878 bool SuppressUserConversions, bool PartialOverloading,
7880
7881 // C++ [over.match.funcs]p7:
7882 // In each case where a candidate is a function template, candidate
7883 // function template specializations are generated using template argument
7884 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
7885 // candidate functions in the usual way.113) A given name can refer to one
7886 // or more function templates and also to a set of overloaded non-template
7887 // functions. In such a case, the candidate functions generated from each
7888 // function template are combined with the set of non-template candidate
7889 // functions.
7890 TemplateDeductionInfo Info(CandidateSet.getLocation());
7891 auto *Method = cast<CXXMethodDecl>(MethodTmpl->getTemplatedDecl());
7892 FunctionDecl *Specialization = nullptr;
7893 ConversionSequenceList Conversions;
7895 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
7896 PartialOverloading, /*AggregateDeductionCandidate=*/false,
7897 /*PartialOrdering=*/false, ObjectType, ObjectClassification,
7898 CandidateSet.getKind() ==
7900 [&](ArrayRef<QualType> ParamTypes,
7901 bool OnlyInitializeNonUserDefinedConversions) {
7902 return S.CheckNonDependentConversions(
7903 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
7904 Sema::CheckNonDependentConversionsFlag(
7905 SuppressUserConversions,
7906 OnlyInitializeNonUserDefinedConversions),
7907 ActingContext, ObjectType, ObjectClassification, PO);
7908 });
7910 OverloadCandidate &Candidate =
7911 CandidateSet.addCandidate(Conversions.size(), Conversions);
7912 Candidate.FoundDecl = FoundDecl;
7913 Candidate.Function = Method;
7914 Candidate.Viable = false;
7915 Candidate.RewriteKind =
7916 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
7917 Candidate.IsSurrogate = false;
7918 Candidate.TookAddressOfOverload =
7919 CandidateSet.getKind() ==
7921
7922 Candidate.IgnoreObjectArgument =
7923 Method->isStatic() ||
7924 (!Method->isExplicitObjectMemberFunction() && ObjectType.isNull());
7925 Candidate.ExplicitCallArguments = Args.size();
7928 else {
7930 Candidate.DeductionFailure =
7931 MakeDeductionFailureInfo(S.Context, Result, Info);
7932 }
7933 return;
7934 }
7935
7936 // Add the function template specialization produced by template argument
7937 // deduction as a candidate.
7938 assert(Specialization && "Missing member function template specialization?");
7940 "Specialization is not a member function?");
7942 cast<CXXMethodDecl>(Specialization), FoundDecl, ActingContext, ObjectType,
7943 ObjectClassification, Args, CandidateSet, SuppressUserConversions,
7944 PartialOverloading, Conversions, PO, Info.hasStrictPackMatch());
7945}
7946
7948 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
7949 CXXRecordDecl *ActingContext,
7950 TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType,
7951 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
7952 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
7953 bool PartialOverloading, OverloadCandidateParamOrder PO) {
7954 if (!CandidateSet.isNewCandidate(MethodTmpl, PO))
7955 return;
7956
7957 if (ExplicitTemplateArgs ||
7960 *this, CandidateSet, MethodTmpl, FoundDecl, ActingContext,
7961 ExplicitTemplateArgs, ObjectType, ObjectClassification, Args,
7962 SuppressUserConversions, PartialOverloading, PO);
7963 return;
7964 }
7965
7967 MethodTmpl, FoundDecl, ActingContext, ObjectType, ObjectClassification,
7968 Args, SuppressUserConversions, PartialOverloading, PO);
7969}
7970
7971/// Determine whether a given function template has a simple explicit specifier
7972/// or a non-value-dependent explicit-specification that evaluates to true.
7976
7981
7983 Sema &S, OverloadCandidateSet &CandidateSet,
7985 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
7986 bool SuppressUserConversions, bool PartialOverloading, bool AllowExplicit,
7988 bool AggregateCandidateDeduction) {
7989
7990 // If the function template has a non-dependent explicit specification,
7991 // exclude it now if appropriate; we are not permitted to perform deduction
7992 // and substitution in this case.
7993 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
7994 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7995 Candidate.FoundDecl = FoundDecl;
7996 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7997 Candidate.Viable = false;
7998 Candidate.FailureKind = ovl_fail_explicit;
7999 return;
8000 }
8001
8002 // C++ [over.match.funcs]p7:
8003 // In each case where a candidate is a function template, candidate
8004 // function template specializations are generated using template argument
8005 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
8006 // candidate functions in the usual way.113) A given name can refer to one
8007 // or more function templates and also to a set of overloaded non-template
8008 // functions. In such a case, the candidate functions generated from each
8009 // function template are combined with the set of non-template candidate
8010 // functions.
8011 TemplateDeductionInfo Info(CandidateSet.getLocation(),
8012 FunctionTemplate->getTemplateDepth());
8013 FunctionDecl *Specialization = nullptr;
8014 ConversionSequenceList Conversions;
8016 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
8017 PartialOverloading, AggregateCandidateDeduction,
8018 /*PartialOrdering=*/false,
8019 /*ObjectType=*/QualType(),
8020 /*ObjectClassification=*/Expr::Classification(),
8021 CandidateSet.getKind() ==
8023 [&](ArrayRef<QualType> ParamTypes,
8024 bool OnlyInitializeNonUserDefinedConversions) {
8025 return S.CheckNonDependentConversions(
8026 FunctionTemplate, ParamTypes, Args, CandidateSet, Conversions,
8027 Sema::CheckNonDependentConversionsFlag(
8028 SuppressUserConversions,
8029 OnlyInitializeNonUserDefinedConversions),
8030 nullptr, QualType(), {}, PO);
8031 });
8033 OverloadCandidate &Candidate =
8034 CandidateSet.addCandidate(Conversions.size(), Conversions);
8035 Candidate.FoundDecl = FoundDecl;
8036 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8037 Candidate.Viable = false;
8038 Candidate.RewriteKind =
8039 CandidateSet.getRewriteInfo().getRewriteKind(Candidate.Function, PO);
8040 Candidate.IsSurrogate = false;
8041 Candidate.IsADLCandidate = llvm::to_underlying(IsADLCandidate);
8042 // Ignore the object argument if there is one, since we don't have an object
8043 // type.
8044 Candidate.TookAddressOfOverload =
8045 CandidateSet.getKind() ==
8047
8048 Candidate.IgnoreObjectArgument =
8049 isa<CXXMethodDecl>(Candidate.Function) &&
8050 !cast<CXXMethodDecl>(Candidate.Function)
8051 ->isExplicitObjectMemberFunction() &&
8053
8054 Candidate.ExplicitCallArguments = Args.size();
8057 else {
8059 Candidate.DeductionFailure =
8061 }
8062 return;
8063 }
8064
8065 // Add the function template specialization produced by template argument
8066 // deduction as a candidate.
8067 assert(Specialization && "Missing function template specialization?");
8069 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
8070 PartialOverloading, AllowExplicit,
8071 /*AllowExplicitConversions=*/false, IsADLCandidate, Conversions, PO,
8072 Info.AggregateDeductionCandidateHasMismatchedArity,
8073 Info.hasStrictPackMatch());
8074}
8075
8078 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
8079 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
8080 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate,
8081 OverloadCandidateParamOrder PO, bool AggregateCandidateDeduction) {
8082 if (!CandidateSet.isNewCandidate(FunctionTemplate, PO))
8083 return;
8084
8085 bool DependentExplicitSpecifier = hasDependentExplicit(FunctionTemplate);
8086
8087 if (ExplicitTemplateArgs ||
8089 (isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl()) &&
8090 DependentExplicitSpecifier)) {
8091
8093 *this, CandidateSet, FunctionTemplate, FoundDecl, ExplicitTemplateArgs,
8094 Args, SuppressUserConversions, PartialOverloading, AllowExplicit,
8095 IsADLCandidate, PO, AggregateCandidateDeduction);
8096
8097 if (DependentExplicitSpecifier)
8099 return;
8100 }
8101
8102 CandidateSet.AddDeferredTemplateCandidate(
8103 FunctionTemplate, FoundDecl, Args, SuppressUserConversions,
8104 PartialOverloading, AllowExplicit, IsADLCandidate, PO,
8105 AggregateCandidateDeduction);
8106}
8107
8110 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
8112 CheckNonDependentConversionsFlag UserConversionFlag,
8113 CXXRecordDecl *ActingContext, QualType ObjectType,
8114 Expr::Classification ObjectClassification, OverloadCandidateParamOrder PO) {
8115 // FIXME: The cases in which we allow explicit conversions for constructor
8116 // arguments never consider calling a constructor template. It's not clear
8117 // that is correct.
8118 const bool AllowExplicit = false;
8119
8120 bool ForOverloadSetAddressResolution =
8122 auto *FD = FunctionTemplate->getTemplatedDecl();
8123 auto *Method = dyn_cast<CXXMethodDecl>(FD);
8124 bool HasThisConversion = !ForOverloadSetAddressResolution && Method &&
8126 unsigned ThisConversions = HasThisConversion ? 1 : 0;
8127
8128 if (Conversions.empty())
8129 Conversions =
8130 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
8131
8132 // Overload resolution is always an unevaluated context.
8135
8136 // For a method call, check the 'this' conversion here too. DR1391 doesn't
8137 // require that, but this check should never result in a hard error, and
8138 // overload resolution is permitted to sidestep instantiations.
8139 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
8140 !ObjectType.isNull()) {
8141 unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed ? 1 : 0;
8142 if (!FD->hasCXXExplicitFunctionObjectParameter() ||
8143 !ParamTypes[0]->isDependentType()) {
8145 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
8146 Method, ActingContext, /*InOverloadResolution=*/true,
8147 FD->hasCXXExplicitFunctionObjectParameter() ? ParamTypes[0]
8148 : QualType());
8149 if (Conversions[ConvIdx].isBad())
8150 return true;
8151 }
8152 }
8153
8154 // A speculative workaround for self-dependent constraint bugs that manifest
8155 // after CWG2369.
8156 // FIXME: Add references to the standard once P3606 is adopted.
8157 auto MaybeInvolveUserDefinedConversion = [&](QualType ParamType,
8158 QualType ArgType) {
8159 ParamType = ParamType.getNonReferenceType();
8160 ArgType = ArgType.getNonReferenceType();
8161 bool PointerConv = ParamType->isPointerType() && ArgType->isPointerType();
8162 if (PointerConv) {
8163 ParamType = ParamType->getPointeeType();
8164 ArgType = ArgType->getPointeeType();
8165 }
8166
8167 if (auto *RD = ParamType->getAsCXXRecordDecl();
8168 RD && RD->hasDefinition() &&
8169 llvm::any_of(LookupConstructors(RD), [](NamedDecl *ND) {
8170 auto Info = getConstructorInfo(ND);
8171 if (!Info)
8172 return false;
8173 CXXConstructorDecl *Ctor = Info.Constructor;
8174 /// isConvertingConstructor takes copy/move constructors into
8175 /// account!
8176 return !Ctor->isCopyOrMoveConstructor() &&
8178 /*AllowExplicit=*/true);
8179 }))
8180 return true;
8181 if (auto *RD = ArgType->getAsCXXRecordDecl();
8182 RD && RD->hasDefinition() &&
8183 !RD->getVisibleConversionFunctions().empty())
8184 return true;
8185
8186 return false;
8187 };
8188
8189 unsigned Offset =
8190 HasThisConversion && Method->hasCXXExplicitFunctionObjectParameter() ? 1
8191 : 0;
8192
8193 for (unsigned I = 0, N = std::min(ParamTypes.size() - Offset, Args.size());
8194 I != N; ++I) {
8195 QualType ParamType = ParamTypes[I + Offset];
8196 if (!ParamType->isDependentType()) {
8197 unsigned ConvIdx;
8199 ConvIdx = Args.size() - 1 - I;
8200 assert(Args.size() + ThisConversions == 2 &&
8201 "number of args (including 'this') must be exactly 2 for "
8202 "reversed order");
8203 // For members, there would be only one arg 'Args[0]' whose ConvIdx
8204 // would also be 0. 'this' got ConvIdx = 1 previously.
8205 assert(!HasThisConversion || (ConvIdx == 0 && I == 0));
8206 } else {
8207 // For members, 'this' got ConvIdx = 0 previously.
8208 ConvIdx = ThisConversions + I;
8209 }
8210 if (Conversions[ConvIdx].isInitialized())
8211 continue;
8212 if (UserConversionFlag.OnlyInitializeNonUserDefinedConversions &&
8213 MaybeInvolveUserDefinedConversion(ParamType, Args[I]->getType()))
8214 continue;
8216 *this, Args[I], ParamType, UserConversionFlag.SuppressUserConversions,
8217 /*InOverloadResolution=*/true,
8218 /*AllowObjCWritebackConversion=*/
8219 getLangOpts().ObjCAutoRefCount, AllowExplicit);
8220 if (Conversions[ConvIdx].isBad())
8221 return true;
8222 }
8223 }
8224
8225 return false;
8226}
8227
8228/// Determine whether this is an allowable conversion from the result
8229/// of an explicit conversion operator to the expected type, per C++
8230/// [over.match.conv]p1 and [over.match.ref]p1.
8231///
8232/// \param ConvType The return type of the conversion function.
8233///
8234/// \param ToType The type we are converting to.
8235///
8236/// \param AllowObjCPointerConversion Allow a conversion from one
8237/// Objective-C pointer to another.
8238///
8239/// \returns true if the conversion is allowable, false otherwise.
8241 QualType ConvType, QualType ToType,
8242 bool AllowObjCPointerConversion) {
8243 QualType ToNonRefType = ToType.getNonReferenceType();
8244
8245 // Easy case: the types are the same.
8246 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
8247 return true;
8248
8249 // Allow qualification conversions.
8250 bool ObjCLifetimeConversion;
8251 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
8252 ObjCLifetimeConversion))
8253 return true;
8254
8255 // If we're not allowed to consider Objective-C pointer conversions,
8256 // we're done.
8257 if (!AllowObjCPointerConversion)
8258 return false;
8259
8260 // Is this an Objective-C pointer conversion?
8261 bool IncompatibleObjC = false;
8262 QualType ConvertedType;
8263 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
8264 IncompatibleObjC);
8265}
8266
8268 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
8269 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8270 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8271 bool AllowExplicit, bool AllowResultConversion, bool StrictPackMatch) {
8272 assert(!Conversion->getDescribedFunctionTemplate() &&
8273 "Conversion function templates use AddTemplateConversionCandidate");
8274 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
8275 if (!CandidateSet.isNewCandidate(Conversion))
8276 return;
8277
8278 // If the conversion function has an undeduced return type, trigger its
8279 // deduction now.
8280 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
8281 if (DeduceReturnType(Conversion, From->getExprLoc()))
8282 return;
8283 ConvType = Conversion->getConversionType().getNonReferenceType();
8284 }
8285
8286 // If we don't allow any conversion of the result type, ignore conversion
8287 // functions that don't convert to exactly (possibly cv-qualified) T.
8288 if (!AllowResultConversion &&
8289 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
8290 return;
8291
8292 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
8293 // operator is only a candidate if its return type is the target type or
8294 // can be converted to the target type with a qualification conversion.
8295 //
8296 // FIXME: Include such functions in the candidate list and explain why we
8297 // can't select them.
8298 if (Conversion->isExplicit() &&
8299 !isAllowableExplicitConversion(*this, ConvType, ToType,
8300 AllowObjCConversionOnExplicit))
8301 return;
8302
8303 // Overload resolution is always an unevaluated context.
8306
8307 // Add this candidate
8308 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
8309 Candidate.FoundDecl = FoundDecl;
8310 Candidate.Function = Conversion;
8312 Candidate.FinalConversion.setFromType(ConvType);
8313 Candidate.FinalConversion.setAllToTypes(ToType);
8314 Candidate.HasFinalConversion = true;
8315 Candidate.Viable = true;
8316 Candidate.ExplicitCallArguments = 1;
8317 Candidate.StrictPackMatch = StrictPackMatch;
8318
8319 // Explicit functions are not actually candidates at all if we're not
8320 // allowing them in this context, but keep them around so we can point
8321 // to them in diagnostics.
8322 if (!AllowExplicit && Conversion->isExplicit()) {
8323 Candidate.Viable = false;
8324 Candidate.FailureKind = ovl_fail_explicit;
8325 return;
8326 }
8327
8328 // C++ [over.match.funcs]p4:
8329 // For conversion functions, the function is considered to be a member of
8330 // the class of the implicit implied object argument for the purpose of
8331 // defining the type of the implicit object parameter.
8332 //
8333 // Determine the implicit conversion sequence for the implicit
8334 // object parameter.
8335 QualType ObjectType = From->getType();
8336 if (const auto *FromPtrType = ObjectType->getAs<PointerType>())
8337 ObjectType = FromPtrType->getPointeeType();
8338 const auto *ConversionContext = ObjectType->castAsCXXRecordDecl();
8339 // C++23 [over.best.ics.general]
8340 // However, if the target is [...]
8341 // - the object parameter of a user-defined conversion function
8342 // [...] user-defined conversion sequences are not considered.
8344 *this, CandidateSet.getLocation(), From->getType(),
8345 From->Classify(Context), Conversion, ConversionContext,
8346 /*InOverloadResolution*/ false, /*ExplicitParameterType=*/QualType(),
8347 /*SuppressUserConversion*/ true);
8348
8349 if (Candidate.Conversions[0].isBad()) {
8350 Candidate.Viable = false;
8352 return;
8353 }
8354
8355 if (Conversion->getTrailingRequiresClause()) {
8356 ConstraintSatisfaction Satisfaction;
8357 if (CheckFunctionConstraints(Conversion, Satisfaction) ||
8358 !Satisfaction.IsSatisfied) {
8359 Candidate.Viable = false;
8361 return;
8362 }
8363 }
8364
8365 // We won't go through a user-defined type conversion function to convert a
8366 // derived to base as such conversions are given Conversion Rank. They only
8367 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
8368 QualType FromCanon
8369 = Context.getCanonicalType(From->getType().getUnqualifiedType());
8370 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
8371 if (FromCanon == ToCanon ||
8372 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
8373 Candidate.Viable = false;
8375 return;
8376 }
8377
8378 // To determine what the conversion from the result of calling the
8379 // conversion function to the type we're eventually trying to
8380 // convert to (ToType), we need to synthesize a call to the
8381 // conversion function and attempt copy initialization from it. This
8382 // makes sure that we get the right semantics with respect to
8383 // lvalues/rvalues and the type. Fortunately, we can allocate this
8384 // call on the stack and we don't need its arguments to be
8385 // well-formed.
8386 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
8387 VK_LValue, From->getBeginLoc());
8389 Context.getPointerType(Conversion->getType()),
8390 CK_FunctionToPointerDecay, &ConversionRef,
8392
8393 QualType ConversionType = Conversion->getConversionType();
8394 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
8395 Candidate.Viable = false;
8397 return;
8398 }
8399
8400 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
8401
8402 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
8403
8404 // Introduce a temporary expression with the right type and value category
8405 // that we can use for deduction purposes.
8406 OpaqueValueExpr FakeCall(From->getBeginLoc(), CallResultType, VK);
8407
8409 TryCopyInitialization(*this, &FakeCall, ToType,
8410 /*SuppressUserConversions=*/true,
8411 /*InOverloadResolution=*/false,
8412 /*AllowObjCWritebackConversion=*/false);
8413
8414 switch (ICS.getKind()) {
8416 Candidate.FinalConversion = ICS.Standard;
8417 Candidate.HasFinalConversion = true;
8418
8419 // C++ [over.ics.user]p3:
8420 // If the user-defined conversion is specified by a specialization of a
8421 // conversion function template, the second standard conversion sequence
8422 // shall have exact match rank.
8423 if (Conversion->getPrimaryTemplate() &&
8425 Candidate.Viable = false;
8427 return;
8428 }
8429
8430 // C++0x [dcl.init.ref]p5:
8431 // In the second case, if the reference is an rvalue reference and
8432 // the second standard conversion sequence of the user-defined
8433 // conversion sequence includes an lvalue-to-rvalue conversion, the
8434 // program is ill-formed.
8435 if (ToType->isRValueReferenceType() &&
8437 Candidate.Viable = false;
8439 return;
8440 }
8441 break;
8442
8444 Candidate.Viable = false;
8446 return;
8447
8448 default:
8449 llvm_unreachable(
8450 "Can only end up with a standard conversion sequence or failure");
8451 }
8452
8453 if (EnableIfAttr *FailedAttr =
8454 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8455 Candidate.Viable = false;
8456 Candidate.FailureKind = ovl_fail_enable_if;
8457 Candidate.DeductionFailure.Data = FailedAttr;
8458 return;
8459 }
8460
8461 if (isNonViableMultiVersionOverload(Conversion)) {
8462 Candidate.Viable = false;
8464 }
8465}
8466
8468 Sema &S, OverloadCandidateSet &CandidateSet,
8470 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
8471 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
8472 bool AllowResultConversion) {
8473
8474 // If the function template has a non-dependent explicit specification,
8475 // exclude it now if appropriate; we are not permitted to perform deduction
8476 // and substitution in this case.
8477 if (!AllowExplicit && isNonDependentlyExplicit(FunctionTemplate)) {
8478 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8479 Candidate.FoundDecl = FoundDecl;
8480 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8481 Candidate.Viable = false;
8482 Candidate.FailureKind = ovl_fail_explicit;
8483 return;
8484 }
8485
8486 QualType ObjectType = From->getType();
8487 Expr::Classification ObjectClassification = From->Classify(S.Context);
8488
8489 TemplateDeductionInfo Info(CandidateSet.getLocation());
8492 FunctionTemplate, ObjectType, ObjectClassification, ToType,
8493 Specialization, Info);
8495 OverloadCandidate &Candidate = CandidateSet.addCandidate();
8496 Candidate.FoundDecl = FoundDecl;
8497 Candidate.Function = FunctionTemplate->getTemplatedDecl();
8498 Candidate.Viable = false;
8500 Candidate.ExplicitCallArguments = 1;
8501 Candidate.DeductionFailure =
8502 MakeDeductionFailureInfo(S.Context, Result, Info);
8503 return;
8504 }
8505
8506 // Add the conversion function template specialization produced by
8507 // template argument deduction as a candidate.
8508 assert(Specialization && "Missing function template specialization?");
8509 S.AddConversionCandidate(Specialization, FoundDecl, ActingContext, From,
8510 ToType, CandidateSet, AllowObjCConversionOnExplicit,
8511 AllowExplicit, AllowResultConversion,
8512 Info.hasStrictPackMatch());
8513}
8514
8517 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
8518 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
8519 bool AllowExplicit, bool AllowResultConversion) {
8520 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
8521 "Only conversion function templates permitted here");
8522
8523 if (!CandidateSet.isNewCandidate(FunctionTemplate))
8524 return;
8525
8527 CandidateSet.getKind() ==
8531 *this, CandidateSet, FunctionTemplate, FoundDecl, ActingDC, From,
8532 ToType, AllowObjCConversionOnExplicit, AllowExplicit,
8533 AllowResultConversion);
8534
8536 return;
8537 }
8538
8540 FunctionTemplate, FoundDecl, ActingDC, From, ToType,
8541 AllowObjCConversionOnExplicit, AllowExplicit, AllowResultConversion);
8542}
8543
8545 DeclAccessPair FoundDecl,
8546 CXXRecordDecl *ActingContext,
8547 const FunctionProtoType *Proto,
8548 Expr *Object,
8549 ArrayRef<Expr *> Args,
8550 OverloadCandidateSet& CandidateSet) {
8551 if (!CandidateSet.isNewCandidate(Conversion))
8552 return;
8553
8554 // Overload resolution is always an unevaluated context.
8557
8558 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
8559 Candidate.FoundDecl = FoundDecl;
8560 Candidate.Function = nullptr;
8561 Candidate.Surrogate = Conversion;
8562 Candidate.IsSurrogate = true;
8563 Candidate.Viable = true;
8564 Candidate.ExplicitCallArguments = Args.size();
8565
8566 // Determine the implicit conversion sequence for the implicit
8567 // object parameter.
8568 ImplicitConversionSequence ObjectInit;
8569 if (Conversion->hasCXXExplicitFunctionObjectParameter()) {
8570 ObjectInit = TryCopyInitialization(*this, Object,
8571 Conversion->getParamDecl(0)->getType(),
8572 /*SuppressUserConversions=*/false,
8573 /*InOverloadResolution=*/true, false);
8574 } else {
8576 *this, CandidateSet.getLocation(), Object->getType(),
8577 Object->Classify(Context), Conversion, ActingContext);
8578 }
8579
8580 if (ObjectInit.isBad()) {
8581 Candidate.Viable = false;
8583 Candidate.Conversions[0] = ObjectInit;
8584 return;
8585 }
8586
8587 // The first conversion is actually a user-defined conversion whose
8588 // first conversion is ObjectInit's standard conversion (which is
8589 // effectively a reference binding). Record it as such.
8590 Candidate.Conversions[0].setUserDefined();
8591 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
8592 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
8593 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
8594 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
8595 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
8596 Candidate.Conversions[0].UserDefined.After
8597 = Candidate.Conversions[0].UserDefined.Before;
8598 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
8599
8600 // Find the
8601 unsigned NumParams = Proto->getNumParams();
8602
8603 // (C++ 13.3.2p2): A candidate function having fewer than m
8604 // parameters is viable only if it has an ellipsis in its parameter
8605 // list (8.3.5).
8606 if (Args.size() > NumParams && !Proto->isVariadic()) {
8607 Candidate.Viable = false;
8609 return;
8610 }
8611
8612 // Function types don't have any default arguments, so just check if
8613 // we have enough arguments.
8614 if (Args.size() < NumParams) {
8615 // Not enough arguments.
8616 Candidate.Viable = false;
8618 return;
8619 }
8620
8621 // Determine the implicit conversion sequences for each of the
8622 // arguments.
8623 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8624 if (ArgIdx < NumParams) {
8625 // (C++ 13.3.2p3): for F to be a viable function, there shall
8626 // exist for each argument an implicit conversion sequence
8627 // (13.3.3.1) that converts that argument to the corresponding
8628 // parameter of F.
8629 QualType ParamType = Proto->getParamType(ArgIdx);
8630 Candidate.Conversions[ArgIdx + 1]
8631 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
8632 /*SuppressUserConversions=*/false,
8633 /*InOverloadResolution=*/false,
8634 /*AllowObjCWritebackConversion=*/
8635 getLangOpts().ObjCAutoRefCount);
8636 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
8637 Candidate.Viable = false;
8639 return;
8640 }
8641 } else {
8642 // (C++ 13.3.2p2): For the purposes of overload resolution, any
8643 // argument for which there is no corresponding parameter is
8644 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
8645 Candidate.Conversions[ArgIdx + 1].setEllipsis();
8646 }
8647 }
8648
8649 if (Conversion->getTrailingRequiresClause()) {
8650 ConstraintSatisfaction Satisfaction;
8651 if (CheckFunctionConstraints(Conversion, Satisfaction, /*Loc*/ {},
8652 /*ForOverloadResolution*/ true) ||
8653 !Satisfaction.IsSatisfied) {
8654 Candidate.Viable = false;
8656 return;
8657 }
8658 }
8659
8660 if (EnableIfAttr *FailedAttr =
8661 CheckEnableIf(Conversion, CandidateSet.getLocation(), {})) {
8662 Candidate.Viable = false;
8663 Candidate.FailureKind = ovl_fail_enable_if;
8664 Candidate.DeductionFailure.Data = FailedAttr;
8665 return;
8666 }
8667}
8668
8670 const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args,
8671 OverloadCandidateSet &CandidateSet,
8672 TemplateArgumentListInfo *ExplicitTemplateArgs) {
8673 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
8674 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
8675 ArrayRef<Expr *> FunctionArgs = Args;
8676
8677 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
8678 FunctionDecl *FD =
8679 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
8680
8681 // Don't consider rewritten functions if we're not rewriting.
8682 if (!CandidateSet.getRewriteInfo().isAcceptableCandidate(FD))
8683 continue;
8684
8685 assert(!isa<CXXMethodDecl>(FD) &&
8686 "unqualified operator lookup found a member function");
8687
8688 if (FunTmpl) {
8689 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8690 FunctionArgs, CandidateSet);
8691 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
8692
8693 // As template candidates are not deduced immediately,
8694 // persist the array in the overload set.
8696 FunctionArgs[1], FunctionArgs[0]);
8697 AddTemplateOverloadCandidate(FunTmpl, F.getPair(), ExplicitTemplateArgs,
8698 Reversed, CandidateSet, false, false, true,
8699 ADLCallKind::NotADL,
8701 }
8702 } else {
8703 if (ExplicitTemplateArgs)
8704 continue;
8705 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet);
8706 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD))
8707 AddOverloadCandidate(FD, F.getPair(),
8708 {FunctionArgs[1], FunctionArgs[0]}, CandidateSet,
8709 false, false, true, false, ADLCallKind::NotADL, {},
8711 }
8712 }
8713}
8714
8716 SourceLocation OpLoc,
8717 ArrayRef<Expr *> Args,
8718 OverloadCandidateSet &CandidateSet,
8720 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8721
8722 // C++ [over.match.oper]p3:
8723 // For a unary operator @ with an operand of a type whose
8724 // cv-unqualified version is T1, and for a binary operator @ with
8725 // a left operand of a type whose cv-unqualified version is T1 and
8726 // a right operand of a type whose cv-unqualified version is T2,
8727 // three sets of candidate functions, designated member
8728 // candidates, non-member candidates and built-in candidates, are
8729 // constructed as follows:
8730 QualType T1 = Args[0]->getType();
8731
8732 // -- If T1 is a complete class type or a class currently being
8733 // defined, the set of member candidates is the result of the
8734 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
8735 // the set of member candidates is empty.
8736 if (T1->isRecordType()) {
8737 bool IsComplete = isCompleteType(OpLoc, T1);
8738 auto *T1RD = T1->getAsCXXRecordDecl();
8739 // Complete the type if it can be completed.
8740 // If the type is neither complete nor being defined, bail out now.
8741 if (!T1RD || (!IsComplete && !T1RD->isBeingDefined()))
8742 return;
8743
8744 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
8745 LookupQualifiedName(Operators, T1RD);
8746 Operators.suppressAccessDiagnostics();
8747
8748 for (LookupResult::iterator Oper = Operators.begin(),
8749 OperEnd = Operators.end();
8750 Oper != OperEnd; ++Oper) {
8751 if (Oper->getAsFunction() &&
8753 !CandidateSet.getRewriteInfo().shouldAddReversed(
8754 *this, {Args[1], Args[0]}, Oper->getAsFunction()))
8755 continue;
8756 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
8757 Args[0]->Classify(Context), Args.slice(1),
8758 CandidateSet, /*SuppressUserConversion=*/false, PO);
8759 }
8760 }
8761}
8762
8764 OverloadCandidateSet& CandidateSet,
8765 bool IsAssignmentOperator,
8766 unsigned NumContextualBoolArguments) {
8767 // Overload resolution is always an unevaluated context.
8770
8771 // Add this candidate
8772 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
8773 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
8774 Candidate.Function = nullptr;
8775 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
8776
8777 // Determine the implicit conversion sequences for each of the
8778 // arguments.
8779 Candidate.Viable = true;
8780 Candidate.ExplicitCallArguments = Args.size();
8781 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8782 // C++ [over.match.oper]p4:
8783 // For the built-in assignment operators, conversions of the
8784 // left operand are restricted as follows:
8785 // -- no temporaries are introduced to hold the left operand, and
8786 // -- no user-defined conversions are applied to the left
8787 // operand to achieve a type match with the left-most
8788 // parameter of a built-in candidate.
8789 //
8790 // We block these conversions by turning off user-defined
8791 // conversions, since that is the only way that initialization of
8792 // a reference to a non-class type can occur from something that
8793 // is not of the same type.
8794 if (ArgIdx < NumContextualBoolArguments) {
8795 assert(ParamTys[ArgIdx] == Context.BoolTy &&
8796 "Contextual conversion to bool requires bool type");
8797 Candidate.Conversions[ArgIdx]
8798 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
8799 } else {
8800 Candidate.Conversions[ArgIdx]
8801 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
8802 ArgIdx == 0 && IsAssignmentOperator,
8803 /*InOverloadResolution=*/false,
8804 /*AllowObjCWritebackConversion=*/
8805 getLangOpts().ObjCAutoRefCount);
8806 }
8807 if (Candidate.Conversions[ArgIdx].isBad()) {
8808 Candidate.Viable = false;
8810 break;
8811 }
8812 }
8813}
8814
8815namespace {
8816
8817/// BuiltinCandidateTypeSet - A set of types that will be used for the
8818/// candidate operator functions for built-in operators (C++
8819/// [over.built]). The types are separated into pointer types and
8820/// enumeration types.
8821class BuiltinCandidateTypeSet {
8822 /// TypeSet - A set of types.
8823 typedef llvm::SmallSetVector<QualType, 8> TypeSet;
8824
8825 /// PointerTypes - The set of pointer types that will be used in the
8826 /// built-in candidates.
8827 TypeSet PointerTypes;
8828
8829 /// MemberPointerTypes - The set of member pointer types that will be
8830 /// used in the built-in candidates.
8831 TypeSet MemberPointerTypes;
8832
8833 /// EnumerationTypes - The set of enumeration types that will be
8834 /// used in the built-in candidates.
8835 TypeSet EnumerationTypes;
8836
8837 /// The set of vector types that will be used in the built-in
8838 /// candidates.
8839 TypeSet VectorTypes;
8840
8841 /// The set of matrix types that will be used in the built-in
8842 /// candidates.
8843 TypeSet MatrixTypes;
8844
8845 /// The set of _BitInt types that will be used in the built-in candidates.
8846 TypeSet BitIntTypes;
8847
8848 /// A flag indicating non-record types are viable candidates
8849 bool HasNonRecordTypes;
8850
8851 /// A flag indicating whether either arithmetic or enumeration types
8852 /// were present in the candidate set.
8853 bool HasArithmeticOrEnumeralTypes;
8854
8855 /// A flag indicating whether the nullptr type was present in the
8856 /// candidate set.
8857 bool HasNullPtrType;
8858
8859 /// Sema - The semantic analysis instance where we are building the
8860 /// candidate type set.
8861 Sema &SemaRef;
8862
8863 /// Context - The AST context in which we will build the type sets.
8864 ASTContext &Context;
8865
8866 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8867 const Qualifiers &VisibleQuals);
8868 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
8869
8870public:
8871 /// iterator - Iterates through the types that are part of the set.
8872 typedef TypeSet::iterator iterator;
8873
8874 BuiltinCandidateTypeSet(Sema &SemaRef)
8875 : HasNonRecordTypes(false),
8876 HasArithmeticOrEnumeralTypes(false),
8877 HasNullPtrType(false),
8878 SemaRef(SemaRef),
8879 Context(SemaRef.Context) { }
8880
8881 void AddTypesConvertedFrom(QualType Ty,
8882 SourceLocation Loc,
8883 bool AllowUserConversions,
8884 bool AllowExplicitConversions,
8885 const Qualifiers &VisibleTypeConversionsQuals);
8886
8887 llvm::iterator_range<iterator> pointer_types() { return PointerTypes; }
8888 llvm::iterator_range<iterator> member_pointer_types() {
8889 return MemberPointerTypes;
8890 }
8891 llvm::iterator_range<iterator> enumeration_types() {
8892 return EnumerationTypes;
8893 }
8894 llvm::iterator_range<iterator> vector_types() { return VectorTypes; }
8895 llvm::iterator_range<iterator> matrix_types() { return MatrixTypes; }
8896 llvm::iterator_range<iterator> bitint_types() { return BitIntTypes; }
8897
8898 bool containsMatrixType(QualType Ty) const { return MatrixTypes.count(Ty); }
8899 bool hasNonRecordTypes() { return HasNonRecordTypes; }
8900 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
8901 bool hasNullPtrType() const { return HasNullPtrType; }
8902};
8903
8904} // end anonymous namespace
8905
8906/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
8907/// the set of pointer types along with any more-qualified variants of
8908/// that type. For example, if @p Ty is "int const *", this routine
8909/// will add "int const *", "int const volatile *", "int const
8910/// restrict *", and "int const volatile restrict *" to the set of
8911/// pointer types. Returns true if the add of @p Ty itself succeeded,
8912/// false otherwise.
8913///
8914/// FIXME: what to do about extended qualifiers?
8915bool
8916BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
8917 const Qualifiers &VisibleQuals) {
8918
8919 // Insert this type.
8920 if (!PointerTypes.insert(Ty))
8921 return false;
8922
8923 QualType PointeeTy;
8924 const PointerType *PointerTy = Ty->getAs<PointerType>();
8925 bool buildObjCPtr = false;
8926 if (!PointerTy) {
8927 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
8928 PointeeTy = PTy->getPointeeType();
8929 buildObjCPtr = true;
8930 } else {
8931 PointeeTy = PointerTy->getPointeeType();
8932 }
8933
8934 // Don't add qualified variants of arrays. For one, they're not allowed
8935 // (the qualifier would sink to the element type), and for another, the
8936 // only overload situation where it matters is subscript or pointer +- int,
8937 // and those shouldn't have qualifier variants anyway.
8938 if (PointeeTy->isArrayType())
8939 return true;
8940
8941 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
8942 bool hasVolatile = VisibleQuals.hasVolatile();
8943 bool hasRestrict = VisibleQuals.hasRestrict();
8944
8945 // Iterate through all strict supersets of BaseCVR.
8946 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
8947 if ((CVR | BaseCVR) != CVR) continue;
8948 // Skip over volatile if no volatile found anywhere in the types.
8949 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
8950
8951 // Skip over restrict if no restrict found anywhere in the types, or if
8952 // the type cannot be restrict-qualified.
8953 if ((CVR & Qualifiers::Restrict) &&
8954 (!hasRestrict ||
8955 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
8956 continue;
8957
8958 // Build qualified pointee type.
8959 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
8960
8961 // Build qualified pointer type.
8962 QualType QPointerTy;
8963 if (!buildObjCPtr)
8964 QPointerTy = Context.getPointerType(QPointeeTy);
8965 else
8966 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
8967
8968 // Insert qualified pointer type.
8969 PointerTypes.insert(QPointerTy);
8970 }
8971
8972 return true;
8973}
8974
8975/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
8976/// to the set of pointer types along with any more-qualified variants of
8977/// that type. For example, if @p Ty is "int const *", this routine
8978/// will add "int const *", "int const volatile *", "int const
8979/// restrict *", and "int const volatile restrict *" to the set of
8980/// pointer types. Returns true if the add of @p Ty itself succeeded,
8981/// false otherwise.
8982///
8983/// FIXME: what to do about extended qualifiers?
8984bool
8985BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
8986 QualType Ty) {
8987 // Insert this type.
8988 if (!MemberPointerTypes.insert(Ty))
8989 return false;
8990
8991 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
8992 assert(PointerTy && "type was not a member pointer type!");
8993
8994 QualType PointeeTy = PointerTy->getPointeeType();
8995 // Don't add qualified variants of arrays. For one, they're not allowed
8996 // (the qualifier would sink to the element type), and for another, the
8997 // only overload situation where it matters is subscript or pointer +- int,
8998 // and those shouldn't have qualifier variants anyway.
8999 if (PointeeTy->isArrayType())
9000 return true;
9001 CXXRecordDecl *Cls = PointerTy->getMostRecentCXXRecordDecl();
9002
9003 // Iterate through all strict supersets of the pointee type's CVR
9004 // qualifiers.
9005 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
9006 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
9007 if ((CVR | BaseCVR) != CVR) continue;
9008
9009 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
9010 MemberPointerTypes.insert(Context.getMemberPointerType(
9011 QPointeeTy, /*Qualifier=*/std::nullopt, Cls));
9012 }
9013
9014 return true;
9015}
9016
9017/// AddTypesConvertedFrom - Add each of the types to which the type @p
9018/// Ty can be implicit converted to the given set of @p Types. We're
9019/// primarily interested in pointer types and enumeration types. We also
9020/// take member pointer types, for the conditional operator.
9021/// AllowUserConversions is true if we should look at the conversion
9022/// functions of a class type, and AllowExplicitConversions if we
9023/// should also include the explicit conversion functions of a class
9024/// type.
9025void
9026BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
9027 SourceLocation Loc,
9028 bool AllowUserConversions,
9029 bool AllowExplicitConversions,
9030 const Qualifiers &VisibleQuals) {
9031 // Only deal with canonical types.
9032 Ty = Context.getCanonicalType(Ty);
9033
9034 // Look through reference types; they aren't part of the type of an
9035 // expression for the purposes of conversions.
9036 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
9037 Ty = RefTy->getPointeeType();
9038
9039 // If we're dealing with an array type, decay to the pointer.
9040 if (Ty->isArrayType())
9041 Ty = SemaRef.Context.getArrayDecayedType(Ty);
9042
9043 // Otherwise, we don't care about qualifiers on the type.
9044 Ty = Ty.getLocalUnqualifiedType();
9045
9046 // Flag if we ever add a non-record type.
9047 bool TyIsRec = Ty->isRecordType();
9048 HasNonRecordTypes = HasNonRecordTypes || !TyIsRec;
9049
9050 // Flag if we encounter an arithmetic type.
9051 HasArithmeticOrEnumeralTypes =
9052 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
9053
9054 if (Ty->isObjCIdType() || Ty->isObjCClassType())
9055 PointerTypes.insert(Ty);
9056 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
9057 // Insert our type, and its more-qualified variants, into the set
9058 // of types.
9059 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
9060 return;
9061 } else if (Ty->isMemberPointerType()) {
9062 // Member pointers are far easier, since the pointee can't be converted.
9063 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
9064 return;
9065 } else if (Ty->isEnumeralType()) {
9066 HasArithmeticOrEnumeralTypes = true;
9067 EnumerationTypes.insert(Ty);
9068 } else if (Ty->isBitIntType()) {
9069 HasArithmeticOrEnumeralTypes = true;
9070 BitIntTypes.insert(Ty);
9071 } else if (Ty->isVectorType()) {
9072 // We treat vector types as arithmetic types in many contexts as an
9073 // extension.
9074 HasArithmeticOrEnumeralTypes = true;
9075 VectorTypes.insert(Ty);
9076 } else if (Ty->isMatrixType()) {
9077 // Similar to vector types, we treat vector types as arithmetic types in
9078 // many contexts as an extension.
9079 HasArithmeticOrEnumeralTypes = true;
9080 MatrixTypes.insert(Ty);
9081 } else if (Ty->isNullPtrType()) {
9082 HasNullPtrType = true;
9083 } else if (AllowUserConversions && TyIsRec) {
9084 // No conversion functions in incomplete types.
9085 if (!SemaRef.isCompleteType(Loc, Ty))
9086 return;
9087
9088 auto *ClassDecl = Ty->castAsCXXRecordDecl();
9089 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9090 if (isa<UsingShadowDecl>(D))
9091 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9092
9093 // Skip conversion function templates; they don't tell us anything
9094 // about which builtin types we can convert to.
9096 continue;
9097
9098 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
9099 if (AllowExplicitConversions || !Conv->isExplicit()) {
9100 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
9101 VisibleQuals);
9102 }
9103 }
9104 }
9105}
9106/// Helper function for adjusting address spaces for the pointer or reference
9107/// operands of builtin operators depending on the argument.
9112
9113/// Helper function for AddBuiltinOperatorCandidates() that adds
9114/// the volatile- and non-volatile-qualified assignment operators for the
9115/// given type to the candidate set.
9117 QualType T,
9118 ArrayRef<Expr *> Args,
9119 OverloadCandidateSet &CandidateSet) {
9120 QualType ParamTypes[2];
9121
9122 // T& operator=(T&, T)
9123 ParamTypes[0] = S.Context.getLValueReferenceType(
9125 ParamTypes[1] = T;
9126 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9127 /*IsAssignmentOperator=*/true);
9128
9130 // volatile T& operator=(volatile T&, T)
9131 ParamTypes[0] = S.Context.getLValueReferenceType(
9133 Args[0]));
9134 ParamTypes[1] = T;
9135 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9136 /*IsAssignmentOperator=*/true);
9137 }
9138}
9139
9140/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
9141/// if any, found in visible type conversion functions found in ArgExpr's type.
9142static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
9143 Qualifiers VRQuals;
9144 CXXRecordDecl *ClassDecl;
9145 if (const MemberPointerType *RHSMPType =
9146 ArgExpr->getType()->getAs<MemberPointerType>())
9147 ClassDecl = RHSMPType->getMostRecentCXXRecordDecl();
9148 else
9149 ClassDecl = ArgExpr->getType()->getAsCXXRecordDecl();
9150 if (!ClassDecl) {
9151 // Just to be safe, assume the worst case.
9152 VRQuals.addVolatile();
9153 VRQuals.addRestrict();
9154 return VRQuals;
9155 }
9156 if (!ClassDecl->hasDefinition())
9157 return VRQuals;
9158
9159 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
9160 if (isa<UsingShadowDecl>(D))
9161 D = cast<UsingShadowDecl>(D)->getTargetDecl();
9162 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
9163 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
9164 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
9165 CanTy = ResTypeRef->getPointeeType();
9166 // Need to go down the pointer/mempointer chain and add qualifiers
9167 // as see them.
9168 bool done = false;
9169 while (!done) {
9170 if (CanTy.isRestrictQualified())
9171 VRQuals.addRestrict();
9172 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
9173 CanTy = ResTypePtr->getPointeeType();
9174 else if (const MemberPointerType *ResTypeMPtr =
9175 CanTy->getAs<MemberPointerType>())
9176 CanTy = ResTypeMPtr->getPointeeType();
9177 else
9178 done = true;
9179 if (CanTy.isVolatileQualified())
9180 VRQuals.addVolatile();
9181 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
9182 return VRQuals;
9183 }
9184 }
9185 }
9186 return VRQuals;
9187}
9188
9189// Note: We're currently only handling qualifiers that are meaningful for the
9190// LHS of compound assignment overloading.
9192 QualifiersAndAtomic Available, QualifiersAndAtomic Applied,
9193 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9194 // _Atomic
9195 if (Available.hasAtomic()) {
9196 Available.removeAtomic();
9197 forAllQualifierCombinationsImpl(Available, Applied.withAtomic(), Callback);
9198 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9199 return;
9200 }
9201
9202 // volatile
9203 if (Available.hasVolatile()) {
9204 Available.removeVolatile();
9205 assert(!Applied.hasVolatile());
9206 forAllQualifierCombinationsImpl(Available, Applied.withVolatile(),
9207 Callback);
9208 forAllQualifierCombinationsImpl(Available, Applied, Callback);
9209 return;
9210 }
9211
9212 Callback(Applied);
9213}
9214
9216 QualifiersAndAtomic Quals,
9217 llvm::function_ref<void(QualifiersAndAtomic)> Callback) {
9219 Callback);
9220}
9221
9223 QualifiersAndAtomic Quals,
9224 Sema &S) {
9225 if (Quals.hasAtomic())
9227 if (Quals.hasVolatile())
9230}
9231
9232namespace {
9233
9234/// Helper class to manage the addition of builtin operator overload
9235/// candidates. It provides shared state and utility methods used throughout
9236/// the process, as well as a helper method to add each group of builtin
9237/// operator overloads from the standard to a candidate set.
9238class BuiltinOperatorOverloadBuilder {
9239 // Common instance state available to all overload candidate addition methods.
9240 Sema &S;
9241 ArrayRef<Expr *> Args;
9242 QualifiersAndAtomic VisibleTypeConversionsQuals;
9243 bool HasArithmeticOrEnumeralCandidateType;
9244 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
9245 OverloadCandidateSet &CandidateSet;
9246
9247 static constexpr int ArithmeticTypesCap = 26;
9248 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
9249
9250 // Define some indices used to iterate over the arithmetic types in
9251 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
9252 // types are that preserved by promotion (C++ [over.built]p2).
9253 unsigned FirstIntegralType,
9254 LastIntegralType;
9255 unsigned FirstPromotedIntegralType,
9256 LastPromotedIntegralType;
9257 unsigned FirstPromotedArithmeticType,
9258 LastPromotedArithmeticType;
9259 unsigned NumArithmeticTypes;
9260
9261 void InitArithmeticTypes() {
9262 // Start of promoted types.
9263 FirstPromotedArithmeticType = 0;
9264 ArithmeticTypes.push_back(S.Context.FloatTy);
9265 ArithmeticTypes.push_back(S.Context.DoubleTy);
9266 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
9268 ArithmeticTypes.push_back(S.Context.Float128Ty);
9270 ArithmeticTypes.push_back(S.Context.Ibm128Ty);
9271
9272 // Start of integral types.
9273 FirstIntegralType = ArithmeticTypes.size();
9274 FirstPromotedIntegralType = ArithmeticTypes.size();
9275 ArithmeticTypes.push_back(S.Context.IntTy);
9276 ArithmeticTypes.push_back(S.Context.LongTy);
9277 ArithmeticTypes.push_back(S.Context.LongLongTy);
9281 ArithmeticTypes.push_back(S.Context.Int128Ty);
9282 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
9283 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
9284 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
9288 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
9289
9290 /// We add candidates for the unique, unqualified _BitInt types present in
9291 /// the candidate type set. The candidate set already handled ensuring the
9292 /// type is unqualified and canonical, but because we're adding from N
9293 /// different sets, we need to do some extra work to unique things. Insert
9294 /// the candidates into a unique set, then move from that set into the list
9295 /// of arithmetic types.
9296 llvm::SmallSetVector<CanQualType, 2> BitIntCandidates;
9297 for (BuiltinCandidateTypeSet &Candidate : CandidateTypes) {
9298 for (QualType BitTy : Candidate.bitint_types())
9299 BitIntCandidates.insert(CanQualType::CreateUnsafe(BitTy));
9300 }
9301 llvm::move(BitIntCandidates, std::back_inserter(ArithmeticTypes));
9302 LastPromotedIntegralType = ArithmeticTypes.size();
9303 LastPromotedArithmeticType = ArithmeticTypes.size();
9304 // End of promoted types.
9305
9306 ArithmeticTypes.push_back(S.Context.BoolTy);
9307 ArithmeticTypes.push_back(S.Context.CharTy);
9308 ArithmeticTypes.push_back(S.Context.WCharTy);
9309 if (S.Context.getLangOpts().Char8)
9310 ArithmeticTypes.push_back(S.Context.Char8Ty);
9311 ArithmeticTypes.push_back(S.Context.Char16Ty);
9312 ArithmeticTypes.push_back(S.Context.Char32Ty);
9313 ArithmeticTypes.push_back(S.Context.SignedCharTy);
9314 ArithmeticTypes.push_back(S.Context.ShortTy);
9315 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
9316 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
9317 LastIntegralType = ArithmeticTypes.size();
9318 NumArithmeticTypes = ArithmeticTypes.size();
9319 // End of integral types.
9320 // FIXME: What about complex? What about half?
9321
9322 // We don't know for sure how many bit-precise candidates were involved, so
9323 // we subtract those from the total when testing whether we're under the
9324 // cap or not.
9325 assert(ArithmeticTypes.size() - BitIntCandidates.size() <=
9326 ArithmeticTypesCap &&
9327 "Enough inline storage for all arithmetic types.");
9328 }
9329
9330 /// Helper method to factor out the common pattern of adding overloads
9331 /// for '++' and '--' builtin operators.
9332 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
9333 bool HasVolatile,
9334 bool HasRestrict) {
9335 QualType ParamTypes[2] = {
9336 S.Context.getLValueReferenceType(CandidateTy),
9337 S.Context.IntTy
9338 };
9339
9340 // Non-volatile version.
9341 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9342
9343 // Use a heuristic to reduce number of builtin candidates in the set:
9344 // add volatile version only if there are conversions to a volatile type.
9345 if (HasVolatile) {
9346 ParamTypes[0] =
9348 S.Context.getVolatileType(CandidateTy));
9349 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9350 }
9351
9352 // Add restrict version only if there are conversions to a restrict type
9353 // and our candidate type is a non-restrict-qualified pointer.
9354 if (HasRestrict && CandidateTy->isAnyPointerType() &&
9355 !CandidateTy.isRestrictQualified()) {
9356 ParamTypes[0]
9359 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9360
9361 if (HasVolatile) {
9362 ParamTypes[0]
9364 S.Context.getCVRQualifiedType(CandidateTy,
9367 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9368 }
9369 }
9370
9371 }
9372
9373 /// Helper to add an overload candidate for a binary builtin with types \p L
9374 /// and \p R.
9375 void AddCandidate(QualType L, QualType R) {
9376 QualType LandR[2] = {L, R};
9377 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9378 }
9379
9380public:
9381 BuiltinOperatorOverloadBuilder(
9382 Sema &S, ArrayRef<Expr *> Args,
9383 QualifiersAndAtomic VisibleTypeConversionsQuals,
9384 bool HasArithmeticOrEnumeralCandidateType,
9385 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
9386 OverloadCandidateSet &CandidateSet)
9387 : S(S), Args(Args),
9388 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
9389 HasArithmeticOrEnumeralCandidateType(
9390 HasArithmeticOrEnumeralCandidateType),
9391 CandidateTypes(CandidateTypes),
9392 CandidateSet(CandidateSet) {
9393
9394 InitArithmeticTypes();
9395 }
9396
9397 // Increment is deprecated for bool since C++17.
9398 //
9399 // C++ [over.built]p3:
9400 //
9401 // For every pair (T, VQ), where T is an arithmetic type other
9402 // than bool, and VQ is either volatile or empty, there exist
9403 // candidate operator functions of the form
9404 //
9405 // VQ T& operator++(VQ T&);
9406 // T operator++(VQ T&, int);
9407 //
9408 // C++ [over.built]p4:
9409 //
9410 // For every pair (T, VQ), where T is an arithmetic type other
9411 // than bool, and VQ is either volatile or empty, there exist
9412 // candidate operator functions of the form
9413 //
9414 // VQ T& operator--(VQ T&);
9415 // T operator--(VQ T&, int);
9416 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
9417 if (!HasArithmeticOrEnumeralCandidateType)
9418 return;
9419
9420 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
9421 const auto TypeOfT = ArithmeticTypes[Arith];
9422 if (TypeOfT == S.Context.BoolTy) {
9423 if (Op == OO_MinusMinus)
9424 continue;
9425 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
9426 continue;
9427 }
9428 addPlusPlusMinusMinusStyleOverloads(
9429 TypeOfT,
9430 VisibleTypeConversionsQuals.hasVolatile(),
9431 VisibleTypeConversionsQuals.hasRestrict());
9432 }
9433 }
9434
9435 // C++ [over.built]p5:
9436 //
9437 // For every pair (T, VQ), where T is a cv-qualified or
9438 // cv-unqualified object type, and VQ is either volatile or
9439 // empty, there exist candidate operator functions of the form
9440 //
9441 // T*VQ& operator++(T*VQ&);
9442 // T*VQ& operator--(T*VQ&);
9443 // T* operator++(T*VQ&, int);
9444 // T* operator--(T*VQ&, int);
9445 void addPlusPlusMinusMinusPointerOverloads() {
9446 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9447 // Skip pointer types that aren't pointers to object types.
9448 if (!PtrTy->getPointeeType()->isObjectType())
9449 continue;
9450
9451 addPlusPlusMinusMinusStyleOverloads(
9452 PtrTy,
9453 (!PtrTy.isVolatileQualified() &&
9454 VisibleTypeConversionsQuals.hasVolatile()),
9455 (!PtrTy.isRestrictQualified() &&
9456 VisibleTypeConversionsQuals.hasRestrict()));
9457 }
9458 }
9459
9460 // C++ [over.built]p6:
9461 // For every cv-qualified or cv-unqualified object type T, there
9462 // exist candidate operator functions of the form
9463 //
9464 // T& operator*(T*);
9465 //
9466 // C++ [over.built]p7:
9467 // For every function type T that does not have cv-qualifiers or a
9468 // ref-qualifier, there exist candidate operator functions of the form
9469 // T& operator*(T*);
9470 void addUnaryStarPointerOverloads() {
9471 for (QualType ParamTy : CandidateTypes[0].pointer_types()) {
9472 QualType PointeeTy = ParamTy->getPointeeType();
9473 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
9474 continue;
9475
9476 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
9477 if (Proto->getMethodQuals() || Proto->getRefQualifier())
9478 continue;
9479
9480 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9481 }
9482 }
9483
9484 // C++ [over.built]p9:
9485 // For every promoted arithmetic type T, there exist candidate
9486 // operator functions of the form
9487 //
9488 // T operator+(T);
9489 // T operator-(T);
9490 void addUnaryPlusOrMinusArithmeticOverloads() {
9491 if (!HasArithmeticOrEnumeralCandidateType)
9492 return;
9493
9494 for (unsigned Arith = FirstPromotedArithmeticType;
9495 Arith < LastPromotedArithmeticType; ++Arith) {
9496 QualType ArithTy = ArithmeticTypes[Arith];
9497 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
9498 }
9499
9500 // Extension: We also add these operators for vector types.
9501 for (QualType VecTy : CandidateTypes[0].vector_types())
9502 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9503 }
9504
9505 // C++ [over.built]p8:
9506 // For every type T, there exist candidate operator functions of
9507 // the form
9508 //
9509 // T* operator+(T*);
9510 void addUnaryPlusPointerOverloads() {
9511 for (QualType ParamTy : CandidateTypes[0].pointer_types())
9512 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
9513 }
9514
9515 // C++ [over.built]p10:
9516 // For every promoted integral type T, there exist candidate
9517 // operator functions of the form
9518 //
9519 // T operator~(T);
9520 void addUnaryTildePromotedIntegralOverloads() {
9521 if (!HasArithmeticOrEnumeralCandidateType)
9522 return;
9523
9524 for (unsigned Int = FirstPromotedIntegralType;
9525 Int < LastPromotedIntegralType; ++Int) {
9526 QualType IntTy = ArithmeticTypes[Int];
9527 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
9528 }
9529
9530 // Extension: We also add this operator for vector types.
9531 for (QualType VecTy : CandidateTypes[0].vector_types())
9532 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
9533 }
9534
9535 // C++ [over.match.oper]p16:
9536 // For every pointer to member type T or type std::nullptr_t, there
9537 // exist candidate operator functions of the form
9538 //
9539 // bool operator==(T,T);
9540 // bool operator!=(T,T);
9541 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
9542 /// Set of (canonical) types that we've already handled.
9543 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9544
9545 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9546 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9547 // Don't add the same builtin candidate twice.
9548 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9549 continue;
9550
9551 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
9552 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9553 }
9554
9555 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
9557 if (AddedTypes.insert(NullPtrTy).second) {
9558 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
9559 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9560 }
9561 }
9562 }
9563 }
9564
9565 // C++ [over.built]p15:
9566 //
9567 // For every T, where T is an enumeration type or a pointer type,
9568 // there exist candidate operator functions of the form
9569 //
9570 // bool operator<(T, T);
9571 // bool operator>(T, T);
9572 // bool operator<=(T, T);
9573 // bool operator>=(T, T);
9574 // bool operator==(T, T);
9575 // bool operator!=(T, T);
9576 // R operator<=>(T, T)
9577 void addGenericBinaryPointerOrEnumeralOverloads(bool IsSpaceship) {
9578 // C++ [over.match.oper]p3:
9579 // [...]the built-in candidates include all of the candidate operator
9580 // functions defined in 13.6 that, compared to the given operator, [...]
9581 // do not have the same parameter-type-list as any non-template non-member
9582 // candidate.
9583 //
9584 // Note that in practice, this only affects enumeration types because there
9585 // aren't any built-in candidates of record type, and a user-defined operator
9586 // must have an operand of record or enumeration type. Also, the only other
9587 // overloaded operator with enumeration arguments, operator=,
9588 // cannot be overloaded for enumeration types, so this is the only place
9589 // where we must suppress candidates like this.
9590 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
9591 UserDefinedBinaryOperators;
9592
9593 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9594 if (!CandidateTypes[ArgIdx].enumeration_types().empty()) {
9595 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
9596 CEnd = CandidateSet.end();
9597 C != CEnd; ++C) {
9598 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
9599 continue;
9600
9601 if (C->Function->isFunctionTemplateSpecialization())
9602 continue;
9603
9604 // We interpret "same parameter-type-list" as applying to the
9605 // "synthesized candidate, with the order of the two parameters
9606 // reversed", not to the original function.
9607 bool Reversed = C->isReversed();
9608 QualType FirstParamType = C->Function->getParamDecl(Reversed ? 1 : 0)
9609 ->getType()
9610 .getUnqualifiedType();
9611 QualType SecondParamType = C->Function->getParamDecl(Reversed ? 0 : 1)
9612 ->getType()
9613 .getUnqualifiedType();
9614
9615 // Skip if either parameter isn't of enumeral type.
9616 if (!FirstParamType->isEnumeralType() ||
9617 !SecondParamType->isEnumeralType())
9618 continue;
9619
9620 // Add this operator to the set of known user-defined operators.
9621 UserDefinedBinaryOperators.insert(
9622 std::make_pair(S.Context.getCanonicalType(FirstParamType),
9623 S.Context.getCanonicalType(SecondParamType)));
9624 }
9625 }
9626 }
9627
9628 /// Set of (canonical) types that we've already handled.
9629 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9630
9631 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
9632 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
9633 // Don't add the same builtin candidate twice.
9634 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9635 continue;
9636 if (IsSpaceship && PtrTy->isFunctionPointerType())
9637 continue;
9638
9639 QualType ParamTypes[2] = {PtrTy, PtrTy};
9640 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9641 }
9642 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9643 CanQualType CanonType = S.Context.getCanonicalType(EnumTy);
9644
9645 // Don't add the same builtin candidate twice, or if a user defined
9646 // candidate exists.
9647 if (!AddedTypes.insert(CanonType).second ||
9648 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
9649 CanonType)))
9650 continue;
9651 QualType ParamTypes[2] = {EnumTy, EnumTy};
9652 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9653 }
9654 }
9655 }
9656
9657 // C++ [over.built]p13:
9658 //
9659 // For every cv-qualified or cv-unqualified object type T
9660 // there exist candidate operator functions of the form
9661 //
9662 // T* operator+(T*, ptrdiff_t);
9663 // T& operator[](T*, ptrdiff_t); [BELOW]
9664 // T* operator-(T*, ptrdiff_t);
9665 // T* operator+(ptrdiff_t, T*);
9666 // T& operator[](ptrdiff_t, T*); [BELOW]
9667 //
9668 // C++ [over.built]p14:
9669 //
9670 // For every T, where T is a pointer to object type, there
9671 // exist candidate operator functions of the form
9672 //
9673 // ptrdiff_t operator-(T, T);
9674 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
9675 /// Set of (canonical) types that we've already handled.
9676 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9677
9678 for (int Arg = 0; Arg < 2; ++Arg) {
9679 QualType AsymmetricParamTypes[2] = {
9682 };
9683 for (QualType PtrTy : CandidateTypes[Arg].pointer_types()) {
9684 QualType PointeeTy = PtrTy->getPointeeType();
9685 if (!PointeeTy->isObjectType())
9686 continue;
9687
9688 AsymmetricParamTypes[Arg] = PtrTy;
9689 if (Arg == 0 || Op == OO_Plus) {
9690 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
9691 // T* operator+(ptrdiff_t, T*);
9692 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
9693 }
9694 if (Op == OO_Minus) {
9695 // ptrdiff_t operator-(T, T);
9696 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9697 continue;
9698
9699 QualType ParamTypes[2] = {PtrTy, PtrTy};
9700 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
9701 }
9702 }
9703 }
9704 }
9705
9706 // C++ [over.built]p12:
9707 //
9708 // For every pair of promoted arithmetic types L and R, there
9709 // exist candidate operator functions of the form
9710 //
9711 // LR operator*(L, R);
9712 // LR operator/(L, R);
9713 // LR operator+(L, R);
9714 // LR operator-(L, R);
9715 // bool operator<(L, R);
9716 // bool operator>(L, R);
9717 // bool operator<=(L, R);
9718 // bool operator>=(L, R);
9719 // bool operator==(L, R);
9720 // bool operator!=(L, R);
9721 //
9722 // where LR is the result of the usual arithmetic conversions
9723 // between types L and R.
9724 //
9725 // C++ [over.built]p24:
9726 //
9727 // For every pair of promoted arithmetic types L and R, there exist
9728 // candidate operator functions of the form
9729 //
9730 // LR operator?(bool, L, R);
9731 //
9732 // where LR is the result of the usual arithmetic conversions
9733 // between types L and R.
9734 // Our candidates ignore the first parameter.
9735 void addGenericBinaryArithmeticOverloads() {
9736 if (!HasArithmeticOrEnumeralCandidateType)
9737 return;
9738
9739 for (unsigned Left = FirstPromotedArithmeticType;
9740 Left < LastPromotedArithmeticType; ++Left) {
9741 for (unsigned Right = FirstPromotedArithmeticType;
9742 Right < LastPromotedArithmeticType; ++Right) {
9743 QualType LandR[2] = { ArithmeticTypes[Left],
9744 ArithmeticTypes[Right] };
9745 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9746 }
9747 }
9748
9749 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
9750 // conditional operator for vector types.
9751 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
9752 for (QualType Vec2Ty : CandidateTypes[1].vector_types()) {
9753 QualType LandR[2] = {Vec1Ty, Vec2Ty};
9754 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9755 }
9756 }
9757
9758 /// Add binary operator overloads for each candidate matrix type M1, M2:
9759 /// * (M1, M1) -> M1
9760 /// * (M1, M1.getElementType()) -> M1
9761 /// * (M2.getElementType(), M2) -> M2
9762 /// * (M2, M2) -> M2 // Only if M2 is not part of CandidateTypes[0].
9763 void addMatrixBinaryArithmeticOverloads() {
9764 if (!HasArithmeticOrEnumeralCandidateType)
9765 return;
9766
9767 for (QualType M1 : CandidateTypes[0].matrix_types()) {
9768 AddCandidate(M1, cast<MatrixType>(M1)->getElementType());
9769 AddCandidate(M1, M1);
9770 }
9771
9772 for (QualType M2 : CandidateTypes[1].matrix_types()) {
9773 AddCandidate(cast<MatrixType>(M2)->getElementType(), M2);
9774 if (!CandidateTypes[0].containsMatrixType(M2))
9775 AddCandidate(M2, M2);
9776 }
9777 }
9778
9779 // C++2a [over.built]p14:
9780 //
9781 // For every integral type T there exists a candidate operator function
9782 // of the form
9783 //
9784 // std::strong_ordering operator<=>(T, T)
9785 //
9786 // C++2a [over.built]p15:
9787 //
9788 // For every pair of floating-point types L and R, there exists a candidate
9789 // operator function of the form
9790 //
9791 // std::partial_ordering operator<=>(L, R);
9792 //
9793 // FIXME: The current specification for integral types doesn't play nice with
9794 // the direction of p0946r0, which allows mixed integral and unscoped-enum
9795 // comparisons. Under the current spec this can lead to ambiguity during
9796 // overload resolution. For example:
9797 //
9798 // enum A : int {a};
9799 // auto x = (a <=> (long)42);
9800 //
9801 // error: call is ambiguous for arguments 'A' and 'long'.
9802 // note: candidate operator<=>(int, int)
9803 // note: candidate operator<=>(long, long)
9804 //
9805 // To avoid this error, this function deviates from the specification and adds
9806 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
9807 // arithmetic types (the same as the generic relational overloads).
9808 //
9809 // For now this function acts as a placeholder.
9810 void addThreeWayArithmeticOverloads() {
9811 addGenericBinaryArithmeticOverloads();
9812 }
9813
9814 // C++ [over.built]p17:
9815 //
9816 // For every pair of promoted integral types L and R, there
9817 // exist candidate operator functions of the form
9818 //
9819 // LR operator%(L, R);
9820 // LR operator&(L, R);
9821 // LR operator^(L, R);
9822 // LR operator|(L, R);
9823 // L operator<<(L, R);
9824 // L operator>>(L, R);
9825 //
9826 // where LR is the result of the usual arithmetic conversions
9827 // between types L and R.
9828 void addBinaryBitwiseArithmeticOverloads() {
9829 if (!HasArithmeticOrEnumeralCandidateType)
9830 return;
9831
9832 for (unsigned Left = FirstPromotedIntegralType;
9833 Left < LastPromotedIntegralType; ++Left) {
9834 for (unsigned Right = FirstPromotedIntegralType;
9835 Right < LastPromotedIntegralType; ++Right) {
9836 QualType LandR[2] = { ArithmeticTypes[Left],
9837 ArithmeticTypes[Right] };
9838 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
9839 }
9840 }
9841 }
9842
9843 // C++ [over.built]p20:
9844 //
9845 // For every pair (T, VQ), where T is an enumeration or
9846 // pointer to member type and VQ is either volatile or
9847 // empty, there exist candidate operator functions of the form
9848 //
9849 // VQ T& operator=(VQ T&, T);
9850 void addAssignmentMemberPointerOrEnumeralOverloads() {
9851 /// Set of (canonical) types that we've already handled.
9852 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9853
9854 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
9855 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
9856 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
9857 continue;
9858
9859 AddBuiltinAssignmentOperatorCandidates(S, EnumTy, Args, CandidateSet);
9860 }
9861
9862 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
9863 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
9864 continue;
9865
9866 AddBuiltinAssignmentOperatorCandidates(S, MemPtrTy, Args, CandidateSet);
9867 }
9868 }
9869 }
9870
9871 // C++ [over.built]p19:
9872 //
9873 // For every pair (T, VQ), where T is any type and VQ is either
9874 // volatile or empty, there exist candidate operator functions
9875 // of the form
9876 //
9877 // T*VQ& operator=(T*VQ&, T*);
9878 //
9879 // C++ [over.built]p21:
9880 //
9881 // For every pair (T, VQ), where T is a cv-qualified or
9882 // cv-unqualified object type and VQ is either volatile or
9883 // empty, there exist candidate operator functions of the form
9884 //
9885 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
9886 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
9887 void addAssignmentPointerOverloads(bool isEqualOp) {
9888 /// Set of (canonical) types that we've already handled.
9889 llvm::SmallPtrSet<QualType, 8> AddedTypes;
9890
9891 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
9892 // If this is operator=, keep track of the builtin candidates we added.
9893 if (isEqualOp)
9894 AddedTypes.insert(S.Context.getCanonicalType(PtrTy));
9895 else if (!PtrTy->getPointeeType()->isObjectType())
9896 continue;
9897
9898 // non-volatile version
9899 QualType ParamTypes[2] = {
9901 isEqualOp ? PtrTy : S.Context.getPointerDiffType(),
9902 };
9903 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9904 /*IsAssignmentOperator=*/ isEqualOp);
9905
9906 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9907 VisibleTypeConversionsQuals.hasVolatile();
9908 if (NeedVolatile) {
9909 // volatile version
9910 ParamTypes[0] =
9912 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9913 /*IsAssignmentOperator=*/isEqualOp);
9914 }
9915
9916 if (!PtrTy.isRestrictQualified() &&
9917 VisibleTypeConversionsQuals.hasRestrict()) {
9918 // restrict version
9919 ParamTypes[0] =
9921 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9922 /*IsAssignmentOperator=*/isEqualOp);
9923
9924 if (NeedVolatile) {
9925 // volatile restrict version
9926 ParamTypes[0] =
9929 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9930 /*IsAssignmentOperator=*/isEqualOp);
9931 }
9932 }
9933 }
9934
9935 if (isEqualOp) {
9936 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
9937 // Make sure we don't add the same candidate twice.
9938 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
9939 continue;
9940
9941 QualType ParamTypes[2] = {
9943 PtrTy,
9944 };
9945
9946 // non-volatile version
9947 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9948 /*IsAssignmentOperator=*/true);
9949
9950 bool NeedVolatile = !PtrTy.isVolatileQualified() &&
9951 VisibleTypeConversionsQuals.hasVolatile();
9952 if (NeedVolatile) {
9953 // volatile version
9954 ParamTypes[0] = S.Context.getLValueReferenceType(
9955 S.Context.getVolatileType(PtrTy));
9956 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9957 /*IsAssignmentOperator=*/true);
9958 }
9959
9960 if (!PtrTy.isRestrictQualified() &&
9961 VisibleTypeConversionsQuals.hasRestrict()) {
9962 // restrict version
9963 ParamTypes[0] = S.Context.getLValueReferenceType(
9964 S.Context.getRestrictType(PtrTy));
9965 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9966 /*IsAssignmentOperator=*/true);
9967
9968 if (NeedVolatile) {
9969 // volatile restrict version
9970 ParamTypes[0] =
9973 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
9974 /*IsAssignmentOperator=*/true);
9975 }
9976 }
9977 }
9978 }
9979 }
9980
9981 // C++ [over.built]p18:
9982 //
9983 // For every triple (L, VQ, R), where L is an arithmetic type,
9984 // VQ is either volatile or empty, and R is a promoted
9985 // arithmetic type, there exist candidate operator functions of
9986 // the form
9987 //
9988 // VQ L& operator=(VQ L&, R);
9989 // VQ L& operator*=(VQ L&, R);
9990 // VQ L& operator/=(VQ L&, R);
9991 // VQ L& operator+=(VQ L&, R);
9992 // VQ L& operator-=(VQ L&, R);
9993 void addAssignmentArithmeticOverloads(bool isEqualOp) {
9994 if (!HasArithmeticOrEnumeralCandidateType)
9995 return;
9996
9997 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
9998 for (unsigned Right = FirstPromotedArithmeticType;
9999 Right < LastPromotedArithmeticType; ++Right) {
10000 QualType ParamTypes[2];
10001 ParamTypes[1] = ArithmeticTypes[Right];
10003 S, ArithmeticTypes[Left], Args[0]);
10004
10006 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10007 ParamTypes[0] =
10008 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10009 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10010 /*IsAssignmentOperator=*/isEqualOp);
10011 });
10012 }
10013 }
10014
10015 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
10016 for (QualType Vec1Ty : CandidateTypes[0].vector_types())
10017 for (QualType Vec2Ty : CandidateTypes[0].vector_types()) {
10018 QualType ParamTypes[2];
10019 ParamTypes[1] = Vec2Ty;
10020 // Add this built-in operator as a candidate (VQ is empty).
10021 ParamTypes[0] = S.Context.getLValueReferenceType(Vec1Ty);
10022 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10023 /*IsAssignmentOperator=*/isEqualOp);
10024
10025 // Add this built-in operator as a candidate (VQ is 'volatile').
10026 if (VisibleTypeConversionsQuals.hasVolatile()) {
10027 ParamTypes[0] = S.Context.getVolatileType(Vec1Ty);
10028 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
10029 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10030 /*IsAssignmentOperator=*/isEqualOp);
10031 }
10032 }
10033 }
10034
10035 // C++ [over.built]p22:
10036 //
10037 // For every triple (L, VQ, R), where L is an integral type, VQ
10038 // is either volatile or empty, and R is a promoted integral
10039 // type, there exist candidate operator functions of the form
10040 //
10041 // VQ L& operator%=(VQ L&, R);
10042 // VQ L& operator<<=(VQ L&, R);
10043 // VQ L& operator>>=(VQ L&, R);
10044 // VQ L& operator&=(VQ L&, R);
10045 // VQ L& operator^=(VQ L&, R);
10046 // VQ L& operator|=(VQ L&, R);
10047 void addAssignmentIntegralOverloads() {
10048 if (!HasArithmeticOrEnumeralCandidateType)
10049 return;
10050
10051 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
10052 for (unsigned Right = FirstPromotedIntegralType;
10053 Right < LastPromotedIntegralType; ++Right) {
10054 QualType ParamTypes[2];
10055 ParamTypes[1] = ArithmeticTypes[Right];
10057 S, ArithmeticTypes[Left], Args[0]);
10058
10060 VisibleTypeConversionsQuals, [&](QualifiersAndAtomic Quals) {
10061 ParamTypes[0] =
10062 makeQualifiedLValueReferenceType(LeftBaseTy, Quals, S);
10063 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10064 });
10065 }
10066 }
10067 }
10068
10069 // C++ [over.operator]p23:
10070 //
10071 // There also exist candidate operator functions of the form
10072 //
10073 // bool operator!(bool);
10074 // bool operator&&(bool, bool);
10075 // bool operator||(bool, bool);
10076 void addExclaimOverload() {
10077 QualType ParamTy = S.Context.BoolTy;
10078 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
10079 /*IsAssignmentOperator=*/false,
10080 /*NumContextualBoolArguments=*/1);
10081 }
10082 void addAmpAmpOrPipePipeOverload() {
10083 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
10084 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
10085 /*IsAssignmentOperator=*/false,
10086 /*NumContextualBoolArguments=*/2);
10087 }
10088
10089 // C++ [over.built]p13:
10090 //
10091 // For every cv-qualified or cv-unqualified object type T there
10092 // exist candidate operator functions of the form
10093 //
10094 // T* operator+(T*, ptrdiff_t); [ABOVE]
10095 // T& operator[](T*, ptrdiff_t);
10096 // T* operator-(T*, ptrdiff_t); [ABOVE]
10097 // T* operator+(ptrdiff_t, T*); [ABOVE]
10098 // T& operator[](ptrdiff_t, T*);
10099 void addSubscriptOverloads() {
10100 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10101 QualType ParamTypes[2] = {PtrTy, S.Context.getPointerDiffType()};
10102 QualType PointeeType = PtrTy->getPointeeType();
10103 if (!PointeeType->isObjectType())
10104 continue;
10105
10106 // T& operator[](T*, ptrdiff_t)
10107 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10108 }
10109
10110 for (QualType PtrTy : CandidateTypes[1].pointer_types()) {
10111 QualType ParamTypes[2] = {S.Context.getPointerDiffType(), PtrTy};
10112 QualType PointeeType = PtrTy->getPointeeType();
10113 if (!PointeeType->isObjectType())
10114 continue;
10115
10116 // T& operator[](ptrdiff_t, T*)
10117 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10118 }
10119 }
10120
10121 // C++ [over.built]p11:
10122 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
10123 // C1 is the same type as C2 or is a derived class of C2, T is an object
10124 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
10125 // there exist candidate operator functions of the form
10126 //
10127 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
10128 //
10129 // where CV12 is the union of CV1 and CV2.
10130 void addArrowStarOverloads() {
10131 for (QualType PtrTy : CandidateTypes[0].pointer_types()) {
10132 QualType C1Ty = PtrTy;
10133 QualType C1;
10134 QualifierCollector Q1;
10135 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
10136 if (!isa<RecordType>(C1))
10137 continue;
10138 // heuristic to reduce number of builtin candidates in the set.
10139 // Add volatile/restrict version only if there are conversions to a
10140 // volatile/restrict type.
10141 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
10142 continue;
10143 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
10144 continue;
10145 for (QualType MemPtrTy : CandidateTypes[1].member_pointer_types()) {
10146 const MemberPointerType *mptr = cast<MemberPointerType>(MemPtrTy);
10147 CXXRecordDecl *D1 = C1->castAsCXXRecordDecl(),
10148 *D2 = mptr->getMostRecentCXXRecordDecl();
10149 if (!declaresSameEntity(D1, D2) &&
10150 !S.IsDerivedFrom(CandidateSet.getLocation(), D1, D2))
10151 break;
10152 QualType ParamTypes[2] = {PtrTy, MemPtrTy};
10153 // build CV12 T&
10154 QualType T = mptr->getPointeeType();
10155 if (!VisibleTypeConversionsQuals.hasVolatile() &&
10156 T.isVolatileQualified())
10157 continue;
10158 if (!VisibleTypeConversionsQuals.hasRestrict() &&
10159 T.isRestrictQualified())
10160 continue;
10161 T = Q1.apply(S.Context, T);
10162 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10163 }
10164 }
10165 }
10166
10167 // Note that we don't consider the first argument, since it has been
10168 // contextually converted to bool long ago. The candidates below are
10169 // therefore added as binary.
10170 //
10171 // C++ [over.built]p25:
10172 // For every type T, where T is a pointer, pointer-to-member, or scoped
10173 // enumeration type, there exist candidate operator functions of the form
10174 //
10175 // T operator?(bool, T, T);
10176 //
10177 void addConditionalOperatorOverloads() {
10178 /// Set of (canonical) types that we've already handled.
10179 llvm::SmallPtrSet<QualType, 8> AddedTypes;
10180
10181 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
10182 for (QualType PtrTy : CandidateTypes[ArgIdx].pointer_types()) {
10183 if (!AddedTypes.insert(S.Context.getCanonicalType(PtrTy)).second)
10184 continue;
10185
10186 QualType ParamTypes[2] = {PtrTy, PtrTy};
10187 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10188 }
10189
10190 for (QualType MemPtrTy : CandidateTypes[ArgIdx].member_pointer_types()) {
10191 if (!AddedTypes.insert(S.Context.getCanonicalType(MemPtrTy)).second)
10192 continue;
10193
10194 QualType ParamTypes[2] = {MemPtrTy, MemPtrTy};
10195 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10196 }
10197
10198 if (S.getLangOpts().CPlusPlus11) {
10199 for (QualType EnumTy : CandidateTypes[ArgIdx].enumeration_types()) {
10200 if (!EnumTy->castAsCanonical<EnumType>()
10201 ->getOriginalDecl()
10202 ->isScoped())
10203 continue;
10204
10205 if (!AddedTypes.insert(S.Context.getCanonicalType(EnumTy)).second)
10206 continue;
10207
10208 QualType ParamTypes[2] = {EnumTy, EnumTy};
10209 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
10210 }
10211 }
10212 }
10213 }
10214};
10215
10216} // end anonymous namespace
10217
10219 SourceLocation OpLoc,
10220 ArrayRef<Expr *> Args,
10221 OverloadCandidateSet &CandidateSet) {
10222 // Find all of the types that the arguments can convert to, but only
10223 // if the operator we're looking at has built-in operator candidates
10224 // that make use of these types. Also record whether we encounter non-record
10225 // candidate types or either arithmetic or enumeral candidate types.
10226 QualifiersAndAtomic VisibleTypeConversionsQuals;
10227 VisibleTypeConversionsQuals.addConst();
10228 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10229 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
10230 if (Args[ArgIdx]->getType()->isAtomicType())
10231 VisibleTypeConversionsQuals.addAtomic();
10232 }
10233
10234 bool HasNonRecordCandidateType = false;
10235 bool HasArithmeticOrEnumeralCandidateType = false;
10237 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
10238 CandidateTypes.emplace_back(*this);
10239 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
10240 OpLoc,
10241 true,
10242 (Op == OO_Exclaim ||
10243 Op == OO_AmpAmp ||
10244 Op == OO_PipePipe),
10245 VisibleTypeConversionsQuals);
10246 HasNonRecordCandidateType = HasNonRecordCandidateType ||
10247 CandidateTypes[ArgIdx].hasNonRecordTypes();
10248 HasArithmeticOrEnumeralCandidateType =
10249 HasArithmeticOrEnumeralCandidateType ||
10250 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
10251 }
10252
10253 // Exit early when no non-record types have been added to the candidate set
10254 // for any of the arguments to the operator.
10255 //
10256 // We can't exit early for !, ||, or &&, since there we have always have
10257 // 'bool' overloads.
10258 if (!HasNonRecordCandidateType &&
10259 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
10260 return;
10261
10262 // Setup an object to manage the common state for building overloads.
10263 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
10264 VisibleTypeConversionsQuals,
10265 HasArithmeticOrEnumeralCandidateType,
10266 CandidateTypes, CandidateSet);
10267
10268 // Dispatch over the operation to add in only those overloads which apply.
10269 switch (Op) {
10270 case OO_None:
10272 llvm_unreachable("Expected an overloaded operator");
10273
10274 case OO_New:
10275 case OO_Delete:
10276 case OO_Array_New:
10277 case OO_Array_Delete:
10278 case OO_Call:
10279 llvm_unreachable(
10280 "Special operators don't use AddBuiltinOperatorCandidates");
10281
10282 case OO_Comma:
10283 case OO_Arrow:
10284 case OO_Coawait:
10285 // C++ [over.match.oper]p3:
10286 // -- For the operator ',', the unary operator '&', the
10287 // operator '->', or the operator 'co_await', the
10288 // built-in candidates set is empty.
10289 break;
10290
10291 case OO_Plus: // '+' is either unary or binary
10292 if (Args.size() == 1)
10293 OpBuilder.addUnaryPlusPointerOverloads();
10294 [[fallthrough]];
10295
10296 case OO_Minus: // '-' is either unary or binary
10297 if (Args.size() == 1) {
10298 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
10299 } else {
10300 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
10301 OpBuilder.addGenericBinaryArithmeticOverloads();
10302 OpBuilder.addMatrixBinaryArithmeticOverloads();
10303 }
10304 break;
10305
10306 case OO_Star: // '*' is either unary or binary
10307 if (Args.size() == 1)
10308 OpBuilder.addUnaryStarPointerOverloads();
10309 else {
10310 OpBuilder.addGenericBinaryArithmeticOverloads();
10311 OpBuilder.addMatrixBinaryArithmeticOverloads();
10312 }
10313 break;
10314
10315 case OO_Slash:
10316 OpBuilder.addGenericBinaryArithmeticOverloads();
10317 break;
10318
10319 case OO_PlusPlus:
10320 case OO_MinusMinus:
10321 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
10322 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
10323 break;
10324
10325 case OO_EqualEqual:
10326 case OO_ExclaimEqual:
10327 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
10328 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10329 OpBuilder.addGenericBinaryArithmeticOverloads();
10330 break;
10331
10332 case OO_Less:
10333 case OO_Greater:
10334 case OO_LessEqual:
10335 case OO_GreaterEqual:
10336 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/false);
10337 OpBuilder.addGenericBinaryArithmeticOverloads();
10338 break;
10339
10340 case OO_Spaceship:
10341 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads(/*IsSpaceship=*/true);
10342 OpBuilder.addThreeWayArithmeticOverloads();
10343 break;
10344
10345 case OO_Percent:
10346 case OO_Caret:
10347 case OO_Pipe:
10348 case OO_LessLess:
10349 case OO_GreaterGreater:
10350 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10351 break;
10352
10353 case OO_Amp: // '&' is either unary or binary
10354 if (Args.size() == 1)
10355 // C++ [over.match.oper]p3:
10356 // -- For the operator ',', the unary operator '&', or the
10357 // operator '->', the built-in candidates set is empty.
10358 break;
10359
10360 OpBuilder.addBinaryBitwiseArithmeticOverloads();
10361 break;
10362
10363 case OO_Tilde:
10364 OpBuilder.addUnaryTildePromotedIntegralOverloads();
10365 break;
10366
10367 case OO_Equal:
10368 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
10369 [[fallthrough]];
10370
10371 case OO_PlusEqual:
10372 case OO_MinusEqual:
10373 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
10374 [[fallthrough]];
10375
10376 case OO_StarEqual:
10377 case OO_SlashEqual:
10378 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
10379 break;
10380
10381 case OO_PercentEqual:
10382 case OO_LessLessEqual:
10383 case OO_GreaterGreaterEqual:
10384 case OO_AmpEqual:
10385 case OO_CaretEqual:
10386 case OO_PipeEqual:
10387 OpBuilder.addAssignmentIntegralOverloads();
10388 break;
10389
10390 case OO_Exclaim:
10391 OpBuilder.addExclaimOverload();
10392 break;
10393
10394 case OO_AmpAmp:
10395 case OO_PipePipe:
10396 OpBuilder.addAmpAmpOrPipePipeOverload();
10397 break;
10398
10399 case OO_Subscript:
10400 if (Args.size() == 2)
10401 OpBuilder.addSubscriptOverloads();
10402 break;
10403
10404 case OO_ArrowStar:
10405 OpBuilder.addArrowStarOverloads();
10406 break;
10407
10408 case OO_Conditional:
10409 OpBuilder.addConditionalOperatorOverloads();
10410 OpBuilder.addGenericBinaryArithmeticOverloads();
10411 break;
10412 }
10413}
10414
10415void
10417 SourceLocation Loc,
10418 ArrayRef<Expr *> Args,
10419 TemplateArgumentListInfo *ExplicitTemplateArgs,
10420 OverloadCandidateSet& CandidateSet,
10421 bool PartialOverloading) {
10422 ADLResult Fns;
10423
10424 // FIXME: This approach for uniquing ADL results (and removing
10425 // redundant candidates from the set) relies on pointer-equality,
10426 // which means we need to key off the canonical decl. However,
10427 // always going back to the canonical decl might not get us the
10428 // right set of default arguments. What default arguments are
10429 // we supposed to consider on ADL candidates, anyway?
10430
10431 // FIXME: Pass in the explicit template arguments?
10432 ArgumentDependentLookup(Name, Loc, Args, Fns);
10433
10434 ArrayRef<Expr *> ReversedArgs;
10435
10436 // Erase all of the candidates we already knew about.
10437 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
10438 CandEnd = CandidateSet.end();
10439 Cand != CandEnd; ++Cand)
10440 if (Cand->Function) {
10441 FunctionDecl *Fn = Cand->Function;
10442 Fns.erase(Fn);
10443 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate())
10444 Fns.erase(FunTmpl);
10445 }
10446
10447 // For each of the ADL candidates we found, add it to the overload
10448 // set.
10449 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
10451
10452 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
10453 if (ExplicitTemplateArgs)
10454 continue;
10455
10457 FD, FoundDecl, Args, CandidateSet, /*SuppressUserConversions=*/false,
10458 PartialOverloading, /*AllowExplicit=*/true,
10459 /*AllowExplicitConversion=*/false, ADLCallKind::UsesADL);
10460 if (CandidateSet.getRewriteInfo().shouldAddReversed(*this, Args, FD)) {
10462 FD, FoundDecl, {Args[1], Args[0]}, CandidateSet,
10463 /*SuppressUserConversions=*/false, PartialOverloading,
10464 /*AllowExplicit=*/true, /*AllowExplicitConversion=*/false,
10465 ADLCallKind::UsesADL, {}, OverloadCandidateParamOrder::Reversed);
10466 }
10467 } else {
10468 auto *FTD = cast<FunctionTemplateDecl>(*I);
10470 FTD, FoundDecl, ExplicitTemplateArgs, Args, CandidateSet,
10471 /*SuppressUserConversions=*/false, PartialOverloading,
10472 /*AllowExplicit=*/true, ADLCallKind::UsesADL);
10473 if (CandidateSet.getRewriteInfo().shouldAddReversed(
10474 *this, Args, FTD->getTemplatedDecl())) {
10475
10476 // As template candidates are not deduced immediately,
10477 // persist the array in the overload set.
10478 if (ReversedArgs.empty())
10479 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
10480
10482 FTD, FoundDecl, ExplicitTemplateArgs, ReversedArgs, CandidateSet,
10483 /*SuppressUserConversions=*/false, PartialOverloading,
10484 /*AllowExplicit=*/true, ADLCallKind::UsesADL,
10486 }
10487 }
10488 }
10489}
10490
10491namespace {
10492enum class Comparison { Equal, Better, Worse };
10493}
10494
10495/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
10496/// overload resolution.
10497///
10498/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
10499/// Cand1's first N enable_if attributes have precisely the same conditions as
10500/// Cand2's first N enable_if attributes (where N = the number of enable_if
10501/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
10502///
10503/// Note that you can have a pair of candidates such that Cand1's enable_if
10504/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
10505/// worse than Cand1's.
10506static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
10507 const FunctionDecl *Cand2) {
10508 // Common case: One (or both) decls don't have enable_if attrs.
10509 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
10510 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
10511 if (!Cand1Attr || !Cand2Attr) {
10512 if (Cand1Attr == Cand2Attr)
10513 return Comparison::Equal;
10514 return Cand1Attr ? Comparison::Better : Comparison::Worse;
10515 }
10516
10517 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
10518 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
10519
10520 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
10521 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
10522 std::optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
10523 std::optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
10524
10525 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
10526 // has fewer enable_if attributes than Cand2, and vice versa.
10527 if (!Cand1A)
10528 return Comparison::Worse;
10529 if (!Cand2A)
10530 return Comparison::Better;
10531
10532 Cand1ID.clear();
10533 Cand2ID.clear();
10534
10535 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
10536 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
10537 if (Cand1ID != Cand2ID)
10538 return Comparison::Worse;
10539 }
10540
10541 return Comparison::Equal;
10542}
10543
10544static Comparison
10546 const OverloadCandidate &Cand2) {
10547 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
10548 !Cand2.Function->isMultiVersion())
10549 return Comparison::Equal;
10550
10551 // If both are invalid, they are equal. If one of them is invalid, the other
10552 // is better.
10553 if (Cand1.Function->isInvalidDecl()) {
10554 if (Cand2.Function->isInvalidDecl())
10555 return Comparison::Equal;
10556 return Comparison::Worse;
10557 }
10558 if (Cand2.Function->isInvalidDecl())
10559 return Comparison::Better;
10560
10561 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
10562 // cpu_dispatch, else arbitrarily based on the identifiers.
10563 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
10564 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
10565 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
10566 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
10567
10568 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
10569 return Comparison::Equal;
10570
10571 if (Cand1CPUDisp && !Cand2CPUDisp)
10572 return Comparison::Better;
10573 if (Cand2CPUDisp && !Cand1CPUDisp)
10574 return Comparison::Worse;
10575
10576 if (Cand1CPUSpec && Cand2CPUSpec) {
10577 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
10578 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size()
10579 ? Comparison::Better
10580 : Comparison::Worse;
10581
10582 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
10583 FirstDiff = std::mismatch(
10584 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
10585 Cand2CPUSpec->cpus_begin(),
10586 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
10587 return LHS->getName() == RHS->getName();
10588 });
10589
10590 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
10591 "Two different cpu-specific versions should not have the same "
10592 "identifier list, otherwise they'd be the same decl!");
10593 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName()
10594 ? Comparison::Better
10595 : Comparison::Worse;
10596 }
10597 llvm_unreachable("No way to get here unless both had cpu_dispatch");
10598}
10599
10600/// Compute the type of the implicit object parameter for the given function,
10601/// if any. Returns std::nullopt if there is no implicit object parameter, and a
10602/// null QualType if there is a 'matches anything' implicit object parameter.
10603static std::optional<QualType>
10606 return std::nullopt;
10607
10608 auto *M = cast<CXXMethodDecl>(F);
10609 // Static member functions' object parameters match all types.
10610 if (M->isStatic())
10611 return QualType();
10612 return M->getFunctionObjectParameterReferenceType();
10613}
10614
10615// As a Clang extension, allow ambiguity among F1 and F2 if they represent
10616// represent the same entity.
10617static bool allowAmbiguity(ASTContext &Context, const FunctionDecl *F1,
10618 const FunctionDecl *F2) {
10619 if (declaresSameEntity(F1, F2))
10620 return true;
10621 auto PT1 = F1->getPrimaryTemplate();
10622 auto PT2 = F2->getPrimaryTemplate();
10623 if (PT1 && PT2) {
10624 if (declaresSameEntity(PT1, PT2) ||
10625 declaresSameEntity(PT1->getInstantiatedFromMemberTemplate(),
10626 PT2->getInstantiatedFromMemberTemplate()))
10627 return true;
10628 }
10629 // TODO: It is not clear whether comparing parameters is necessary (i.e.
10630 // different functions with same params). Consider removing this (as no test
10631 // fail w/o it).
10632 auto NextParam = [&](const FunctionDecl *F, unsigned &I, bool First) {
10633 if (First) {
10634 if (std::optional<QualType> T = getImplicitObjectParamType(Context, F))
10635 return *T;
10636 }
10637 assert(I < F->getNumParams());
10638 return F->getParamDecl(I++)->getType();
10639 };
10640
10641 unsigned F1NumParams = F1->getNumParams() + isa<CXXMethodDecl>(F1);
10642 unsigned F2NumParams = F2->getNumParams() + isa<CXXMethodDecl>(F2);
10643
10644 if (F1NumParams != F2NumParams)
10645 return false;
10646
10647 unsigned I1 = 0, I2 = 0;
10648 for (unsigned I = 0; I != F1NumParams; ++I) {
10649 QualType T1 = NextParam(F1, I1, I == 0);
10650 QualType T2 = NextParam(F2, I2, I == 0);
10651 assert(!T1.isNull() && !T2.isNull() && "Unexpected null param types");
10652 if (!Context.hasSameUnqualifiedType(T1, T2))
10653 return false;
10654 }
10655 return true;
10656}
10657
10658/// We're allowed to use constraints partial ordering only if the candidates
10659/// have the same parameter types:
10660/// [over.match.best.general]p2.6
10661/// F1 and F2 are non-template functions with the same
10662/// non-object-parameter-type-lists, and F1 is more constrained than F2 [...]
10664 FunctionDecl *Fn2,
10665 bool IsFn1Reversed,
10666 bool IsFn2Reversed) {
10667 assert(Fn1 && Fn2);
10668 if (Fn1->isVariadic() != Fn2->isVariadic())
10669 return false;
10670
10671 if (!S.FunctionNonObjectParamTypesAreEqual(Fn1, Fn2, nullptr,
10672 IsFn1Reversed ^ IsFn2Reversed))
10673 return false;
10674
10675 auto *Mem1 = dyn_cast<CXXMethodDecl>(Fn1);
10676 auto *Mem2 = dyn_cast<CXXMethodDecl>(Fn2);
10677 if (Mem1 && Mem2) {
10678 // if they are member functions, both are direct members of the same class,
10679 // and
10680 if (Mem1->getParent() != Mem2->getParent())
10681 return false;
10682 // if both are non-static member functions, they have the same types for
10683 // their object parameters
10684 if (Mem1->isInstance() && Mem2->isInstance() &&
10686 Mem1->getFunctionObjectParameterReferenceType(),
10687 Mem1->getFunctionObjectParameterReferenceType()))
10688 return false;
10689 }
10690 return true;
10691}
10692
10693static FunctionDecl *
10695 bool IsFn1Reversed, bool IsFn2Reversed) {
10696 if (!Fn1 || !Fn2)
10697 return nullptr;
10698
10699 // C++ [temp.constr.order]:
10700 // A non-template function F1 is more partial-ordering-constrained than a
10701 // non-template function F2 if:
10702 bool Cand1IsSpecialization = Fn1->getPrimaryTemplate();
10703 bool Cand2IsSpecialization = Fn2->getPrimaryTemplate();
10704
10705 if (Cand1IsSpecialization || Cand2IsSpecialization)
10706 return nullptr;
10707
10708 // - they have the same non-object-parameter-type-lists, and [...]
10709 if (!sameFunctionParameterTypeLists(S, Fn1, Fn2, IsFn1Reversed,
10710 IsFn2Reversed))
10711 return nullptr;
10712
10713 // - the declaration of F1 is more constrained than the declaration of F2.
10714 return S.getMoreConstrainedFunction(Fn1, Fn2);
10715}
10716
10717/// isBetterOverloadCandidate - Determines whether the first overload
10718/// candidate is a better candidate than the second (C++ 13.3.3p1).
10720 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
10722 bool PartialOverloading) {
10723 // Define viable functions to be better candidates than non-viable
10724 // functions.
10725 if (!Cand2.Viable)
10726 return Cand1.Viable;
10727 else if (!Cand1.Viable)
10728 return false;
10729
10730 // [CUDA] A function with 'never' preference is marked not viable, therefore
10731 // is never shown up here. The worst preference shown up here is 'wrong side',
10732 // e.g. an H function called by a HD function in device compilation. This is
10733 // valid AST as long as the HD function is not emitted, e.g. it is an inline
10734 // function which is called only by an H function. A deferred diagnostic will
10735 // be triggered if it is emitted. However a wrong-sided function is still
10736 // a viable candidate here.
10737 //
10738 // If Cand1 can be emitted and Cand2 cannot be emitted in the current
10739 // context, Cand1 is better than Cand2. If Cand1 can not be emitted and Cand2
10740 // can be emitted, Cand1 is not better than Cand2. This rule should have
10741 // precedence over other rules.
10742 //
10743 // If both Cand1 and Cand2 can be emitted, or neither can be emitted, then
10744 // other rules should be used to determine which is better. This is because
10745 // host/device based overloading resolution is mostly for determining
10746 // viability of a function. If two functions are both viable, other factors
10747 // should take precedence in preference, e.g. the standard-defined preferences
10748 // like argument conversion ranks or enable_if partial-ordering. The
10749 // preference for pass-object-size parameters is probably most similar to a
10750 // type-based-overloading decision and so should take priority.
10751 //
10752 // If other rules cannot determine which is better, CUDA preference will be
10753 // used again to determine which is better.
10754 //
10755 // TODO: Currently IdentifyPreference does not return correct values
10756 // for functions called in global variable initializers due to missing
10757 // correct context about device/host. Therefore we can only enforce this
10758 // rule when there is a caller. We should enforce this rule for functions
10759 // in global variable initializers once proper context is added.
10760 //
10761 // TODO: We can only enable the hostness based overloading resolution when
10762 // -fgpu-exclude-wrong-side-overloads is on since this requires deferring
10763 // overloading resolution diagnostics.
10764 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function &&
10765 S.getLangOpts().GPUExcludeWrongSideOverloads) {
10766 if (FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true)) {
10767 bool IsCallerImplicitHD = SemaCUDA::isImplicitHostDeviceFunction(Caller);
10768 bool IsCand1ImplicitHD =
10770 bool IsCand2ImplicitHD =
10772 auto P1 = S.CUDA().IdentifyPreference(Caller, Cand1.Function);
10773 auto P2 = S.CUDA().IdentifyPreference(Caller, Cand2.Function);
10774 assert(P1 != SemaCUDA::CFP_Never && P2 != SemaCUDA::CFP_Never);
10775 // The implicit HD function may be a function in a system header which
10776 // is forced by pragma. In device compilation, if we prefer HD candidates
10777 // over wrong-sided candidates, overloading resolution may change, which
10778 // may result in non-deferrable diagnostics. As a workaround, we let
10779 // implicit HD candidates take equal preference as wrong-sided candidates.
10780 // This will preserve the overloading resolution.
10781 // TODO: We still need special handling of implicit HD functions since
10782 // they may incur other diagnostics to be deferred. We should make all
10783 // host/device related diagnostics deferrable and remove special handling
10784 // of implicit HD functions.
10785 auto EmitThreshold =
10786 (S.getLangOpts().CUDAIsDevice && IsCallerImplicitHD &&
10787 (IsCand1ImplicitHD || IsCand2ImplicitHD))
10790 auto Cand1Emittable = P1 > EmitThreshold;
10791 auto Cand2Emittable = P2 > EmitThreshold;
10792 if (Cand1Emittable && !Cand2Emittable)
10793 return true;
10794 if (!Cand1Emittable && Cand2Emittable)
10795 return false;
10796 }
10797 }
10798
10799 // C++ [over.match.best]p1: (Changed in C++23)
10800 //
10801 // -- if F is a static member function, ICS1(F) is defined such
10802 // that ICS1(F) is neither better nor worse than ICS1(G) for
10803 // any function G, and, symmetrically, ICS1(G) is neither
10804 // better nor worse than ICS1(F).
10805 unsigned StartArg = 0;
10806 if (!Cand1.TookAddressOfOverload &&
10808 StartArg = 1;
10809
10810 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
10811 // We don't allow incompatible pointer conversions in C++.
10812 if (!S.getLangOpts().CPlusPlus)
10813 return ICS.isStandard() &&
10814 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
10815
10816 // The only ill-formed conversion we allow in C++ is the string literal to
10817 // char* conversion, which is only considered ill-formed after C++11.
10818 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
10820 };
10821
10822 // Define functions that don't require ill-formed conversions for a given
10823 // argument to be better candidates than functions that do.
10824 unsigned NumArgs = Cand1.Conversions.size();
10825 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
10826 bool HasBetterConversion = false;
10827 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10828 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
10829 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
10830 if (Cand1Bad != Cand2Bad) {
10831 if (Cand1Bad)
10832 return false;
10833 HasBetterConversion = true;
10834 }
10835 }
10836
10837 if (HasBetterConversion)
10838 return true;
10839
10840 // C++ [over.match.best]p1:
10841 // A viable function F1 is defined to be a better function than another
10842 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
10843 // conversion sequence than ICSi(F2), and then...
10844 bool HasWorseConversion = false;
10845 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
10847 Cand1.Conversions[ArgIdx],
10848 Cand2.Conversions[ArgIdx])) {
10850 // Cand1 has a better conversion sequence.
10851 HasBetterConversion = true;
10852 break;
10853
10855 if (Cand1.Function && Cand2.Function &&
10856 Cand1.isReversed() != Cand2.isReversed() &&
10857 allowAmbiguity(S.Context, Cand1.Function, Cand2.Function)) {
10858 // Work around large-scale breakage caused by considering reversed
10859 // forms of operator== in C++20:
10860 //
10861 // When comparing a function against a reversed function, if we have a
10862 // better conversion for one argument and a worse conversion for the
10863 // other, the implicit conversion sequences are treated as being equally
10864 // good.
10865 //
10866 // This prevents a comparison function from being considered ambiguous
10867 // with a reversed form that is written in the same way.
10868 //
10869 // We diagnose this as an extension from CreateOverloadedBinOp.
10870 HasWorseConversion = true;
10871 break;
10872 }
10873
10874 // Cand1 can't be better than Cand2.
10875 return false;
10876
10878 // Do nothing.
10879 break;
10880 }
10881 }
10882
10883 // -- for some argument j, ICSj(F1) is a better conversion sequence than
10884 // ICSj(F2), or, if not that,
10885 if (HasBetterConversion && !HasWorseConversion)
10886 return true;
10887
10888 // -- the context is an initialization by user-defined conversion
10889 // (see 8.5, 13.3.1.5) and the standard conversion sequence
10890 // from the return type of F1 to the destination type (i.e.,
10891 // the type of the entity being initialized) is a better
10892 // conversion sequence than the standard conversion sequence
10893 // from the return type of F2 to the destination type.
10895 Cand1.Function && Cand2.Function &&
10898
10899 assert(Cand1.HasFinalConversion && Cand2.HasFinalConversion);
10900 // First check whether we prefer one of the conversion functions over the
10901 // other. This only distinguishes the results in non-standard, extension
10902 // cases such as the conversion from a lambda closure type to a function
10903 // pointer or block.
10908 Cand1.FinalConversion,
10909 Cand2.FinalConversion);
10910
10913
10914 // FIXME: Compare kind of reference binding if conversion functions
10915 // convert to a reference type used in direct reference binding, per
10916 // C++14 [over.match.best]p1 section 2 bullet 3.
10917 }
10918
10919 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
10920 // as combined with the resolution to CWG issue 243.
10921 //
10922 // When the context is initialization by constructor ([over.match.ctor] or
10923 // either phase of [over.match.list]), a constructor is preferred over
10924 // a conversion function.
10925 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
10926 Cand1.Function && Cand2.Function &&
10929 return isa<CXXConstructorDecl>(Cand1.Function);
10930
10931 if (Cand1.StrictPackMatch != Cand2.StrictPackMatch)
10932 return Cand2.StrictPackMatch;
10933
10934 // -- F1 is a non-template function and F2 is a function template
10935 // specialization, or, if not that,
10936 bool Cand1IsSpecialization = Cand1.Function &&
10938 bool Cand2IsSpecialization = Cand2.Function &&
10940 if (Cand1IsSpecialization != Cand2IsSpecialization)
10941 return Cand2IsSpecialization;
10942
10943 // -- F1 and F2 are function template specializations, and the function
10944 // template for F1 is more specialized than the template for F2
10945 // according to the partial ordering rules described in 14.5.5.2, or,
10946 // if not that,
10947 if (Cand1IsSpecialization && Cand2IsSpecialization) {
10948 const auto *Obj1Context =
10949 dyn_cast<CXXRecordDecl>(Cand1.FoundDecl->getDeclContext());
10950 const auto *Obj2Context =
10951 dyn_cast<CXXRecordDecl>(Cand2.FoundDecl->getDeclContext());
10952 if (FunctionTemplateDecl *BetterTemplate = S.getMoreSpecializedTemplate(
10954 Cand2.Function->getPrimaryTemplate(), Loc,
10956 : TPOC_Call,
10958 Obj1Context ? S.Context.getCanonicalTagType(Obj1Context)
10959 : QualType{},
10960 Obj2Context ? S.Context.getCanonicalTagType(Obj2Context)
10961 : QualType{},
10962 Cand1.isReversed() ^ Cand2.isReversed(), PartialOverloading)) {
10963 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
10964 }
10965 }
10966
10967 // -— F1 and F2 are non-template functions and F1 is more
10968 // partial-ordering-constrained than F2 [...],
10970 S, Cand1.Function, Cand2.Function, Cand1.isReversed(),
10971 Cand2.isReversed());
10972 F && F == Cand1.Function)
10973 return true;
10974
10975 // -- F1 is a constructor for a class D, F2 is a constructor for a base
10976 // class B of D, and for all arguments the corresponding parameters of
10977 // F1 and F2 have the same type.
10978 // FIXME: Implement the "all parameters have the same type" check.
10979 bool Cand1IsInherited =
10980 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
10981 bool Cand2IsInherited =
10982 isa_and_nonnull<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
10983 if (Cand1IsInherited != Cand2IsInherited)
10984 return Cand2IsInherited;
10985 else if (Cand1IsInherited) {
10986 assert(Cand2IsInherited);
10987 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
10988 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
10989 if (Cand1Class->isDerivedFrom(Cand2Class))
10990 return true;
10991 if (Cand2Class->isDerivedFrom(Cand1Class))
10992 return false;
10993 // Inherited from sibling base classes: still ambiguous.
10994 }
10995
10996 // -- F2 is a rewritten candidate (12.4.1.2) and F1 is not
10997 // -- F1 and F2 are rewritten candidates, and F2 is a synthesized candidate
10998 // with reversed order of parameters and F1 is not
10999 //
11000 // We rank reversed + different operator as worse than just reversed, but
11001 // that comparison can never happen, because we only consider reversing for
11002 // the maximally-rewritten operator (== or <=>).
11003 if (Cand1.RewriteKind != Cand2.RewriteKind)
11004 return Cand1.RewriteKind < Cand2.RewriteKind;
11005
11006 // Check C++17 tie-breakers for deduction guides.
11007 {
11008 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
11009 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
11010 if (Guide1 && Guide2) {
11011 // -- F1 is generated from a deduction-guide and F2 is not
11012 if (Guide1->isImplicit() != Guide2->isImplicit())
11013 return Guide2->isImplicit();
11014
11015 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
11016 if (Guide1->getDeductionCandidateKind() == DeductionCandidate::Copy)
11017 return true;
11018 if (Guide2->getDeductionCandidateKind() == DeductionCandidate::Copy)
11019 return false;
11020
11021 // --F1 is generated from a non-template constructor and F2 is generated
11022 // from a constructor template
11023 const auto *Constructor1 = Guide1->getCorrespondingConstructor();
11024 const auto *Constructor2 = Guide2->getCorrespondingConstructor();
11025 if (Constructor1 && Constructor2) {
11026 bool isC1Templated = Constructor1->getTemplatedKind() !=
11028 bool isC2Templated = Constructor2->getTemplatedKind() !=
11030 if (isC1Templated != isC2Templated)
11031 return isC2Templated;
11032 }
11033 }
11034 }
11035
11036 // Check for enable_if value-based overload resolution.
11037 if (Cand1.Function && Cand2.Function) {
11038 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
11039 if (Cmp != Comparison::Equal)
11040 return Cmp == Comparison::Better;
11041 }
11042
11043 bool HasPS1 = Cand1.Function != nullptr &&
11045 bool HasPS2 = Cand2.Function != nullptr &&
11047 if (HasPS1 != HasPS2 && HasPS1)
11048 return true;
11049
11050 auto MV = isBetterMultiversionCandidate(Cand1, Cand2);
11051 if (MV == Comparison::Better)
11052 return true;
11053 if (MV == Comparison::Worse)
11054 return false;
11055
11056 // If other rules cannot determine which is better, CUDA preference is used
11057 // to determine which is better.
11058 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
11059 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11060 return S.CUDA().IdentifyPreference(Caller, Cand1.Function) >
11061 S.CUDA().IdentifyPreference(Caller, Cand2.Function);
11062 }
11063
11064 // General member function overloading is handled above, so this only handles
11065 // constructors with address spaces.
11066 // This only handles address spaces since C++ has no other
11067 // qualifier that can be used with constructors.
11068 const auto *CD1 = dyn_cast_or_null<CXXConstructorDecl>(Cand1.Function);
11069 const auto *CD2 = dyn_cast_or_null<CXXConstructorDecl>(Cand2.Function);
11070 if (CD1 && CD2) {
11071 LangAS AS1 = CD1->getMethodQualifiers().getAddressSpace();
11072 LangAS AS2 = CD2->getMethodQualifiers().getAddressSpace();
11073 if (AS1 != AS2) {
11075 return true;
11077 return false;
11078 }
11079 }
11080
11081 return false;
11082}
11083
11084/// Determine whether two declarations are "equivalent" for the purposes of
11085/// name lookup and overload resolution. This applies when the same internal/no
11086/// linkage entity is defined by two modules (probably by textually including
11087/// the same header). In such a case, we don't consider the declarations to
11088/// declare the same entity, but we also don't want lookups with both
11089/// declarations visible to be ambiguous in some cases (this happens when using
11090/// a modularized libstdc++).
11092 const NamedDecl *B) {
11093 auto *VA = dyn_cast_or_null<ValueDecl>(A);
11094 auto *VB = dyn_cast_or_null<ValueDecl>(B);
11095 if (!VA || !VB)
11096 return false;
11097
11098 // The declarations must be declaring the same name as an internal linkage
11099 // entity in different modules.
11100 if (!VA->getDeclContext()->getRedeclContext()->Equals(
11101 VB->getDeclContext()->getRedeclContext()) ||
11102 getOwningModule(VA) == getOwningModule(VB) ||
11103 VA->isExternallyVisible() || VB->isExternallyVisible())
11104 return false;
11105
11106 // Check that the declarations appear to be equivalent.
11107 //
11108 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
11109 // For constants and functions, we should check the initializer or body is
11110 // the same. For non-constant variables, we shouldn't allow it at all.
11111 if (Context.hasSameType(VA->getType(), VB->getType()))
11112 return true;
11113
11114 // Enum constants within unnamed enumerations will have different types, but
11115 // may still be similar enough to be interchangeable for our purposes.
11116 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
11117 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
11118 // Only handle anonymous enums. If the enumerations were named and
11119 // equivalent, they would have been merged to the same type.
11120 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
11121 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
11122 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
11123 !Context.hasSameType(EnumA->getIntegerType(),
11124 EnumB->getIntegerType()))
11125 return false;
11126 // Allow this only if the value is the same for both enumerators.
11127 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
11128 }
11129 }
11130
11131 // Nothing else is sufficiently similar.
11132 return false;
11133}
11134
11137 assert(D && "Unknown declaration");
11138 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
11139
11140 Module *M = getOwningModule(D);
11141 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
11142 << !M << (M ? M->getFullModuleName() : "");
11143
11144 for (auto *E : Equiv) {
11145 Module *M = getOwningModule(E);
11146 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
11147 << !M << (M ? M->getFullModuleName() : "");
11148 }
11149}
11150
11153 static_cast<TemplateDeductionResult>(DeductionFailure.Result) ==
11155 static_cast<CNSInfo *>(DeductionFailure.Data)
11156 ->Satisfaction.ContainsErrors;
11157}
11158
11161 ArrayRef<Expr *> Args, bool SuppressUserConversions,
11162 bool PartialOverloading, bool AllowExplicit,
11164 bool AggregateCandidateDeduction) {
11165
11166 auto *C =
11167 allocateDeferredCandidate<DeferredFunctionTemplateOverloadCandidate>();
11168
11171 /*AllowObjCConversionOnExplicit=*/false,
11172 /*AllowResultConversion=*/false, AllowExplicit, SuppressUserConversions,
11173 PartialOverloading, AggregateCandidateDeduction},
11175 FoundDecl,
11176 Args,
11177 IsADLCandidate,
11178 PO};
11179
11180 HasDeferredTemplateConstructors |=
11181 isa<CXXConstructorDecl>(FunctionTemplate->getTemplatedDecl());
11182}
11183
11185 FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl,
11186 CXXRecordDecl *ActingContext, QualType ObjectType,
11187 Expr::Classification ObjectClassification, ArrayRef<Expr *> Args,
11188 bool SuppressUserConversions, bool PartialOverloading,
11190
11191 assert(!isa<CXXConstructorDecl>(MethodTmpl->getTemplatedDecl()));
11192
11193 auto *C =
11194 allocateDeferredCandidate<DeferredMethodTemplateOverloadCandidate>();
11195
11198 /*AllowObjCConversionOnExplicit=*/false,
11199 /*AllowResultConversion=*/false,
11200 /*AllowExplicit=*/false, SuppressUserConversions, PartialOverloading,
11201 /*AggregateCandidateDeduction=*/false},
11202 MethodTmpl,
11203 FoundDecl,
11204 Args,
11205 ActingContext,
11206 ObjectClassification,
11207 ObjectType,
11208 PO};
11209}
11210
11213 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
11214 bool AllowObjCConversionOnExplicit, bool AllowExplicit,
11215 bool AllowResultConversion) {
11216
11217 auto *C =
11218 allocateDeferredCandidate<DeferredConversionTemplateOverloadCandidate>();
11219
11222 AllowObjCConversionOnExplicit, AllowResultConversion,
11223 /*AllowExplicit=*/false,
11224 /*SuppressUserConversions=*/false,
11225 /*PartialOverloading*/ false,
11226 /*AggregateCandidateDeduction=*/false},
11228 FoundDecl,
11229 ActingContext,
11230 From,
11231 ToType};
11232}
11233
11234static void
11237
11239 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext,
11240 /*ExplicitTemplateArgs=*/nullptr, C.ObjectType, C.ObjectClassification,
11241 C.Args, C.SuppressUserConversions, C.PartialOverloading, C.PO);
11242}
11243
11244static void
11248 S, CandidateSet, C.FunctionTemplate, C.FoundDecl,
11249 /*ExplicitTemplateArgs=*/nullptr, C.Args, C.SuppressUserConversions,
11250 C.PartialOverloading, C.AllowExplicit, C.IsADLCandidate, C.PO,
11251 C.AggregateCandidateDeduction);
11252}
11253
11254static void
11258 S, CandidateSet, C.FunctionTemplate, C.FoundDecl, C.ActingContext, C.From,
11259 C.ToType, C.AllowObjCConversionOnExplicit, C.AllowExplicit,
11260 C.AllowResultConversion);
11261}
11262
11264 Candidates.reserve(Candidates.size() + DeferredCandidatesCount);
11265 DeferredTemplateOverloadCandidate *Cand = FirstDeferredCandidate;
11266 while (Cand) {
11267 switch (Cand->Kind) {
11270 S, *this,
11271 *static_cast<DeferredFunctionTemplateOverloadCandidate *>(Cand));
11272 break;
11275 S, *this,
11276 *static_cast<DeferredMethodTemplateOverloadCandidate *>(Cand));
11277 break;
11280 S, *this,
11281 *static_cast<DeferredConversionTemplateOverloadCandidate *>(Cand));
11282 break;
11283 }
11284 Cand = Cand->Next;
11285 }
11286 FirstDeferredCandidate = nullptr;
11287 DeferredCandidatesCount = 0;
11288}
11289
11291OverloadCandidateSet::ResultForBestCandidate(const iterator &Best) {
11292 Best->Best = true;
11293 if (Best->Function && Best->Function->isDeleted())
11294 return OR_Deleted;
11295 return OR_Success;
11296}
11297
11298void OverloadCandidateSet::CudaExcludeWrongSideCandidates(
11300 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
11301 // are accepted by both clang and NVCC. However, during a particular
11302 // compilation mode only one call variant is viable. We need to
11303 // exclude non-viable overload candidates from consideration based
11304 // only on their host/device attributes. Specifically, if one
11305 // candidate call is WrongSide and the other is SameSide, we ignore
11306 // the WrongSide candidate.
11307 // We only need to remove wrong-sided candidates here if
11308 // -fgpu-exclude-wrong-side-overloads is off. When
11309 // -fgpu-exclude-wrong-side-overloads is on, all candidates are compared
11310 // uniformly in isBetterOverloadCandidate.
11311 if (!S.getLangOpts().CUDA || S.getLangOpts().GPUExcludeWrongSideOverloads)
11312 return;
11313 const FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
11314
11315 bool ContainsSameSideCandidate =
11316 llvm::any_of(Candidates, [&](const OverloadCandidate *Cand) {
11317 // Check viable function only.
11318 return Cand->Viable && Cand->Function &&
11319 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11321 });
11322
11323 if (!ContainsSameSideCandidate)
11324 return;
11325
11326 auto IsWrongSideCandidate = [&](const OverloadCandidate *Cand) {
11327 // Check viable function only to avoid unnecessary data copying/moving.
11328 return Cand->Viable && Cand->Function &&
11329 S.CUDA().IdentifyPreference(Caller, Cand->Function) ==
11331 };
11332 llvm::erase_if(Candidates, IsWrongSideCandidate);
11333}
11334
11335/// Computes the best viable function (C++ 13.3.3)
11336/// within an overload candidate set.
11337///
11338/// \param Loc The location of the function name (or operator symbol) for
11339/// which overload resolution occurs.
11340///
11341/// \param Best If overload resolution was successful or found a deleted
11342/// function, \p Best points to the candidate function found.
11343///
11344/// \returns The result of overload resolution.
11346 SourceLocation Loc,
11347 iterator &Best) {
11348
11350 DeferredCandidatesCount == 0) &&
11351 "Unexpected deferred template candidates");
11352
11353 bool TwoPhaseResolution =
11354 DeferredCandidatesCount != 0 && !ResolutionByPerfectCandidateIsDisabled;
11355
11356 if (TwoPhaseResolution) {
11357 OverloadingResult Res = BestViableFunctionImpl(S, Loc, Best);
11358 if (Best != end() && Best->isPerfectMatch(S.Context)) {
11359 if (!(HasDeferredTemplateConstructors &&
11360 isa_and_nonnull<CXXConversionDecl>(Best->Function)))
11361 return Res;
11362 }
11363 }
11364
11366 return BestViableFunctionImpl(S, Loc, Best);
11367}
11368
11369OverloadingResult OverloadCandidateSet::BestViableFunctionImpl(
11371
11373 Candidates.reserve(this->Candidates.size());
11374 std::transform(this->Candidates.begin(), this->Candidates.end(),
11375 std::back_inserter(Candidates),
11376 [](OverloadCandidate &Cand) { return &Cand; });
11377
11378 if (S.getLangOpts().CUDA)
11379 CudaExcludeWrongSideCandidates(S, Candidates);
11380
11381 Best = end();
11382 for (auto *Cand : Candidates) {
11383 Cand->Best = false;
11384 if (Cand->Viable) {
11385 if (Best == end() ||
11386 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
11387 Best = Cand;
11388 } else if (Cand->NotValidBecauseConstraintExprHasError()) {
11389 // This candidate has constraint that we were unable to evaluate because
11390 // it referenced an expression that contained an error. Rather than fall
11391 // back onto a potentially unintended candidate (made worse by
11392 // subsuming constraints), treat this as 'no viable candidate'.
11393 Best = end();
11394 return OR_No_Viable_Function;
11395 }
11396 }
11397
11398 // If we didn't find any viable functions, abort.
11399 if (Best == end())
11400 return OR_No_Viable_Function;
11401
11402 llvm::SmallVector<OverloadCandidate *, 4> PendingBest;
11403 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
11404 PendingBest.push_back(&*Best);
11405 Best->Best = true;
11406
11407 // Make sure that this function is better than every other viable
11408 // function. If not, we have an ambiguity.
11409 while (!PendingBest.empty()) {
11410 auto *Curr = PendingBest.pop_back_val();
11411 for (auto *Cand : Candidates) {
11412 if (Cand->Viable && !Cand->Best &&
11413 !isBetterOverloadCandidate(S, *Curr, *Cand, Loc, Kind)) {
11414 PendingBest.push_back(Cand);
11415 Cand->Best = true;
11416
11418 Curr->Function))
11419 EquivalentCands.push_back(Cand->Function);
11420 else
11421 Best = end();
11422 }
11423 }
11424 }
11425
11426 if (Best == end())
11427 return OR_Ambiguous;
11428
11429 OverloadingResult R = ResultForBestCandidate(Best);
11430
11431 if (!EquivalentCands.empty())
11433 EquivalentCands);
11434 return R;
11435}
11436
11437namespace {
11438
11439enum OverloadCandidateKind {
11440 oc_function,
11441 oc_method,
11442 oc_reversed_binary_operator,
11443 oc_constructor,
11444 oc_implicit_default_constructor,
11445 oc_implicit_copy_constructor,
11446 oc_implicit_move_constructor,
11447 oc_implicit_copy_assignment,
11448 oc_implicit_move_assignment,
11449 oc_implicit_equality_comparison,
11450 oc_inherited_constructor
11451};
11452
11453enum OverloadCandidateSelect {
11454 ocs_non_template,
11455 ocs_template,
11456 ocs_described_template,
11457};
11458
11459static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
11460ClassifyOverloadCandidate(Sema &S, const NamedDecl *Found,
11461 const FunctionDecl *Fn,
11463 std::string &Description) {
11464
11465 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
11466 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
11467 isTemplate = true;
11468 Description = S.getTemplateArgumentBindingsText(
11469 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
11470 }
11471
11472 OverloadCandidateSelect Select = [&]() {
11473 if (!Description.empty())
11474 return ocs_described_template;
11475 return isTemplate ? ocs_template : ocs_non_template;
11476 }();
11477
11478 OverloadCandidateKind Kind = [&]() {
11479 if (Fn->isImplicit() && Fn->getOverloadedOperator() == OO_EqualEqual)
11480 return oc_implicit_equality_comparison;
11481
11482 if (CRK & CRK_Reversed)
11483 return oc_reversed_binary_operator;
11484
11485 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
11486 if (!Ctor->isImplicit()) {
11488 return oc_inherited_constructor;
11489 else
11490 return oc_constructor;
11491 }
11492
11493 if (Ctor->isDefaultConstructor())
11494 return oc_implicit_default_constructor;
11495
11496 if (Ctor->isMoveConstructor())
11497 return oc_implicit_move_constructor;
11498
11499 assert(Ctor->isCopyConstructor() &&
11500 "unexpected sort of implicit constructor");
11501 return oc_implicit_copy_constructor;
11502 }
11503
11504 if (const auto *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
11505 // This actually gets spelled 'candidate function' for now, but
11506 // it doesn't hurt to split it out.
11507 if (!Meth->isImplicit())
11508 return oc_method;
11509
11510 if (Meth->isMoveAssignmentOperator())
11511 return oc_implicit_move_assignment;
11512
11513 if (Meth->isCopyAssignmentOperator())
11514 return oc_implicit_copy_assignment;
11515
11516 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
11517 return oc_method;
11518 }
11519
11520 return oc_function;
11521 }();
11522
11523 return std::make_pair(Kind, Select);
11524}
11525
11526void MaybeEmitInheritedConstructorNote(Sema &S, const Decl *FoundDecl) {
11527 // FIXME: It'd be nice to only emit a note once per using-decl per overload
11528 // set.
11529 if (const auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
11530 S.Diag(FoundDecl->getLocation(),
11531 diag::note_ovl_candidate_inherited_constructor)
11532 << Shadow->getNominatedBaseClass();
11533}
11534
11535} // end anonymous namespace
11536
11538 const FunctionDecl *FD) {
11539 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
11540 bool AlwaysTrue;
11541 if (EnableIf->getCond()->isValueDependent() ||
11542 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
11543 return false;
11544 if (!AlwaysTrue)
11545 return false;
11546 }
11547 return true;
11548}
11549
11550/// Returns true if we can take the address of the function.
11551///
11552/// \param Complain - If true, we'll emit a diagnostic
11553/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
11554/// we in overload resolution?
11555/// \param Loc - The location of the statement we're complaining about. Ignored
11556/// if we're not complaining, or if we're in overload resolution.
11558 bool Complain,
11559 bool InOverloadResolution,
11560 SourceLocation Loc) {
11561 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
11562 if (Complain) {
11563 if (InOverloadResolution)
11564 S.Diag(FD->getBeginLoc(),
11565 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
11566 else
11567 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
11568 }
11569 return false;
11570 }
11571
11572 if (FD->getTrailingRequiresClause()) {
11573 ConstraintSatisfaction Satisfaction;
11574 if (S.CheckFunctionConstraints(FD, Satisfaction, Loc))
11575 return false;
11576 if (!Satisfaction.IsSatisfied) {
11577 if (Complain) {
11578 if (InOverloadResolution) {
11579 SmallString<128> TemplateArgString;
11580 if (FunctionTemplateDecl *FunTmpl = FD->getPrimaryTemplate()) {
11581 TemplateArgString += " ";
11582 TemplateArgString += S.getTemplateArgumentBindingsText(
11583 FunTmpl->getTemplateParameters(),
11585 }
11586
11587 S.Diag(FD->getBeginLoc(),
11588 diag::note_ovl_candidate_unsatisfied_constraints)
11589 << TemplateArgString;
11590 } else
11591 S.Diag(Loc, diag::err_addrof_function_constraints_not_satisfied)
11592 << FD;
11593 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
11594 }
11595 return false;
11596 }
11597 }
11598
11599 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
11600 return P->hasAttr<PassObjectSizeAttr>();
11601 });
11602 if (I == FD->param_end())
11603 return true;
11604
11605 if (Complain) {
11606 // Add one to ParamNo because it's user-facing
11607 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
11608 if (InOverloadResolution)
11609 S.Diag(FD->getLocation(),
11610 diag::note_ovl_candidate_has_pass_object_size_params)
11611 << ParamNo;
11612 else
11613 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
11614 << FD << ParamNo;
11615 }
11616 return false;
11617}
11618
11620 const FunctionDecl *FD) {
11621 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
11622 /*InOverloadResolution=*/true,
11623 /*Loc=*/SourceLocation());
11624}
11625
11627 bool Complain,
11628 SourceLocation Loc) {
11629 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
11630 /*InOverloadResolution=*/false,
11631 Loc);
11632}
11633
11634// Don't print candidates other than the one that matches the calling
11635// convention of the call operator, since that is guaranteed to exist.
11637 const auto *ConvD = dyn_cast<CXXConversionDecl>(Fn);
11638
11639 if (!ConvD)
11640 return false;
11641 const auto *RD = cast<CXXRecordDecl>(Fn->getParent());
11642 if (!RD->isLambda())
11643 return false;
11644
11645 CXXMethodDecl *CallOp = RD->getLambdaCallOperator();
11646 CallingConv CallOpCC =
11647 CallOp->getType()->castAs<FunctionType>()->getCallConv();
11648 QualType ConvRTy = ConvD->getType()->castAs<FunctionType>()->getReturnType();
11649 CallingConv ConvToCC =
11650 ConvRTy->getPointeeType()->castAs<FunctionType>()->getCallConv();
11651
11652 return ConvToCC != CallOpCC;
11653}
11654
11655// Notes the location of an overload candidate.
11657 OverloadCandidateRewriteKind RewriteKind,
11658 QualType DestType, bool TakingAddress) {
11659 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
11660 return;
11661 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
11662 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
11663 return;
11664 if (Fn->isMultiVersion() && Fn->hasAttr<TargetVersionAttr>() &&
11665 !Fn->getAttr<TargetVersionAttr>()->isDefaultVersion())
11666 return;
11668 return;
11669
11670 std::string FnDesc;
11671 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
11672 ClassifyOverloadCandidate(*this, Found, Fn, RewriteKind, FnDesc);
11673 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
11674 << (unsigned)KSPair.first << (unsigned)KSPair.second
11675 << Fn << FnDesc;
11676
11677 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
11678 Diag(Fn->getLocation(), PD);
11679 MaybeEmitInheritedConstructorNote(*this, Found);
11680}
11681
11682static void
11684 // Perhaps the ambiguity was caused by two atomic constraints that are
11685 // 'identical' but not equivalent:
11686 //
11687 // void foo() requires (sizeof(T) > 4) { } // #1
11688 // void foo() requires (sizeof(T) > 4) && T::value { } // #2
11689 //
11690 // The 'sizeof(T) > 4' constraints are seemingly equivalent and should cause
11691 // #2 to subsume #1, but these constraint are not considered equivalent
11692 // according to the subsumption rules because they are not the same
11693 // source-level construct. This behavior is quite confusing and we should try
11694 // to help the user figure out what happened.
11695
11696 SmallVector<AssociatedConstraint, 3> FirstAC, SecondAC;
11697 FunctionDecl *FirstCand = nullptr, *SecondCand = nullptr;
11698 for (auto I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11699 if (!I->Function)
11700 continue;
11702 if (auto *Template = I->Function->getPrimaryTemplate())
11703 Template->getAssociatedConstraints(AC);
11704 else
11705 I->Function->getAssociatedConstraints(AC);
11706 if (AC.empty())
11707 continue;
11708 if (FirstCand == nullptr) {
11709 FirstCand = I->Function;
11710 FirstAC = AC;
11711 } else if (SecondCand == nullptr) {
11712 SecondCand = I->Function;
11713 SecondAC = AC;
11714 } else {
11715 // We have more than one pair of constrained functions - this check is
11716 // expensive and we'd rather not try to diagnose it.
11717 return;
11718 }
11719 }
11720 if (!SecondCand)
11721 return;
11722 // The diagnostic can only happen if there are associated constraints on
11723 // both sides (there needs to be some identical atomic constraint).
11724 if (S.MaybeEmitAmbiguousAtomicConstraintsDiagnostic(FirstCand, FirstAC,
11725 SecondCand, SecondAC))
11726 // Just show the user one diagnostic, they'll probably figure it out
11727 // from here.
11728 return;
11729}
11730
11731// Notes the location of all overload candidates designated through
11732// OverloadedExpr
11733void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
11734 bool TakingAddress) {
11735 assert(OverloadedExpr->getType() == Context.OverloadTy);
11736
11737 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
11738 OverloadExpr *OvlExpr = Ovl.Expression;
11739
11740 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11741 IEnd = OvlExpr->decls_end();
11742 I != IEnd; ++I) {
11743 if (FunctionTemplateDecl *FunTmpl =
11744 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
11745 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), CRK_None, DestType,
11746 TakingAddress);
11747 } else if (FunctionDecl *Fun
11748 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
11749 NoteOverloadCandidate(*I, Fun, CRK_None, DestType, TakingAddress);
11750 }
11751 }
11752}
11753
11754/// Diagnoses an ambiguous conversion. The partial diagnostic is the
11755/// "lead" diagnostic; it will be given two arguments, the source and
11756/// target types of the conversion.
11758 Sema &S,
11759 SourceLocation CaretLoc,
11760 const PartialDiagnostic &PDiag) const {
11761 S.Diag(CaretLoc, PDiag)
11762 << Ambiguous.getFromType() << Ambiguous.getToType();
11763 unsigned CandsShown = 0;
11765 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
11766 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow())
11767 break;
11768 ++CandsShown;
11769 S.NoteOverloadCandidate(I->first, I->second);
11770 }
11771 S.Diags.overloadCandidatesShown(CandsShown);
11772 if (I != E)
11773 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
11774}
11775
11777 unsigned I, bool TakingCandidateAddress) {
11778 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
11779 assert(Conv.isBad());
11780 assert(Cand->Function && "for now, candidate must be a function");
11781 FunctionDecl *Fn = Cand->Function;
11782
11783 // There's a conversion slot for the object argument if this is a
11784 // non-constructor method. Note that 'I' corresponds the
11785 // conversion-slot index.
11786 bool isObjectArgument = false;
11787 if (!TakingCandidateAddress && isa<CXXMethodDecl>(Fn) &&
11789 if (I == 0)
11790 isObjectArgument = true;
11791 else if (!Fn->hasCXXExplicitFunctionObjectParameter())
11792 I--;
11793 }
11794
11795 std::string FnDesc;
11796 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
11797 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, Cand->getRewriteKind(),
11798 FnDesc);
11799
11800 Expr *FromExpr = Conv.Bad.FromExpr;
11801 QualType FromTy = Conv.Bad.getFromType();
11802 QualType ToTy = Conv.Bad.getToType();
11803 SourceRange ToParamRange;
11804
11805 // FIXME: In presence of parameter packs we can't determine parameter range
11806 // reliably, as we don't have access to instantiation.
11807 bool HasParamPack =
11808 llvm::any_of(Fn->parameters().take_front(I), [](const ParmVarDecl *Parm) {
11809 return Parm->isParameterPack();
11810 });
11811 if (!isObjectArgument && !HasParamPack)
11812 ToParamRange = Fn->getParamDecl(I)->getSourceRange();
11813
11814 if (FromTy == S.Context.OverloadTy) {
11815 assert(FromExpr && "overload set argument came from implicit argument?");
11816 Expr *E = FromExpr->IgnoreParens();
11817 if (isa<UnaryOperator>(E))
11818 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
11819 DeclarationName Name = cast<OverloadExpr>(E)->getName();
11820
11821 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
11822 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11823 << ToParamRange << ToTy << Name << I + 1;
11824 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11825 return;
11826 }
11827
11828 // Do some hand-waving analysis to see if the non-viability is due
11829 // to a qualifier mismatch.
11830 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
11831 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
11832 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
11833 CToTy = RT->getPointeeType();
11834 else {
11835 // TODO: detect and diagnose the full richness of const mismatches.
11836 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
11837 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
11838 CFromTy = FromPT->getPointeeType();
11839 CToTy = ToPT->getPointeeType();
11840 }
11841 }
11842
11843 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
11844 !CToTy.isAtLeastAsQualifiedAs(CFromTy, S.getASTContext())) {
11845 Qualifiers FromQs = CFromTy.getQualifiers();
11846 Qualifiers ToQs = CToTy.getQualifiers();
11847
11848 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
11849 if (isObjectArgument)
11850 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace_this)
11851 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11852 << FnDesc << FromQs.getAddressSpace() << ToQs.getAddressSpace();
11853 else
11854 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
11855 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
11856 << FnDesc << ToParamRange << FromQs.getAddressSpace()
11857 << ToQs.getAddressSpace() << ToTy->isReferenceType() << I + 1;
11858 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11859 return;
11860 }
11861
11862 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11863 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
11864 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11865 << ToParamRange << FromTy << FromQs.getObjCLifetime()
11866 << ToQs.getObjCLifetime() << (unsigned)isObjectArgument << I + 1;
11867 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11868 return;
11869 }
11870
11871 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
11872 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
11873 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11874 << ToParamRange << FromTy << FromQs.getObjCGCAttr()
11875 << ToQs.getObjCGCAttr() << (unsigned)isObjectArgument << I + 1;
11876 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11877 return;
11878 }
11879
11880 if (!FromQs.getPointerAuth().isEquivalent(ToQs.getPointerAuth())) {
11881 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ptrauth)
11882 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11883 << FromTy << !!FromQs.getPointerAuth()
11884 << FromQs.getPointerAuth().getAsString() << !!ToQs.getPointerAuth()
11885 << ToQs.getPointerAuth().getAsString() << I + 1
11886 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
11887 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11888 return;
11889 }
11890
11891 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
11892 assert(CVR && "expected qualifiers mismatch");
11893
11894 if (isObjectArgument) {
11895 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
11896 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11897 << FromTy << (CVR - 1);
11898 } else {
11899 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
11900 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11901 << ToParamRange << FromTy << (CVR - 1) << I + 1;
11902 }
11903 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11904 return;
11905 }
11906
11909 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_value_category)
11910 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11911 << (unsigned)isObjectArgument << I + 1
11913 << ToParamRange;
11914 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11915 return;
11916 }
11917
11918 // Special diagnostic for failure to convert an initializer list, since
11919 // telling the user that it has type void is not useful.
11920 if (FromExpr && isa<InitListExpr>(FromExpr)) {
11921 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
11922 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11923 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11926 ? 2
11927 : 0);
11928 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11929 return;
11930 }
11931
11932 // Diagnose references or pointers to incomplete types differently,
11933 // since it's far from impossible that the incompleteness triggered
11934 // the failure.
11935 QualType TempFromTy = FromTy.getNonReferenceType();
11936 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
11937 TempFromTy = PTy->getPointeeType();
11938 if (TempFromTy->isIncompleteType()) {
11939 // Emit the generic diagnostic and, optionally, add the hints to it.
11940 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
11941 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11942 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
11943 << (unsigned)(Cand->Fix.Kind);
11944
11945 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11946 return;
11947 }
11948
11949 // Diagnose base -> derived pointer conversions.
11950 unsigned BaseToDerivedConversion = 0;
11951 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
11952 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
11953 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11954 FromPtrTy->getPointeeType(), S.getASTContext()) &&
11955 !FromPtrTy->getPointeeType()->isIncompleteType() &&
11956 !ToPtrTy->getPointeeType()->isIncompleteType() &&
11957 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
11958 FromPtrTy->getPointeeType()))
11959 BaseToDerivedConversion = 1;
11960 }
11961 } else if (const ObjCObjectPointerType *FromPtrTy
11962 = FromTy->getAs<ObjCObjectPointerType>()) {
11963 if (const ObjCObjectPointerType *ToPtrTy
11964 = ToTy->getAs<ObjCObjectPointerType>())
11965 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
11966 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
11967 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
11968 FromPtrTy->getPointeeType(), S.getASTContext()) &&
11969 FromIface->isSuperClassOf(ToIface))
11970 BaseToDerivedConversion = 2;
11971 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
11972 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy,
11973 S.getASTContext()) &&
11974 !FromTy->isIncompleteType() &&
11975 !ToRefTy->getPointeeType()->isIncompleteType() &&
11976 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
11977 BaseToDerivedConversion = 3;
11978 }
11979 }
11980
11981 if (BaseToDerivedConversion) {
11982 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
11983 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11984 << ToParamRange << (BaseToDerivedConversion - 1) << FromTy << ToTy
11985 << I + 1;
11986 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
11987 return;
11988 }
11989
11990 if (isa<ObjCObjectPointerType>(CFromTy) &&
11991 isa<PointerType>(CToTy)) {
11992 Qualifiers FromQs = CFromTy.getQualifiers();
11993 Qualifiers ToQs = CToTy.getQualifiers();
11994 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
11995 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
11996 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
11997 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument
11998 << I + 1;
11999 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12000 return;
12001 }
12002 }
12003
12004 if (TakingCandidateAddress && !checkAddressOfCandidateIsAvailable(S, Fn))
12005 return;
12006
12007 // Emit the generic diagnostic and, optionally, add the hints to it.
12008 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
12009 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12010 << ToParamRange << FromTy << ToTy << (unsigned)isObjectArgument << I + 1
12011 << (unsigned)(Cand->Fix.Kind);
12012
12013 // Check that location of Fn is not in system header.
12014 if (!S.SourceMgr.isInSystemHeader(Fn->getLocation())) {
12015 // If we can fix the conversion, suggest the FixIts.
12016 for (const FixItHint &HI : Cand->Fix.Hints)
12017 FDiag << HI;
12018 }
12019
12020 S.Diag(Fn->getLocation(), FDiag);
12021
12022 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12023}
12024
12025/// Additional arity mismatch diagnosis specific to a function overload
12026/// candidates. This is not covered by the more general DiagnoseArityMismatch()
12027/// over a candidate in any candidate set.
12029 unsigned NumArgs, bool IsAddressOf = false) {
12030 assert(Cand->Function && "Candidate is required to be a function.");
12031 FunctionDecl *Fn = Cand->Function;
12032 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12033 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12034
12035 // With invalid overloaded operators, it's possible that we think we
12036 // have an arity mismatch when in fact it looks like we have the
12037 // right number of arguments, because only overloaded operators have
12038 // the weird behavior of overloading member and non-member functions.
12039 // Just don't report anything.
12040 if (Fn->isInvalidDecl() &&
12041 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
12042 return true;
12043
12044 if (NumArgs < MinParams) {
12045 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
12047 Cand->DeductionFailure.getResult() ==
12049 } else {
12050 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
12052 Cand->DeductionFailure.getResult() ==
12054 }
12055
12056 return false;
12057}
12058
12059/// General arity mismatch diagnosis over a candidate in a candidate set.
12061 unsigned NumFormalArgs,
12062 bool IsAddressOf = false) {
12063 assert(isa<FunctionDecl>(D) &&
12064 "The templated declaration should at least be a function"
12065 " when diagnosing bad template argument deduction due to too many"
12066 " or too few arguments");
12067
12069
12070 // TODO: treat calls to a missing default constructor as a special case
12071 const auto *FnTy = Fn->getType()->castAs<FunctionProtoType>();
12072 unsigned MinParams = Fn->getMinRequiredExplicitArguments() +
12073 ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12074
12075 // at least / at most / exactly
12076 bool HasExplicitObjectParam =
12077 !IsAddressOf && Fn->hasCXXExplicitFunctionObjectParameter();
12078
12079 unsigned ParamCount =
12080 Fn->getNumNonObjectParams() + ((IsAddressOf && !Fn->isStatic()) ? 1 : 0);
12081 unsigned mode, modeCount;
12082
12083 if (NumFormalArgs < MinParams) {
12084 if (MinParams != ParamCount || FnTy->isVariadic() ||
12085 FnTy->isTemplateVariadic())
12086 mode = 0; // "at least"
12087 else
12088 mode = 2; // "exactly"
12089 modeCount = MinParams;
12090 } else {
12091 if (MinParams != ParamCount)
12092 mode = 1; // "at most"
12093 else
12094 mode = 2; // "exactly"
12095 modeCount = ParamCount;
12096 }
12097
12098 std::string Description;
12099 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12100 ClassifyOverloadCandidate(S, Found, Fn, CRK_None, Description);
12101
12102 if (modeCount == 1 && !IsAddressOf &&
12103 Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0)->getDeclName())
12104 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
12105 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12106 << Description << mode
12107 << Fn->getParamDecl(HasExplicitObjectParam ? 1 : 0) << NumFormalArgs
12108 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12109 else
12110 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
12111 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
12112 << Description << mode << modeCount << NumFormalArgs
12113 << HasExplicitObjectParam << Fn->getParametersSourceRange();
12114
12115 MaybeEmitInheritedConstructorNote(S, Found);
12116}
12117
12118/// Arity mismatch diagnosis specific to a function overload candidate.
12120 unsigned NumFormalArgs) {
12121 assert(Cand->Function && "Candidate must be a function");
12122 FunctionDecl *Fn = Cand->Function;
12123 if (!CheckArityMismatch(S, Cand, NumFormalArgs, Cand->TookAddressOfOverload))
12124 DiagnoseArityMismatch(S, Cand->FoundDecl, Fn, NumFormalArgs,
12125 Cand->TookAddressOfOverload);
12126}
12127
12129 if (TemplateDecl *TD = Templated->getDescribedTemplate())
12130 return TD;
12131 llvm_unreachable("Unsupported: Getting the described template declaration"
12132 " for bad deduction diagnosis");
12133}
12134
12135/// Diagnose a failed template-argument deduction.
12136static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
12137 DeductionFailureInfo &DeductionFailure,
12138 unsigned NumArgs,
12139 bool TakingCandidateAddress) {
12140 TemplateParameter Param = DeductionFailure.getTemplateParameter();
12141 NamedDecl *ParamD;
12142 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
12143 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
12144 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
12145 switch (DeductionFailure.getResult()) {
12147 llvm_unreachable(
12148 "TemplateDeductionResult::Success while diagnosing bad deduction");
12150 llvm_unreachable("TemplateDeductionResult::NonDependentConversionFailure "
12151 "while diagnosing bad deduction");
12154 return;
12155
12157 assert(ParamD && "no parameter found for incomplete deduction result");
12158 S.Diag(Templated->getLocation(),
12159 diag::note_ovl_candidate_incomplete_deduction)
12160 << ParamD->getDeclName();
12161 MaybeEmitInheritedConstructorNote(S, Found);
12162 return;
12163 }
12164
12166 assert(ParamD && "no parameter found for incomplete deduction result");
12167 S.Diag(Templated->getLocation(),
12168 diag::note_ovl_candidate_incomplete_deduction_pack)
12169 << ParamD->getDeclName()
12170 << (DeductionFailure.getFirstArg()->pack_size() + 1)
12171 << *DeductionFailure.getFirstArg();
12172 MaybeEmitInheritedConstructorNote(S, Found);
12173 return;
12174 }
12175
12177 assert(ParamD && "no parameter found for bad qualifiers deduction result");
12179
12180 QualType Param = DeductionFailure.getFirstArg()->getAsType();
12181
12182 // Param will have been canonicalized, but it should just be a
12183 // qualified version of ParamD, so move the qualifiers to that.
12185 Qs.strip(Param);
12186 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
12187 assert(S.Context.hasSameType(Param, NonCanonParam));
12188
12189 // Arg has also been canonicalized, but there's nothing we can do
12190 // about that. It also doesn't matter as much, because it won't
12191 // have any template parameters in it (because deduction isn't
12192 // done on dependent types).
12193 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
12194
12195 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
12196 << ParamD->getDeclName() << Arg << NonCanonParam;
12197 MaybeEmitInheritedConstructorNote(S, Found);
12198 return;
12199 }
12200
12202 assert(ParamD && "no parameter found for inconsistent deduction result");
12203 int which = 0;
12204 if (isa<TemplateTypeParmDecl>(ParamD))
12205 which = 0;
12206 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
12207 // Deduction might have failed because we deduced arguments of two
12208 // different types for a non-type template parameter.
12209 // FIXME: Use a different TDK value for this.
12210 QualType T1 =
12211 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
12212 QualType T2 =
12213 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
12214 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
12215 S.Diag(Templated->getLocation(),
12216 diag::note_ovl_candidate_inconsistent_deduction_types)
12217 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
12218 << *DeductionFailure.getSecondArg() << T2;
12219 MaybeEmitInheritedConstructorNote(S, Found);
12220 return;
12221 }
12222
12223 which = 1;
12224 } else {
12225 which = 2;
12226 }
12227
12228 // Tweak the diagnostic if the problem is that we deduced packs of
12229 // different arities. We'll print the actual packs anyway in case that
12230 // includes additional useful information.
12231 if (DeductionFailure.getFirstArg()->getKind() == TemplateArgument::Pack &&
12232 DeductionFailure.getSecondArg()->getKind() == TemplateArgument::Pack &&
12233 DeductionFailure.getFirstArg()->pack_size() !=
12234 DeductionFailure.getSecondArg()->pack_size()) {
12235 which = 3;
12236 }
12237
12238 S.Diag(Templated->getLocation(),
12239 diag::note_ovl_candidate_inconsistent_deduction)
12240 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
12241 << *DeductionFailure.getSecondArg();
12242 MaybeEmitInheritedConstructorNote(S, Found);
12243 return;
12244 }
12245
12247 assert(ParamD && "no parameter found for invalid explicit arguments");
12248 if (ParamD->getDeclName())
12249 S.Diag(Templated->getLocation(),
12250 diag::note_ovl_candidate_explicit_arg_mismatch_named)
12251 << ParamD->getDeclName();
12252 else {
12253 int index = 0;
12254 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
12255 index = TTP->getIndex();
12256 else if (NonTypeTemplateParmDecl *NTTP
12257 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
12258 index = NTTP->getIndex();
12259 else
12260 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
12261 S.Diag(Templated->getLocation(),
12262 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
12263 << (index + 1);
12264 }
12265 MaybeEmitInheritedConstructorNote(S, Found);
12266 return;
12267
12269 // Format the template argument list into the argument string.
12270 SmallString<128> TemplateArgString;
12271 TemplateArgumentList *Args = DeductionFailure.getTemplateArgumentList();
12272 TemplateArgString = " ";
12273 TemplateArgString += S.getTemplateArgumentBindingsText(
12274 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12275 if (TemplateArgString.size() == 1)
12276 TemplateArgString.clear();
12277 S.Diag(Templated->getLocation(),
12278 diag::note_ovl_candidate_unsatisfied_constraints)
12279 << TemplateArgString;
12280
12282 static_cast<CNSInfo*>(DeductionFailure.Data)->Satisfaction);
12283 return;
12284 }
12287 DiagnoseArityMismatch(S, Found, Templated, NumArgs, TakingCandidateAddress);
12288 return;
12289
12291 S.Diag(Templated->getLocation(),
12292 diag::note_ovl_candidate_instantiation_depth);
12293 MaybeEmitInheritedConstructorNote(S, Found);
12294 return;
12295
12297 // Format the template argument list into the argument string.
12298 SmallString<128> TemplateArgString;
12299 if (TemplateArgumentList *Args =
12300 DeductionFailure.getTemplateArgumentList()) {
12301 TemplateArgString = " ";
12302 TemplateArgString += S.getTemplateArgumentBindingsText(
12303 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12304 if (TemplateArgString.size() == 1)
12305 TemplateArgString.clear();
12306 }
12307
12308 // If this candidate was disabled by enable_if, say so.
12309 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
12310 if (PDiag && PDiag->second.getDiagID() ==
12311 diag::err_typename_nested_not_found_enable_if) {
12312 // FIXME: Use the source range of the condition, and the fully-qualified
12313 // name of the enable_if template. These are both present in PDiag.
12314 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
12315 << "'enable_if'" << TemplateArgString;
12316 return;
12317 }
12318
12319 // We found a specific requirement that disabled the enable_if.
12320 if (PDiag && PDiag->second.getDiagID() ==
12321 diag::err_typename_nested_not_found_requirement) {
12322 S.Diag(Templated->getLocation(),
12323 diag::note_ovl_candidate_disabled_by_requirement)
12324 << PDiag->second.getStringArg(0) << TemplateArgString;
12325 return;
12326 }
12327
12328 // Format the SFINAE diagnostic into the argument string.
12329 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
12330 // formatted message in another diagnostic.
12331 SmallString<128> SFINAEArgString;
12332 SourceRange R;
12333 if (PDiag) {
12334 SFINAEArgString = ": ";
12335 R = SourceRange(PDiag->first, PDiag->first);
12336 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
12337 }
12338
12339 S.Diag(Templated->getLocation(),
12340 diag::note_ovl_candidate_substitution_failure)
12341 << TemplateArgString << SFINAEArgString << R;
12342 MaybeEmitInheritedConstructorNote(S, Found);
12343 return;
12344 }
12345
12348 // Format the template argument list into the argument string.
12349 SmallString<128> TemplateArgString;
12350 if (TemplateArgumentList *Args =
12351 DeductionFailure.getTemplateArgumentList()) {
12352 TemplateArgString = " ";
12353 TemplateArgString += S.getTemplateArgumentBindingsText(
12354 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
12355 if (TemplateArgString.size() == 1)
12356 TemplateArgString.clear();
12357 }
12358
12359 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
12360 << (*DeductionFailure.getCallArgIndex() + 1)
12361 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
12362 << TemplateArgString
12363 << (DeductionFailure.getResult() ==
12365 break;
12366 }
12367
12369 // FIXME: Provide a source location to indicate what we couldn't match.
12370 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
12371 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
12372 if (FirstTA.getKind() == TemplateArgument::Template &&
12373 SecondTA.getKind() == TemplateArgument::Template) {
12374 TemplateName FirstTN = FirstTA.getAsTemplate();
12375 TemplateName SecondTN = SecondTA.getAsTemplate();
12376 if (FirstTN.getKind() == TemplateName::Template &&
12377 SecondTN.getKind() == TemplateName::Template) {
12378 if (FirstTN.getAsTemplateDecl()->getName() ==
12379 SecondTN.getAsTemplateDecl()->getName()) {
12380 // FIXME: This fixes a bad diagnostic where both templates are named
12381 // the same. This particular case is a bit difficult since:
12382 // 1) It is passed as a string to the diagnostic printer.
12383 // 2) The diagnostic printer only attempts to find a better
12384 // name for types, not decls.
12385 // Ideally, this should folded into the diagnostic printer.
12386 S.Diag(Templated->getLocation(),
12387 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
12388 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
12389 return;
12390 }
12391 }
12392 }
12393
12394 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
12396 return;
12397
12398 // FIXME: For generic lambda parameters, check if the function is a lambda
12399 // call operator, and if so, emit a prettier and more informative
12400 // diagnostic that mentions 'auto' and lambda in addition to
12401 // (or instead of?) the canonical template type parameters.
12402 S.Diag(Templated->getLocation(),
12403 diag::note_ovl_candidate_non_deduced_mismatch)
12404 << FirstTA << SecondTA;
12405 return;
12406 }
12407 // TODO: diagnose these individually, then kill off
12408 // note_ovl_candidate_bad_deduction, which is uselessly vague.
12410 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
12411 MaybeEmitInheritedConstructorNote(S, Found);
12412 return;
12414 S.Diag(Templated->getLocation(),
12415 diag::note_cuda_ovl_candidate_target_mismatch);
12416 return;
12417 }
12418}
12419
12420/// Diagnose a failed template-argument deduction, for function calls.
12422 unsigned NumArgs,
12423 bool TakingCandidateAddress) {
12424 assert(Cand->Function && "Candidate must be a function");
12425 FunctionDecl *Fn = Cand->Function;
12429 if (CheckArityMismatch(S, Cand, NumArgs))
12430 return;
12431 }
12432 DiagnoseBadDeduction(S, Cand->FoundDecl, Fn, // pattern
12433 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
12434}
12435
12436/// CUDA: diagnose an invalid call across targets.
12438 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
12439 assert(Cand->Function && "Candidate must be a Function.");
12440 FunctionDecl *Callee = Cand->Function;
12441
12442 CUDAFunctionTarget CallerTarget = S.CUDA().IdentifyTarget(Caller),
12443 CalleeTarget = S.CUDA().IdentifyTarget(Callee);
12444
12445 std::string FnDesc;
12446 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12447 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee,
12448 Cand->getRewriteKind(), FnDesc);
12449
12450 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
12451 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12452 << FnDesc /* Ignored */
12453 << CalleeTarget << CallerTarget;
12454
12455 // This could be an implicit constructor for which we could not infer the
12456 // target due to a collsion. Diagnose that case.
12457 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
12458 if (Meth != nullptr && Meth->isImplicit()) {
12459 CXXRecordDecl *ParentClass = Meth->getParent();
12461
12462 switch (FnKindPair.first) {
12463 default:
12464 return;
12465 case oc_implicit_default_constructor:
12467 break;
12468 case oc_implicit_copy_constructor:
12470 break;
12471 case oc_implicit_move_constructor:
12473 break;
12474 case oc_implicit_copy_assignment:
12476 break;
12477 case oc_implicit_move_assignment:
12479 break;
12480 };
12481
12482 bool ConstRHS = false;
12483 if (Meth->getNumParams()) {
12484 if (const ReferenceType *RT =
12485 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
12486 ConstRHS = RT->getPointeeType().isConstQualified();
12487 }
12488 }
12489
12490 S.CUDA().inferTargetForImplicitSpecialMember(ParentClass, CSM, Meth,
12491 /* ConstRHS */ ConstRHS,
12492 /* Diagnose */ true);
12493 }
12494}
12495
12497 assert(Cand->Function && "Candidate must be a function");
12498 FunctionDecl *Callee = Cand->Function;
12499 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
12500
12501 S.Diag(Callee->getLocation(),
12502 diag::note_ovl_candidate_disabled_by_function_cond_attr)
12503 << Attr->getCond()->getSourceRange() << Attr->getMessage();
12504}
12505
12507 assert(Cand->Function && "Candidate must be a function");
12508 FunctionDecl *Fn = Cand->Function;
12510 assert(ES.isExplicit() && "not an explicit candidate");
12511
12512 unsigned Kind;
12513 switch (Fn->getDeclKind()) {
12514 case Decl::Kind::CXXConstructor:
12515 Kind = 0;
12516 break;
12517 case Decl::Kind::CXXConversion:
12518 Kind = 1;
12519 break;
12520 case Decl::Kind::CXXDeductionGuide:
12521 Kind = Fn->isImplicit() ? 0 : 2;
12522 break;
12523 default:
12524 llvm_unreachable("invalid Decl");
12525 }
12526
12527 // Note the location of the first (in-class) declaration; a redeclaration
12528 // (particularly an out-of-class definition) will typically lack the
12529 // 'explicit' specifier.
12530 // FIXME: This is probably a good thing to do for all 'candidate' notes.
12531 FunctionDecl *First = Fn->getFirstDecl();
12532 if (FunctionDecl *Pattern = First->getTemplateInstantiationPattern())
12533 First = Pattern->getFirstDecl();
12534
12535 S.Diag(First->getLocation(),
12536 diag::note_ovl_candidate_explicit)
12537 << Kind << (ES.getExpr() ? 1 : 0)
12538 << (ES.getExpr() ? ES.getExpr()->getSourceRange() : SourceRange());
12539}
12540
12542 auto *DG = dyn_cast<CXXDeductionGuideDecl>(Fn);
12543 if (!DG)
12544 return;
12545 TemplateDecl *OriginTemplate =
12547 // We want to always print synthesized deduction guides for type aliases.
12548 // They would retain the explicit bit of the corresponding constructor.
12549 if (!(DG->isImplicit() || (OriginTemplate && OriginTemplate->isTypeAlias())))
12550 return;
12551 std::string FunctionProto;
12552 llvm::raw_string_ostream OS(FunctionProto);
12553 FunctionTemplateDecl *Template = DG->getDescribedFunctionTemplate();
12554 if (!Template) {
12555 // This also could be an instantiation. Find out the primary template.
12556 FunctionDecl *Pattern =
12557 DG->getTemplateInstantiationPattern(/*ForDefinition=*/false);
12558 if (!Pattern) {
12559 // The implicit deduction guide is built on an explicit non-template
12560 // deduction guide. Currently, this might be the case only for type
12561 // aliases.
12562 // FIXME: Add a test once https://github.com/llvm/llvm-project/pull/96686
12563 // gets merged.
12564 assert(OriginTemplate->isTypeAlias() &&
12565 "Non-template implicit deduction guides are only possible for "
12566 "type aliases");
12567 DG->print(OS);
12568 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12569 << FunctionProto;
12570 return;
12571 }
12573 assert(Template && "Cannot find the associated function template of "
12574 "CXXDeductionGuideDecl?");
12575 }
12576 Template->print(OS);
12577 S.Diag(DG->getLocation(), diag::note_implicit_deduction_guide)
12578 << FunctionProto;
12579}
12580
12581/// Generates a 'note' diagnostic for an overload candidate. We've
12582/// already generated a primary error at the call site.
12583///
12584/// It really does need to be a single diagnostic with its caret
12585/// pointed at the candidate declaration. Yes, this creates some
12586/// major challenges of technical writing. Yes, this makes pointing
12587/// out problems with specific arguments quite awkward. It's still
12588/// better than generating twenty screens of text for every failed
12589/// overload.
12590///
12591/// It would be great to be able to express per-candidate problems
12592/// more richly for those diagnostic clients that cared, but we'd
12593/// still have to be just as careful with the default diagnostics.
12594/// \param CtorDestAS Addr space of object being constructed (for ctor
12595/// candidates only).
12597 unsigned NumArgs,
12598 bool TakingCandidateAddress,
12599 LangAS CtorDestAS = LangAS::Default) {
12600 assert(Cand->Function && "Candidate must be a function");
12601 FunctionDecl *Fn = Cand->Function;
12603 return;
12604
12605 // There is no physical candidate declaration to point to for OpenCL builtins.
12606 // Except for failed conversions, the notes are identical for each candidate,
12607 // so do not generate such notes.
12608 if (S.getLangOpts().OpenCL && Fn->isImplicit() &&
12610 return;
12611
12612 // Skip implicit member functions when trying to resolve
12613 // the address of a an overload set for a function pointer.
12614 if (Cand->TookAddressOfOverload &&
12615 !Fn->hasCXXExplicitFunctionObjectParameter() && !Fn->isStatic())
12616 return;
12617
12618 // Note deleted candidates, but only if they're viable.
12619 if (Cand->Viable) {
12620 if (Fn->isDeleted()) {
12621 std::string FnDesc;
12622 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12623 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12624 Cand->getRewriteKind(), FnDesc);
12625
12626 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
12627 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
12628 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
12629 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12630 return;
12631 }
12632
12633 // We don't really have anything else to say about viable candidates.
12634 S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12635 return;
12636 }
12637
12638 // If this is a synthesized deduction guide we're deducing against, add a note
12639 // for it. These deduction guides are not explicitly spelled in the source
12640 // code, so simply printing a deduction failure note mentioning synthesized
12641 // template parameters or pointing to the header of the surrounding RecordDecl
12642 // would be confusing.
12643 //
12644 // We prefer adding such notes at the end of the deduction failure because
12645 // duplicate code snippets appearing in the diagnostic would likely become
12646 // noisy.
12647 auto _ = llvm::make_scope_exit([&] { NoteImplicitDeductionGuide(S, Fn); });
12648
12649 switch (Cand->FailureKind) {
12652 return DiagnoseArityMismatch(S, Cand, NumArgs);
12653
12655 return DiagnoseBadDeduction(S, Cand, NumArgs,
12656 TakingCandidateAddress);
12657
12659 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
12660 << (Fn->getPrimaryTemplate() ? 1 : 0);
12661 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12662 return;
12663 }
12664
12666 Qualifiers QualsForPrinting;
12667 QualsForPrinting.setAddressSpace(CtorDestAS);
12668 S.Diag(Fn->getLocation(),
12669 diag::note_ovl_candidate_illegal_constructor_adrspace_mismatch)
12670 << QualsForPrinting;
12671 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12672 return;
12673 }
12674
12678 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12679
12681 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
12682 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
12683 if (Cand->Conversions[I].isInitialized() && Cand->Conversions[I].isBad())
12684 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
12685
12686 // FIXME: this currently happens when we're called from SemaInit
12687 // when user-conversion overload fails. Figure out how to handle
12688 // those conditions and diagnose them well.
12689 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn, Cand->getRewriteKind());
12690 }
12691
12693 return DiagnoseBadTarget(S, Cand);
12694
12695 case ovl_fail_enable_if:
12696 return DiagnoseFailedEnableIfAttr(S, Cand);
12697
12698 case ovl_fail_explicit:
12699 return DiagnoseFailedExplicitSpec(S, Cand);
12700
12702 // It's generally not interesting to note copy/move constructors here.
12703 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
12704 return;
12705 S.Diag(Fn->getLocation(),
12706 diag::note_ovl_candidate_inherited_constructor_slice)
12707 << (Fn->getPrimaryTemplate() ? 1 : 0)
12708 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
12709 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
12710 return;
12711
12713 bool Available = checkAddressOfCandidateIsAvailable(S, Fn);
12714 (void)Available;
12715 assert(!Available);
12716 break;
12717 }
12719 // Do nothing, these should simply be ignored.
12720 break;
12721
12723 std::string FnDesc;
12724 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
12725 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn,
12726 Cand->getRewriteKind(), FnDesc);
12727
12728 S.Diag(Fn->getLocation(),
12729 diag::note_ovl_candidate_constraints_not_satisfied)
12730 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
12731 << FnDesc /* Ignored */;
12732 ConstraintSatisfaction Satisfaction;
12733 if (S.CheckFunctionConstraints(Fn, Satisfaction))
12734 break;
12735 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12736 }
12737 }
12738}
12739
12742 return;
12743
12744 // Desugar the type of the surrogate down to a function type,
12745 // retaining as many typedefs as possible while still showing
12746 // the function type (and, therefore, its parameter types).
12747 QualType FnType = Cand->Surrogate->getConversionType();
12748 bool isLValueReference = false;
12749 bool isRValueReference = false;
12750 bool isPointer = false;
12751 if (const LValueReferenceType *FnTypeRef =
12752 FnType->getAs<LValueReferenceType>()) {
12753 FnType = FnTypeRef->getPointeeType();
12754 isLValueReference = true;
12755 } else if (const RValueReferenceType *FnTypeRef =
12756 FnType->getAs<RValueReferenceType>()) {
12757 FnType = FnTypeRef->getPointeeType();
12758 isRValueReference = true;
12759 }
12760 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
12761 FnType = FnTypePtr->getPointeeType();
12762 isPointer = true;
12763 }
12764 // Desugar down to a function type.
12765 FnType = QualType(FnType->getAs<FunctionType>(), 0);
12766 // Reconstruct the pointer/reference as appropriate.
12767 if (isPointer) FnType = S.Context.getPointerType(FnType);
12768 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
12769 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
12770
12771 if (!Cand->Viable &&
12773 S.Diag(Cand->Surrogate->getLocation(),
12774 diag::note_ovl_surrogate_constraints_not_satisfied)
12775 << Cand->Surrogate;
12776 ConstraintSatisfaction Satisfaction;
12777 if (S.CheckFunctionConstraints(Cand->Surrogate, Satisfaction))
12778 S.DiagnoseUnsatisfiedConstraint(Satisfaction);
12779 } else {
12780 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
12781 << FnType;
12782 }
12783}
12784
12785static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
12786 SourceLocation OpLoc,
12787 OverloadCandidate *Cand) {
12788 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
12789 std::string TypeStr("operator");
12790 TypeStr += Opc;
12791 TypeStr += "(";
12792 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
12793 if (Cand->Conversions.size() == 1) {
12794 TypeStr += ")";
12795 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12796 } else {
12797 TypeStr += ", ";
12798 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
12799 TypeStr += ")";
12800 S.Diag(OpLoc, diag::note_ovl_builtin_candidate) << TypeStr;
12801 }
12802}
12803
12805 OverloadCandidate *Cand) {
12806 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
12807 if (ICS.isBad()) break; // all meaningless after first invalid
12808 if (!ICS.isAmbiguous()) continue;
12809
12811 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
12812 }
12813}
12814
12816 if (Cand->Function)
12817 return Cand->Function->getLocation();
12818 if (Cand->IsSurrogate)
12819 return Cand->Surrogate->getLocation();
12820 return SourceLocation();
12821}
12822
12823static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
12824 switch (static_cast<TemplateDeductionResult>(DFI.Result)) {
12828 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
12829
12833 return 1;
12834
12837 return 2;
12838
12846 return 3;
12847
12849 return 4;
12850
12852 return 5;
12853
12856 return 6;
12857 }
12858 llvm_unreachable("Unhandled deduction result");
12859}
12860
12861namespace {
12862
12863struct CompareOverloadCandidatesForDisplay {
12864 Sema &S;
12865 SourceLocation Loc;
12866 size_t NumArgs;
12868
12869 CompareOverloadCandidatesForDisplay(
12870 Sema &S, SourceLocation Loc, size_t NArgs,
12872 : S(S), NumArgs(NArgs), CSK(CSK) {}
12873
12874 OverloadFailureKind EffectiveFailureKind(const OverloadCandidate *C) const {
12875 // If there are too many or too few arguments, that's the high-order bit we
12876 // want to sort by, even if the immediate failure kind was something else.
12877 if (C->FailureKind == ovl_fail_too_many_arguments ||
12878 C->FailureKind == ovl_fail_too_few_arguments)
12879 return static_cast<OverloadFailureKind>(C->FailureKind);
12880
12881 if (C->Function) {
12882 if (NumArgs > C->Function->getNumParams() && !C->Function->isVariadic())
12884 if (NumArgs < C->Function->getMinRequiredArguments())
12886 }
12887
12888 return static_cast<OverloadFailureKind>(C->FailureKind);
12889 }
12890
12891 bool operator()(const OverloadCandidate *L,
12892 const OverloadCandidate *R) {
12893 // Fast-path this check.
12894 if (L == R) return false;
12895
12896 // Order first by viability.
12897 if (L->Viable) {
12898 if (!R->Viable) return true;
12899
12900 if (int Ord = CompareConversions(*L, *R))
12901 return Ord < 0;
12902 // Use other tie breakers.
12903 } else if (R->Viable)
12904 return false;
12905
12906 assert(L->Viable == R->Viable);
12907
12908 // Criteria by which we can sort non-viable candidates:
12909 if (!L->Viable) {
12910 OverloadFailureKind LFailureKind = EffectiveFailureKind(L);
12911 OverloadFailureKind RFailureKind = EffectiveFailureKind(R);
12912
12913 // 1. Arity mismatches come after other candidates.
12914 if (LFailureKind == ovl_fail_too_many_arguments ||
12915 LFailureKind == ovl_fail_too_few_arguments) {
12916 if (RFailureKind == ovl_fail_too_many_arguments ||
12917 RFailureKind == ovl_fail_too_few_arguments) {
12918 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
12919 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
12920 if (LDist == RDist) {
12921 if (LFailureKind == RFailureKind)
12922 // Sort non-surrogates before surrogates.
12923 return !L->IsSurrogate && R->IsSurrogate;
12924 // Sort candidates requiring fewer parameters than there were
12925 // arguments given after candidates requiring more parameters
12926 // than there were arguments given.
12927 return LFailureKind == ovl_fail_too_many_arguments;
12928 }
12929 return LDist < RDist;
12930 }
12931 return false;
12932 }
12933 if (RFailureKind == ovl_fail_too_many_arguments ||
12934 RFailureKind == ovl_fail_too_few_arguments)
12935 return true;
12936
12937 // 2. Bad conversions come first and are ordered by the number
12938 // of bad conversions and quality of good conversions.
12939 if (LFailureKind == ovl_fail_bad_conversion) {
12940 if (RFailureKind != ovl_fail_bad_conversion)
12941 return true;
12942
12943 // The conversion that can be fixed with a smaller number of changes,
12944 // comes first.
12945 unsigned numLFixes = L->Fix.NumConversionsFixed;
12946 unsigned numRFixes = R->Fix.NumConversionsFixed;
12947 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
12948 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
12949 if (numLFixes != numRFixes) {
12950 return numLFixes < numRFixes;
12951 }
12952
12953 // If there's any ordering between the defined conversions...
12954 if (int Ord = CompareConversions(*L, *R))
12955 return Ord < 0;
12956 } else if (RFailureKind == ovl_fail_bad_conversion)
12957 return false;
12958
12959 if (LFailureKind == ovl_fail_bad_deduction) {
12960 if (RFailureKind != ovl_fail_bad_deduction)
12961 return true;
12962
12964 unsigned LRank = RankDeductionFailure(L->DeductionFailure);
12965 unsigned RRank = RankDeductionFailure(R->DeductionFailure);
12966 if (LRank != RRank)
12967 return LRank < RRank;
12968 }
12969 } else if (RFailureKind == ovl_fail_bad_deduction)
12970 return false;
12971
12972 // TODO: others?
12973 }
12974
12975 // Sort everything else by location.
12976 SourceLocation LLoc = GetLocationForCandidate(L);
12977 SourceLocation RLoc = GetLocationForCandidate(R);
12978
12979 // Put candidates without locations (e.g. builtins) at the end.
12980 if (LLoc.isValid() && RLoc.isValid())
12981 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
12982 if (LLoc.isValid() && !RLoc.isValid())
12983 return true;
12984 if (RLoc.isValid() && !LLoc.isValid())
12985 return false;
12986 assert(!LLoc.isValid() && !RLoc.isValid());
12987 // For builtins and other functions without locations, fallback to the order
12988 // in which they were added into the candidate set.
12989 return L < R;
12990 }
12991
12992private:
12993 struct ConversionSignals {
12994 unsigned KindRank = 0;
12996
12997 static ConversionSignals ForSequence(ImplicitConversionSequence &Seq) {
12998 ConversionSignals Sig;
12999 Sig.KindRank = Seq.getKindRank();
13000 if (Seq.isStandard())
13001 Sig.Rank = Seq.Standard.getRank();
13002 else if (Seq.isUserDefined())
13003 Sig.Rank = Seq.UserDefined.After.getRank();
13004 // We intend StaticObjectArgumentConversion to compare the same as
13005 // StandardConversion with ICR_ExactMatch rank.
13006 return Sig;
13007 }
13008
13009 static ConversionSignals ForObjectArgument() {
13010 // We intend StaticObjectArgumentConversion to compare the same as
13011 // StandardConversion with ICR_ExactMatch rank. Default give us that.
13012 return {};
13013 }
13014 };
13015
13016 // Returns -1 if conversions in L are considered better.
13017 // 0 if they are considered indistinguishable.
13018 // 1 if conversions in R are better.
13019 int CompareConversions(const OverloadCandidate &L,
13020 const OverloadCandidate &R) {
13021 // We cannot use `isBetterOverloadCandidate` because it is defined
13022 // according to the C++ standard and provides a partial order, but we need
13023 // a total order as this function is used in sort.
13024 assert(L.Conversions.size() == R.Conversions.size());
13025 for (unsigned I = 0, N = L.Conversions.size(); I != N; ++I) {
13026 auto LS = L.IgnoreObjectArgument && I == 0
13027 ? ConversionSignals::ForObjectArgument()
13028 : ConversionSignals::ForSequence(L.Conversions[I]);
13029 auto RS = R.IgnoreObjectArgument
13030 ? ConversionSignals::ForObjectArgument()
13031 : ConversionSignals::ForSequence(R.Conversions[I]);
13032 if (std::tie(LS.KindRank, LS.Rank) != std::tie(RS.KindRank, RS.Rank))
13033 return std::tie(LS.KindRank, LS.Rank) < std::tie(RS.KindRank, RS.Rank)
13034 ? -1
13035 : 1;
13036 }
13037 // FIXME: find a way to compare templates for being more or less
13038 // specialized that provides a strict weak ordering.
13039 return 0;
13040 }
13041};
13042}
13043
13044/// CompleteNonViableCandidate - Normally, overload resolution only
13045/// computes up to the first bad conversion. Produces the FixIt set if
13046/// possible.
13047static void
13049 ArrayRef<Expr *> Args,
13051 assert(!Cand->Viable);
13052
13053 // Don't do anything on failures other than bad conversion.
13055 return;
13056
13057 // We only want the FixIts if all the arguments can be corrected.
13058 bool Unfixable = false;
13059 // Use a implicit copy initialization to check conversion fixes.
13061
13062 // Attempt to fix the bad conversion.
13063 unsigned ConvCount = Cand->Conversions.size();
13064 for (unsigned ConvIdx =
13065 ((!Cand->TookAddressOfOverload && Cand->IgnoreObjectArgument) ? 1
13066 : 0);
13067 /**/; ++ConvIdx) {
13068 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
13069 if (Cand->Conversions[ConvIdx].isInitialized() &&
13070 Cand->Conversions[ConvIdx].isBad()) {
13071 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13072 break;
13073 }
13074 }
13075
13076 // FIXME: this should probably be preserved from the overload
13077 // operation somehow.
13078 bool SuppressUserConversions = false;
13079
13080 unsigned ConvIdx = 0;
13081 unsigned ArgIdx = 0;
13082 ArrayRef<QualType> ParamTypes;
13083 bool Reversed = Cand->isReversed();
13084
13085 if (Cand->IsSurrogate) {
13086 QualType ConvType
13088 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13089 ConvType = ConvPtrType->getPointeeType();
13090 ParamTypes = ConvType->castAs<FunctionProtoType>()->getParamTypes();
13091 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13092 ConvIdx = 1;
13093 } else if (Cand->Function) {
13094 ParamTypes =
13095 Cand->Function->getType()->castAs<FunctionProtoType>()->getParamTypes();
13096 if (isa<CXXMethodDecl>(Cand->Function) &&
13099 // Conversion 0 is 'this', which doesn't have a corresponding parameter.
13100 ConvIdx = 1;
13102 Cand->Function->getDeclName().getCXXOverloadedOperator() != OO_Call &&
13104 OO_Subscript)
13105 // Argument 0 is 'this', which doesn't have a corresponding parameter.
13106 ArgIdx = 1;
13107 }
13108 } else {
13109 // Builtin operator.
13110 assert(ConvCount <= 3);
13111 ParamTypes = Cand->BuiltinParamTypes;
13112 }
13113
13114 // Fill in the rest of the conversions.
13115 for (unsigned ParamIdx = Reversed ? ParamTypes.size() - 1 : 0;
13116 ConvIdx != ConvCount && ArgIdx < Args.size();
13117 ++ConvIdx, ++ArgIdx, ParamIdx += (Reversed ? -1 : 1)) {
13118 if (Cand->Conversions[ConvIdx].isInitialized()) {
13119 // We've already checked this conversion.
13120 } else if (ParamIdx < ParamTypes.size()) {
13121 if (ParamTypes[ParamIdx]->isDependentType())
13122 Cand->Conversions[ConvIdx].setAsIdentityConversion(
13123 Args[ArgIdx]->getType());
13124 else {
13125 Cand->Conversions[ConvIdx] =
13126 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ParamIdx],
13127 SuppressUserConversions,
13128 /*InOverloadResolution=*/true,
13129 /*AllowObjCWritebackConversion=*/
13130 S.getLangOpts().ObjCAutoRefCount);
13131 // Store the FixIt in the candidate if it exists.
13132 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
13133 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
13134 }
13135 } else
13136 Cand->Conversions[ConvIdx].setEllipsis();
13137 }
13138}
13139
13142 SourceLocation OpLoc,
13143 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13144
13146
13147 // Sort the candidates by viability and position. Sorting directly would
13148 // be prohibitive, so we make a set of pointers and sort those.
13150 if (OCD == OCD_AllCandidates) Cands.reserve(size());
13151 for (iterator Cand = Candidates.begin(), LastCand = Candidates.end();
13152 Cand != LastCand; ++Cand) {
13153 if (!Filter(*Cand))
13154 continue;
13155 switch (OCD) {
13156 case OCD_AllCandidates:
13157 if (!Cand->Viable) {
13158 if (!Cand->Function && !Cand->IsSurrogate) {
13159 // This a non-viable builtin candidate. We do not, in general,
13160 // want to list every possible builtin candidate.
13161 continue;
13162 }
13163 CompleteNonViableCandidate(S, Cand, Args, Kind);
13164 }
13165 break;
13166
13168 if (!Cand->Viable)
13169 continue;
13170 break;
13171
13173 if (!Cand->Best)
13174 continue;
13175 break;
13176 }
13177
13178 Cands.push_back(Cand);
13179 }
13180
13181 llvm::stable_sort(
13182 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
13183
13184 return Cands;
13185}
13186
13188 SourceLocation OpLoc) {
13189 bool DeferHint = false;
13190 if (S.getLangOpts().CUDA && S.getLangOpts().GPUDeferDiag) {
13191 // Defer diagnostic for CUDA/HIP if there are wrong-sided candidates or
13192 // host device candidates.
13193 auto WrongSidedCands =
13194 CompleteCandidates(S, OCD_AllCandidates, Args, OpLoc, [](auto &Cand) {
13195 return (Cand.Viable == false &&
13197 (Cand.Function &&
13198 Cand.Function->template hasAttr<CUDAHostAttr>() &&
13199 Cand.Function->template hasAttr<CUDADeviceAttr>());
13200 });
13201 DeferHint = !WrongSidedCands.empty();
13202 }
13203 return DeferHint;
13204}
13205
13206/// When overload resolution fails, prints diagnostic messages containing the
13207/// candidates in the candidate set.
13210 ArrayRef<Expr *> Args, StringRef Opc, SourceLocation OpLoc,
13211 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
13212
13213 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
13214
13215 S.Diag(PD.first, PD.second, shouldDeferDiags(S, Args, OpLoc));
13216
13217 // In WebAssembly we don't want to emit further diagnostics if a table is
13218 // passed as an argument to a function.
13219 bool NoteCands = true;
13220 for (const Expr *Arg : Args) {
13221 if (Arg->getType()->isWebAssemblyTableType())
13222 NoteCands = false;
13223 }
13224
13225 if (NoteCands)
13226 NoteCandidates(S, Args, Cands, Opc, OpLoc);
13227
13228 if (OCD == OCD_AmbiguousCandidates)
13230 {Candidates.begin(), Candidates.end()});
13231}
13232
13235 StringRef Opc, SourceLocation OpLoc) {
13236 bool ReportedAmbiguousConversions = false;
13237
13238 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13239 unsigned CandsShown = 0;
13240 auto I = Cands.begin(), E = Cands.end();
13241 for (; I != E; ++I) {
13242 OverloadCandidate *Cand = *I;
13243
13244 if (CandsShown >= S.Diags.getNumOverloadCandidatesToShow() &&
13245 ShowOverloads == Ovl_Best) {
13246 break;
13247 }
13248 ++CandsShown;
13249
13250 if (Cand->Function)
13251 NoteFunctionCandidate(S, Cand, Args.size(),
13252 Kind == CSK_AddressOfOverloadSet, DestAS);
13253 else if (Cand->IsSurrogate)
13254 NoteSurrogateCandidate(S, Cand);
13255 else {
13256 assert(Cand->Viable &&
13257 "Non-viable built-in candidates are not added to Cands.");
13258 // Generally we only see ambiguities including viable builtin
13259 // operators if overload resolution got screwed up by an
13260 // ambiguous user-defined conversion.
13261 //
13262 // FIXME: It's quite possible for different conversions to see
13263 // different ambiguities, though.
13264 if (!ReportedAmbiguousConversions) {
13265 NoteAmbiguousUserConversions(S, OpLoc, Cand);
13266 ReportedAmbiguousConversions = true;
13267 }
13268
13269 // If this is a viable builtin, print it.
13270 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
13271 }
13272 }
13273
13274 // Inform S.Diags that we've shown an overload set with N elements. This may
13275 // inform the future value of S.Diags.getNumOverloadCandidatesToShow().
13276 S.Diags.overloadCandidatesShown(CandsShown);
13277
13278 if (I != E)
13279 S.Diag(OpLoc, diag::note_ovl_too_many_candidates,
13280 shouldDeferDiags(S, Args, OpLoc))
13281 << int(E - I);
13282}
13283
13284static SourceLocation
13286 return Cand->Specialization ? Cand->Specialization->getLocation()
13287 : SourceLocation();
13288}
13289
13290namespace {
13291struct CompareTemplateSpecCandidatesForDisplay {
13292 Sema &S;
13293 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
13294
13295 bool operator()(const TemplateSpecCandidate *L,
13296 const TemplateSpecCandidate *R) {
13297 // Fast-path this check.
13298 if (L == R)
13299 return false;
13300
13301 // Assuming that both candidates are not matches...
13302
13303 // Sort by the ranking of deduction failures.
13307
13308 // Sort everything else by location.
13309 SourceLocation LLoc = GetLocationForCandidate(L);
13310 SourceLocation RLoc = GetLocationForCandidate(R);
13311
13312 // Put candidates without locations (e.g. builtins) at the end.
13313 if (LLoc.isInvalid())
13314 return false;
13315 if (RLoc.isInvalid())
13316 return true;
13317
13318 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
13319 }
13320};
13321}
13322
13323/// Diagnose a template argument deduction failure.
13324/// We are treating these failures as overload failures due to bad
13325/// deductions.
13327 bool ForTakingAddress) {
13329 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
13330}
13331
13332void TemplateSpecCandidateSet::destroyCandidates() {
13333 for (iterator i = begin(), e = end(); i != e; ++i) {
13334 i->DeductionFailure.Destroy();
13335 }
13336}
13337
13339 destroyCandidates();
13340 Candidates.clear();
13341}
13342
13343/// NoteCandidates - When no template specialization match is found, prints
13344/// diagnostic messages containing the non-matching specializations that form
13345/// the candidate set.
13346/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
13347/// OCD == OCD_AllCandidates and Cand->Viable == false.
13349 // Sort the candidates by position (assuming no candidate is a match).
13350 // Sorting directly would be prohibitive, so we make a set of pointers
13351 // and sort those.
13353 Cands.reserve(size());
13354 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
13355 if (Cand->Specialization)
13356 Cands.push_back(Cand);
13357 // Otherwise, this is a non-matching builtin candidate. We do not,
13358 // in general, want to list every possible builtin candidate.
13359 }
13360
13361 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
13362
13363 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
13364 // for generalization purposes (?).
13365 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
13366
13368 unsigned CandsShown = 0;
13369 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
13370 TemplateSpecCandidate *Cand = *I;
13371
13372 // Set an arbitrary limit on the number of candidates we'll spam
13373 // the user with. FIXME: This limit should depend on details of the
13374 // candidate list.
13375 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
13376 break;
13377 ++CandsShown;
13378
13379 assert(Cand->Specialization &&
13380 "Non-matching built-in candidates are not added to Cands.");
13381 Cand->NoteDeductionFailure(S, ForTakingAddress);
13382 }
13383
13384 if (I != E)
13385 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
13386}
13387
13388// [PossiblyAFunctionType] --> [Return]
13389// NonFunctionType --> NonFunctionType
13390// R (A) --> R(A)
13391// R (*)(A) --> R (A)
13392// R (&)(A) --> R (A)
13393// R (S::*)(A) --> R (A)
13395 QualType Ret = PossiblyAFunctionType;
13396 if (const PointerType *ToTypePtr =
13397 PossiblyAFunctionType->getAs<PointerType>())
13398 Ret = ToTypePtr->getPointeeType();
13399 else if (const ReferenceType *ToTypeRef =
13400 PossiblyAFunctionType->getAs<ReferenceType>())
13401 Ret = ToTypeRef->getPointeeType();
13402 else if (const MemberPointerType *MemTypePtr =
13403 PossiblyAFunctionType->getAs<MemberPointerType>())
13404 Ret = MemTypePtr->getPointeeType();
13405 Ret =
13406 Context.getCanonicalType(Ret).getUnqualifiedType();
13407 return Ret;
13408}
13409
13411 bool Complain = true) {
13412 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
13413 S.DeduceReturnType(FD, Loc, Complain))
13414 return true;
13415
13416 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
13417 if (S.getLangOpts().CPlusPlus17 &&
13418 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
13419 !S.ResolveExceptionSpec(Loc, FPT))
13420 return true;
13421
13422 return false;
13423}
13424
13425namespace {
13426// A helper class to help with address of function resolution
13427// - allows us to avoid passing around all those ugly parameters
13428class AddressOfFunctionResolver {
13429 Sema& S;
13430 Expr* SourceExpr;
13431 const QualType& TargetType;
13432 QualType TargetFunctionType; // Extracted function type from target type
13433
13434 bool Complain;
13435 //DeclAccessPair& ResultFunctionAccessPair;
13436 ASTContext& Context;
13437
13438 bool TargetTypeIsNonStaticMemberFunction;
13439 bool FoundNonTemplateFunction;
13440 bool StaticMemberFunctionFromBoundPointer;
13441 bool HasComplained;
13442
13443 OverloadExpr::FindResult OvlExprInfo;
13444 OverloadExpr *OvlExpr;
13445 TemplateArgumentListInfo OvlExplicitTemplateArgs;
13446 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
13447 TemplateSpecCandidateSet FailedCandidates;
13448
13449public:
13450 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
13451 const QualType &TargetType, bool Complain)
13452 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
13453 Complain(Complain), Context(S.getASTContext()),
13454 TargetTypeIsNonStaticMemberFunction(
13455 !!TargetType->getAs<MemberPointerType>()),
13456 FoundNonTemplateFunction(false),
13457 StaticMemberFunctionFromBoundPointer(false),
13458 HasComplained(false),
13459 OvlExprInfo(OverloadExpr::find(SourceExpr)),
13460 OvlExpr(OvlExprInfo.Expression),
13461 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
13462 ExtractUnqualifiedFunctionTypeFromTargetType();
13463
13464 if (TargetFunctionType->isFunctionType()) {
13465 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
13466 if (!UME->isImplicitAccess() &&
13468 StaticMemberFunctionFromBoundPointer = true;
13469 } else if (OvlExpr->hasExplicitTemplateArgs()) {
13470 DeclAccessPair dap;
13471 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
13472 OvlExpr, false, &dap)) {
13473 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
13474 if (!Method->isStatic()) {
13475 // If the target type is a non-function type and the function found
13476 // is a non-static member function, pretend as if that was the
13477 // target, it's the only possible type to end up with.
13478 TargetTypeIsNonStaticMemberFunction = true;
13479
13480 // And skip adding the function if its not in the proper form.
13481 // We'll diagnose this due to an empty set of functions.
13482 if (!OvlExprInfo.HasFormOfMemberPointer)
13483 return;
13484 }
13485
13486 Matches.push_back(std::make_pair(dap, Fn));
13487 }
13488 return;
13489 }
13490
13491 if (OvlExpr->hasExplicitTemplateArgs())
13492 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
13493
13494 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
13495 // C++ [over.over]p4:
13496 // If more than one function is selected, [...]
13497 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
13498 if (FoundNonTemplateFunction) {
13499 EliminateAllTemplateMatches();
13500 EliminateLessPartialOrderingConstrainedMatches();
13501 } else
13502 EliminateAllExceptMostSpecializedTemplate();
13503 }
13504 }
13505
13506 if (S.getLangOpts().CUDA && Matches.size() > 1)
13507 EliminateSuboptimalCudaMatches();
13508 }
13509
13510 bool hasComplained() const { return HasComplained; }
13511
13512private:
13513 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
13514 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
13515 S.IsFunctionConversion(FD->getType(), TargetFunctionType);
13516 }
13517
13518 /// \return true if A is considered a better overload candidate for the
13519 /// desired type than B.
13520 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
13521 // If A doesn't have exactly the correct type, we don't want to classify it
13522 // as "better" than anything else. This way, the user is required to
13523 // disambiguate for us if there are multiple candidates and no exact match.
13524 return candidateHasExactlyCorrectType(A) &&
13525 (!candidateHasExactlyCorrectType(B) ||
13526 compareEnableIfAttrs(S, A, B) == Comparison::Better);
13527 }
13528
13529 /// \return true if we were able to eliminate all but one overload candidate,
13530 /// false otherwise.
13531 bool eliminiateSuboptimalOverloadCandidates() {
13532 // Same algorithm as overload resolution -- one pass to pick the "best",
13533 // another pass to be sure that nothing is better than the best.
13534 auto Best = Matches.begin();
13535 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
13536 if (isBetterCandidate(I->second, Best->second))
13537 Best = I;
13538
13539 const FunctionDecl *BestFn = Best->second;
13540 auto IsBestOrInferiorToBest = [this, BestFn](
13541 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
13542 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
13543 };
13544
13545 // Note: We explicitly leave Matches unmodified if there isn't a clear best
13546 // option, so we can potentially give the user a better error
13547 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
13548 return false;
13549 Matches[0] = *Best;
13550 Matches.resize(1);
13551 return true;
13552 }
13553
13554 bool isTargetTypeAFunction() const {
13555 return TargetFunctionType->isFunctionType();
13556 }
13557
13558 // [ToType] [Return]
13559
13560 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
13561 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
13562 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
13563 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
13564 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
13565 }
13566
13567 // return true if any matching specializations were found
13568 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
13569 const DeclAccessPair& CurAccessFunPair) {
13570 if (CXXMethodDecl *Method
13571 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
13572 // Skip non-static function templates when converting to pointer, and
13573 // static when converting to member pointer.
13574 bool CanConvertToFunctionPointer =
13575 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13576 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13577 return false;
13578 }
13579 else if (TargetTypeIsNonStaticMemberFunction)
13580 return false;
13581
13582 // C++ [over.over]p2:
13583 // If the name is a function template, template argument deduction is
13584 // done (14.8.2.2), and if the argument deduction succeeds, the
13585 // resulting template argument list is used to generate a single
13586 // function template specialization, which is added to the set of
13587 // overloaded functions considered.
13588 FunctionDecl *Specialization = nullptr;
13589 TemplateDeductionInfo Info(FailedCandidates.getLocation());
13591 FunctionTemplate, &OvlExplicitTemplateArgs, TargetFunctionType,
13592 Specialization, Info, /*IsAddressOfFunction*/ true);
13593 Result != TemplateDeductionResult::Success) {
13594 // Make a note of the failed deduction for diagnostics.
13595 FailedCandidates.addCandidate()
13596 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
13597 MakeDeductionFailureInfo(Context, Result, Info));
13598 return false;
13599 }
13600
13601 // Template argument deduction ensures that we have an exact match or
13602 // compatible pointer-to-function arguments that would be adjusted by ICS.
13603 // This function template specicalization works.
13605 Context.getCanonicalType(Specialization->getType()),
13606 Context.getCanonicalType(TargetFunctionType)));
13607
13609 return false;
13610
13611 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
13612 return true;
13613 }
13614
13615 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
13616 const DeclAccessPair& CurAccessFunPair) {
13617 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13618 // Skip non-static functions when converting to pointer, and static
13619 // when converting to member pointer.
13620 bool CanConvertToFunctionPointer =
13621 Method->isStatic() || Method->isExplicitObjectMemberFunction();
13622 if (CanConvertToFunctionPointer == TargetTypeIsNonStaticMemberFunction)
13623 return false;
13624 }
13625 else if (TargetTypeIsNonStaticMemberFunction)
13626 return false;
13627
13628 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
13629 if (S.getLangOpts().CUDA) {
13630 FunctionDecl *Caller = S.getCurFunctionDecl(/*AllowLambda=*/true);
13631 if (!(Caller && Caller->isImplicit()) &&
13632 !S.CUDA().IsAllowedCall(Caller, FunDecl))
13633 return false;
13634 }
13635 if (FunDecl->isMultiVersion()) {
13636 const auto *TA = FunDecl->getAttr<TargetAttr>();
13637 if (TA && !TA->isDefaultVersion())
13638 return false;
13639 const auto *TVA = FunDecl->getAttr<TargetVersionAttr>();
13640 if (TVA && !TVA->isDefaultVersion())
13641 return false;
13642 }
13643
13644 // If any candidate has a placeholder return type, trigger its deduction
13645 // now.
13646 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
13647 Complain)) {
13648 HasComplained |= Complain;
13649 return false;
13650 }
13651
13652 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
13653 return false;
13654
13655 // If we're in C, we need to support types that aren't exactly identical.
13656 if (!S.getLangOpts().CPlusPlus ||
13657 candidateHasExactlyCorrectType(FunDecl)) {
13658 Matches.push_back(std::make_pair(
13659 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
13660 FoundNonTemplateFunction = true;
13661 return true;
13662 }
13663 }
13664
13665 return false;
13666 }
13667
13668 bool FindAllFunctionsThatMatchTargetTypeExactly() {
13669 bool Ret = false;
13670
13671 // If the overload expression doesn't have the form of a pointer to
13672 // member, don't try to convert it to a pointer-to-member type.
13673 if (IsInvalidFormOfPointerToMemberFunction())
13674 return false;
13675
13676 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13677 E = OvlExpr->decls_end();
13678 I != E; ++I) {
13679 // Look through any using declarations to find the underlying function.
13680 NamedDecl *Fn = (*I)->getUnderlyingDecl();
13681
13682 // C++ [over.over]p3:
13683 // Non-member functions and static member functions match
13684 // targets of type "pointer-to-function" or "reference-to-function."
13685 // Nonstatic member functions match targets of
13686 // type "pointer-to-member-function."
13687 // Note that according to DR 247, the containing class does not matter.
13688 if (FunctionTemplateDecl *FunctionTemplate
13689 = dyn_cast<FunctionTemplateDecl>(Fn)) {
13690 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
13691 Ret = true;
13692 }
13693 // If we have explicit template arguments supplied, skip non-templates.
13694 else if (!OvlExpr->hasExplicitTemplateArgs() &&
13695 AddMatchingNonTemplateFunction(Fn, I.getPair()))
13696 Ret = true;
13697 }
13698 assert(Ret || Matches.empty());
13699 return Ret;
13700 }
13701
13702 void EliminateAllExceptMostSpecializedTemplate() {
13703 // [...] and any given function template specialization F1 is
13704 // eliminated if the set contains a second function template
13705 // specialization whose function template is more specialized
13706 // than the function template of F1 according to the partial
13707 // ordering rules of 14.5.5.2.
13708
13709 // The algorithm specified above is quadratic. We instead use a
13710 // two-pass algorithm (similar to the one used to identify the
13711 // best viable function in an overload set) that identifies the
13712 // best function template (if it exists).
13713
13714 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
13715 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
13716 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
13717
13718 // TODO: It looks like FailedCandidates does not serve much purpose
13719 // here, since the no_viable diagnostic has index 0.
13720 UnresolvedSetIterator Result = S.getMostSpecialized(
13721 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
13722 SourceExpr->getBeginLoc(), S.PDiag(),
13723 S.PDiag(diag::err_addr_ovl_ambiguous)
13724 << Matches[0].second->getDeclName(),
13725 S.PDiag(diag::note_ovl_candidate)
13726 << (unsigned)oc_function << (unsigned)ocs_described_template,
13727 Complain, TargetFunctionType);
13728
13729 if (Result != MatchesCopy.end()) {
13730 // Make it the first and only element
13731 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
13732 Matches[0].second = cast<FunctionDecl>(*Result);
13733 Matches.resize(1);
13734 } else
13735 HasComplained |= Complain;
13736 }
13737
13738 void EliminateAllTemplateMatches() {
13739 // [...] any function template specializations in the set are
13740 // eliminated if the set also contains a non-template function, [...]
13741 for (unsigned I = 0, N = Matches.size(); I != N; ) {
13742 if (Matches[I].second->getPrimaryTemplate() == nullptr)
13743 ++I;
13744 else {
13745 Matches[I] = Matches[--N];
13746 Matches.resize(N);
13747 }
13748 }
13749 }
13750
13751 void EliminateLessPartialOrderingConstrainedMatches() {
13752 // C++ [over.over]p5:
13753 // [...] Any given non-template function F0 is eliminated if the set
13754 // contains a second non-template function that is more
13755 // partial-ordering-constrained than F0. [...]
13756 assert(Matches[0].second->getPrimaryTemplate() == nullptr &&
13757 "Call EliminateAllTemplateMatches() first");
13758 SmallVector<std::pair<DeclAccessPair, FunctionDecl *>, 4> Results;
13759 Results.push_back(Matches[0]);
13760 for (unsigned I = 1, N = Matches.size(); I < N; ++I) {
13761 assert(Matches[I].second->getPrimaryTemplate() == nullptr);
13762 FunctionDecl *F = getMorePartialOrderingConstrained(
13763 S, Matches[I].second, Results[0].second,
13764 /*IsFn1Reversed=*/false,
13765 /*IsFn2Reversed=*/false);
13766 if (!F) {
13767 Results.push_back(Matches[I]);
13768 continue;
13769 }
13770 if (F == Matches[I].second) {
13771 Results.clear();
13772 Results.push_back(Matches[I]);
13773 }
13774 }
13775 std::swap(Matches, Results);
13776 }
13777
13778 void EliminateSuboptimalCudaMatches() {
13779 S.CUDA().EraseUnwantedMatches(S.getCurFunctionDecl(/*AllowLambda=*/true),
13780 Matches);
13781 }
13782
13783public:
13784 void ComplainNoMatchesFound() const {
13785 assert(Matches.empty());
13786 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
13787 << OvlExpr->getName() << TargetFunctionType
13788 << OvlExpr->getSourceRange();
13789 if (FailedCandidates.empty())
13790 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13791 /*TakingAddress=*/true);
13792 else {
13793 // We have some deduction failure messages. Use them to diagnose
13794 // the function templates, and diagnose the non-template candidates
13795 // normally.
13796 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
13797 IEnd = OvlExpr->decls_end();
13798 I != IEnd; ++I)
13799 if (FunctionDecl *Fun =
13800 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
13802 S.NoteOverloadCandidate(*I, Fun, CRK_None, TargetFunctionType,
13803 /*TakingAddress=*/true);
13804 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
13805 }
13806 }
13807
13808 bool IsInvalidFormOfPointerToMemberFunction() const {
13809 return TargetTypeIsNonStaticMemberFunction &&
13810 !OvlExprInfo.HasFormOfMemberPointer;
13811 }
13812
13813 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
13814 // TODO: Should we condition this on whether any functions might
13815 // have matched, or is it more appropriate to do that in callers?
13816 // TODO: a fixit wouldn't hurt.
13817 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
13818 << TargetType << OvlExpr->getSourceRange();
13819 }
13820
13821 bool IsStaticMemberFunctionFromBoundPointer() const {
13822 return StaticMemberFunctionFromBoundPointer;
13823 }
13824
13825 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
13826 S.Diag(OvlExpr->getBeginLoc(),
13827 diag::err_invalid_form_pointer_member_function)
13828 << OvlExpr->getSourceRange();
13829 }
13830
13831 void ComplainOfInvalidConversion() const {
13832 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
13833 << OvlExpr->getName() << TargetType;
13834 }
13835
13836 void ComplainMultipleMatchesFound() const {
13837 assert(Matches.size() > 1);
13838 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
13839 << OvlExpr->getName() << OvlExpr->getSourceRange();
13840 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
13841 /*TakingAddress=*/true);
13842 }
13843
13844 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
13845
13846 int getNumMatches() const { return Matches.size(); }
13847
13848 FunctionDecl* getMatchingFunctionDecl() const {
13849 if (Matches.size() != 1) return nullptr;
13850 return Matches[0].second;
13851 }
13852
13853 const DeclAccessPair* getMatchingFunctionAccessPair() const {
13854 if (Matches.size() != 1) return nullptr;
13855 return &Matches[0].first;
13856 }
13857};
13858}
13859
13860FunctionDecl *
13862 QualType TargetType,
13863 bool Complain,
13864 DeclAccessPair &FoundResult,
13865 bool *pHadMultipleCandidates) {
13866 assert(AddressOfExpr->getType() == Context.OverloadTy);
13867
13868 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
13869 Complain);
13870 int NumMatches = Resolver.getNumMatches();
13871 FunctionDecl *Fn = nullptr;
13872 bool ShouldComplain = Complain && !Resolver.hasComplained();
13873 if (NumMatches == 0 && ShouldComplain) {
13874 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
13875 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
13876 else
13877 Resolver.ComplainNoMatchesFound();
13878 }
13879 else if (NumMatches > 1 && ShouldComplain)
13880 Resolver.ComplainMultipleMatchesFound();
13881 else if (NumMatches == 1) {
13882 Fn = Resolver.getMatchingFunctionDecl();
13883 assert(Fn);
13884 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13885 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
13886 FoundResult = *Resolver.getMatchingFunctionAccessPair();
13887 if (Complain) {
13888 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
13889 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
13890 else
13891 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
13892 }
13893 }
13894
13895 if (pHadMultipleCandidates)
13896 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
13897 return Fn;
13898}
13899
13903 OverloadExpr *Ovl = R.Expression;
13904 bool IsResultAmbiguous = false;
13905 FunctionDecl *Result = nullptr;
13906 DeclAccessPair DAP;
13907 SmallVector<FunctionDecl *, 2> AmbiguousDecls;
13908
13909 // Return positive for better, negative for worse, 0 for equal preference.
13910 auto CheckCUDAPreference = [&](FunctionDecl *FD1, FunctionDecl *FD2) {
13911 FunctionDecl *Caller = getCurFunctionDecl(/*AllowLambda=*/true);
13912 return static_cast<int>(CUDA().IdentifyPreference(Caller, FD1)) -
13913 static_cast<int>(CUDA().IdentifyPreference(Caller, FD2));
13914 };
13915
13916 // Don't use the AddressOfResolver because we're specifically looking for
13917 // cases where we have one overload candidate that lacks
13918 // enable_if/pass_object_size/...
13919 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
13920 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
13921 if (!FD)
13922 return nullptr;
13923
13925 continue;
13926
13927 // If we found a better result, update Result.
13928 auto FoundBetter = [&]() {
13929 IsResultAmbiguous = false;
13930 DAP = I.getPair();
13931 Result = FD;
13932 };
13933
13934 // We have more than one result - see if it is more
13935 // partial-ordering-constrained than the previous one.
13936 if (Result) {
13937 // Check CUDA preference first. If the candidates have differennt CUDA
13938 // preference, choose the one with higher CUDA preference. Otherwise,
13939 // choose the one with more constraints.
13940 if (getLangOpts().CUDA) {
13941 int PreferenceByCUDA = CheckCUDAPreference(FD, Result);
13942 // FD has different preference than Result.
13943 if (PreferenceByCUDA != 0) {
13944 // FD is more preferable than Result.
13945 if (PreferenceByCUDA > 0)
13946 FoundBetter();
13947 continue;
13948 }
13949 }
13950 // FD has the same CUDA preference than Result. Continue to check
13951 // constraints.
13952
13953 // C++ [over.over]p5:
13954 // [...] Any given non-template function F0 is eliminated if the set
13955 // contains a second non-template function that is more
13956 // partial-ordering-constrained than F0 [...]
13957 FunctionDecl *MoreConstrained =
13959 /*IsFn1Reversed=*/false,
13960 /*IsFn2Reversed=*/false);
13961 if (MoreConstrained != FD) {
13962 if (!MoreConstrained) {
13963 IsResultAmbiguous = true;
13964 AmbiguousDecls.push_back(FD);
13965 }
13966 continue;
13967 }
13968 // FD is more constrained - replace Result with it.
13969 }
13970 FoundBetter();
13971 }
13972
13973 if (IsResultAmbiguous)
13974 return nullptr;
13975
13976 if (Result) {
13977 // We skipped over some ambiguous declarations which might be ambiguous with
13978 // the selected result.
13979 for (FunctionDecl *Skipped : AmbiguousDecls) {
13980 // If skipped candidate has different CUDA preference than the result,
13981 // there is no ambiguity. Otherwise check whether they have different
13982 // constraints.
13983 if (getLangOpts().CUDA && CheckCUDAPreference(Skipped, Result) != 0)
13984 continue;
13985 if (!getMoreConstrainedFunction(Skipped, Result))
13986 return nullptr;
13987 }
13988 Pair = DAP;
13989 }
13990 return Result;
13991}
13992
13994 ExprResult &SrcExpr, bool DoFunctionPointerConversion) {
13995 Expr *E = SrcExpr.get();
13996 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
13997
13998 DeclAccessPair DAP;
14000 if (!Found || Found->isCPUDispatchMultiVersion() ||
14001 Found->isCPUSpecificMultiVersion())
14002 return false;
14003
14004 // Emitting multiple diagnostics for a function that is both inaccessible and
14005 // unavailable is consistent with our behavior elsewhere. So, always check
14006 // for both.
14010 if (Res.isInvalid())
14011 return false;
14012 Expr *Fixed = Res.get();
14013 if (DoFunctionPointerConversion && Fixed->getType()->isFunctionType())
14014 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
14015 else
14016 SrcExpr = Fixed;
14017 return true;
14018}
14019
14021 OverloadExpr *ovl, bool Complain, DeclAccessPair *FoundResult,
14022 TemplateSpecCandidateSet *FailedTSC, bool ForTypeDeduction) {
14023 // C++ [over.over]p1:
14024 // [...] [Note: any redundant set of parentheses surrounding the
14025 // overloaded function name is ignored (5.1). ]
14026 // C++ [over.over]p1:
14027 // [...] The overloaded function name can be preceded by the &
14028 // operator.
14029
14030 // If we didn't actually find any template-ids, we're done.
14031 if (!ovl->hasExplicitTemplateArgs())
14032 return nullptr;
14033
14034 TemplateArgumentListInfo ExplicitTemplateArgs;
14035 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
14036
14037 // Look through all of the overloaded functions, searching for one
14038 // whose type matches exactly.
14039 FunctionDecl *Matched = nullptr;
14040 for (UnresolvedSetIterator I = ovl->decls_begin(),
14041 E = ovl->decls_end(); I != E; ++I) {
14042 // C++0x [temp.arg.explicit]p3:
14043 // [...] In contexts where deduction is done and fails, or in contexts
14044 // where deduction is not done, if a template argument list is
14045 // specified and it, along with any default template arguments,
14046 // identifies a single function template specialization, then the
14047 // template-id is an lvalue for the function template specialization.
14049 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
14050 if (!FunctionTemplate)
14051 continue;
14052
14053 // C++ [over.over]p2:
14054 // If the name is a function template, template argument deduction is
14055 // done (14.8.2.2), and if the argument deduction succeeds, the
14056 // resulting template argument list is used to generate a single
14057 // function template specialization, which is added to the set of
14058 // overloaded functions considered.
14059 FunctionDecl *Specialization = nullptr;
14060 TemplateDeductionInfo Info(ovl->getNameLoc());
14062 FunctionTemplate, &ExplicitTemplateArgs, Specialization, Info,
14063 /*IsAddressOfFunction*/ true);
14065 // Make a note of the failed deduction for diagnostics.
14066 if (FailedTSC)
14067 FailedTSC->addCandidate().set(
14068 I.getPair(), FunctionTemplate->getTemplatedDecl(),
14070 continue;
14071 }
14072
14073 assert(Specialization && "no specialization and no error?");
14074
14075 // C++ [temp.deduct.call]p6:
14076 // [...] If all successful deductions yield the same deduced A, that
14077 // deduced A is the result of deduction; otherwise, the parameter is
14078 // treated as a non-deduced context.
14079 if (Matched) {
14080 if (ForTypeDeduction &&
14082 Specialization->getType()))
14083 continue;
14084 // Multiple matches; we can't resolve to a single declaration.
14085 if (Complain) {
14086 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
14087 << ovl->getName();
14089 }
14090 return nullptr;
14091 }
14092
14093 Matched = Specialization;
14094 if (FoundResult) *FoundResult = I.getPair();
14095 }
14096
14097 if (Matched &&
14098 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
14099 return nullptr;
14100
14101 return Matched;
14102}
14103
14105 ExprResult &SrcExpr, bool doFunctionPointerConversion, bool complain,
14106 SourceRange OpRangeForComplaining, QualType DestTypeForComplaining,
14107 unsigned DiagIDForComplaining) {
14108 assert(SrcExpr.get()->getType() == Context.OverloadTy);
14109
14111
14112 DeclAccessPair found;
14113 ExprResult SingleFunctionExpression;
14115 ovl.Expression, /*complain*/ false, &found)) {
14116 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
14117 SrcExpr = ExprError();
14118 return true;
14119 }
14120
14121 // It is only correct to resolve to an instance method if we're
14122 // resolving a form that's permitted to be a pointer to member.
14123 // Otherwise we'll end up making a bound member expression, which
14124 // is illegal in all the contexts we resolve like this.
14125 if (!ovl.HasFormOfMemberPointer &&
14126 isa<CXXMethodDecl>(fn) &&
14127 cast<CXXMethodDecl>(fn)->isInstance()) {
14128 if (!complain) return false;
14129
14130 Diag(ovl.Expression->getExprLoc(),
14131 diag::err_bound_member_function)
14132 << 0 << ovl.Expression->getSourceRange();
14133
14134 // TODO: I believe we only end up here if there's a mix of
14135 // static and non-static candidates (otherwise the expression
14136 // would have 'bound member' type, not 'overload' type).
14137 // Ideally we would note which candidate was chosen and why
14138 // the static candidates were rejected.
14139 SrcExpr = ExprError();
14140 return true;
14141 }
14142
14143 // Fix the expression to refer to 'fn'.
14144 SingleFunctionExpression =
14145 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
14146
14147 // If desired, do function-to-pointer decay.
14148 if (doFunctionPointerConversion) {
14149 SingleFunctionExpression =
14150 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
14151 if (SingleFunctionExpression.isInvalid()) {
14152 SrcExpr = ExprError();
14153 return true;
14154 }
14155 }
14156 }
14157
14158 if (!SingleFunctionExpression.isUsable()) {
14159 if (complain) {
14160 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
14161 << ovl.Expression->getName()
14162 << DestTypeForComplaining
14163 << OpRangeForComplaining
14165 NoteAllOverloadCandidates(SrcExpr.get());
14166
14167 SrcExpr = ExprError();
14168 return true;
14169 }
14170
14171 return false;
14172 }
14173
14174 SrcExpr = SingleFunctionExpression;
14175 return true;
14176}
14177
14178/// Add a single candidate to the overload set.
14180 DeclAccessPair FoundDecl,
14181 TemplateArgumentListInfo *ExplicitTemplateArgs,
14182 ArrayRef<Expr *> Args,
14183 OverloadCandidateSet &CandidateSet,
14184 bool PartialOverloading,
14185 bool KnownValid) {
14186 NamedDecl *Callee = FoundDecl.getDecl();
14187 if (isa<UsingShadowDecl>(Callee))
14188 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
14189
14190 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
14191 if (ExplicitTemplateArgs) {
14192 assert(!KnownValid && "Explicit template arguments?");
14193 return;
14194 }
14195 // Prevent ill-formed function decls to be added as overload candidates.
14196 if (!isa<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
14197 return;
14198
14199 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
14200 /*SuppressUserConversions=*/false,
14201 PartialOverloading);
14202 return;
14203 }
14204
14205 if (FunctionTemplateDecl *FuncTemplate
14206 = dyn_cast<FunctionTemplateDecl>(Callee)) {
14207 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
14208 ExplicitTemplateArgs, Args, CandidateSet,
14209 /*SuppressUserConversions=*/false,
14210 PartialOverloading);
14211 return;
14212 }
14213
14214 assert(!KnownValid && "unhandled case in overloaded call candidate");
14215}
14216
14218 ArrayRef<Expr *> Args,
14219 OverloadCandidateSet &CandidateSet,
14220 bool PartialOverloading) {
14221
14222#ifndef NDEBUG
14223 // Verify that ArgumentDependentLookup is consistent with the rules
14224 // in C++0x [basic.lookup.argdep]p3:
14225 //
14226 // Let X be the lookup set produced by unqualified lookup (3.4.1)
14227 // and let Y be the lookup set produced by argument dependent
14228 // lookup (defined as follows). If X contains
14229 //
14230 // -- a declaration of a class member, or
14231 //
14232 // -- a block-scope function declaration that is not a
14233 // using-declaration, or
14234 //
14235 // -- a declaration that is neither a function or a function
14236 // template
14237 //
14238 // then Y is empty.
14239
14240 if (ULE->requiresADL()) {
14242 E = ULE->decls_end(); I != E; ++I) {
14243 assert(!(*I)->getDeclContext()->isRecord());
14244 assert(isa<UsingShadowDecl>(*I) ||
14245 !(*I)->getDeclContext()->isFunctionOrMethod());
14246 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
14247 }
14248 }
14249#endif
14250
14251 // It would be nice to avoid this copy.
14252 TemplateArgumentListInfo TABuffer;
14253 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14254 if (ULE->hasExplicitTemplateArgs()) {
14255 ULE->copyTemplateArgumentsInto(TABuffer);
14256 ExplicitTemplateArgs = &TABuffer;
14257 }
14258
14260 E = ULE->decls_end(); I != E; ++I)
14261 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14262 CandidateSet, PartialOverloading,
14263 /*KnownValid*/ true);
14264
14265 if (ULE->requiresADL())
14267 Args, ExplicitTemplateArgs,
14268 CandidateSet, PartialOverloading);
14269}
14270
14272 LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs,
14273 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet) {
14274 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
14275 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
14276 CandidateSet, false, /*KnownValid*/ false);
14277}
14278
14279/// Determine whether a declaration with the specified name could be moved into
14280/// a different namespace.
14282 switch (Name.getCXXOverloadedOperator()) {
14283 case OO_New: case OO_Array_New:
14284 case OO_Delete: case OO_Array_Delete:
14285 return false;
14286
14287 default:
14288 return true;
14289 }
14290}
14291
14292/// Attempt to recover from an ill-formed use of a non-dependent name in a
14293/// template, where the non-dependent name was declared after the template
14294/// was defined. This is common in code written for a compilers which do not
14295/// correctly implement two-stage name lookup.
14296///
14297/// Returns true if a viable candidate was found and a diagnostic was issued.
14299 Sema &SemaRef, SourceLocation FnLoc, const CXXScopeSpec &SS,
14301 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
14302 CXXRecordDecl **FoundInClass = nullptr) {
14303 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
14304 return false;
14305
14306 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
14307 if (DC->isTransparentContext())
14308 continue;
14309
14310 SemaRef.LookupQualifiedName(R, DC);
14311
14312 if (!R.empty()) {
14314
14315 OverloadCandidateSet Candidates(FnLoc, CSK);
14316 SemaRef.AddOverloadedCallCandidates(R, ExplicitTemplateArgs, Args,
14317 Candidates);
14318
14321 Candidates.BestViableFunction(SemaRef, FnLoc, Best);
14322
14323 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
14324 // We either found non-function declarations or a best viable function
14325 // at class scope. A class-scope lookup result disables ADL. Don't
14326 // look past this, but let the caller know that we found something that
14327 // either is, or might be, usable in this class.
14328 if (FoundInClass) {
14329 *FoundInClass = RD;
14330 if (OR == OR_Success) {
14331 R.clear();
14332 R.addDecl(Best->FoundDecl.getDecl(), Best->FoundDecl.getAccess());
14333 R.resolveKind();
14334 }
14335 }
14336 return false;
14337 }
14338
14339 if (OR != OR_Success) {
14340 // There wasn't a unique best function or function template.
14341 return false;
14342 }
14343
14344 // Find the namespaces where ADL would have looked, and suggest
14345 // declaring the function there instead.
14346 Sema::AssociatedNamespaceSet AssociatedNamespaces;
14347 Sema::AssociatedClassSet AssociatedClasses;
14348 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
14349 AssociatedNamespaces,
14350 AssociatedClasses);
14351 Sema::AssociatedNamespaceSet SuggestedNamespaces;
14353 DeclContext *Std = SemaRef.getStdNamespace();
14354 for (Sema::AssociatedNamespaceSet::iterator
14355 it = AssociatedNamespaces.begin(),
14356 end = AssociatedNamespaces.end(); it != end; ++it) {
14357 // Never suggest declaring a function within namespace 'std'.
14358 if (Std && Std->Encloses(*it))
14359 continue;
14360
14361 // Never suggest declaring a function within a namespace with a
14362 // reserved name, like __gnu_cxx.
14363 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
14364 if (NS &&
14365 NS->getQualifiedNameAsString().find("__") != std::string::npos)
14366 continue;
14367
14368 SuggestedNamespaces.insert(*it);
14369 }
14370 }
14371
14372 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
14373 << R.getLookupName();
14374 if (SuggestedNamespaces.empty()) {
14375 SemaRef.Diag(Best->Function->getLocation(),
14376 diag::note_not_found_by_two_phase_lookup)
14377 << R.getLookupName() << 0;
14378 } else if (SuggestedNamespaces.size() == 1) {
14379 SemaRef.Diag(Best->Function->getLocation(),
14380 diag::note_not_found_by_two_phase_lookup)
14381 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
14382 } else {
14383 // FIXME: It would be useful to list the associated namespaces here,
14384 // but the diagnostics infrastructure doesn't provide a way to produce
14385 // a localized representation of a list of items.
14386 SemaRef.Diag(Best->Function->getLocation(),
14387 diag::note_not_found_by_two_phase_lookup)
14388 << R.getLookupName() << 2;
14389 }
14390
14391 // Try to recover by calling this function.
14392 return true;
14393 }
14394
14395 R.clear();
14396 }
14397
14398 return false;
14399}
14400
14401/// Attempt to recover from ill-formed use of a non-dependent operator in a
14402/// template, where the non-dependent operator was declared after the template
14403/// was defined.
14404///
14405/// Returns true if a viable candidate was found and a diagnostic was issued.
14406static bool
14408 SourceLocation OpLoc,
14409 ArrayRef<Expr *> Args) {
14410 DeclarationName OpName =
14412 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
14413 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
14415 /*ExplicitTemplateArgs=*/nullptr, Args);
14416}
14417
14418namespace {
14419class BuildRecoveryCallExprRAII {
14420 Sema &SemaRef;
14421 Sema::SatisfactionStackResetRAII SatStack;
14422
14423public:
14424 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S), SatStack(S) {
14425 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
14426 SemaRef.IsBuildingRecoveryCallExpr = true;
14427 }
14428
14429 ~BuildRecoveryCallExprRAII() { SemaRef.IsBuildingRecoveryCallExpr = false; }
14430};
14431}
14432
14433/// Attempts to recover from a call where no functions were found.
14434///
14435/// This function will do one of three things:
14436/// * Diagnose, recover, and return a recovery expression.
14437/// * Diagnose, fail to recover, and return ExprError().
14438/// * Do not diagnose, do not recover, and return ExprResult(). The caller is
14439/// expected to diagnose as appropriate.
14440static ExprResult
14443 SourceLocation LParenLoc,
14445 SourceLocation RParenLoc,
14446 bool EmptyLookup, bool AllowTypoCorrection) {
14447 // Do not try to recover if it is already building a recovery call.
14448 // This stops infinite loops for template instantiations like
14449 //
14450 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
14451 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
14452 if (SemaRef.IsBuildingRecoveryCallExpr)
14453 return ExprResult();
14454 BuildRecoveryCallExprRAII RCE(SemaRef);
14455
14456 CXXScopeSpec SS;
14457 SS.Adopt(ULE->getQualifierLoc());
14458 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
14459
14460 TemplateArgumentListInfo TABuffer;
14461 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
14462 if (ULE->hasExplicitTemplateArgs()) {
14463 ULE->copyTemplateArgumentsInto(TABuffer);
14464 ExplicitTemplateArgs = &TABuffer;
14465 }
14466
14467 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
14469 CXXRecordDecl *FoundInClass = nullptr;
14470 if (DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
14472 ExplicitTemplateArgs, Args, &FoundInClass)) {
14473 // OK, diagnosed a two-phase lookup issue.
14474 } else if (EmptyLookup) {
14475 // Try to recover from an empty lookup with typo correction.
14476 R.clear();
14477 NoTypoCorrectionCCC NoTypoValidator{};
14478 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
14479 ExplicitTemplateArgs != nullptr,
14480 dyn_cast<MemberExpr>(Fn));
14481 CorrectionCandidateCallback &Validator =
14482 AllowTypoCorrection
14483 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
14484 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
14485 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
14486 Args))
14487 return ExprError();
14488 } else if (FoundInClass && SemaRef.getLangOpts().MSVCCompat) {
14489 // We found a usable declaration of the name in a dependent base of some
14490 // enclosing class.
14491 // FIXME: We should also explain why the candidates found by name lookup
14492 // were not viable.
14493 if (SemaRef.DiagnoseDependentMemberLookup(R))
14494 return ExprError();
14495 } else {
14496 // We had viable candidates and couldn't recover; let the caller diagnose
14497 // this.
14498 return ExprResult();
14499 }
14500
14501 // If we get here, we should have issued a diagnostic and formed a recovery
14502 // lookup result.
14503 assert(!R.empty() && "lookup results empty despite recovery");
14504
14505 // If recovery created an ambiguity, just bail out.
14506 if (R.isAmbiguous()) {
14508 return ExprError();
14509 }
14510
14511 // Build an implicit member call if appropriate. Just drop the
14512 // casts and such from the call, we don't really care.
14513 ExprResult NewFn = ExprError();
14514 if ((*R.begin())->isCXXClassMember())
14515 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
14516 ExplicitTemplateArgs, S);
14517 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
14518 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
14519 ExplicitTemplateArgs);
14520 else
14521 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
14522
14523 if (NewFn.isInvalid())
14524 return ExprError();
14525
14526 // This shouldn't cause an infinite loop because we're giving it
14527 // an expression with viable lookup results, which should never
14528 // end up here.
14529 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
14530 MultiExprArg(Args.data(), Args.size()),
14531 RParenLoc);
14532}
14533
14536 MultiExprArg Args,
14537 SourceLocation RParenLoc,
14538 OverloadCandidateSet *CandidateSet,
14539 ExprResult *Result) {
14540#ifndef NDEBUG
14541 if (ULE->requiresADL()) {
14542 // To do ADL, we must have found an unqualified name.
14543 assert(!ULE->getQualifier() && "qualified name with ADL");
14544
14545 // We don't perform ADL for implicit declarations of builtins.
14546 // Verify that this was correctly set up.
14547 FunctionDecl *F;
14548 if (ULE->decls_begin() != ULE->decls_end() &&
14549 ULE->decls_begin() + 1 == ULE->decls_end() &&
14550 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
14551 F->getBuiltinID() && F->isImplicit())
14552 llvm_unreachable("performing ADL for builtin");
14553
14554 // We don't perform ADL in C.
14555 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
14556 }
14557#endif
14558
14559 UnbridgedCastsSet UnbridgedCasts;
14560 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
14561 *Result = ExprError();
14562 return true;
14563 }
14564
14565 // Add the functions denoted by the callee to the set of candidate
14566 // functions, including those from argument-dependent lookup.
14567 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
14568
14569 if (getLangOpts().MSVCCompat &&
14570 CurContext->isDependentContext() && !isSFINAEContext() &&
14572
14574 if (CandidateSet->empty() ||
14575 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
14577 // In Microsoft mode, if we are inside a template class member function
14578 // then create a type dependent CallExpr. The goal is to postpone name
14579 // lookup to instantiation time to be able to search into type dependent
14580 // base classes.
14581 CallExpr *CE =
14582 CallExpr::Create(Context, Fn, Args, Context.DependentTy, VK_PRValue,
14583 RParenLoc, CurFPFeatureOverrides());
14585 *Result = CE;
14586 return true;
14587 }
14588 }
14589
14590 if (CandidateSet->empty())
14591 return false;
14592
14593 UnbridgedCasts.restore();
14594 return false;
14595}
14596
14597// Guess at what the return type for an unresolvable overload should be.
14600 std::optional<QualType> Result;
14601 // Adjust Type after seeing a candidate.
14602 auto ConsiderCandidate = [&](const OverloadCandidate &Candidate) {
14603 if (!Candidate.Function)
14604 return;
14605 if (Candidate.Function->isInvalidDecl())
14606 return;
14607 QualType T = Candidate.Function->getReturnType();
14608 if (T.isNull())
14609 return;
14610 if (!Result)
14611 Result = T;
14612 else if (Result != T)
14613 Result = QualType();
14614 };
14615
14616 // Look for an unambiguous type from a progressively larger subset.
14617 // e.g. if types disagree, but all *viable* overloads return int, choose int.
14618 //
14619 // First, consider only the best candidate.
14620 if (Best && *Best != CS.end())
14621 ConsiderCandidate(**Best);
14622 // Next, consider only viable candidates.
14623 if (!Result)
14624 for (const auto &C : CS)
14625 if (C.Viable)
14626 ConsiderCandidate(C);
14627 // Finally, consider all candidates.
14628 if (!Result)
14629 for (const auto &C : CS)
14630 ConsiderCandidate(C);
14631
14632 if (!Result)
14633 return QualType();
14634 auto Value = *Result;
14635 if (Value.isNull() || Value->isUndeducedType())
14636 return QualType();
14637 return Value;
14638}
14639
14640/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
14641/// the completed call expression. If overload resolution fails, emits
14642/// diagnostics and returns ExprError()
14645 SourceLocation LParenLoc,
14646 MultiExprArg Args,
14647 SourceLocation RParenLoc,
14648 Expr *ExecConfig,
14649 OverloadCandidateSet *CandidateSet,
14651 OverloadingResult OverloadResult,
14652 bool AllowTypoCorrection) {
14653 switch (OverloadResult) {
14654 case OR_Success: {
14655 FunctionDecl *FDecl = (*Best)->Function;
14656 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
14657 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
14658 return ExprError();
14659 ExprResult Res =
14660 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14661 if (Res.isInvalid())
14662 return ExprError();
14663 return SemaRef.BuildResolvedCallExpr(
14664 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14665 /*IsExecConfig=*/false,
14666 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14667 }
14668
14669 case OR_No_Viable_Function: {
14670 if (*Best != CandidateSet->end() &&
14671 CandidateSet->getKind() ==
14673 if (CXXMethodDecl *M =
14674 dyn_cast_if_present<CXXMethodDecl>((*Best)->Function);
14676 CandidateSet->NoteCandidates(
14678 Fn->getBeginLoc(),
14679 SemaRef.PDiag(diag::err_member_call_without_object) << 0 << M),
14680 SemaRef, OCD_AmbiguousCandidates, Args);
14681 return ExprError();
14682 }
14683 }
14684
14685 // Try to recover by looking for viable functions which the user might
14686 // have meant to call.
14687 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
14688 Args, RParenLoc,
14689 CandidateSet->empty(),
14690 AllowTypoCorrection);
14691 if (Recovery.isInvalid() || Recovery.isUsable())
14692 return Recovery;
14693
14694 // If the user passes in a function that we can't take the address of, we
14695 // generally end up emitting really bad error messages. Here, we attempt to
14696 // emit better ones.
14697 for (const Expr *Arg : Args) {
14698 if (!Arg->getType()->isFunctionType())
14699 continue;
14700 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
14701 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
14702 if (FD &&
14703 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
14704 Arg->getExprLoc()))
14705 return ExprError();
14706 }
14707 }
14708
14709 CandidateSet->NoteCandidates(
14711 Fn->getBeginLoc(),
14712 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
14713 << ULE->getName() << Fn->getSourceRange()),
14714 SemaRef, OCD_AllCandidates, Args);
14715 break;
14716 }
14717
14718 case OR_Ambiguous:
14719 CandidateSet->NoteCandidates(
14720 PartialDiagnosticAt(Fn->getBeginLoc(),
14721 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
14722 << ULE->getName() << Fn->getSourceRange()),
14723 SemaRef, OCD_AmbiguousCandidates, Args);
14724 break;
14725
14726 case OR_Deleted: {
14727 FunctionDecl *FDecl = (*Best)->Function;
14728 SemaRef.DiagnoseUseOfDeletedFunction(Fn->getBeginLoc(),
14729 Fn->getSourceRange(), ULE->getName(),
14730 *CandidateSet, FDecl, Args);
14731
14732 // We emitted an error for the unavailable/deleted function call but keep
14733 // the call in the AST.
14734 ExprResult Res =
14735 SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
14736 if (Res.isInvalid())
14737 return ExprError();
14738 return SemaRef.BuildResolvedCallExpr(
14739 Res.get(), FDecl, LParenLoc, Args, RParenLoc, ExecConfig,
14740 /*IsExecConfig=*/false,
14741 static_cast<CallExpr::ADLCallKind>((*Best)->IsADLCandidate));
14742 }
14743 }
14744
14745 // Overload resolution failed, try to recover.
14746 SmallVector<Expr *, 8> SubExprs = {Fn};
14747 SubExprs.append(Args.begin(), Args.end());
14748 return SemaRef.CreateRecoveryExpr(Fn->getBeginLoc(), RParenLoc, SubExprs,
14749 chooseRecoveryType(*CandidateSet, Best));
14750}
14751
14754 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
14755 if (I->Viable &&
14756 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
14757 I->Viable = false;
14758 I->FailureKind = ovl_fail_addr_not_available;
14759 }
14760 }
14761}
14762
14765 SourceLocation LParenLoc,
14766 MultiExprArg Args,
14767 SourceLocation RParenLoc,
14768 Expr *ExecConfig,
14769 bool AllowTypoCorrection,
14770 bool CalleesAddressIsTaken) {
14771
14775
14776 OverloadCandidateSet CandidateSet(Fn->getExprLoc(), CSK);
14777 ExprResult result;
14778
14779 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
14780 &result))
14781 return result;
14782
14783 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
14784 // functions that aren't addressible are considered unviable.
14785 if (CalleesAddressIsTaken)
14786 markUnaddressableCandidatesUnviable(*this, CandidateSet);
14787
14789 OverloadingResult OverloadResult =
14790 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
14791
14792 // [C++23][over.call.func]
14793 // if overload resolution selects a non-static member function,
14794 // the call is ill-formed;
14796 Best != CandidateSet.end()) {
14797 if (auto *M = dyn_cast_or_null<CXXMethodDecl>(Best->Function);
14798 M && M->isImplicitObjectMemberFunction()) {
14799 OverloadResult = OR_No_Viable_Function;
14800 }
14801 }
14802
14803 // Model the case with a call to a templated function whose definition
14804 // encloses the call and whose return type contains a placeholder type as if
14805 // the UnresolvedLookupExpr was type-dependent.
14806 if (OverloadResult == OR_Success) {
14807 const FunctionDecl *FDecl = Best->Function;
14808 if (LangOpts.CUDA)
14809 CUDA().recordPotentialODRUsedVariable(Args, CandidateSet);
14810 if (FDecl && FDecl->isTemplateInstantiation() &&
14811 FDecl->getReturnType()->isUndeducedType()) {
14812
14813 // Creating dependent CallExpr is not okay if the enclosing context itself
14814 // is not dependent. This situation notably arises if a non-dependent
14815 // member function calls the later-defined overloaded static function.
14816 //
14817 // For example, in
14818 // class A {
14819 // void c() { callee(1); }
14820 // static auto callee(auto x) { }
14821 // };
14822 //
14823 // Here callee(1) is unresolved at the call site, but is not inside a
14824 // dependent context. There will be no further attempt to resolve this
14825 // call if it is made dependent.
14826
14827 if (const auto *TP =
14828 FDecl->getTemplateInstantiationPattern(/*ForDefinition=*/false);
14829 TP && TP->willHaveBody() && CurContext->isDependentContext()) {
14830 return CallExpr::Create(Context, Fn, Args, Context.DependentTy,
14831 VK_PRValue, RParenLoc, CurFPFeatureOverrides());
14832 }
14833 }
14834 }
14835
14836 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
14837 ExecConfig, &CandidateSet, &Best,
14838 OverloadResult, AllowTypoCorrection);
14839}
14840
14844 const UnresolvedSetImpl &Fns,
14845 bool PerformADL) {
14847 Context, NamingClass, NNSLoc, DNI, PerformADL, Fns.begin(), Fns.end(),
14848 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
14849}
14850
14853 bool HadMultipleCandidates) {
14854 // FoundDecl can be the TemplateDecl of Method. Don't retain a template in
14855 // the FoundDecl as it impedes TransformMemberExpr.
14856 // We go a bit further here: if there's no difference in UnderlyingDecl,
14857 // then using FoundDecl vs Method shouldn't make a difference either.
14858 if (FoundDecl->getUnderlyingDecl() == FoundDecl)
14859 FoundDecl = Method;
14860 // Convert the expression to match the conversion function's implicit object
14861 // parameter.
14862 ExprResult Exp;
14863 if (Method->isExplicitObjectMemberFunction())
14865 else
14867 E, /*Qualifier=*/std::nullopt, FoundDecl, Method);
14868 if (Exp.isInvalid())
14869 return true;
14870
14871 if (Method->getParent()->isLambda() &&
14872 Method->getConversionType()->isBlockPointerType()) {
14873 // This is a lambda conversion to block pointer; check if the argument
14874 // was a LambdaExpr.
14875 Expr *SubE = E;
14876 auto *CE = dyn_cast<CastExpr>(SubE);
14877 if (CE && CE->getCastKind() == CK_NoOp)
14878 SubE = CE->getSubExpr();
14879 SubE = SubE->IgnoreParens();
14880 if (auto *BE = dyn_cast<CXXBindTemporaryExpr>(SubE))
14881 SubE = BE->getSubExpr();
14882 if (isa<LambdaExpr>(SubE)) {
14883 // For the conversion to block pointer on a lambda expression, we
14884 // construct a special BlockLiteral instead; this doesn't really make
14885 // a difference in ARC, but outside of ARC the resulting block literal
14886 // follows the normal lifetime rules for block literals instead of being
14887 // autoreleased.
14891 Exp.get()->getExprLoc(), Exp.get()->getExprLoc(), Method, Exp.get());
14893
14894 // FIXME: This note should be produced by a CodeSynthesisContext.
14895 if (BlockExp.isInvalid())
14896 Diag(Exp.get()->getExprLoc(), diag::note_lambda_to_block_conv);
14897 return BlockExp;
14898 }
14899 }
14900 CallExpr *CE;
14901 QualType ResultType = Method->getReturnType();
14903 ResultType = ResultType.getNonLValueExprType(Context);
14904 if (Method->isExplicitObjectMemberFunction()) {
14905 ExprResult FnExpr =
14906 CreateFunctionRefExpr(*this, Method, FoundDecl, Exp.get(),
14907 HadMultipleCandidates, E->getBeginLoc());
14908 if (FnExpr.isInvalid())
14909 return ExprError();
14910 Expr *ObjectParam = Exp.get();
14911 CE = CallExpr::Create(Context, FnExpr.get(), MultiExprArg(&ObjectParam, 1),
14912 ResultType, VK, Exp.get()->getEndLoc(),
14914 CE->setUsesMemberSyntax(true);
14915 } else {
14916 MemberExpr *ME =
14917 BuildMemberExpr(Exp.get(), /*IsArrow=*/false, SourceLocation(),
14919 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()),
14920 HadMultipleCandidates, DeclarationNameInfo(),
14921 Context.BoundMemberTy, VK_PRValue, OK_Ordinary);
14922
14923 CE = CXXMemberCallExpr::Create(Context, ME, /*Args=*/{}, ResultType, VK,
14924 Exp.get()->getEndLoc(),
14926 }
14927
14928 if (CheckFunctionCall(Method, CE,
14929 Method->getType()->castAs<FunctionProtoType>()))
14930 return ExprError();
14931
14933}
14934
14937 const UnresolvedSetImpl &Fns,
14938 Expr *Input, bool PerformADL) {
14940 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
14941 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
14942 // TODO: provide better source location info.
14943 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
14944
14945 if (checkPlaceholderForOverload(*this, Input))
14946 return ExprError();
14947
14948 Expr *Args[2] = { Input, nullptr };
14949 unsigned NumArgs = 1;
14950
14951 // For post-increment and post-decrement, add the implicit '0' as
14952 // the second argument, so that we know this is a post-increment or
14953 // post-decrement.
14954 if (Opc == UO_PostInc || Opc == UO_PostDec) {
14955 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
14956 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
14957 SourceLocation());
14958 NumArgs = 2;
14959 }
14960
14961 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
14962
14963 if (Input->isTypeDependent()) {
14965 // [C++26][expr.unary.op][expr.pre.incr]
14966 // The * operator yields an lvalue of type
14967 // The pre/post increment operators yied an lvalue.
14968 if (Opc == UO_PreDec || Opc == UO_PreInc || Opc == UO_Deref)
14969 VK = VK_LValue;
14970
14971 if (Fns.empty())
14972 return UnaryOperator::Create(Context, Input, Opc, Context.DependentTy, VK,
14973 OK_Ordinary, OpLoc, false,
14975
14976 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
14978 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns);
14979 if (Fn.isInvalid())
14980 return ExprError();
14981 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), ArgsArray,
14982 Context.DependentTy, VK_PRValue, OpLoc,
14984 }
14985
14986 // Build an empty overload set.
14988
14989 // Add the candidates from the given function set.
14990 AddNonMemberOperatorCandidates(Fns, ArgsArray, CandidateSet);
14991
14992 // Add operator candidates that are member functions.
14993 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
14994
14995 // Add candidates from ADL.
14996 if (PerformADL) {
14997 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
14998 /*ExplicitTemplateArgs*/nullptr,
14999 CandidateSet);
15000 }
15001
15002 // Add builtin operator candidates.
15003 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
15004
15005 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15006
15007 // Perform overload resolution.
15009 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15010 case OR_Success: {
15011 // We found a built-in operator or an overloaded operator.
15012 FunctionDecl *FnDecl = Best->Function;
15013
15014 if (FnDecl) {
15015 Expr *Base = nullptr;
15016 // We matched an overloaded operator. Build a call to that
15017 // operator.
15018
15019 // Convert the arguments.
15020 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15021 CheckMemberOperatorAccess(OpLoc, Input, nullptr, Best->FoundDecl);
15022
15023 ExprResult InputInit;
15024 if (Method->isExplicitObjectMemberFunction())
15025 InputInit = InitializeExplicitObjectArgument(*this, Input, Method);
15026 else
15028 Input, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15029 if (InputInit.isInvalid())
15030 return ExprError();
15031 Base = Input = InputInit.get();
15032 } else {
15033 // Convert the arguments.
15034 ExprResult InputInit
15036 Context,
15037 FnDecl->getParamDecl(0)),
15039 Input);
15040 if (InputInit.isInvalid())
15041 return ExprError();
15042 Input = InputInit.get();
15043 }
15044
15045 // Build the actual expression node.
15046 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
15047 Base, HadMultipleCandidates,
15048 OpLoc);
15049 if (FnExpr.isInvalid())
15050 return ExprError();
15051
15052 // Determine the result type.
15053 QualType ResultTy = FnDecl->getReturnType();
15055 ResultTy = ResultTy.getNonLValueExprType(Context);
15056
15057 Args[0] = Input;
15059 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
15061 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15062
15063 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
15064 return ExprError();
15065
15066 if (CheckFunctionCall(FnDecl, TheCall,
15067 FnDecl->getType()->castAs<FunctionProtoType>()))
15068 return ExprError();
15069 return CheckForImmediateInvocation(MaybeBindToTemporary(TheCall), FnDecl);
15070 } else {
15071 // We matched a built-in operator. Convert the arguments, then
15072 // break out so that we will build the appropriate built-in
15073 // operator node.
15075 Input, Best->BuiltinParamTypes[0], Best->Conversions[0],
15078 if (InputRes.isInvalid())
15079 return ExprError();
15080 Input = InputRes.get();
15081 break;
15082 }
15083 }
15084
15086 // This is an erroneous use of an operator which can be overloaded by
15087 // a non-member function. Check for non-member operators which were
15088 // defined too late to be candidates.
15089 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
15090 // FIXME: Recover by calling the found function.
15091 return ExprError();
15092
15093 // No viable function; fall through to handling this as a
15094 // built-in operator, which will produce an error message for us.
15095 break;
15096
15097 case OR_Ambiguous:
15098 CandidateSet.NoteCandidates(
15099 PartialDiagnosticAt(OpLoc,
15100 PDiag(diag::err_ovl_ambiguous_oper_unary)
15102 << Input->getType() << Input->getSourceRange()),
15103 *this, OCD_AmbiguousCandidates, ArgsArray,
15104 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15105 return ExprError();
15106
15107 case OR_Deleted: {
15108 // CreateOverloadedUnaryOp fills the first element of ArgsArray with the
15109 // object whose method was called. Later in NoteCandidates size of ArgsArray
15110 // is passed further and it eventually ends up compared to number of
15111 // function candidate parameters which never includes the object parameter,
15112 // so slice ArgsArray to make sure apples are compared to apples.
15113 StringLiteral *Msg = Best->Function->getDeletedMessage();
15114 CandidateSet.NoteCandidates(
15115 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
15117 << (Msg != nullptr)
15118 << (Msg ? Msg->getString() : StringRef())
15119 << Input->getSourceRange()),
15120 *this, OCD_AllCandidates, ArgsArray.drop_front(),
15121 UnaryOperator::getOpcodeStr(Opc), OpLoc);
15122 return ExprError();
15123 }
15124 }
15125
15126 // Either we found no viable overloaded operator or we matched a
15127 // built-in operator. In either case, fall through to trying to
15128 // build a built-in operation.
15129 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
15130}
15131
15134 const UnresolvedSetImpl &Fns,
15135 ArrayRef<Expr *> Args, bool PerformADL) {
15136 SourceLocation OpLoc = CandidateSet.getLocation();
15137
15138 OverloadedOperatorKind ExtraOp =
15141 : OO_None;
15142
15143 // Add the candidates from the given function set. This also adds the
15144 // rewritten candidates using these functions if necessary.
15145 AddNonMemberOperatorCandidates(Fns, Args, CandidateSet);
15146
15147 // As template candidates are not deduced immediately,
15148 // persist the array in the overload set.
15149 ArrayRef<Expr *> ReversedArgs;
15150 if (CandidateSet.getRewriteInfo().allowsReversed(Op) ||
15151 CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15152 ReversedArgs = CandidateSet.getPersistentArgsArray(Args[1], Args[0]);
15153
15154 // Add operator candidates that are member functions.
15155 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15156 if (CandidateSet.getRewriteInfo().allowsReversed(Op))
15157 AddMemberOperatorCandidates(Op, OpLoc, ReversedArgs, CandidateSet,
15159
15160 // In C++20, also add any rewritten member candidates.
15161 if (ExtraOp) {
15162 AddMemberOperatorCandidates(ExtraOp, OpLoc, Args, CandidateSet);
15163 if (CandidateSet.getRewriteInfo().allowsReversed(ExtraOp))
15164 AddMemberOperatorCandidates(ExtraOp, OpLoc, ReversedArgs, CandidateSet,
15166 }
15167
15168 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
15169 // performed for an assignment operator (nor for operator[] nor operator->,
15170 // which don't get here).
15171 if (Op != OO_Equal && PerformADL) {
15172 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15173 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
15174 /*ExplicitTemplateArgs*/ nullptr,
15175 CandidateSet);
15176 if (ExtraOp) {
15177 DeclarationName ExtraOpName =
15178 Context.DeclarationNames.getCXXOperatorName(ExtraOp);
15179 AddArgumentDependentLookupCandidates(ExtraOpName, OpLoc, Args,
15180 /*ExplicitTemplateArgs*/ nullptr,
15181 CandidateSet);
15182 }
15183 }
15184
15185 // Add builtin operator candidates.
15186 //
15187 // FIXME: We don't add any rewritten candidates here. This is strictly
15188 // incorrect; a builtin candidate could be hidden by a non-viable candidate,
15189 // resulting in our selecting a rewritten builtin candidate. For example:
15190 //
15191 // enum class E { e };
15192 // bool operator!=(E, E) requires false;
15193 // bool k = E::e != E::e;
15194 //
15195 // ... should select the rewritten builtin candidate 'operator==(E, E)'. But
15196 // it seems unreasonable to consider rewritten builtin candidates. A core
15197 // issue has been filed proposing to removed this requirement.
15198 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
15199}
15200
15203 const UnresolvedSetImpl &Fns, Expr *LHS,
15204 Expr *RHS, bool PerformADL,
15205 bool AllowRewrittenCandidates,
15206 FunctionDecl *DefaultedFn) {
15207 Expr *Args[2] = { LHS, RHS };
15208 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
15209
15210 if (!getLangOpts().CPlusPlus20)
15211 AllowRewrittenCandidates = false;
15212
15214
15215 // If either side is type-dependent, create an appropriate dependent
15216 // expression.
15217 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
15218 if (Fns.empty()) {
15219 // If there are no functions to store, just build a dependent
15220 // BinaryOperator or CompoundAssignment.
15223 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_LValue,
15224 OK_Ordinary, OpLoc, CurFPFeatureOverrides(), Context.DependentTy,
15225 Context.DependentTy);
15227 Context, Args[0], Args[1], Opc, Context.DependentTy, VK_PRValue,
15229 }
15230
15231 // FIXME: save results of ADL from here?
15232 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15233 // TODO: provide better source location info in DNLoc component.
15234 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
15235 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
15237 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, Fns, PerformADL);
15238 if (Fn.isInvalid())
15239 return ExprError();
15240 return CXXOperatorCallExpr::Create(Context, Op, Fn.get(), Args,
15241 Context.DependentTy, VK_PRValue, OpLoc,
15243 }
15244
15245 // If this is the .* operator, which is not overloadable, just
15246 // create a built-in binary operator.
15247 if (Opc == BO_PtrMemD) {
15248 auto CheckPlaceholder = [&](Expr *&Arg) {
15250 if (Res.isUsable())
15251 Arg = Res.get();
15252 return !Res.isUsable();
15253 };
15254
15255 // CreateBuiltinBinOp() doesn't like it if we tell it to create a '.*'
15256 // expression that contains placeholders (in either the LHS or RHS).
15257 if (CheckPlaceholder(Args[0]) || CheckPlaceholder(Args[1]))
15258 return ExprError();
15259 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15260 }
15261
15262 // Always do placeholder-like conversions on the RHS.
15263 if (checkPlaceholderForOverload(*this, Args[1]))
15264 return ExprError();
15265
15266 // Do placeholder-like conversion on the LHS; note that we should
15267 // not get here with a PseudoObject LHS.
15268 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
15269 if (checkPlaceholderForOverload(*this, Args[0]))
15270 return ExprError();
15271
15272 // If this is the assignment operator, we only perform overload resolution
15273 // if the left-hand side is a class or enumeration type. This is actually
15274 // a hack. The standard requires that we do overload resolution between the
15275 // various built-in candidates, but as DR507 points out, this can lead to
15276 // problems. So we do it this way, which pretty much follows what GCC does.
15277 // Note that we go the traditional code path for compound assignment forms.
15278 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
15279 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15280
15281 // Build the overload set.
15284 Op, OpLoc, AllowRewrittenCandidates));
15285 if (DefaultedFn)
15286 CandidateSet.exclude(DefaultedFn);
15287 LookupOverloadedBinOp(CandidateSet, Op, Fns, Args, PerformADL);
15288
15289 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15290
15291 // Perform overload resolution.
15293 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
15294 case OR_Success: {
15295 // We found a built-in operator or an overloaded operator.
15296 FunctionDecl *FnDecl = Best->Function;
15297
15298 bool IsReversed = Best->isReversed();
15299 if (IsReversed)
15300 std::swap(Args[0], Args[1]);
15301
15302 if (FnDecl) {
15303
15304 if (FnDecl->isInvalidDecl())
15305 return ExprError();
15306
15307 Expr *Base = nullptr;
15308 // We matched an overloaded operator. Build a call to that
15309 // operator.
15310
15311 OverloadedOperatorKind ChosenOp =
15313
15314 // C++2a [over.match.oper]p9:
15315 // If a rewritten operator== candidate is selected by overload
15316 // resolution for an operator@, its return type shall be cv bool
15317 if (Best->RewriteKind && ChosenOp == OO_EqualEqual &&
15318 !FnDecl->getReturnType()->isBooleanType()) {
15319 bool IsExtension =
15321 Diag(OpLoc, IsExtension ? diag::ext_ovl_rewrite_equalequal_not_bool
15322 : diag::err_ovl_rewrite_equalequal_not_bool)
15323 << FnDecl->getReturnType() << BinaryOperator::getOpcodeStr(Opc)
15324 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15325 Diag(FnDecl->getLocation(), diag::note_declared_at);
15326 if (!IsExtension)
15327 return ExprError();
15328 }
15329
15330 if (AllowRewrittenCandidates && !IsReversed &&
15331 CandidateSet.getRewriteInfo().isReversible()) {
15332 // We could have reversed this operator, but didn't. Check if some
15333 // reversed form was a viable candidate, and if so, if it had a
15334 // better conversion for either parameter. If so, this call is
15335 // formally ambiguous, and allowing it is an extension.
15337 for (OverloadCandidate &Cand : CandidateSet) {
15338 if (Cand.Viable && Cand.Function && Cand.isReversed() &&
15339 allowAmbiguity(Context, Cand.Function, FnDecl)) {
15340 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
15342 *this, OpLoc, Cand.Conversions[ArgIdx],
15343 Best->Conversions[ArgIdx]) ==
15345 AmbiguousWith.push_back(Cand.Function);
15346 break;
15347 }
15348 }
15349 }
15350 }
15351
15352 if (!AmbiguousWith.empty()) {
15353 bool AmbiguousWithSelf =
15354 AmbiguousWith.size() == 1 &&
15355 declaresSameEntity(AmbiguousWith.front(), FnDecl);
15356 Diag(OpLoc, diag::ext_ovl_ambiguous_oper_binary_reversed)
15358 << Args[0]->getType() << Args[1]->getType() << AmbiguousWithSelf
15359 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15360 if (AmbiguousWithSelf) {
15361 Diag(FnDecl->getLocation(),
15362 diag::note_ovl_ambiguous_oper_binary_reversed_self);
15363 // Mark member== const or provide matching != to disallow reversed
15364 // args. Eg.
15365 // struct S { bool operator==(const S&); };
15366 // S()==S();
15367 if (auto *MD = dyn_cast<CXXMethodDecl>(FnDecl))
15368 if (Op == OverloadedOperatorKind::OO_EqualEqual &&
15369 !MD->isConst() &&
15370 !MD->hasCXXExplicitFunctionObjectParameter() &&
15371 Context.hasSameUnqualifiedType(
15372 MD->getFunctionObjectParameterType(),
15373 MD->getParamDecl(0)->getType().getNonReferenceType()) &&
15374 Context.hasSameUnqualifiedType(
15375 MD->getFunctionObjectParameterType(),
15376 Args[0]->getType()) &&
15377 Context.hasSameUnqualifiedType(
15378 MD->getFunctionObjectParameterType(),
15379 Args[1]->getType()))
15380 Diag(FnDecl->getLocation(),
15381 diag::note_ovl_ambiguous_eqeq_reversed_self_non_const);
15382 } else {
15383 Diag(FnDecl->getLocation(),
15384 diag::note_ovl_ambiguous_oper_binary_selected_candidate);
15385 for (auto *F : AmbiguousWith)
15386 Diag(F->getLocation(),
15387 diag::note_ovl_ambiguous_oper_binary_reversed_candidate);
15388 }
15389 }
15390 }
15391
15392 // Check for nonnull = nullable.
15393 // This won't be caught in the arg's initialization: the parameter to
15394 // the assignment operator is not marked nonnull.
15395 if (Op == OO_Equal)
15397 Args[1]->getType(), OpLoc);
15398
15399 // Convert the arguments.
15400 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
15401 // Best->Access is only meaningful for class members.
15402 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
15403
15404 ExprResult Arg0, Arg1;
15405 unsigned ParamIdx = 0;
15406 if (Method->isExplicitObjectMemberFunction()) {
15407 Arg0 = InitializeExplicitObjectArgument(*this, Args[0], FnDecl);
15408 ParamIdx = 1;
15409 } else {
15411 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15412 }
15415 Context, FnDecl->getParamDecl(ParamIdx)),
15416 SourceLocation(), Args[1]);
15417 if (Arg0.isInvalid() || Arg1.isInvalid())
15418 return ExprError();
15419
15420 Base = Args[0] = Arg0.getAs<Expr>();
15421 Args[1] = RHS = Arg1.getAs<Expr>();
15422 } else {
15423 // Convert the arguments.
15426 FnDecl->getParamDecl(0)),
15427 SourceLocation(), Args[0]);
15428 if (Arg0.isInvalid())
15429 return ExprError();
15430
15431 ExprResult Arg1 =
15434 FnDecl->getParamDecl(1)),
15435 SourceLocation(), Args[1]);
15436 if (Arg1.isInvalid())
15437 return ExprError();
15438 Args[0] = LHS = Arg0.getAs<Expr>();
15439 Args[1] = RHS = Arg1.getAs<Expr>();
15440 }
15441
15442 // Build the actual expression node.
15443 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
15444 Best->FoundDecl, Base,
15445 HadMultipleCandidates, OpLoc);
15446 if (FnExpr.isInvalid())
15447 return ExprError();
15448
15449 // Determine the result type.
15450 QualType ResultTy = FnDecl->getReturnType();
15452 ResultTy = ResultTy.getNonLValueExprType(Context);
15453
15454 CallExpr *TheCall;
15455 ArrayRef<const Expr *> ArgsArray(Args, 2);
15456 const Expr *ImplicitThis = nullptr;
15457
15458 // We always create a CXXOperatorCallExpr, even for explicit object
15459 // members; CodeGen should take care not to emit the this pointer.
15461 Context, ChosenOp, FnExpr.get(), Args, ResultTy, VK, OpLoc,
15463 static_cast<CallExpr::ADLCallKind>(Best->IsADLCandidate));
15464
15465 if (const auto *Method = dyn_cast<CXXMethodDecl>(FnDecl);
15466 Method && Method->isImplicitObjectMemberFunction()) {
15467 // Cut off the implicit 'this'.
15468 ImplicitThis = ArgsArray[0];
15469 ArgsArray = ArgsArray.slice(1);
15470 }
15471
15472 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
15473 FnDecl))
15474 return ExprError();
15475
15476 if (Op == OO_Equal) {
15477 // Check for a self move.
15478 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
15479 // lifetime check.
15481 *this, AssignedEntity{Args[0], dyn_cast<CXXMethodDecl>(FnDecl)},
15482 Args[1]);
15483 }
15484 if (ImplicitThis) {
15485 QualType ThisType = Context.getPointerType(ImplicitThis->getType());
15486 QualType ThisTypeFromDecl = Context.getPointerType(
15487 cast<CXXMethodDecl>(FnDecl)->getFunctionObjectParameterType());
15488
15489 CheckArgAlignment(OpLoc, FnDecl, "'this'", ThisType,
15490 ThisTypeFromDecl);
15491 }
15492
15493 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
15494 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
15496
15497 ExprResult R = MaybeBindToTemporary(TheCall);
15498 if (R.isInvalid())
15499 return ExprError();
15500
15501 R = CheckForImmediateInvocation(R, FnDecl);
15502 if (R.isInvalid())
15503 return ExprError();
15504
15505 // For a rewritten candidate, we've already reversed the arguments
15506 // if needed. Perform the rest of the rewrite now.
15507 if ((Best->RewriteKind & CRK_DifferentOperator) ||
15508 (Op == OO_Spaceship && IsReversed)) {
15509 if (Op == OO_ExclaimEqual) {
15510 assert(ChosenOp == OO_EqualEqual && "unexpected operator name");
15511 R = CreateBuiltinUnaryOp(OpLoc, UO_LNot, R.get());
15512 } else {
15513 assert(ChosenOp == OO_Spaceship && "unexpected operator name");
15514 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
15515 Expr *ZeroLiteral =
15517
15520 Ctx.Entity = FnDecl;
15522
15524 OpLoc, Opc, Fns, IsReversed ? ZeroLiteral : R.get(),
15525 IsReversed ? R.get() : ZeroLiteral, /*PerformADL=*/true,
15526 /*AllowRewrittenCandidates=*/false);
15527
15529 }
15530 if (R.isInvalid())
15531 return ExprError();
15532 } else {
15533 assert(ChosenOp == Op && "unexpected operator name");
15534 }
15535
15536 // Make a note in the AST if we did any rewriting.
15537 if (Best->RewriteKind != CRK_None)
15538 R = new (Context) CXXRewrittenBinaryOperator(R.get(), IsReversed);
15539
15540 return R;
15541 } else {
15542 // We matched a built-in operator. Convert the arguments, then
15543 // break out so that we will build the appropriate built-in
15544 // operator node.
15546 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15549 if (ArgsRes0.isInvalid())
15550 return ExprError();
15551 Args[0] = ArgsRes0.get();
15552
15554 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15557 if (ArgsRes1.isInvalid())
15558 return ExprError();
15559 Args[1] = ArgsRes1.get();
15560 break;
15561 }
15562 }
15563
15564 case OR_No_Viable_Function: {
15565 // C++ [over.match.oper]p9:
15566 // If the operator is the operator , [...] and there are no
15567 // viable functions, then the operator is assumed to be the
15568 // built-in operator and interpreted according to clause 5.
15569 if (Opc == BO_Comma)
15570 break;
15571
15572 // When defaulting an 'operator<=>', we can try to synthesize a three-way
15573 // compare result using '==' and '<'.
15574 if (DefaultedFn && Opc == BO_Cmp) {
15575 ExprResult E = BuildSynthesizedThreeWayComparison(OpLoc, Fns, Args[0],
15576 Args[1], DefaultedFn);
15577 if (E.isInvalid() || E.isUsable())
15578 return E;
15579 }
15580
15581 // For class as left operand for assignment or compound assignment
15582 // operator do not fall through to handling in built-in, but report that
15583 // no overloaded assignment operator found
15585 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
15586 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
15587 Args, OpLoc);
15588 DeferDiagsRAII DDR(*this,
15589 CandidateSet.shouldDeferDiags(*this, Args, OpLoc));
15590 if (Args[0]->getType()->isRecordType() &&
15591 Opc >= BO_Assign && Opc <= BO_OrAssign) {
15592 Diag(OpLoc, diag::err_ovl_no_viable_oper)
15594 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15595 if (Args[0]->getType()->isIncompleteType()) {
15596 Diag(OpLoc, diag::note_assign_lhs_incomplete)
15597 << Args[0]->getType()
15598 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
15599 }
15600 } else {
15601 // This is an erroneous use of an operator which can be overloaded by
15602 // a non-member function. Check for non-member operators which were
15603 // defined too late to be candidates.
15604 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
15605 // FIXME: Recover by calling the found function.
15606 return ExprError();
15607
15608 // No viable function; try to create a built-in operation, which will
15609 // produce an error. Then, show the non-viable candidates.
15610 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15611 }
15612 assert(Result.isInvalid() &&
15613 "C++ binary operator overloading is missing candidates!");
15614 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
15615 return Result;
15616 }
15617
15618 case OR_Ambiguous:
15619 CandidateSet.NoteCandidates(
15620 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15622 << Args[0]->getType()
15623 << Args[1]->getType()
15624 << Args[0]->getSourceRange()
15625 << Args[1]->getSourceRange()),
15627 OpLoc);
15628 return ExprError();
15629
15630 case OR_Deleted: {
15631 if (isImplicitlyDeleted(Best->Function)) {
15632 FunctionDecl *DeletedFD = Best->Function;
15634 if (DFK.isSpecialMember()) {
15635 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
15636 << Args[0]->getType() << DFK.asSpecialMember();
15637 } else {
15638 assert(DFK.isComparison());
15639 Diag(OpLoc, diag::err_ovl_deleted_comparison)
15640 << Args[0]->getType() << DeletedFD;
15641 }
15642
15643 // The user probably meant to call this special member. Just
15644 // explain why it's deleted.
15645 NoteDeletedFunction(DeletedFD);
15646 return ExprError();
15647 }
15648
15649 StringLiteral *Msg = Best->Function->getDeletedMessage();
15650 CandidateSet.NoteCandidates(
15652 OpLoc,
15653 PDiag(diag::err_ovl_deleted_oper)
15654 << getOperatorSpelling(Best->Function->getDeclName()
15655 .getCXXOverloadedOperator())
15656 << (Msg != nullptr) << (Msg ? Msg->getString() : StringRef())
15657 << Args[0]->getSourceRange() << Args[1]->getSourceRange()),
15659 OpLoc);
15660 return ExprError();
15661 }
15662 }
15663
15664 // We matched a built-in operator; build it.
15665 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
15666}
15667
15669 SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS,
15670 FunctionDecl *DefaultedFn) {
15671 const ComparisonCategoryInfo *Info =
15672 Context.CompCategories.lookupInfoForType(DefaultedFn->getReturnType());
15673 // If we're not producing a known comparison category type, we can't
15674 // synthesize a three-way comparison. Let the caller diagnose this.
15675 if (!Info)
15676 return ExprResult((Expr*)nullptr);
15677
15678 // If we ever want to perform this synthesis more generally, we will need to
15679 // apply the temporary materialization conversion to the operands.
15680 assert(LHS->isGLValue() && RHS->isGLValue() &&
15681 "cannot use prvalue expressions more than once");
15682 Expr *OrigLHS = LHS;
15683 Expr *OrigRHS = RHS;
15684
15685 // Replace the LHS and RHS with OpaqueValueExprs; we're going to refer to
15686 // each of them multiple times below.
15687 LHS = new (Context)
15688 OpaqueValueExpr(LHS->getExprLoc(), LHS->getType(), LHS->getValueKind(),
15689 LHS->getObjectKind(), LHS);
15690 RHS = new (Context)
15691 OpaqueValueExpr(RHS->getExprLoc(), RHS->getType(), RHS->getValueKind(),
15692 RHS->getObjectKind(), RHS);
15693
15694 ExprResult Eq = CreateOverloadedBinOp(OpLoc, BO_EQ, Fns, LHS, RHS, true, true,
15695 DefaultedFn);
15696 if (Eq.isInvalid())
15697 return ExprError();
15698
15699 ExprResult Less = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, LHS, RHS, true,
15700 true, DefaultedFn);
15701 if (Less.isInvalid())
15702 return ExprError();
15703
15705 if (Info->isPartial()) {
15706 Greater = CreateOverloadedBinOp(OpLoc, BO_LT, Fns, RHS, LHS, true, true,
15707 DefaultedFn);
15708 if (Greater.isInvalid())
15709 return ExprError();
15710 }
15711
15712 // Form the list of comparisons we're going to perform.
15713 struct Comparison {
15714 ExprResult Cmp;
15716 } Comparisons[4] =
15722 };
15723
15724 int I = Info->isPartial() ? 3 : 2;
15725
15726 // Combine the comparisons with suitable conditional expressions.
15728 for (; I >= 0; --I) {
15729 // Build a reference to the comparison category constant.
15730 auto *VI = Info->lookupValueInfo(Comparisons[I].Result);
15731 // FIXME: Missing a constant for a comparison category. Diagnose this?
15732 if (!VI)
15733 return ExprResult((Expr*)nullptr);
15734 ExprResult ThisResult =
15736 if (ThisResult.isInvalid())
15737 return ExprError();
15738
15739 // Build a conditional unless this is the final case.
15740 if (Result.get()) {
15741 Result = ActOnConditionalOp(OpLoc, OpLoc, Comparisons[I].Cmp.get(),
15742 ThisResult.get(), Result.get());
15743 if (Result.isInvalid())
15744 return ExprError();
15745 } else {
15746 Result = ThisResult;
15747 }
15748 }
15749
15750 // Build a PseudoObjectExpr to model the rewriting of an <=> operator, and to
15751 // bind the OpaqueValueExprs before they're (repeatedly) used.
15752 Expr *SyntacticForm = BinaryOperator::Create(
15753 Context, OrigLHS, OrigRHS, BO_Cmp, Result.get()->getType(),
15754 Result.get()->getValueKind(), Result.get()->getObjectKind(), OpLoc,
15756 Expr *SemanticForm[] = {LHS, RHS, Result.get()};
15757 return PseudoObjectExpr::Create(Context, SyntacticForm, SemanticForm, 2);
15758}
15759
15761 Sema &S, SmallVectorImpl<Expr *> &MethodArgs, CXXMethodDecl *Method,
15762 MultiExprArg Args, SourceLocation LParenLoc) {
15763
15764 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
15765 unsigned NumParams = Proto->getNumParams();
15766 unsigned NumArgsSlots =
15767 MethodArgs.size() + std::max<unsigned>(Args.size(), NumParams);
15768 // Build the full argument list for the method call (the implicit object
15769 // parameter is placed at the beginning of the list).
15770 MethodArgs.reserve(MethodArgs.size() + NumArgsSlots);
15771 bool IsError = false;
15772 // Initialize the implicit object parameter.
15773 // Check the argument types.
15774 for (unsigned i = 0; i != NumParams; i++) {
15775 Expr *Arg;
15776 if (i < Args.size()) {
15777 Arg = Args[i];
15778 ExprResult InputInit =
15780 S.Context, Method->getParamDecl(i)),
15781 SourceLocation(), Arg);
15782 IsError |= InputInit.isInvalid();
15783 Arg = InputInit.getAs<Expr>();
15784 } else {
15785 ExprResult DefArg =
15786 S.BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
15787 if (DefArg.isInvalid()) {
15788 IsError = true;
15789 break;
15790 }
15791 Arg = DefArg.getAs<Expr>();
15792 }
15793
15794 MethodArgs.push_back(Arg);
15795 }
15796 return IsError;
15797}
15798
15800 SourceLocation RLoc,
15801 Expr *Base,
15802 MultiExprArg ArgExpr) {
15804 Args.push_back(Base);
15805 for (auto *e : ArgExpr) {
15806 Args.push_back(e);
15807 }
15808 DeclarationName OpName =
15809 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
15810
15811 SourceRange Range = ArgExpr.empty()
15812 ? SourceRange{}
15813 : SourceRange(ArgExpr.front()->getBeginLoc(),
15814 ArgExpr.back()->getEndLoc());
15815
15816 // If either side is type-dependent, create an appropriate dependent
15817 // expression.
15819
15820 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
15821 // CHECKME: no 'operator' keyword?
15822 DeclarationNameInfo OpNameInfo(OpName, LLoc);
15823 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15825 NamingClass, NestedNameSpecifierLoc(), OpNameInfo, UnresolvedSet<0>());
15826 if (Fn.isInvalid())
15827 return ExprError();
15828 // Can't add any actual overloads yet
15829
15830 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn.get(), Args,
15831 Context.DependentTy, VK_PRValue, RLoc,
15833 }
15834
15835 // Handle placeholders
15836 UnbridgedCastsSet UnbridgedCasts;
15837 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
15838 return ExprError();
15839 }
15840 // Build an empty overload set.
15842
15843 // Subscript can only be overloaded as a member function.
15844
15845 // Add operator candidates that are member functions.
15846 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15847
15848 // Add builtin operator candidates.
15849 if (Args.size() == 2)
15850 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
15851
15852 bool HadMultipleCandidates = (CandidateSet.size() > 1);
15853
15854 // Perform overload resolution.
15856 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
15857 case OR_Success: {
15858 // We found a built-in operator or an overloaded operator.
15859 FunctionDecl *FnDecl = Best->Function;
15860
15861 if (FnDecl) {
15862 // We matched an overloaded operator. Build a call to that
15863 // operator.
15864
15865 CheckMemberOperatorAccess(LLoc, Args[0], ArgExpr, Best->FoundDecl);
15866
15867 // Convert the arguments.
15869 SmallVector<Expr *, 2> MethodArgs;
15870
15871 // Initialize the object parameter.
15872 if (Method->isExplicitObjectMemberFunction()) {
15873 ExprResult Res =
15875 if (Res.isInvalid())
15876 return ExprError();
15877 Args[0] = Res.get();
15878 ArgExpr = Args;
15879 } else {
15881 Args[0], /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
15882 if (Arg0.isInvalid())
15883 return ExprError();
15884
15885 MethodArgs.push_back(Arg0.get());
15886 }
15887
15889 *this, MethodArgs, Method, ArgExpr, LLoc);
15890 if (IsError)
15891 return ExprError();
15892
15893 // Build the actual expression node.
15894 DeclarationNameInfo OpLocInfo(OpName, LLoc);
15895 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
15897 *this, FnDecl, Best->FoundDecl, Base, HadMultipleCandidates,
15898 OpLocInfo.getLoc(), OpLocInfo.getInfo());
15899 if (FnExpr.isInvalid())
15900 return ExprError();
15901
15902 // Determine the result type
15903 QualType ResultTy = FnDecl->getReturnType();
15905 ResultTy = ResultTy.getNonLValueExprType(Context);
15906
15908 Context, OO_Subscript, FnExpr.get(), MethodArgs, ResultTy, VK, RLoc,
15910
15911 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
15912 return ExprError();
15913
15914 if (CheckFunctionCall(Method, TheCall,
15915 Method->getType()->castAs<FunctionProtoType>()))
15916 return ExprError();
15917
15919 FnDecl);
15920 } else {
15921 // We matched a built-in operator. Convert the arguments, then
15922 // break out so that we will build the appropriate built-in
15923 // operator node.
15925 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
15928 if (ArgsRes0.isInvalid())
15929 return ExprError();
15930 Args[0] = ArgsRes0.get();
15931
15933 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
15936 if (ArgsRes1.isInvalid())
15937 return ExprError();
15938 Args[1] = ArgsRes1.get();
15939
15940 break;
15941 }
15942 }
15943
15944 case OR_No_Viable_Function: {
15946 CandidateSet.empty()
15947 ? (PDiag(diag::err_ovl_no_oper)
15948 << Args[0]->getType() << /*subscript*/ 0
15949 << Args[0]->getSourceRange() << Range)
15950 : (PDiag(diag::err_ovl_no_viable_subscript)
15951 << Args[0]->getType() << Args[0]->getSourceRange() << Range);
15952 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
15953 OCD_AllCandidates, ArgExpr, "[]", LLoc);
15954 return ExprError();
15955 }
15956
15957 case OR_Ambiguous:
15958 if (Args.size() == 2) {
15959 CandidateSet.NoteCandidates(
15961 LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
15962 << "[]" << Args[0]->getType() << Args[1]->getType()
15963 << Args[0]->getSourceRange() << Range),
15964 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15965 } else {
15966 CandidateSet.NoteCandidates(
15968 PDiag(diag::err_ovl_ambiguous_subscript_call)
15969 << Args[0]->getType()
15970 << Args[0]->getSourceRange() << Range),
15971 *this, OCD_AmbiguousCandidates, Args, "[]", LLoc);
15972 }
15973 return ExprError();
15974
15975 case OR_Deleted: {
15976 StringLiteral *Msg = Best->Function->getDeletedMessage();
15977 CandidateSet.NoteCandidates(
15979 PDiag(diag::err_ovl_deleted_oper)
15980 << "[]" << (Msg != nullptr)
15981 << (Msg ? Msg->getString() : StringRef())
15982 << Args[0]->getSourceRange() << Range),
15983 *this, OCD_AllCandidates, Args, "[]", LLoc);
15984 return ExprError();
15985 }
15986 }
15987
15988 // We matched a built-in operator; build it.
15989 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
15990}
15991
15993 SourceLocation LParenLoc,
15994 MultiExprArg Args,
15995 SourceLocation RParenLoc,
15996 Expr *ExecConfig, bool IsExecConfig,
15997 bool AllowRecovery) {
15998 assert(MemExprE->getType() == Context.BoundMemberTy ||
15999 MemExprE->getType() == Context.OverloadTy);
16000
16001 // Dig out the member expression. This holds both the object
16002 // argument and the member function we're referring to.
16003 Expr *NakedMemExpr = MemExprE->IgnoreParens();
16004
16005 // Determine whether this is a call to a pointer-to-member function.
16006 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
16007 assert(op->getType() == Context.BoundMemberTy);
16008 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
16009
16010 QualType fnType =
16011 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
16012
16013 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
16014 QualType resultType = proto->getCallResultType(Context);
16016
16017 // Check that the object type isn't more qualified than the
16018 // member function we're calling.
16019 Qualifiers funcQuals = proto->getMethodQuals();
16020
16021 QualType objectType = op->getLHS()->getType();
16022 if (op->getOpcode() == BO_PtrMemI)
16023 objectType = objectType->castAs<PointerType>()->getPointeeType();
16024 Qualifiers objectQuals = objectType.getQualifiers();
16025
16026 Qualifiers difference = objectQuals - funcQuals;
16027 difference.removeObjCGCAttr();
16028 difference.removeAddressSpace();
16029 if (difference) {
16030 std::string qualsString = difference.getAsString();
16031 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
16032 << fnType.getUnqualifiedType()
16033 << qualsString
16034 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
16035 }
16036
16038 Context, MemExprE, Args, resultType, valueKind, RParenLoc,
16040
16041 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
16042 call, nullptr))
16043 return ExprError();
16044
16045 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
16046 return ExprError();
16047
16048 if (CheckOtherCall(call, proto))
16049 return ExprError();
16050
16051 return MaybeBindToTemporary(call);
16052 }
16053
16054 // We only try to build a recovery expr at this level if we can preserve
16055 // the return type, otherwise we return ExprError() and let the caller
16056 // recover.
16057 auto BuildRecoveryExpr = [&](QualType Type) {
16058 if (!AllowRecovery)
16059 return ExprError();
16060 std::vector<Expr *> SubExprs = {MemExprE};
16061 llvm::append_range(SubExprs, Args);
16062 return CreateRecoveryExpr(MemExprE->getBeginLoc(), RParenLoc, SubExprs,
16063 Type);
16064 };
16065 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
16066 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_PRValue,
16067 RParenLoc, CurFPFeatureOverrides());
16068
16069 UnbridgedCastsSet UnbridgedCasts;
16070 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16071 return ExprError();
16072
16073 MemberExpr *MemExpr;
16074 CXXMethodDecl *Method = nullptr;
16075 bool HadMultipleCandidates = false;
16076 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
16077 NestedNameSpecifier Qualifier = std::nullopt;
16078 if (isa<MemberExpr>(NakedMemExpr)) {
16079 MemExpr = cast<MemberExpr>(NakedMemExpr);
16081 FoundDecl = MemExpr->getFoundDecl();
16082 Qualifier = MemExpr->getQualifier();
16083 UnbridgedCasts.restore();
16084 } else {
16085 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
16086 Qualifier = UnresExpr->getQualifier();
16087
16088 QualType ObjectType = UnresExpr->getBaseType();
16089 Expr::Classification ObjectClassification
16091 : UnresExpr->getBase()->Classify(Context);
16092
16093 // Add overload candidates
16094 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
16096
16097 // FIXME: avoid copy.
16098 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16099 if (UnresExpr->hasExplicitTemplateArgs()) {
16100 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
16101 TemplateArgs = &TemplateArgsBuffer;
16102 }
16103
16105 E = UnresExpr->decls_end(); I != E; ++I) {
16106
16107 QualType ExplicitObjectType = ObjectType;
16108
16109 NamedDecl *Func = *I;
16110 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
16112 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
16113
16114 bool HasExplicitParameter = false;
16115 if (const auto *M = dyn_cast<FunctionDecl>(Func);
16116 M && M->hasCXXExplicitFunctionObjectParameter())
16117 HasExplicitParameter = true;
16118 else if (const auto *M = dyn_cast<FunctionTemplateDecl>(Func);
16119 M &&
16120 M->getTemplatedDecl()->hasCXXExplicitFunctionObjectParameter())
16121 HasExplicitParameter = true;
16122
16123 if (HasExplicitParameter)
16124 ExplicitObjectType = GetExplicitObjectType(*this, UnresExpr);
16125
16126 // Microsoft supports direct constructor calls.
16127 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
16129 CandidateSet,
16130 /*SuppressUserConversions*/ false);
16131 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
16132 // If explicit template arguments were provided, we can't call a
16133 // non-template member function.
16134 if (TemplateArgs)
16135 continue;
16136
16137 AddMethodCandidate(Method, I.getPair(), ActingDC, ExplicitObjectType,
16138 ObjectClassification, Args, CandidateSet,
16139 /*SuppressUserConversions=*/false);
16140 } else {
16142 I.getPair(), ActingDC, TemplateArgs,
16143 ExplicitObjectType, ObjectClassification,
16144 Args, CandidateSet,
16145 /*SuppressUserConversions=*/false);
16146 }
16147 }
16148
16149 HadMultipleCandidates = (CandidateSet.size() > 1);
16150
16151 DeclarationName DeclName = UnresExpr->getMemberName();
16152
16153 UnbridgedCasts.restore();
16154
16156 bool Succeeded = false;
16157 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
16158 Best)) {
16159 case OR_Success:
16160 Method = cast<CXXMethodDecl>(Best->Function);
16161 FoundDecl = Best->FoundDecl;
16162 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
16163 if (DiagnoseUseOfOverloadedDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
16164 break;
16165 // If FoundDecl is different from Method (such as if one is a template
16166 // and the other a specialization), make sure DiagnoseUseOfDecl is
16167 // called on both.
16168 // FIXME: This would be more comprehensively addressed by modifying
16169 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
16170 // being used.
16171 if (Method != FoundDecl.getDecl() &&
16173 break;
16174 Succeeded = true;
16175 break;
16176
16178 CandidateSet.NoteCandidates(
16180 UnresExpr->getMemberLoc(),
16181 PDiag(diag::err_ovl_no_viable_member_function_in_call)
16182 << DeclName << MemExprE->getSourceRange()),
16183 *this, OCD_AllCandidates, Args);
16184 break;
16185 case OR_Ambiguous:
16186 CandidateSet.NoteCandidates(
16187 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
16188 PDiag(diag::err_ovl_ambiguous_member_call)
16189 << DeclName << MemExprE->getSourceRange()),
16190 *this, OCD_AmbiguousCandidates, Args);
16191 break;
16192 case OR_Deleted:
16194 UnresExpr->getMemberLoc(), MemExprE->getSourceRange(), DeclName,
16195 CandidateSet, Best->Function, Args, /*IsMember=*/true);
16196 break;
16197 }
16198 // Overload resolution fails, try to recover.
16199 if (!Succeeded)
16200 return BuildRecoveryExpr(chooseRecoveryType(CandidateSet, &Best));
16201
16202 ExprResult Res =
16203 FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
16204 if (Res.isInvalid())
16205 return ExprError();
16206 MemExprE = Res.get();
16207
16208 // If overload resolution picked a static member
16209 // build a non-member call based on that function.
16210 if (Method->isStatic()) {
16211 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args, RParenLoc,
16212 ExecConfig, IsExecConfig);
16213 }
16214
16215 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
16216 }
16217
16218 QualType ResultType = Method->getReturnType();
16220 ResultType = ResultType.getNonLValueExprType(Context);
16221
16222 assert(Method && "Member call to something that isn't a method?");
16223 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16224
16225 CallExpr *TheCall = nullptr;
16227 if (Method->isExplicitObjectMemberFunction()) {
16228 if (PrepareExplicitObjectArgument(*this, Method, MemExpr->getBase(), Args,
16229 NewArgs))
16230 return ExprError();
16231
16232 // Build the actual expression node.
16233 ExprResult FnExpr =
16234 CreateFunctionRefExpr(*this, Method, FoundDecl, MemExpr,
16235 HadMultipleCandidates, MemExpr->getExprLoc());
16236 if (FnExpr.isInvalid())
16237 return ExprError();
16238
16239 TheCall =
16240 CallExpr::Create(Context, FnExpr.get(), Args, ResultType, VK, RParenLoc,
16241 CurFPFeatureOverrides(), Proto->getNumParams());
16242 TheCall->setUsesMemberSyntax(true);
16243 } else {
16244 // Convert the object argument (for a non-static member function call).
16246 MemExpr->getBase(), Qualifier, FoundDecl, Method);
16247 if (ObjectArg.isInvalid())
16248 return ExprError();
16249 MemExpr->setBase(ObjectArg.get());
16250 TheCall = CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
16251 RParenLoc, CurFPFeatureOverrides(),
16252 Proto->getNumParams());
16253 }
16254
16255 // Check for a valid return type.
16256 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
16257 TheCall, Method))
16258 return BuildRecoveryExpr(ResultType);
16259
16260 // Convert the rest of the arguments
16261 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
16262 RParenLoc))
16263 return BuildRecoveryExpr(ResultType);
16264
16265 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16266
16267 if (CheckFunctionCall(Method, TheCall, Proto))
16268 return ExprError();
16269
16270 // In the case the method to call was not selected by the overloading
16271 // resolution process, we still need to handle the enable_if attribute. Do
16272 // that here, so it will not hide previous -- and more relevant -- errors.
16273 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
16274 if (const EnableIfAttr *Attr =
16275 CheckEnableIf(Method, LParenLoc, Args, true)) {
16276 Diag(MemE->getMemberLoc(),
16277 diag::err_ovl_no_viable_member_function_in_call)
16278 << Method << Method->getSourceRange();
16279 Diag(Method->getLocation(),
16280 diag::note_ovl_candidate_disabled_by_function_cond_attr)
16281 << Attr->getCond()->getSourceRange() << Attr->getMessage();
16282 return ExprError();
16283 }
16284 }
16285
16287 TheCall->getDirectCallee()->isPureVirtual()) {
16288 const FunctionDecl *MD = TheCall->getDirectCallee();
16289
16290 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
16292 Diag(MemExpr->getBeginLoc(),
16293 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
16295 << MD->getParent();
16296
16297 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
16298 if (getLangOpts().AppleKext)
16299 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
16300 << MD->getParent() << MD->getDeclName();
16301 }
16302 }
16303
16304 if (auto *DD = dyn_cast<CXXDestructorDecl>(TheCall->getDirectCallee())) {
16305 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
16306 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
16307 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
16308 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
16309 MemExpr->getMemberLoc());
16310 }
16311
16313 TheCall->getDirectCallee());
16314}
16315
16318 SourceLocation LParenLoc,
16319 MultiExprArg Args,
16320 SourceLocation RParenLoc) {
16321 if (checkPlaceholderForOverload(*this, Obj))
16322 return ExprError();
16323 ExprResult Object = Obj;
16324
16325 UnbridgedCastsSet UnbridgedCasts;
16326 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
16327 return ExprError();
16328
16329 assert(Object.get()->getType()->isRecordType() &&
16330 "Requires object type argument");
16331
16332 // C++ [over.call.object]p1:
16333 // If the primary-expression E in the function call syntax
16334 // evaluates to a class object of type "cv T", then the set of
16335 // candidate functions includes at least the function call
16336 // operators of T. The function call operators of T are obtained by
16337 // ordinary lookup of the name operator() in the context of
16338 // (E).operator().
16339 OverloadCandidateSet CandidateSet(LParenLoc,
16341 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
16342
16343 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
16344 diag::err_incomplete_object_call, Object.get()))
16345 return true;
16346
16347 auto *Record = Object.get()->getType()->castAsCXXRecordDecl();
16348 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
16351
16352 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16353 Oper != OperEnd; ++Oper) {
16354 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
16355 Object.get()->Classify(Context), Args, CandidateSet,
16356 /*SuppressUserConversion=*/false);
16357 }
16358
16359 // When calling a lambda, both the call operator, and
16360 // the conversion operator to function pointer
16361 // are considered. But when constraint checking
16362 // on the call operator fails, it will also fail on the
16363 // conversion operator as the constraints are always the same.
16364 // As the user probably does not intend to perform a surrogate call,
16365 // we filter them out to produce better error diagnostics, ie to avoid
16366 // showing 2 failed overloads instead of one.
16367 bool IgnoreSurrogateFunctions = false;
16368 if (CandidateSet.nonDeferredCandidatesCount() == 1 && Record->isLambda()) {
16369 const OverloadCandidate &Candidate = *CandidateSet.begin();
16370 if (!Candidate.Viable &&
16372 IgnoreSurrogateFunctions = true;
16373 }
16374
16375 // C++ [over.call.object]p2:
16376 // In addition, for each (non-explicit in C++0x) conversion function
16377 // declared in T of the form
16378 //
16379 // operator conversion-type-id () cv-qualifier;
16380 //
16381 // where cv-qualifier is the same cv-qualification as, or a
16382 // greater cv-qualification than, cv, and where conversion-type-id
16383 // denotes the type "pointer to function of (P1,...,Pn) returning
16384 // R", or the type "reference to pointer to function of
16385 // (P1,...,Pn) returning R", or the type "reference to function
16386 // of (P1,...,Pn) returning R", a surrogate call function [...]
16387 // is also considered as a candidate function. Similarly,
16388 // surrogate call functions are added to the set of candidate
16389 // functions for each conversion function declared in an
16390 // accessible base class provided the function is not hidden
16391 // within T by another intervening declaration.
16392 const auto &Conversions = Record->getVisibleConversionFunctions();
16393 for (auto I = Conversions.begin(), E = Conversions.end();
16394 !IgnoreSurrogateFunctions && I != E; ++I) {
16395 NamedDecl *D = *I;
16396 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
16397 if (isa<UsingShadowDecl>(D))
16398 D = cast<UsingShadowDecl>(D)->getTargetDecl();
16399
16400 // Skip over templated conversion functions; they aren't
16401 // surrogates.
16403 continue;
16404
16406 if (!Conv->isExplicit()) {
16407 // Strip the reference type (if any) and then the pointer type (if
16408 // any) to get down to what might be a function type.
16409 QualType ConvType = Conv->getConversionType().getNonReferenceType();
16410 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
16411 ConvType = ConvPtrType->getPointeeType();
16412
16413 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
16414 {
16415 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
16416 Object.get(), Args, CandidateSet);
16417 }
16418 }
16419 }
16420
16421 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16422
16423 // Perform overload resolution.
16425 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
16426 Best)) {
16427 case OR_Success:
16428 // Overload resolution succeeded; we'll build the appropriate call
16429 // below.
16430 break;
16431
16432 case OR_No_Viable_Function: {
16434 CandidateSet.empty()
16435 ? (PDiag(diag::err_ovl_no_oper)
16436 << Object.get()->getType() << /*call*/ 1
16437 << Object.get()->getSourceRange())
16438 : (PDiag(diag::err_ovl_no_viable_object_call)
16439 << Object.get()->getType() << Object.get()->getSourceRange());
16440 CandidateSet.NoteCandidates(
16441 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
16442 OCD_AllCandidates, Args);
16443 break;
16444 }
16445 case OR_Ambiguous:
16446 if (!R.isAmbiguous())
16447 CandidateSet.NoteCandidates(
16448 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16449 PDiag(diag::err_ovl_ambiguous_object_call)
16450 << Object.get()->getType()
16451 << Object.get()->getSourceRange()),
16452 *this, OCD_AmbiguousCandidates, Args);
16453 break;
16454
16455 case OR_Deleted: {
16456 // FIXME: Is this diagnostic here really necessary? It seems that
16457 // 1. we don't have any tests for this diagnostic, and
16458 // 2. we already issue err_deleted_function_use for this later on anyway.
16459 StringLiteral *Msg = Best->Function->getDeletedMessage();
16460 CandidateSet.NoteCandidates(
16461 PartialDiagnosticAt(Object.get()->getBeginLoc(),
16462 PDiag(diag::err_ovl_deleted_object_call)
16463 << Object.get()->getType() << (Msg != nullptr)
16464 << (Msg ? Msg->getString() : StringRef())
16465 << Object.get()->getSourceRange()),
16466 *this, OCD_AllCandidates, Args);
16467 break;
16468 }
16469 }
16470
16471 if (Best == CandidateSet.end())
16472 return true;
16473
16474 UnbridgedCasts.restore();
16475
16476 if (Best->Function == nullptr) {
16477 // Since there is no function declaration, this is one of the
16478 // surrogate candidates. Dig out the conversion function.
16479 CXXConversionDecl *Conv
16481 Best->Conversions[0].UserDefined.ConversionFunction);
16482
16483 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
16484 Best->FoundDecl);
16485 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
16486 return ExprError();
16487 assert(Conv == Best->FoundDecl.getDecl() &&
16488 "Found Decl & conversion-to-functionptr should be same, right?!");
16489 // We selected one of the surrogate functions that converts the
16490 // object parameter to a function pointer. Perform the conversion
16491 // on the object argument, then let BuildCallExpr finish the job.
16492
16493 // Create an implicit member expr to refer to the conversion operator.
16494 // and then call it.
16495 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
16496 Conv, HadMultipleCandidates);
16497 if (Call.isInvalid())
16498 return ExprError();
16499 // Record usage of conversion in an implicit cast.
16501 Context, Call.get()->getType(), CK_UserDefinedConversion, Call.get(),
16502 nullptr, VK_PRValue, CurFPFeatureOverrides());
16503
16504 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
16505 }
16506
16507 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
16508
16509 // We found an overloaded operator(). Build a CXXOperatorCallExpr
16510 // that calls this method, using Object for the implicit object
16511 // parameter and passing along the remaining arguments.
16512 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16513
16514 // An error diagnostic has already been printed when parsing the declaration.
16515 if (Method->isInvalidDecl())
16516 return ExprError();
16517
16518 const auto *Proto = Method->getType()->castAs<FunctionProtoType>();
16519 unsigned NumParams = Proto->getNumParams();
16520
16521 DeclarationNameInfo OpLocInfo(
16522 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
16523 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
16524 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16525 Obj, HadMultipleCandidates,
16526 OpLocInfo.getLoc(),
16527 OpLocInfo.getInfo());
16528 if (NewFn.isInvalid())
16529 return true;
16530
16531 SmallVector<Expr *, 8> MethodArgs;
16532 MethodArgs.reserve(NumParams + 1);
16533
16534 bool IsError = false;
16535
16536 // Initialize the object parameter.
16538 if (Method->isExplicitObjectMemberFunction()) {
16539 IsError |= PrepareExplicitObjectArgument(*this, Method, Obj, Args, NewArgs);
16540 } else {
16542 Object.get(), /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16543 if (ObjRes.isInvalid())
16544 IsError = true;
16545 else
16546 Object = ObjRes;
16547 MethodArgs.push_back(Object.get());
16548 }
16549
16551 *this, MethodArgs, Method, Args, LParenLoc);
16552
16553 // If this is a variadic call, handle args passed through "...".
16554 if (Proto->isVariadic()) {
16555 // Promote the arguments (C99 6.5.2.2p7).
16556 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
16558 Args[i], VariadicCallType::Method, nullptr);
16559 IsError |= Arg.isInvalid();
16560 MethodArgs.push_back(Arg.get());
16561 }
16562 }
16563
16564 if (IsError)
16565 return true;
16566
16567 DiagnoseSentinelCalls(Method, LParenLoc, Args);
16568
16569 // Once we've built TheCall, all of the expressions are properly owned.
16570 QualType ResultTy = Method->getReturnType();
16572 ResultTy = ResultTy.getNonLValueExprType(Context);
16573
16575 Context, OO_Call, NewFn.get(), MethodArgs, ResultTy, VK, RParenLoc,
16577
16578 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
16579 return true;
16580
16581 if (CheckFunctionCall(Method, TheCall, Proto))
16582 return true;
16583
16585}
16586
16588 SourceLocation OpLoc,
16589 bool *NoArrowOperatorFound) {
16590 assert(Base->getType()->isRecordType() &&
16591 "left-hand side must have class type");
16592
16594 return ExprError();
16595
16596 SourceLocation Loc = Base->getExprLoc();
16597
16598 // C++ [over.ref]p1:
16599 //
16600 // [...] An expression x->m is interpreted as (x.operator->())->m
16601 // for a class object x of type T if T::operator->() exists and if
16602 // the operator is selected as the best match function by the
16603 // overload resolution mechanism (13.3).
16604 DeclarationName OpName =
16605 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
16607
16608 if (RequireCompleteType(Loc, Base->getType(),
16609 diag::err_typecheck_incomplete_tag, Base))
16610 return ExprError();
16611
16612 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
16613 LookupQualifiedName(R, Base->getType()->castAsRecordDecl());
16615
16616 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
16617 Oper != OperEnd; ++Oper) {
16618 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
16619 {}, CandidateSet,
16620 /*SuppressUserConversion=*/false);
16621 }
16622
16623 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16624
16625 // Perform overload resolution.
16627 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
16628 case OR_Success:
16629 // Overload resolution succeeded; we'll build the call below.
16630 break;
16631
16632 case OR_No_Viable_Function: {
16633 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
16634 if (CandidateSet.empty()) {
16635 QualType BaseType = Base->getType();
16636 if (NoArrowOperatorFound) {
16637 // Report this specific error to the caller instead of emitting a
16638 // diagnostic, as requested.
16639 *NoArrowOperatorFound = true;
16640 return ExprError();
16641 }
16642 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
16643 << BaseType << Base->getSourceRange();
16644 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
16645 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
16646 << FixItHint::CreateReplacement(OpLoc, ".");
16647 }
16648 } else
16649 Diag(OpLoc, diag::err_ovl_no_viable_oper)
16650 << "operator->" << Base->getSourceRange();
16651 CandidateSet.NoteCandidates(*this, Base, Cands);
16652 return ExprError();
16653 }
16654 case OR_Ambiguous:
16655 if (!R.isAmbiguous())
16656 CandidateSet.NoteCandidates(
16657 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
16658 << "->" << Base->getType()
16659 << Base->getSourceRange()),
16661 return ExprError();
16662
16663 case OR_Deleted: {
16664 StringLiteral *Msg = Best->Function->getDeletedMessage();
16665 CandidateSet.NoteCandidates(
16666 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
16667 << "->" << (Msg != nullptr)
16668 << (Msg ? Msg->getString() : StringRef())
16669 << Base->getSourceRange()),
16670 *this, OCD_AllCandidates, Base);
16671 return ExprError();
16672 }
16673 }
16674
16675 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
16676
16677 // Convert the object parameter.
16678 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
16679
16680 if (Method->isExplicitObjectMemberFunction()) {
16682 if (R.isInvalid())
16683 return ExprError();
16684 Base = R.get();
16685 } else {
16687 Base, /*Qualifier=*/std::nullopt, Best->FoundDecl, Method);
16688 if (BaseResult.isInvalid())
16689 return ExprError();
16690 Base = BaseResult.get();
16691 }
16692
16693 // Build the operator call.
16694 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
16695 Base, HadMultipleCandidates, OpLoc);
16696 if (FnExpr.isInvalid())
16697 return ExprError();
16698
16699 QualType ResultTy = Method->getReturnType();
16701 ResultTy = ResultTy.getNonLValueExprType(Context);
16702
16703 CallExpr *TheCall =
16704 CXXOperatorCallExpr::Create(Context, OO_Arrow, FnExpr.get(), Base,
16705 ResultTy, VK, OpLoc, CurFPFeatureOverrides());
16706
16707 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
16708 return ExprError();
16709
16710 if (CheckFunctionCall(Method, TheCall,
16711 Method->getType()->castAs<FunctionProtoType>()))
16712 return ExprError();
16713
16715}
16716
16718 DeclarationNameInfo &SuffixInfo,
16719 ArrayRef<Expr*> Args,
16720 SourceLocation LitEndLoc,
16721 TemplateArgumentListInfo *TemplateArgs) {
16722 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
16723
16724 OverloadCandidateSet CandidateSet(UDSuffixLoc,
16726 AddNonMemberOperatorCandidates(R.asUnresolvedSet(), Args, CandidateSet,
16727 TemplateArgs);
16728
16729 bool HadMultipleCandidates = (CandidateSet.size() > 1);
16730
16731 // Perform overload resolution. This will usually be trivial, but might need
16732 // to perform substitutions for a literal operator template.
16734 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
16735 case OR_Success:
16736 case OR_Deleted:
16737 break;
16738
16740 CandidateSet.NoteCandidates(
16741 PartialDiagnosticAt(UDSuffixLoc,
16742 PDiag(diag::err_ovl_no_viable_function_in_call)
16743 << R.getLookupName()),
16744 *this, OCD_AllCandidates, Args);
16745 return ExprError();
16746
16747 case OR_Ambiguous:
16748 CandidateSet.NoteCandidates(
16749 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
16750 << R.getLookupName()),
16751 *this, OCD_AmbiguousCandidates, Args);
16752 return ExprError();
16753 }
16754
16755 FunctionDecl *FD = Best->Function;
16756 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
16757 nullptr, HadMultipleCandidates,
16758 SuffixInfo.getLoc(),
16759 SuffixInfo.getInfo());
16760 if (Fn.isInvalid())
16761 return true;
16762
16763 // Check the argument types. This should almost always be a no-op, except
16764 // that array-to-pointer decay is applied to string literals.
16765 Expr *ConvArgs[2];
16766 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
16769 SourceLocation(), Args[ArgIdx]);
16770 if (InputInit.isInvalid())
16771 return true;
16772 ConvArgs[ArgIdx] = InputInit.get();
16773 }
16774
16775 QualType ResultTy = FD->getReturnType();
16777 ResultTy = ResultTy.getNonLValueExprType(Context);
16778
16780 Context, Fn.get(), llvm::ArrayRef(ConvArgs, Args.size()), ResultTy, VK,
16781 LitEndLoc, UDSuffixLoc, CurFPFeatureOverrides());
16782
16783 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
16784 return ExprError();
16785
16786 if (CheckFunctionCall(FD, UDL, nullptr))
16787 return ExprError();
16788
16790}
16791
16794 SourceLocation RangeLoc,
16795 const DeclarationNameInfo &NameInfo,
16796 LookupResult &MemberLookup,
16797 OverloadCandidateSet *CandidateSet,
16798 Expr *Range, ExprResult *CallExpr) {
16799 Scope *S = nullptr;
16800
16802 if (!MemberLookup.empty()) {
16803 ExprResult MemberRef =
16804 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
16805 /*IsPtr=*/false, CXXScopeSpec(),
16806 /*TemplateKWLoc=*/SourceLocation(),
16807 /*FirstQualifierInScope=*/nullptr,
16808 MemberLookup,
16809 /*TemplateArgs=*/nullptr, S);
16810 if (MemberRef.isInvalid()) {
16811 *CallExpr = ExprError();
16812 return FRS_DiagnosticIssued;
16813 }
16814 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, {}, Loc, nullptr);
16815 if (CallExpr->isInvalid()) {
16816 *CallExpr = ExprError();
16817 return FRS_DiagnosticIssued;
16818 }
16819 } else {
16820 ExprResult FnR = CreateUnresolvedLookupExpr(/*NamingClass=*/nullptr,
16822 NameInfo, UnresolvedSet<0>());
16823 if (FnR.isInvalid())
16824 return FRS_DiagnosticIssued;
16826
16827 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
16828 CandidateSet, CallExpr);
16829 if (CandidateSet->empty() || CandidateSetError) {
16830 *CallExpr = ExprError();
16831 return FRS_NoViableFunction;
16832 }
16834 OverloadingResult OverloadResult =
16835 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
16836
16837 if (OverloadResult == OR_No_Viable_Function) {
16838 *CallExpr = ExprError();
16839 return FRS_NoViableFunction;
16840 }
16841 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
16842 Loc, nullptr, CandidateSet, &Best,
16843 OverloadResult,
16844 /*AllowTypoCorrection=*/false);
16845 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
16846 *CallExpr = ExprError();
16847 return FRS_DiagnosticIssued;
16848 }
16849 }
16850 return FRS_Success;
16851}
16852
16854 FunctionDecl *Fn) {
16855 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
16856 ExprResult SubExpr =
16857 FixOverloadedFunctionReference(PE->getSubExpr(), Found, Fn);
16858 if (SubExpr.isInvalid())
16859 return ExprError();
16860 if (SubExpr.get() == PE->getSubExpr())
16861 return PE;
16862
16863 return new (Context)
16864 ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr.get());
16865 }
16866
16867 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
16868 ExprResult SubExpr =
16869 FixOverloadedFunctionReference(ICE->getSubExpr(), Found, Fn);
16870 if (SubExpr.isInvalid())
16871 return ExprError();
16872 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
16873 SubExpr.get()->getType()) &&
16874 "Implicit cast type cannot be determined from overload");
16875 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
16876 if (SubExpr.get() == ICE->getSubExpr())
16877 return ICE;
16878
16879 return ImplicitCastExpr::Create(Context, ICE->getType(), ICE->getCastKind(),
16880 SubExpr.get(), nullptr, ICE->getValueKind(),
16882 }
16883
16884 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
16885 if (!GSE->isResultDependent()) {
16886 ExprResult SubExpr =
16887 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
16888 if (SubExpr.isInvalid())
16889 return ExprError();
16890 if (SubExpr.get() == GSE->getResultExpr())
16891 return GSE;
16892
16893 // Replace the resulting type information before rebuilding the generic
16894 // selection expression.
16895 ArrayRef<Expr *> A = GSE->getAssocExprs();
16896 SmallVector<Expr *, 4> AssocExprs(A);
16897 unsigned ResultIdx = GSE->getResultIndex();
16898 AssocExprs[ResultIdx] = SubExpr.get();
16899
16900 if (GSE->isExprPredicate())
16902 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
16903 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16904 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16905 ResultIdx);
16907 Context, GSE->getGenericLoc(), GSE->getControllingType(),
16908 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
16909 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
16910 ResultIdx);
16911 }
16912 // Rather than fall through to the unreachable, return the original generic
16913 // selection expression.
16914 return GSE;
16915 }
16916
16917 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
16918 assert(UnOp->getOpcode() == UO_AddrOf &&
16919 "Can only take the address of an overloaded function");
16920 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
16921 if (!Method->isImplicitObjectMemberFunction()) {
16922 // Do nothing: the address of static and
16923 // explicit object member functions is a (non-member) function pointer.
16924 } else {
16925 // Fix the subexpression, which really has to be an
16926 // UnresolvedLookupExpr holding an overloaded member function
16927 // or template.
16928 ExprResult SubExpr =
16929 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16930 if (SubExpr.isInvalid())
16931 return ExprError();
16932 if (SubExpr.get() == UnOp->getSubExpr())
16933 return UnOp;
16934
16935 if (CheckUseOfCXXMethodAsAddressOfOperand(UnOp->getBeginLoc(),
16936 SubExpr.get(), Method))
16937 return ExprError();
16938
16939 assert(isa<DeclRefExpr>(SubExpr.get()) &&
16940 "fixed to something other than a decl ref");
16941 NestedNameSpecifier Qualifier =
16942 cast<DeclRefExpr>(SubExpr.get())->getQualifier();
16943 assert(Qualifier &&
16944 "fixed to a member ref with no nested name qualifier");
16945
16946 // We have taken the address of a pointer to member
16947 // function. Perform the computation here so that we get the
16948 // appropriate pointer to member type.
16949 QualType MemPtrType = Context.getMemberPointerType(
16950 Fn->getType(), Qualifier,
16951 cast<CXXRecordDecl>(Method->getDeclContext()));
16952 // Under the MS ABI, lock down the inheritance model now.
16953 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
16954 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
16955
16956 return UnaryOperator::Create(Context, SubExpr.get(), UO_AddrOf,
16957 MemPtrType, VK_PRValue, OK_Ordinary,
16958 UnOp->getOperatorLoc(), false,
16960 }
16961 }
16962 ExprResult SubExpr =
16963 FixOverloadedFunctionReference(UnOp->getSubExpr(), Found, Fn);
16964 if (SubExpr.isInvalid())
16965 return ExprError();
16966 if (SubExpr.get() == UnOp->getSubExpr())
16967 return UnOp;
16968
16969 return CreateBuiltinUnaryOp(UnOp->getOperatorLoc(), UO_AddrOf,
16970 SubExpr.get());
16971 }
16972
16973 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
16974 if (Found.getAccess() == AS_none) {
16976 }
16977 // FIXME: avoid copy.
16978 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
16979 if (ULE->hasExplicitTemplateArgs()) {
16980 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
16981 TemplateArgs = &TemplateArgsBuffer;
16982 }
16983
16984 QualType Type = Fn->getType();
16985 ExprValueKind ValueKind =
16986 getLangOpts().CPlusPlus && !Fn->hasCXXExplicitFunctionObjectParameter()
16987 ? VK_LValue
16988 : VK_PRValue;
16989
16990 // FIXME: Duplicated from BuildDeclarationNameExpr.
16991 if (unsigned BID = Fn->getBuiltinID()) {
16992 if (!Context.BuiltinInfo.isDirectlyAddressable(BID)) {
16993 Type = Context.BuiltinFnTy;
16994 ValueKind = VK_PRValue;
16995 }
16996 }
16997
16999 Fn, Type, ValueKind, ULE->getNameInfo(), ULE->getQualifierLoc(),
17000 Found.getDecl(), ULE->getTemplateKeywordLoc(), TemplateArgs);
17001 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
17002 return DRE;
17003 }
17004
17005 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
17006 // FIXME: avoid copy.
17007 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
17008 if (MemExpr->hasExplicitTemplateArgs()) {
17009 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
17010 TemplateArgs = &TemplateArgsBuffer;
17011 }
17012
17013 Expr *Base;
17014
17015 // If we're filling in a static method where we used to have an
17016 // implicit member access, rewrite to a simple decl ref.
17017 if (MemExpr->isImplicitAccess()) {
17018 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17020 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
17021 MemExpr->getQualifierLoc(), Found.getDecl(),
17022 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
17023 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
17024 return DRE;
17025 } else {
17026 SourceLocation Loc = MemExpr->getMemberLoc();
17027 if (MemExpr->getQualifier())
17028 Loc = MemExpr->getQualifierLoc().getBeginLoc();
17029 Base =
17030 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*IsImplicit=*/true);
17031 }
17032 } else
17033 Base = MemExpr->getBase();
17034
17035 ExprValueKind valueKind;
17036 QualType type;
17037 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
17038 valueKind = VK_LValue;
17039 type = Fn->getType();
17040 } else {
17041 valueKind = VK_PRValue;
17042 type = Context.BoundMemberTy;
17043 }
17044
17045 return BuildMemberExpr(
17046 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
17047 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
17048 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
17049 type, valueKind, OK_Ordinary, TemplateArgs);
17050 }
17051
17052 llvm_unreachable("Invalid reference to overloaded function");
17053}
17054
17060
17061bool clang::shouldEnforceArgLimit(bool PartialOverloading,
17063 if (!PartialOverloading || !Function)
17064 return true;
17065 if (Function->isVariadic())
17066 return false;
17067 if (const auto *Proto =
17068 dyn_cast<FunctionProtoType>(Function->getFunctionType()))
17069 if (Proto->isTemplateVariadic())
17070 return false;
17071 if (auto *Pattern = Function->getTemplateInstantiationPattern())
17072 if (const auto *Proto =
17073 dyn_cast<FunctionProtoType>(Pattern->getFunctionType()))
17074 if (Proto->isTemplateVariadic())
17075 return false;
17076 return true;
17077}
17078
17080 DeclarationName Name,
17081 OverloadCandidateSet &CandidateSet,
17082 FunctionDecl *Fn, MultiExprArg Args,
17083 bool IsMember) {
17084 StringLiteral *Msg = Fn->getDeletedMessage();
17085 CandidateSet.NoteCandidates(
17086 PartialDiagnosticAt(Loc, PDiag(diag::err_ovl_deleted_call)
17087 << IsMember << Name << (Msg != nullptr)
17088 << (Msg ? Msg->getString() : StringRef())
17089 << Range),
17090 *this, OCD_AllCandidates, Args);
17091}
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.
#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.
This file declares semantic analysis functions specific to ARM.
static bool hasAttr(const Decl *D, bool IgnoreImplicitAttr)
Definition SemaCUDA.cpp:109
static bool hasExplicitAttr(const VarDecl *D)
Definition SemaCUDA.cpp:31
This file declares semantic analysis for CUDA constructs.
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 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 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 bool IsVectorElementConversion(Sema &S, QualType FromType, QualType ToType, ImplicitConversionKind &ICK, Expr *From)
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 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 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.
__device__ __2f16 b
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:463
bool isFloat() const
Definition APValue.h:468
bool isInt() const
Definition APValue.h:467
std::string getAsString(const ASTContext &Ctx, QualType Ty) const
Definition APValue.cpp:956
APFloat & getFloat()
Definition APValue.h:503
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:188
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.
DeclarationNameTable DeclarationNames
Definition ASTContext.h:744
CanQualType FloatTy
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
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:894
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:860
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
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.
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
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 ...
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:859
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
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:3908
QualType getConstantArrayType(const ASTContext &Ctx) const
Definition Type.cpp:279
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3738
QualType getElementType() const
Definition TypeBase.h:3750
QualType getValueType() const
Gets the type contained by this atomic type, i.e.
Definition TypeBase.h:8142
Attr - This represents one attribute.
Definition Attr.h:44
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:3974
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given binary opcode.
Definition Expr.cpp:2175
StringRef getOpcodeStr() const
Definition Expr.h:4040
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:2128
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:4938
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4115
Pointer to a block type.
Definition TypeBase.h:3558
This class is used for builtin types like 'int'.
Definition TypeBase.h:3182
Kind getKind() const
Definition TypeBase.h:3230
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)
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:2604
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3019
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:3056
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2937
bool isExplicit() const
Return true if the declaration is already resolved to be explicit.
Definition DeclCXX.h:2973
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:2977
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:179
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:692
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
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:2703
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:2710
QualType getFunctionObjectParameterReferenceType() const
Return the type of the object pointed by this.
Definition DeclCXX.cpp:2820
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2255
static CXXOperatorCallExpr * Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation OperatorLoc, FPOptionsOverride FPFeatures, ADLCallKind UsesADL=NotADL)
Definition ExprCXX.cpp:624
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:1018
llvm::iterator_range< conversion_iterator > getVisibleConversionFunctions() const
Get all conversion functions visible in current class, including conversion function templates.
Definition DeclCXX.cpp:1977
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:1736
A rewritten comparison expression that was originally written using operator syntax.
Definition ExprCXX.h:286
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:73
bool isEmpty() const
No scope specifier.
Definition DeclSpec.h:178
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:2879
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:1513
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3062
void setUsesMemberSyntax(bool V=true)
Definition Expr.h:3043
void markDependentForPostponedNameLookup()
Used by Sema to implement MSVC-compatible delayed name lookup.
Definition Expr.h:3261
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:3293
QualType getElementType() const
Definition TypeBase.h:3303
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:4960
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3776
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition Expr.cpp:346
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:37
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:1449
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2109
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:1272
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:1465
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:263
T * getAttr() const
Definition DeclBase.h:573
ASTContext & getASTContext() const LLVM_READONLY
Definition DeclBase.cpp:524
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition DeclBase.h:593
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:251
bool isInvalidDecl() const
Definition DeclBase.h:588
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition DeclBase.h:559
SourceLocation getLocation() const
Definition DeclBase.h:439
DeclContext * getDeclContext()
Definition DeclBase.h:448
AccessSpecifier getAccess() const
Definition DeclBase.h:507
specific_attr_iterator< T > specific_attr_end() const
Definition DeclBase.h:569
specific_attr_iterator< T > specific_attr_begin() const
Definition DeclBase.h:564
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
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:830
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:854
void overloadCandidatesShown(unsigned N)
Call this after showing N overload candidates.
Definition Diagnostic.h:776
unsigned getNumOverloadCandidatesToShow() const
When a call or operator fails, print out up to this many candidate overloads as suggestions.
Definition Diagnostic.h:761
OverloadsShown getShowOverloads() const
Definition Diagnostic.h:752
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:591
RAII object that enters a new expression evaluation context.
Store information needed for an explicit specifier.
Definition DeclCXX.h:1924
bool isExplicit() const
Determine whether this specifier is known to correspond to an explicit declaration.
Definition DeclCXX.h:1948
ExplicitSpecKind getKind() const
Definition DeclCXX.h:1932
const Expr * getExpr() const
Definition DeclCXX.h:1933
static ExplicitSpecifier getFromDecl(FunctionDecl *Function)
Definition DeclCXX.cpp:2354
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition ExprCXX.cpp:1464
The return type of classify().
Definition Expr.h:337
bool isLValue() const
Definition Expr.h:387
bool isPRValue() const
Definition Expr.h:390
bool isXValue() const
Definition Expr.h:388
static Classification makeSimpleLValue()
Create a simple, modifiable lvalue.
Definition Expr.h:395
bool isRValue() const
Definition Expr.h:391
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:3078
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:444
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3069
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:3293
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
Definition Expr.cpp:4164
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
Definition Expr.h:833
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
Definition Expr.h:837
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition Expr.h:451
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:813
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:4001
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:273
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:476
Classification Classify(ASTContext &Ctx) const
Classify - Classify this expression according to the C++11 expression taxonomy.
Definition Expr.h:412
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:523
static ExprValueKind getValueKindForType(QualType T)
getValueKindForType - Given a formal return or parameter type, give its value kind.
Definition Expr.h:434
ExtVectorType - Extended vector type.
Definition TypeBase.h:4283
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3157
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition Diagnostic.h:78
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:139
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:102
Represents a function declaration or definition.
Definition Decl.h:1999
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition Decl.h:2686
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2794
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4134
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3703
param_iterator param_end()
Definition Decl.h:2784
bool isMemberLikeConstrainedFriend() const
Determine whether a function is a friend function that cannot be redeclared outside of its class,...
Definition Decl.cpp:3607
bool hasCXXExplicitFunctionObjectParameter() const
Definition Decl.cpp:3806
QualType getReturnType() const
Definition Decl.h:2842
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2771
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:4205
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4254
param_iterator param_begin()
Definition Decl.h:2783
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3125
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4270
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition Decl.cpp:4198
unsigned getNumNonObjectParams() const
Definition Decl.cpp:3810
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2469
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition Decl.cpp:4071
bool isConsteval() const
Definition Decl.h:2481
bool isTargetMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the target functionality.
Definition Decl.cpp:3651
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:2859
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:3656
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3767
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition Decl.h:2682
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5282
ExtParameterInfo getExtParameterInfo(unsigned I) const
Definition TypeBase.h:5786
unsigned getNumParams() const
Definition TypeBase.h:5560
Qualifiers getMethodQuals() const
Definition TypeBase.h:5708
QualType getParamType(unsigned i) const
Definition TypeBase.h:5562
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5686
ArrayRef< QualType > param_types() const
Definition TypeBase.h:5722
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:4589
ExtInfo withNoReturn(bool noReturn) const
Definition TypeBase.h:4660
ParameterABI getABI() const
Return the ABI treatment of this parameter.
Definition TypeBase.h:4517
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition TypeBase.h:4478
ExtInfo getExtInfo() const
Definition TypeBase.h:4834
CallingConv getCallConv() const
Definition TypeBase.h:4833
QualType getReturnType() const
Definition TypeBase.h:4818
QualType getCallResultType(const ASTContext &Context) const
Determine the type of an expression that calls a function of this type.
Definition TypeBase.h:4846
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:4560
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:3789
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2068
ImplicitConversionSequence - Represents an implicit conversion sequence, which may be a standard conv...
Definition Overload.h:615
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:666
void setBad(BadConversionSequence::FailureKind Failure, Expr *FromExpr, QualType ToType)
Sets this sequence as a bad conversion for an explicit argument.
Definition Overload.h:763
UserDefinedConversionSequence UserDefined
When ConversionKind == UserDefinedConversion, provides the details of the user-defined conversion seq...
Definition Overload.h:670
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:820
AmbiguousConversionSequence Ambiguous
When ConversionKind == AmbiguousConversion, provides the details of the ambiguous conversion.
Definition Overload.h:674
void setInitializerListContainerType(QualType T, bool IA)
Definition Overload.h:805
bool hasInitializerListContainerType() const
Definition Overload.h:802
unsigned getKindRank() const
Return a ranking of the implicit conversion sequence kind, where smaller ranks represent better conve...
Definition Overload.h:727
bool isInitializerListOfIncompleteArray() const
Definition Overload.h:809
BadConversionSequence Bad
When ConversionKind == BadConversion, provides the details of the bad conversion.
Definition Overload.h:678
QualType getInitializerListContainerType() const
Definition Overload.h:812
void DiagnoseAmbiguousConversion(Sema &S, SourceLocation CaretLoc, const PartialDiagnostic &PDiag) const
Diagnoses an ambiguous conversion.
Describes an C or C++ initializer list.
Definition Expr.h:5235
bool hasDesignatedInit() const
Determine whether this initializer list contains a designated initializer.
Definition Expr.h:5350
unsigned getNumInits() const
Definition Expr.h:5265
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:2491
const Expr * getInit(unsigned Init) const
Definition Expr.h:5289
SourceLocation getEndLoc() const LLVM_READONLY
Definition Expr.cpp:2509
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:971
An lvalue reference type, per C++11 [dcl.ref].
Definition TypeBase.h:3633
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) 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
LLVM_ATTRIBUTE_REINITIALIZES void clear()
Clears out any current state.
Definition Lookup.h:607
DeclClass * getAsSingle() const
Definition Lookup.h:558
void addDecl(NamedDecl *D)
Add a declaration to these results with its natural access.
Definition Lookup.h:475
bool empty() const
Return true if no decls were found.
Definition Lookup.h:362
void resolveKind()
Resolves the result kind of the lookup, possibly hiding decls.
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition Lookup.h:666
bool isAmbiguous() const
Definition Lookup.h:324
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
const UnresolvedSetImpl & asUnresolvedSet() const
Definition Lookup.h:354
UnresolvedSetImpl::iterator iterator
Definition Lookup.h:154
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition Lookup.h:636
DeclarationName getLookupName() const
Gets the name to look up.
Definition Lookup.h:265
iterator end() const
Definition Lookup.h:359
iterator begin() const
Definition Lookup.h:358
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3300
SourceLocation getMemberLoc() const
getMemberLoc - Return the location of the "member", in X->F, it is the location of 'F'.
Definition Expr.h:3489
NestedNameSpecifier getQualifier() const
If the member name was qualified, retrieves the nested-name-specifier that precedes the member name.
Definition Expr.h:3411
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3383
bool hasQualifier() const
Determines whether this member expression actually had a C++ nested-name-specifier prior to the name ...
Definition Expr.h:3397
bool performsVirtualDispatch(const LangOptions &LO) const
Returns true if virtual dispatch is performed.
Definition Expr.h:3518
Expr * getBase() const
Definition Expr.h:3377
void setBase(Expr *E)
Definition Expr.h:3376
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.cpp:1790
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3495
DeclAccessPair getFoundDecl() const
Retrieves the declaration found by lookup.
Definition Expr.h:3387
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3669
NestedNameSpecifier getQualifier() const
Definition TypeBase.h:3701
CXXRecordDecl * getMostRecentCXXRecordDecl() const
Note: this can trigger extra deserialization when external AST sources are used.
Definition Type.cpp:5502
QualType getPointeeType() const
Definition TypeBase.h:3687
Describes a module or submodule.
Definition Module.h:144
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:239
This represents a decl that may have a name.
Definition Decl.h:273
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition Decl.h:486
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:300
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:339
std::string getQualifiedNameAsString() const
Definition Decl.cpp:1680
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition Decl.cpp:1206
Represent a C++ namespace.
Definition Decl.h:591
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:7905
ObjCMethodDecl - Represents an instance or class method declaration.
Definition DeclObjC.h:140
Represents a pointer to an Objective C object.
Definition TypeBase.h:7961
bool isSpecialized() const
Whether this type is specialized, meaning that it has type arguments.
Definition TypeBase.h:8050
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition TypeBase.h:8019
QualType getPointeeType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:7973
ObjCInterfaceDecl * getInterfaceDecl() const
If this pointer points to an Objective @interface type, gets the declaration for that interface.
Definition TypeBase.h:8013
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition Type.cpp:1840
bool isObjCClassType() const
True if this is equivalent to the 'Class' type, i.e.
Definition TypeBase.h:8025
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1180
OverloadCandidateSet - A set of overload candidates, used in C++ overload resolution (C++ 13....
Definition Overload.h:1153
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:1353
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:1451
ConversionSequenceList allocateConversionSequences(unsigned NumConversions)
Allocate storage for conversion sequences for NumConversions conversions.
Definition Overload.h:1385
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:1401
OperatorRewriteInfo getRewriteInfo() const
Definition Overload.h:1343
bool shouldDeferTemplateArgumentDeduction(const LangOptions &Opts) const
Definition Overload.h:1542
@ CSK_AddressOfOverloadSet
C++ [over.match.call.general] Resolve a call through the address of an overload set.
Definition Overload.h:1178
@ CSK_InitByConstructor
C++ [over.match.ctor], [over.match.list] Initialization of an object of class type by constructor,...
Definition Overload.h:1174
@ CSK_InitByUserDefinedConversion
C++ [over.match.copy]: Copy-initialization of an object of class type by user-defined conversion.
Definition Overload.h:1169
@ CSK_Normal
Normal lookup.
Definition Overload.h:1157
@ CSK_Operator
C++ [over.match.oper]: Lookup of operator function candidates in a call using operator syntax.
Definition Overload.h:1164
SmallVectorImpl< OverloadCandidate >::iterator iterator
Definition Overload.h:1369
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:1361
SourceLocation getLocation() const
Definition Overload.h:1341
OverloadCandidate & addCandidate(unsigned NumConversions=0, ConversionSequenceList Conversions={})
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Definition Overload.h:1416
void InjectNonDeducedTemplateCandidates(Sema &S)
CandidateSetKind getKind() const
Definition Overload.h:1342
size_t nonDeferredCandidatesCount() const
Definition Overload.h:1376
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:3122
bool hasExplicitTemplateArgs() const
Determines whether this expression had explicit template arguments.
Definition ExprCXX.h:3274
static FindResult find(Expr *E)
Finds the overloaded expression in the given expression E of OverloadTy.
Definition ExprCXX.h:3183
NestedNameSpecifier getQualifier() const
Fetches the nested-name qualifier, if one was given.
Definition ExprCXX.h:3238
SourceLocation getNameLoc() const
Gets the location of the name.
Definition ExprCXX.h:3235
UnresolvedSetImpl::iterator decls_iterator
Definition ExprCXX.h:3213
decls_iterator decls_begin() const
Definition ExprCXX.h:3215
unsigned getNumDecls() const
Gets the number of declarations in the unresolved set.
Definition ExprCXX.h:3226
SourceLocation getTemplateKeywordLoc() const
Retrieve the location of the template keyword preceding this name, if any.
Definition ExprCXX.h:3248
NestedNameSpecifierLoc getQualifierLoc() const
Fetches the nested-name qualifier with source-location information, if one was given.
Definition ExprCXX.h:3244
void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const
Copies the template arguments into the given structure.
Definition ExprCXX.h:3336
decls_iterator decls_end() const
Definition ExprCXX.h:3218
DeclarationName getName() const
Gets the name looked up.
Definition ExprCXX.h:3232
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition Attr.h:256
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2184
Represents a parameter to a function.
Definition Decl.h:1789
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition Decl.cpp:3050
bool isEquivalent(PointerAuthQualifier Other) const
Definition TypeBase.h:301
std::string getAsString() const
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3346
QualType getPointeeType() const
Definition TypeBase.h:3356
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
Definition Expr.cpp:5032
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8427
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
Definition TypeBase.h:8421
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition TypeBase.h:8432
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3591
QualType getLocalUnqualifiedType() const
Return this type with all of the instance-specific qualifiers removed, but without removing any quali...
Definition TypeBase.h:1225
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:8343
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8469
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8383
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:8528
QualType getCanonicalType() const
Definition TypeBase.h:8395
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8437
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:8497
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8416
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition TypeBase.h:8464
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
Definition TypeBase.h:8389
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition TypeBase.h:1332
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:8508
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition TypeBase.h:8375
A qualifier set is used to build a set of qualifiers.
Definition TypeBase.h:8283
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition TypeBase.h:8290
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition Type.cpp:4710
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:3651
Represents a struct/union/class.
Definition Decl.h:4309
field_range fields() const
Definition Decl.h:4512
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3589
QualType getPointeeType() const
Definition TypeBase.h:3607
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:1473
bool areLaxCompatibleSveTypes(QualType FirstType, QualType SecondType)
Return true if the given vector types are lax-compatible SVE vector types, false otherwise.
Definition SemaARM.cpp:1517
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition SemaBase.cpp:61
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
bool IsAllowedCall(const FunctionDecl *Caller, const FunctionDecl *Callee)
Determines whether Caller may invoke Callee, based on their CUDA host/device attributes.
Definition SemaCUDA.h:186
CUDAFunctionTarget IdentifyTarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr=false)
Determines whether the given function is a CUDA device/host/kernel/etc.
Definition SemaCUDA.cpp:134
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:371
static bool isImplicitHostDeviceFunction(const FunctionDecl *D)
Definition SemaCUDA.cpp:312
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:318
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:225
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:10258
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:6313
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6342
RAII class to control scope of DeferDiags.
Definition Sema.h:9992
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:12360
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition Sema.h:12393
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:850
bool TryFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy) const
Same as IsFunctionConversion, but if this would return true, it sets ResultTy to ToType.
bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const
Returns true if From is a function or pointer to a function with the cfi_unchecked_callee attribute b...
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:10008
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:9281
@ LookupUsingDeclName
Look up all declarations in a scope with the given name, including resolved using declarations.
Definition Sema.h:9308
@ LookupOperatorName
Look up of an operator name (e.g., operator+) for use with operator overloading.
Definition Sema.h:9293
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition Sema.h:9289
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:405
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:167
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)
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:1438
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)
bool TemplateParameterListsAreEqual(const TemplateCompareNewDeclInfo &NewInstFrom, TemplateParameterList *New, const NamedDecl *OldInstFrom, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc=SourceLocation())
Determine whether the given template parameter lists are equivalent.
ReferenceCompareResult
ReferenceCompareResult - Expresses the result of comparing two types (cv1 T1 and cv2 T2) to determine...
Definition Sema.h:10341
@ Ref_Incompatible
Ref_Incompatible - The two types are incompatible, so direct reference binding is not possible.
Definition Sema.h:10344
@ Ref_Compatible
Ref_Compatible - The two types are reference-compatible.
Definition Sema.h:10350
@ Ref_Related
Ref_Related - The two types are reference-related, which means that their unqualified forms (T1 and T...
Definition Sema.h:10348
@ AR_dependent
Definition Sema.h:1653
@ AR_accessible
Definition Sema.h:1651
@ AR_inaccessible
Definition Sema.h:1652
@ AR_delayed
Definition Sema.h:1654
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:2042
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:1647
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:1276
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:680
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:915
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:1483
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:748
ASTContext & getASTContext() const
Definition Sema.h:918
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:756
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:10729
@ FRS_DiagnosticIssued
Definition Sema.h:10731
@ FRS_NoViableFunction
Definition Sema.h:10730
llvm::SmallSetVector< CXXRecordDecl *, 16 > AssociatedClassSet
Definition Sema.h:9274
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:10059
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:1184
bool IsComplexPromotion(QualType FromType, QualType ToType)
Determine if a conversion is a complex promotion.
Module * getOwningModule(const Decl *Entity)
Get the module owning an entity.
Definition Sema.h:3573
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:12074
bool AddingCFIUncheckedCallee(QualType From, QualType To) const
Returns true if From is a function or pointer to a function without the cfi_unchecked_callee attribut...
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)
bool CheckFunctionTemplateSpecialization(FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend=false)
Perform semantic analysis for the given function template specialization.
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:272
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:83
const LangOptions & getLangOpts() const
Definition Sema.h:911
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:1274
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:1448
llvm::SmallSetVector< DeclContext *, 16 > AssociatedNamespaceSet
Definition Sema.h:9273
MemberPointerConversionDirection
Definition Sema.h:10179
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)
bool AreConstraintExpressionsEqual(const NamedDecl *Old, const Expr *OldConstr, const TemplateCompareNewDeclInfo &New, const Expr *NewConstr)
ReferenceConversionsScope::ReferenceConversions ReferenceConversions
Definition Sema.h:10369
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.
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
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.
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
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:633
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:15324
bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath=nullptr, bool IgnoreAccess=false)
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:6927
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:1411
MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference)
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:8122
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:13792
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 ?
bool IsFunctionConversion(QualType FromType, QualType ToType, bool *DiscardingCFIUncheckedCallee=nullptr, bool *AddingCFIUncheckedCallee=nullptr) const
Determine whether the conversion from FromType to ToType is a valid conversion that strips "noexcept"...
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:7422
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 DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:218
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:15279
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:123
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:6698
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6667
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.
MemberPointerConversionResult
Definition Sema.h:10171
SourceManager & SourceMgr
Definition Sema.h:1279
bool DiagnoseDependentMemberLookup(const LookupResult &R)
Diagnose a lookup that found results in an enclosing class during error recovery.
DiagnosticsEngine & Diags
Definition Sema.h:1278
NamespaceDecl * getStdNamespace() const
ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose=true)
DefaultFunctionArrayConversion (C99 6.3.2.1p3, C99 6.3.2.1p4).
Definition SemaExpr.cpp:509
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.
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...
void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First=true)
Emit diagnostics explaining why a constraint expression was deemed unsatisfied.
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:6375
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:1418
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:8599
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:292
void dump() const
dump - Print this standard conversion sequence to standard error.
DeclAccessPair FoundCopyConstructor
Definition Overload.h:386
unsigned BindsToRvalue
Whether we're binding to an rvalue.
Definition Overload.h:351
ImplicitConversionKind Second
Second - The second conversion can be an integral promotion, floating point promotion,...
Definition Overload.h:303
ImplicitConversionKind First
First – The first conversion can be an lvalue-to-rvalue conversion, array-to-pointer conversion,...
Definition Overload.h:297
unsigned BindsImplicitObjectArgumentWithoutRefQualifier
Whether this binds an implicit object argument to a non-static member function without a ref-qualifie...
Definition Overload.h:356
unsigned ReferenceBinding
ReferenceBinding - True when this is a reference binding (C++ [over.ics.ref]).
Definition Overload.h:333
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:318
CXXConstructorDecl * CopyConstructor
CopyConstructor - The copy constructor that is used to perform this conversion, when the conversion i...
Definition Overload.h:385
unsigned IncompatibleObjC
IncompatibleObjC - Whether this is an Objective-C conversion that we should warn about (if we actuall...
Definition Overload.h:328
unsigned ObjCLifetimeConversionBinding
Whether this binds a reference to an object with a different Objective-C lifetime qualifier.
Definition Overload.h:361
ImplicitConversionKind Third
Third - The third conversion can be a qualification conversion or a function conversion.
Definition Overload.h:312
unsigned QualificationIncludesObjCLifetime
Whether the qualification conversion involves a change in the Objective-C lifetime (for automatic ref...
Definition Overload.h:323
void setToType(unsigned Idx, QualType T)
Definition Overload.h:390
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:378
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:343
ImplicitConversionKind Dimension
Dimension - Between the second and third conversion a vector or matrix dimension conversion may occur...
Definition Overload.h:308
unsigned BindsToFunctionLvalue
Whether we're binding to a function lvalue.
Definition Overload.h:347
unsigned DirectBinding
DirectBinding - True when this is a reference binding that is a direct binding (C++ [dcl....
Definition Overload.h:338
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:368
QualType getToType(unsigned Idx) const
Definition Overload.h:405
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:358
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:346
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1801
StringRef getString() const
Definition Expr.h:1869
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:673
virtual bool hasIbm128Type() const
Determine whether the __ibm128 type is supported on this target.
Definition TargetInfo.h:727
virtual bool hasFloat128Type() const
Determine whether the __float128 type is supported on this target.
Definition TargetInfo.h:712
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:3535
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isIncompleteOrObjectType() const
Return true if this is an incomplete or object type, in other words, not a function type.
Definition TypeBase.h:2503
bool isBlockPointerType() const
Definition TypeBase.h:8600
bool isVoidType() const
Definition TypeBase.h:8936
bool isBooleanType() const
Definition TypeBase.h:9066
bool isObjCBuiltinType() const
Definition TypeBase.h:8800
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2229
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:1955
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition Type.cpp:787
bool isIncompleteArrayType() const
Definition TypeBase.h:8687
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
Definition Type.cpp:2209
bool isFloat16Type() const
Definition TypeBase.h:8945
bool isComplexType() const
isComplexType() does not include complex integers (a GCC extension).
Definition Type.cpp:724
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2119
bool isRValueReferenceType() const
Definition TypeBase.h:8612
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:8683
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition TypeBase.h:9096
bool isArrayType() const
Definition TypeBase.h:8679
bool isCharType() const
Definition Type.cpp:2136
bool isConvertibleToFixedPointType() const
Return true if this can be converted to (or from) a fixed point type.
Definition TypeBase.h:9004
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2341
bool isPointerType() const
Definition TypeBase.h:8580
bool isArrayParameterType() const
Definition TypeBase.h:8695
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:8980
bool isSVESizelessBuiltinType() const
Returns true for SVE scalable vector types.
Definition Type.cpp:2578
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9226
bool isReferenceType() const
Definition TypeBase.h:8604
bool isEnumeralType() const
Definition TypeBase.h:8711
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition Type.cpp:2107
bool isObjCQualifiedIdType() const
Definition TypeBase.h:8770
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9054
bool isAnyCharacterType() const
Determine whether this type is any of the built-in character types.
Definition Type.cpp:2172
bool isObjCObjectOrInterfaceType() const
Definition TypeBase.h:8757
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2808
bool isLValueReferenceType() const
Definition TypeBase.h:8608
bool isBitIntType() const
Definition TypeBase.h:8845
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2800
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition Type.cpp:2415
bool isAnyComplexType() const
Definition TypeBase.h:8715
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:8992
bool isHalfType() const
Definition TypeBase.h:8940
const BuiltinType * getAsPlaceholderType() const
Definition TypeBase.h:8918
bool isQueueT() const
Definition TypeBase.h:8826
bool isMemberPointerType() const
Definition TypeBase.h:8661
bool isObjCIdType() const
Definition TypeBase.h:8782
bool isMatrixType() const
Definition TypeBase.h:8737
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9072
bool isObjectType() const
Determine whether this type is an object type.
Definition TypeBase.h:2528
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isEventT() const
Definition TypeBase.h:8818
bool isBFloat16Type() const
Definition TypeBase.h:8957
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2440
bool isFunctionType() const
Definition TypeBase.h:8576
bool isObjCObjectPointerType() const
Definition TypeBase.h:8749
bool isVectorType() const
Definition TypeBase.h:8719
bool isObjCClassType() const
Definition TypeBase.h:8788
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2324
bool isRVVSizelessBuiltinType() const
Returns true for RVV scalable vector types.
Definition Type.cpp:2599
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2939
bool isHLSLAttributedResourceType() const
Definition TypeBase.h:8893
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:2257
bool isAnyPointerType() const
Definition TypeBase.h:8588
TypeClass getTypeClass() const
Definition TypeBase.h:2403
bool isSamplerT() const
Definition TypeBase.h:8814
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9159
bool isNullPtrType() const
Definition TypeBase.h:8973
bool isRecordType() const
Definition TypeBase.h:8707
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2246
static OverloadedOperatorKind getOverloadedOperator(Opcode Opc)
Retrieve the overloaded operator kind that corresponds to the given unary opcode.
Definition Expr.cpp:1426
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:4995
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
Definition Expr.cpp:1402
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3384
bool requiresADL() const
True if this declaration should be extended by argument-dependent lookup.
Definition ExprCXX.h:3453
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:432
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition ExprCXX.h:4120
DeclarationName getMemberName() const
Retrieve the name of the member that this expression refers to.
Definition ExprCXX.h:4228
QualType getBaseType() const
Definition ExprCXX.h:4202
bool isArrow() const
Determine whether this member expression used the '->' operator; otherwise, it used the '.
Definition ExprCXX.h:4212
Expr * getBase()
Retrieve the base object of this member expressions, e.g., the x in x.m.
Definition ExprCXX.h:4193
SourceLocation getBeginLoc() const LLVM_READONLY
Definition ExprCXX.h:4238
SourceLocation getMemberLoc() const
Retrieve the location of the name of the member that this expression refers to.
Definition ExprCXX.h:4232
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:640
static UserDefinedLiteral * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation LitEndLoc, SourceLocation SuffixLoc, FPOptionsOverride FPFeatures)
Definition ExprCXX.cpp:966
QualType getType() const
Definition Decl.h:722
unsigned getNumElements() const
Definition TypeBase.h:4206
QualType getElementType() const
Definition TypeBase.h:4205
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.
bool Ret(InterpState &S, CodePtr &PC)
Definition Interp.h:312
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:809
@ NonFunction
This is not an overload because the lookup results contain a non-function.
Definition Sema.h:820
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:816
@ Overload
This is a legitimate overload: the existing declarations are functions or function templates with dif...
Definition Sema.h:812
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:60
@ 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:852
@ ovl_fail_final_conversion_not_exact
This conversion function template specialization candidate is not viable because the final conversion...
Definition Overload.h:880
@ ovl_fail_enable_if
This candidate function was not viable because an enable_if attribute disabled it.
Definition Overload.h:889
@ ovl_fail_illegal_constructor
This conversion candidate was not considered because it is an illegal instantiation of a constructor ...
Definition Overload.h:872
@ ovl_fail_bad_final_conversion
This conversion candidate is not viable because its result type is not implicitly convertible to the ...
Definition Overload.h:876
@ 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:917
@ ovl_fail_too_few_arguments
Definition Overload.h:854
@ ovl_fail_addr_not_available
This candidate was not viable because its address could not be taken.
Definition Overload.h:896
@ ovl_fail_too_many_arguments
Definition Overload.h:853
@ ovl_non_default_multiversion_function
This candidate was not viable because it is a non-default multiversioned function.
Definition Overload.h:904
@ ovl_fail_constraints_not_satisfied
This candidate was not viable because its associated constraints were not satisfied.
Definition Overload.h:913
@ ovl_fail_bad_conversion
Definition Overload.h:855
@ ovl_fail_bad_target
(CUDA) This candidate was not viable because the callee was not accessible from the caller's target (...
Definition Overload.h:885
@ ovl_fail_bad_deduction
Definition Overload.h:856
@ ovl_fail_inhctor_slice
This inherited constructor is not viable because it would slice the argument.
Definition Overload.h:900
@ ovl_fail_object_addrspace_mismatch
This constructor/conversion candidate fail due to an address space mismatch between the object being ...
Definition Overload.h:909
@ ovl_fail_explicit
This candidate constructor or conversion function is explicit but the context doesn't permit explicit...
Definition Overload.h:893
@ ovl_fail_trivial_conversion
This conversion candidate was not considered because it duplicates the work of a trivial or derived-t...
Definition Overload.h:861
@ Comparison
A comparison.
Definition Sema.h:665
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1782
@ RQ_LValue
An lvalue ref-qualifier was provided (&).
Definition TypeBase.h:1785
@ RQ_RValue
An rvalue ref-qualifier was provided (&&).
Definition TypeBase.h:1788
ImplicitConversionRank
ImplicitConversionRank - The rank of an implicit conversion kind.
Definition Overload.h:215
@ ICR_Conversion
Conversion.
Definition Overload.h:229
@ ICR_Writeback_Conversion
ObjC ARC writeback conversion.
Definition Overload.h:241
@ ICR_HLSL_Dimension_Reduction
HLSL Matching Dimension Reduction.
Definition Overload.h:251
@ ICR_HLSL_Dimension_Reduction_Conversion
HLSL Dimension reduction with conversion.
Definition Overload.h:257
@ ICR_HLSL_Scalar_Widening
HLSL Scalar Widening.
Definition Overload.h:220
@ ICR_C_Conversion
Conversion only allowed in the C standard (e.g. void* to char*).
Definition Overload.h:244
@ ICR_OCL_Scalar_Widening
OpenCL Scalar Widening.
Definition Overload.h:232
@ ICR_Complex_Real_Conversion
Complex <-> Real conversion.
Definition Overload.h:238
@ ICR_HLSL_Scalar_Widening_Conversion
HLSL Scalar Widening with conversion.
Definition Overload.h:235
@ ICR_HLSL_Dimension_Reduction_Promotion
HLSL Dimension reduction with promotion.
Definition Overload.h:254
@ ICR_Promotion
Promotion.
Definition Overload.h:223
@ ICR_Exact_Match
Exact Match.
Definition Overload.h:217
@ ICR_C_Conversion_Extension
Conversion not allowed by the C standard, but that we accept as an extension anyway.
Definition Overload.h:248
@ ICR_HLSL_Scalar_Widening_Promotion
HLSL Scalar Widening with promotion.
Definition Overload.h:226
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:161
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:151
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1044
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:124
@ AS_none
Definition Specifiers.h:127
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:922
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
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:205
@ 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:202
@ 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:208
@ 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_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:687
@ IncompatiblePointer
IncompatiblePointer - The assignment is between two pointers types that are not compatible,...
Definition Sema.h:710
@ CompatiblePointerDiscardsQualifiers
CompatiblePointerDiscardsQualifiers - The assignment discards c/v/r qualifiers, which we accept as an...
Definition Sema.h:731
@ Compatible
Compatible - the types are compatible according to the standard.
Definition Sema.h:689
@ IncompatiblePointerSign
IncompatiblePointerSign - The assignment is between two pointers types which point to integers which ...
Definition Sema.h:727
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:585
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:213
CXXSpecialMemberKind
Kinds of C++ special members.
Definition Sema.h:424
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:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
const FunctionProtoType * T
bool shouldEnforceArgLimit(bool PartialOverloading, FunctionDecl *Function)
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:117
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:268
@ NK_Not_Narrowing
Not a narrowing conversion.
Definition Overload.h:270
@ NK_Constant_Narrowing
A narrowing conversion, because a constant expression got narrowed.
Definition Overload.h:276
@ NK_Dependent_Narrowing
Cannot tell whether this is a narrowing conversion because the expression is value-dependent.
Definition Overload.h:284
@ NK_Type_Narrowing
A narrowing conversion by virtue of the source and destination types.
Definition Overload.h:273
@ NK_Variable_Narrowing
A narrowing conversion, because a non-constant-expression variable might have got narrowed.
Definition Overload.h:280
@ TPOC_Conversion
Partial ordering of function templates for a call to a conversion function.
Definition Template.h:304
@ TPOC_Call
Partial ordering of function templates for a function call.
Definition Template.h:300
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition DeclBase.h:1288
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:366
@ MiscellaneousDeductionFailure
Deduction failed; that's all we know.
Definition Sema.h:416
@ NonDependentConversionFailure
Checking non-dependent argument conversions failed.
Definition Sema.h:411
@ ConstraintsNotSatisfied
The deduced arguments did not satisfy the constraints associated with the template.
Definition Sema.h:414
@ Underqualified
Template argument deduction failed due to inconsistent cv-qualifiers on a template parameter type tha...
Definition Sema.h:387
@ InstantiationDepth
Template argument deduction exceeded the maximum template instantiation depth (which has already been...
Definition Sema.h:373
@ InvalidExplicitArguments
The explicitly-specified template arguments were not valid template arguments for the given template.
Definition Sema.h:409
@ CUDATargetMismatch
CUDA Target attributes do not match.
Definition Sema.h:418
@ TooFewArguments
When performing template argument deduction for a function template, there were too few call argument...
Definition Sema.h:406
@ Incomplete
Template argument deduction did not deduce a value for every template parameter.
Definition Sema.h:376
@ Invalid
The declaration was invalid; do nothing.
Definition Sema.h:370
@ Success
Template argument deduction was successful.
Definition Sema.h:368
@ SubstitutionFailure
Substitution of the deduced template argument values resulted in an error.
Definition Sema.h:390
@ IncompletePack
Template argument deduction did not deduce a value for every expansion of an expanded template parame...
Definition Sema.h:379
@ DeducedMismatch
After substituting deduced template arguments, a dependent parameter type did not match the correspon...
Definition Sema.h:393
@ Inconsistent
Template argument deduction produced inconsistent deduced values for the given template parameter.
Definition Sema.h:382
@ TooManyArguments
When performing template argument deduction for a function template, there were too many call argumen...
Definition Sema.h:403
@ AlreadyDiagnosed
Some error which was already diagnosed.
Definition Sema.h:420
@ DeducedMismatchNested
After substituting deduced template arguments, an element of a dependent parameter type did not match...
Definition Sema.h:397
@ NonDeducedMismatch
A non-depnedent component of the parameter did not match the corresponding component of the argument.
Definition Sema.h:400
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:278
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:1512
CCEKind
Contexts in which a converted constant expression is required.
Definition Sema.h:824
@ TemplateArg
Value of a non-type template parameter.
Definition Sema.h:827
@ Noexcept
Condition in a noexcept(bool) specifier.
Definition Sema.h:832
@ ArrayBound
Array bound in array declarator or new-expression.
Definition Sema.h:830
@ TempArgStrict
As above, but applies strict template checking rules.
Definition Sema.h:828
@ ExplicitBool
Condition in an explicit(bool) specifier.
Definition Sema.h:831
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:5895
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:445
__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:515
ConversionSet::const_iterator const_iterator
Definition Overload.h:551
SmallVector< std::pair< NamedDecl *, FunctionDecl * >, 4 > ConversionSet
Definition Overload.h:516
void addConversion(NamedDecl *Found, FunctionDecl *D)
Definition Overload.h:542
void copyFrom(const AmbiguousConversionSequence &)
const Expr * ConstraintExpr
Definition Decl.h:87
UnsignedOrNone ArgPackSubstIndex
Definition Decl.h:88
QualType getToType() const
Definition Overload.h:600
QualType getFromType() const
Definition Overload.h:599
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:1095
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:645
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:647
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:633
Extra information about a function prototype.
Definition TypeBase.h:5367
const ExtParameterInfo * ExtParameterInfos
Definition TypeBase.h:5372
Information about operator rewrites to consider when adding operator functions to a candidate set.
Definition Overload.h:1188
bool shouldAddReversed(Sema &S, ArrayRef< Expr * > OriginalArgs, FunctionDecl *FD)
Determine whether we should add a rewritten candidate for FD with reversed parameter order.
bool allowsReversed(OverloadedOperatorKind Op)
Determine whether reversing parameter order is allowed for operator Op.
SourceLocation OpLoc
The source location of the operator.
Definition Overload.h:1199
bool AllowRewrittenCandidates
Whether we should include rewritten candidates in the overload set.
Definition Overload.h:1201
bool isReversible()
Determines whether this operator could be implemented by a function with reversed parameter order.
Definition Overload.h:1237
bool isAcceptableCandidate(const FunctionDecl *FD)
Definition Overload.h:1210
OverloadCandidateRewriteKind getRewriteKind(const FunctionDecl *FD, OverloadCandidateParamOrder PO)
Determine the kind of rewrite that should be performed for this candidate.
Definition Overload.h:1227
OverloadCandidate - A single candidate in an overload set (C++ 13.3).
Definition Overload.h:926
unsigned StrictPackMatch
Have we matched any packs on the parameter side, versus any non-packs on the argument side,...
Definition Overload.h:991
unsigned IgnoreObjectArgument
IgnoreObjectArgument - True to indicate that the first argument's conversion, which for this function...
Definition Overload.h:982
bool TryToFixBadConversion(unsigned Idx, Sema &S)
Definition Overload.h:1056
bool NotValidBecauseConstraintExprHasError() const
bool isReversed() const
Definition Overload.h:1030
unsigned IsADLCandidate
True if the candidate was found using ADL.
Definition Overload.h:995
unsigned IsSurrogate
IsSurrogate - True to indicate that this candidate is a surrogate for a conversion to a function poin...
Definition Overload.h:972
QualType BuiltinParamTypes[3]
BuiltinParamTypes - Provides the parameter types of a built-in overload candidate.
Definition Overload.h:940
DeclAccessPair FoundDecl
FoundDecl - The original declaration that was looked up / invented / otherwise found,...
Definition Overload.h:936
FunctionDecl * Function
Function - The actual function that this candidate represents.
Definition Overload.h:931
unsigned RewriteKind
Whether this is a rewritten candidate, and if so, of what kind?
Definition Overload.h:1003
ConversionFixItGenerator Fix
The FixIt hints which can be used to fix the Bad candidate.
Definition Overload.h:952
unsigned Best
Whether this candidate is the best viable function, or tied for being the best viable function.
Definition Overload.h:966
StandardConversionSequence FinalConversion
FinalConversion - For a conversion function (where Function is a CXXConversionDecl),...
Definition Overload.h:1021
unsigned getNumParams() const
Definition Overload.h:1069
unsigned HasFinalConversion
Whether FinalConversion has been set.
Definition Overload.h:999
unsigned TookAddressOfOverload
Definition Overload.h:985
unsigned FailureKind
FailureKind - The reason why this candidate is not viable.
Definition Overload.h:1008
unsigned ExplicitCallArguments
The number of call arguments that were explicitly provided, to be used while performing partial order...
Definition Overload.h:1012
ConversionSequenceList Conversions
The conversion sequences used to convert the function arguments to the function parameters.
Definition Overload.h:949
DeductionFailureInfo DeductionFailure
Definition Overload.h:1015
unsigned Viable
Viable - True to indicate that this overload candidate is viable.
Definition Overload.h:956
CXXConversionDecl * Surrogate
Surrogate - The conversion function for which this candidate is a surrogate, but only if IsSurrogate ...
Definition Overload.h:944
OverloadCandidateRewriteKind getRewriteKind() const
Get RewriteKind value in OverloadCandidateRewriteKind type (This function is to workaround the spurio...
Definition Overload.h:1026
bool SuppressUserConversions
Do not consider any user-defined conversions when constructing the initializing sequence.
Definition Sema.h:10461
bool OnlyInitializeNonUserDefinedConversions
Before constructing the initializing sequence, we check whether the parameter type and argument type ...
Definition Sema.h:10468
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:12954
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13042
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13080
Abstract class used to diagnose incomplete types.
Definition Sema.h:8203
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:470
StandardConversionSequence Before
Represents the standard conversion that occurs before the actual user-defined conversion.
Definition Overload.h:482
FunctionDecl * ConversionFunction
ConversionFunction - The function that will perform the user-defined conversion.
Definition Overload.h:504
bool HadMultipleCandidates
HadMultipleCandidates - When this is true, it means that the conversion function was resolved from an...
Definition Overload.h:495
StandardConversionSequence After
After - Represents the standard conversion that occurs after the actual user-defined conversion.
Definition Overload.h:499
bool EllipsisConversion
EllipsisConversion - When this is true, it means user-defined conversion sequence starts with a ....
Definition Overload.h:490
DeclAccessPair FoundConversionFunction
The declaration that we found via name lookup, which might be the same as ConversionFunction or it mi...
Definition Overload.h:509
void dump() const
dump - Print this user-defined conversion sequence to standard error.
Describes an entity that is being assigned.